moshpit 0.8.1

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

use std::{
    ffi::OsString,
    fs::{DirBuilder, OpenOptions},
    io::{Read as _, Write as _, stdin, stdout},
    net::SocketAddr,
    path::{Path, PathBuf},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    thread,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

#[cfg(target_family = "unix")]
use std::os::unix::fs::DirBuilderExt;

use anyhow::{Context as _, Result};
use clap::Parser as _;
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use dialoguer::{Confirm, Password};
use libmoshpit::{
    DiffMode, DisplayPreference, Emulator, EncryptedFrame, KEY_ALGORITHM_X25519, Kex,
    KexConfig as _, KexMode, KeyPair, MoshpitError, PredictionEngine, Renderer, UdpReader,
    UdpSender, UuidWrapper, init_tracing, load, paint_overlays_to_ansi, parse_server_destination,
    run_key_exchange,
};
use terminal_size::terminal_size;
#[cfg(unix)]
use tokio::signal::unix::{SignalKind, signal};
use tokio::{
    net::{TcpStream, UdpSocket},
    select, spawn,
    sync::{
        Mutex,
        mpsc::{Receiver, Sender, channel},
    },
    time,
};
use tokio_util::sync::CancellationToken;
use tracing::{error, info, trace};
use uuid::Uuid;

use crate::{cli::Cli, config::Config};

#[cfg_attr(coverage_nightly, coverage(off))]
pub(crate) async fn run<I, T>(args: Option<I>) -> Result<()>
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
{
    let cli = if let Some(args) = args {
        Cli::try_parse_from(args)?
    } else {
        Cli::try_parse()?
    };
    let mut config =
        load::<Cli, Config, Cli>(&cli, &cli).with_context(|| MoshpitError::ConfigLoad)?;
    init_tracing(&config, config.tracing().file(), &cli, None)
        .with_context(|| MoshpitError::TracingInit)?;
    maybe_generate_keypair(&config)?;

    let (user, socket_addr) =
        parse_server_destination(config.server_destination(), config.server_port())?;
    let server_ip = socket_addr.ip().to_string();
    let server_port = config.server_port();
    let _ = config.set_user(user);

    run_session_loop(config, socket_addr, server_ip, server_port).await
}

/// Cached passphrase state, avoiding re-prompting across reconnects.
#[derive(Debug)]
enum PassCache {
    /// Not yet prompted.
    Uncached,
    /// Prompted; key is unencrypted — no passphrase needed.
    NoPassphrase,
    /// Prompted; encrypted key passphrase.
    Passphrase(String),
}

impl PassCache {
    /// Returns `true` when a cached answer is available.
    fn is_cached(&self) -> bool {
        !matches!(self, Self::Uncached)
    }

    /// Returns the cached passphrase.  `None` means the key is unencrypted.
    ///
    /// Panics if called while `Uncached`.
    fn passphrase(&self) -> Option<String> {
        match self {
            Self::Uncached => unreachable!("passphrase() called before caching"),
            Self::NoPassphrase => None,
            Self::Passphrase(s) => Some(s.clone()),
        }
    }
}

/// Maximum time allowed for the entire TCP key exchange.  If the server accepts
/// the TCP connection but never sends a frame the client would otherwise block
/// forever inside `read_frame().await`; this bound converts that hang into a
/// retriable network error.
const KEX_TIMEOUT: Duration = Duration::from_secs(30);

/// An unrecoverable key-exchange error that should not trigger the retry loop.
#[derive(Debug)]
struct FatalKexError {
    inner: MoshpitError,
    key_path: PathBuf,
}

impl std::fmt::Display for FatalKexError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} (key: {})", self.inner, self.key_path.display())
    }
}

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

#[derive(Clone, Copy, Default)]
enum EscapeState {
    #[default]
    Normal,
    PendingDot,
}

/// Show a mosh-style reconnecting banner at the top of the terminal.
///
/// The banner is white-on-blue, occupies the entire first row, and is
/// rendered by writing raw ANSI escape sequences through the same stdout
/// channel used for normal terminal output.
async fn show_reconnect_banner(stdout_tx: &Sender<Vec<u8>>) {
    // ESC[s          – save cursor position
    // ESC[1;1H       – move to row 1, col 1
    // ESC[44;97;1m   – blue background, bright-white bold text
    // ESC[K          – erase to end of line (fills line with blue)
    // ESC[0m         – reset attributes
    // ESC[u          – restore cursor position
    let msg = b"\x1b[s\x1b[1;1H\x1b[44;97;1m [moshpit] server unreachable, reconnecting... (Ctrl-^ . to quit) \x1b[K\x1b[0m\x1b[u";
    drop(stdout_tx.send(msg.to_vec()).await);
}

/// Clear the reconnecting banner and restore the first row to normal.
async fn clear_reconnect_banner(stdout_tx: &Sender<Vec<u8>>) {
    // Reset attributes first so the erase uses the default background.
    let msg = b"\x1b[s\x1b[1;1H\x1b[0m\x1b[K\x1b[u";
    drop(stdout_tx.send(msg.to_vec()).await);
}

/// Redraw the banner once per second, counting down from `total_secs` to 0.
/// Returns `true` if the user pressed the escape sequence (`Ctrl-^ .`) to quit.
async fn countdown_reconnect_banner(
    stdout_tx: &Sender<Vec<u8>>,
    total_secs: u64,
    attempt: u32,
    max_backoff_secs: u64,
    exit_token: &CancellationToken,
) -> bool {
    for remaining in (0..=total_secs).rev() {
        let msg = format!(
            "\x1b[s\x1b[1;1H\x1b[44;97;1m [moshpit] server unreachable, reconnecting \
(attempt #{attempt}, {remaining}s, max {max_backoff_secs}s, Ctrl-^ . to quit)... \x1b[K\x1b[0m\x1b[u"
        );
        drop(stdout_tx.send(msg.into_bytes()).await);
        if remaining > 0 {
            select! {
                () = exit_token.cancelled() => return true,
                () = time::sleep(Duration::from_secs(1)) => {}
            }
        }
    }
    exit_token.is_cancelled()
}

/// Holds the `kb_rx` mutex during reconnect countdowns and detects `Ctrl-^ .`.
/// Cancels `exit_token` when the escape sequence is detected, then returns.
/// Stops when `done_token` is cancelled (countdown finished normally).
async fn run_escape_listener(
    kb_rx: Arc<Mutex<Receiver<Vec<u8>>>>,
    exit_token: CancellationToken,
    done_token: CancellationToken,
) {
    let mut state = EscapeState::Normal;
    let mut rx = kb_rx.lock().await;
    loop {
        select! {
            () = done_token.cancelled() => break,
            data = rx.recv() => match data {
                None => break,
                Some(data) => {
                    for &byte in &data {
                        state = match state {
                            EscapeState::Normal => {
                                if byte == 0x1E { EscapeState::PendingDot } else { EscapeState::Normal }
                            }
                            EscapeState::PendingDot => {
                                if byte == 0x2E {
                                    exit_token.cancel();
                                    return;
                                } else if byte == 0x1E {
                                    EscapeState::PendingDot
                                } else {
                                    EscapeState::Normal
                                }
                            }
                        };
                    }
                }
            }
        }
    }
}

fn encode_char_key(c: char, ctrl: bool, alt: bool) -> Vec<u8> {
    let mut out = Vec::new();
    if ctrl {
        let byte = match c.to_ascii_lowercase() {
            '@' => 0x00,
            'a'..='z' => c.to_ascii_lowercase() as u8 - b'a' + 1,
            '[' => 0x1b,
            // crossterm's Unix parser maps 0x1C-0x1F to Char('4'-'7') + CONTROL
            // (e.g. Ctrl+6 / Ctrl+^ → 0x1E → Char('6') + CONTROL).  Accepting
            // both the digit and the traditional symbol form keeps behaviour
            // consistent across platforms and terminal emulators.
            '\\' | '4' => 0x1c,
            ']' | '5' => 0x1d,
            '^' | '6' => 0x1e,
            '_' | '7' => 0x1f,
            _ => {
                let mut buf = [0u8; 4];
                let s = c.encode_utf8(&mut buf);
                if alt {
                    out.push(0x1b);
                }
                out.extend_from_slice(s.as_bytes());
                return out;
            }
        };
        if alt {
            out.push(0x1b);
        }
        out.push(byte);
        return out;
    }

    if alt {
        out.push(0x1b);
    }
    let mut buf = [0u8; 4];
    out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
    out
}

