ai-usagebar 0.20.1

Waybar widget + TUI for tracking AI plan usage across multiple providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
//! Administrative commands for named Claude accounts.

use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::anthropic::cli_account::{self, CliSwitchOpts, CliSwitchOutcome, KeychainStore};
use crate::claude_desktop::{self, Paths, SwitchOpts, SwitchPlan};
use crate::config::Config;
use crate::error::{AppError, Result};
use crate::widget::cli::AccountAction;

struct Registered {
    config_path: PathBuf,
    credential_file: PathBuf,
    account_dir: PathBuf,
    credential_display: String,
    already_existed: bool,
    anthropic_enabled: bool,
}

impl Registered {
    fn supports_scoped_login(&self) -> bool {
        self.credential_file
            .file_name()
            .and_then(|name| name.to_str())
            == Some(".credentials.json")
    }
}

/// Run an administrative account command and return its process exit code.
#[must_use]
pub fn run(action: &AccountAction) -> i32 {
    match action {
        AccountAction::Add {
            label,
            no_login,
            desktop,
            email,
            yes,
        } => {
            if *desktop {
                add_desktop(label, email.as_deref(), *yes)
            } else {
                add(label, !no_login)
            }
        }
        AccountAction::Status { json } => status(*json),
        AccountAction::Switch {
            label,
            desktop,
            cli,
            dry_run,
            yes,
            force,
            keep_bridge,
            backup_sessions,
            keep_backups,
        } => switch(&SwitchArgs {
            label,
            desktop: *desktop,
            cli: *cli,
            dry_run: *dry_run,
            yes: *yes,
            force: *force,
            opts: SwitchOpts {
                keep_bridge: *keep_bridge,
                backup_sessions: *backup_sessions,
                keep_backups: *keep_backups,
            },
        }),
    }
}

/// A config that fails to parse must not blank out the account report: the
/// menu bar polls `account status` while the file is being edited. Read-only
/// status can safely fall back to the conventional account locations.
fn config_or_default() -> Config {
    Config::load().unwrap_or_else(|error| {
        eprintln!("ai-usagebar account: using defaults, config.toml did not parse: {error}");
        Config::default()
    })
}

/// Read-only status can degrade while a config is mid-edit; commands that
/// change credentials or Desktop state cannot. Falling back there could select
/// the default profile store instead of the user's configured one.
fn config_for_mutation(loaded: Result<Config>) -> Result<Config> {
    loaded.map_err(|error| {
        AppError::Other(format!(
            "refusing to change account state because config.toml did not parse: {error}"
        ))
    })
}

fn status(json: bool) -> i32 {
    let config = config_or_default();
    let accounts = config.anthropic.all_accounts();
    let paths = Paths::resolve(&config.anthropic)
        .ok()
        .filter(Paths::available);

    // A Desktop profile captured without an e-mail can still be named: the
    // same account signed into the CLI records one, keyed by the same UUID.
    let emails_by_uuid: Vec<(String, String)> = accounts
        .iter()
        .filter_map(|account| {
            let marker = cli_account::marker_path(&account.config_dir());
            Some((
                cli_account::account_uuid_in(&marker)?,
                cli_account::account_email_in(&marker)?,
            ))
        })
        .collect();
    let email_for = |uuid: &str| -> Option<&str> {
        emails_by_uuid
            .iter()
            .find(|(known, _)| known == uuid)
            .map(|(_, email)| email.as_str())
    };

    let desktop = paths.as_ref().map(|paths| {
        let profiles = claude_desktop::load_profiles(&paths.profiles_dir);
        let sessions_root = paths.sessions_root();
        let active_uuid = claude_desktop::active_account_uuid(&paths.config_json());
        let active_label = active_uuid
            .as_deref()
            .and_then(|uuid| claude_desktop::label_for_uuid(&profiles, uuid))
            .map(str::to_string);
        let rows: Vec<serde_json::Value> = profiles
            .iter()
            .map(|profile| {
                serde_json::json!({
                    "label": profile.label,
                    "email": profile
                        .email
                        .as_deref()
                        .or_else(|| email_for(&profile.account_uuid)),
                    "account_uuid": profile.account_uuid,
                    "org_uuid": profile.org_uuid,
                    "has_credentials": profile.has_credentials,
                    "has_desktop_state": profile.has_desktop_state,
                    "sessions": claude_desktop::session_count(&sessions_root, profile),
                    "active": Some(&profile.label) == active_label.as_ref(),
                })
            })
            .collect();
        serde_json::json!({
            "available": true,
            "data_dir": paths.data_dir,
            "profiles_dir": paths.profiles_dir,
            "active_label": active_label,
            "active_account_uuid": active_uuid,
            "profiles": rows,
        })
    });

    let home = cli_account::home_claude_json().ok();
    let cli_active = home
        .as_deref()
        .and_then(|home| cli_account::resolve_active_label(home, &accounts));
    let cli_rows: Vec<serde_json::Value> = accounts
        .iter()
        .map(|account| {
            let marker = cli_account::marker_path(&account.config_dir());
            serde_json::json!({
                "label": account.label,
                "email": cli_account::account_email_in(&marker),
                "account_uuid": cli_account::account_uuid_in(&marker),
                "config_dir": account.config_dir(),
                "active": Some(&account.label) == cli_active.as_ref(),
            })
        })
        .collect();
    let cli = serde_json::json!({
        "active_label": cli_active,
        "active_account_uuid": home.as_deref().and_then(cli_account::account_uuid_in),
        "accounts": cli_rows,
    });

    let report = serde_json::json!({ "desktop": desktop, "cli": cli });
    if json {
        println!("{report}");
        return 0;
    }
    print_status(&report);
    0
}

