moshpit 0.15.0

moshpit client (mp) — encrypted, resilient remote terminal session client
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
// 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::{collections::BTreeSet, ffi::OsString, io::Cursor, sync::LazyLock};

use clap::{ArgMatches, CommandFactory, Parser, Subcommand, parser::ValueSource};
use config::{ConfigError, Map, Source, Value, ValueKind};
use getset::{CopyGetters, Getters};
use libmoshpit::PathDefaults;
use vergen_pretty::{Pretty, vergen_pretty_env};

static LONG_VERSION: LazyLock<String> = LazyLock::new(|| {
    let pretty = Pretty::builder().env(vergen_pretty_env!()).build();
    let mut cursor = Cursor::new(vec![]);
    let mut output = env!("CARGO_PKG_VERSION").to_string();
    output.push_str("\n\n");
    pretty
        .display(&mut cursor)
        .expect("writing to Vec never fails");
    output += &String::from_utf8_lossy(cursor.get_ref());
    output
});

/// Client subcommands.  When absent, `mp` runs the connect flow against the
/// `server_destination` positional.
#[derive(Clone, Debug, Subcommand)]
pub(crate) enum Commands {
    /// Print the fully-resolved effective configuration and the source of each value.
    ///
    /// Resolution flags (`-c`, `-t`, `-p`, `-k`, value flags, …) must be supplied
    /// before the subcommand, e.g. `mp -c /path/to/config.toml ec`.
    Ec {
        /// Emit machine-readable JSON instead of a colored table.
        #[clap(long, help = "Emit machine-readable JSON instead of a table")]
        json: bool,
    },
    /// List or terminate sessions on a moshpits server.
    Sessions {
        #[command(subcommand)]
        action: SessionsAction,
    },
}

/// `mp sessions` subcommands.
#[derive(Clone, Debug, Subcommand)]
pub(crate) enum SessionsAction {
    /// List the authenticated user's live sessions on a server.
    List {
        /// The destination of the server to query: user@host[:port].
        #[clap(help = "The destination of the server to query: user@host[:port]")]
        destination: String,
    },
    /// Terminate one of the authenticated user's own sessions by name.
    Kill {
        /// The destination of the server: user@host[:port].
        #[clap(help = "The destination of the server: user@host[:port]")]
        destination: String,
        /// The session's display name, as shown by `mp sessions list`.
        #[clap(help = "The session's display name, as shown by `mp sessions list`")]
        name: String,
    },
}