fn encode_nav_key(
    code: crossterm::event::KeyCode,
    has_mod: bool,
    mod_param: u8,
) -> Option<Vec<u8>> {
    use crossterm::event::KeyCode;

    let bytes = match code {
        KeyCode::Up => {
            if has_mod {
                format!("\x1b[1;{mod_param}A").into_bytes()
            } else {
                b"\x1b[A".to_vec()
            }
        }
        KeyCode::Down => {
            if has_mod {
                format!("\x1b[1;{mod_param}B").into_bytes()
            } else {
                b"\x1b[B".to_vec()
            }
        }
        KeyCode::Right => {
            if has_mod {
                format!("\x1b[1;{mod_param}C").into_bytes()
            } else {
                b"\x1b[C".to_vec()
            }
        }
        KeyCode::Left => {
            if has_mod {
                format!("\x1b[1;{mod_param}D").into_bytes()
            } else {
                b"\x1b[D".to_vec()
            }
        }
        KeyCode::Home => {
            if has_mod {
                format!("\x1b[1;{mod_param}H").into_bytes()
            } else {
                b"\x1b[H".to_vec()
            }
        }
        KeyCode::End => {
            if has_mod {
                format!("\x1b[1;{mod_param}F").into_bytes()
            } else {
                b"\x1b[F".to_vec()
            }
        }
        KeyCode::Insert => {
            if has_mod {
                format!("\x1b[2;{mod_param}~").into_bytes()
            } else {
                b"\x1b[2~".to_vec()
            }
        }
        KeyCode::Delete => {
            if has_mod {
                format!("\x1b[3;{mod_param}~").into_bytes()
            } else {
                b"\x1b[3~".to_vec()
            }
        }
        KeyCode::PageUp => {
            if has_mod {
                format!("\x1b[5;{mod_param}~").into_bytes()
            } else {
                b"\x1b[5~".to_vec()
            }
        }
        KeyCode::PageDown => {
            if has_mod {
                format!("\x1b[6;{mod_param}~").into_bytes()
            } else {
                b"\x1b[6~".to_vec()
            }
        }
        _ => return None,
    };
    Some(bytes)
}

fn encode_function_key(n: u8, has_mod: bool, mod_param: u8) -> Vec<u8> {
    match n {
        1 => {
            if has_mod {
                format!("\x1b[1;{mod_param}P").into_bytes()
            } else {
                b"\x1bOP".to_vec()
            }
        }
        2 => {
            if has_mod {
                format!("\x1b[1;{mod_param}Q").into_bytes()
            } else {
                b"\x1bOQ".to_vec()
            }
        }
        3 => {
            if has_mod {
                format!("\x1b[1;{mod_param}R").into_bytes()
            } else {
                b"\x1bOR".to_vec()
            }
        }
        4 => {
            if has_mod {
                format!("\x1b[1;{mod_param}S").into_bytes()
            } else {
                b"\x1bOS".to_vec()
            }
        }
        5 => {
            if has_mod {
                format!("\x1b[15;{mod_param}~").into_bytes()
            } else {
                b"\x1b[15~".to_vec()
            }
        }
        6 => {
            if has_mod {
                format!("\x1b[17;{mod_param}~").into_bytes()
            } else {
                b"\x1b[17~".to_vec()
            }
        }
        7 => {
            if has_mod {
                format!("\x1b[18;{mod_param}~").into_bytes()
            } else {
                b"\x1b[18~".to_vec()
            }
        }
        8 => {
            if has_mod {
                format!("\x1b[19;{mod_param}~").into_bytes()
            } else {
                b"\x1b[19~".to_vec()
            }
        }
        9 => {
            if has_mod {
                format!("\x1b[20;{mod_param}~").into_bytes()
            } else {
                b"\x1b[20~".to_vec()
            }
        }
        10 => {
            if has_mod {
                format!("\x1b[21;{mod_param}~").into_bytes()
            } else {
                b"\x1b[21~".to_vec()
            }
        }
        11 => {
            if has_mod {
                format!("\x1b[23;{mod_param}~").into_bytes()
            } else {
                b"\x1b[23~".to_vec()
            }
        }
        12 => {
            if has_mod {
                format!("\x1b[24;{mod_param}~").into_bytes()
            } else {
                b"\x1b[24~".to_vec()
            }
        }
        _ => Vec::new(),
    }
}

/// Converts a crossterm `KeyEvent` to the ANSI escape bytes a terminal would
/// produce for the same keypress.  Returns an empty `Vec` for events that
/// should not be forwarded (key-release events, unhandled keys, etc.).
///
/// On Windows the console API reports key presses as structured events; on Unix
/// crossterm parses raw stdin bytes in raw mode.  Either way this re-encodes
/// the event as ANSI bytes for forwarding to the server.
fn key_event_to_bytes(event: crossterm::event::KeyEvent) -> Vec<u8> {
    use crossterm::event::{KeyCode, KeyEventKind, KeyModifiers};
    // Only forward press events; Windows always reports both press and release.
    if event.kind != KeyEventKind::Press {
        return Vec::new();
    }
    let mods = event.modifiers;
    let ctrl = mods.contains(KeyModifiers::CONTROL);
    let alt = mods.contains(KeyModifiers::ALT);
    let shift = mods.contains(KeyModifiers::SHIFT);
    // CSI modifier parameter: 1 + shift + alt*2 + ctrl*4
    let mod_param = 1u8 + u8::from(shift) + (u8::from(alt) * 2) + (u8::from(ctrl) * 4);
    let has_mod = mod_param > 1;

    match event.code {
        KeyCode::Char(c) => encode_char_key(c, ctrl, alt),
        KeyCode::Backspace => vec![0x7f],
        KeyCode::Enter => vec![b'\r'],
        KeyCode::Tab => vec![b'\t'],
        KeyCode::BackTab => b"\x1b[Z".to_vec(),
        KeyCode::Esc => vec![0x1b],
        KeyCode::Null => vec![0x00],
        KeyCode::F(n) => encode_function_key(n, has_mod, mod_param),
        code => encode_nav_key(code, has_mod, mod_param).unwrap_or_default(),
    }
}

/// Temporarily pauses the stdin reader and restores cooked mode, calls `f`,
/// then re-enables raw mode and resumes the reader.  Wraps interactive prompts
/// (passphrase, TOFU, key-mismatch) that require a functioning line editor.
#[cfg_attr(coverage_nightly, coverage(off))]
fn with_cooked_term<T>(paused: &AtomicBool, f: impl FnOnce() -> T) -> T {
    paused.store(true, Ordering::SeqCst);
    // Give the reader thread time to observe the pause before raw mode drops.
    thread::sleep(Duration::from_millis(100));
    drop(disable_raw_mode());
    let result = f();
    drop(enable_raw_mode());
    paused.store(false, Ordering::SeqCst);
    result
}

/// Polls for crossterm key events and forwards their ANSI byte encoding to the
/// keyboard channel.  When `paused` is set, idles so `with_cooked_term` can
/// safely disable raw mode around interactive prompts.
fn stdin_reader_loop(kb_tx: &Sender<Vec<u8>>, paused: &AtomicBool) {
    use crossterm::event::{Event, poll, read};
    loop {
        if paused.load(Ordering::Relaxed) {
            thread::sleep(Duration::from_millis(50));
            continue;
        }
        match poll(Duration::from_millis(50)) {
            Ok(true) => {
                if let Ok(Event::Key(ke)) = read() {
                    let bytes = key_event_to_bytes(ke);
                    if !bytes.is_empty() && kb_tx.blocking_send(bytes).is_err() {
                        break;
                    }
                }
            }
            Ok(false) => {}
            Err(_) => break,
        }
    }
}

/// Runs the reconnect countdown alongside an escape-sequence listener.
/// Returns `true` if the user pressed `Ctrl-^ .` to quit.
#[cfg_attr(coverage_nightly, coverage(off))]
async fn countdown_with_escape(
    stdout_tx: &Sender<Vec<u8>>,
    backoff_secs: u64,
    attempt: u32,
    max_backoff_secs: u64,
    exit_token: &CancellationToken,
    kb_rx: Arc<Mutex<Receiver<Vec<u8>>>>,
) -> bool {
    let escape_done = CancellationToken::new();
    let escape_handle = spawn(run_escape_listener(
        kb_rx,
        exit_token.clone(),
        escape_done.clone(),
    ));
    let exiting = countdown_reconnect_banner(
        stdout_tx,
        backoff_secs,
        attempt,
        max_backoff_secs,
        exit_token,
    )
    .await;
    escape_done.cancel();
    drop(escape_handle.await);
    exiting
}

