ditto-cli 0.4.2

Switch between Claude Code, Codex, opencode, OMP, Prime Agent, Pi, and 29 more coding-agent accounts
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
use std::{ffi::OsString, path::PathBuf};

use anyhow::{Result, bail};
use clap::{Args, Parser, Subcommand, ValueEnum};

#[derive(Debug, Parser)]
#[command(
    name = "ditto-cli",
    version,
    about = "Launch Claude Code, Codex, fx, opencode, OMP, Prime Agent, Pi, and other coding agents with isolated profiles"
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,
    /// Report as JSON on stdout, and errors as JSON on stderr.
    ///
    /// Global so it can be written wherever it reads best, before the
    /// subcommand or after it.
    #[arg(long, global = true)]
    pub json: bool,
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// List available profiles.
    List,
    /// Show authentication status for every supported agent.
    Status {
        /// Profile name. Uses the last selected profile when omitted.
        profile: Option<String>,
    },
    /// Create an isolated profile.
    Create {
        /// Profile name: letters, numbers, '-' and '_'.
        name: String,
    },
    /// Rename an isolated profile.
    Rename {
        /// Current profile name.
        profile: String,
        /// New profile name.
        new_name: String,
    },
    /// Delete an isolated profile and everything inside it.
    Delete(DeleteArgs),
    /// Preserve reusable configuration for one or all isolated profiles.
    Sync(SyncArgs),
    /// Show, pin, or release the profile commands use when none is named.
    Default(DefaultArgs),
    /// Show or change the profile a directory launches with.
    Workspace(WorkspaceArgs),
    /// Show every supported agent directory for a profile.
    Paths {
        /// Profile name. Uses the last selected profile when omitted.
        profile: Option<String>,
    },
    /// Launch Claude Code.
    #[command(visible_alias = "cc")]
    Claude(LaunchArgs),
    /// Launch Codex.
    #[command(visible_alias = "cx")]
    Codex(LaunchArgs),
    /// Launch Codex Desktop with an isolated profile.
    #[command(visible_alias = "cxa")]
    CodexApp(CodexAppArgs),
    /// Launch fx.
    Fx(LaunchArgs),
    /// Launch opencode.
    #[command(visible_alias = "oc")]
    Opencode(LaunchArgs),
    /// Launch Oh My Pi.
    Omp(LaunchArgs),
    /// Launch Prime Agent.
    #[command(visible_alias = "pa")]
    PrimeAgent(LaunchArgs),
    /// Launch Pi.
    Pi(LaunchArgs),
    /// Any other agent Ditto knows, by name: `ditto-cli gemini [profile] -- [args]`.
    ///
    /// The list is long and changes, so it is a table rather than a variant
    /// each; `--help` prints it after the commands.
    #[command(external_subcommand)]
    Other(Vec<OsString>),
    /// Print shell functions that route the tools' own names through Ditto.
    ShellInit(ShellInitArgs),
    /// Show or change the profile indicator Claude Code displays.
    Indicator(IndicatorArgs),
    /// Print the profile status line. Claude Code runs this itself.
    #[command(hide = true)]
    Statusline(StatuslineArgs),
    /// Update Ditto CLI itself.
    Update(UpdateArgs),
}

#[derive(Debug, Args)]
pub struct WorkspaceArgs {
    #[command(subcommand)]
    pub command: Option<WorkspaceCommand>,
}