#[derive(Clone, CopyGetters, Debug, Getters, Parser)]
#[command(author, version, about, long_version = LONG_VERSION.as_str(), long_about = None)]
#[allow(clippy::struct_excessive_bools)]
pub(crate) struct Cli {
    /// Optional subcommand.  When `None`, the connect flow runs.
    #[command(subcommand)]
    #[getset(get = "pub(crate)")]
    command: Option<Commands>,
    /// The absolute path to a non-standard config file
    #[clap(short, long, help = "Specify the absolute path to the config file")]
    #[getset(get = "pub(crate)")]
    config_absolute_path: Option<String>,
    /// The absolute path to a non-standard tracing output file
    #[clap(
        short,
        long,
        help = "Specify the absolute path to the tracing output file"
    )]
    #[getset(get = "pub(crate)")]
    tracing_absolute_path: Option<String>,
    /// An absolute path to a non-standard private key file
    #[clap(
        short,
        long,
        help = "Specify the absolute path to the private key file"
    )]
    #[getset(get = "pub(crate)")]
    private_key_path: Option<String>,
    /// An absolute path to a non-standard public key file
    #[clap(
        short = 'k',
        long,
        help = "Specify the absolute path to the public key file"
    )]
    #[getset(get = "pub(crate)")]
    public_key_path: Option<String>,
    /// An optional port number for the server to connect to
    /// defaults to 40404
    #[clap(
        short,
        long,
        help = "The port number of the server to connect to (default: 40404)",
        default_value_t = 40404
    )]
    #[getset(get_copy = "pub(crate)")]
    server_port: u16,
    /// The destination of the server to connect to
    /// This takes the form of 'user@host[:port]' where the user is optional
    /// and will default to the user executing the command. Host may be a
    /// hostname, an IPv4 literal, or a bracketed IPv6 literal (e.g. `[::1]`
    /// or `[::1]:2222`) — IPv6 literals always require brackets.
    ///
    /// Optional at the parse level so subcommands (e.g. `ec`) can run without a
    /// destination; the connect flow validates that it is present.
    #[clap(
        help = "The destination of the server to connect to: user@host[:port]. Host may be a \
                hostname, an IPv4 literal, or a bracketed IPv6 literal (e.g. [::1] or [::1]:2222)"
    )]
    #[getset(get = "pub(crate)")]
    server_destination: Option<String>,
    /// Local-echo prediction preference: adaptive (default), always, or never.
    #[clap(
        long,
        value_name = "MODE",
        default_value = "adaptive",
        help = "Local-echo prediction: adaptive (default), always, or never"
    )]
    #[getset(get = "pub(crate)")]
    predict: String,
    /// Send warmup keepalives before the UDP session starts to establish
    /// a bidirectional NAT binding before bulk terminal data flows.
    /// Only useful on NAT paths; adds one round-trip of startup latency.
    #[clap(
        long,
        help = "Send NAT warmup keepalives at UDP session start (opt-in)"
    )]
    #[getset(get_copy = "pub(crate)")]
    nat_warmup: bool,
    /// Number of keepalive frames to send during NAT warmup (default: 3).
    #[clap(
        long,
        value_name = "N",
        default_value_t = 3,
        help = "Number of NAT warmup keepalives to send (default: 3)"
    )]
    #[getset(get_copy = "pub(crate)")]
    nat_warmup_count: u32,
    /// Diff transport mode.
    ///
    /// `auto` (default): pick the best mode for the transport — `statesync` over
    /// TCP (incremental diffs keep server CPU low) and `reliable` over UDP.
    ///
    /// `reliable`: NAK-based selective retransmission — best for low-loss
    /// networks where retransmit rarely fires.
    ///
    /// `datagram`: fire-and-forget diffs with no retransmission; the server
    /// sends a periodic full-screen snapshot for recovery instead.  Eliminates
    /// head-of-line blocking on flaky or high-loss connections.
    ///
    /// `statesync`: Mosh-style ack-based diffs; the server always sends
    /// `contents_diff(ack_state → current)` so each packet is self-contained.
    /// No NAKs, no reorder buffer.  Best for moderate-loss, low-bandwidth links.
    #[clap(
        long,
        value_name = "MODE",
        default_value = "auto",
        help = "Diff mode: auto (statesync over TCP, reliable over UDP), reliable, datagram, or statesync"
    )]
    #[getset(get = "pub(crate)")]
    diff_mode: String,
    /// Legacy escape hatch: forward raw server PTY bytes straight to the
    /// terminal instead of rendering exclusively through the differential
    /// renderer.  Off by default; enable only if the rendered path regresses.
    #[clap(
        long,
        help = "Forward raw server bytes to the terminal (legacy; disables unified rendering)"
    )]
    #[getset(get_copy = "pub(crate)")]
    legacy_passthrough: bool,
    /// Disable the one-time real-terminal color probe (OSC 10/11) done at session
    /// startup.  On by default; use this if a terminal answers the probe
    /// incorrectly or hangs — falls back to the hardcoded canned theme.
    #[clap(
        long,
        help = "Disable local terminal color probing (use hardcoded default colors)"
    )]
    #[getset(get_copy = "pub(crate)")]
    no_color_probe: bool,
    /// Data-channel transport mode.  `udp` (default) uses encrypted UDP datagrams;
    /// `tcp` connects to the server's TCP data port (fallback for UDP-blocking firewalls).
    /// Requires the server to have `allow_tcp_transport = true` in its config.
    #[clap(
        long,
        value_name = "MODE",
        default_value = "udp",
        help = "Data-channel transport: udp (default) or tcp"
    )]
    #[getset(get = "pub(crate)")]
    transport: String,
    /// Ordered KEX algorithms to offer (comma-separated).
    /// Example: `--kex-algos ml-kem-768-sha256,x25519-sha256`
    #[clap(
        long,
        value_name = "ALGOS",
        help = "Ordered KEX algorithms to offer, comma-separated [supported: x25519-sha256 (default), ml-kem-768-sha256, ml-kem-512-sha256, ml-kem-1024-sha256, p384-sha384, p256-sha256]"
    )]
    #[getset(get = "pub(crate)")]
    kex_algos: Option<String>,
    /// Ordered AEAD algorithms to offer (comma-separated).
    /// Example: `--aead-algos chacha20-poly1305,aes256-gcm-siv`
    #[clap(
        long,
        value_name = "ALGOS",
        help = "Ordered AEAD algorithms to offer, comma-separated [supported: aes256-gcm-siv (default), aes256-gcm, chacha20-poly1305, aes128-gcm-siv]"
    )]
    #[getset(get = "pub(crate)")]
    aead_algos: Option<String>,
    /// Ordered MAC algorithms to offer (comma-separated).
    /// Example: `--mac-algos hmac-sha256`
    #[clap(
        long,
        value_name = "ALGOS",
        help = "Ordered MAC algorithms to offer, comma-separated [supported: hmac-sha512 (default), hmac-sha256]"
    )]
    #[getset(get = "pub(crate)")]
    mac_algos: Option<String>,
    /// Ordered KDF algorithms to offer (comma-separated).
    /// Example: `--kdf-algos hkdf-sha512`
    #[clap(
        long,
        value_name = "ALGOS",
        help = "Ordered KDF algorithms to offer, comma-separated [supported: hkdf-sha256 (default), hkdf-sha384, hkdf-sha512]"
    )]
    #[getset(get = "pub(crate)")]
    kdf_algos: Option<String>,
    /// Force-quit escape prefix key, e.g. `ctrl-^` (default).  Pressed and then
    /// followed by `.` to disconnect.
    #[clap(
        long,
        value_name = "KEY",
        help = "Force-quit prefix key, e.g. ctrl-^ (default), ctrl-a, ctrl-] — combined with . to quit"
    )]
    #[getset(get = "pub(crate)")]
    escape_key: Option<String>,
    /// Ignore any session cached for this terminal and start a brand-new
    /// session instead of resuming it. One-shot: applies to this invocation's
    /// first connect attempt only — automatic reconnects afterward resume the
    /// newly-created session normally. Not part of the persistent config
    /// (never routed through [`Source::collect`]) — see `mp sessions list` to
    /// find the abandoned session's name if it needs to be cleaned up with
    /// `mp sessions kill`.
    #[clap(
        long,
        conflicts_with = "attach",
        help = "Start a brand-new session, ignoring any session cached for this terminal"
    )]
    #[getset(get_copy = "pub(crate)")]
    force_new_session: bool,
    /// Attach to a specific session by its display name (see `mp sessions
    /// list`) instead of the UUID cached for this terminal. One-shot, same
    /// scope as `force_new_session`. Not part of the persistent config.
    #[clap(
        long,
        value_name = "NAME",
        conflicts_with = "force_new_session",
        help = "Attach to a session by name instead of the one cached for this terminal (see `mp sessions list`)"
    )]
    #[getset(get = "pub(crate)")]
    attach: Option<String>,
    /// Display name to request for a brand-new session (see `mp sessions
    /// list`). Ignored when resuming an existing session. Not part of the
    /// persistent config.
    #[clap(
        long,
        value_name = "NAME",
        conflicts_with = "attach",
        help = "Display name for a new session (see `mp sessions list`); ignored when resuming"
    )]
    #[getset(get = "pub(crate)")]
    session_name: Option<String>,
    /// Command to run on the server instead of the login shell, given after
    /// `--` (e.g. `mp host -- tmux new -A -s main`).  The arguments are joined
    /// with spaces and run by the remote login shell as `$SHELL -l -c "<cmd>"`,
    /// like `ssh host cmd`; the session ends when the command exits.  Always
    /// starts a new session (implies `--force-new-session` for this connect).
    /// One-shot, not part of the persistent config.
    #[clap(
        last = true,
        value_name = "COMMAND",
        conflicts_with = "attach",
        help = "Command to run instead of the login shell (after `--`), e.g. `mp host -- htop`; \
                always starts a new session that ends when the command exits"
    )]
    #[getset(get = "pub(crate)")]
    remote_command: Vec<String>,
    /// Set of clap argument ids the user actually supplied on the command line
    /// (`ValueSource::CommandLine`), populated by [`Cli::parse_argv`].  This is
    /// the source of truth for "came from the command line": it lets
    /// [`Source::collect`] emit only user-provided values (so clap defaults no
    /// longer clobber the config file / environment) and powers the `ec`
    /// command's provenance column.  Not a real CLI argument.
    #[clap(skip)]
    #[getset(get = "pub(crate)")]
    explicit_args: BTreeSet<String>,
}