/// Persistent reconnect loop.  Runs until the shell exits (via `process::exit`).
#[cfg_attr(nightly, allow(clippy::too_many_lines))]
#[cfg_attr(coverage_nightly, coverage(off))]
async fn run_session_loop(
    config: Config,
    socket_addr: SocketAddr,
    server_ip: String,
    server_port: u16,
) -> Result<()> {
    // Clamp to [2 s, 24 h].
    let max_backoff = Duration::from_secs(config.max_reconnect_backoff_secs().clamp(2, 86_400));

    // Persistent stdout writer — survives reconnects.
    let (stdout_tx, mut stdout_rx) = channel::<Vec<u8>>(256);
    let _stdout_thread = thread::spawn(move || {
        let mut out = stdout();
        while let Some(msg) = stdout_rx.blocking_recv() {
            drop(out.write_all(&msg));
            drop(out.flush());
        }
    });

    // Passphrase cache: avoids re-prompting on reconnect.
    let pass_cache: Arc<std::sync::Mutex<PassCache>> =
        Arc::new(std::sync::Mutex::new(PassCache::Uncached));

    let mut config = config;
    let mut backoff = Duration::from_secs(2);
    let mut reconnect_attempt: u32 = 0;
    // Shared exit token: cancelled when the user presses Ctrl-^ . to quit.
    let exit_token = CancellationToken::new();

    // Start the stdin reader before the first KEX so Ctrl-^ . is always
    // detectable.  with_cooked_term pauses it around interactive prompts.
    let stdin_paused = Arc::new(AtomicBool::new(false));
    enable_raw_mode()?;
    let (kb_tx, kb_rx) = channel::<Vec<u8>>(64);
    let paused_for_reader = stdin_paused.clone();
    let _stdin_thread = thread::spawn(move || stdin_reader_loop(&kb_tx, &paused_for_reader));
    let kb_rx_shared = Arc::new(Mutex::new(kb_rx));

    let mut had_successful_kex = false;

    loop {
        match connect_and_kex(
            &mut config,
            socket_addr,
            &server_ip,
            server_port,
            &pass_cache,
            stdin_paused.clone(),
        )
        .await
        {
            Ok((kex, udp_arc, nak_timeout)) => {
                backoff = Duration::from_secs(2);
                clear_reconnect_banner(&stdout_tx).await;
                had_successful_kex = true;

                let session_result = run_udp_session(
                    kex,
                    udp_arc,
                    nak_timeout,
                    kb_rx_shared.clone(),
                    config.nat_warmup(),
                    config.nat_warmup_count(),
                    stdout_tx.clone(),
                    config.predict(),
                    config.diff_mode(),
                    exit_token.clone(),
                )
                .await;
                if let Err(e) = session_result {
                    drop(disable_raw_mode());
                    return Err(e);
                }
                if exit_token.is_cancelled() {
                    drop(disable_raw_mode());
                    time::sleep(Duration::from_millis(100)).await;
                    std::process::exit(0);
                }
                // Session dropped — show the reconnecting banner while we retry.
                show_reconnect_banner(&stdout_tx).await;
                time::sleep(Duration::from_millis(500)).await;
            }
            Err(e) => {
                if let Some(fatal) = e.downcast_ref::<FatalKexError>() {
                    eprintln!("mp: fatal key error: {fatal}");
                    eprintln!(
                        "mp: run `mp-keygen` to regenerate your keypair at {}",
                        fatal.key_path.display()
                    );
                    drop(disable_raw_mode());
                    return Err(e);
                }
                if e.downcast_ref::<MoshpitError>()
                    .is_some_and(|e| *e == MoshpitError::HostKeyRejected)
                {
                    drop(disable_raw_mode());
                    return Err(e);
                }
                if let Some(&err) = e.downcast_ref::<MoshpitError>() {
                    match err {
                        MoshpitError::KeyNotEstablished => {
                            eprintln!("mp: server rejected the key exchange");
                            eprintln!(
                                "mp: ensure your public key is listed in \
                                 ~/.mp/authorized_keys on the server"
                            );
                            drop(disable_raw_mode());
                            return Err(e);
                        }
                        MoshpitError::NoCommonAlgorithm => {
                            eprintln!("mp: no common algorithm found during key exchange");
                            eprintln!(
                                "mp: check --kex-algos, --aead-algos, --mac-algos, \
                                 and --kdf-algos settings on both client and server"
                            );
                            drop(disable_raw_mode());
                            return Err(e);
                        }
                        _ => {}
                    }
                }
                reconnect_attempt = reconnect_attempt.saturating_add(1);
                error!("Failed to connect to {socket_addr}: {e}, retrying in {backoff:?}");
                // Reset passphrase cache on early failures so the user can
                // re-enter it on the next attempt.
                if !had_successful_kex {
                    *pass_cache
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner) = PassCache::Uncached;
                }
                if countdown_with_escape(
                    &stdout_tx,
                    backoff.as_secs(),
                    reconnect_attempt,
                    max_backoff.as_secs(),
                    &exit_token,
                    kb_rx_shared.clone(),
                )
                .await
                {
                    clear_reconnect_banner(&stdout_tx).await;
                    let msg = b"\r\n\x1b[0m[moshpit] Disconnected.\r\n";
                    drop(stdout_tx.send(msg.to_vec()).await);
                    drop(disable_raw_mode());
                    time::sleep(Duration::from_millis(100)).await;
                    std::process::exit(0);
                }
                backoff = (backoff * 2).min(max_backoff);
            }
        }
    }
}

