libtmux 0.1.0-alpha.8

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

use std::fmt;
use std::io;
use std::time::Duration;

use crate::CommandSummary;
use crate::version::{ReleaseVersion, TmuxVersion};

/// The category of an invalid [`crate::ServerBuilder`] configuration.
///
/// Rejected path and environment bytes are never retained by this value.
///
/// # Examples
///
/// ```
/// use libtmux::{Error, ServerConfigurationErrorKind};
///
/// // A socket name and a socket path are two ways to say the same thing, and
/// // tmux has no rule for which wins, so the builder refuses rather than picks.
/// let failure = libtmux::Server::builder()
///     .socket_name("named")
///     .socket_path("/tmp/libtmux-rs-dev/explicit")
///     .build()
///     .expect_err("two socket selectors");
///
/// assert!(matches!(
///     failure,
///     Error::InvalidServerConfiguration {
///         kind: ServerConfigurationErrorKind::ConflictingSocketSelectors,
///         ..
///     },
/// ));
///
/// // The rejected bytes are not carried in the error, so logging it cannot
/// // disclose a path.
/// assert!(!failure.to_string().contains("/tmp/"));
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ServerConfigurationErrorKind {
    /// A socket name and an explicit socket path were both configured.
    ConflictingSocketSelectors,
    /// A socket name was not one non-empty path component.
    InvalidSocketName,
    /// An explicit socket path was empty or contained a NUL byte.
    InvalidSocketPath,
    /// A config path was empty or contained a NUL byte.
    InvalidConfigPath,
    /// The requested color mode was neither 88 nor 256 colors.
    InvalidColorMode,
    /// The process working directory could not be captured.
    WorkingDirectoryUnavailable,
    /// A stable socket root could not be captured.
    SocketRootUnavailable,
    /// There is no `TMUX` variable, so this process is not inside tmux.
    ///
    /// Distinct from [`Self::MalformedTmuxVariable`], which means the
    /// variable is there and does not say what tmux says: the first is an
    /// ordinary state a caller may branch on, the second is a broken
    /// environment worth reporting.
    NotInsideTmux,

    /// The `TMUX` variable is present but is not tmux's triple.
    ///
    /// tmux writes `socket,pid,session`. An empty value, or one with no
    /// socket before the first comma, means something rewrote it.
    MalformedTmuxVariable,
}

/// Why a control-mode connection failed.
///
/// The distinction matters to a caller: a connection that never opened is a
/// setup problem, whereas one that closed mid-command may simply mean the
/// session it was attached to has ended.
///
/// # Examples
///
// Gate the doc attribute: a `#[cfg]` inside a doctest reads the doctest's own
// crate, which has no features, so the example would pass vacuously.
#[cfg_attr(
    feature = "control-mode",
    doc = r#"```
use libtmux::{ControlModeErrorKind, Error};

// `Closed` means the far side ended, often just the session going away. The
// rest mean the connection never worked. The variant is `#[non_exhaustive]`,
// so a caller matches it rather than building one.
fn session_ended(failure: &Error) -> bool {
    matches!(
        failure,
        Error::ControlMode { kind: ControlModeErrorKind::Closed, .. },
    )
}

let unrelated = libtmux::Server::builder()
    .socket_name("named")
    .socket_path("/tmp/libtmux-rs-dev/explicit")
    .build()
    .expect_err("two socket selectors");
assert!(!session_ended(&unrelated));
```"#
)]
#[cfg(feature = "control-mode")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ControlModeErrorKind {
    /// The tmux client could not be started, or its pipes failed.
    Transport,
    /// tmux started without giving the crate the pipes it asked for.
    ///
    /// Nothing a caller does causes this; it means the process could not be
    /// set up as requested.
    MissingPipes,
    /// The connection closed before the command was answered.
    Closed,
    /// The command contains an argument no control-mode line can carry.
    ///
    /// Control mode is a text protocol, so an argument that is not UTF-8
    /// cannot be sent over it even though the same command would run fine as
    /// a subprocess.
    UnrepresentableCommand,
}

/// What tmux says when it holds no session to resolve a target against.
pub(crate) const NO_CURRENT_TARGET: &str = "no current target";

/// What tmux says when a move has nowhere to go.
///
/// Reported as a command failure, but it is an ordinary state rather than a
/// fault: a session holding one window has no next window and never will.
/// Navigation reports it as absence so a caller does not have to tell the two
/// apart by reading text.
pub(crate) const NO_SUCH_NEIGHBOUR: [&str; 4] = [
    "no next window",
    "no previous window",
    "no last window",
    "no last pane",
];

/// Which way tmux would not accept an option.
///
/// # Examples
///
/// Each kind points at a different fix, so a caller can act instead of
/// re-reading tmux's wording:
///
/// ```
/// use libtmux::{Error, OptionErrorKind};
///
/// fn advise(error: &Error) -> &'static str {
///     match error {
///         Error::OptionRejected { kind, .. } => match kind {
///             OptionErrorKind::Unknown => "check the spelling",
///             OptionErrorKind::Ambiguous => "write more of the name",
///             OptionErrorKind::BadValue => "the option will not hold that",
///             _ => "tmux refused it",
///         },
///         _ => "not an option problem",
///     }
/// }
///
/// let refused = Error::OptionRejected {
///     kind: OptionErrorKind::Ambiguous,
///     detail: "status-l".to_owned(),
/// };
/// assert_eq!(advise(&refused), "write more of the name");
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum OptionErrorKind {
    /// No option goes by that name.
    Unknown,
    /// The name is a prefix of more than one option, so tmux will not guess.
    Ambiguous,
    /// The option exists and will not hold that value.
    BadValue,
}

/// Which way a tmux server was not there.
///
/// The four are one decision -- there is no server -- and four different
/// stories about how, which is the difference between a socket nobody has
/// started and a server that died under the command being run.
///
/// # Examples
///
/// ```
/// use libtmux::{Error, ServerGoneKind};
///
/// fn advise(error: &Error) -> &'static str {
///     match error {
///         Error::ServerGone { kind, .. } => match kind {
///             ServerGoneKind::NotRunning => "start one",
///             ServerGoneKind::Unreachable => "check the socket path",
///             ServerGoneKind::Lost | ServerGoneKind::Stopped => "it went away mid-command",
///             _ => "there is no server",
///         },
///         _ => "not a server problem",
///     }
/// }
///
/// let absent = Error::ServerGone {
///     command: "list-sessions",
///     kind: ServerGoneKind::NotRunning,
///     stderr: "no server running on /tmp/libtmux-rs-dev/absent".to_owned(),
/// };
/// assert_eq!(advise(&absent), "start one");
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ServerGoneKind {
    /// Nothing was listening on the socket.
    NotRunning,
    /// The socket was there and the connection to it failed.
    Unreachable,
    /// The connection was lost with the command in flight, which is a server
    /// that crashed or was killed.
    Lost,
    /// The server shut down with the command in flight.
    Stopped,
}

