libtmux 0.1.0

Async typed tmux client and object model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
//! Buffers, keys, formats, and scoped operations against real tmux.

#![cfg(feature = "test-support")]

#[path = "support/versions.rs"]
mod versions;

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

use libtmux::test::{TestServer, retry_until};
use libtmux::{ChannelWait, Command, NewWindowOptions, SplitDirection, SplitOptions};

#[tokio::test]
async fn a_listed_buffer_name_passes_back_unchanged() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    // `=` ends a field in the framed listing and a space is shell-quoted;
    // neither may split or alter a name.
    let mut expected = vec![libtmux::TmuxText::from("a=b c")];
    server
        .set_buffer(Some("a=b c"), "framed")
        .await
        .expect("buffer is stored");
    // tmux before 3.7 stores a newline in a name; 3.7 refuses one.
    let multiline = server
        .cmd(
            Command::new("set-buffer")
                .arg("-b")
                .arg("two\nlines")
                .arg("--")
                .arg("x"),
        )
        .await
        .expect("tmux answers");
    if multiline.success() {
        expected.push(libtmux::TmuxText::from("two\nlines"));
    }

    let mut names = server.buffer_names().await.expect("names");
    names.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));
    assert_eq!(names, expected);

    let safe_delete = versions::supports(server, &libtmux::since::NAMED_BUFFER_IDENTITY).await;
    for name in &names {
        assert!(
            server.buffer(name).await.expect("read").is_some(),
            "{name:?}"
        );
        if safe_delete {
            server.delete_buffer(name).await.expect("buffer is deleted");
        } else {
            assert!(matches!(
                server.delete_buffer(name).await,
                Err(libtmux::Error::UnsupportedCapability { .. })
            ));
            assert!(
                server
                    .buffer(name)
                    .await
                    .expect("retained buffer")
                    .is_some()
            );
        }
    }
    assert_eq!(
        server.buffer_names().await.expect("names").is_empty(),
        safe_delete
    );

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

#[tokio::test]
async fn buffers_hold_exact_bytes_and_report_absence() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    assert!(server.buffer_names().await.expect("names").is_empty());
    assert!(
        server.buffer("absent").await.expect("read").is_none(),
        "an unknown buffer is absent rather than an error",
    );

    // A buffer holds bytes, including ones no string type would keep.
    server
        .set_buffer(Some("payload"), "line one\nline two\ttabbed")
        .await
        .expect("buffer is stored");

    assert_eq!(
        server.buffer("payload").await.expect("read"),
        Some(b"line one\nline two\ttabbed".to_vec()),
    );

    let names = server.buffer_names().await.expect("names");
    assert_eq!(names, ["payload"]);

    if versions::supports(server, &libtmux::since::NAMED_BUFFER_IDENTITY).await {
        server
            .delete_buffer("payload")
            .await
            .expect("buffer is deleted");
        assert!(server.buffer("payload").await.expect("read").is_none());
        assert!(
            server.delete_buffer("payload").await.is_err(),
            "deleting a buffer that is gone is a failure, not a silent success",
        );
    }

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

#[tokio::test]
async fn flag_shaped_buffer_data_and_channels_stay_literal() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    server
        .set_buffer(Some("-literal-buffer"), "-literal-payload")
        .await
        .expect("flag-shaped buffer data stays literal");
    assert_eq!(
        server.buffer("-literal-buffer").await.expect("read"),
        Some(b"-literal-payload".to_vec()),
    );

    server
        .lock_channel("-literal-lock")
        .await
        .expect("a flag-shaped channel locks");
    server
        .unlock_channel("-literal-lock")
        .await
        .expect("a flag-shaped channel unlocks");
    server
        .signal_channel("-literal-signal")
        .await
        .expect("a flag-shaped channel signals");
    assert_eq!(
        server
            .wait_for_channel("-literal-signal", Duration::from_secs(5))
            .await
            .expect("a flag-shaped channel waits"),
        ChannelWait::Signalled,
    );

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

#[tokio::test]
async fn key_bindings_can_be_added_and_removed() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    server
        .bind_key("prefix", "Y", "display-message bound")
        .await
        .expect("key is bound");

    let listed = server
        .key_bindings(Some("prefix"))
        .await
        .expect("bindings are listed");
    assert!(
        listed
            .iter()
            .any(|line| line.contains(" Y ") && line.contains("display-message")),
        "the new binding appears in tmux's own listing",
    );

    server
        .unbind_key("prefix", "Y")
        .await
        .expect("key is unbound");
    let listed = server
        .key_bindings(Some("prefix"))
        .await
        .expect("bindings are listed");
    assert!(!listed.iter().any(|line| line.contains(" Y ")));

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

/// Each field reads back as tmux holds it, for the shapes the `bind-key` lines
/// get wrong: a table name with a space, a key tmux quotes, a note with a
/// newline, the repeat flag, and a command holding the field separator.
///
/// `solo` holds one binding, the listing tmux 3.7 through 3.7c print nowhere
/// when asked for with `-T`.
#[tokio::test]
async fn real_tmux_compat_key_bindings_read_as_fields() {
    use libtmux::{Error, since};

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let version = server
        .capabilities()
        .await
        .expect("capabilities")
        .tmux_version()
        .clone();
    if !version.has_behavior(&since::LIST_KEYS_FORMAT) {
        let refused = server
            .typed_key_bindings(None)
            .await
            .expect_err("list-keys -F is 3.7 and later");
        assert!(
            matches!(refused, Error::UnsupportedCapability { .. }),
            "{refused:?}"
        );
        guard.shutdown().await.expect("tmux fixture shuts down");
        return;
    }

    for command in [
        Command::new("bind-key")
            .arg("-r")
            .arg("-N")
            .arg("a\nnote")
            .arg("-T")
            .arg("sp ace")
            .arg("\"")
            .arg("display-message 'two words'"),
        Command::new("bind-key")
            .arg("-T")
            .arg("solo")
            .arg("M-'")
            .arg("display-message a=b ; display-message c"),
    ] {
        let bound = server.cmd(command).await.expect("bind-key runs");
        assert!(bound.success(), "{:?}", bound.stderr_lossy());
    }

    let spaced = server
        .typed_key_bindings(Some("sp ace"))
        .await
        .expect("bindings decode");
    assert_eq!(spaced.len(), 1);
    assert_eq!(spaced[0].table(), "sp ace");
    assert_eq!(spaced[0].key(), "\"");
    assert_eq!(spaced[0].command(), "display-message \"two words\"");
    assert_eq!(
        spaced[0].note().map(libtmux::TmuxText::as_bytes),
        Some(b"a\nnote".as_slice())
    );
    assert!(spaced[0].repeats());

    let solo = server
        .typed_key_bindings(Some("solo"))
        .await
        .expect("bindings decode");
    assert_eq!(solo.len(), 1, "a one-binding table is listed");
    assert_eq!(solo[0].key(), "M-'");
    assert_eq!(
        solo[0].command(),
        r"display-message a=b \; display-message c"
    );
    assert_eq!(solo[0].note(), None);
    assert!(!solo[0].repeats());

    // Nothing tmux printed was dropped: one binding per `bind-key` line, and
    // the command is the text that line ends with.
    let all = server
        .typed_key_bindings(None)
        .await
        .expect("bindings decode");
    let lines = server
        .key_bindings(None)
        .await
        .expect("bindings are listed");
    assert_eq!(all.len(), lines.len());
    let command = solo[0].command().as_str().expect("the command is UTF-8");
    assert!(
        lines
            .iter()
            .any(|line| line.contains("-T solo") && line.ends_with(command)),
        "{lines:?}",
    );
    assert!(
        server
            .typed_key_bindings(Some("no-such-table"))
            .await
            .expect("bindings decode")
            .is_empty()
    );

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

#[tokio::test]
async fn formats_expand_against_a_target() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("formatted").await.expect("session");

    // A format is evaluated against a pane, and resolves the session and
    // window around it from there.
    let pane = session
        .panes()
        .await
        .expect("panes")
        .into_iter()
        .next()
        .expect("one pane");

    // The trailing newline display-message adds is framing, not content.
    let name = server
        .format(Some(&pane), "#{session_name}")
        .await
        .expect("format expands");
    assert_eq!(name.as_bytes(), b"formatted");

    let combined = server
        .format(Some(&pane), "#{session_name}:#{session_windows}")
        .await
        .expect("format expands");
    assert_eq!(combined.as_bytes(), b"formatted:1");

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

#[tokio::test]
async fn sourcing_a_file_applies_its_commands() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let directory = tempfile::tempdir().expect("temporary directory");
    let config = directory.path().join("extra.conf");
    std::fs::write(&config, "set-option -s @sourced yes\n").expect("config is written");

    server.source_file(&config).await.expect("file is sourced");
    assert_eq!(
        server.typed_option("@sourced").await.expect("read"),
        Some(libtmux::OptionValue::from("yes")),
        "the sourced option is set",
    );

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

/// A caller's own error type, without a libtmux conversion.
#[derive(Debug, PartialEq)]
enum Failure {
    Deliberate,
}

#[tokio::test]
async fn scoped_operations_clean_up_after_success_and_failure() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    // Success: the session exists inside the scope and not after it.
    let seen = server
        .with_session("scoped", async |session| {
            Ok::<_, libtmux::Error>(session.id().to_string())
        })
        .await
        .expect("the scope runs and the operation succeeds");
    assert!(seen.starts_with('$'));
    assert!(server.sessions().await.expect("sessions").is_empty());

    let outcome = server
        .with_session("failing", async |_session| {
            Err::<(), Failure>(Failure::Deliberate)
        })
        .await;
    assert!(matches!(
        outcome,
        Err(libtmux::ScopeError::Operation(Failure::Deliberate))
    ));
    assert!(
        server.sessions().await.expect("sessions").is_empty(),
        "cleanup runs even when the operation failed",
    );

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

#[tokio::test]
async fn scoped_windows_and_panes_nest() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("nested").await.expect("session");

    let before = session.windows().await.expect("windows").len();

    let pane_count = session
        .with_window(
            NewWindowOptions::new("temporary").command("sleep 300"),
            async |window| {
                window
                    .with_pane(
                        SplitOptions::new(SplitDirection::Below).command("sleep 300"),
                        async |_pane| {
                            Ok::<_, libtmux::Error>(window.panes().await.expect("panes").len())
                        },
                    )
                    .await
            },
        )
        .await
        .expect("both scopes run and the operation succeeds");

    assert_eq!(pane_count, 2, "the scoped pane existed inside its scope");
    assert_eq!(
        session.windows().await.expect("windows").len(),
        before,
        "the scoped window is gone afterwards",
    );

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

#[tokio::test]
async fn scoped_operations_clean_up_after_cancellation() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server().clone();
    let anchor = server.new_session("anchor").await.expect("session");
    let window = anchor
        .active_window()
        .await
        .expect("window lookup")
        .expect("window");
    let ready = Arc::new(tokio::sync::Barrier::new(4));

    let session_scope = tokio::spawn({
        let server = server.clone();
        let ready = Arc::clone(&ready);
        async move {
            server
                .with_session("cancelled-session", async move |_session| {
                    ready.wait().await;
                    std::future::pending::<Result<(), libtmux::Error>>().await
                })
                .await
        }
    });
    let window_scope = tokio::spawn({
        let anchor = anchor.clone();
        let ready = Arc::clone(&ready);
        async move {
            anchor
                .with_window("cancelled-window", async move |_window| {
                    ready.wait().await;
                    std::future::pending::<Result<(), libtmux::Error>>().await
                })
                .await
        }
    });
    let pane_scope = tokio::spawn({
        let window = window.clone();
        let ready = Arc::clone(&ready);
        async move {
            window
                .with_pane(SplitDirection::Below, async move |_pane| {
                    ready.wait().await;
                    std::future::pending::<Result<(), libtmux::Error>>().await
                })
                .await
        }
    });

    tokio::time::timeout(Duration::from_secs(5), ready.wait())
        .await
        .expect("all scoped objects are created");
    session_scope.abort();
    window_scope.abort();
    pane_scope.abort();
    for scope in [session_scope, window_scope, pane_scope] {
        assert!(scope.await.expect_err("scope is aborted").is_cancelled());
    }

    let cleanup = retry_until(Duration::from_secs(5), async || {
        matches!(server.sessions().await, Ok(objects) if objects.len() == 1)
            && matches!(anchor.windows().await, Ok(objects) if objects.len() == 1)
            && matches!(window.panes().await, Ok(objects) if objects.len() == 1)
    })
    .await;
    let sessions = server.sessions().await.expect("sessions").len();
    let windows = anchor.windows().await.expect("windows").len();
    let panes = window.panes().await.expect("panes").len();
    guard.shutdown().await.expect("tmux fixture shuts down");

    assert!(
        cleanup.is_ok(),
        "aborted scopes left sessions={sessions}, windows={windows}, panes={panes}",
    );
}