fn print_status(report: &serde_json::Value) {
    match &report["desktop"] {
        serde_json::Value::Null => {
            println!("Claude Desktop   not found (macOS only)");
        }
        desktop => {
            println!(
                "Claude Desktop   {}",
                desktop["data_dir"].as_str().unwrap_or("?")
            );
            let profiles = desktop["profiles"]
                .as_array()
                .map_or(&[][..], Vec::as_slice);
            if profiles.is_empty() {
                println!(
                    "  no saved accounts in {} — capture one with \
                     `ai-usagebar account add <label> --desktop`",
                    desktop["profiles_dir"].as_str().unwrap_or("?")
                );
            }
            for profile in profiles {
                println!(
                    "  {:<12} {:<28} sessions={:<5} creds={:<4} state={:<4}{}",
                    profile["label"].as_str().unwrap_or("?"),
                    profile["email"].as_str().unwrap_or("(email unknown)"),
                    profile["sessions"].as_u64().unwrap_or(0),
                    yes_no(&profile["has_credentials"]),
                    yes_no(&profile["has_desktop_state"]),
                    active_tag(&profile["active"]),
                );
            }
        }
    }

    println!();
    println!("Claude Code      the `claude` CLI's default login");
    let accounts = report["cli"]["accounts"]
        .as_array()
        .map_or(&[][..], Vec::as_slice);
    if accounts.is_empty() {
        println!("  no named accounts — add one with `ai-usagebar account add <label>`");
    }
    for account in accounts {
        println!(
            "  {:<12} {:<28}{}",
            account["label"].as_str().unwrap_or("?"),
            account["email"].as_str().unwrap_or("(email unknown)"),
            active_tag(&account["active"]),
        );
    }
    if report["cli"]["active_label"].is_null() && !accounts.is_empty() {
        println!(
            "  note: the live CLI login belongs to no account listed here, so its \
             saved copies may be stale."
        );
    }
}

fn yes_no(value: &serde_json::Value) -> &'static str {
    if value.as_bool().unwrap_or(false) {
        "yes"
    } else {
        "no"
    }
}

fn active_tag(value: &serde_json::Value) -> &'static str {
    if value.as_bool().unwrap_or(false) {
        "  [active]"
    } else {
        ""
    }
}