/// What tmux says when it has no client to act on.
pub(crate) const NO_CURRENT_CLIENT: &str = "no current client";

/// What a failure means for the caller.
///
/// [`Error`] carries the detail; this carries the decision. Each variant is a
/// different thing to do about it, which is why there are fewer of these than
/// there are error variants.
///
/// New kinds may be added, so match with a `_` arm.
///
/// # Examples
///
/// ```
/// use libtmux::ErrorKind;
///
/// fn retryable(kind: ErrorKind) -> bool {
///     matches!(kind, ErrorKind::Timeout | ErrorKind::Transport)
/// }
///
/// assert!(retryable(ErrorKind::Transport));
/// assert!(!retryable(ErrorKind::ObjectGone));
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The object is not on the server. Look it up again, or create it.
    ObjectGone,
    /// tmux ran the command and refused it. The arguments were wrong.
    Refused,
    /// No tmux server answered. Start one, or name the socket that has it.
    ServerGone,
    /// The command did not finish in time. Retry, or allow longer.
    Timeout,
    /// tmux could not be run at all: not installed, or not where the server
    /// was told to look. Nothing about the request will change this.
    Unreachable,
    /// The tmux that answered is older than this crate supports.
    UnsupportedVersion,
    /// The caller passed something that cannot be sent to tmux.
    InvalidInput,
    /// The process or connection carrying the command failed. Usually the
    /// environment rather than the request, so retrying may work.
    Transport,
    /// tmux answered in a shape the crate could not read. Worth reporting.
    Decode,
}

/// An invalid scope-specific tmux object ID.
///
/// The error records the expected sigil but never retains the rejected input.
///
/// # Examples
///
/// ```
/// use libtmux::SessionId;
///
/// // The sigil is the whole difference between the id types, so a mistake
/// // names the one that was expected.
/// let error = "@1".parse::<SessionId>().expect_err("@ denotes a window");
/// assert_eq!(error.expected_sigil(), '$');
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub struct IdParseError {
    expected_sigil: char,
}

impl IdParseError {
    pub(crate) const fn new(expected_sigil: char) -> Self {
        Self { expected_sigil }
    }

    /// Return the sigil required by the requested ID scope.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::SessionId;
    ///
    /// let error = "@1".parse::<SessionId>().expect_err("@ denotes a window");
    /// assert_eq!(error.expected_sigil(), '$');
    /// ```
    #[must_use]
    pub const fn expected_sigil(self) -> char {
        self.expected_sigil
    }
}

impl fmt::Display for IdParseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "invalid tmux ID: expected {} followed by an integer from 0 through {}",
            self.expected_sigil,
            u32::MAX,
        )
    }
}

impl std::error::Error for IdParseError {}