#[tokio::test]
async fn shell_commands_run_through_tmux_and_report_their_output() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    // tmux 3.3 through 3.4 route run-shell output into a pane's copy-mode
    // buffer rather than to the client, and still exit zero. The crate refuses
    // there rather than reporting an empty listing, which would be a wrong
    // answer the caller could not tell from a command that printed nothing.
    let outcome = server.run_shell("printf 'first\\nsecond\\n'").await;
    let Ok(lines) = outcome else {
        let error = outcome.expect_err("refused");
        assert!(
            matches!(&error, libtmux::Error::CapabilityDefective { capability, .. }
                if *capability == "run-shell output"),
            "an affected release refuses with the reason, got {error:?}",
        );
        assert_eq!(error.kind(), libtmux::ErrorKind::UnsupportedVersion);
        guard.shutdown().await.expect("tmux fixture shuts down");
        return;
    };

    assert_eq!(
        lines
            .iter()
            .map(libtmux::TmuxText::as_bytes)
            .collect::<Vec<_>>(),
        [&b"first"[..], &b"second"[..]],
    );

    // A command producing nothing is an empty listing, not a failure.
    assert!(server.run_shell("true").await.expect("runs").is_empty());

    // Background acceptance says nothing about the command's own outcome.
    server
        .spawn_shell("false")
        .await
        .expect("tmux accepts a background command whatever it later does");

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

#[tokio::test]
async fn wait_for_channels_lock_and_release() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    // Locking an unheld channel takes it; unlocking releases it again.
    server
        .lock_channel("gate")
        .await
        .expect("channel is locked");
    server
        .unlock_channel("gate")
        .await
        .expect("channel is unlocked");

    // Signalling a channel nobody waits on is accepted, and tmux keeps it:
    // the next wait spends the latch rather than blocking.
    server
        .signal_channel("gate")
        .await
        .expect("channel is signalled");
    assert_eq!(
        server
            .wait_for_channel("gate", Duration::from_secs(5))
            .await
            .expect("waiting is not an error"),
        ChannelWait::Signalled,
        "a signal with nobody waiting is kept, not dropped",
    );
    // One-shot: the latch is spent, so the next wait runs out of time. That is
    // an outcome, not an error, which is the distinction the return type
    // exists to carry.
    assert_eq!(
        server
            .wait_for_channel("gate", Duration::from_millis(300))
            .await
            .expect("running out of time is not an error"),
        ChannelWait::TimedOut,
        "the latch releases one wait, not every later one",
    );

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

/// Cancelling a queued `lock_channel` wedges the channel for every later
/// locker: a tmux defect, not something this crate can protect against. See
/// [`Server::lock_channel`]'s hazard note.
///
/// `cmd_wait_for_unlock` hands a channel to the next queued locker with no
/// mechanism to skip one whose client already disconnected, so killing a
/// locker while it is queued -- not while it holds the lock -- corrupts the
/// channel for everyone behind it, even though nobody ever unlocked it
/// explicitly. Pinned with a tight bound so this fails loudly, not
/// silently, if a tmux release ever fixes the defect.
#[tokio::test]
async fn real_tmux_compat_cancelling_a_queued_lock_wedges_the_channel() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    // Uncontested: takes the lock and returns at once. Never unlocked.
    server
        .lock_channel("wedge")
        .await
        .expect("the first lock is uncontested");

    // Contested: queues behind the holder above, then is cancelled while
    // still queued -- what `kill_on_drop` is for, killing the underlying
    // `tmux wait-for -L` subprocess rather than leaving it running.
    let cancelled = tokio::time::timeout(
        libtmux::test::scaled(Duration::from_secs(2)),
        server.lock_channel("wedge"),
    )
    .await;
    assert!(
        cancelled.is_err(),
        "the second lock is genuinely contested and queues",
    );

    // A third locker has nothing ahead of it but the first holder -- the
    // second never acquired the channel, only queued -- yet tmux hands it
    // to the dead second locker anyway and never notices it is gone, so
    // this wedges rather than resolving at a sensible bound.
    let wedged = tokio::time::timeout(
        libtmux::test::scaled(Duration::from_millis(800)),
        server.lock_channel("wedge"),
    )
    .await;
    assert!(
        wedged.is_err(),
        "cancelling the queued locker corrupts the channel for good, per the defect this pins",
    );

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

/// Waiting blocks until something signals, rather than returning at once.
///
/// The latch makes the easy case indistinguishable from a broken one: a wait
/// that returned immediately would satisfy a test that only checks the
/// outcome. So this signals from elsewhere, after a delay, and requires that
/// the wait actually spanned it.
#[tokio::test]
async fn a_wait_blocks_until_something_signals_the_channel() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    let signaller = server.clone();
    let signalling = tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(400)).await;
        signaller
            .signal_channel("ready")
            .await
            .expect("channel is signalled");
    });

    let started = std::time::Instant::now();
    let outcome = server
        .wait_for_channel("ready", Duration::from_secs(10))
        .await
        .expect("waiting is not an error");
    let waited = started.elapsed();

    signalling.await.expect("the signalling task finishes");
    assert_eq!(outcome, ChannelWait::Signalled);
    assert!(
        waited >= Duration::from_millis(300),
        "the wait returned in {waited:?}, so it did not wait for the signal",
    );

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

#[tokio::test]
async fn client_operations_need_a_client_and_report_when_there_is_none() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    server.new_session("headless").await.expect("session");

    // A test server has no terminal attached, so there are no clients and the
    // operations that need one fail loudly rather than pretending to work.
    assert!(server.clients().await.expect("clients list").is_empty());
    assert!(
        server.display_popup(None, "true").await.is_err(),
        "a popup needs a client with a terminal",
    );

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