#[derive(Debug, Subcommand)]
pub enum WorkspaceCommand {
    /// Bind a directory to a profile.
    Use {
        /// Profile the directory should launch with.
        profile: String,
        /// Record the binding in Ditto's own registry rather than writing a
        /// file, for directories that are not yours to add a file to.
        #[arg(long)]
        global: bool,
        /// Directory to bind. Uses the current directory when omitted.
        #[arg(long)]
        path: Option<PathBuf>,
    },
    /// Remove the binding on a directory, leaving its ancestors alone.
    Clear {
        /// Directory to unbind. Uses the current directory when omitted.
        #[arg(long)]
        path: Option<PathBuf>,
    },
    /// List the directories recorded in Ditto's own registry.
    List,
    /// Show or change whether launching binds an unbound directory.
    Auto {
        /// Reports the current setting when omitted.
        state: Option<AutoState>,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum AutoState {
    On,
    Off,
}

impl AutoState {
    pub fn enabled(self) -> bool {
        matches!(self, Self::On)
    }
}

#[derive(Debug, Args)]
pub struct ShellInitArgs {
    /// Shell to write for. Read from `SHELL` when omitted.
    pub shell: Option<ShellKind>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum ShellKind {
    Bash,
    Fish,
    Zsh,
}

#[derive(Debug, Args)]
pub struct DeleteArgs {
    /// Profile name. Named in full, because there is nothing to fall back to
    /// that would be safe to delete by accident.
    pub profile: String,
    /// Confirm the deletion.
    ///
    /// Deleting takes the profile's credentials, settings, and session history
    /// with it and cannot be undone, so it is never the default answer to a
    /// command that was typed or generated by mistake.
    #[arg(long)]
    pub yes: bool,
}

#[derive(Debug, Args)]
pub struct SyncArgs {
    /// Profile to preserve configuration for. Choose this or `--all`.
    #[arg(required_unless_present = "all", conflicts_with = "all")]
    pub profile: Option<String>,
    /// Preserve configuration for every managed profile instead of one.
    #[arg(long)]
    pub all: bool,
    /// Copy existing conversations for every tool into the target profile(s).
    ///
    /// Existing files and sessions are kept. The copies then remain isolated,
    /// so later conversations under one account do not appear under another.
    #[arg(long, visible_alias = "pi-history")]
    pub history: bool,
    /// Replace the settings this profile has already answered for itself.
    ///
    /// Without it a profile keeps every setting it has changed, which is what
    /// makes it worth having; with it your own configuration wins outright.
    #[arg(long)]
    pub overwrite: bool,
    /// Point the skills, agents, commands, hooks, and plugins this profile has
    /// its own copies of back at yours.
    ///
    /// Profiles made before Ditto shared any of that have real directories
    /// where the links go, and replacing one is a thing to ask for. What was
    /// there is moved aside rather than deleted.
    #[arg(long)]
    pub adopt: bool,
}

#[derive(Debug, Args)]
pub struct DefaultArgs {
    /// Profile to pin. Reports the current pin when omitted.
    pub profile: Option<String>,
    /// Release the pin, handing the fallback back to the last launched profile.
    #[arg(long, conflicts_with = "profile")]
    pub clear: bool,
}

impl DefaultArgs {
    /// Neither a name nor `--clear` means the command was asked to report
    /// rather than change, matching how `indicator` reads its own flags.
    pub fn action(&self) -> Option<DefaultAction<'_>> {
        match (self.profile.as_deref(), self.clear) {
            (Some(name), _) => Some(DefaultAction::Pin(name)),
            (_, true) => Some(DefaultAction::Clear),
            _ => None,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DefaultAction<'a> {
    Pin(&'a str),
    Clear,
}

#[derive(Debug, Args)]
pub struct IndicatorArgs {
    /// Profile name. Uses the saved profile when omitted.
    pub profile: Option<String>,
    /// Show the profile in Claude Code's status line.
    #[arg(long, conflicts_with = "off")]
    pub on: bool,
    /// Take the profile back out of Claude Code's status line.
    #[arg(long)]
    pub off: bool,
    /// Keep the status line this profile already has, with the profile drawn
    /// in front of it. Turns the indicator on.
    ///
    /// Without it a profile that has its own status line is left alone, since
    /// Claude Code draws one status line and the one already there was asked
    /// for.
    #[arg(long, conflicts_with = "off")]
    pub keep_mine: bool,
}

impl IndicatorArgs {
    /// Neither flag means the command was asked to report rather than change.
    /// Asking to keep a status line is asking for the indicator as well: there
    /// is nothing else the answer could mean.
    pub fn action(&self) -> Option<IndicatorAction> {
        match (self.on || self.keep_mine, self.off) {
            (true, _) => Some(IndicatorAction::On),
            (_, true) => Some(IndicatorAction::Off),
            _ => None,
        }
    }
}

/// Written by Ditto, read by Ditto: Claude Code runs the command in the
/// settings file exactly as it finds it, so anything the status line needs to
/// know has to be an argument on that command.
#[derive(Debug, Args)]
pub struct StatuslineArgs {
    /// Status line to draw the profile in front of.
    #[arg(long, allow_hyphen_values = true)]
    pub with: Option<String>,
    /// The same, percent-encoded for a shell that could not carry it literally.
    #[arg(long, allow_hyphen_values = true, conflicts_with = "with")]
    pub with_encoded: Option<String>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IndicatorAction {
    On,
    Off,
}

#[derive(Debug, Args)]
pub struct UpdateArgs {
    /// Compare the installed and published versions without installing.
    #[arg(long)]
    pub check: bool,
    /// Install from the Git repository instead of crates.io.
    #[arg(long)]
    pub git: bool,
}

#[derive(Debug, Args)]
pub struct LaunchArgs {
    /// Profile name. Uses the last selected profile when omitted.
    pub profile: Option<String>,
    /// Arguments passed to the underlying CLI. Place them after `--`.
    #[arg(last = true)]
    pub args: Vec<OsString>,
}

#[derive(Debug, Args)]
pub struct CodexAppArgs {
    /// Profile name. Uses the last selected profile when omitted.
    pub profile: Option<String>,
    /// Open this directory as a project. Omit to reopen the profile without adding a project.
    #[arg(short = 'C', long, value_name = "PATH")]
    pub directory: Option<PathBuf>,
}

/// The launch a tool named outside the subcommand list was asked for.
///
/// clap hands over the bare words, so this reads them the way [`LaunchArgs`]
/// would have: at most a profile name, then `--` and the tool's own arguments.
/// Whether the name is a tool at all is for the caller, which has the table.
pub fn external_launch(argv: &[OsString]) -> Result<(String, LaunchArgs)> {
    let Some((name, rest)) = argv.split_first() else {
        bail!("no tool was named");
    };
    let name = name.to_string_lossy().into_owned();
    let (positional, args) = match rest.iter().position(|word| word == "--") {
        Some(separator) => (&rest[..separator], rest[separator + 1..].to_vec()),
        None => (rest, Vec::new()),
    };
    let profile = match positional {
        [] => None,
        [profile] if !profile.to_string_lossy().starts_with('-') => {
            Some(profile.to_string_lossy().into_owned())
        }
        _ => bail!(
            "`ditto-cli {name}` takes at most a profile name; put {name}'s own arguments after `--`"
        ),
    };
    Ok((name, LaunchArgs { profile, args }))
}

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

    #[test]
    fn parses_a_launch_of_a_tool_named_outside_the_subcommand_list() {
        let cli =
            Cli::try_parse_from(["ditto-cli", "gemini", "work", "--", "--model", "x"]).unwrap();
        let Some(Command::Other(argv)) = cli.command else {
            panic!("a name clap does not know should reach the table");
        };
        let (name, launch) = external_launch(&argv).unwrap();
        assert_eq!(name, "gemini");
        assert_eq!(launch.profile.as_deref(), Some("work"));
        assert_eq!(
            launch.args,
            [OsString::from("--model"), OsString::from("x")]
        );

        let words = |words: &[&str]| words.iter().map(OsString::from).collect::<Vec<_>>();
        let (_, launch) = external_launch(&words(&["gemini"])).unwrap();
        assert_eq!(launch.profile, None);
        assert!(launch.args.is_empty());
        let (_, launch) = external_launch(&words(&["gemini", "--", "-p", "hi"])).unwrap();
        assert_eq!(launch.profile, None);
        assert_eq!(launch.args.len(), 2);

        // Arguments meant for the tool come after `--`, as with every other
        // launch; anything else before it is a mistake worth naming.
        assert!(external_launch(&words(&["gemini", "--model", "x"])).is_err());
        assert!(external_launch(&words(&["gemini", "work", "extra"])).is_err());
    }

    #[test]
    fn parses_profile_rename_command() {
        let cli = Cli::try_parse_from(["ditto-cli", "rename", "work", "client"]).unwrap();

        assert!(matches!(
            cli.command,
            Some(Command::Rename {
                profile,
                new_name
            }) if profile == "work" && new_name == "client"
        ));
    }
    #[test]
    fn parses_sync_arguments() {
        let named = Cli::try_parse_from(["ditto-cli", "sync", "work"]).unwrap();
        assert!(matches!(
            named.command,
            Some(Command::Sync(SyncArgs {
                profile, overwrite, ..
            }))
                if profile.as_deref() == Some("work") && !overwrite
        ));

        assert!(Cli::try_parse_from(["ditto-cli", "sync", "--overwrite"]).is_err());

        let all =
            Cli::try_parse_from(["ditto-cli", "sync", "--all", "--history", "--adopt"]).unwrap();
        assert!(matches!(
            all.command,
            Some(Command::Sync(SyncArgs {
                all: true,
                history: true,
                adopt: true,
                ..
            }))
        ));
        assert!(Cli::try_parse_from(["ditto-cli", "sync", "work", "--all"]).is_err());
    }

    #[test]
    fn parses_update_flags() {
        let plain = Cli::try_parse_from(["ditto-cli", "update"]).unwrap();
        assert!(matches!(
            plain.command,
            Some(Command::Update(UpdateArgs { check, git })) if !check && !git
        ));

        let checking = Cli::try_parse_from(["ditto-cli", "update", "--check"]).unwrap();
        assert!(matches!(
            checking.command,
            Some(Command::Update(UpdateArgs { check, git })) if check && !git
        ));

        let from_git = Cli::try_parse_from(["ditto-cli", "update", "--git"]).unwrap();
        assert!(matches!(
            from_git.command,
            Some(Command::Update(UpdateArgs { check, git })) if !check && git
        ));
    }

    #[test]
    fn parses_opencode_launch_arguments() {
        let cli = Cli::try_parse_from([
            "ditto-cli",
            "opencode",
            "work",
            "--",
            "--model",
            "anthropic/claude-opus-5",
        ])
        .unwrap();

        assert!(matches!(
            cli.command,
            Some(Command::Opencode(LaunchArgs { profile, args }))
                if profile.as_deref() == Some("work")
                    && args == [
                        OsString::from("--model"),
                        OsString::from("anthropic/claude-opus-5"),
                    ]
        ));
    }

    #[test]
    fn parses_prime_agent_launch_arguments() {
        let cli = Cli::try_parse_from([
            "ditto-cli",
            "prime-agent",
            "work",
            "--",
            "--model",
            "claude-opus-4-1",
        ])
        .unwrap();

        assert!(matches!(
            cli.command,
            Some(Command::PrimeAgent(LaunchArgs { profile, args }))
                if profile.as_deref() == Some("work")
                    && args == [
                        OsString::from("--model"),
                        OsString::from("claude-opus-4-1"),
                    ]
        ));
    }

    #[test]
    fn parses_pi_launch_arguments() {
        let cli = Cli::try_parse_from([
            "ditto-cli",
            "pi",
            "work",
            "--",
            "--model",
            "anthropic/claude-opus-4-6",
        ])
        .unwrap();

        assert!(matches!(
            cli.command,
            Some(Command::Pi(LaunchArgs { profile, args }))
                if profile.as_deref() == Some("work")
                    && args == [
                        OsString::from("--model"),
                        OsString::from("anthropic/claude-opus-4-6"),
                    ]
        ));
    }

    #[test]
    fn parses_short_launch_aliases() {
        let claude = Cli::try_parse_from(["ditto-cli", "cc", "work"]).unwrap();
        assert!(matches!(
            claude.command,
            Some(Command::Claude(LaunchArgs { profile, args }))
                if profile.as_deref() == Some("work") && args.is_empty()
        ));

        let codex = Cli::try_parse_from(["ditto-cli", "cx", "work"]).unwrap();
        assert!(matches!(
            codex.command,
            Some(Command::Codex(LaunchArgs { profile, .. })) if profile.as_deref() == Some("work")
        ));

        let codex_app =
            Cli::try_parse_from(["ditto-cli", "cxa", "work", "-C", "/tmp/project"]).unwrap();
        assert!(matches!(
            codex_app.command,
            Some(Command::CodexApp(CodexAppArgs { profile, directory }))
                if profile.as_deref() == Some("work")
                    && directory == Some(PathBuf::from("/tmp/project"))
        ));

        let opencode =
            Cli::try_parse_from(["ditto-cli", "oc", "work", "--", "--model", "opus"]).unwrap();
        assert!(matches!(
            opencode.command,
            Some(Command::Opencode(LaunchArgs { profile, args }))
                if profile.as_deref() == Some("work")
                    && args == [OsString::from("--model"), OsString::from("opus")]
        ));

        let prime_agent = Cli::try_parse_from(["ditto-cli", "pa", "work"]).unwrap();
        assert!(matches!(
            prime_agent.command,
            Some(Command::PrimeAgent(LaunchArgs { profile, args }))
                if profile.as_deref() == Some("work") && args.is_empty()
        ));
    }

    #[test]
    fn parses_a_launch_with_nothing_after_the_separator() {
        // The shape the generated shell functions always send: no profile, and a
        // `--` with however many arguments the user typed behind it, including
        // none. Reading the `--` as a profile name would launch a profile called
        // `--` and fail on a name nobody typed.
        let cli = Cli::try_parse_from(["ditto-cli", "omp", "--"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Omp(LaunchArgs { profile, args })) if profile.is_none() && args.is_empty()
        ));

        let with_arguments =
            Cli::try_parse_from(["ditto-cli", "omp", "--", "--model", "opus"]).unwrap();
        assert!(matches!(
            with_arguments.command,
            Some(Command::Omp(LaunchArgs { profile, args }))
                if profile.is_none()
                    && args == [OsString::from("--model"), OsString::from("opus")]
        ));
    }

    #[test]
    fn parses_shell_init_commands() {
        let named = Cli::try_parse_from(["ditto-cli", "shell-init", "fish"]).unwrap();
        assert!(matches!(
            named.command,
            Some(Command::ShellInit(ShellInitArgs { shell })) if shell == Some(ShellKind::Fish)
        ));

        // No shell means the environment is asked, which is the form the
        // documented one-liner uses.
        let detected = Cli::try_parse_from(["ditto-cli", "shell-init"]).unwrap();
        assert!(matches!(
            detected.command,
            Some(Command::ShellInit(ShellInitArgs { shell })) if shell.is_none()
        ));

        // A shell Ditto cannot write for is refused at parse time, so nothing
        // ever prints syntax the shell reading it could not parse.
        assert!(Cli::try_parse_from(["ditto-cli", "shell-init", "pwsh"]).is_err());
    }

    fn indicator_args(arguments: &[&str]) -> IndicatorArgs {
        match Cli::try_parse_from(arguments).unwrap().command {
            Some(Command::Indicator(arguments)) => arguments,
            other => panic!("expected an indicator command, got {other:?}"),
        }
    }

    #[test]
    fn parses_indicator_commands() {
        // A profile alone reports rather than changing anything, so the status
        // line can be checked without touching it.
        let reporting = indicator_args(&["ditto-cli", "indicator", "work"]);
        assert_eq!(reporting.profile.as_deref(), Some("work"));
        assert_eq!(reporting.action(), None);

        assert_eq!(indicator_args(&["ditto-cli", "indicator"]).action(), None);

        let turning_on = indicator_args(&["ditto-cli", "indicator", "work", "--on"]);
        assert_eq!(turning_on.profile.as_deref(), Some("work"));
        assert_eq!(turning_on.action(), Some(IndicatorAction::On));

        let turning_off = indicator_args(&["ditto-cli", "indicator", "--off"]);
        assert_eq!(turning_off.profile, None);
        assert_eq!(turning_off.action(), Some(IndicatorAction::Off));

        // Asking for both at once has no sensible answer.
        assert!(Cli::try_parse_from(["ditto-cli", "indicator", "--on", "--off"]).is_err());
    }

    fn workspace_command(arguments: &[&str]) -> Option<WorkspaceCommand> {
        match Cli::try_parse_from(arguments).unwrap().command {
            Some(Command::Workspace(arguments)) => arguments.command,
            other => panic!("expected a workspace command, got {other:?}"),
        }
    }

    #[test]
    fn parses_workspace_commands() {
        // A bare `workspace` reports the binding rather than changing it.
        assert!(workspace_command(&["ditto-cli", "workspace"]).is_none());

        assert!(matches!(
            workspace_command(&["ditto-cli", "workspace", "use", "work"]),
            Some(WorkspaceCommand::Use { profile, global, path })
                if profile == "work" && !global && path.is_none()
        ));

        assert!(matches!(
            workspace_command(&["ditto-cli", "workspace", "use", "work", "--global"]),
            Some(WorkspaceCommand::Use { global, .. }) if global
        ));

        assert!(matches!(
            workspace_command(&["ditto-cli", "workspace", "clear", "--path", "/tmp/project"]),
            Some(WorkspaceCommand::Clear { path })
                if path.as_deref() == Some(std::path::Path::new("/tmp/project"))
        ));

        assert!(matches!(
            workspace_command(&["ditto-cli", "workspace", "list"]),
            Some(WorkspaceCommand::List)
        ));

        // Binding has no fallback profile to reach for, so the name is required.
        assert!(Cli::try_parse_from(["ditto-cli", "workspace", "use"]).is_err());
    }

    #[test]
    fn parses_the_auto_bind_setting() {
        // No state reports rather than changing, matching how `indicator` and
        // the rest of the reporting commands read their own arguments.
        assert!(matches!(
            workspace_command(&["ditto-cli", "workspace", "auto"]),
            Some(WorkspaceCommand::Auto { state: None })
        ));

        for (argument, expected) in [("on", AutoState::On), ("off", AutoState::Off)] {
            assert!(matches!(
                workspace_command(&["ditto-cli", "workspace", "auto", argument]),
                Some(WorkspaceCommand::Auto { state: Some(state) }) if state == expected
            ));
        }

        assert!(AutoState::On.enabled());
        assert!(!AutoState::Off.enabled());
        assert!(Cli::try_parse_from(["ditto-cli", "workspace", "auto", "maybe"]).is_err());
    }

    #[test]
    fn parses_the_status_line_command_claude_code_runs() {
        let bare = Cli::try_parse_from(["ditto-cli", "statusline"]).unwrap();
        assert!(matches!(
            bare.command,
            Some(Command::Statusline(StatuslineArgs { with, with_encoded }))
                if with.is_none() && with_encoded.is_none()
        ));

        // The status line Ditto is drawing in front of arrives as one
        // argument, whatever it is made of. A command starting with a dash is
        // still a command and not a flag of Ditto's.
        let keeping =
            Cli::try_parse_from(["ditto-cli", "statusline", "--with", "-x | y --with z"]).unwrap();
        assert!(matches!(
            keeping.command,
            Some(Command::Statusline(StatuslineArgs { with: Some(with), .. }))
                if with == "-x | y --with z"
        ));

        let encoded =
            Cli::try_parse_from(["ditto-cli", "statusline", "--with-encoded", "a%20b"]).unwrap();
        assert!(matches!(
            encoded.command,
            Some(Command::Statusline(StatuslineArgs { with_encoded: Some(value), .. }))
                if value == "a%20b"
        ));
    }

    fn default_args(arguments: &[&str]) -> DefaultArgs {
        match Cli::try_parse_from(arguments).unwrap().command {
            Some(Command::Default(arguments)) => arguments,
            other => panic!("expected a default command, got {other:?}"),
        }
    }

    #[test]
    fn parses_default_profile_commands() {
        // A bare `default` reports the pin rather than changing it, so it can
        // be read without a name to hand it.
        assert_eq!(default_args(&["ditto-cli", "default"]).action(), None);
        assert_eq!(
            default_args(&["ditto-cli", "default", "work"]).action(),
            Some(DefaultAction::Pin("work"))
        );
        assert_eq!(
            default_args(&["ditto-cli", "default", "--clear"]).action(),
            Some(DefaultAction::Clear)
        );

        // Pinning and releasing at once has no sensible answer.
        assert!(Cli::try_parse_from(["ditto-cli", "default", "work", "--clear"]).is_err());
    }

    #[test]
    fn requires_confirmation_to_parse_a_deletion() {
        let confirmed = Cli::try_parse_from(["ditto-cli", "delete", "work", "--yes"]).unwrap();
        assert!(matches!(
            confirmed.command,
            Some(Command::Delete(DeleteArgs { profile, yes })) if profile == "work" && yes
        ));

        // Parsing still succeeds without it. The command refuses at run time so
        // the answer explains what deleting takes with it, rather than being a
        // usage error about a missing flag.
        let unconfirmed = Cli::try_parse_from(["ditto-cli", "delete", "work"]).unwrap();
        assert!(matches!(
            unconfirmed.command,
            Some(Command::Delete(DeleteArgs { yes, .. })) if !yes
        ));

        // Deleting has no fallback profile, so the name is not optional.
        assert!(Cli::try_parse_from(["ditto-cli", "delete"]).is_err());
    }

    /// The flag is global so an agent can write it wherever it reads best,
    /// rather than having to remember which side of the subcommand it lives on.
    #[test]
    fn accepts_json_on_either_side_of_the_subcommand() {
        for arguments in [
            ["ditto-cli", "list", "--json"],
            ["ditto-cli", "--json", "list"],
        ] {
            let cli = Cli::try_parse_from(arguments).unwrap();
            assert!(cli.json, "did not set json for {arguments:?}");
            assert!(matches!(cli.command, Some(Command::List)));
        }

        assert!(!Cli::try_parse_from(["ditto-cli", "list"]).unwrap().json);
    }

    #[test]
    fn parses_omp_launch_arguments() {
        let cli =
            Cli::try_parse_from(["ditto-cli", "omp", "work", "--", "--model", "opus"]).unwrap();

        assert!(matches!(
            cli.command,
            Some(Command::Omp(LaunchArgs { profile, args }))
                if profile.as_deref() == Some("work")
                    && args == [OsString::from("--model"), OsString::from("opus")]
        ));
    }
}