/// An error returned by libtmux.
///
/// Request-bearing variants expose a Core-scoped dispatch-request identity.
/// The Core allocates it before validation, so an error may carry an identity
/// even when no process was spawned. Clones of one [`crate::Server`] share the
/// allocating Core; independently constructed servers do not share its scope.
/// The identity is not globally unique, a process ID, an internal attempt ID,
/// or a control-mode protocol-block ID.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// use libtmux::ErrorKind;
///
/// let guard = libtmux::test::TestServer::new().await?;
/// let doomed = guard.server().new_session("doomed").await?;
/// let mut stale = doomed.clone();
/// guard.server().new_session("survivor").await?;
/// doomed.kill().await?;
///
/// // A handle outliving its object is the normal way this fails, so
/// // `is_object_gone` is the branch most callers write.
/// let failure = stale.rename("renamed").await.expect_err("the session is gone");
/// assert!(failure.is_object_gone());
/// assert_eq!(failure.kind(), ErrorKind::ObjectGone);
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// A server builder value was invalid.
    #[non_exhaustive]
    #[error("invalid server configuration ({kind:?})")]
    InvalidServerConfiguration {
        /// The path-free failure category.
        kind: ServerConfigurationErrorKind,
    },

    /// The output from `tmux -V` did not match a supported shape.
    #[error("invalid tmux version output")]
    InvalidVersionOutput {
        /// The number of bytes returned by tmux.
        output_len: usize,
    },

    /// The detected tmux version does not meet the supported floor.
    #[error("tmux {found} is below the minimum supported version {minimum}")]
    UnsupportedTmuxVersion {
        /// The detected tmux version.
        found: TmuxVersion,
        /// The minimum supported release.
        minimum: ReleaseVersion,
    },

    /// tmux would not accept an option name or value.
    ///
    /// Classified because the three answers call for different fixes: an
    /// unknown name is a typo, an ambiguous one needs more of the name, and a
    /// rejected value needs a different value. A caller reading stderr would
    /// have to know that tmux says "bad value" for a flag and "value is
    /// invalid" for a number.
    #[error("tmux rejected the option: {detail}")]
    OptionRejected {
        /// Which of the three answers tmux gave.
        kind: OptionErrorKind,
        /// The name tmux could not resolve, or the value it would not take.
        detail: String,
    },

    /// tmux answered a format query with a value this crate cannot read.
    ///
    /// Reports a disagreement between the crate and the tmux that answered,
    /// not a caller mistake: the crate asked for an ID and tmux returned
    /// something that is not one. Worth reporting.
    #[non_exhaustive]
    #[error("tmux answered {format} with a value that is not an id: {detail}")]
    UnreadableFormatValue {
        /// The format the crate asked for.
        format: &'static str,
        /// What was wrong with the answer. Never retains the value.
        detail: IdParseError,
    },

    /// A different tmux daemon now holds this endpoint.
    ///
    /// The socket path is unchanged, so nothing about the address says the
    /// server was replaced. Ids are reissued from the start by the
    /// replacement, so a handle held across the restart names an object that
    /// exists and is not the one it meant.
    #[error("the tmux server was replaced: expected {expected}, found {found}")]
    ServerGenerationChanged {
        /// The daemon the caller captured.
        expected: crate::ServerGeneration,
        /// The daemon answering now.
        found: crate::ServerGeneration,
    },

    /// tmux produced more output than the dispatch was allowed to read.
    ///
    /// Not a truncation. A shortened tmux listing decodes cleanly and says
    /// something false -- fewer panes than exist -- so the dispatch fails
    /// instead, and the caller either asks tmux for less or raises
    /// [`crate::OutputLimits`].
    #[non_exhaustive]
    #[error("{command} produced more than {limit} bytes on {stream} (request {request_id})")]
    OutputLimitExceeded {
        /// Core-scoped dispatch-request identity.
        request_id: u64,
        /// Sanitized command context.
        command: CommandSummary,
        /// Which stream ran past its budget.
        stream: &'static str,
        /// The budget in bytes.
        limit: usize,
    },

    /// The server is already running as much work as it admits.
    ///
    /// The dispatch never started, so retrying it is safe: nothing was sent
    /// to tmux and no state changed. Distinct from
    /// [`Self::Timeout`](Self::Timeout), which means the work may have run.
    #[non_exhaustive]
    #[error(
        "{command} was not admitted: {in_flight} dispatches already running (request {request_id})"
    )]
    Overloaded {
        /// Core-scoped dispatch-request identity.
        request_id: u64,
        /// Sanitized command context.
        command: CommandSummary,
        /// How many dispatches the server admits at once.
        in_flight: usize,
    },

    /// A control-mode frame grew past what the connection admits.
    ///
    /// Control mode reads from a process that keeps running, so the framing is
    /// the only thing bounding memory. The connection cannot be resynchronized
    /// after this -- the parser is mid-frame and does not know where the next
    /// one begins -- so it is finished, and a caller who wants to continue
    /// attaches again.
    #[cfg(feature = "control-mode")]
    #[non_exhaustive]
    #[error("a control-mode {frame} grew past its {limit} byte budget")]
    ControlModeFrameTooLarge {
        /// Which frame: a line, or a command's response block.
        frame: &'static str,
        /// The budget in bytes.
        limit: usize,
    },

    /// A session of this name already exists.
    ///
    /// Classified rather than left as a generic refusal because it is the one
    /// creation failure a caller routinely expects and handles: it means "pick
    /// another name", not "tmux is broken". Checking with `has-session` first
    /// would race, since another process can take the name in between.
    #[error("a session named {name} already exists")]
    SessionExists {
        /// The name that was already taken.
        name: String,
    },

    /// The running tmux is too old for a capability the caller asked for.
    ///
    /// Distinct from [`Error::UnsupportedTmuxVersion`], which is about the
    /// crate's own floor: this one says the crate works here and the *feature*
    /// does not. tmux itself would usually accept the flag and quietly ignore
    /// it, which turns "your tmux is too old" into "the command did nothing",
    /// so it is reported rather than passed through.
    #[error("{capability} needs tmux {needs} or newer, and this is {found}")]
    UnsupportedCapability {
        /// What the caller asked for, named as a caller would say it.
        capability: &'static str,
        /// The first release that has it.
        needs: ReleaseVersion,
        /// The release actually running.
        found: TmuxVersion,
    },

    /// tmux has this capability and the running release gets it wrong.
    ///
    /// Distinct from [`Self::UnsupportedCapability`], which means the release
    /// predates the feature and the answer is to upgrade. Here releases on
    /// both sides work, so neither "upgrade" nor "the floor is too low" is
    /// the fix: the caller has to leave a specific range.
    ///
    /// Raised rather than returning what the release reports, because what it
    /// reports is wrong in a way the caller cannot see.
    #[error(
        "tmux {found} does not implement {capability} correctly; \
         releases from {broken_in} up to but not including {fixed_in} are affected"
    )]
    CapabilityDefective {
        /// What the caller asked for, named as a caller would say it.
        capability: &'static str,
        /// The release actually running.
        found: TmuxVersion,
        /// The first release that gets it wrong.
        broken_in: ReleaseVersion,
        /// The first release that gets it right again.
        fixed_in: ReleaseVersion,
    },

    /// The version probe process returned a non-zero status.
    #[non_exhaustive]
    #[error(
        "tmux version probe request {request_id} ({command}) failed with exit code {exit_code:?} and signal {signal:?}"
    )]
    VersionProbeFailed {
        /// The Core-scoped dispatch-request identity.
        request_id: u64,
        /// The sanitized logical version-probe command.
        command: CommandSummary,
        /// The process exit code, when it exited normally.
        exit_code: Option<i32>,
        /// The terminating signal, when it did not exit normally.
        signal: Option<i32>,
    },

    /// A command or executable contained a byte that cannot be passed to a process.
    #[non_exhaustive]
    #[error("invalid {input} for tmux request {request_id}")]
    InvalidCommandInput {
        /// The Core-scoped dispatch-request identity.
        request_id: u64,
        /// The validated input category.
        input: &'static str,
    },

    /// The configured tmux executable was not found.
    #[non_exhaustive]
    #[error("tmux executable was not found for request {request_id} ({command})")]
    ExecutableNotFound {
        /// The Core-scoped dispatch-request identity.
        request_id: u64,
        /// The sanitized logical command.
        command: CommandSummary,
        /// The operating-system spawn error.
        #[source]
        source: io::Error,
    },

    /// The tmux process could not be started.
    #[non_exhaustive]
    #[error("failed to start tmux request {request_id} ({command})")]
    Spawn {
        /// The Core-scoped dispatch-request identity.
        request_id: u64,
        /// The sanitized logical command.
        command: CommandSummary,
        /// The operating-system spawn error.
        #[source]
        source: io::Error,
    },

    /// A captured output stream could not be drained.
    #[non_exhaustive]
    #[error("failed to read {stream} for tmux request {request_id} ({command})")]
    ReadOutput {
        /// The Core-scoped dispatch-request identity.
        request_id: u64,
        /// The sanitized logical command.
        command: CommandSummary,
        /// The output stream that failed.
        stream: &'static str,
        /// The source error category without its potentially unsafe message.
        kind: io::ErrorKind,
    },

    /// The direct tmux child could not be awaited.
    #[non_exhaustive]
    #[error("failed to wait for tmux request {request_id} ({command})")]
    WaitChild {
        /// The Core-scoped dispatch-request identity.
        request_id: u64,
        /// The sanitized logical command.
        command: CommandSummary,
        /// The operating-system wait error.
        #[source]
        source: io::Error,
    },

    /// A tmux request exceeded its configured deadline.
    #[non_exhaustive]
    #[error("tmux request {request_id} ({command}) timed out after {timeout:?}")]
    Timeout {
        /// The Core-scoped dispatch-request identity.
        request_id: u64,
        /// The sanitized logical command.
        command: CommandSummary,
        /// The configured deadline.
        timeout: Duration,
    },

    /// The executor has stopped accepting requests.
    #[non_exhaustive]
    #[error("tmux executor is shut down for request {request_id} ({command})")]
    ExecutorShutdown {
        /// The Core-scoped dispatch-request identity.
        request_id: u64,
        /// The sanitized logical command.
        command: CommandSummary,
    },

    /// A Core-scoped dispatch-request identity is already active in this
    /// executor.
    #[non_exhaustive]
    #[error("tmux request {request_id} is already active ({command})")]
    DuplicateRequest {
        /// The duplicate Core-scoped dispatch-request identity.
        request_id: u64,
        /// The sanitized logical command.
        command: CommandSummary,
    },

    /// The independent supervisor ended unexpectedly after cleaning up its child.
    #[non_exhaustive]
    #[error("tmux supervisor was lost for request {request_id} ({command})")]
    SupervisorLost {
        /// The Core-scoped dispatch-request identity.
        request_id: u64,
        /// The sanitized logical command.
        command: CommandSummary,
    },

    /// A refresh could not find the object it was asked to update.
    ///
    /// This is distinct from a connection failure: tmux answered, and the
    /// object was not among the results. It has been closed or killed since
    /// the handle was created.
    #[non_exhaustive]
    #[error("tmux no longer has {kind} {id}")]
    ObjectGone {
        /// The kind of object that disappeared.
        kind: ObjectKind,
        /// The tmux identity that is no longer present.
        id: String,
    },

    /// A control-mode connection failed.
    #[cfg(feature = "control-mode")]
    #[non_exhaustive]
    #[error("control mode connection failed ({kind:?})")]
    ControlMode {
        /// Which stage of the connection failed.
        kind: ControlModeErrorKind,
        /// The operating-system error, when there was one.
        #[source]
        source: Option<io::Error>,
    },

    /// A blocking runtime could not be created.
    #[non_exhaustive]
    #[error("could not build a runtime")]
    RuntimeUnavailable {
        /// The operating-system error.
        #[source]
        source: io::Error,
    },

    /// A blocking runtime was driven from inside another runtime.
    ///
    /// A runtime cannot be driven from within one, so [`crate::blocking::Runtime::run`]
    /// panics here. [`crate::blocking::Runtime::try_run`] returns this instead,
    /// for callers who would rather handle it: await the future directly.
    #[error("a blocking runtime cannot be driven from inside an async context")]
    RuntimeNested,

    /// The tmux server the command needed was not there.
    ///
    /// tmux exits 1 for this and for a command it refused, and separates them
    /// only in stderr, so this is read from the message rather than the
    /// status. [`ServerGoneKind`] says which way it was missing.
    #[error("tmux found no server for {command}: {stderr}")]
    ServerGone {
        /// The tmux command that found no server.
        command: &'static str,
        /// Which way the server was not there.
        kind: ServerGoneKind,
        /// What tmux wrote to stderr.
        stderr: String,
    },

    /// tmux rejected a command that the crate requires to succeed.
    ///
    /// The raw [`crate::Server::cmd`] boundary keeps a nonzero status as data.
    /// This variant is for operations whose whole purpose is the effect, so a
    /// refusal is a failure rather than a result.
    #[non_exhaustive]
    #[error("tmux rejected {command} (exit {exit_code:?}): {stderr}")]
    CommandFailed {
        /// The tmux command that was rejected.
        command: &'static str,
        /// The process exit code, when it exited normally.
        exit_code: Option<i32>,
        /// The message tmux printed, which explains the refusal.
        stderr: String,
    },

    /// tmux listing output could not be decoded into typed snapshots.
    ///
    /// This reports a disagreement between the crate and the tmux that
    /// answered, not an ordinary tmux failure. A command that merely reports a
    /// nonzero status stays raw data at the [`crate::Server::cmd`] boundary.
    #[non_exhaustive]
    #[error("failed to decode {list_command} output: {detail}")]
    DecodeListing {
        /// The tmux list command whose output failed to decode.
        list_command: &'static str,
        /// Payload-free decoding metadata.
        detail: ListingDecodeError,
    },
}