impl Cli {
    /// Parse `argv` into a [`Cli`], recording which arguments the user actually
    /// supplied on the command line.
    ///
    /// clap's derived struct cannot distinguish a value the user typed from a
    /// `default_value`, so we parse twice: once into the typed struct and once
    /// into raw [`ArgMatches`], whose [`ValueSource`] reveals the true origin of
    /// each argument.  The resulting [`Cli::explicit_args`] set drives
    /// [`Source::collect`] (so clap defaults no longer clobber the config file or
    /// environment) and the `ec` command's provenance column.
    ///
    /// # Errors
    /// Returns a clap error if `argv` fails to parse.
    pub(crate) fn parse_argv<I, T>(argv: I) -> clap::error::Result<Self>
    where
        I: IntoIterator<Item = T> + Clone,
        T: Into<OsString> + Clone,
    {
        let mut cli = Cli::try_parse_from(argv.clone())?;
        // Fully-qualified: the `command` field's getset getter shadows the
        // inherent `Cli::command()` provided by `CommandFactory`.
        let matches = <Cli as CommandFactory>::command().try_get_matches_from(argv)?;
        cli.explicit_args = explicit_command_line_ids(&matches);
        Ok(cli)
    }
}

/// Collect the ids of all top-level arguments whose value originated from the
/// command line (as opposed to a default value or being unset).
fn explicit_command_line_ids(matches: &ArgMatches) -> BTreeSet<String> {
    matches
        .ids()
        .filter(|id| matches.value_source(id.as_str()) == Some(ValueSource::CommandLine))
        .map(|id| id.as_str().to_string())
        .collect()
}