/// Connect via TCP, run the key exchange, and persist the session UUID.
#[cfg_attr(nightly, allow(clippy::too_many_lines))]
async fn connect_and_kex(
    config: &mut Config,
    socket_addr: SocketAddr,
    server_ip: &str,
    server_port: u16,
    pass_cache: &Arc<std::sync::Mutex<PassCache>>,
    stdin_paused: Arc<AtomicBool>,
) -> Result<(Kex, Arc<UdpSocket>, Duration)> {
    // Refresh resume UUID from disk (may have been updated by previous connection).
    let _ = config.set_resume_session_uuid(read_session_uuid(server_ip, server_port));

    let socket = TcpStream::connect(socket_addr).await?;
    info!("Connected to {}", socket.peer_addr()?);

    let cache = pass_cache.clone();
    let paused_pass = stdin_paused.clone();
    let pass_fn = move || -> Result<Option<String>> {
        let guard = cache
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if guard.is_cached() {
            info!(
                "passphrase: returning cached value (has_passphrase={})",
                guard.passphrase().is_some()
            );
            return Ok(guard.passphrase());
        }
        drop(guard);
        info!("passphrase: prompting user");
        let result =
            tokio::task::block_in_place(|| with_cooked_term(&paused_pass, read_passpharase));
        match &result {
            Ok(Some(_)) => info!("passphrase: prompt returned a passphrase"),
            Ok(None) => info!("passphrase: prompt returned None (key may be unencrypted)"),
            Err(e) => error!("passphrase: prompt failed: {e}"),
        }
        if let Ok(ref pass) = result {
            *cache
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner) = match pass {
                Some(s) => PassCache::Passphrase(s.clone()),
                None => PassCache::NoPassphrase,
            };
        }
        result
    };

    let (sock_read, sock_write) = socket.into_split();

    let paused_tofu = stdin_paused.clone();
    let tofu_fn: libmoshpit::TofuFn =
        Arc::new(move |host: &str, fingerprint: &str| -> Result<bool> {
            tokio::task::block_in_place(|| {
                with_cooked_term(&paused_tofu, || {
                    let prompt = format!(
                        "The authenticity of host '{host}' can't be established.\n\
                     Fingerprint is SHA256:{fingerprint}.\n\
                     Are you sure you want to continue connecting? (yes/no)"
                    );
                    let input: String = dialoguer::Input::new()
                        .with_prompt(prompt)
                        .interact_text()?;
                    Ok(input.eq_ignore_ascii_case("yes"))
                })
            })
        });

    let paused_mismatch = stdin_paused;
    let mismatch_fn: libmoshpit::HostKeyMismatchFn = Arc::new(
        move |host: &str, old_fingerprint: &str, new_fingerprint: &str| -> Result<bool> {
            tokio::task::block_in_place(|| {
                with_cooked_term(&paused_mismatch, || {
                    eprintln!("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                    eprintln!("@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
                    eprintln!("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                    eprintln!("Potential DNS spoofing or machine-in-the-middle detected.");
                    eprintln!("Host: {host}");
                    eprintln!("Offending key fingerprint: SHA256:{old_fingerprint}");
                    eprintln!("Presented key fingerprint: SHA256:{new_fingerprint}");

                    Confirm::new()
                        .with_prompt(
                            "Update ~/.mp/known_hosts with the newly presented key for this host?",
                        )
                        .default(false)
                        .wait_for_newline(true)
                        .interact()
                        .map_err(Into::into)
                })
            })
        },
    );

    let kex_start = Instant::now();
    let kex_result = time::timeout(
        KEX_TIMEOUT,
        run_key_exchange(
            config.clone(),
            sock_read,
            sock_write,
            pass_fn,
            Some(tofu_fn),
            Some(mismatch_fn),
        ),
    )
    .await;
    let (kex, udp_arc, _) = match kex_result {
        Err(_elapsed) => {
            return Err(anyhow::anyhow!(
                "key exchange timed out after {KEX_TIMEOUT:?} — \
                 server accepted TCP connection but sent no data"
            ));
        }
        Ok(inner) => inner,
    }
    .map_err(|e| {
        if let Some(&moshpit_err) = e.downcast_ref::<MoshpitError>() {
            match moshpit_err {
                MoshpitError::KeyFileMissing
                | MoshpitError::KeyCorrupt
                | MoshpitError::KeyPairMismatch
                | MoshpitError::DecryptionFailed
                | MoshpitError::InvalidPublicKeyFormat
                | MoshpitError::InvalidKeyHeader => {
                    let key_path = config
                        .key_pair_paths()
                        .ok()
                        .map(|(p, _)| p)
                        .unwrap_or_default();
                    return anyhow::anyhow!(FatalKexError {
                        inner: moshpit_err,
                        key_path,
                    });
                }
                _ => {}
            }
        }
        e
    })?;

    if let Some(session_uuid) = kex.session_uuid() {
        if let Err(e) = write_session_uuid(server_ip, server_port, session_uuid) {
            trace!("Failed to write session file: {e}");
        }
        if kex.is_resume() {
            info!("Session {session_uuid} resumed");
        } else {
            info!("New session {session_uuid} started");
        }
    }
    // Use the TCP KEX elapsed time as a proxy for network RTT.  The key
    // exchange involves ~2 round trips, so the total elapsed time is
    // approximately 2× RTT, making it a reasonable base for the NAK backoff
    // schedule.  Clamp to [20 ms, 500 ms] to handle both LAN and high-latency
    // paths without risking spurious NAKs or excessively slow recovery.
    let nak_timeout = kex_start
        .elapsed()
        .clamp(Duration::from_millis(20), Duration::from_millis(500));
    info!("nak_timeout set to {:?} from kex elapsed time", nak_timeout);
    Ok((kex, udp_arc, nak_timeout))
}

/// Set up UDP tasks for one session and wait until the server disconnects.
#[cfg_attr(nightly, allow(clippy::too_many_lines))]
#[cfg_attr(nightly, allow(clippy::too_many_arguments))]
#[cfg_attr(coverage_nightly, coverage(off))]
async fn run_udp_session(
    kex: Kex,
    udp_arc: Arc<UdpSocket>,
    nak_timeout: Duration,
    kb_rx: Arc<Mutex<Receiver<Vec<u8>>>>,
    nat_warmup: bool,
    nat_warmup_count: u32,
    stdout_tx: Sender<Vec<u8>>,
    display_preference: DisplayPreference,
    diff_mode: DiffMode,
    exit_token: CancellationToken,
) -> Result<()> {
    let (reconnect_tx, mut reconnect_rx) = channel::<()>(1);
    let token = CancellationToken::new();
    let (tx, rx) = channel::<EncryptedFrame>(256);
    let (_control_tx, control_rx) = channel::<EncryptedFrame>(16);
    let (retransmit_tx, retransmit_rx) = channel::<Vec<u64>>(512);

    // Derive silence timeout from path RTT: max(nak_timeout × 30, 9 s).
    // With a 3 s server keepalive interval this guarantees ≥ 3 keepalives
    // arrive before the silence window closes.  On LAN (nak_timeout ≈ 20 ms)
    // this gives 9 s vs the former fixed 15 s; on high-latency paths it scales
    // up proportionally so a single slow keepalive never causes a false disconnect.
    let silence_timeout = (nak_timeout * 30).max(Duration::from_secs(9));
    let mac_tag_len = kex.mac_tag_len();
    let mut udp_reader = UdpReader::builder()
        .socket(udp_arc.clone())
        .id(kex.uuid())
        .hmac(kex.build_hmac())
        .rnk(kex.build_aead_key()?)
        .mac_tag_len(mac_tag_len)
        .nak_out_tx(tx.clone())
        .retransmit_tx(retransmit_tx)
        .silence_timeout(silence_timeout)
        .nak_timeout(nak_timeout)
        .reconnect_tx(reconnect_tx)
        .query_response_tx(tx.clone())
        .diff_mode(diff_mode)
        .build();

    let mut udp_sender = UdpSender::builder()
        .socket(udp_arc)
        .control_rx(control_rx)
        .rx(rx)
        .retransmit_rx(retransmit_rx)
        .id(kex.uuid())
        .hmac(kex.build_hmac())
        .rnk(kex.build_aead_key()?)
        .diff_mode(diff_mode)
        .build();

    let sender_token = token.clone();
    let _sender = spawn(async move { udp_sender.frame_loop(sender_token).await });

    let (cols, rows) = terminal_size().map_or((80, 24), |(w, h)| (w.0, h.0));
    tx.send(EncryptedFrame::Resize((kex.uuid_wrapper(), cols, rows)))
        .await?;

    // NAT warmup: send keepalive frames before the session loop begins so that
    // a bidirectional NAT binding is established before the server starts
    // sending terminal diffs.  This prevents the initial burst of dropped
    // packets that causes head-of-line blocking under some NAT configurations.
    // Off by default; opt in with `--nat-warmup` / `MOSHPIT_NAT_WARMUP=true`.
    if nat_warmup {
        info!(
            "NAT warmup: sending {} keepalive frame(s)",
            nat_warmup_count
        );
        for _ in 0..nat_warmup_count {
            let ts = u64::try_from(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_micros(),
            )
            .unwrap_or(0);
            tx.send(EncryptedFrame::Keepalive(ts)).await?;
        }
    }

    // ── Prediction / emulator shared state ──────────────────────────────────
    let emulator = Arc::new(std::sync::Mutex::new(Emulator::new(rows, cols)));
    let prediction = Arc::new(std::sync::Mutex::new(PredictionEngine::new(
        display_preference,
    )));
    let renderer = Arc::new(std::sync::Mutex::new(Renderer::new(rows, cols)));

    let reader_token = token.clone();
    let emu_reader = emulator.clone();
    let pred_reader = prediction.clone();
    let rend_reader = renderer.clone();
    let stdout_tx_reader = stdout_tx.clone();
    let exit_token_reader = exit_token.clone();
    let _reader = spawn(async move {
        udp_reader
            .client_frame_loop(
                reader_token,
                exit_token_reader,
                stdout_tx_reader,
                emu_reader,
                pred_reader,
                rend_reader,
            )
            .await;
    });

    spawn_resize_handler(
        tx.clone(),
        kex.uuid_wrapper(),
        token.clone(),
        emulator.clone(),
        renderer.clone(),
    );

    // Stdin forwarder: holds the shared kb_rx mutex for this session's lifetime.
    let fwd_token = token.clone();
    let exit_token_fwd = exit_token.clone();
    let session_tx = tx;
    let uuid_wrapper = kex.uuid_wrapper();
    let emu_fwd = emulator.clone();
    let pred_fwd = prediction.clone();
    let stdout_tx_fwd = stdout_tx;
    let _forwarder = spawn(async move {
        let mut rx = kb_rx.lock().await;
        let mut escape_state = EscapeState::Normal;
        loop {
            select! {
                () = fwd_token.cancelled() => break,
                data = rx.recv() => match data {
                    Some(data) => {
                        let mut to_forward: Vec<u8> = Vec::new();
                        let mut exit_requested = false;
                        for &byte in &data {
                            escape_state = match escape_state {
                                EscapeState::Normal => {
                                    if byte == 0x1E {
                                        EscapeState::PendingDot
                                    } else {
                                        to_forward.push(byte);
                                        EscapeState::Normal
                                    }
                                }
                                EscapeState::PendingDot => {
                                    if byte == 0x2E {
                                        exit_requested = true;
                                        break;
                                    } else if byte == 0x1E {
                                        // Repeated prefix: discard, stay pending
                                        EscapeState::PendingDot
                                    } else {
                                        // Forward the held 0x1E and the current byte
                                        to_forward.push(0x1E);
                                        to_forward.push(byte);
                                        EscapeState::Normal
                                    }
                                }
                            };
                        }
                        if !to_forward.is_empty() {
                            // Forward to server.
                            if session_tx
                                .send(EncryptedFrame::Bytes((uuid_wrapper, to_forward.clone())))
                                .await
                                .is_err()
                            {
                                break;
                            }
                            // Local echo prediction: feed each byte to the engine.
                            let (overlays, cursor) = {
                                let emu = emu_fwd.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
                                let screen = emu.screen();
                                let mut pred = pred_fwd.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
                                for byte in &to_forward {
                                    pred.new_user_byte(*byte, screen);
                                }
                                pred.apply(screen)
                            };
                            let preview = paint_overlays_to_ansi(&overlays, cursor);
                            if !preview.is_empty() {
                                drop(stdout_tx_fwd.send(preview).await);
                            }
                        }
                        if exit_requested {
                            let msg = b"\r\n\x1b[0m[moshpit] Disconnected.\r\n";
                            drop(stdout_tx_fwd.send(msg.to_vec()).await);
                            exit_token_fwd.cancel();
                            fwd_token.cancel();
                            break;
                        }
                    }
                    None => break,
                },
            }
        }
    });

    // Wait for a reconnect signal or a user-requested exit (Ctrl-^ .).
    select! {
        _ = reconnect_rx.recv() => {}
        () = exit_token.cancelled() => {}
    }
    token.cancel();
    // Allow the stdin forwarder to release the kb_rx mutex before the next session.
    time::sleep(Duration::from_millis(150)).await;
    Ok(())
}

#[cfg(unix)]
fn spawn_resize_handler(
    resize_tx: Sender<EncryptedFrame>,
    resize_uuid: UuidWrapper,
    resize_token: CancellationToken,
    emulator: Arc<std::sync::Mutex<Emulator>>,
    renderer: Arc<std::sync::Mutex<Renderer>>,
) {
    let _resize_handle = spawn(async move {
        match signal(SignalKind::window_change()) {
            Ok(mut sigwinch) => loop {
                tokio::select! {
                    () = resize_token.cancelled() => break,
                    _ = sigwinch.recv() => {
                        let (columns, rows) = terminal_size()
                            .map_or((80, 24), |(width, height)| (width.0, height.0));
                        emulator.lock().unwrap_or_else(std::sync::PoisonError::into_inner).set_size(rows, columns);
                        renderer.lock().unwrap_or_else(std::sync::PoisonError::into_inner).set_size(rows, columns);
                        if let Err(e) =
                            resize_tx.send(EncryptedFrame::Resize((resize_uuid, columns, rows))).await
                        {
                            error!("Failed to send resize frame: {e}");
                            break;
                        }
                    }
                }
            },
            Err(e) => error!("Failed to register SIGWINCH handler: {e}"),
        }
    });
}

// On Windows there is no SIGWINCH.  Instead, poll GetConsoleScreenBufferInfo
// (via terminal_size) every 250 ms and send a Resize frame whenever the
// dimensions change.  This avoids touching the console input buffer so it
// does not conflict with the stdin reader below.
#[cfg(windows)]
fn spawn_resize_handler(
    resize_tx: Sender<EncryptedFrame>,
    resize_uuid: UuidWrapper,
    resize_token: CancellationToken,
    emulator: Arc<std::sync::Mutex<Emulator>>,
    renderer: Arc<std::sync::Mutex<Renderer>>,
) {
    let _resize_handle = thread::spawn(move || {
        let mut last_size = terminal_size().map_or((80, 24), |(w, h)| (w.0, h.0));
        loop {
            if resize_token.is_cancelled() {
                break;
            }
            thread::sleep(Duration::from_millis(250));
            let current_size = terminal_size().map_or(last_size, |(w, h)| (w.0, h.0));
            if current_size != last_size {
                last_size = current_size;
                let (columns, rows) = current_size;
                emulator
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .set_size(rows, columns);
                renderer
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .set_size(rows, columns);
                if let Err(e) =
                    resize_tx.blocking_send(EncryptedFrame::Resize((resize_uuid, columns, rows)))
                {
                    error!("Failed to send resize frame: {e}");
                    break;
                }
            }
        }
    });
}

fn maybe_generate_keypair(config: &Config) -> Result<()> {
    let (priv_key_path, pub_key_path) = config.key_pair_paths()?;
    if priv_key_path.try_exists()? && pub_key_path.try_exists()? {
        return Ok(());
    }

    println!("No keypair found at the configured location.");
    println!("  Private key: {}", priv_key_path.display());
    println!("  Public key:  {}", pub_key_path.display());

    let generate = Confirm::new()
        .with_prompt("Generate a new keypair now?")
        .default(true)
        .wait_for_newline(true)
        .interact()?;

    if !generate {
        return Ok(());
    }

    // Create the parent directory for the private key if needed
    if let Some(parent) = priv_key_path.parent() {
        create_key_dir(parent)?;
    }

    let passphrase: String = Password::new()
        .with_prompt(format!(
            "Enter passphrase for \"{}\"",
            priv_key_path.display()
        ))
        .with_confirmation(
            "Enter same passphrase again",
            "Passphrases do not match. Try again.",
        )
        .allow_empty_password(false)
        .report(false)
        .interact()?;
    let passphrase_opt = Some(passphrase);

    let keypair = KeyPair::generate_key_pair(
        passphrase_opt.as_ref(),
        KexMode::Client,
        KEY_ALGORITHM_X25519,
    )?;

    let mut priv_key_file = {
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .mode(0o600)
                .open(&priv_key_path)?
        }
        #[cfg(not(unix))]
        {
            OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&priv_key_path)?
        }
    };
    keypair.write_private_key(&mut priv_key_file)?;

    let mut pub_key_file = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(&pub_key_path)?;
    keypair.write_public_key(&mut pub_key_file)?;

    println!(
        "Your identification has been saved in {}",
        priv_key_path.display()
    );
    println!(
        "Your public key has been saved in {}",
        pub_key_path.display()
    );
    println!("The key fingerprint is:");
    println!("{}", keypair.fingerprint()?);
    println!("The key's randomart image is:");
    print!("{}", keypair.randomart());

    Ok(())
}