/// The kind of tmux object a failure refers to.
///
/// # Examples
///
/// ```
/// use libtmux::ObjectKind;
///
/// // Carried by `Error::ObjectGone` so a caller can say what disappeared
/// // without parsing the message.
/// assert_eq!(ObjectKind::Pane.to_string(), "pane");
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ObjectKind {
    /// A tmux session.
    Session,
    /// A tmux window.
    Window,
    /// A tmux pane.
    Pane,
    /// A client attached to the server.
    Client,
}

impl fmt::Display for ObjectKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Session => "session",
            Self::Window => "window",
            Self::Pane => "pane",
            Self::Client => "client",
        })
    }
}

/// Payload-free metadata describing why tmux output could not be decoded.
///
/// This never retains row bytes, snapshot text, or decoded values, so it is
/// safe to log wherever the rest of [`Error`] is.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use libtmux::Error;
///
/// // Reached through the one variant that carries it. Both accessors are
/// // optional because tmux does not always give enough to locate the row.
/// fn locate(failure: &Error) -> Option<(&'static str, Option<usize>)> {
///     match failure {
///         Error::DecodeListing { list_command, detail, .. } => {
///             Some((*list_command, detail.row()))
///         }
///         _ => None,
///     }
/// }
///
/// // The payload is metadata only: no tmux bytes are retained, so logging it
/// // cannot leak a pane's contents.
/// let other = libtmux::Server::builder()
///     .socket_name("named")
///     .socket_path("/tmp/libtmux-rs-dev/explicit")
///     .build()
///     .expect_err("two socket selectors");
/// assert_eq!(locate(&other), None);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ListingDecodeError {
    inner: crate::formats::FormatCodecError,
}

impl ListingDecodeError {
    pub(crate) const fn new(inner: crate::formats::FormatCodecError) -> Self {
        Self { inner }
    }

    /// Return the zero-based row that failed, when the failure reached a row.
    ///
    /// Plan-construction failures happen before any row is read and report
    /// `None`.
    #[must_use]
    pub const fn row(&self) -> Option<usize> {
        self.inner.row()
    }

    /// Return the stable tmux format name that failed, when one is known.
    #[must_use]
    pub const fn field_name(&self) -> Option<&'static str> {
        self.inner.field_name()
    }
}

impl fmt::Display for ListingDecodeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.fmt(formatter)
    }
}

impl std::error::Error for ListingDecodeError {}