fn build_algo_table(
    kex: Option<&str>,
    aead: Option<&str>,
    mac: Option<&str>,
    kdf: Option<&str>,
) -> Option<Map<String, Value>> {
    let mut table = Map::new();
    let parse = |s: &str| -> Vec<Value> {
        s.split(',')
            .map(|a| Value::new(None, ValueKind::String(a.trim().to_string())))
            .collect()
    };
    for (key, opt) in [("kex", kex), ("aead", aead), ("mac", mac), ("kdf", kdf)] {
        if let Some(s) = opt {
            let _old = table.insert(
                key.to_string(),
                Value::new(None, ValueKind::Array(parse(s))),
            );
        }
    }
    (!table.is_empty()).then_some(table)
}

impl Source for Cli {
    fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
        Box::new((*self).clone())
    }

    #[allow(clippy::too_many_lines)] // a flat enumeration of every CLI argument
    fn collect(&self) -> Result<Map<String, Value>, ConfigError> {
        let mut map = Map::new();
        let origin = String::from("command line");
        // Only emit values the user actually typed on the command line.  Without
        // this gate, clap's `default_value`s would be emitted here and override
        // the config file and environment (see `parse_argv` / `explicit_args`).
        let on = |id: &str| self.explicit_args.contains(id);

        if on("config_absolute_path")
            && let Some(config_path) = &self.config_absolute_path
        {
            let _old = map.insert(
                "config_path".to_string(),
                Value::new(Some(&origin), ValueKind::String(config_path.clone())),
            );
        }
        if on("tracing_absolute_path")
            && let Some(tracing_path) = &self.tracing_absolute_path
        {
            let _old = map.insert(
                "tracing_path".to_string(),
                Value::new(Some(&origin), ValueKind::String(tracing_path.clone())),
            );
        }
        if on("private_key_path")
            && let Some(private_key_path) = &self.private_key_path
        {
            let _old = map.insert(
                "private_key_path".to_string(),
                Value::new(Some(&origin), ValueKind::String(private_key_path.clone())),
            );
        }
        if on("public_key_path")
            && let Some(public_key_path) = &self.public_key_path
        {
            let _old = map.insert(
                "public_key_path".to_string(),
                Value::new(Some(&origin), ValueKind::String(public_key_path.clone())),
            );
        }
        if on("server_port") {
            let _old = map.insert(
                "server_port".to_string(),
                Value::new(Some(&origin), ValueKind::U64(u16::into(self.server_port))),
            );
        }
        if on("server_destination")
            && let Some(server_destination) = &self.server_destination
        {
            let _old = map.insert(
                "server_destination".to_string(),
                Value::new(Some(&origin), ValueKind::String(server_destination.clone())),
            );
        }
        if on("predict") {
            let _old = map.insert(
                "predict".to_string(),
                Value::new(Some(&origin), ValueKind::String(self.predict.clone())),
            );
        }
        if on("nat_warmup") {
            let _old = map.insert(
                "nat_warmup".to_string(),
                Value::new(Some(&origin), ValueKind::Boolean(self.nat_warmup)),
            );
        }
        if on("nat_warmup_count") {
            let _old = map.insert(
                "nat_warmup_count".to_string(),
                Value::new(
                    Some(&origin),
                    ValueKind::U64(u32::into(self.nat_warmup_count)),
                ),
            );
        }
        if on("diff_mode") {
            let _old = map.insert(
                "diff_mode".to_string(),
                Value::new(Some(&origin), ValueKind::String(self.diff_mode.clone())),
            );
        }
        if on("transport") {
            let _old = map.insert(
                "transport".to_string(),
                Value::new(Some(&origin), ValueKind::String(self.transport.clone())),
            );
        }
        if on("legacy_passthrough") {
            let _old = map.insert(
                "legacy_passthrough".to_string(),
                Value::new(Some(&origin), ValueKind::Boolean(self.legacy_passthrough)),
            );
        }
        if on("no_color_probe") {
            let _old = map.insert(
                "probe_terminal_colors".to_string(),
                Value::new(Some(&origin), ValueKind::Boolean(!self.no_color_probe)),
            );
        }
        if on("escape_key")
            && let Some(escape_key) = &self.escape_key
        {
            let _old = map.insert(
                "escape_key".to_string(),
                Value::new(Some(&origin), ValueKind::String(escape_key.clone())),
            );
        }
        if let Some(table) = build_algo_table(
            self.kex_algos.as_deref().filter(|_| on("kex_algos")),
            self.aead_algos.as_deref().filter(|_| on("aead_algos")),
            self.mac_algos.as_deref().filter(|_| on("mac_algos")),
            self.kdf_algos.as_deref().filter(|_| on("kdf_algos")),
        ) {
            let _old = map.insert(
                "preferred_algorithms".to_string(),
                Value::new(Some(&origin), ValueKind::Table(table)),
            );
        }
        Ok(map)
    }
}