/// Capture a Claude Desktop account. Unlike the CLI half, this cannot happen
/// quietly in the background: the app has one login slot, so the only way to
/// obtain a second account's credential is to sign it out and have the user
/// sign back in as the account being saved.
fn add_desktop(label: &str, email: Option<&str>, assume_yes: bool) -> i32 {
    if let Err(error) = crate::config::validate_account_label(label) {
        eprintln!("ai-usagebar account add: {error}");
        return 1;
    }
    let config = match config_for_mutation(Config::load()) {
        Ok(config) => config,
        Err(error) => {
            eprintln!("ai-usagebar account add: {error}");
            return 1;
        }
    };
    let paths = match Paths::resolve(&config.anthropic) {
        Ok(paths) if paths.available() => paths,
        Ok(paths) => {
            eprintln!(
                "ai-usagebar account add: no Claude Desktop app data at {} (macOS only)",
                paths.data_dir.display()
            );
            return 1;
        }
        Err(error) => {
            eprintln!("ai-usagebar account add: {error}");
            return 1;
        }
    };

    let profiles = claude_desktop::load_profiles(&paths.profiles_dir);
    let active = claude_desktop::active_account_uuid(&paths.config_json())
        .and_then(|uuid| claude_desktop::label_for_uuid(&profiles, &uuid).map(str::to_string));

    println!("Capturing a Claude Desktop account as {label:?}.");
    println!("  The app will close and reopen at its login screen, where you sign in as the");
    println!("  account you want to save. Nothing else on this machine is touched.");
    match &active {
        Some(previous) => println!(
            "  Your current account ({previous:?}) is saved first, so switching back is intact."
        ),
        None => println!(
            "  Your current login is copied to {} first and restored if you cancel.",
            paths.prelogin_dir().display()
        ),
    }
    if !assume_yes && !confirm("  Close Claude and start the login?") {
        println!("Aborted (pass -y to skip this prompt).");
        return 1;
    }
    // Cosmetic, and the only chance to ask: once the app is signed out this
    // process is polling, not reading stdin.
    let email = email
        .map(str::to_string)
        .or_else(|| ask("  E-mail for this account (optional, for display): "));
    println!("  Waiting for sign-in (up to five minutes); press Ctrl-C to cancel and restore.");

    let mut notes = Vec::new();
    let outcome = claude_desktop::capture::capture_profile(
        &paths,
        label,
        email.as_deref(),
        &claude_desktop::app::DesktopApp,
        claude_desktop::capture::WaitOpts::default(),
        &mut notes,
    );
    for note in &notes {
        println!("  note: {note}");
    }
    match outcome {
        Err(error) => {
            eprintln!("ai-usagebar account add: {error}");
            1
        }
        Ok(claude_desktop::capture::CaptureOutcome::TimedOut) => {
            eprintln!(
                "No login detected in time — your previous account was restored. \
                 Re-run when you are ready to sign in."
            );
            1
        }
        Ok(claude_desktop::capture::CaptureOutcome::Cancelled) => {
            eprintln!("Capture cancelled — your previous account was restored.");
            1
        }
        Ok(claude_desktop::capture::CaptureOutcome::AlreadySaved(existing)) => {
            println!(
                "That account is already saved as {existing:?} — nothing new to add. \
                 You are left signed into it."
            );
            0
        }
        Ok(claude_desktop::capture::CaptureOutcome::Captured(captured)) => {
            println!(
                "  seeded         {} session(s) and {} routine(s) from your other accounts",
                captured.seeded_sessions, captured.seeded_routines
            );
            println!();
            println!(
                "Added Claude Desktop account {label:?}. Switch to it with:\n\
                 \n  ai-usagebar account switch {label} --desktop\n"
            );
            0
        }
    }
}

struct SwitchArgs<'a> {
    label: &'a str,
    desktop: bool,
    cli: bool,
    dry_run: bool,
    yes: bool,
    force: bool,
    opts: SwitchOpts,
}

fn switch(args: &SwitchArgs) -> i32 {
    let config = match config_for_mutation(Config::load()) {
        Ok(config) => config,
        Err(error) => {
            eprintln!("ai-usagebar account switch: {error}");
            return 1;
        }
    };
    // Neither flag means both surfaces. A label that only exists on one side is
    // then a skip, not a failure: the two namespaces are independent and may
    // legitimately hold different sets of accounts.
    let both = !args.desktop && !args.cli;
    let mut failed = false;
    let mut acted = false;

    if args.desktop || both {
        match switch_desktop(&config, args, both) {
            Ok(true) => acted = true,
            Ok(false) => {}
            Err(error) => {
                eprintln!("ai-usagebar account switch: {error}");
                failed = true;
            }
        }
    }
    if args.cli || both {
        if acted {
            println!();
        }
        match switch_cli(&config, args, both) {
            Ok(true) => acted = true,
            Ok(false) => {}
            Err(error) => {
                eprintln!("ai-usagebar account switch: {error}");
                failed = true;
            }
        }
    }

    if !acted && !failed {
        eprintln!(
            "ai-usagebar account switch: nothing to do for {:?}. \
             Run `ai-usagebar account status` to see the known accounts.",
            args.label
        );
        return 1;
    }
    i32::from(failed)
}