impl Error {
    /// Classify a refused tmux command, recognizing a target that has gone.
    ///
    /// tmux reports a missing target as `can't find <kind>: <target>` and
    /// exits 1, the same status it uses for an argument it did not like, so
    /// the message is the only thing that separates them. It is not
    /// localized -- tmux has no message catalogue -- and the wording has been
    /// stable across every supported release.
    ///
    /// Anything that does not match stays a refusal, so a future rewording
    /// costs the distinction rather than correctness.
    /// `target` is the request's own `-t`, when it had one. tmux reports a
    /// server holding no sessions as `no current target` even for a target it
    /// was given, so the request is what recovers the name.
    pub(crate) fn refused(
        command: &'static str,
        exit_code: Option<i32>,
        stderr: String,
        target: Option<&std::ffi::OsStr>,
    ) -> Self {
        // The wording is tmux's own and is identical on every supported
        // release. None of these say the request was wrong, so they are read
        // before anything that does.
        const GONE: [(&str, ServerGoneKind); 4] = [
            ("no server running on", ServerGoneKind::NotRunning),
            ("error connecting to", ServerGoneKind::Unreachable),
            // Before the shorter one, which it starts with and does not mean.
            ("server exited unexpectedly", ServerGoneKind::Lost),
            ("server exited", ServerGoneKind::Stopped),
        ];

        const MISSING: [(&str, ObjectKind); 4] = [
            ("can't find session:", ObjectKind::Session),
            ("can't find window:", ObjectKind::Window),
            ("can't find pane:", ObjectKind::Pane),
            ("can't find client:", ObjectKind::Client),
        ];

        // tmux spells "no such option name" two ways. `set-option` and
        // `show-options` resolve the name with `options_match` first, which
        // says "invalid option"; the "unknown option" in `options_scope_from_name`
        // sits behind that call and so is unreachable from the CLI on every
        // supported release. Both mean the same thing, so both map to the same
        // kind rather than leaving a hole if tmux ever reorders the two.
        const OPTION: [(&str, OptionErrorKind); 5] = [
            ("invalid option:", OptionErrorKind::Unknown),
            ("unknown option:", OptionErrorKind::Unknown),
            ("ambiguous option:", OptionErrorKind::Ambiguous),
            ("bad value:", OptionErrorKind::BadValue),
            ("value is invalid:", OptionErrorKind::BadValue),
        ];

        for (prefix, kind) in GONE {
            if stderr.trim_end().starts_with(prefix) {
                return Self::ServerGone {
                    command,
                    kind,
                    stderr,
                };
            }
        }

        for (prefix, kind) in OPTION {
            if let Some(detail) = stderr.trim_end().strip_prefix(prefix) {
                return Self::OptionRejected {
                    kind,
                    detail: detail.trim().to_owned(),
                };
            }
        }

        if let Some(name) = stderr.trim_end().strip_prefix("duplicate session:") {
            return Self::SessionExists {
                name: name.trim().to_owned(),
            };
        }

        if let Some(target) = target.filter(|_| stderr.trim_end() == NO_CURRENT_TARGET) {
            return Self::object_gone(&target.to_string_lossy());
        }

        for (prefix, kind) in MISSING {
            if let Some(id) = stderr.trim_end().strip_prefix(prefix) {
                return Self::ObjectGone {
                    kind,
                    id: id.trim().to_owned(),
                };
            }
        }

        Self::CommandFailed {
            command,
            exit_code,
            stderr,
        }
    }

    /// Report a tmux target that could not be resolved.
    ///
    /// The kind comes from the sigil, which is how tmux names its objects.
    /// A target that is a name rather than an ID is reported as a session,
    /// because a name is what `-t` accepts for one.
    fn object_gone(target: &str) -> Self {
        Self::ObjectGone {
            kind: match target.as_bytes().first() {
                Some(b'@') => ObjectKind::Window,
                Some(b'%') => ObjectKind::Pane,
                _ => ObjectKind::Session,
            },
            id: target.to_owned(),
        }
    }