/// Exercise `Client` against the one kind of client a headless test can make.
///
/// Every other client needs a terminal. A control-mode attach does not, and
/// tmux counts it as a client like any other, so it is what makes the
/// positive case testable at all.
#[cfg(feature = "control-mode")]
#[tokio::test]
async fn a_client_reports_itself_while_it_is_attached() {
    use libtmux::control::ControlMode;
    use std::time::Duration;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let Some(guard) = versions::control_fixture(guard).await else {
        return;
    };
    let server = guard.server();
    let first = server.new_session("client-one").await.expect("session");
    let second = server.new_session("client-two").await.expect("session");

    let control = ControlMode::attach(server, first.id())
        .await
        .expect("control mode attaches");

    // tmux registers the client as part of attaching, but the listing is a
    // separate command, so wait for it rather than assuming the order.
    retry_until(Duration::from_secs(10), async || {
        server
            .clients()
            .await
            .is_ok_and(|clients| !clients.is_empty())
    })
    .await
    .expect("the attached client is listed");

    let mut client = server.clients().await.expect("clients").remove(0);
    assert!(client.is_control_mode(), "this client attached with -C");
    assert!(!client.name().as_bytes().is_empty());
    assert!(client.pid() > 0);

    // A client is attached to exactly one session, and switching moves it.
    client
        .switch_to(&second)
        .await
        .expect("the client switches session");
    retry_until(Duration::from_secs(10), async || {
        second
            .refreshed()
            .await
            .is_ok_and(|session| session.is_attached())
    })
    .await
    .expect("the second session reports the client");

    client.refresh().await.expect("the client still exists");

    // Detaching consumes the handle, and the listing empties out.
    client.detach().await.expect("the client detaches");
    retry_until(Duration::from_secs(10), async || {
        server
            .clients()
            .await
            .is_ok_and(|clients| clients.is_empty())
    })
    .await
    .expect("the detached client stops being listed");

    let _ = control.shutdown().await;
    guard.shutdown().await.expect("tmux fixture shuts down");
}

#[cfg(feature = "control-mode")]
#[tokio::test]
async fn server_operations_reject_foreign_handles() {
    use libtmux::control::ControlMode;
    use libtmux::{Chooser, Error, ErrorKind};

    macro_rules! error_kind {
        ($future:expr) => {
            match $future.await {
                Err(error @ Error::ServerMismatch { .. }) => error.kind(),
                Err(error) => panic!("foreign handle returned {error:?}"),
                Ok(_) => panic!("foreign handle was accepted"),
            }
        };
    }

    let left_guard = TestServer::builder().start().await.expect("tmux starts");
    let right_guard = TestServer::builder().start().await.expect("tmux starts");
    let left = left_guard.server();
    let right = right_guard.server();
    let left_session = left.new_session("left").await.expect("left session");
    let right_session = right.new_session("right").await.expect("right session");
    let right_pane = right_session.panes().await.expect("right panes").remove(0);
    assert_eq!(
        error_kind!(left.format(Some(&right_pane), "#{session_name}")),
        ErrorKind::InvalidInput
    );
    if !versions::supports_control(right).await {
        left_guard.shutdown().await.expect("left fixture closes");
        right_guard.shutdown().await.expect("right fixture closes");
        return;
    }
    let control = ControlMode::attach(right, right_session.id())
        .await
        .expect("control mode attaches");

    retry_until(Duration::from_secs(10), async || {
        right
            .clients()
            .await
            .is_ok_and(|clients| !clients.is_empty())
    })
    .await
    .expect("the foreign client is listed");
    let foreign_client = right.clients().await.expect("right clients").remove(0);

    let kinds = [
        error_kind!(left.format(Some(&right_pane), "#{session_name}")),
        error_kind!(left.display_popup(Some(&foreign_client), "true")),
        error_kind!(left.display_menu(
            Some(&foreign_client),
            "menu",
            [libtmux::MenuItem::new("Item", "i", "display-message item")],
        )),
        error_kind!(left.command_prompt(
            Some(&foreign_client),
            Some("question"),
            "display-message answer",
        )),
        error_kind!(left.choose(Chooser::Tree, Some(&foreign_client))),
        error_kind!(left.find_window(Some(&foreign_client), "needle")),
        error_kind!(left.display_panes(Some(&foreign_client))),
        error_kind!(foreign_client.switch_to(&left_session)),
    ];

    assert_eq!(kinds, [ErrorKind::InvalidInput; 8]);

    let _ = control.shutdown().await;
    right_guard
        .shutdown()
        .await
        .expect("right tmux fixture shuts down");
    left_guard
        .shutdown()
        .await
        .expect("left tmux fixture shuts down");
}

#[tokio::test]
async fn pane_modes_enter_and_leave() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("modes").await.expect("session");
    let mut pane = session
        .panes()
        .await
        .expect("panes")
        .into_iter()
        .next()
        .expect("one pane");

    assert!(!pane.is_in_mode(), "a fresh pane has no mode open");

    pane.copy_mode().await.expect("copy mode is entered");
    pane.refresh().await.expect("the pane still exists");
    assert!(pane.is_in_mode(), "copy mode is a pane mode");

    pane.exit_mode().await.expect("the mode is cancelled");
    pane.refresh().await.expect("the pane still exists");
    assert!(!pane.is_in_mode(), "cancelling leaves the mode");

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

/// A mode that is not copy mode must be leavable too.
///
/// `exit_mode` sent the cancel key, which reaches a pane through the copy-mode
/// key table. Clock mode and tree mode have none, so the key was answered "not
/// in a mode" while the pane stayed in one, and `is_in_mode` and `exit_mode`
/// disagreed about the same pane. `clock_mode` is a public way in, so the
/// crate could put a pane into a state only a raw command could clear.
///
/// The old test entered copy mode, which is the one mode the cancel key does
/// leave, so it passed throughout.
#[tokio::test]
async fn a_pane_leaves_a_mode_that_is_not_copy_mode() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("clocked").await.expect("session");
    let mut pane = session
        .panes()
        .await
        .expect("panes")
        .into_iter()
        .next()
        .expect("one pane");

    pane.clock_mode().await.expect("clock mode is entered");
    pane.refresh().await.expect("the pane still exists");
    assert!(pane.is_in_mode(), "clock mode is a pane mode");

    pane.exit_mode().await.expect("clock mode is left");
    pane.refresh().await.expect("the pane still exists");
    assert!(
        !pane.is_in_mode(),
        "a mode that is not copy mode is left as well"
    );

    // A pane in no mode is left alone rather than refused, so a caller can
    // reach a known state without asking first.
    pane.exit_mode()
        .await
        .expect("leaving no mode at all is not a failure");

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

/// A pane's edge flags must follow the split that made it.
///
/// These read from the snapshot rather than dispatching, so nothing catches
/// them being wired to the wrong format field: `pane_at_left` and
/// `pane_at_right` differ only in a word.
#[tokio::test]
async fn edge_flags_follow_the_split_that_made_them() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("edges").await.expect("session");
    let window = session
        .active_window()
        .await
        .expect("windows")
        .expect("a session has a window");

    let only = window.panes().await.expect("panes").remove(0);
    assert!(only.is_at_left(), "an undivided pane touches both edges");
    assert!(only.is_at_right(), "an undivided pane touches both edges");

    only.split(SplitOptions::new(SplitDirection::Right))
        .await
        .expect("the pane splits sideways");

    let panes = window.panes().await.expect("panes");
    assert_eq!(panes.len(), 2, "the split produced a second pane");
    let (left, right) = (&panes[0], &panes[1]);

    assert!(left.is_at_left(), "the original keeps the left edge");
    assert!(!left.is_at_right(), "and gives up the right one");
    assert!(right.is_at_right(), "the new pane takes the right edge");
    assert!(!right.is_at_left(), "and does not hold the left one");

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

/// A global window option must be read from the global table, not the window
/// the server happens to be pointing at.
///
/// A plain round trip cannot say that: writing and reading through the same
/// wrong scope agrees with itself. So this gives the window a different value
/// and checks the global read is unmoved by it.
///
/// What this cannot pin is the `-w` half of tmux's `-w -g`. tmux resolves an
/// option's table from its name, so `show-options -g main-pane-width` and
/// `-wg` return the same value and no assertion here can tell them apart.
/// Dropping `-w` in the scope leaves this test passing, which was checked
/// rather than assumed.
#[tokio::test]
async fn a_global_window_option_is_read_globally() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("options").await.expect("session");
    let window = session
        .active_window()
        .await
        .expect("windows")
        .expect("a session has a window");

    server
        .set_global_window_option("main-pane-width", "123")
        .await
        .expect("the global window option is set");
    window
        .set_option("main-pane-width", "456")
        .await
        .expect("the window takes a value of its own");

    let read = server
        .typed_global_window_option("main-pane-width")
        .await
        .expect("the option is readable");
    assert_eq!(
        read,
        Some(libtmux::OptionValue::from("123")),
        "the global read is not answered by the window's own value"
    );

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

/// Piping a pane must start and stop with the same call.
///
/// `pipe-pane` toggles when given no command, so a caller who cannot stop it
/// leaves tmux writing into a process for the life of the pane.
///
/// The sink lives in a directory of its own rather than beside the fixture's
/// socket. An earlier version wrote it next to the socket and removed it on
/// the way out, which meant a failing run left a file behind that outlived
/// the fixture's own cleanup and kept the directory in the shared root --
/// `just fixture-root` reported it. A temporary directory is removed whether
/// the test returns or panics.
#[tokio::test]
async fn a_pane_pipes_until_it_is_told_to_stop() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("piped").await.expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    let mut pane = pane;
    assert!(!pane.is_piped(), "nothing yet");

    let sink_dir = tempfile::Builder::new()
        .prefix("libtmux-pipe-")
        .tempdir()
        .expect("a directory of its own");
    let sink = sink_dir.path().join("seen");

    pane.pipe(Some(format!("cat >{}", sink.display())))
        .await
        .expect("the pane pipes");
    pane.refresh().await.expect("the pane still exists");
    assert!(pane.is_piped(), "now piping");

    pane.send_keys("printf 'piped\n'").await.expect("keys");
    pane.send_key_names(["Enter"]).await.expect("enter");
    retry_until(Duration::from_secs(10), async || {
        std::fs::read(&sink).is_ok_and(|seen| seen.windows(5).any(|word| word == b"piped"))
    })
    .await
    .expect("what the pane printed reaches the pipe");

    pane.pipe(None::<String>).await.expect("the pipe stops");
    pane.refresh().await.expect("the pane still exists");
    assert!(!pane.is_piped(), "the same call with no command stops it");

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