/// `Ok(false)` means "this surface does not know that label, and the other one
/// might" — reported as a note rather than an error.
fn switch_desktop(config: &Config, args: &SwitchArgs, tolerant: bool) -> Result<bool> {
    let paths = Paths::resolve(&config.anthropic)?;
    if !paths.available() {
        if !tolerant {
            return Err(AppError::Other(format!(
                "no Claude Desktop app data at {} (macOS only)",
                paths.data_dir.display()
            )));
        }
        return Ok(false);
    }

    // Keep planning and mutation in one process-wide transaction. Two menu or
    // terminal switches planned against the same live identity must not race.
    let _lock = crate::cache::acquire_lock(
        &paths.backups_dir.join(".account-switch.lock"),
        Duration::from_secs(2),
    )?;

    let plan = match claude_desktop::plan_switch(&paths, args.label, args.opts.clone()) {
        Ok(plan) => plan,
        Err(error) if tolerant => {
            println!("Claude Desktop   skipped: {error}");
            return Ok(false);
        }
        Err(error) => return Err(error),
    };
    print_plan(&plan);

    if args.dry_run {
        println!("  (dry run — nothing was changed)");
        return Ok(true);
    }
    if !args.yes
        && !confirm(&format!(
            "  Quit and relaunch the Claude Desktop app as {:?}?",
            plan.target.label
        ))
    {
        println!("  aborted (pass -y to skip this prompt)");
        return Ok(false);
    }

    let notes = claude_desktop::apply_switch(&paths, &plan, &claude_desktop::app::DesktopApp)?;
    for note in &notes {
        println!("  note: {note}");
    }
    println!(
        "  switched — the app is reopening as {:?}.",
        plan.target.label
    );
    Ok(true)
}

fn print_plan(plan: &SwitchPlan) {
    let email = plan.target.email.as_deref().unwrap_or("email unknown");
    println!("Claude Desktop   → {} ({email})", plan.target.label);
    if let Some(outgoing) = &plan.outgoing {
        println!("  saving          {outgoing}'s credential and browser state first");
    }
    match plan.target.org_uuid {
        Some(_) => {
            let routines = plan.scheduled.as_ref().map_or(0, |merge| merge.added);
            println!(
                "  history         {} new + {} refreshed session(s), {routines} routine(s)",
                plan.sessions.copied.len(),
                plan.sessions.updated.len(),
            );
        }
        None => println!("  history         skipped (no org recorded for this account yet)"),
    }
    println!("  credential      swap to the saved Desktop login");
    println!(
        "  browser state   {}",
        if plan.restores_desktop_state {
            "restore this account's cookies and local storage"
        } else {
            "none saved yet"
        }
    );
    if !plan.opts.keep_bridge {
        println!("  remote bridge   clear (a stale session id breaks /remote-control)");
    }
    if !plan.archive_members.is_empty() {
        println!("  rollback        {}", plan.archive.display());
    }
}

fn switch_cli(config: &Config, args: &SwitchArgs, tolerant: bool) -> Result<bool> {
    let accounts = config.anthropic.all_accounts();
    if tolerant && !accounts.iter().any(|a| a.label == args.label) {
        println!(
            "Claude Code      skipped: no account {:?} configured",
            args.label
        );
        return Ok(false);
    }
    let home = cli_account::home_claude_json()?;
    let outcome = cli_account::switch_cli_account(
        &home,
        &accounts,
        args.label,
        CliSwitchOpts {
            force: args.force,
            dry_run: args.dry_run,
        },
        &KeychainStore,
    )?;

    println!("Claude Code      → {}", args.label);
    match outcome {
        CliSwitchOutcome::AlreadyActive => {
            println!("  already the CLI's default login; nothing to do");
        }
        CliSwitchOutcome::RemovedDuplicate => {
            println!("  already active; removed its redundant named credential copy");
        }
        CliSwitchOutcome::WouldRemoveDuplicate => {
            println!("  would remove its redundant named credential copy");
            println!("  (dry run — nothing was changed)");
        }
        CliSwitchOutcome::RepairedActive => {
            println!("  repaired the empty default credential slot from its saved login");
        }
        CliSwitchOutcome::WouldSwitch { outgoing } => {
            print_cli_capture(outgoing.as_deref());
            println!("  (dry run — nothing was changed)");
        }
        CliSwitchOutcome::Switched { outgoing } => {
            print_cli_capture(outgoing.as_deref());
            println!(
                "  switched — plain `claude` now signs in as {:?}.",
                args.label
            );
        }
    }
    Ok(true)
}