    /// Return what this failure means for the caller.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::ErrorKind;
    ///
    /// // The shape this exists for: use it if it is there, make it if not.
    /// let session = match server.session("work").await? {
    ///     Some(session) => session,
    ///     None => server.new_session("work").await?,
    /// };
    ///
    /// // And when an operation races something else removing it. The handle
    /// // is cloned because killing consumes one, which is how the crate
    /// // stops you from using a window you just destroyed.
    /// let window = session.new_window("doomed").await?;
    /// let mut stale = window.clone();
    /// window.kill().await?;
    ///
    /// let error = stale.rename("gone").await.expect_err("the window was killed");
    /// assert_eq!(error.kind(), ErrorKind::ObjectGone);
    /// assert!(error.is_object_gone());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn kind(&self) -> ErrorKind {
        match self {
            // A replaced daemon reissues ids from the start, so every handle
            // captured from the previous one names something that is not
            // there. That is the same decision as a missing object, and the
            // same branch a caller already writes for one.
            Self::ObjectGone { .. } | Self::ServerGenerationChanged { .. } => ErrorKind::ObjectGone,
            Self::ServerGone { .. } => ErrorKind::ServerGone,
            Self::CommandFailed { .. }
            | Self::OutputLimitExceeded { .. }
            | Self::Overloaded { .. }
            | Self::SessionExists { .. }
            | Self::OptionRejected { .. } => ErrorKind::Refused,
            Self::Timeout { .. } => ErrorKind::Timeout,
            Self::ExecutableNotFound { .. }
            | Self::InvalidServerConfiguration { .. }
            | Self::RuntimeUnavailable { .. } => ErrorKind::Unreachable,
            // The call is wrong, not the environment: the same future awaited
            // directly would work.
            Self::RuntimeNested => ErrorKind::InvalidInput,
            Self::UnsupportedTmuxVersion { .. }
            | Self::UnsupportedCapability { .. }
            | Self::CapabilityDefective { .. } => ErrorKind::UnsupportedVersion,
            Self::InvalidCommandInput { .. } => ErrorKind::InvalidInput,
            Self::Spawn { .. }
            | Self::ReadOutput { .. }
            | Self::WaitChild { .. }
            | Self::VersionProbeFailed { .. }
            | Self::ExecutorShutdown { .. }
            | Self::DuplicateRequest { .. }
            | Self::SupervisorLost { .. } => ErrorKind::Transport,
            Self::InvalidVersionOutput { .. }
            | Self::DecodeListing { .. }
            | Self::UnreadableFormatValue { .. } => ErrorKind::Decode,
            #[cfg(feature = "control-mode")]
            Self::ControlModeFrameTooLarge { .. } => ErrorKind::Decode,
            #[cfg(feature = "control-mode")]
            Self::ControlMode { kind, .. } => match kind {
                ControlModeErrorKind::UnrepresentableCommand => ErrorKind::InvalidInput,
                ControlModeErrorKind::Transport
                | ControlModeErrorKind::MissingPipes
                | ControlModeErrorKind::Closed => ErrorKind::Transport,
            },
        }
    }

    /// Report whether tmux no longer has the object the call named.
    ///
    /// The most common branch a caller writes, and the one that is easy to
    /// get wrong: an object disappearing is an ordinary race, not a failure
    /// of the request.
    #[must_use]
    pub fn is_object_gone(&self) -> bool {
        self.kind() == ErrorKind::ObjectGone
    }

    /// Report whether making the same call again could succeed.
    ///
    /// True for a timeout and for a transport failure, which are usually the
    /// machine rather than the request. False for anything tmux answered,
    /// which will be answered the same way again.
    #[must_use]
    pub fn is_transient(&self) -> bool {
        matches!(self.kind(), ErrorKind::Timeout | ErrorKind::Transport)
    }

    #[cfg(feature = "control-mode")]
    pub(crate) const fn control_mode(source: io::Error) -> Self {
        Self::ControlMode {
            kind: ControlModeErrorKind::Transport,
            source: Some(source),
        }
    }

    /// tmux started but did not provide the pipes to talk over.
    #[cfg(feature = "control-mode")]
    pub(crate) const fn control_mode_pipes() -> Self {
        Self::ControlMode {
            kind: ControlModeErrorKind::MissingPipes,
            source: None,
        }
    }

    /// A command carries an argument no control-mode line can express.
    #[cfg(feature = "control-mode")]
    pub(crate) const fn control_mode_unrepresentable() -> Self {
        Self::ControlMode {
            kind: ControlModeErrorKind::UnrepresentableCommand,
            source: None,
        }
    }

    /// A protocol frame ran past its budget.
    ///
    /// Not recoverable in place: the parser is mid-frame and cannot know where
    /// the next one starts, so the connection is finished and the caller
    /// reopens.
    #[cfg(feature = "control-mode")]
    pub(crate) const fn control_mode_frame_too_large(frame: &'static str, limit: usize) -> Self {
        Self::ControlModeFrameTooLarge { frame, limit }
    }

    /// The connection closed before the command was answered.
    #[cfg(feature = "control-mode")]
    pub(crate) const fn control_mode_closed() -> Self {
        Self::ControlMode {
            kind: ControlModeErrorKind::Closed,
            source: None,
        }
    }

    #[cfg(feature = "blocking")]
    pub(crate) const fn runtime_unavailable(source: io::Error) -> Self {
        Self::RuntimeUnavailable { source }
    }

    pub(crate) const fn invalid_server_configuration(kind: ServerConfigurationErrorKind) -> Self {
        Self::InvalidServerConfiguration { kind }
    }

    pub(crate) fn version_probe_failed(
        request_id: u64,
        command: CommandSummary,
        exit_code: Option<i32>,
        signal: Option<i32>,
    ) -> Self {
        Self::VersionProbeFailed {
            request_id,
            command,
            exit_code,
            signal,
        }
    }

    pub(crate) fn from_invalid_version_output(output_len: usize) -> Self {
        Self::InvalidVersionOutput { output_len }
    }

    pub(crate) fn unsupported_tmux_version(found: TmuxVersion, minimum: ReleaseVersion) -> Self {
        Self::UnsupportedTmuxVersion { found, minimum }
    }

    pub(crate) fn invalid_command_input(request_id: u64, input: &'static str) -> Self {
        Self::InvalidCommandInput { request_id, input }
    }

    pub(crate) fn spawn(
        request_id: u64,
        command: CommandSummary,
        source: io::Error,
        executable_not_found: bool,
    ) -> Self {
        if executable_not_found {
            Self::ExecutableNotFound {
                request_id,
                command,
                source,
            }
        } else {
            Self::Spawn {
                request_id,
                command,
                source,
            }
        }
    }

    pub(crate) fn read_output(
        request_id: u64,
        command: CommandSummary,
        stream: &'static str,
        kind: io::ErrorKind,
    ) -> Self {
        Self::ReadOutput {
            request_id,
            command,
            stream,
            kind,
        }
    }

    pub(crate) fn wait_child(request_id: u64, command: CommandSummary, source: io::Error) -> Self {
        Self::WaitChild {
            request_id,
            command,
            source,
        }
    }

    pub(crate) fn timeout(request_id: u64, command: CommandSummary, timeout: Duration) -> Self {
        Self::Timeout {
            request_id,
            command,
            timeout,
        }
    }

    pub(crate) fn executor_shutdown(request_id: u64, command: CommandSummary) -> Self {
        Self::ExecutorShutdown {
            request_id,
            command,
        }
    }

    pub(crate) fn duplicate_request(request_id: u64, command: CommandSummary) -> Self {
        Self::DuplicateRequest {
            request_id,
            command,
        }
    }

    pub(crate) fn supervisor_lost(request_id: u64, command: CommandSummary) -> Self {
        Self::SupervisorLost {
            request_id,
            command,
        }
    }

    /// Return the length of the invalid `tmux -V` output, when present.
    ///
    /// The error never retains the process output itself.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::TmuxVersion;
    ///
    /// let output = b"invalid\n";
    /// let error = TmuxVersion::parse_output(output).expect_err("output is invalid");
    /// assert_eq!(error.invalid_version_output_len(), Some(output.len()));
    /// ```
    #[must_use]
    pub fn invalid_version_output_len(&self) -> Option<usize> {
        match self {
            Self::InvalidVersionOutput { output_len } => Some(*output_len),
            _ => None,
        }
    }

    /// Return the detected version for a minimum-version error.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::TmuxVersion;
    ///
    /// let version = TmuxVersion::parse_output(b"tmux 3.2\n")?;
    /// let error = version.ensure_supported().expect_err("3.2 is unsupported");
    /// assert_eq!(error.found_version(), Some(&version));
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    #[must_use]
    pub fn found_version(&self) -> Option<&TmuxVersion> {
        match self {
            Self::UnsupportedTmuxVersion { found, .. }
            | Self::UnsupportedCapability { found, .. } => Some(found),
            _ => None,
        }
    }

    /// Return the required release for a minimum-version error.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::TmuxVersion;
    ///
    /// let version = TmuxVersion::parse_output(b"tmux 3.2\n")?;
    /// let error = version.ensure_supported().expect_err("3.2 is unsupported");
    /// assert_eq!(error.minimum_version(), Some(&TmuxVersion::MIN_SUPPORTED));
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    #[must_use]
    pub fn minimum_version(&self) -> Option<&ReleaseVersion> {
        match self {
            Self::UnsupportedTmuxVersion { minimum, .. } => Some(minimum),
            Self::UnsupportedCapability { needs, .. } => Some(needs),
            _ => None,
        }
    }
}