impl PathDefaults for Cli {
    fn env_prefix(&self) -> String {
        env!("CARGO_PKG_NAME").to_ascii_uppercase()
    }

    fn config_absolute_path(&self) -> Option<String> {
        self.config_absolute_path.clone()
    }

    fn default_file_path(&self) -> String {
        env!("CARGO_PKG_NAME").to_string()
    }

    fn default_file_name(&self) -> String {
        env!("CARGO_PKG_NAME").to_string()
    }

    fn tracing_absolute_path(&self) -> Option<String> {
        self.tracing_absolute_path.clone()
    }

    fn default_tracing_path(&self) -> String {
        format!("{}/logs", env!("CARGO_PKG_NAME"))
    }

    fn default_tracing_file_name(&self) -> String {
        env!("CARGO_PKG_NAME").to_string()
    }
}

#[cfg(test)]
mod tests {
    use clap::Parser as _;
    use config::{Source as _, ValueKind};
    use libmoshpit::PathDefaults as _;

    use super::{Cli, Commands, SessionsAction};

    #[test]
    fn test_cli_defaults() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "user@host"])?;
        assert_eq!(cli.config_absolute_path(), &None);
        assert_eq!(cli.tracing_absolute_path(), &None);
        assert_eq!(cli.private_key_path(), &None);
        assert_eq!(cli.public_key_path(), &None);
        assert_eq!(cli.server_port(), 40404);
        assert_eq!(cli.server_destination().as_deref(), Some("user@host"));
        assert_eq!(cli.predict(), "adaptive");
        assert!(cli.command().is_none());
        // Only the positional was supplied; defaulted flags are not "explicit".
        assert!(cli.explicit_args().contains("server_destination"));
        assert!(!cli.explicit_args().contains("server_port"));
        Ok(())
    }

    #[test]
    fn test_cli_parsing() -> anyhow::Result<()> {
        let cli = Cli::parse_argv([
            "moshpit",
            "-c",
            "/tmp/config",
            "-t",
            "/tmp/trace",
            "-p",
            "/tmp/priv",
            "-k",
            "/tmp/pub",
            "-s",
            "1234",
            "--predict",
            "always",
            "admin@10.0.0.1",
        ])?;
        assert_eq!(cli.config_absolute_path().as_deref(), Some("/tmp/config"));
        assert_eq!(cli.tracing_absolute_path().as_deref(), Some("/tmp/trace"));
        assert_eq!(cli.private_key_path().as_deref(), Some("/tmp/priv"));
        assert_eq!(cli.public_key_path().as_deref(), Some("/tmp/pub"));
        assert_eq!(cli.server_port(), 1234);
        assert_eq!(cli.server_destination().as_deref(), Some("admin@10.0.0.1"));
        assert_eq!(cli.predict(), "always");
        assert!(cli.command().is_none());
        Ok(())
    }

    #[test]
    fn test_ec_subcommand_parses() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "ec"])?;
        assert!(matches!(cli.command(), Some(Commands::Ec { json: false })));
        assert_eq!(cli.server_destination().as_deref(), None);
        Ok(())
    }

    #[test]
    fn test_ec_subcommand_json_flag() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "ec", "--json"])?;
        assert!(matches!(cli.command(), Some(Commands::Ec { json: true })));
        Ok(())
    }

    #[test]
    fn test_ec_with_global_flags() -> anyhow::Result<()> {
        // Resolution flags must precede the subcommand.
        let cli = Cli::parse_argv(["moshpit", "-c", "/tmp/c", "ec"])?;
        assert_eq!(cli.config_absolute_path().as_deref(), Some("/tmp/c"));
        assert!(matches!(cli.command(), Some(Commands::Ec { .. })));
        Ok(())
    }

    #[test]
    fn test_ec_rejects_destination() {
        // `ec` and a connect destination are mutually exclusive.
        assert!(Cli::parse_argv(["moshpit", "ec", "user@host"]).is_err());
    }

    #[test]
    fn test_sessions_list_subcommand_parses() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "sessions", "list", "user@host"])?;
        match cli.command() {
            Some(Commands::Sessions {
                action: SessionsAction::List { destination },
            }) => assert_eq!(destination, "user@host"),
            other => panic!("expected Sessions::List, got {other:?}"),
        }
        Ok(())
    }

    #[test]
    fn test_sessions_kill_subcommand_parses() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "sessions", "kill", "user@host", "brave-hopper"])?;
        match cli.command() {
            Some(Commands::Sessions {
                action: SessionsAction::Kill { destination, name },
            }) => {
                assert_eq!(destination, "user@host");
                assert_eq!(name, "brave-hopper");
            }
            other => panic!("expected Sessions::Kill, got {other:?}"),
        }
        Ok(())
    }

    #[test]
    fn test_sessions_kill_requires_name() {
        assert!(Cli::parse_argv(["moshpit", "sessions", "kill", "user@host"]).is_err());
    }

    #[test]
    fn test_force_new_session_flag() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "--force-new-session", "user@host"])?;
        assert!(cli.force_new_session());
        assert_eq!(cli.attach(), &None);
        Ok(())
    }

    #[test]
    fn test_force_new_session_defaults_false() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "user@host"])?;
        assert!(!cli.force_new_session());
        Ok(())
    }

    #[test]
    fn test_attach_flag() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "--attach", "brave-hopper", "user@host"])?;
        assert_eq!(cli.attach().as_deref(), Some("brave-hopper"));
        Ok(())
    }

    #[test]
    fn test_session_name_flag() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "--session-name", "my-session", "user@host"])?;
        assert_eq!(cli.session_name().as_deref(), Some("my-session"));
        Ok(())
    }

    #[test]
    fn test_force_new_session_conflicts_with_attach() {
        assert!(
            Cli::parse_argv([
                "moshpit",
                "--force-new-session",
                "--attach",
                "brave-hopper",
                "user@host",
            ])
            .is_err()
        );
    }

    #[test]
    fn test_session_name_conflicts_with_attach() {
        assert!(
            Cli::parse_argv([
                "moshpit",
                "--session-name",
                "foo",
                "--attach",
                "brave-hopper",
                "user@host",
            ])
            .is_err()
        );
    }

    #[test]
    fn test_force_new_session_and_session_name_compose() -> anyhow::Result<()> {
        let cli = Cli::parse_argv([
            "moshpit",
            "--force-new-session",
            "--session-name",
            "foo",
            "user@host",
        ])?;
        assert!(cli.force_new_session());
        assert_eq!(cli.session_name().as_deref(), Some("foo"));
        Ok(())
    }

    #[test]
    fn test_management_flags_not_in_explicit_collect_map() -> anyhow::Result<()> {
        // force_new_session/attach/session_name are one-shot directives read
        // directly off `Cli`, never routed through `Source::collect()` into
        // the persistent config.
        let cli = Cli::parse_argv([
            "moshpit",
            "--force-new-session",
            "--session-name",
            "foo",
            "user@host",
        ])?;
        let map = cli.collect()?;
        assert!(!map.contains_key("force_new_session"));
        assert!(!map.contains_key("attach"));
        assert!(!map.contains_key("session_name"));
        Ok(())
    }

    #[test]
    fn test_remote_command_after_double_dash() -> anyhow::Result<()> {
        let cli = Cli::parse_argv([
            "moshpit",
            "user@host",
            "--",
            "tmux",
            "new",
            "-A",
            "-s",
            "main",
        ])?;
        assert_eq!(cli.server_destination().as_deref(), Some("user@host"));
        assert_eq!(cli.remote_command(), &["tmux", "new", "-A", "-s", "main"]);
        assert!(!cli.collect()?.contains_key("remote_command"));
        Ok(())
    }

    #[test]
    fn test_no_remote_command_by_default() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "user@host"])?;
        assert_eq!(cli.remote_command(), &Vec::<String>::new());
        Ok(())
    }

    #[test]
    fn test_remote_command_requires_double_dash() {
        assert!(Cli::parse_argv(["moshpit", "user@host", "htop"]).is_err());
    }

    #[test]
    fn test_remote_command_conflicts_with_attach() {
        assert!(
            Cli::parse_argv(["moshpit", "--attach", "foo", "user@host", "--", "htop"]).is_err()
        );
    }

    #[test]
    fn test_connect_still_parses() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "user@host"])?;
        assert!(cli.command().is_none());
        assert_eq!(cli.server_destination().as_deref(), Some("user@host"));
        Ok(())
    }

    #[test]
    fn test_source_impl() -> anyhow::Result<()> {
        // Explicitly-set values are emitted; defaulted values (e.g. predict) are not.
        let cli = Cli::parse_argv(["moshpit", "-s", "1234", "host"])?;
        let map = cli.collect()?;

        assert!(matches!(
            map.get("server_port")
                .ok_or_else(|| anyhow::anyhow!("\"server_port\" not found in map"))?
                .kind,
            ValueKind::U64(1234)
        ));

        if let ValueKind::String(ref s) = map
            .get("server_destination")
            .ok_or_else(|| anyhow::anyhow!("\"server_destination\" not found in map"))?
            .kind
        {
            assert_eq!(s, "host");
        } else {
            panic!("Expected String");
        }

        // `predict` was not supplied, so it must NOT be emitted (no clap-default
        // pollution that would clobber the config file / environment).
        assert!(!map.contains_key("predict"));
        assert!(!map.contains_key("config_path"));

        let boxed = cli.clone_into_box();
        let map2 = boxed.collect()?;
        if let ValueKind::String(ref s) = map2
            .get("server_destination")
            .ok_or_else(|| anyhow::anyhow!("\"server_destination\" not found in map2"))?
            .kind
        {
            assert_eq!(s, "host");
        } else {
            panic!("Expected String");
        }
        Ok(())
    }

    #[test]
    fn test_source_impl_omits_defaults() -> anyhow::Result<()> {
        // With only the positional supplied, no defaulted flag leaks into the map.
        let cli = Cli::parse_argv(["moshpit", "host"])?;
        let map = cli.collect()?;
        assert!(map.contains_key("server_destination"));
        assert!(!map.contains_key("server_port"));
        assert!(!map.contains_key("predict"));
        assert!(!map.contains_key("diff_mode"));
        assert!(!map.contains_key("transport"));
        Ok(())
    }

    #[test]
    fn test_transport_defaults_to_udp() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "host"])?;
        assert_eq!(cli.transport(), "udp");
        Ok(())
    }

    #[test]
    fn test_transport_tcp_flag_parses_and_collects() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "--transport", "tcp", "host"])?;
        assert_eq!(cli.transport(), "tcp");
        let map = cli.collect()?;
        if let ValueKind::String(ref s) = map
            .get("transport")
            .ok_or_else(|| anyhow::anyhow!("\"transport\" not found in map"))?
            .kind
        {
            assert_eq!(s, "tcp");
        } else {
            panic!("Expected String");
        }
        Ok(())
    }

    #[test]
    fn test_source_impl_with_options() -> anyhow::Result<()> {
        let cli = Cli::parse_argv([
            "moshpit", "-c", "cfg", "-t", "trc", "-p", "prv", "-k", "pub", "host",
        ])?;
        let map = cli.collect()?;

        if let ValueKind::String(ref s) = map
            .get("config_path")
            .ok_or_else(|| anyhow::anyhow!("\"config_path\" not found in map"))?
            .kind
        {
            assert_eq!(s, "cfg");
        } else {
            panic!("Expected String");
        }

        if let ValueKind::String(ref s) = map
            .get("tracing_path")
            .ok_or_else(|| anyhow::anyhow!("\"tracing_path\" not found in map"))?
            .kind
        {
            assert_eq!(s, "trc");
        } else {
            panic!("Expected String");
        }

        if let ValueKind::String(ref s) = map
            .get("private_key_path")
            .ok_or_else(|| anyhow::anyhow!("\"private_key_path\" not found in map"))?
            .kind
        {
            assert_eq!(s, "prv");
        } else {
            panic!("Expected String");
        }

        if let ValueKind::String(ref s) = map
            .get("public_key_path")
            .ok_or_else(|| anyhow::anyhow!("\"public_key_path\" not found in map"))?
            .kind
        {
            assert_eq!(s, "pub");
        } else {
            panic!("Expected String");
        }
        Ok(())
    }

    #[test]
    fn collect_emits_all_explicit_value_flags() -> anyhow::Result<()> {
        let cli = Cli::parse_argv([
            "moshpit",
            "--predict",
            "always",
            "--nat-warmup",
            "--nat-warmup-count",
            "5",
            "--diff-mode",
            "datagram",
            "--legacy-passthrough",
            "host",
        ])?;
        let map = cli.collect()?;
        assert!(map.contains_key("nat_warmup"));
        assert!(map.contains_key("nat_warmup_count"));
        assert!(map.contains_key("legacy_passthrough"));
        if let ValueKind::String(ref s) = map
            .get("predict")
            .ok_or_else(|| anyhow::anyhow!("\"predict\" not found in map"))?
            .kind
        {
            assert_eq!(s, "always");
        } else {
            panic!("Expected String for predict");
        }
        if let ValueKind::String(ref s) = map
            .get("diff_mode")
            .ok_or_else(|| anyhow::anyhow!("\"diff_mode\" not found in map"))?
            .kind
        {
            assert_eq!(s, "datagram");
        } else {
            panic!("Expected String for diff_mode");
        }
        Ok(())
    }

    #[test]
    fn collect_emits_escape_key() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "--escape-key", "ctrl-a", "host"])?;
        assert_eq!(cli.escape_key().as_deref(), Some("ctrl-a"));
        let map = cli.collect()?;
        if let ValueKind::String(ref s) = map
            .get("escape_key")
            .ok_or_else(|| anyhow::anyhow!("\"escape_key\" not found in map"))?
            .kind
        {
            assert_eq!(s, "ctrl-a");
        } else {
            panic!("Expected String for escape_key");
        }
        Ok(())
    }

    #[test]
    fn collect_omits_unset_escape_key() -> anyhow::Result<()> {
        let cli = Cli::parse_argv(["moshpit", "host"])?;
        assert_eq!(cli.escape_key().as_deref(), None);
        let map = cli.collect()?;
        assert!(!map.contains_key("escape_key"));
        Ok(())
    }

    #[test]
    fn collect_emits_algo_table() -> anyhow::Result<()> {
        // Surrounding spaces exercise the `trim` in the parse closure.
        let cli = Cli::parse_argv([
            "moshpit",
            "--kex-algos",
            "x25519-sha256, ml-kem-768-sha256",
            "--aead-algos",
            "aes256-gcm-siv",
            "--mac-algos",
            "hmac-sha512",
            "--kdf-algos",
            "hkdf-sha256",
            "host",
        ])?;
        let map = cli.collect()?;
        if let ValueKind::Table(ref table) = map
            .get("preferred_algorithms")
            .ok_or_else(|| anyhow::anyhow!("\"preferred_algorithms\" not found in map"))?
            .kind
        {
            assert!(table.contains_key("kex"));
            assert!(table.contains_key("aead"));
            assert!(table.contains_key("mac"));
            assert!(table.contains_key("kdf"));
        } else {
            panic!("Expected Table for preferred_algorithms");
        }
        Ok(())
    }

    #[test]
    fn test_path_defaults() -> anyhow::Result<()> {
        let cli = Cli::try_parse_from(["moshpit", "-c", "cfg", "-t", "trc", "host"])?;
        assert_eq!(cli.env_prefix(), "MOSHPIT");
        assert_eq!(cli.config_absolute_path().as_deref(), Some("cfg"));
        assert_eq!(cli.default_file_path(), "moshpit");
        assert_eq!(cli.default_file_name(), "moshpit");
        assert_eq!(cli.tracing_absolute_path().as_deref(), Some("trc"));
        assert_eq!(cli.default_tracing_path(), "moshpit/logs");
        assert_eq!(cli.default_tracing_file_name(), "moshpit");
        Ok(())
    }
}