fn print_cli_capture(outgoing: Option<&str>) {
    match outgoing {
        Some(label) => println!("  saving          {label}'s credential back into its own account"),
        None => println!("  saving          nothing to save (--force discarded the live login)"),
    }
}

fn confirm(prompt: &str) -> bool {
    matches!(
        ask(&format!("{prompt} [y/N] "))
            .unwrap_or_default()
            .to_ascii_lowercase()
            .as_str(),
        "y" | "yes"
    )
}

/// One line from the terminal, or `None` when there isn't one — piped input and
/// the menu bar's subprocess both land here, and neither can answer.
fn ask(prompt: &str) -> Option<String> {
    use std::io::IsTerminal;

    if !std::io::stdin().is_terminal() {
        return None;
    }
    print!("{prompt}");
    let _ = std::io::stdout().flush();
    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer).ok()?;
    let answer = answer.trim().to_string();
    (!answer.is_empty()).then_some(answer)
}

fn add(label: &str, login: bool) -> i32 {
    let registration = match register(label) {
        Ok(registration) => registration,
        Err(error) => {
            eprintln!("ai-usagebar account: could not add {label:?}: {error}");
            return 1;
        }
    };

    if registration.already_existed {
        println!(
            "Claude account {label:?} is already configured in {}.",
            registration.config_path.display()
        );
    } else {
        println!(
            "Added Claude account {label:?} to {}.",
            registration.config_path.display()
        );
        println!("  credentials_path = {}", registration.credential_display);
    }
    if !registration.anthropic_enabled {
        println!("  note: [anthropic] is disabled; set enabled = true for this account to appear.");
    }
    println!();

    if !registration.supports_scoped_login() {
        if login {
            eprintln!(
                "Automatic login requires this account's credentials_path to end in \
                 .credentials.json; it currently points to {}. Update that entry or \
                 keep managing its credential file manually.",
                registration.credential_file.display()
            );
            return 1;
        }
        println!("Registration kept unchanged; interactive login was not requested.");
        return 0;
    }

    if !login {
        print!("{}", manual_login_hint(&registration.account_dir));
        return 0;
    }

    // After a CLI account has been moved into the default Keychain slot, a
    // scoped login for that same active label would recreate a second copy of
    // its rotating refresh-token lineage. Reauthenticate it in the one live
    // slot instead, or switch away before recreating its named slot.
    #[cfg(target_os = "macos")]
    if cli_label_is_active(&registration.config_path, label) {
        eprintln!(
            "Cannot open an isolated login for {label:?} while it is the active plain `claude` \
             login; that would duplicate its rotating credential. Run plain `claude` to \
             reauthenticate it, or switch the CLI to another account first."
        );
        return 1;
    }

    println!(
        "Opening `claude` for {label:?} with an isolated CLAUDE_CONFIG_DIR; your \
         default Claude login is untouched."
    );
    println!();
    match login_claude_account(&registration.account_dir) {
        LoginOutcome::NotFound => {
            eprintln!("`claude` was not found on PATH. The account remains registered.\n");
            eprint!("{}", manual_login_hint(&registration.account_dir));
            1
        }
        LoginOutcome::Failed(code) => {
            eprintln!(
                "`claude` exited with status {code}. The account remains registered; retry with:\n"
            );
            eprint!("{}", manual_login_hint(&registration.account_dir));
            1
        }
        LoginOutcome::Ok => {
            // Touch metadata only: rewriting the pre-login contents here would
            // clobber config edits made while the interactive command ran.
            if let Err(error) = restamp_config(&registration.config_path) {
                eprintln!(
                    "warning: login finished, but config.toml could not be touched for live reload: {error}"
                );
            }
            println!();
            println!(
                "`claude` finished for {label:?}; the menu bar / TUI will refresh momentarily."
            );
            0
        }
    }
}

