libtmux 0.1.0-alpha.13

Async typed tmux client and object model (alpha)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
//! Options and hooks against real tmux.

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

use libtmux::test::TestServer;
use libtmux::{EnvironmentEntry, OptionValue};
use libtmux::{NewWindowOptions, TmuxText};

fn bytes(value: Option<impl Into<TmuxText>>) -> Vec<u8> {
    value
        .expect("tmux reports a value")
        .into()
        .as_bytes()
        .to_vec()
}

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

    // tmux renders each of these differently in its listing form: bare with
    // backslash escapes, double quotes, or single quotes. Reading through
    // `show-options -v` returns the stored bytes whatever the display form.
    for value in [
        "plain",
        "a b  c",
        "has\"quote",
        "has\\back",
        "has;semi",
        "has'single",
        "tab\tsep",
    ] {
        server
            .set_option("@probe", value)
            .await
            .expect("option is set");
        assert_eq!(
            bytes(server.typed_option("@probe").await.expect("option is read")),
            value.as_bytes(),
            "{value:?} round-trips exactly",
        );
    }

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

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

    // A user option exists only while it is set, so an unset one is absent
    // rather than an error, even though tmux itself calls it unknown.
    assert!(
        server
            .typed_option("@absent")
            .await
            .expect("an unset user option is absent")
            .is_none(),
    );

    // A built-in name tmux does not have is a caller mistake.
    let error = server
        .typed_option("no-such-built-in")
        .await
        .expect_err("an unknown built-in name is refused");
    assert!(matches!(
        error,
        libtmux::Error::OptionRejected {
            kind: libtmux::OptionErrorKind::Unknown,
            ..
        },
    ));

    // A known option with no value at this scope reports absence instead.
    assert!(
        server
            .typed_global_option("after-kill-pane[0]")
            .await
            .expect("a known hook name is accepted")
            .is_none(),
    );

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

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

    let session = server.new_session("scoped").await.expect("session created");
    let window = session
        .new_window(NewWindowOptions::new("scoped").command("sleep 300"))
        .await
        .expect("window created");
    let pane = window
        .panes()
        .await
        .expect("panes list")
        .into_iter()
        .next()
        .expect("one pane");

    server.set_option("@where", "server").await.expect("set");
    session.set_option("@where", "session").await.expect("set");
    window.set_option("@where", "window").await.expect("set");
    pane.set_option("@where", "pane").await.expect("set");

    assert_eq!(
        bytes(server.typed_option("@where").await.expect("read")),
        b"server"
    );
    assert_eq!(
        bytes(session.typed_option("@where").await.expect("read")),
        b"session"
    );
    assert_eq!(
        bytes(window.typed_option("@where").await.expect("read")),
        b"window"
    );
    assert_eq!(
        bytes(pane.typed_option("@where").await.expect("read")),
        b"pane"
    );

    // Unsetting one scope leaves the others alone.
    window.unset_option("@where").await.expect("unset");
    assert!(window.typed_option("@where").await.expect("read").is_none());
    assert_eq!(
        bytes(session.typed_option("@where").await.expect("read")),
        b"session"
    );
    assert_eq!(
        bytes(pane.typed_option("@where").await.expect("read")),
        b"pane"
    );

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

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

    session.set_option("@parts", "one").await.expect("set");
    session
        .append_option("@parts", "-two")
        .await
        .expect("append");

    assert_eq!(
        bytes(session.typed_option("@parts").await.expect("read")),
        b"one-two",
    );

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

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

    server
        .set_option("@listed", "a value with spaces")
        .await
        .expect("option is set");

    let names = server.option_names().await.expect("names are listed");
    assert!(names.iter().any(|name| name == "@listed"));
    // Array options appear once per index, exactly as tmux writes them.
    assert!(
        names.iter().any(|name| name.starts_with("command-alias[")),
        "array options keep their index",
    );

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

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

    server
        .set_hook("after-new-window", "display-message hooked")
        .await
        .expect("hook is set");

    // Hooks live in the option tables, so the same reader sees them.
    assert_eq!(
        bytes(
            server
                .typed_global_option("after-new-window[0]")
                .await
                .expect("hook is read"),
        ),
        b"display-message hooked",
    );

    server
        .unset_hook("after-new-window")
        .await
        .expect("hook is removed");
    assert!(
        server
            .typed_global_option("after-new-window[0]")
            .await
            .expect("hook is read")
            .is_none(),
    );

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