/// A pane must report the terminal tmux gave it.
///
/// Reads from the snapshot, so a field wired to the wrong name would return
/// some other pane's string rather than fail.
#[tokio::test]
async fn a_pane_reports_its_own_terminal() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("ttys").await.expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    let reported = pane.tty().as_str().expect("a tty path is text").to_owned();
    let asked = server
        .format(Some(&pane), "#{pane_tty}")
        .await
        .expect("tmux answers for the same pane");

    assert_eq!(
        reported,
        asked.as_str().expect("a tty path is text"),
        "the accessor and tmux name the same terminal"
    );
    assert!(reported.starts_with("/dev/"), "and it is a device path");

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

/// A window's activity and bell flags must each read their own field.
///
/// They differ by a word and both are `bool`, so a swap type-checks. Reading
/// them on a fresh window cannot catch one: both are false there, and a swap
/// between two equal values is invisible. So this drives activity high and
/// leaves the bell low first, which was measured rather than assumed -- the
/// first version of this test passed with `has_bell` wired to the activity
/// field.
#[tokio::test]
async fn window_flags_each_read_their_own_field() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("flags").await.expect("session");
    let window = session
        .active_window()
        .await
        .expect("windows")
        .expect("a session has a window");

    // Activity is only recorded for a window nobody is looking at, so the
    // second window is what makes the first one eligible.
    server
        .set_global_window_option("monitor-activity", "on")
        .await
        .expect("activity is monitored");
    session
        .new_window(NewWindowOptions::new("elsewhere"))
        .await
        .expect("a second window takes the focus");

    let panes = window.panes().await.expect("panes");
    panes[0].send_keys("printf 'noise\n'").await.expect("keys");
    panes[0].send_key_names(["Enter"]).await.expect("enter");

    let mut window = window;
    retry_until(Duration::from_secs(10), async || {
        window.refresh().await.is_ok() && window.has_activity()
    })
    .await
    .expect("the background window records activity");

    assert!(
        !window.has_bell(),
        "nothing rang a bell, so the two flags differ and a swap would show"
    );

    for (reported, format) in [
        (window.has_activity(), "#{window_activity_flag}"),
        (window.has_bell(), "#{window_bell_flag}"),
    ] {
        let asked = server
            .cmd(
                Command::new("display-message")
                    .arg("-p")
                    .arg("-t")
                    .arg(window.id().to_string())
                    .arg(format),
            )
            .await
            .expect("tmux answers");
        let asked = asked.stdout_lossy().trim() == "1";
        assert_eq!(reported, asked, "{format} agrees with the accessor");
    }

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

/// Pasting a buffer must put its bytes into the pane.
#[tokio::test]
async fn a_buffer_pastes_into_a_pane() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("pasted").await.expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    server
        .set_buffer(Some("greeting"), "printf 'pasted-here\n'")
        .await
        .expect("the buffer is set");
    pane.paste_buffer(Some("greeting"))
        .await
        .expect("the buffer pastes");
    pane.send_key_names(["Enter"]).await.expect("enter");

    retry_until(Duration::from_secs(10), async || {
        pane.capture().await.is_ok_and(|lines| {
            lines
                .iter()
                .any(|line| line.as_bytes().windows(11).any(|w| w == b"pasted-here"))
        })
    })
    .await
    .expect("what was pasted runs in the pane");

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