#[cfg(target_family = "unix")]
fn create_key_dir(path: &Path) -> Result<()> {
    DirBuilder::new().mode(0o700).recursive(true).create(path)?;
    Ok(())
}

#[cfg(not(target_family = "unix"))]
fn create_key_dir(path: &Path) -> Result<()> {
    DirBuilder::new().recursive(true).create(path)?;
    Ok(())
}

fn read_passpharase() -> Result<Option<String>> {
    Password::new()
        .with_prompt("Please enter your private key passphrase")
        .report(false)
        .interact()
        .map(Some)
        .map_err(Into::into)
}

/// Returns a sanitized string identifying the current terminal, used to give each
/// terminal window its own independent session slot.
///
/// Resolves the stdin file descriptor to its TTY device path and sanitizes it for
/// use as a filename component (e.g. `/dev/pts/3` → `dev_pts_3`).  Returns `None`
/// when stdin is not a TTY (piped/scripted invocations).
#[cfg(unix)]
fn tty_id() -> Option<String> {
    use std::io::IsTerminal as _;
    if !stdin().is_terminal() {
        return None;
    }
    // Linux exposes a symlink at /proc/self/fd/0 → the actual TTY device.
    // Other Unix systems expose the same information at /dev/fd/0.
    #[cfg(target_os = "linux")]
    let link = std::fs::read_link("/proc/self/fd/0").ok()?;
    #[cfg(not(target_os = "linux"))]
    let link = std::fs::read_link("/dev/fd/0").ok()?;
    let raw = link.to_string_lossy();
    // Strip the leading slash and replace non-alphanumeric chars with '_'.
    let sanitized: String = raw
        .trim_start_matches('/')
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if sanitized.is_empty() {
        None
    } else {
        Some(sanitized)
    }
}

/// Windows equivalent: `GetConsoleWindow()` returns the HWND of the console
/// window associated with the calling process.  Like the TTY device path on
/// Unix, the HWND is:
/// - unique per console window (cmd.exe window, Windows Terminal tab, etc.)
/// - stable across process restarts within the same window
/// - different between simultaneously open windows
#[cfg(windows)]
#[allow(unsafe_code)]
fn tty_id() -> Option<String> {
    use std::io::IsTerminal as _;
    // Call Win32 GetConsoleWindow() via raw FFI — no extra crate required.
    unsafe extern "system" {
        fn GetConsoleWindow() -> *mut std::ffi::c_void;
    }
    if !stdin().is_terminal() {
        return None;
    }
    let hwnd = unsafe { GetConsoleWindow() };
    if hwnd.is_null() {
        None
    } else {
        Some(format!("{:x}", hwnd.addr()))
    }
}

#[cfg(not(any(unix, windows)))]
fn tty_id() -> Option<String> {
    None
}

fn client_id_path(home: &Path) -> PathBuf {
    home.join(".mp").join("client_id")
}

/// Returns (or creates) a stable random UUID that uniquely identifies this client
/// installation.  Written once to `~/.mp/client_id` and reused on every subsequent
/// run, so the session file for a given server can always be found regardless of the
/// current process PID.
fn client_id() -> Option<Uuid> {
    client_id_in_home(&dirs2::home_dir()?)
}

#[allow(clippy::unnecessary_wraps)]
fn client_id_in_home(home: &Path) -> Option<Uuid> {
    let path = client_id_path(home);
    if let Ok(mut f) = std::fs::File::open(&path) {
        let mut buf = String::new();
        drop(f.read_to_string(&mut buf));
        if let Ok(uuid) = buf.trim().parse::<Uuid>() {
            return Some(uuid);
        }
    }
    // First run: generate a new client ID and persist it.
    let id = Uuid::new_v4();
    if let Some(parent) = path.parent() {
        drop(std::fs::create_dir_all(parent));
    }
    if let Ok(mut f) = std::fs::File::create(&path) {
        drop(write!(f, "{id}"));
    }
    Some(id)
}

/// Returns the path `~/.mp/sessions/<client_id>_<host>_<port>[_<tty_id>]` for
/// session UUID persistence.
///
/// When stdin is a TTY the filename includes a sanitized TTY identifier (e.g.
/// `dev_pts_3`), giving each terminal window its own independent session slot.
/// Restarting after a crash in the same window reuses the same slot, enabling
/// transparent resume.  When stdin is not a TTY the TTY suffix is omitted and
/// the connection falls back to last-connect-wins semantics.
fn session_file_path(host: &str, port: u16) -> Option<PathBuf> {
    let home = dirs2::home_dir()?;
    // Sanitize host so it is safe as a file-name component.
    let safe_host: String = host
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '.' {
                c
            } else {
                '_'
            }
        })
        .collect();
    let cid = client_id()?;
    let name = match tty_id() {
        Some(tty) => format!("{cid}_{safe_host}_{port}_{tty}"),
        None => format!("{cid}_{safe_host}_{port}"),
    };
    Some(home.join(".mp").join("sessions").join(name))
}

#[cfg(test)]
fn session_file_path_in_home(home: &Path, host: &str, port: u16) -> Option<PathBuf> {
    // Sanitize host so it is safe as a file-name component.
    let safe_host: String = host
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '.' {
                c
            } else {
                '_'
            }
        })
        .collect();
    let cid = client_id_in_home(home)?;
    let name = match tty_id() {
        Some(tty) => format!("{cid}_{safe_host}_{port}_{tty}"),
        None => format!("{cid}_{safe_host}_{port}"),
    };
    Some(home.join(".mp").join("sessions").join(name))
}