#[cfg(target_os = "macos")]
fn cli_label_is_active(config_path: &Path, label: &str) -> bool {
    let Ok(config) = Config::load_from(config_path) else {
        return false;
    };
    let Ok(home) = cli_account::home_claude_json() else {
        return false;
    };
    cli_account::resolve_active_label(&home, &config.anthropic.all_accounts()).as_deref()
        == Some(label)
}

enum LoginOutcome {
    Ok,
    Failed(i32),
    NotFound,
}

fn login_claude_account(account_dir: &Path) -> LoginOutcome {
    match std::process::Command::new("claude")
        .env("CLAUDE_CONFIG_DIR", account_dir)
        .status()
    {
        Ok(status) if status.success() => LoginOutcome::Ok,
        Ok(status) => LoginOutcome::Failed(status.code().unwrap_or(-1)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => LoginOutcome::NotFound,
        Err(_) => LoginOutcome::Failed(-1),
    }
}

fn register(label: &str) -> Result<Registered> {
    let config_path = crate::config::resolved_path()
        .or_else(crate::config::default_path)
        .ok_or_else(|| {
            AppError::Other("could not resolve a config.toml path (no home directory?)".into())
        })?;
    let home = crate::cache::home_dir().ok();
    register_at(&config_path, label, home.as_deref())
}

fn register_at(config_path: &Path, label: &str, home: Option<&Path>) -> Result<Registered> {
    let original = match std::fs::read_to_string(config_path) {
        Ok(contents) => contents,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(error) => return Err(AppError::io_at(config_path, error)),
    };
    let mut doc: toml_edit::DocumentMut = if original.trim().is_empty() {
        toml_edit::DocumentMut::new()
    } else {
        original.parse().map_err(|error: toml_edit::TomlError| {
            AppError::Other(format!("config.toml is not valid TOML: {error}"))
        })?
    };

    // Honor an existing explicit or accounts_dir-discovered account. In
    // particular, do not send a re-login to a different default directory.
    let (existing, anthropic_enabled) = if config_path.exists() {
        let config = Config::load_from(config_path)?;
        let existing = config
            .anthropic
            .all_accounts()
            .into_iter()
            .find(|account| account.label == label);
        (existing, config.anthropic.enabled)
    } else {
        (None, true)
    };
    let already_existed = existing.is_some();
    let credential_file = existing.map_or_else(
        || crate::config::default_account_credentials_path(config_path, label),
        |account| account.credentials_path,
    );
    let account_dir = credential_file
        .parent()
        .ok_or_else(|| AppError::Other("account credentials path has no parent directory".into()))?
        .to_path_buf();
    let credential_display = home.map_or_else(
        || credential_file.display().to_string(),
        |home| crate::config::tildify(&credential_file, home),
    );

    if !already_existed {
        crate::config::add_anthropic_account_to_doc(&mut doc, label, &credential_display)?;
    }

    let supports_scoped_login =
        credential_file.file_name().and_then(|name| name.to_str()) == Some(".credentials.json");
    if !already_existed || supports_scoped_login {
        let directory_was_missing = !account_dir.exists();
        std::fs::create_dir_all(&account_dir)
            .map_err(|error| AppError::io_at(&account_dir, error))?;
        if !already_existed || directory_was_missing {
            restrict_account_dir(&account_dir)?;
        }
    }
    if !already_existed {
        crate::cache::atomic_write(config_path, doc.to_string().as_bytes())?;
    }

    Ok(Registered {
        config_path: config_path.to_path_buf(),
        credential_file,
        account_dir,
        credential_display,
        already_existed,
        anthropic_enabled,
    })
}

fn restamp_config(path: &Path) -> Result<()> {
    let file = std::fs::OpenOptions::new()
        .write(true)
        .open(path)
        .map_err(|error| AppError::io_at(path, error))?;
    let times = std::fs::FileTimes::new().set_modified(std::time::SystemTime::now());
    file.set_times(times)
        .map_err(|error| AppError::io_at(path, error))
}

#[cfg(unix)]
fn restrict_account_dir(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
        .map_err(|error| AppError::io_at(path, error))
}

#[cfg(not(unix))]
fn restrict_account_dir(_path: &Path) -> Result<()> {
    Ok(())
}

fn manual_login_hint(account_dir: &Path) -> String {
    format!(
        "Sign in later with:\n\n  {}\n\nThe account appears automatically after login.\n",
        shell_login_command(account_dir)
    )
}

#[cfg(not(windows))]
fn shell_login_command(account_dir: &Path) -> String {
    let escaped = account_dir.display().to_string().replace('\'', "'\\''");
    format!("CLAUDE_CONFIG_DIR='{escaped}' claude")
}

#[cfg(windows)]
fn shell_login_command(account_dir: &Path) -> String {
    let escaped = account_dir.display().to_string().replace('\'', "''");
    format!("$env:CLAUDE_CONFIG_DIR = '{escaped}'; claude")
}

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

    #[test]
    fn mutation_commands_never_fall_back_after_a_config_error() {
        let error = config_for_mutation(Err(AppError::Other("broken config".into())))
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("refusing to change account state"),
            "{error}"
        );
        assert!(error.contains("broken config"), "{error}");
    }

    #[test]
    fn registration_uses_isolated_standard_layout() {
        let temporary = tempfile::TempDir::new().unwrap();
        let config_path = temporary.path().join("config.toml");
        let registration = register_at(&config_path, "work", Some(temporary.path())).unwrap();

        assert!(!registration.already_existed);
        assert_eq!(
            registration.credential_file,
            temporary.path().join("accounts/work/.credentials.json")
        );
        assert!(registration.supports_scoped_login());
        let written = std::fs::read_to_string(config_path).unwrap();
        assert!(written.contains("label = \"work\""));
        assert!(written.contains("credentials_path = \"~/accounts/work/.credentials.json\""));
    }

    #[cfg(unix)]
    #[test]
    fn registration_restricts_the_account_directory() {
        use std::os::unix::fs::PermissionsExt;

        let temporary = tempfile::TempDir::new().unwrap();
        let config_path = temporary.path().join("config.toml");
        let registration = register_at(&config_path, "work", None).unwrap();
        let mode = std::fs::metadata(registration.account_dir)
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o700);
    }

    #[test]
    fn existing_account_keeps_its_configured_path() {
        let temporary = tempfile::TempDir::new().unwrap();
        let config_path = temporary.path().join("config.toml");
        let credentials = temporary.path().join("custom/work.json");
        std::fs::write(
            &config_path,
            format!(
                "[[anthropic.accounts]]\nlabel = \"work\"\ncredentials_path = {:?}\n",
                credentials.display().to_string()
            ),
        )
        .unwrap();

        let registration = register_at(&config_path, "work", None).unwrap();
        assert!(registration.already_existed);
        assert_eq!(registration.credential_file, credentials);
        assert!(!registration.supports_scoped_login());
        assert!(!temporary.path().join("custom").exists());
    }

    #[test]
    fn disabled_anthropic_setting_is_preserved_and_reportable() {
        let temporary = tempfile::TempDir::new().unwrap();
        let config_path = temporary.path().join("config.toml");
        std::fs::write(&config_path, "[anthropic]\nenabled = false\n").unwrap();

        let registration = register_at(&config_path, "work", None).unwrap();
        assert!(!registration.anthropic_enabled);
        let written = std::fs::read_to_string(config_path).unwrap();
        assert!(written.contains("enabled = false"));
    }

    #[test]
    fn login_hint_quotes_paths_with_spaces() {
        let command = shell_login_command(Path::new("/tmp/Claude Accounts/work"));
        assert!(command.contains("Claude Accounts"));
        #[cfg(not(windows))]
        assert_eq!(
            command,
            "CLAUDE_CONFIG_DIR='/tmp/Claude Accounts/work' claude"
        );
    }

    #[test]
    fn restamp_never_rewrites_config_contents() {
        let temporary = tempfile::TempDir::new().unwrap();
        let path = temporary.path().join("config.toml");
        std::fs::write(&path, "# edited while login ran\n").unwrap();
        restamp_config(&path).unwrap();
        assert_eq!(
            std::fs::read_to_string(path).unwrap(),
            "# edited while login ran\n"
        );
    }
}