/// Searching a window's panes must find one that matches.
///
/// The lenient form returns an empty vector rather than an error, so a search
/// that never matched and a search that failed look alike to a caller. This
/// covers the case where it does match, which is the one that would be silent.
#[cfg(feature = "query")]
#[tokio::test]
async fn searching_a_window_finds_the_pane_that_matches() {
    use libtmux::query::Filterable as _;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("searched").await.expect("session");
    let window = session
        .active_window()
        .await
        .expect("windows")
        .expect("a session has a window");

    let panes = window.panes().await.expect("panes");
    let wanted = panes[0].id().to_string();

    let fields = libtmux::Pane::filter_fields();
    let found = window
        .search_panes(fields.pane_id.eq(wanted.as_str()))
        .await
        .unwrap_or_default();

    assert_eq!(found.len(), 1, "the pane that matches is returned");
    assert_eq!(found[0].id().to_string(), wanted);

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

/// A client's own fields must each name the client, not its neighbour.
///
/// `tty` and `term_name` are both `TmuxText` off the same projection, so one
/// reading the other's field type-checks and returns a plausible string. A
/// control client makes the two differ -- it has no terminal, so `client_tty`
/// is empty while `client_termname` is not -- which is what lets a swap show.
///
/// `suspend` is deliberately absent: it sends SIGTSTP to the client, and the
/// only client here is the control connection this test is holding.
#[cfg(feature = "control-mode")]
#[tokio::test]
async fn a_client_reports_its_own_terminal_and_type() {
    use libtmux::control::ControlMode;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let Some(guard) = versions::control_fixture(guard).await else {
        return;
    };
    let server = guard.server();
    let session = server.new_session("client-fields").await.expect("session");
    let control = ControlMode::attach(server, session.id())
        .await
        .expect("control mode attaches");

    retry_until(Duration::from_secs(10), async || {
        server
            .clients()
            .await
            .is_ok_and(|clients| !clients.is_empty())
    })
    .await
    .expect("the attached client is listed");

    let client = server.clients().await.expect("clients").remove(0);
    let name = client.name().to_string_lossy().into_owned();

    assert_ne!(
        client.tty().as_str().expect("client text"),
        client.term_name().as_str().expect("client text"),
        "the two fields differ here, so a swap between them would show"
    );

    for (reported, format) in [
        (client.tty(), "#{client_tty}"),
        (client.term_name(), "#{client_termname}"),
    ] {
        // `-t` rather than `-c`, because `-c` did not take an argument until
        // 3.5a: `display-message`'s option string is `acd:INpt:F:v` on 3.2a,
        // so the client name becomes a positional argument, the command
        // exceeds its one-argument maximum, and tmux answers with a usage
        // error. Its own usage line advertises `[-c target-client]` there
        // anyway, so the help disagrees with the parser.
        //
        // `-t` resolves the client on every supported release, and is what
        // `Client` itself uses. Checked rather than assumed: with the client
        // attached as `screen-256color` and the asking process at `vt100`,
        // both 3.2a and 3.7c answer `screen-256color`, so this reports the
        // target rather than the caller.
        let asked = server
            .cmd(
                Command::new("display-message")
                    .arg("-p")
                    .arg("-t")
                    .arg(&name)
                    .arg(format),
            )
            .await
            .expect("tmux answers for this client");
        assert_eq!(
            reported.as_str().expect("client text"),
            asked.stdout_lossy().trim(),
            "{format} agrees with the accessor"
        );
    }

    assert!(
        !client.is_readonly(),
        "a client that attached without -r may act"
    );
    client.redraw().await.expect("the client redraws");

    let _ = control.shutdown().await;
    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// Every timestamp accessor is a `SystemTime` inside the test's own window,
/// and names the moment its filter handle reads as Unix seconds.
///
/// A unit error -- milliseconds for seconds, or an offset -- lands outside the
/// window, which a check for "positive" did not catch.
#[cfg(all(feature = "control-mode", feature = "query"))]
#[tokio::test]
async fn timestamps_are_system_times_that_agree_with_their_handles() {
    use std::time::{SystemTime, UNIX_EPOCH};

    use libtmux::control::ControlMode;
    use libtmux::query::Filterable as _;
    use libtmux::{Availability, Client, Session, Window};

    // tmux keeps whole seconds, so the window opens on the second it started.
    let since_epoch = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("the clock is past 1970");
    let before = UNIX_EPOCH + Duration::from_secs(since_epoch.as_secs());

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let Some(guard) = versions::control_fixture(guard).await else {
        return;
    };
    let server = guard.server();
    let mut session = server.new_session("clock").await.expect("session");
    let control = ControlMode::attach(server, session.id())
        .await
        .expect("control mode attaches");
    retry_until(Duration::from_secs(10), async || {
        server
            .clients()
            .await
            .is_ok_and(|clients| !clients.is_empty())
    })
    .await
    .expect("the attached client is listed");

    session.refresh().await.expect("session refreshes");
    let window = session
        .active_window()
        .await
        .expect("window lookup")
        .expect("a window");
    let client = server.clients().await.expect("clients").remove(0);
    let generation = server.generation().await.expect("generation");
    let after = SystemTime::now();

    let seconds = |time: SystemTime| {
        let offset = time.duration_since(UNIX_EPOCH).expect("after 1970");
        i64::try_from(offset.as_secs()).expect("fits tmux's seconds")
    };
    let sessions = Session::filter_fields();
    let last_attached = session.last_attached().expect("a client attached");
    for (label, time, handle) in [
        (
            "session_created",
            session.created(),
            session.get(sessions.session_created),
        ),
        (
            "session_last_attached",
            last_attached,
            session.get(sessions.session_last_attached),
        ),
        (
            "window_activity",
            window.last_activity(),
            window.get(Window::filter_fields().window_activity),
        ),
        (
            "client_created",
            client.created(),
            client.get(Client::filter_fields().client_created),
        ),
    ] {
        assert!(
            before <= time && time <= after,
            "{label} is {time:?}, outside {before:?}..={after:?}",
        );
        assert_eq!(
            handle,
            Availability::Available(seconds(time)),
            "{label}'s handle reads the same moment as Unix seconds",
        );
    }

    let started = generation.start_time();
    assert!(
        before <= started && started <= after,
        "start_time is {started:?}, outside {before:?}..={after:?}",
    );
    assert!(
        generation
            .to_string()
            .ends_with(&format!(" started {}", seconds(started))),
        "Display prints the same moment as Unix seconds",
    );

    let _ = control.shutdown().await;
    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// The remaining dispatch-only commands must reach tmux and be accepted.
///
/// These change something a headless server cannot show back -- a prefix key
/// arriving, a prompt history no client has filled -- so what is covered is
/// that the command is built and accepted, not what it did.
#[tokio::test]
async fn dispatch_only_commands_are_accepted() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("dispatch").await.expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    pane.send_prefix().await.expect("the prefix key is sent");

    server
        .clear_prompt_history()
        .await
        .expect("the prompt history is cleared");

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

/// Unlinking a link that is already gone must not say the window is gone.
///
/// A link-scoped command names both halves, `session:@id`, because a window
/// linked into several sessions has one id and several links and the id alone
/// could not say which link to drop. tmux answers a target it cannot resolve
/// by echoing it back, and it echoes an identity identically whether the
/// window died or is merely linked somewhere else -- so the answer alone
/// cannot separate them, and reading it as proof of death claims "closed or
/// killed" about a window still running under another link.
///
/// That is what costs a caller something: `is_object_gone` is what they branch
/// on to drop a handle.
#[tokio::test]
async fn unlinking_a_gone_link_does_not_call_a_live_window_gone() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let home = server.new_session("home").await.expect("session");
    let elsewhere = server.new_session("elsewhere").await.expect("session");

    let shared = home
        .new_window(NewWindowOptions::new("shared"))
        .await
        .expect("a window to share");
    let shared_id = shared.id().to_string();
    let index = shared.index();

    shared
        .link_to(&elsewhere, None)
        .await
        .expect("the window is linked into a second session");

    // Two handles to the same link, taken before either is used: `unlink`
    // consumes the handle, and after the first call this session holds no
    // window at that index to take a second from.
    let mut handles = Vec::new();
    for _ in 0..2 {
        handles.push(
            home.windows()
                .await
                .expect("windows")
                .into_iter()
                .find(|window| window.index() == index)
                .expect("the shared window is linked here"),
        );
    }
    let second = handles.pop().expect("two handles");
    let first = handles.pop().expect("two handles");

    // The first removal succeeds: two links, one goes.
    first.unlink().await.expect("the link is removed");

    // The window itself is still running, held by the other session.
    let alive = server
        .windows()
        .await
        .expect("windows")
        .into_iter()
        .any(|window| window.id().to_string() == shared_id);
    assert!(alive, "the window survives losing one of its links");

    // Removing the same link again fails, and what it says matters.
    let again = home
        .windows()
        .await
        .expect("windows")
        .into_iter()
        .find(|window| window.index() == index);
    assert!(
        again.is_none(),
        "the session no longer holds a window at that index"
    );

    let refused = second.unlink().await.expect_err("the link is already gone");

    assert!(
        !refused.is_object_gone(),
        "a missing link is not a missing object; the window is still alive. got {refused:?}"
    );

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

/// A `TMUX_PANE` that is set and wrong is not the same as one that is unset.
///
/// Both used to answer "not inside tmux", which sends a caller who *is* inside
/// tmux to check the wrong thing entirely. `Server::from_env_value` already
/// drew this line for `TMUX`, ten lines away, with a comment making the case.
#[tokio::test]
async fn a_malformed_pane_variable_is_not_being_outside_tmux() {
    use libtmux::ServerConfigurationErrorKind as Kind;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    server.new_session("env").await.expect("session");

    let absent = libtmux::Pane::from_env_value(server, None::<std::ffi::OsString>)
        .await
        .expect_err("nothing set the variable");
    assert!(
        matches!(
            &absent,
            libtmux::Error::InvalidServerConfiguration {
                kind: Kind::NotInsideTmux,
                ..
            }
        ),
        "an unset variable means this process was not started by tmux, got {absent:?}"
    );

    for wrong in ["%abc", "@0", "%-1", "#{pane_id}", ""] {
        let malformed = libtmux::Pane::from_env_value(server, Some(wrong))
            .await
            .expect_err("the variable is set and does not name a pane");
        assert!(
            matches!(
                &malformed,
                libtmux::Error::InvalidServerConfiguration {
                    kind: Kind::MalformedTmuxVariable,
                    ..
                }
            ),
            "{wrong:?} is a variable written wrongly, not an absent one, got {malformed:?}"
        );
    }

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

/// A chooser opens in a pane, so it needs no client; a popup needs one.
///
/// Both kinds are dispatched from `Server` and both take `Option<&Client>`,
/// which makes them look like one family that disagrees about clients. They
/// are two families: `choose` and `find_window` put a *pane* into a mode, and
/// `display_popup` and its three siblings draw *on a client* and cannot
/// without one.
///
/// Asserting the return value alone cannot tell them apart -- that was the
/// mistake this test replaces. `Ok` from `choose` was read as an empty promise
/// until somebody looked at the pane, which is in a mode.
#[tokio::test]
async fn a_chooser_opens_in_a_pane_and_a_popup_needs_a_client() {
    use libtmux::Chooser;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("nobody").await.expect("session");
    assert!(
        server.clients().await.expect("clients").is_empty(),
        "nothing is attached"
    );

    let mut pane = session.panes().await.expect("panes").remove(0);
    assert!(!pane.is_in_mode(), "the pane starts in no mode");

    server
        .choose(Chooser::Tree, None)
        .await
        .expect("a chooser needs no client");
    pane.refresh().await.expect("the pane still exists");
    assert!(
        pane.is_in_mode(),
        "the chooser is open in the pane, which is what the Ok meant"
    );

    let refused = server
        .display_popup(None, "true")
        .await
        .expect_err("a popup draws on a client and there is none");
    assert_eq!(refused.kind(), libtmux::ErrorKind::Refused);

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

/// One dead object must answer the same way whichever call asks.
///
/// tmux has two vocabularies for it. `cmd-find.c` resolves a target and says
/// "can't find pane"; `options.c` resolves its own and says "no such pane".
/// Matching only the first meant `is_object_gone` answered `true` from
/// `capture` and `false` from `typed_option` about the same dead pane.
///
/// The `@` branch made it worse than inconsistent. A user option that is not
/// set is unknown to tmux, so that failure is the answer `None` -- but the
/// branch swallowed *every* failure for an `@` name, so a pane that had gone
/// away read as a pane whose option was never set.
///
/// The option is set before the pane is killed. Without that, `Ok(None)` is
/// indistinguishable from a legitimate "never set" and the test proves
/// nothing.
#[tokio::test]
async fn a_dead_pane_says_so_however_the_question_is_asked() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("gone").await.expect("session");
    let window = session
        .active_window()
        .await
        .expect("windows")
        .expect("a session has a window");
    let doomed = window
        .panes()
        .await
        .expect("panes")
        .remove(0)
        .split(SplitOptions::new(SplitDirection::Below))
        .await
        .expect("a second pane to kill");

    // The positive control: the option is really set, on a pane that is really
    // there, so a later `None` cannot mean "never set".
    doomed
        .set_option("@marker", "here")
        .await
        .expect("the user option is set");
    assert_eq!(
        doomed.typed_option("@marker").await.expect("readable"),
        Some(libtmux::OptionValue::from("here")),
    );

    // `kill` consumes the handle, so the questions afterwards are asked
    // through a second one taken before it.
    let asking = window
        .panes()
        .await
        .expect("panes")
        .into_iter()
        .find(|pane| pane.id() == doomed.id())
        .expect("the doomed pane is listed");
    doomed.kill().await.expect("the pane is killed");
    let doomed = asking;

    // Every route to the same fact agrees.
    let by_capture = doomed.capture().await.expect_err("the pane is gone");
    assert!(
        by_capture.is_object_gone(),
        "capture says so: {by_capture:?}"
    );

    let by_option = doomed
        .typed_option("remain-on-exit")
        .await
        .expect_err("the pane is gone");
    assert!(
        by_option.is_object_gone(),
        "a built-in option says so too: {by_option:?}"
    );

    let by_user_option = doomed
        .typed_option("@marker")
        .await
        .expect_err("the pane is gone, not the option unset");
    assert!(
        by_user_option.is_object_gone(),
        "a user option must not report a gone pane as an unset option: {by_user_option:?}"
    );

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

/// A variable nobody set and a session that has ended are different answers.
///
/// `environment` returned `Ok(None)` for any refusal, so a dead session read as
/// a variable that was never there -- and the three other environment methods
/// on the same handle reported the death correctly, so one struct disagreed
/// with itself.
///
/// tmux says which it is, on the same exit code: "unknown variable: NAME" for
/// the first, "no such session: NAME" for the second.
///
/// The variable is set before the session is killed, so `Ok(None)` afterwards
/// cannot be read as a legitimate "never set".
#[tokio::test]
async fn a_dead_session_is_not_an_unset_variable() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    // A second session keeps the server alive once the first is killed.
    server.new_session("keeper").await.expect("session");
    let doomed = server.new_session("doomed").await.expect("session");

    doomed
        .set_environment("FOO", "bar")
        .await
        .expect("the variable is set");
    assert!(
        doomed.environment("FOO").await.expect("readable").is_some(),
        "the positive control: it really is set"
    );
    assert!(
        doomed
            .environment("NEVER_SET")
            .await
            .expect("readable")
            .is_none(),
        "a name tmux does not hold is still None"
    );

    let asking = server
        .sessions()
        .await
        .expect("sessions")
        .into_iter()
        .find(|session| session.id() == doomed.id())
        .expect("the doomed session is listed");
    doomed.kill().await.expect("the session is killed");

    let refused = asking
        .environment("FOO")
        .await
        .expect_err("the session is gone, not the variable unset");
    assert!(
        refused.is_object_gone(),
        "a gone session must not read as an unset variable: {refused:?}"
    );

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

#[tokio::test]
async fn interactive_commands_need_a_client() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    server.new_session("interactive").await.expect("session");

    // A headless server has no terminal, so commands that draw on one fail
    // loudly rather than reporting a success nobody could see. From 3.8-rc,
    // display-panes is a pane mode instead of a client overlay: tmux opens it
    // in the target pane with no client and closes it after
    // display-panes-time.
    let panes_mode = versions::supports(
        server,
        &libtmux::ReleaseVersion::new(3, 8, libtmux::ReleaseSuffix::RELEASE_CANDIDATE),
    )
    .await;
    assert_eq!(server.display_panes(None).await.is_ok(), panes_mode);
    assert!(
        server
            .display_menu(
                None,
                "menu",
                [libtmux::MenuItem::new("Item", "i", "kill-pane")]
            )
            .await
            .is_err(),
    );
    assert!(
        server
            .command_prompt(None, Some("question"), "kill-pane")
            .await
            .is_err(),
    );

    // The choosers are the exception: tmux accepts one with no client and
    // silently does nothing. This records what tmux does rather than what
    // symmetry would suggest.
    server
        .choose(libtmux::Chooser::Tree, None)
        .await
        .expect("tmux accepts a chooser with no client");

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

#[tokio::test]
async fn retry_until_waits_for_tmux_rather_than_sleeping() {
    use libtmux::test::{retry_until, scaled, unique_name};
    use std::time::Duration;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    // A unique name lets concurrent tests share one server without colliding.
    let name = unique_name("retry");
    let session = server.new_session(name.as_str()).await.expect("session");
    assert_ne!(unique_name("retry"), name);

    // tmux applies a split before the new pane's command has necessarily
    // execed, so wait for the state under test.
    session
        .windows()
        .await
        .expect("windows")
        .into_iter()
        .next()
        .expect("one window")
        .split(SplitOptions::new(SplitDirection::Below).command("sleep 300"))
        .await
        .expect("pane is created");

    retry_until(Duration::from_secs(5), async || {
        session.panes().await.is_ok_and(|panes| panes.len() == 2)
    })
    .await
    .expect("the second pane appears");

    // A condition that never holds reports the deadline instead of hanging.
    let waited = retry_until(Duration::from_millis(50), async || false)
        .await
        .expect_err("a condition that never holds times out");
    assert_eq!(waited.waited(), scaled(Duration::from_millis(50)));

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

#[tokio::test]
async fn a_scoped_raw_command_targets_its_own_object() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let first = server.new_session("first").await.expect("first session");
    let second = server.new_session("second").await.expect("second session");

    // Each handle addresses itself, not whatever tmux considers current.
    for (session, expected) in [(&first, "first"), (&second, "second")] {
        let named = session
            .cmd(
                Command::new("display-message")
                    .arg("-p")
                    .arg("#{session_name}"),
            )
            .await
            .expect("the command runs");
        assert_eq!(named.stdout_lossy().trim(), expected);
    }

    // The placement is the point. tmux stops reading flags at the first
    // positional, so a target appended after `--` is taken as text: the
    // command succeeds and types it into whichever pane was current. Sending
    // through the handle puts `-t` where tmux still reads it.
    let window = second
        .active_window()
        .await
        .expect("active window")
        .expect("a session has a window");
    let pane = window
        .active_pane()
        .await
        .expect("active pane")
        .expect("a window has a pane");

    pane.cmd(
        Command::new("send-keys")
            .arg("--")
            .arg("echo scoped")
            .arg("Enter"),
    )
    .await
    .expect("keys are sent");

    let seen = retry_until(Duration::from_secs(5), async || {
        pane.capture().await.is_ok_and(|lines| {
            lines
                .iter()
                .any(|line| String::from_utf8_lossy(line.as_bytes()).contains("scoped"))
        })
    })
    .await;
    assert!(seen.is_ok(), "the keys reached this pane, not another");

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

#[tokio::test]
async fn formatting_returns_text_and_displaying_returns_nothing() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("split").await.expect("session");
    let window = session
        .active_window()
        .await
        .expect("active window")
        .expect("a session has a window");

    // The reading half expands in the object's own context, so each handle
    // answers about itself rather than about whatever tmux considers current.
    assert_eq!(
        session
            .format("#{session_name}")
            .await
            .expect("format")
            .to_string_lossy(),
        "split",
    );
    assert_eq!(
        window
            .format("#{window_id}")
            .await
            .expect("format")
            .to_string_lossy(),
        window.id().to_string(),
    );

    // A format that expands to nothing is empty text rather than an error:
    // tmux expanded it fine, the answer is just empty.
    assert!(
        session
            .format("#{?0,yes,}")
            .await
            .expect("format")
            .as_bytes()
            .is_empty(),
    );

    // The showing half returns nothing, and succeeds with nobody attached: a
    // headless server shows the message to no one, which is not a failure.
    let pane = window
        .active_pane()
        .await
        .expect("active pane")
        .expect("a window has a pane");
    assert_eq!(
        pane.format("#{pane_id}")
            .await
            .expect("format")
            .to_string_lossy(),
        pane.id().to_string(),
    );

    session.display("hello").await.expect("display");
    window.display("hello").await.expect("display");
    pane.display("hello").await.expect("display");

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

#[tokio::test]
async fn prompt_history_is_available_on_every_supported_release() {
    let guard = TestServer::new().await.expect("tmux starts");
    assert!(
        guard
            .server()
            .prompt_history(libtmux::PromptKind::Command)
            .await
            .expect("prompt history reads")
            .is_empty()
    );
    guard.shutdown().await.expect("tmux fixture shuts down");
}

#[tokio::test]
async fn the_server_access_list_names_its_owner_and_refuses_to_unseat_them() {
    let mut builder = TestServer::builder();
    if let Some(executable) = std::env::var_os("LIBTMUX_TEST_TMUX") {
        builder = builder.tmux_executable(executable);
    }
    let guard = builder.start().await.expect("tmux starts");
    let server = guard.server();

    // Whoever started the server owns it, and an owner may always act.
    let rules = server.access_rules().await.expect("access list");
    let owner = rules.first().expect("the owner is listed");
    assert_eq!(rules.len(), 1);
    assert_eq!(owner.mode(), libtmux::AccessMode::Write);
    assert_eq!(owner.principal(), libtmux::Principal::User);
    assert!(!owner.name().is_empty());

    // tmux refuses to change the owner's own entry, so a caller cannot lock
    // itself out of the server it just started.
    let user = owner.name().to_owned();
    for attempt in [
        server
            .grant_access(&user, libtmux::AccessMode::ReadOnly)
            .await,
        server.revoke_access(&user).await,
    ] {
        let error = attempt.expect_err("tmux refuses to change the owner");
        assert!(
            error.to_string().contains("owns the server"),
            "the refusal says why: {error}",
        );
    }

    // And the list is unchanged by the refusals.
    assert_eq!(server.access_rules().await.expect("access list"), rules);

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

/// Prompt marks come from the shell, so a shell that emits none is the case
/// most callers meet: bash and zsh do not without shell integration, fish
/// does. An unmarked capture is an answer about the shell, not a failure.
#[tokio::test]
async fn real_tmux_compat_capture_line_flags_mark_prompts_when_the_shell_emits_them() {
    use libtmux::{CaptureOptions, since};

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("prompts").await.expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    let supported = server
        .capabilities()
        .await
        .expect("capabilities")
        .tmux_version()
        .has_behavior(&since::CAPTURE_LINE_FLAGS);

    if !supported {
        // Below 3.7 tmux accepts no `-F`, and saying so beats an empty answer.
        let refused = pane.capture_lines(CaptureOptions::visible()).await;
        assert!(
            matches!(
                refused.as_ref().map_err(libtmux::Error::kind),
                Err(libtmux::ErrorKind::UnsupportedVersion),
            ),
            "an older tmux reports the version rather than returning nothing: {refused:?}",
        );
        guard.shutdown().await.expect("tmux fixture shuts down");
        return;
    }

    // Standing in for shell integration: the sequences a shell would emit
    // around its prompt and before its output.
    pane.send_keys(
        r"printf '\033]133;A\007'; echo THE-PROMPT; printf '\033]133;C\007'; echo the-output",
    )
    .await
    .expect("keys are sent");
    pane.send_key_names(["Enter"]).await.expect("Enter is sent");
    tokio::time::sleep(Duration::from_millis(600)).await;

    let lines = pane
        .capture_lines(CaptureOptions::history())
        .await
        .expect("the capture succeeds");

    let prompt = lines
        .iter()
        .position(|line| line.starts_prompt)
        .expect("the prompt mark is reported");
    let output = lines
        .iter()
        .position(|line| line.starts_output)
        .expect("the output mark is reported");

    assert!(prompt < output, "the prompt precedes its output");
    assert_eq!(
        lines[prompt].text.to_string_lossy().trim(),
        "THE-PROMPT",
        "the mark lands on the line the shell was drawing",
    );
    assert_eq!(lines[output].text.to_string_lossy().trim(), "the-output");

    // The flags are stripped rather than left at the front of the text.
    assert!(
        lines
            .iter()
            .all(|line| !line.text.to_string_lossy().starts_with("- ")),
        "no line keeps tmux's flag column in its text",
    );

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

/// A client stopped in place is not a client that went away.
///
/// tmux leaves a suspended client out of `list-clients` -- the listing filters
/// the dead, the exiting and the suspended together -- while still resolving
/// it as a command target. Reading absence from that listing as `ObjectGone`
/// told a caller to discard a handle that works again the moment the client
/// resumes, which is the opposite of what `is_object_gone` is consulted for.
///
/// The client is spawned here rather than taken from `ControlMode`, because
/// suspending a client stops its process and a crate-held connection would
/// then be one this test cannot take down. A child it owns can be killed
/// outright, stopped or not.
#[tokio::test]
async fn a_suspended_client_is_not_reported_gone() {
    use libtmux::since;
    use std::process;

    /// SIGKILL rather than closing stdin: a stopped process never reads its
    /// stdin to notice EOF, so the polite shutdown is the one that hangs.
    struct KillOnDrop(process::Child);
    impl Drop for KillOnDrop {
        fn drop(&mut self) {
            drop(self.0.kill());
            drop(self.0.wait());
        }
    }

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("suspendable").await.expect("session");

    let hides_stopped = server
        .capabilities()
        .await
        .expect("capabilities")
        .tmux_version()
        .has_behavior(&since::CLIENTS_HIDE_STOPPED);

    let child = process::Command::new("tmux")
        .arg("-S")
        .arg(guard.socket_path())
        .arg("-C")
        .arg("attach")
        .arg("-t")
        .arg("suspendable")
        .stdin(process::Stdio::piped())
        .stdout(process::Stdio::null())
        .stderr(process::Stdio::null())
        .spawn()
        .expect("a control-mode client attaches");
    let _client_process = KillOnDrop(child);

    retry_until(Duration::from_secs(10), async || {
        server
            .clients()
            .await
            .is_ok_and(|clients| !clients.is_empty())
    })
    .await
    .expect("the attached client is listed");

    let client = server.clients().await.expect("clients").remove(0);
    client.suspend().await.expect("the client suspends");

    if !hides_stopped {
        // Before 3.7 the listing screens on the session alone, and suspending
        // never clears that, so the client stays listed and reads back with
        // no miss path to take. Asserted rather than skipped: the fix must
        // not have invented an error on a release that has no problem.
        let same = client
            .refreshed()
            .await
            .expect("the client is still listed");
        assert_eq!(same.name(), client.name());
        assert!(
            !server.clients().await.expect("clients").is_empty(),
            "an older tmux lists a suspended client",
        );
        guard.shutdown().await.expect("tmux fixture shuts down");
        return;
    }

    // Leaving the listing is the condition that used to read as gone, so the
    // test asserts it happened rather than assuming the command took effect.
    retry_until(Duration::from_secs(10), async || {
        server
            .clients()
            .await
            .is_ok_and(|clients| clients.is_empty())
    })
    .await
    .expect("the suspended client leaves the listing");

    let Err(error) = client.refreshed().await else {
        panic!("the suspended client is not in the listing to be found")
    };
    assert!(
        matches!(error, libtmux::Error::ClientSuspended { .. }),
        "a suspended client resolves and says so: {error:?}",
    );
    assert!(
        !error.is_object_gone(),
        "this is what a caller consults before discarding the handle",
    );
    assert!(
        error.is_transient(),
        "the same client handle works once the process resumes",
    );

    // And the reason the misreading was tempting: every count a caller might
    // consult goes quiet at once. The client still carries tmux's `attached`
    // flag, but the session stops reporting it, so nothing in the listing
    // surface distinguishes this from a client that left.
    assert!(
        !session.refreshed().await.expect("session").is_attached(),
        "a suspended client stops counting toward its session",
    );
}

/// A capture can now reach what only `Pane::cmd` could before.
///
/// `capture-pane` trims trailing spaces unless given `-N`, and no typed path
/// passed it, so every capture normalised away whatever a program printed at
/// a line's end. A caller asserting on exact pane content had to drop to the
/// untyped API and read bytes.
#[tokio::test]
async fn a_capture_can_keep_the_spaces_tmux_would_trim() {
    use libtmux::CaptureOptions;

    fn printed(lines: Vec<libtmux::TmuxText>) -> String {
        lines
            .into_iter()
            .map(|line| line.to_string_lossy().into_owned())
            .find(|line| line.starts_with("AB"))
            .expect("the printed line is captured")
    }

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    // Printing is the pane's initial command; prompt readiness is not part of
    // this capture assertion.
    let session = server
        .new_session(
            libtmux::NewSessionOptions::new("trailing").command("printf 'AB   \\n'; exec /bin/sh"),
        )
        .await
        .expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    retry_until(Duration::from_secs(10), async || {
        pane.capture()
            .await
            .is_ok_and(|lines| lines.iter().any(|l| l.to_string_lossy().starts_with("AB")))
    })
    .await
    .expect("the pane prints");

    let trimmed = printed(pane.capture().await.expect("default capture"));
    let exact = printed(
        pane.capture_with(CaptureOptions::visible().trailing_spaces())
            .await
            .expect("capture keeping trailing spaces"),
    );

    assert_eq!(trimmed, "AB", "tmux trims trailing spaces without `-N`");
    assert!(
        exact.starts_with("AB   "),
        "`-N` keeps what the program printed: {exact:?}",
    );
    assert!(
        exact.len() > trimmed.len(),
        "the exact capture is longer: {exact:?} vs {trimmed:?}",
    );

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

/// `capture-pane -T` arrived in 3.4, and the crate refuses it below that.
///
/// Asserted on both sides rather than skipped: a capability check that is
/// never exercised on the releases producing the refusal is a branch nothing
/// runs. `just compat` puts 3.2a below the boundary and four releases above.
#[tokio::test]
async fn trimming_blank_cells_is_refused_below_the_release_that_has_it() {
    use libtmux::{CaptureOptions, since};

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("blankcells").await.expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    let supported = server
        .capabilities()
        .await
        .expect("capabilities")
        .tmux_version()
        .has_behavior(&since::CAPTURE_TRIM_BLANK_CELLS);

    let asked = pane
        .capture_with(CaptureOptions::visible().trim_blank_cells())
        .await;

    if supported {
        asked.expect("3.4 and later accept -T");
    } else {
        assert!(
            matches!(
                asked.as_ref().map_err(libtmux::Error::kind),
                Err(libtmux::ErrorKind::UnsupportedVersion),
            ),
            "an older tmux reports the version rather than dispatching a flag \
             it will reject: {asked:?}",
        );
    }

    // `-N` and `-P` are present at the supported floor, so neither is gated
    // and both must work on every release the lanes build.
    pane.capture_with(CaptureOptions::visible().trailing_spaces())
        .await
        .expect("-N works on every supported release");
    pane.capture_with(CaptureOptions::visible().pending_escape())
        .await
        .expect("-P works on every supported release");

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

/// Waiting answers without a feature, and survives the two shapes that made a
/// rebuilt version report success while losing output.
///
/// A screen read misses text that scrolled away before the look, and splits a
/// line wider than the pane into several. Both report success with the wrong
/// content, which is the direction that costs a caller most, so both are
/// asserted rather than assumed.
#[tokio::test]
async fn waiting_survives_scrollback_and_a_line_wider_than_the_pane() {
    use libtmux::PaneWait;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("waits").await.expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    // Wider than any sane pane, so tmux wraps it. A screen read would see
    // several lines and never match a needle spanning the wrap.
    let wide = "W".repeat(400);
    pane.send_keys(format!("printf '{wide}\\n'"))
        .await
        .expect("keys are sent");
    pane.send_key_names(["Enter"]).await.expect("it runs");

    assert_eq!(
        pane.wait_for_text(&wide, Duration::from_secs(10))
            .await
            .expect("waiting is not an error"),
        PaneWait::Arrived,
        "a line wider than the pane is matched across its wrap",
    );

    // Push the wide line off the visible screen. A screen read would now
    // report it absent; the scrollback still holds it.
    for _ in 0..60 {
        pane.send_keys("printf 'filler\\n'").await.expect("keys");
        pane.send_key_names(["Enter"]).await.expect("it runs");
    }
    assert_eq!(
        pane.wait_for_text(&wide, Duration::from_secs(10))
            .await
            .expect("waiting is not an error"),
        PaneWait::Arrived,
        "text that scrolled off the screen is still found",
    );

    // Running out of time is an outcome, not an error.
    assert_eq!(
        pane.wait_for_text("nothing prints this", Duration::from_millis(400))
            .await
            .expect("a deadline is not an error"),
        PaneWait::TimedOut,
    );

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

/// A pane whose process ended stops the wait instead of holding the deadline.
#[tokio::test]
async fn waiting_ends_when_the_pane_dies_rather_than_at_the_deadline() {
    use libtmux::{NewWindowOptions, PaneWait};

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("dying").await.expect("session");

    // `remain-on-exit` keeps the pane after its command ends, so the wait has
    // a dead pane to observe rather than a missing one.
    server
        .cmd(
            Command::new("set-option")
                .arg("-g")
                .arg("remain-on-exit")
                .arg("on"),
        )
        .await
        .expect("panes remain after exit");
    let window = session
        .new_window(NewWindowOptions::new("shortlived").command("true"))
        .await
        .expect("window");
    let pane = window.panes().await.expect("panes").remove(0);

    let started = std::time::Instant::now();
    let outcome = pane
        .wait_for_text("never printed", Duration::from_secs(20))
        .await
        .expect("waiting is not an error");
    let waited = started.elapsed();

    assert_eq!(outcome, PaneWait::Dead);
    assert!(
        waited < Duration::from_secs(15),
        "a dead pane ends the wait early rather than at the deadline: {waited:?}",
    );

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

/// A predicate wait sees whole lines, answers when they satisfy it, and holds
/// an unmet one to the deadline rather than past or short of it.
#[tokio::test]
async fn a_predicate_wait_arrives_or_runs_to_its_deadline() {
    use libtmux::PaneWait;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("predicate").await.expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    // Wider than the pane, so equality holds only if the wrap is joined; and
    // the echoed command contains the text without being equal to it.
    let wide = "P".repeat(300);
    pane.send_line(format!("printf '%s\\n' {wide} {wide}"))
        .await
        .expect("keys are sent");
    let outcome = pane
        .wait_until(Duration::from_secs(10), |lines| {
            lines.iter().filter(|line| **line == *wide).count() == 2
        })
        .await
        .expect("waiting is not an error");
    assert_eq!(outcome, PaneWait::Arrived, "both printed lines were seen");

    let within = Duration::from_millis(400);
    let started = std::time::Instant::now();
    let outcome = tokio::time::timeout(
        within * 10,
        pane.wait_until(within, |lines| lines.iter().any(|line| *line == "absent")),
    )
    .await
    .expect("an unmet wait ends near its deadline, not long after it")
    .expect("a deadline is not an error");
    let waited = started.elapsed();

    assert_eq!(outcome, PaneWait::TimedOut);
    assert!(
        waited >= within,
        "an unmet wait answers at its deadline, not before: {waited:?}",
    );

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

/// A predicate wait on a dead pane ends early, as `wait_for_text` does.
#[tokio::test]
async fn a_predicate_wait_ends_when_the_pane_dies() {
    use libtmux::PaneWait;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("dying").await.expect("session");
    server
        .cmd(
            Command::new("set-option")
                .arg("-g")
                .arg("remain-on-exit")
                .arg("on"),
        )
        .await
        .expect("panes remain after exit");
    let window = session
        .new_window(NewWindowOptions::new("shortlived").command("true"))
        .await
        .expect("window");
    let pane = window.panes().await.expect("panes").remove(0);

    let started = std::time::Instant::now();
    let outcome = pane
        .wait_until(Duration::from_secs(20), |_| false)
        .await
        .expect("waiting is not an error");
    let waited = started.elapsed();

    assert_eq!(outcome, PaneWait::Dead);
    assert!(
        waited < Duration::from_secs(15),
        "a dead pane ends the wait early rather than at the deadline: {waited:?}",
    );

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

/// A pane reached over a control connection waits over that connection.
///
/// A look is a two-command chain, so this is the path where it has to travel
/// as one control-mode line and come back as one block.
#[cfg(feature = "control-mode")]
#[tokio::test]
async fn a_predicate_wait_runs_over_a_control_connection() {
    use libtmux::PaneWait;
    use libtmux::control::ControlMode;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let Some(guard) = versions::control_fixture(guard).await else {
        return;
    };
    let session = guard.server().new_session("routed").await.expect("session");
    let (sender, events) = ControlMode::attach(guard.server(), session.id())
        .await
        .expect("a control connection")
        .split();
    let routed = guard
        .server()
        .over_control_mode(&sender)
        .await
        .expect("a routed handle");
    let pane = routed.panes().await.expect("panes").remove(0);

    pane.send_line("printf 'ROUTED-%s\\n' 1")
        .await
        .expect("keys are sent");
    let outcome = pane
        .wait_until(Duration::from_secs(10), |lines| {
            lines.iter().any(|line| *line == "ROUTED-1")
        })
        .await
        .expect("waiting is not an error");
    assert_eq!(outcome, PaneWait::Arrived);

    events.shutdown().await.expect("the connection closes");
    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// A quiet shorter than the polling interval costs one interval anyway.
///
/// `wait_for_quiet` compares one look with the last, so the shortest silence
/// it can observe is the gap between two of them. Both waits document that
/// gap as 120ms, and a number in prose is only as good as what fails when it
/// moves: shortening `POLL_INTERVAL` without saying so fails here.
#[tokio::test]
async fn a_quiet_below_the_polling_interval_still_costs_one() {
    use libtmux::PaneWait;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("settling").await.expect("session");
    let pane = session.panes().await.expect("panes").remove(0);

    // Nothing is dispatched, so what this times is the floor the interval puts
    // under a shorter request rather than any work the pane is doing.
    let started = std::time::Instant::now();
    let settled = pane
        .wait_for_quiet(Duration::from_millis(5), Duration::from_secs(20))
        .await
        .expect("waiting is not an error");
    let waited = started.elapsed();

    assert_eq!(settled, PaneWait::Arrived, "an idle pane is quiet");
    assert!(
        waited >= Duration::from_millis(120),
        "a 5ms quiet cannot be seen sooner than the 120ms interval: {waited:?}",
    );

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

/// Breaking out the only pane relinks its window instead of doing nothing.
///
/// tmux takes the command, and `cmd-break-pane.c` links the window at a free
/// index rather than refusing. The documentation said it did nothing, which
/// left a caller holding a window whose index had silently moved.
#[tokio::test]
async fn breaking_out_the_only_pane_moves_its_window() {
    use libtmux::NewWindowOptions;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("lonely").await.expect("session");
    let window = session
        .new_window(NewWindowOptions::new("lone"))
        .await
        .expect("window");
    let pane = window.panes().await.expect("panes").remove(0);

    assert_eq!(window.panes().await.expect("panes").len(), 1, "one pane");
    let before = window.index();
    let window_id = window.id().clone();

    pane.break_out().await.expect("tmux accepts the command");

    let after = window
        .refreshed()
        .await
        .expect("the window is still there, by id");
    assert_eq!(after.id(), &window_id, "the window keeps its identity");
    assert_ne!(
        after.index(),
        before,
        "the window moved to a free index rather than nothing happening",
    );

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

/// A handle whose index moved must not act on whatever took the slot.
///
/// Breaking a lone pane out of a window relinks that window at a free index,
/// which renumbers nothing else but leaves every handle above it holding an
/// index that now belongs to a different live window. tmux answers such a
/// target without complaint, so an index-scoped command reports success on the
/// wrong object.
#[tokio::test]
async fn a_window_acts_on_itself_after_its_index_moved() {
    use libtmux::NewWindowOptions;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("renumber").await.expect("session");

    let mut moved = session
        .new_window(NewWindowOptions::new("moved"))
        .await
        .expect("window");
    let moved_id = moved.id().clone();
    let cached = moved.index();

    // Breaking out its only pane relinks the window at a free index.
    let pane = moved.panes().await.expect("panes").remove(0);
    pane.break_out().await.expect("tmux accepts the command");

    let after = moved.refreshed().await.expect("the window still exists");
    assert_ne!(after.index(), cached, "the window moved");

    // Put a window in the slot the handle still remembers. This is what
    // separates dangerous from merely stale: an empty slot refuses, and an
    // occupied one answers about somebody else.
    let intruder = session
        .new_window(NewWindowOptions::new("intruder").index(cached))
        .await
        .expect("a window takes the vacated slot");
    let intruder_id = intruder.id().clone();
    assert_eq!(intruder.index(), cached, "the slot is occupied again");
    assert_ne!(intruder_id, moved_id, "by a different window");

    // Selecting through the stale handle must reach the handle's own window.
    moved.select().await.expect("select succeeds");
    let active = session
        .active_window()
        .await
        .expect("active window")
        .expect("a session always has one");
    assert_eq!(
        active.id(),
        &moved_id,
        "select acted on the handle's window, not on whatever took its index",
    );
    assert_ne!(
        active.id(),
        &intruder_id,
        "and not on the window occupying its old index",
    );

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

#[tokio::test]
async fn a_name_outside_ascii_survives_the_listing() {
    // tmux replaces every byte outside `0x20..=0x7e` with `_` unless it
    // believes its client speaks UTF-8, and it decides that from the client
    // process's own `TMUX` and locale variables. This crate unsets `TMUX` and
    // inherits whatever locale its caller had, so without saying so directly
    // this name comes back as six underscores and no error.
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    let session = server.new_session("日本語").await.expect("session");
    assert_eq!(session.name().as_bytes(), "日本語".as_bytes());

    let listed = server.sessions().await.expect("sessions");
    assert_eq!(listed[0].name().as_bytes(), "日本語".as_bytes());

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