fn read_uuid_from_path(path: &Path) -> Option<Uuid> {
    let mut file = std::fs::File::open(path).ok()?;
    let mut buf = String::new();
    let _ = file.read_to_string(&mut buf).ok();
    buf.trim().parse::<Uuid>().ok()
}

fn write_uuid_to_path(path: &Path, uuid: Uuid) -> Result<()> {
    if let Some(parent) = path.parent() {
        #[cfg(unix)]
        {
            DirBuilder::new()
                .mode(0o700)
                .recursive(true)
                .create(parent)?;
        }
        #[cfg(not(unix))]
        {
            DirBuilder::new().recursive(true).create(parent)?;
        }
    }
    let mut file = {
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .mode(0o600)
                .open(path)?
        }
        #[cfg(not(unix))]
        {
            std::fs::File::create(path)?
        }
    };
    write!(file, "{uuid}")?;
    Ok(())
}

/// Read a persisted session UUID from disk, if any.
fn read_session_uuid(host: &str, port: u16) -> Option<Uuid> {
    read_uuid_from_path(&session_file_path(host, port)?)
}

/// Write (or overwrite) the session UUID to disk.
fn write_session_uuid(host: &str, port: u16, session_uuid: Uuid) -> Result<()> {
    let path = session_file_path(host, port).ok_or_else(|| anyhow::anyhow!("no home dir"))?;
    write_uuid_to_path(&path, session_uuid)
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    struct TestHome {
        path: PathBuf,
    }

    impl TestHome {
        fn new() -> Self {
            let path = std::env::temp_dir().join(Uuid::new_v4().to_string());
            std::fs::create_dir_all(&path).expect("failed to create temp dir");
            Self { path }
        }

        fn path(&self) -> &Path {
            &self.path
        }
    }

    impl Drop for TestHome {
        fn drop(&mut self) {
            drop(std::fs::remove_dir_all(&self.path));
        }
    }

    #[test]
    fn test_pass_cache() {
        let mut cache = PassCache::Uncached;
        assert!(!cache.is_cached());

        cache = PassCache::NoPassphrase;
        assert!(cache.is_cached());
        assert_eq!(cache.passphrase(), None);

        cache = PassCache::Passphrase("secret".to_string());
        assert!(cache.is_cached());
        assert_eq!(cache.passphrase(), Some("secret".to_string()));
    }

    #[test]
    #[should_panic(expected = "passphrase() called before caching")]
    fn test_pass_cache_panic() {
        let cache = PassCache::Uncached;
        drop(cache.passphrase());
    }

    #[tokio::test]
    async fn test_banners() -> Result<()> {
        let (tx, mut rx) = channel(10);
        show_reconnect_banner(&tx).await;
        let msg = rx
            .recv()
            .await
            .ok_or_else(|| anyhow::anyhow!("channel closed"))?;
        assert!(
            String::from_utf8_lossy(&msg).contains("[moshpit] server unreachable, reconnecting...")
        );

        clear_reconnect_banner(&tx).await;
        let msg = rx
            .recv()
            .await
            .ok_or_else(|| anyhow::anyhow!("channel closed"))?;
        assert!(String::from_utf8_lossy(&msg).ends_with("\x1b[0m\x1b[K\x1b[u"));

        let token = CancellationToken::new();
        let _ = countdown_reconnect_banner(&tx, 0, 1, 10, &token).await;
        let msg = rx
            .recv()
            .await
            .ok_or_else(|| anyhow::anyhow!("channel closed"))?;
        assert!(String::from_utf8_lossy(&msg).contains("attempt #1"));
        Ok(())
    }

    #[tokio::test]
    async fn countdown_banner_pre_cancelled_returns_true() {
        let (tx, mut _rx) = channel(10);
        let token = CancellationToken::new();
        token.cancel();
        let result = countdown_reconnect_banner(&tx, 0, 1, 10, &token).await;
        assert!(result);
    }

    #[test]
    fn read_uuid_from_path_missing_file_returns_none() {
        let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
        let path = dir.join("session");
        assert!(read_uuid_from_path(&path).is_none());
    }

    #[test]
    fn read_uuid_from_path_garbage_returns_none() {
        let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
        std::fs::create_dir_all(&dir).expect("failed to create temp dir");
        let path = dir.join("session");
        std::fs::write(&path, "not-a-uuid").expect("failed to write test file");
        assert!(read_uuid_from_path(&path).is_none());
    }

    #[test]
    fn write_and_read_uuid_roundtrip() -> Result<()> {
        let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
        let path = dir.join("sub").join("session");
        let uuid = Uuid::new_v4();
        write_uuid_to_path(&path, uuid)?;
        assert_eq!(read_uuid_from_path(&path), Some(uuid));
        Ok(())
    }

    #[test]
    fn write_uuid_creates_parent_directories() -> Result<()> {
        let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
        let nested = dir.join("a").join("b").join("c").join("session");
        let uuid = Uuid::new_v4();
        write_uuid_to_path(&nested, uuid)?;
        assert!(nested.exists());
        Ok(())
    }

    #[test]
    fn client_id_path_is_under_dot_mp() {
        let home = TestHome::new();
        let path = client_id_path(home.path());
        assert!(path.starts_with(home.path().join(".mp")));
        assert_eq!(path.file_name().expect("path has a file name"), "client_id");
    }

    #[test]
    fn test_client_id() {
        let home = TestHome::new();
        let id1 = client_id_in_home(home.path());
        assert!(id1.is_some());
        let id2 = client_id_in_home(home.path());
        assert_eq!(id1, id2); // Should read the same from disk
    }

    #[test]
    fn test_session_uuid_persistence() -> Result<()> {
        let home = TestHome::new();
        let host = "test.host";
        let port = 12345;
        let uuid = Uuid::new_v4();

        // Write it
        let path = session_file_path_in_home(home.path(), host, port)
            .ok_or_else(|| anyhow::anyhow!("no session file path"))?;
        if let Some(parent) = path.parent() {
            DirBuilder::new().recursive(true).create(parent)?;
        }
        std::fs::write(&path, uuid.to_string())?;

        // Read it back
        let read_uuid = {
            let mut file = std::fs::File::open(&path)?;
            let mut buf = String::new();
            let _ = file.read_to_string(&mut buf)?;
            buf.trim().parse::<Uuid>()?
        };
        assert_eq!(uuid, read_uuid);
        Ok(())
    }

    #[test]
    fn test_session_file_path() -> Result<()> {
        let home = TestHome::new();
        let host = "some_host.com";
        let port = 2222;
        let path = session_file_path_in_home(home.path(), host, port)
            .ok_or_else(|| anyhow::anyhow!("no session file path"))?;
        assert!(path.to_string_lossy().contains("some_host.com"));
        assert!(path.to_string_lossy().contains("2222"));
        Ok(())
    }

    #[test]
    fn test_create_key_dir() -> Result<()> {
        let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
        let key_dir = dir.join("keys");
        create_key_dir(&key_dir)?;
        assert!(key_dir.exists());
        assert!(key_dir.is_dir());
        Ok(())
    }

    #[test]
    fn test_maybe_generate_keypair_existing() -> Result<()> {
        let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
        std::fs::create_dir_all(&dir)?;
        let priv_path = dir.join("id_ed25519");
        let pub_path = dir.join("id_ed25519.pub");
        let config_path = dir.join("config.toml");

        std::fs::write(&priv_path, "fake private key")?;
        std::fs::write(&pub_path, "fake public key")?;
        std::fs::write(
            &config_path,
            "[tracing.stdout]\n\
             with_target = false\n\
             with_thread_ids = false\n\
             with_thread_names = false\n\
             with_line_number = false\n\
             with_level = false\n\
             [tracing.file]\n\
             quiet = 0\n\
             verbose = 0\n\
             [tracing.file.layer]\n\
             with_target = false\n\
             with_thread_ids = false\n\
             with_thread_names = false\n\
             with_line_number = false\n\
             with_level = false\n",
        )?;

        let cli = Cli::try_parse_from([
            "moshpit",
            "-c",
            config_path.to_str().expect("path is valid UTF-8"),
            "-p",
            priv_path.to_str().expect("path is valid UTF-8"),
            "-k",
            pub_path.to_str().expect("path is valid UTF-8"),
            "user@host",
        ])?;
        let config = load::<Cli, Config, Cli>(&cli, &cli)?;

        // Should return Ok(()) immediately without prompting
        let result = maybe_generate_keypair(&config);
        assert!(result.is_ok());
        Ok(())
    }

    #[tokio::test]
    async fn test_connect_and_kex_tcp_failure() -> Result<()> {
        let mut config = Config::default();
        let pass_cache = Arc::new(std::sync::Mutex::new(PassCache::Uncached));

        // Bind to a random port and immediately close it
        let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
        let port = listener.local_addr()?.port();
        drop(listener);

        let addr = format!("127.0.0.1:{port}").parse()?;

        // This should fail with ConnectionRefused
        let result = connect_and_kex(
            &mut config,
            addr,
            "127.0.0.1",
            port,
            &pass_cache,
            Arc::new(AtomicBool::new(false)),
        )
        .await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .to_lowercase()
                .contains("refused")
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_connect_and_kex_kex_failure() -> Result<()> {
        let dir = std::env::temp_dir().join(Uuid::new_v4().to_string());
        std::fs::create_dir_all(&dir)?;
        let config_path = dir.join("config.toml");
        // Empty key files: /dev/null doesn't exist on Windows, so create real empty files.
        let empty_priv_key_path = dir.join("empty_priv_key");
        let empty_pub_key_path = dir.join("empty_pub_key");
        std::fs::write(&empty_priv_key_path, b"")?;
        std::fs::write(&empty_pub_key_path, b"")?;
        std::fs::write(
            &config_path,
            "[tracing.stdout]\n\
             with_target = false\n\
             with_thread_ids = false\n\
             with_thread_names = false\n\
             with_line_number = false\n\
             with_level = false\n\
             [tracing.file]\n\
             quiet = 0\n\
             verbose = 0\n\
             [tracing.file.layer]\n\
             with_target = false\n\
             with_thread_ids = false\n\
             with_thread_names = false\n\
             with_line_number = false\n\
             with_level = false\n",
        )?;
        let cli = Cli::try_parse_from([
            "moshpit",
            "-c",
            config_path.to_str().expect("test path is valid UTF-8"),
            "-p",
            empty_priv_key_path
                .to_str()
                .expect("test path is valid UTF-8"),
            "-k",
            empty_pub_key_path
                .to_str()
                .expect("test path is valid UTF-8"),
            "user@host",
        ])?;
        let mut config = load::<Cli, Config, Cli>(&cli, &cli)?;

        let pass_cache = Arc::new(std::sync::Mutex::new(PassCache::Uncached));

        // Bind a real listener
        let listener = match tokio::net::TcpListener::bind("127.0.0.1:0").await {
            Ok(listener) => listener,
            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => return Ok(()),
            Err(e) => return Err(e.into()),
        };
        let port = listener.local_addr()?.port();

        // Spawn a task to accept the connection and send the greeting, then drop
        drop(spawn(async move {
            use tokio::io::AsyncWriteExt;
            if let Ok((mut socket, _)) = listener.accept().await {
                drop(socket.write_all(b"SSH-2.0-Moshpit\r\n").await);
            }
        }));

        let addr = format!("127.0.0.1:{port}").parse()?;

        // TcpStream::connect will succeed, but run_key_exchange will fail
        let result = connect_and_kex(
            &mut config,
            addr,
            "127.0.0.1",
            port,
            &pass_cache,
            Arc::new(AtomicBool::new(false)),
        )
        .await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.downcast_ref::<FatalKexError>().is_some(),
            "empty key files should produce FatalKexError, got: {err}"
        );
        Ok(())
    }

    #[test]
    fn fatal_kex_error_display_includes_error_and_path() {
        use libmoshpit::MoshpitError;
        let key_path = PathBuf::from("/home/user/.mp/id_ed25519");
        let fatal = FatalKexError {
            inner: MoshpitError::KeyFileMissing,
            key_path: key_path.clone(),
        };
        let display = format!("{fatal}");
        assert!(
            display.contains("Key file not found"),
            "display should contain error message, got: {display}"
        );
        assert!(
            display.contains("/home/user/.mp/id_ed25519"),
            "display should contain key path, got: {display}"
        );
    }

    #[tokio::test]
    async fn connect_and_kex_missing_key_file_wrapped_as_fatal_error() -> Result<()> {
        use clap::Parser as _;
        let home = TestHome::new();
        let config_path = home.path().join("config.toml");
        // Non-existent key paths
        let priv_path = home.path().join("nonexistent_id_ed25519");
        let pub_path = home.path().join("nonexistent_id_ed25519.pub");
        std::fs::write(
            &config_path,
            "[tracing.stdout]\n\
             with_target = false\n\
             with_thread_ids = false\n\
             with_thread_names = false\n\
             with_line_number = false\n\
             with_level = false\n\
             [tracing.file]\n\
             quiet = 0\n\
             verbose = 0\n\
             [tracing.file.layer]\n\
             with_target = false\n\
             with_thread_ids = false\n\
             with_thread_names = false\n\
             with_line_number = false\n\
             with_level = false\n",
        )?;
        let cli = Cli::try_parse_from([
            "moshpit",
            "-c",
            config_path.to_str().expect("path is valid UTF-8"),
            "-p",
            priv_path.to_str().expect("path is valid UTF-8"),
            "-k",
            pub_path.to_str().expect("path is valid UTF-8"),
            "user@host",
        ])?;
        let mut config = load::<Cli, Config, Cli>(&cli, &cli)?;
        let pass_cache = Arc::new(std::sync::Mutex::new(PassCache::Uncached));

        // Bind a real listener so TCP connection succeeds
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let port = listener.local_addr()?.port();
        drop(spawn(async move {
            if let Ok((_, _)) = listener.accept().await {}
        }));

        let addr = format!("127.0.0.1:{port}").parse()?;
        let result = connect_and_kex(
            &mut config,
            addr,
            "127.0.0.1",
            port,
            &pass_cache,
            Arc::new(AtomicBool::new(false)),
        )
        .await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.downcast_ref::<FatalKexError>().is_some(),
            "missing key file should produce FatalKexError, got: {err}"
        );
        Ok(())
    }

    // crossterm's Unix parser maps 0x1C-0x1F bytes to Char('4'-'7') + CONTROL.
    // Verify that encode_char_key round-trips these correctly on all platforms.
    #[test]
    fn ctrl_digit_aliases_produce_correct_control_codes() {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};

        fn ctrl_char(c: char) -> KeyEvent {
            KeyEvent {
                code: KeyCode::Char(c),
                modifiers: KeyModifiers::CONTROL,
                kind: KeyEventKind::Press,
                state: KeyEventState::empty(),
            }
        }

        // Ctrl+6 (crossterm Unix: 0x1E → Char('6') + CONTROL) — escape prefix
        assert_eq!(key_event_to_bytes(ctrl_char('6')), b"\x1e");
        // Ctrl+4 (0x1C), Ctrl+5 (0x1D), Ctrl+7 (0x1F)
        assert_eq!(key_event_to_bytes(ctrl_char('4')), b"\x1c");
        assert_eq!(key_event_to_bytes(ctrl_char('5')), b"\x1d");
        assert_eq!(key_event_to_bytes(ctrl_char('7')), b"\x1f");
    }

    mod escape_listener {
        use std::sync::Arc;
        use tokio::sync::Mutex;
        use tokio::sync::mpsc::channel;
        use tokio_util::sync::CancellationToken;

        use super::super::run_escape_listener;

        #[tokio::test]
        async fn done_token_cancels_listener_without_triggering_exit() {
            let (tx, rx) = channel::<Vec<u8>>(8);
            let kb_rx = Arc::new(Mutex::new(rx));
            let exit_token = CancellationToken::new();
            let done_token = CancellationToken::new();
            done_token.cancel();
            run_escape_listener(kb_rx, exit_token.clone(), done_token).await;
            assert!(!exit_token.is_cancelled());
            drop(tx);
        }

        #[tokio::test]
        async fn sender_drop_stops_listener_without_triggering_exit() {
            let (tx, rx) = channel::<Vec<u8>>(8);
            let kb_rx = Arc::new(Mutex::new(rx));
            let exit_token = CancellationToken::new();
            let done_token = CancellationToken::new();
            drop(tx);
            run_escape_listener(kb_rx, exit_token.clone(), done_token).await;
            assert!(!exit_token.is_cancelled());
        }

        #[tokio::test]
        async fn normal_bytes_do_not_trigger_exit() -> anyhow::Result<()> {
            let (tx, rx) = channel::<Vec<u8>>(8);
            let kb_rx = Arc::new(Mutex::new(rx));
            let exit_token = CancellationToken::new();
            let done_token = CancellationToken::new();
            tx.send(b"hello".to_vec()).await?;
            drop(tx);
            run_escape_listener(kb_rx, exit_token.clone(), done_token).await;
            assert!(!exit_token.is_cancelled());
            Ok(())
        }

        #[tokio::test]
        async fn escape_prefix_then_non_dot_does_not_trigger_exit() -> anyhow::Result<()> {
            let (tx, rx) = channel::<Vec<u8>>(8);
            let kb_rx = Arc::new(Mutex::new(rx));
            let exit_token = CancellationToken::new();
            let done_token = CancellationToken::new();
            // 0x1E followed by 'x' — state resets to Normal
            tx.send(vec![0x1E, b'x']).await?;
            drop(tx);
            run_escape_listener(kb_rx, exit_token.clone(), done_token).await;
            assert!(!exit_token.is_cancelled());
            Ok(())
        }

        #[tokio::test]
        async fn repeated_escape_prefix_stays_pending_without_triggering_exit() -> anyhow::Result<()>
        {
            let (tx, rx) = channel::<Vec<u8>>(8);
            let kb_rx = Arc::new(Mutex::new(rx));
            let exit_token = CancellationToken::new();
            let done_token = CancellationToken::new();
            // Multiple 0x1E bytes — stays in PendingDot but never completes
            tx.send(vec![0x1E, 0x1E, 0x1E]).await?;
            drop(tx);
            run_escape_listener(kb_rx, exit_token.clone(), done_token).await;
            assert!(!exit_token.is_cancelled());
            Ok(())
        }

        #[tokio::test]
        async fn full_sequence_in_one_chunk_triggers_exit() -> anyhow::Result<()> {
            let (tx, rx) = channel::<Vec<u8>>(8);
            let kb_rx = Arc::new(Mutex::new(rx));
            let exit_token = CancellationToken::new();
            let done_token = CancellationToken::new();
            tx.send(vec![0x1E, 0x2E]).await?;
            run_escape_listener(kb_rx, exit_token.clone(), done_token).await;
            assert!(exit_token.is_cancelled());
            Ok(())
        }

        #[tokio::test]
        async fn sequence_split_across_sends_triggers_exit() -> anyhow::Result<()> {
            let (tx, rx) = channel::<Vec<u8>>(8);
            let kb_rx = Arc::new(Mutex::new(rx));
            let exit_token = CancellationToken::new();
            let done_token = CancellationToken::new();
            tx.send(vec![0x1E]).await?;
            tx.send(vec![0x2E]).await?;
            run_escape_listener(kb_rx, exit_token.clone(), done_token).await;
            assert!(exit_token.is_cancelled());
            Ok(())
        }
    }

    mod key_encoding {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};

        use super::super::key_event_to_bytes;

        fn press(code: KeyCode) -> KeyEvent {
            KeyEvent {
                code,
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: KeyEventState::empty(),
            }
        }

        fn press_mod(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
            KeyEvent {
                code,
                modifiers: mods,
                kind: KeyEventKind::Press,
                state: KeyEventState::empty(),
            }
        }

        fn release(code: KeyCode) -> KeyEvent {
            KeyEvent {
                code,
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Release,
                state: KeyEventState::empty(),
            }
        }

        #[test]
        fn release_events_produce_no_bytes() {
            assert!(key_event_to_bytes(release(KeyCode::Char('a'))).is_empty());
            assert!(key_event_to_bytes(release(KeyCode::Up)).is_empty());
        }

        #[test]
        fn arrow_keys_produce_csi_sequences() {
            assert_eq!(key_event_to_bytes(press(KeyCode::Up)), b"\x1b[A");
            assert_eq!(key_event_to_bytes(press(KeyCode::Down)), b"\x1b[B");
            assert_eq!(key_event_to_bytes(press(KeyCode::Right)), b"\x1b[C");
            assert_eq!(key_event_to_bytes(press(KeyCode::Left)), b"\x1b[D");
        }

        #[test]
        fn arrow_keys_with_shift_use_modifier_param() {
            let shift = KeyModifiers::SHIFT;
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Up, shift)),
                b"\x1b[1;2A"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Down, shift)),
                b"\x1b[1;2B"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Right, shift)),
                b"\x1b[1;2C"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Left, shift)),
                b"\x1b[1;2D"
            );
        }

        #[test]
        fn arrow_keys_with_ctrl_use_modifier_param() {
            let ctrl = KeyModifiers::CONTROL;
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Up, ctrl)),
                b"\x1b[1;5A"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Left, ctrl)),
                b"\x1b[1;5D"
            );
        }

        #[test]
        fn navigation_keys() {
            assert_eq!(key_event_to_bytes(press(KeyCode::Home)), b"\x1b[H");
            assert_eq!(key_event_to_bytes(press(KeyCode::End)), b"\x1b[F");
            assert_eq!(key_event_to_bytes(press(KeyCode::Insert)), b"\x1b[2~");
            assert_eq!(key_event_to_bytes(press(KeyCode::Delete)), b"\x1b[3~");
            assert_eq!(key_event_to_bytes(press(KeyCode::PageUp)), b"\x1b[5~");
            assert_eq!(key_event_to_bytes(press(KeyCode::PageDown)), b"\x1b[6~");
        }

        #[test]
        fn navigation_keys_with_modifier() {
            let ctrl = KeyModifiers::CONTROL;
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Home, ctrl)),
                b"\x1b[1;5H"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::End, ctrl)),
                b"\x1b[1;5F"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Insert, ctrl)),
                b"\x1b[2;5~"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Delete, ctrl)),
                b"\x1b[3;5~"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::PageUp, ctrl)),
                b"\x1b[5;5~"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::PageDown, ctrl)),
                b"\x1b[6;5~"
            );
        }

        #[test]
        fn function_keys() {
            assert_eq!(key_event_to_bytes(press(KeyCode::F(1))), b"\x1bOP");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(2))), b"\x1bOQ");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(3))), b"\x1bOR");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(4))), b"\x1bOS");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(5))), b"\x1b[15~");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(6))), b"\x1b[17~");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(7))), b"\x1b[18~");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(8))), b"\x1b[19~");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(9))), b"\x1b[20~");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(10))), b"\x1b[21~");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(11))), b"\x1b[23~");
            assert_eq!(key_event_to_bytes(press(KeyCode::F(12))), b"\x1b[24~");
        }

        #[test]
        fn function_keys_out_of_range_produce_no_bytes() {
            assert!(key_event_to_bytes(press(KeyCode::F(0))).is_empty());
            assert!(key_event_to_bytes(press(KeyCode::F(13))).is_empty());
        }

        #[test]
        fn function_keys_with_modifier() {
            let shift = KeyModifiers::SHIFT;
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::F(1), shift)),
                b"\x1b[1;2P"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::F(5), shift)),
                b"\x1b[15;2~"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::F(12), shift)),
                b"\x1b[24;2~"
            );
        }

        #[test]
        fn simple_keys() {
            assert_eq!(key_event_to_bytes(press(KeyCode::Backspace)), b"\x7f");
            assert_eq!(key_event_to_bytes(press(KeyCode::Enter)), b"\r");
            assert_eq!(key_event_to_bytes(press(KeyCode::Tab)), b"\t");
            assert_eq!(key_event_to_bytes(press(KeyCode::BackTab)), b"\x1b[Z");
            assert_eq!(key_event_to_bytes(press(KeyCode::Esc)), b"\x1b");
            assert_eq!(key_event_to_bytes(press(KeyCode::Null)), b"\x00");
        }

        #[test]
        fn printable_chars() {
            assert_eq!(key_event_to_bytes(press(KeyCode::Char('a'))), b"a");
            assert_eq!(key_event_to_bytes(press(KeyCode::Char('Z'))), b"Z");
            assert_eq!(key_event_to_bytes(press(KeyCode::Char('!'))), b"!");
        }

        #[test]
        fn non_ascii_char_encodes_utf8() {
            assert_eq!(
                key_event_to_bytes(press(KeyCode::Char('\u{00e9}'))), // é
                "\u{00e9}".as_bytes()
            );
        }

        #[test]
        fn ctrl_chars_produce_control_codes() {
            let ctrl = KeyModifiers::CONTROL;
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Char('a'), ctrl)),
                b"\x01"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Char('c'), ctrl)),
                b"\x03"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Char('z'), ctrl)),
                b"\x1a"
            );
            // Ctrl-@ → NUL (0x00)
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Char('@'), ctrl)),
                b"\x00"
            );
            // Ctrl-[ → ESC (0x1B)
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Char('['), ctrl)),
                b"\x1b"
            );
            // Ctrl-^ is the moshpit escape prefix
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Char('^'), ctrl)),
                b"\x1e"
            );
        }

        #[test]
        fn ctrl_non_ascii_encodes_utf8_fallback() {
            let ctrl = KeyModifiers::CONTROL;
            // Non-ASCII + Ctrl has no standard control code; falls through to UTF-8
            let result = key_event_to_bytes(press_mod(KeyCode::Char('\u{00e9}'), ctrl));
            assert_eq!(result, "\u{00e9}".as_bytes());
        }

        #[test]
        fn alt_chars_prefix_with_escape() {
            let alt = KeyModifiers::ALT;
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Char('a'), alt)),
                b"\x1ba"
            );
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Char('z'), alt)),
                b"\x1bz"
            );
        }

        #[test]
        fn ctrl_alt_chars_prefix_with_escape_and_control_code() {
            let ctrl_alt = KeyModifiers::CONTROL | KeyModifiers::ALT;
            // Ctrl+Alt+a → ESC + 0x01
            assert_eq!(
                key_event_to_bytes(press_mod(KeyCode::Char('a'), ctrl_alt)),
                b"\x1b\x01"
            );
        }

        #[test]
        fn ctrl_alt_non_ascii_utf8_fallback() {
            let ctrl_alt = KeyModifiers::CONTROL | KeyModifiers::ALT;
            // Non-ASCII + Ctrl+Alt falls through to UTF-8 with ESC prefix
            let result = key_event_to_bytes(press_mod(KeyCode::Char('\u{00e9}'), ctrl_alt));
            let mut expected = b"\x1b".to_vec();
            expected.extend_from_slice("\u{00e9}".as_bytes());
            assert_eq!(result, expected);
        }
    }
}