impl fmt::Debug for Error {
    #[allow(
        clippy::too_many_lines,
        reason = "exhaustive safe formatting keeps every public error variant byte-free"
    )]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RuntimeNested => formatter.debug_struct("RuntimeNested").finish(),
            Self::InvalidServerConfiguration { kind } => formatter
                .debug_struct("InvalidServerConfiguration")
                .field("kind", kind)
                .finish(),
            Self::UnsupportedCapability {
                capability,
                needs,
                found,
            } => formatter
                .debug_struct("UnsupportedCapability")
                .field("capability", capability)
                .field("needs", needs)
                .field("found", found)
                .finish(),
            Self::CapabilityDefective {
                capability,
                found,
                broken_in,
                fixed_in,
            } => formatter
                .debug_struct("CapabilityDefective")
                .field("capability", capability)
                .field("found", found)
                .field("broken_in", broken_in)
                .field("fixed_in", fixed_in)
                .finish(),
            Self::UnreadableFormatValue { format, detail } => formatter
                .debug_struct("UnreadableFormatValue")
                .field("format", format)
                .field("detail", detail)
                .finish(),
            #[cfg(feature = "control-mode")]
            Self::ControlModeFrameTooLarge { frame, limit } => formatter
                .debug_struct("ControlModeFrameTooLarge")
                .field("frame", frame)
                .field("limit", limit)
                .finish(),
            Self::OutputLimitExceeded {
                request_id,
                command,
                stream,
                limit,
            } => formatter
                .debug_struct("OutputLimitExceeded")
                .field("request_id", request_id)
                .field("command", command)
                .field("stream", stream)
                .field("limit", limit)
                .finish(),
            Self::Overloaded {
                request_id,
                command,
                in_flight,
            } => formatter
                .debug_struct("Overloaded")
                .field("request_id", request_id)
                .field("command", command)
                .field("in_flight", in_flight)
                .finish(),
            Self::ServerGenerationChanged { expected, found } => formatter
                .debug_struct("ServerGenerationChanged")
                .field("expected", expected)
                .field("found", found)
                .finish(),
            Self::OptionRejected { kind, detail } => formatter
                .debug_struct("OptionRejected")
                .field("kind", kind)
                .field("detail", detail)
                .finish(),
            Self::SessionExists { name } => formatter
                .debug_struct("SessionExists")
                .field("name", name)
                .finish(),
            Self::InvalidVersionOutput { output_len } => formatter
                .debug_struct("InvalidVersionOutput")
                .field("output_len", output_len)
                .finish(),
            Self::UnsupportedTmuxVersion { found, minimum } => formatter
                .debug_struct("UnsupportedTmuxVersion")
                .field("found", found)
                .field("minimum", minimum)
                .finish(),
            Self::VersionProbeFailed {
                request_id,
                command,
                exit_code,
                signal,
            } => formatter
                .debug_struct("VersionProbeFailed")
                .field("request_id", request_id)
                .field("command", command)
                .field("exit_code", exit_code)
                .field("signal", signal)
                .finish_non_exhaustive(),
            Self::InvalidCommandInput { request_id, input } => formatter
                .debug_struct("InvalidCommandInput")
                .field("request_id", request_id)
                .field("input", input)
                .finish(),
            Self::ExecutableNotFound {
                request_id,
                command,
                source,
            } => formatter
                .debug_struct("ExecutableNotFound")
                .field("request_id", request_id)
                .field("command", command)
                .field("source", source)
                .finish(),
            Self::Spawn {
                request_id,
                command,
                source,
            } => formatter
                .debug_struct("Spawn")
                .field("request_id", request_id)
                .field("command", command)
                .field("source", source)
                .finish(),
            Self::ReadOutput {
                request_id,
                command,
                stream,
                kind,
            } => formatter
                .debug_struct("ReadOutput")
                .field("request_id", request_id)
                .field("command", command)
                .field("stream", stream)
                .field("kind", kind)
                .finish(),
            Self::WaitChild {
                request_id,
                command,
                source,
            } => formatter
                .debug_struct("WaitChild")
                .field("request_id", request_id)
                .field("command", command)
                .field("source", source)
                .finish(),
            Self::Timeout {
                request_id,
                command,
                timeout,
            } => formatter
                .debug_struct("Timeout")
                .field("request_id", request_id)
                .field("command", command)
                .field("timeout", timeout)
                .finish(),
            Self::ExecutorShutdown {
                request_id,
                command,
            } => formatter
                .debug_struct("ExecutorShutdown")
                .field("request_id", request_id)
                .field("command", command)
                .finish(),
            Self::DuplicateRequest {
                request_id,
                command,
            } => formatter
                .debug_struct("DuplicateRequest")
                .field("request_id", request_id)
                .field("command", command)
                .finish(),
            Self::SupervisorLost {
                request_id,
                command,
            } => formatter
                .debug_struct("SupervisorLost")
                .field("request_id", request_id)
                .field("command", command)
                .finish(),
            #[cfg(feature = "control-mode")]
            Self::ControlMode { kind, source } => formatter
                .debug_struct("ControlMode")
                .field("kind", kind)
                .field("kind", &source.as_ref().map(io::Error::kind))
                .finish(),
            Self::RuntimeUnavailable { source } => formatter
                .debug_struct("RuntimeUnavailable")
                .field("kind", &source.kind())
                .finish(),
            Self::CommandFailed {
                command,
                exit_code,
                stderr,
            } => formatter
                .debug_struct("CommandFailed")
                .field("command", command)
                .field("exit_code", exit_code)
                .field("stderr", stderr)
                .finish(),
            Self::ObjectGone { kind, id } => formatter
                .debug_struct("ObjectGone")
                .field("kind", kind)
                .field("id", id)
                .finish(),
            Self::ServerGone {
                command,
                kind,
                stderr,
            } => formatter
                .debug_struct("ServerGone")
                .field("command", command)
                .field("kind", kind)
                .field("stderr", stderr)
                .finish(),
            Self::DecodeListing {
                list_command,
                detail,
            } => formatter
                .debug_struct("DecodeListing")
                .field("list_command", list_command)
                .field("detail", detail)
                .finish(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Error, ErrorKind, ServerGoneKind};

    /// The three server-gone wordings a live fixture cannot produce on demand.
    ///
    /// Only "no server running" is reachable from a test, because the other
    /// three need the server to die between the client connecting and the
    /// command finishing. They are read from tmux's `client.c`, so they are
    /// asserted against the classifier rather than against tmux.
    #[test]
    fn a_server_that_is_not_there_is_not_a_refusal() {
        for (stderr, expected) in [
            (
                "no server running on /tmp/libtmux-rs-dev/absent",
                ServerGoneKind::NotRunning,
            ),
            (
                "error connecting to /tmp/libtmux-rs-dev/absent (Connection refused)",
                ServerGoneKind::Unreachable,
            ),
            ("server exited unexpectedly", ServerGoneKind::Lost),
            ("server exited", ServerGoneKind::Stopped),
        ] {
            let error = Error::refused("list-sessions", Some(1), stderr.to_owned(), None);
            assert_eq!(error.kind(), ErrorKind::ServerGone, "{stderr}");
            assert!(
                matches!(&error, Error::ServerGone { kind, .. } if *kind == expected),
                "{stderr} should be {expected:?}, got {error:?}",
            );
            assert!(!error.is_object_gone(), "{stderr}");
        }
    }

    /// The order the two server-exit wordings are read in is load-bearing.
    ///
    /// A lost server says `server exited unexpectedly`, which starts with the
    /// `server exited` of one that shut down and does not mean it.
    #[test]
    fn a_lost_server_is_not_read_as_one_that_stopped() {
        let error = Error::refused(
            "new-session",
            Some(1),
            "server exited unexpectedly".to_owned(),
            None,
        );
        assert!(
            matches!(&error, Error::ServerGone { kind, .. } if *kind == ServerGoneKind::Lost),
            "{error:?}",
        );
    }

    /// A refusal that says nothing about the server stays a refusal, so the
    /// classification is not simply calling everything gone.
    #[test]
    fn a_refusal_that_names_no_server_stays_a_refusal() {
        let error = Error::refused(
            "delete-buffer",
            Some(1),
            "no buffer never-existed".to_owned(),
            None,
        );
        assert_eq!(error.kind(), ErrorKind::Refused, "{error:?}");
    }
}