#[tokio::test]
async fn option_values_decode_into_flags_and_numbers() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    // Reading the global session table needs a session to exist, because tmux
    // resolves it against the current one.
    server.new_session("typed").await.expect("session");

    // The bytes behind a typed value still read as a flag, whatever variant
    // carried them: `status` is a choice and arrives as text.
    let status = server
        .typed_global_option("status")
        .await
        .expect("read")
        .expect("status is set");
    assert_eq!(TmuxText::from(status).as_flag(), Some(true));

    // Numeric options parse without the caller checking UTF-8 first.
    // history-limit lives in the session table, not the server one.
    let limit = server
        .typed_global_option("history-limit")
        .await
        .expect("read")
        .expect("history-limit is set");
    assert!(
        TmuxText::from(limit)
            .parse::<u32>()
            .is_some_and(|value| value > 0)
    );

    // A value that is neither is reported as neither, rather than guessed at.
    server.set_option("@prose", "sometimes").await.expect("set");
    let prose = TmuxText::from(
        server
            .typed_option("@prose")
            .await
            .expect("read")
            .expect("the option is set"),
    );
    assert_eq!(prose.as_flag(), None);
    assert_eq!(prose.parse::<u32>(), None);

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

#[tokio::test]
async fn options_decode_by_declared_kind_rather_than_by_shape() {
    use libtmux::{OptionKind, OptionValue, option_schema};

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

    // The schema comes from tmux's own table, so a flag is a flag even though
    // its value is the text "off", and a number is a number.
    assert_eq!(
        option_schema("mouse").map(OptionSchemaKind::kind),
        Some(OptionKind::Flag),
    );
    assert_eq!(
        server.typed_global_option("mouse").await.expect("read"),
        Some(OptionValue::Flag(false)),
    );
    assert!(matches!(
        server
            .typed_global_option("history-limit")
            .await
            .expect("read"),
        Some(OptionValue::Number(limit)) if limit > 0,
    ));

    // `status` looks like a flag and is not: tmux accepts on, off, and 2
    // through 5 for several status lines. Guessing from the value would have
    // called it a flag, which is why the schema comes from tmux's own table.
    assert_eq!(
        option_schema("status").map(OptionSchemaKind::kind),
        Some(OptionKind::Choice),
    );
    assert!(matches!(
        server.typed_global_option("status").await.expect("read"),
        Some(OptionValue::Text(_)),
    ));

    // A user option has no declared type, so it stays text whatever it holds.
    assert_eq!(option_schema("@mine"), None);
    server.set_option("@mine", "on").await.expect("set");
    assert!(matches!(
        server.typed_option("@mine").await.expect("read"),
        Some(OptionValue::Text(_)),
    ));

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

use libtmux::OptionSchema as OptionSchemaKind;

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

    assert!(
        server.hook("alert-bell").await.expect("read").is_none(),
        "a hook holding nothing is absent, not present and empty",
    );

    // A value tmux renders with quotes when it lists it, so reading it back
    // through the listing would return the rendering rather than the value.
    server
        .set_hook("alert-bell", r#"run-shell "echo a  b""#)
        .await
        .expect("the hook is set");

    let read = server
        .hook("alert-bell")
        .await
        .expect("read")
        .expect("the hook is set");
    assert_eq!(read.len(), 1);
    assert_eq!(
        read.first().expect("a command").as_bytes(),
        br#"run-shell "echo a  b""#,
        "the exact bytes come back, double space and all",
    );

    // The listing reports it too, and reports only hooks holding something:
    // tmux names every hook it knows and most of them hold nothing.
    let all = server.hooks().await.expect("listing");
    assert!(all.contains_key("alert-bell"));
    assert!(
        all.len() < 20,
        "only the hooks holding something are listed, not every name tmux knows: {}",
        all.len(),
    );

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

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

    // Setting without an index writes slot 0; an explicit index writes that
    // slot, and the gap between them is real rather than closed up.
    server
        .set_hook("alert-bell", "display-message zero")
        .await
        .expect("slot 0");
    server
        .set_hook("alert-bell[3]", "display-message three")
        .await
        .expect("slot 3");

    let read = server
        .hook("alert-bell")
        .await
        .expect("read")
        .expect("the hook is set");

    assert_eq!(read.len(), 2);
    let indices: Vec<u32> = read.iter().map(|(index, _)| *index).collect();
    assert_eq!(indices, [0, 3], "the gap tmux keeps is kept here too");
    assert!(read.get(1).is_none(), "nothing is invented for the gap");
    assert_eq!(
        read.first()
            .map(|value| value.to_string_lossy().into_owned()),
        Some("display-message zero".to_owned()),
        "the lowest index is what a hook set without one holds",
    );

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

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

    // A pane hook, because those are the hooks tmux keeps at window scope.
    // `alert-bell` is a session hook, and setting it here would land on the
    // session while this test read it back through the window and agreed.
    window
        .set_hook("pane-died", "display-message window")
        .await
        .expect("window hook");

    // Reading by name is what works at every scope. tmux will not enumerate
    // the hooks set on a window or a pane -- `show-hooks` reports nothing for
    // them and `show-options` omits them while still listing ordinary options
    // -- but it does list the slots of a hook it is asked about by name. That
    // is why `Window` and `Pane` offer `hook` and no listing: a listing there
    // could answer nothing but empty, which reads as "none set".
    let read = window
        .hook("pane-died")
        .await
        .expect("read")
        .expect("the window holds what was set on it");
    assert_eq!(
        read.first()
            .map(|value| value.to_string_lossy().into_owned()),
        Some("display-message window".to_owned()),
    );

    // The server enumerates the scopes tmux does report.
    server
        .set_hook("alert-silence", "display-message server")
        .await
        .expect("server hook");
    assert!(
        server
            .hooks()
            .await
            .expect("listing")
            .contains_key("alert-silence"),
    );

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

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

    session
        .set_option("status-left-length", "30")
        .await
        .expect("a number");
    session.set_option("status", "on").await.expect("a flag");
    session
        .set_option("@marker", "kept")
        .await
        .expect("a user option");

    let options = session.options().await.expect("listing");

    // Each value comes back decoded by the kind tmux declares, not guessed
    // from how it looks: `status` holds "on" and is a choice rather than a
    // flag, because tmux also accepts 2 through 5 for it.
    assert_eq!(
        options.get("status-left-length"),
        Some(&OptionValue::Number(30)),
    );
    assert!(matches!(
        options.get("@marker"),
        Some(OptionValue::Text(text)) if text.as_bytes() == b"kept",
    ));
    assert!(options.contains_key("status"));

    // The listing reports what is set, and an empty answer would mean nothing
    // is set rather than that the listing failed: a refusal is an error.
    assert!(!options.is_empty());

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

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

    // `command-alias` is a server option and an array, so tmux lists it one
    // entry per index and the listing keeps those names rather than
    // collapsing them.
    let options = server.options().await.expect("listing");

    let aliased: Vec<&String> = options
        .keys()
        .filter(|name| name.starts_with("command-alias["))
        .collect();
    assert!(
        !aliased.is_empty(),
        "tmux ships command-alias entries: {:?}",
        options.keys().take(5).collect::<Vec<_>>(),
    );

    // A listing reports what is set at that scope, not what an object would
    // resolve to. A session that has set nothing of its own is empty even
    // though every option still has an effective value it inherits.
    let fresh = server
        .new_session("inheriting")
        .await
        .expect("session")
        .options()
        .await
        .expect("listing");
    assert!(
        fresh.is_empty(),
        "a session that set nothing has nothing of its own: {fresh:?}",
    );

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

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

    session
        .set_environment("EDITOR", "vi")
        .await
        .expect("a value");
    session
        .hide_environment("PAGER")
        .await
        .expect("a removal mark");

    let environment = session.environment_all().await.expect("listing");

    // tmux stores "hold this value" and "do not pass this on" as different
    // things, and neither is absence. Reporting both as absent would hide the
    // second, which is what a caller sets deliberately.
    assert!(matches!(
        environment.get("EDITOR"),
        Some(EnvironmentEntry::Set(value)) if value.as_bytes() == b"vi",
    ));
    assert_eq!(environment.get("PAGER"), Some(&EnvironmentEntry::Removed));
    assert_eq!(environment.get("NEVER_SET"), None);

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

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

    // Each of these breaks a naive parse of the listing: an embedded newline
    // spans lines, and a continuation line holding `=` reads exactly like the
    // next variable. Reading every name back on its own is what survives it.
    session
        .set_environment("MULTILINE", "first\nDECOY=not-a-variable")
        .await
        .expect("a value with a newline");
    session
        .set_environment("SPACED", "x  y")
        .await
        .expect("a value with runs of spaces");
    // Shaped like the listing's own framing, and carrying every byte the
    // listing escapes, so a value that ends early reads as another variable.
    session
        .set_environment("FRAMED", "a\"; export FRAMED;\nFORGED=\"b\\$c`d\\\\")
        .await
        .expect("a value shaped like framing");

    let environment = session.environment_all().await.expect("listing");

    for name in ["MULTILINE", "SPACED", "FRAMED"] {
        assert_eq!(
            environment.get(name),
            session.environment(name).await.expect("read").as_ref(),
            "{name} reads the same whole as alone",
        );
    }
    assert_eq!(environment.get("FORGED"), None, "framing inside a value");

    assert!(matches!(
        environment.get("MULTILINE"),
        Some(EnvironmentEntry::Set(value)) if value.as_bytes() == b"first\nDECOY=not-a-variable",
    ));
    assert!(matches!(
        environment.get("SPACED"),
        Some(EnvironmentEntry::Set(value)) if value.as_bytes() == b"x  y",
    ));
    assert_eq!(
        environment.get("DECOY"),
        None,
        "a continuation line is not a variable, however much it looks like one",
    );

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

#[tokio::test]
async fn writing_a_whole_hook_replaces_or_merges_as_asked() {
    use libtmux::{IndexedHooks, ReplaceMode, TmuxText};
    use std::collections::BTreeMap;

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

    server
        .set_hook("alert-bell[7]", "display-message existing")
        .await
        .expect("an entry to survive or not");

    let mut entries = BTreeMap::new();
    entries.insert(0, TmuxText::from(b"display-message first".to_vec()));
    entries.insert(3, TmuxText::from(b"display-message fourth".to_vec()));
    let written = IndexedHooks::from(entries);

    // Merge leaves what it does not name, so the earlier entry stays.
    server
        .set_hooks("alert-bell", &written, ReplaceMode::Merge)
        .await
        .expect("merge");
    let merged = server
        .hook("alert-bell")
        .await
        .expect("read")
        .expect("the hook is set");
    assert_eq!(merged.len(), 3);
    assert!(
        merged.get(7).is_some(),
        "merge kept the entry it did not name"
    );

    // Replace clears first, so only what was written remains -- gaps and all.
    server
        .set_hooks("alert-bell", &written, ReplaceMode::Replace)
        .await
        .expect("replace");
    let replaced = server
        .hook("alert-bell")
        .await
        .expect("read")
        .expect("the hook is set");
    assert_eq!(
        replaced.iter().map(|(index, _)| *index).collect::<Vec<_>>(),
        [0, 3],
        "the sparse indices are kept and nothing else survives",
    );

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

#[tokio::test]
async fn a_later_bulk_hook_refusal_reports_the_hook_already_written() {
    use libtmux::{Error, ErrorKind, IndexedHooks, ReplaceMode, TmuxText};
    use std::collections::BTreeMap;

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

    let mut entries = BTreeMap::new();
    entries.insert(0, TmuxText::from("display-message first"));
    entries.insert(1, TmuxText::from("no-such-tmux-command"));

    let error = server
        .set_hooks(
            "alert-bell",
            &IndexedHooks::from(entries),
            ReplaceMode::Merge,
        )
        .await
        .expect_err("tmux refuses the second hook command");

    let hooks = server
        .hook("alert-bell")
        .await
        .expect("the partly written hook can be read")
        .expect("the first hook remains set");
    assert_eq!(
        hooks.get(0).map(TmuxText::as_bytes),
        Some(b"display-message first".as_slice()),
    );
    assert!(hooks.get(1).is_none(), "the refused hook was not stored");

    assert_eq!(error.kind(), ErrorKind::PartialEffect);
    assert!(matches!(
        error,
        Error::AfterEffect {
            operation: "set-hooks",
            source,
            ..
        } if source.kind() == ErrorKind::Refused
    ));

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

#[tokio::test]
async fn a_first_bulk_hook_refusal_has_no_partial_effect() {
    use libtmux::{ErrorKind, IndexedHooks, ReplaceMode, TmuxText};
    use std::collections::BTreeMap;

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

    let mut entries = BTreeMap::new();
    entries.insert(0, TmuxText::from("no-such-tmux-command"));
    entries.insert(1, TmuxText::from("display-message never-written"));

    let error = server
        .set_hooks(
            "alert-bell",
            &IndexedHooks::from(entries),
            ReplaceMode::Merge,
        )
        .await
        .expect_err("tmux refuses the first hook command");

    assert_eq!(error.kind(), ErrorKind::Refused);
    assert!(
        server
            .hook("alert-bell")
            .await
            .expect("the hook can be read")
            .is_none(),
        "the member after the refusal never ran",
    );

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

#[tokio::test]
async fn tmux_refusing_an_option_says_which_of_three_things_went_wrong() {
    use libtmux::OptionErrorKind;

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

    // Three different fixes: a typo, a name that needs more of itself, and a
    // value the option will not hold. Reading stderr to tell them apart also
    // means knowing tmux says "bad value" for a flag and "value is invalid"
    // for a number, which is not a distinction a caller should have to learn.
    let cases = [
        ("no-such-option", "x", OptionErrorKind::Unknown),
        ("status-l", "x", OptionErrorKind::Ambiguous),
        ("mouse", "notabool", OptionErrorKind::BadValue),
        (
            "status-left-length",
            "notanumber",
            OptionErrorKind::BadValue,
        ),
    ];

    for (name, value, expected) in cases {
        let error = server
            .set_global_option(name, value)
            .await
            .expect_err("tmux refuses it");
        assert!(
            matches!(&error, libtmux::Error::OptionRejected { kind, .. } if *kind == expected),
            "{name}={value} should be {expected:?}, got {error:?}",
        );
        assert_eq!(error.kind(), libtmux::ErrorKind::Refused);
    }

    // A name it does resolve is still accepted.
    server
        .set_global_option("status-left-length", "30")
        .await
        .expect("a valid option and value");

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

#[tokio::test]
async fn rejected_sensitive_values_are_absent_from_errors() {
    use libtmux::{Error, OptionErrorKind};

    const SECRET: &str = "libtmux-sentinel-sensitive-value";

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

    for name in ["mouse", "status-keys"] {
        let error = server
            .set_global_option(name, SECRET)
            .await
            .expect_err("tmux refuses the value");
        assert!(
            matches!(
                &error,
                Error::OptionRejected {
                    kind: OptionErrorKind::BadValue,
                    detail,
                } if detail == name
            ),
            "the error names the option and classifies its value: {error:?}",
        );
        assert!(!error.to_string().contains(SECRET), "{error}");
        assert!(!format!("{error:?}").contains(SECRET), "{error:?}");
    }

    let error = server
        .set_hook("after-new-window", SECRET)
        .await
        .expect_err("tmux refuses an unknown hook command");
    assert!(error.to_string().contains("set-hook"), "{error}");
    assert!(!error.to_string().contains(SECRET), "{error}");
    assert!(!format!("{error:?}").contains(SECRET), "{error:?}");

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

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

    server
        .set_environment("SERVER_ONLY", "yes")
        .await
        .expect("a server value");

    // Separate stores, not one layered over the other. Reading a session is
    // not a fallback to the server, whenever the session was created: tmux
    // merges the two only when it starts a process.
    let before = server.new_session("before").await.expect("session");
    let after = server.new_session("after").await.expect("session");
    for (label, session) in [("before", &before), ("after", &after)] {
        assert_eq!(
            session.environment("SERVER_ONLY").await.expect("read"),
            None,
            "the {label} session has no entry of its own for a server variable",
        );
    }

    // Setting it on one session does not reach back to the server.
    after
        .set_environment("SESSION_ONLY", "mine")
        .await
        .expect("a session value");
    assert_eq!(
        server.environment("SESSION_ONLY").await.expect("read"),
        None
    );

    // The two halves of removal behave on the server as they do on a session.
    server.hide_environment("HIDDEN").await.expect("a mark");
    assert_eq!(
        server.environment("HIDDEN").await.expect("read"),
        Some(EnvironmentEntry::Removed),
    );

    let listing = server.environment_all().await.expect("listing");
    assert!(matches!(
        listing.get("SERVER_ONLY"),
        Some(EnvironmentEntry::Set(value)) if value.as_bytes() == b"yes",
    ));
    assert_eq!(listing.get("HIDDEN"), Some(&EnvironmentEntry::Removed));
    assert_eq!(listing.get("SESSION_ONLY"), None);

    server
        .unset_environment("SERVER_ONLY")
        .await
        .expect("removal");
    assert_eq!(server.environment("SERVER_ONLY").await.expect("read"), None);

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

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

    server
        .set_environment("BOTH", "from_server")
        .await
        .expect("set");
    server
        .set_environment("ONLY_SERVER", "reaches")
        .await
        .expect("set");
    server
        .hide_environment("HIDDEN_GLOBALLY")
        .await
        .expect("mark");

    let session = server.new_session("merged").await.expect("session");
    session
        .set_environment("BOTH", "from_session")
        .await
        .expect("set");

    // The stores are separate right up until tmux starts something, so this is
    // the only place the merge is observable. Reading the two stores back tells
    // a caller nothing about what a pane will actually be handed.
    let window = session
        .new_window(
            NewWindowOptions::new("merged")
                .command("sh -c 'printf \"%s|%s|%s\" \"$BOTH\" \"$ONLY_SERVER\" \"${HIDDEN_GLOBALLY-absent}\"; sleep 30'"),
        )
        .await
        .expect("window created");
    let pane = window
        .panes()
        .await
        .expect("panes")
        .into_iter()
        .next()
        .expect("one pane");

    let mut captured = String::new();
    for _ in 0..50 {
        let lines = pane.capture().await.expect("capture");
        captured = lines
            .iter()
            .map(|line| line.to_string_lossy().into_owned())
            .collect::<Vec<_>>()
            .join("\n");
        if captured.contains('|') {
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(40)).await;
    }

    // The session's value wins, a server-only name still arrives, and a
    // globally hidden name is missing rather than empty.
    assert!(
        captured.contains("from_session|reaches|absent"),
        "merged environment, got {captured:?}",
    );

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

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

    // tmux ships defaults in the low indices of this option, so writing far
    // above them keeps the test's own entries distinguishable.
    server
        .set_array_option("command-alias", 30, "thirty=display -p 30")
        .await
        .expect("index 30 is set");
    server
        .set_array_option("command-alias", 35, "five=display -p 35")
        .await
        .expect("index 35 is set");

    let aliases = server.array_option("command-alias").await.expect("read");
    assert_eq!(
        bytes(aliases.get(30).cloned()),
        b"thirty=display -p 30",
        "the value is stored under the index asked for",
    );
    assert_eq!(aliases.get(31), None, "nothing was written between them");
    assert!(
        aliases.indices().any(|index| *index == 35),
        "the higher index is listed: {:?}",
        aliases.indices().collect::<Vec<_>>(),
    );

    // Appending extends that index's value rather than adding an entry.
    let before = aliases.len();
    server
        .append_array_option("command-alias", 30, " extra")
        .await
        .expect("append");
    let appended = server.array_option("command-alias").await.expect("read");
    assert_eq!(appended.len(), before, "appending did not add an entry");
    assert_eq!(
        bytes(appended.get(30).cloned()),
        b"thirty=display -p 30 extra",
    );

    // Removing one leaves the rest where they were: nothing renumbers.
    server
        .unset_array_option("command-alias", 35)
        .await
        .expect("unset");
    let after = server.array_option("command-alias").await.expect("read");
    assert_eq!(after.get(35), None, "the entry is gone");
    assert_eq!(
        bytes(after.get(30).cloned()),
        b"thirty=display -p 30 extra",
        "the entry below it did not move",
    );

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

#[tokio::test]
async fn a_name_shaped_like_a_flag_is_refused_not_obeyed() {
    // tmux reads a leading `-` as a flag wherever it appears, so an option
    // name a caller did not write could act on a different option. `-u` is
    // the sharp one: it unsets.
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("flags").await.expect("session");

    session
        .set_option("@kept", "original")
        .await
        .expect("a plain user option is set");

    session
        .set_option("-u", "@kept")
        .await
        .expect_err("a name that is a flag is refused");

    assert_eq!(
        bytes(
            session
                .typed_option("@kept")
                .await
                .expect("the option reads")
        ),
        b"original".to_vec(),
        "the option a flag name pointed at survived",
    );

    // A variable may legitimately be named anything, so the guard does not
    // refuse this one; what it stops is `-u` being read as the flag that
    // removes a different variable.
    session
        .set_environment("KEPT", "original")
        .await
        .expect("a plain variable is set");
    session
        .set_environment("-u", "KEPT")
        .await
        .expect("a variable named like a flag is a variable");

    let kept = session
        .environment("KEPT")
        .await
        .expect("the variable reads");
    assert!(
        matches!(&kept, Some(EnvironmentEntry::Set(value)) if value.as_bytes() == b"original"),
        "the variable a flag name pointed at survived, got {kept:?}",
    );

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

#[tokio::test]
async fn a_whole_hook_write_refuses_bytes_rather_than_substituting_them() {
    use libtmux::{IndexedHooks, ReplaceMode, TmuxText};
    use std::collections::BTreeMap;

    // A hook value is a tmux command, and tmux refuses one carrying a byte it
    // cannot read. Passing the bytes through a `String` first replaced that
    // byte with U+FFFD, which tmux then accepted: the caller was told the
    // write succeeded and tmux held a command they had not written.
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();

    let mut command = b"set-environment -g MARK \"a".to_vec();
    command.push(0xff);
    command.extend_from_slice(b"b\"");

    let mut entries = BTreeMap::new();
    entries.insert(0, TmuxText::from(command));
    server
        .set_hooks(
            "alert-bell",
            &IndexedHooks::from(entries),
            ReplaceMode::Replace,
        )
        .await
        .expect_err("tmux refuses a command it cannot read");

    assert!(
        server
            .hook("alert-bell")
            .await
            .expect("the hook reads")
            .is_none_or(|hook| hook.get(0).is_none()),
        "nothing was stored under a substituted value",
    );

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

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

    for slot in [0_usize, 2, 5] {
        server
            .set_hook(
                &format!("alert-bell[{slot}]"),
                format!("display-message {slot}"),
            )
            .await
            .expect("a slot is written");
    }

    // A hook is an array, and tmux empties the array for an unindexed write.
    // Setting one hook used to discard every other slot the caller had
    // registered, and report success for doing it.
    server
        .set_hook("alert-bell", "display-message replaced")
        .await
        .expect("the hook is set");

    let hooks = server
        .hook("alert-bell")
        .await
        .expect("the hook reads")
        .expect("the hook is set");
    assert_eq!(
        hooks.get(2).map(|command| command.to_string_lossy()),
        Some("display-message 2".into()),
        "a slot nobody wrote to survives: {hooks:?}",
    );
    assert_eq!(
        hooks.get(5).map(|command| command.to_string_lossy()),
        Some("display-message 5".into()),
        "and so does the last one: {hooks:?}",
    );
    assert_eq!(
        hooks.get(0).map(|command| command.to_string_lossy()),
        Some("display-message replaced".into()),
        "while slot 0 is the one that changed: {hooks:?}",
    );

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

#[tokio::test]
async fn the_schema_agrees_with_where_tmux_accepts_a_write() {
    use libtmux::{OptionScope, option_schema};

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("scoped").await.expect("a session");
    let window = session
        .windows()
        .await
        .expect("windows")
        .into_iter()
        .next()
        .expect("one window");

    // A pane hook is a window option too, and tmux has said so since 3.2a. The
    // schema called it pane-only, so anything consulting it to choose a scope
    // was told this write would not land.
    let schema = option_schema("pane-died").expect("a documented hook");
    assert!(schema.accepts(OptionScope::Window), "{:?}", schema.scopes());

    window
        .set_hook("pane-died", "display-message gone")
        .await
        .expect("tmux accepts a pane hook at window scope");
    assert!(
        window
            .hook("pane-died")
            .await
            .expect("the hook reads")
            .is_some(),
        "and reads it back there",
    );

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

#[tokio::test]
async fn a_write_tmux_would_place_elsewhere_is_refused() {
    use libtmux::{ErrorKind, OptionScope};

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("scoped").await.expect("a session");
    let pane = session
        .active_window()
        .await
        .expect("active window")
        .expect("a session has a window")
        .active_pane()
        .await
        .expect("active pane")
        .expect("a window has a pane");

    // tmux keeps `mouse` per session and picks that table from the name, so it
    // would carry this out for the whole session and exit 0. Reading it back
    // through the same pane resolves the same way and agrees, which is why
    // this has to be refused before it is sent rather than checked after.
    let error = pane
        .set_option("mouse", "on")
        .await
        .expect_err("a session option is not the pane's to set");
    assert_eq!(error.kind(), ErrorKind::InvalidInput);
    assert!(
        matches!(
            error,
            libtmux::Error::OptionScopeMismatch {
                requested: OptionScope::Pane,
                ..
            }
        ),
        "the error names the scope that was asked for: {error:?}",
    );

    // The control: tmux keeps this one at window and pane both, so the same
    // handle writes it, and a guard that refused here would be refusing what
    // tmux accepts.
    pane.set_option("remain-on-exit", "on")
        .await
        .expect("a pane option is the pane's to set");

    // A user option has no entry in tmux's table and tmux honours the flags
    // literally for one, so nothing is guessed about where it belongs.
    pane.set_option("@mine", "value")
        .await
        .expect("a user option is written wherever it was aimed");

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

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

    // tmux takes an unambiguous prefix for the option itself, so this is a
    // write to the session's `mouse` however little of the name was typed.
    // Matching on the text alone let it through and the write landed.
    pane.set_option("mous", "on")
        .await
        .expect_err("a prefix reaches the option it names");

    // The same for a spelling tmux maps before it looks anything up.
    pane.set_option("display-panes-color", "red")
        .await
        .expect_err("an alias reaches the option it maps to");

    // An ambiguous prefix belongs to tmux: it names the input in its own
    // answer, which is more use than a guess made here.
    let ambiguous = pane
        .set_option("pane-b", "on")
        .await
        .expect_err("tmux refuses an ambiguous name");
    assert!(
        !matches!(ambiguous, libtmux::Error::OptionScopeMismatch { .. }),
        "and it is tmux's refusal, not this crate's: {ambiguous:?}",
    );

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

/// `pane-border-format` reached a build that already has it, not just one
/// numbered high enough.
///
/// `ensure_scope`'s `LATE_SCOPES` check used to call `TmuxVersion::meets`,
/// which clamps every development identifier to the crate's minimum
/// supported release regardless of its own next-release number -- so a
/// `next-X.Y` build that genuinely has this capability was refused anyway.
/// Fixed by switching to `TmuxVersion::has_behavior`, which reads `next-X.Y`
/// as the real release. Asserted on whichever tmux is actually running
/// rather than assumed, so this is correct on every release the compat
/// matrix builds, `next-3.9` included, without a version predicate.
#[tokio::test]
async fn a_late_pane_scope_is_granted_to_whichever_tmux_actually_has_it() {
    use libtmux::since;

    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();
    let session = server.new_session("late-scope").await.expect("a session");
    let pane = session
        .active_window()
        .await
        .expect("active window")
        .expect("a session has a window")
        .active_pane()
        .await
        .expect("active pane")
        .expect("a window has a pane");

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

    let result = pane.set_option("pane-border-format", "#{pane_index}").await;
    if has_capability {
        result.expect("a build that already has this capability accepts the write");
    } else {
        let error = result.expect_err("a build below the real floor is still refused");
        assert!(
            matches!(
                error,
                libtmux::Error::UnsupportedCapability {
                    capability: "pane-border-format",
                    ..
                }
            ),
            "the refusal names the capability: {error:?}",
        );
    }

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

/// Each kind is written as the variant `typed_option` reads back, and reads
/// back equal, on every handle that has a typed write.
#[tokio::test]
async fn a_typed_write_reads_back_as_the_value_written() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server();
    let session = server.new_session("typed").await.expect("a session");
    let window = session
        .active_window()
        .await
        .expect("active window")
        .expect("a session has a window");

    let cases = [
        ("mouse", OptionValue::Flag(true)),
        ("history-limit", OptionValue::Number(4321)),
        ("status-keys", OptionValue::from("vi")),
        ("status-left", OptionValue::from("typed #[fg=red]")),
    ];
    for (name, value) in cases {
        session
            .set_typed_option(name, value.clone())
            .await
            .unwrap_or_else(|error| panic!("{name} takes {value:?}: {error}"));
        assert_eq!(
            session.typed_option(name).await.expect("read"),
            Some(value),
            "{name} reads back as written",
        );
    }

    window
        .set_typed_option("synchronize-panes", true)
        .await
        .expect("a window flag");
    assert_eq!(
        window
            .typed_option("synchronize-panes")
            .await
            .expect("read"),
        Some(OptionValue::Flag(true)),
    );

    server
        .set_typed_option("escape-time", 15)
        .await
        .expect("a server number");
    assert_eq!(
        server.typed_option("escape-time").await.expect("read"),
        Some(OptionValue::Number(15)),
    );
    server
        .set_typed_global_window_option("mode-keys", "vi")
        .await
        .expect("a global window choice");
    assert_eq!(
        server
            .typed_global_window_option("mode-keys")
            .await
            .expect("read"),
        Some(OptionValue::from("vi")),
    );

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

/// A value the table refuses fails before dispatch and leaves the option as
/// it was.
///
/// The first case is the one that proves nothing was sent: tmux itself takes
/// `1` for a flag, so had the write reached it `mouse` would now be on. The
/// other two are values tmux would also refuse, so what shows they were
/// stopped here is the error: tmux's refusal is `OptionRejected`.
#[tokio::test]
async fn a_value_the_table_refuses_never_reaches_tmux() {
    use libtmux::{Error, ErrorKind, OptionKind, OptionValueRefusal};

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

    session
        .set_typed_option("mouse", false)
        .await
        .expect("mouse starts off");
    session
        .set_typed_option("status-keys", "emacs")
        .await
        .expect("status-keys starts at emacs");
    session
        .set_typed_option("history-limit", 1234)
        .await
        .expect("history-limit starts at 1234");

    let cases = [
        (
            "mouse",
            OptionValue::Number(1),
            OptionValueRefusal::WrongKind {
                expected: OptionKind::Flag,
            },
            OptionValue::Flag(false),
        ),
        (
            "status-keys",
            OptionValue::from("dvorak"),
            OptionValueRefusal::NotAChoice {
                choices: &["emacs", "vi"],
            },
            OptionValue::from("emacs"),
        ),
        (
            "history-limit",
            OptionValue::Number(-1),
            OptionValueRefusal::OutOfRange {
                range: 0..=i64::from(i32::MAX),
            },
            OptionValue::Number(1234),
        ),
    ];
    for (name, value, expected, unchanged) in cases {
        let result = session.set_typed_option(name, value).await;
        assert_eq!(
            session.typed_option(name).await.expect("read"),
            Some(unchanged),
            "{name} is as it was",
        );

        let error = result.expect_err("the table refuses the value");
        assert!(
            matches!(
                &error,
                Error::OptionValueRefused { option, reason }
                    if *option == name && *reason == expected
            ),
            "{name}: refused before dispatch, for the declared reason: {error:?}",
        );
        assert_eq!(error.kind(), ErrorKind::InvalidInput);
        assert!(!error.is_transient(), "the same value is refused again");
        let reported = format!("{error} {error:?}");
        assert!(
            !reported.contains("dvorak"),
            "the value stays out of the error: {reported}",
        );
    }

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

/// A refusal is decided without tmux: after the server is gone, a valid write
/// fails for want of it and an invalid one is still refused by the table.
#[tokio::test]
async fn a_typed_refusal_needs_no_server() {
    use libtmux::Error;

    let guard = TestServer::builder().start().await.expect("tmux starts");
    let server = guard.server().clone();
    guard.shutdown().await.expect("tmux fixture shuts down");

    let valid = server
        .set_typed_global_option("history-limit", 10)
        .await
        .expect_err("nothing is there to take the write");
    assert!(
        !matches!(valid, Error::OptionValueRefused { .. }),
        "a valid value reaches dispatch, and dispatch fails: {valid:?}",
    );

    let invalid = server
        .set_typed_global_option("history-limit", -1)
        .await
        .expect_err("the table refuses the value");
    assert!(
        matches!(invalid, Error::OptionValueRefused { .. }),
        "refused before any dispatch was attempted: {invalid:?}",
    );
}

/// A user option has no declared kind: a typed write stores any variant as
/// the text a read shows for it, and reads back as text.
#[tokio::test]
async fn a_typed_user_option_is_stored_as_text() {
    let guard = TestServer::builder().start().await.expect("tmux starts");
    let session = guard.server().new_session("user").await.expect("a session");

    let cases = [
        ("@flag", OptionValue::Flag(true), "on"),
        ("@number", OptionValue::Number(-3), "-3"),
        ("@text", OptionValue::from("dvorak"), "dvorak"),
    ];
    for (name, value, stored) in cases {
        session
            .set_typed_option(name, value)
            .await
            .unwrap_or_else(|error| panic!("{name} takes any variant: {error}"));
        let read = session.typed_option(name).await.expect("read");
        assert!(
            matches!(read, Some(OptionValue::Text(_))),
            "{name} reads back as text: {read:?}",
        );
        assert_eq!(
            String::from_utf8_lossy(&bytes(read)),
            stored,
            "{name} is stored as the text a read shows",
        );
    }

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