#[cfg(test)]
mod compat_tests {

    /// Pin the tmux wording that says how an option was refused.
    ///
    /// The three answers need three different fixes, and tmux distinguishes
    /// them only in stderr: every one of these exits 1. It also spells a
    /// rejected value two ways, "bad value" for a flag and "value is invalid"
    /// for a number, which is why the kind exists rather than the text.
    #[cfg(feature = "test-support")]
    #[tokio::test]
    async fn real_tmux_compat_error_option_refusal_wording_is_recognized() {
        use crate::test::TestServer;
        use crate::{Error, ErrorKind, OptionErrorKind};

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

        for (name, value, expected) in [
            ("no-such-option", "x", OptionErrorKind::Unknown),
            // A prefix of `status-left`, `status-left-length`, and
            // `status-left-style` on every supported release, so tmux will not
            // choose. A release that left only one of them would turn this
            // answer into a different kind, which is the point of pinning it.
            ("status-l", "x", OptionErrorKind::Ambiguous),
            ("mouse", "notabool", OptionErrorKind::BadValue),
            (
                "status-left-length",
                "notanumber",
                OptionErrorKind::BadValue,
            ),
        ] {
            let error = server
                .set_global_option(name, value)
                .await
                .expect_err("tmux refuses it");
            assert!(
                matches!(&error, Error::OptionRejected { kind, .. } if *kind == expected),
                "{name}={value} should be {expected:?}, got {error:?}",
            );
            assert_eq!(error.kind(), ErrorKind::Refused);
            assert!(!error.is_object_gone(), "a refusal is not a missing object");
        }

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

    /// Pin the tmux wording that separates a missing target from a refusal.
    ///
    /// `Error::refused` reads tmux's stderr because tmux exits 1 for both, so
    /// this asserts against the tmux the lane is running rather than against
    /// the source this was written from. Every compatibility lane runs it, so
    /// a release that rewords these is a failure here rather than a silently
    /// wrong `is_object_gone` in the field.
    #[cfg(feature = "test-support")]
    #[tokio::test]
    async fn real_tmux_compat_error_missing_target_wording_is_recognized() {
        use crate::ErrorKind;
        use crate::test::TestServer;

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

        // One live session, so tmux can resolve a current target and reports
        // the specific object it could not find.
        for (label, error) in [
            (
                "window",
                server
                    .window_by_id(&"@4242".parse().expect("a window id"))
                    .await
                    .map(|found| assert!(found.is_none(), "the window does not exist"))
                    .err(),
            ),
            (
                "pane",
                server
                    .pane_by_id(&"%4242".parse().expect("a pane id"))
                    .await
                    .map(|found| assert!(found.is_none(), "the pane does not exist"))
                    .err(),
            ),
        ] {
            assert!(error.is_none(), "a lookup reports absence, not {label}");
        }

        // A mutation against a target tmux does not have is where the wording
        // matters: it is the only signal separating this from a bad argument.
        let mut window = session.windows().await.expect("windows").remove(0);
        let doomed = session
            .new_window(crate::NewWindowOptions::new("doomed").command("sleep 300"))
            .await
            .expect("window");
        let mut stale = doomed.clone();
        doomed.kill().await.expect("the window is killed");

        let error = stale.rename("gone").await.expect_err("the window is gone");
        assert_eq!(
            error.kind(),
            ErrorKind::ObjectGone,
            "tmux 'can't find window' is recognized: {error}",
        );

        // And a refusal that is not a missing target stays a refusal, so the
        // classification is not simply calling everything gone.
        let refused = server
            .delete_buffer("never-existed")
            .await
            .expect_err("tmux has no such buffer");
        assert_eq!(refused.kind(), ErrorKind::Refused, "{refused}");

        // With no session left, tmux cannot resolve a current target and says
        // so instead, for the same request. Both wordings mean gone.
        window
            .rename("last")
            .await
            .expect("the window still exists");
        session.kill().await.expect("the session is killed");

        let error = stale
            .rename("still gone")
            .await
            .expect_err("the window is gone");
        assert_eq!(
            error.kind(),
            ErrorKind::ObjectGone,
            "tmux 'no current target' is recognized: {error}",
        );

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

    /// Pin the tmux wording that says the server, not the request, is the
    /// problem.
    ///
    /// tmux exits 1 for a command it refused and for a command that found no
    /// server, and separates them only in stderr. Reading the second as the
    /// first tells a caller to fix arguments that were never the trouble.
    #[cfg(feature = "test-support")]
    #[tokio::test]
    async fn real_tmux_compat_error_absent_server_wording_is_recognized() {
        use std::time::Duration;

        use crate::test::{TestServer, retry_until};
        use crate::{Command, ErrorKind, ServerGoneKind};

        let mut guard = TestServer::builder().start().await.expect("tmux starts");
        guard.session("compat-gone").await.expect("session");

        guard
            .server()
            .cmd(Command::new("kill-server"))
            .await
            .expect("the server is killed");

        // tmux stops answering on the socket before the kernel has a status
        // for the process behind it, so this waits for the daemon rather than
        // for a duration.
        retry_until(Duration::from_secs(5), async || {
            !guard.daemon_state().is_running()
        })
        .await
        .expect("the daemon exits");

        let error = guard
            .server()
            .sessions()
            .await
            .expect_err("there is no server to list");
        assert_eq!(
            error.kind(),
            ErrorKind::ServerGone,
            "tmux 'no server running' is recognized: {error}",
        );
        assert!(
            matches!(&error, crate::Error::ServerGone { kind, .. } if *kind == ServerGoneKind::NotRunning),
            "the absence is named: {error:?}",
        );
        assert!(
            !error.is_object_gone(),
            "an absent server is not a missing object: {error}",
        );

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