ai-usagebar 0.16.0

Waybar widget + TUI for AI plan usage across Anthropic, OpenAI, Z.AI, OpenRouter, DeepSeek, Kimi, and Antigravity
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
//! The always-exits-0 orchestrator. Dispatches on `--vendor`, fetches a
//! snapshot, renders the right output mode, and prints. Catches every error
//! into a fallback `⚠` JSON / pretty line so Waybar never hides the module.

use std::io::Write;
use std::time::Duration;

use chrono::Utc;
use reqwest::Client;

use crate::anthropic::{self, creds::CredsTarget, fetch::FetchOutcome};
use crate::anthropic_api;
use crate::antigravity;
use crate::cache::{Cache, DEFAULT_TTL};
use crate::config::Config;
use crate::deepseek;
use crate::error::{AppError, Result};
use crate::grok;
use crate::kilo;
use crate::kimi;
use crate::moonshot;
use crate::novita;
use crate::openai;
use crate::openrouter;
use crate::pango::escape;
use crate::theme::Theme;
use crate::vendor::{HTTP_CLIENT_TIMEOUT, RenderOpts, VendorOutcome};
use crate::waybar::WaybarOutput;
use crate::widget::cli::{Cli, Vendor};
use crate::widget::pretty::print_pretty;
use crate::widget::render::{DEFAULT_FORMAT, RenderInput, render_anthropic};
use crate::zai;

/// Entry point — runs to completion and ALWAYS returns Ok with exit code 0
/// in the caller. Mirrors claudebar's `die()` invariant.
pub async fn run(cli: Cli) -> i32 {
    // Scroll-cycle short-circuit: don't render, just bump state + signal waybar.
    if cli.cycle_next || cli.cycle_prev {
        return run_cycle(&cli).await;
    }
    if let Some(secs) = cli.watch {
        return run_watch(cli, secs).await;
    }
    run_once(&cli, &mut std::io::stdout()).await;
    0
}

/// Cycle to the next/prev enabled vendor and signal waybar to refresh.
/// Always exits 0 — Waybar swallows non-zero exits anyway.
async fn run_cycle(cli: &Cli) -> i32 {
    // Cycling against the *default* vendor set because the config failed to
    // parse would persist a selection the user never made. Do nothing instead;
    // the next render surfaces the config error through the `⚠` fallback.
    let Ok(config) = Config::load() else {
        return 0;
    };
    let enabled = config.enabled_vendors();
    if enabled.is_empty() {
        return 0;
    }
    // Starting point: current persisted vendor, else config.primary, else
    // anthropic. resolved_vendor() encodes that precedence, minus the
    // `cli.vendor` override (cycle commands ignore --vendor on purpose).
    let start = match config.ui.primary {
        Some(id) if enabled.contains(&id) => id,
        _ => enabled[0],
    };
    let delta = if cli.cycle_next { 1 } else { -1 };
    // Signalling after a *failed* persist told Waybar to re-render a selection
    // that was never written, so the bar redrew the same vendor and the scroll
    // looked like it had been swallowed. Only announce a change that happened.
    if crate::active::cycle(&enabled, start, delta).is_err() {
        return 0;
    }

    // Refresh the bar immediately. The Waybar module's `signal: 13` setting
    // means SIGRTMIN+13 re-runs the exec. SIGRTMIN is libc-dependent; the
    // shell-safe value on Linux glibc is signal 47 (= SIGRTMIN(34)+13).
    crate::waybar::request_refresh();
    0
}

/// `--watch` repaints in place, which only makes sense on a terminal. Piped or
/// redirected, the escape sequence is just garbage in the captured output.
/// Split out from the loop so the decision is testable without a real TTY.
fn should_clear_screen(stdout_is_tty: bool) -> bool {
    stdout_is_tty
}

async fn run_watch(cli: Cli, secs: u64) -> i32 {
    let interval = Duration::from_secs(secs.max(1));
    let clear = {
        use std::io::IsTerminal;
        should_clear_screen(std::io::stdout().is_terminal())
    };
    loop {
        if clear {
            // Clear screen + home cursor.
            print!("\x1b[2J\x1b[H");
        }
        let _ = std::io::stdout().flush();
        run_once(&cli, &mut std::io::stdout()).await;
        println!();
        eprintln!("(re-rendering every {secs}s — press Ctrl-C to exit)");
        tokio::select! {
            _ = tokio::time::sleep(interval) => continue,
            _ = tokio::signal::ctrl_c() => return 0,
        }
    }
}

async fn run_once(cli: &Cli, out: &mut impl Write) {
    let output = match build_output(cli).await {
        Ok(o) => o,
        Err(e) => fallback(&e, cli),
    };

    if cli.output_json() {
        let _ = out.write_all(output.to_json_line().as_bytes());
    } else {
        let _ = print_pretty(out, &output);
    }
    let _ = out.flush();
}

async fn build_output(cli: &Cli) -> Result<WaybarOutput> {
    // A broken config is reported through the `⚠` fallback (still exit 0)
    // rather than silently reverting to the default vendor set — otherwise a
    // typo'd section shows another account's usage with no diagnostic.
    let config = Config::load()?;
    let vendor = cli.resolved_vendor(&config);
    if !dispatch_is_eligible(cli, &config, vendor) {
        return Err(AppError::Other(format!(
            "vendor {:?} is disabled in {}",
            vendor,
            crate::config::config_path_hint()
        )));
    }
    match vendor {
        Vendor::Anthropic => anthropic_output(cli, &config).await,
        Vendor::AnthropicApi => anthropic_api_output(cli, &config).await,
        Vendor::Openrouter => openrouter_output(cli, &config).await,
        Vendor::Openai => openai_output(cli, &config).await,
        Vendor::Zai => zai_output(cli, &config).await,
        Vendor::Deepseek => deepseek_output(cli, &config).await,
        Vendor::Kimi => kimi_output(cli, &config).await,
        Vendor::Kilo => kilo_output(cli, &config).await,
        Vendor::Novita => novita_output(cli, &config).await,
        Vendor::Moonshot => moonshot_output(cli, &config).await,
        Vendor::Grok => grok_output(cli, &config).await,
        Vendor::Antigravity => antigravity_output(cli, &config).await,
    }
}

/// Config and persisted selections may only dispatch enabled vendors. An
/// explicit `--vendor` is an intentional CLI opt-in, including for vendors
/// that default to disabled (such as Kimi).
fn dispatch_is_eligible(cli: &Cli, config: &Config, vendor: Vendor) -> bool {
    cli.has_explicit_vendor() || config.is_enabled(vendor.to_id())
}

/// Antigravity authenticates through whichever local product is running (the
/// 2.0 app, the `agy` CLI, or the IDE) — there is no API key to resolve.
async fn antigravity_output(cli: &Cli, _config: &Config) -> Result<WaybarOutput> {
    let client = http_client()?;
    let cache = vendor_cache(cli, "antigravity")?;
    let outcome = match antigravity::fetch_snapshot(&client, &cache, DEFAULT_TTL).await {
        Ok(o) => o,
        Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
        Err(e) => return Err(e),
    };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(antigravity::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn grok_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let key = crate::config::resolve_api_key(
        "Grok",
        &config.grok.api_key_env,
        config.grok.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "grok")?;
    let endpoints = grok::fetch::Endpoints::default();
    let outcome = match grok::fetch_snapshot(
        &client,
        &key,
        &cache,
        &endpoints,
        DEFAULT_TTL,
        config.grok.team_id.as_deref(),
    )
    .await
    {
        Ok(o) => o,
        Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
        Err(e) => return Err(e),
    };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(grok::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn moonshot_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "Moonshot",
        &config.moonshot.api_key_env,
        config.moonshot.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "moonshot")?;
    let (endpoints, currency) = moonshot::fetch::Endpoints::for_region(&config.moonshot.region);
    let outcome = match moonshot::fetch_snapshot(
        &client,
        &api_key,
        &cache,
        &endpoints,
        DEFAULT_TTL,
        currency,
    )
    .await
    {
        Ok(o) => o,
        Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
        Err(e) => return Err(e),
    };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(moonshot::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn novita_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "Novita",
        &config.novita.api_key_env,
        config.novita.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "novita")?;
    let endpoints = novita::fetch::Endpoints::default();
    let outcome =
        match novita::fetch_snapshot(&client, &api_key, &cache, &endpoints, DEFAULT_TTL).await {
            Ok(o) => o,
            Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
            Err(e) => return Err(e),
        };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(novita::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn kilo_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "Kilo",
        &config.kilo.api_key_env,
        config.kilo.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "kilo")?;
    let endpoints = kilo::fetch::Endpoints::default();
    let outcome = match kilo::fetch_snapshot(
        &client,
        &api_key,
        &cache,
        &endpoints,
        DEFAULT_TTL,
        config.kilo.organization_id.as_deref(),
    )
    .await
    {
        Ok(o) => o,
        Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
        Err(e) => return Err(e),
    };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(kilo::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn anthropic_api_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let key = crate::config::resolve_api_key(
        "Anthropic_API",
        &config.anthropic_api.api_key_env,
        config.anthropic_api.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "anthropic_api")?;
    let endpoints = anthropic_api::fetch::Endpoints::default();
    let outcome = match anthropic_api::fetch_snapshot(
        &client,
        &key,
        &cache,
        &endpoints,
        DEFAULT_TTL,
        config.anthropic_api.monthly_limit,
    )
    .await
    {
        Ok(o) => o,
        Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
        Err(e) => return Err(e),
    };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(anthropic_api::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn openai_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let client = http_client()?;
    let cache = vendor_cache(cli, "openai")?;
    let creds_path = match config.openai.codex_auth_path.as_deref() {
        Some(p) => p.to_path_buf(),
        None => openai::creds::default_path()?,
    };
    let endpoints = openai::fetch::Endpoints::default();
    let outcome =
        match openai::fetch_snapshot(&client, &creds_path, &cache, &endpoints, DEFAULT_TTL).await {
            Ok(o) => o,
            Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
            Err(e) => return Err(e),
        };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(openai::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn zai_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "Zai",
        &config.zai.api_key_env,
        config.zai.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "zai")?;
    let endpoints = zai::fetch::Endpoints::default();
    let outcome = match zai::fetch_snapshot(
        &client,
        &api_key,
        &cache,
        &endpoints,
        DEFAULT_TTL,
        config.zai.plan_tier.as_deref(),
    )
    .await
    {
        Ok(o) => o,
        Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
        Err(e) => return Err(e),
    };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(zai::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn openrouter_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "OpenRouter",
        &config.openrouter.api_key_env,
        config.openrouter.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "openrouter")?;
    let endpoints = openrouter::fetch::Endpoints::default();
    let outcome = match openrouter::fetch_snapshot(
        &client,
        &api_key,
        &cache,
        &endpoints,
        DEFAULT_TTL,
    )
    .await
    {
        Ok(o) => o,
        Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
        Err(e) => return Err(e),
    };

    let theme = theme_from_cli(cli);

    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(openrouter::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn deepseek_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "DeepSeek",
        &config.deepseek.api_key_env,
        config.deepseek.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "deepseek")?;
    let endpoints = deepseek::fetch::Endpoints::default();
    let outcome =
        match deepseek::fetch_snapshot(&client, &api_key, &cache, &endpoints, DEFAULT_TTL).await {
            Ok(o) => o,
            Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
            Err(e) => return Err(e),
        };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(deepseek::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn kimi_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "Kimi",
        &config.kimi.api_key_env,
        config.kimi.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "kimi")?;
    let endpoints = kimi::fetch::Endpoints::default();
    let outcome =
        match kimi::fetch_snapshot(&client, &api_key, &cache, &endpoints, DEFAULT_TTL).await {
            Ok(o) => o,
            Err(e) if e.is_transient() => return Ok(WaybarOutput::loading(cli.icon.as_deref())),
            Err(e) => return Err(e),
        };

    let theme = theme_from_cli(cli);
    let snap = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    let opts = RenderOpts::from_cli(cli);
    Ok(kimi::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

async fn anthropic_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let client = http_client()?;
    let (creds_target, cache) = anthropic_target(cli, config)?;
    let endpoints = anthropic::fetch::Endpoints::default();
    let outcome =
        match anthropic::fetch_snapshot(&client, &creds_target, &cache, &endpoints, DEFAULT_TTL)
            .await
        {
            Ok(o) => o,
            Err(e) if e.is_transient() => {
                // Mirror claudebar's `loading_network` path.
                return Ok(WaybarOutput::loading(cli.icon.as_deref()));
            }
            Err(e) => return Err(e),
        };

    let theme = theme_from_cli(cli);

    Ok(render_with_theme(&outcome, &theme, cli))
}

fn render_with_theme(outcome: &FetchOutcome, theme: &Theme, cli: &Cli) -> WaybarOutput {
    let format_owned = cli
        .format
        .clone()
        .unwrap_or_else(|| DEFAULT_FORMAT.to_string());
    let input = RenderInput {
        outcome,
        theme,
        format: &format_owned,
        tooltip_format: cli.tooltip_format.as_deref(),
        icon: cli.icon.as_deref(),
        pace_tolerance: cli.pace_tolerance,
        format_pace_color: cli.format_pace_color,
        tooltip_pace_pts: cli.tooltip_pace_pts,
        now: Utc::now(),
    };
    render_anthropic(&input)
}

fn http_client() -> Result<Client> {
    Client::builder()
        .timeout(HTTP_CLIENT_TIMEOUT)
        .build()
        .map_err(|e| AppError::Other(format!("http client init: {e}")))
}

fn vendor_cache(cli: &Cli, vendor: &str) -> Result<Cache> {
    match cli.cache_dir.as_deref() {
        Some(p) => Ok(Cache::at(p.join(vendor))),
        None => Cache::for_vendor(vendor),
    }
}

/// Resolve the Anthropic credentials target + cache for this run, honoring
/// `--account` (issue #14). `--cache-dir` still overrides the cache location;
/// `--account <label>` selects a configured extra account (its credentials
/// file and an `anthropic/<label>` cache subdir); with neither, the default
/// account behaves byte-identically to before.
fn anthropic_target(cli: &Cli, config: &Config) -> Result<(CredsTarget, Cache)> {
    match cli.account.as_deref() {
        Some(label) => named_account_target(cli, config, label),
        None => Ok((
            anthropic_default_creds(cli, config)?,
            vendor_cache(cli, "anthropic")?,
        )),
    }
}

/// A configured extra account (`--account <label>`): its own credentials file
/// and an isolated `anthropic/<label>` cache. `--account` conflicts with
/// `--creds-path`, so the account's file is the only credentials source here —
/// an Explicit target, so a missing/broken file fails loudly instead of
/// falling back to the (different account's) macOS Keychain item (#15).
fn named_account_target(cli: &Cli, config: &Config, label: &str) -> Result<(CredsTarget, Cache)> {
    let (creds, default_cache) = config.anthropic.account_target(label)?;
    // `--cache-dir` still wins for scripted/multi-monitor setups; otherwise use
    // the account's default `anthropic/<label>` cache from account_target.
    let cache = match cli.cache_dir.as_deref() {
        Some(p) => Cache::at(p.join("anthropic").join(label)),
        None => default_cache,
    };
    Ok((creds, cache))
}

/// Default-account credentials: `--creds-path` wins, then the singular
/// `[anthropic] credentials_path`, then the platform default file. This is the
/// pre-#14 resolution, kept intact so default output never changes. Only the
/// platform-default file is a `Default` target (eligible for the macOS
/// Keychain fallback); the two overrides are explicit user choices, read
/// strictly.
fn anthropic_default_creds(cli: &Cli, config: &Config) -> Result<CredsTarget> {
    if let Some(p) = cli.creds_path.as_deref() {
        return Ok(CredsTarget::Explicit(p.to_path_buf()));
    }
    if let Some(p) = config.anthropic.credentials_path.as_deref() {
        return Ok(CredsTarget::Explicit(p.to_path_buf()));
    }
    Ok(CredsTarget::Default(anthropic::creds::default_path()?))
}

fn theme_from_cli(cli: &Cli) -> Theme {
    Theme::default().merged_with_omarchy().with_overrides(
        cli.color_low.clone(),
        cli.color_mid.clone(),
        cli.color_high.clone(),
        cli.color_critical.clone(),
    )
}

/// Fallback output when everything goes wrong — always renders a `⚠` widget.
fn fallback(err: &AppError, _cli: &Cli) -> WaybarOutput {
    let tooltip = match err {
        AppError::Credentials(m) => format!("Credentials error.\n{m}"),
        AppError::Http { status, body } => format!("HTTP {status}\n{body}"),
        AppError::Schema(m) => format!("API schema drift.\n{m}"),
        AppError::Io { path, source } => format!("I/O error at {}.\n{source}", path.display()),
        AppError::Other(m) | AppError::Transport(m) => m.clone(),
        AppError::Json(e) => format!("JSON error: {e}"),
        AppError::Toml(e) => format!("TOML error: {e}"),
        AppError::IoBare(e) => format!("I/O error: {e}"),
    };
    // Tooltips are Pango markup. Escape error text before serializing it so an
    // error cannot inject markup; serde still produces valid one-line JSON.
    WaybarOutput::error(&escape(&tooltip))
}

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

    use crate::anthropic::fetch::FetchOutcome;
    use crate::usage::{AnthropicSnapshot, UsageWindow};

    fn cli_default() -> Cli {
        // clap's Default isn't derived for us; build from parse_from with no
        // args to get the canonical defaults.
        use clap::Parser;
        Cli::parse_from(["ai-usagebar"])
    }

    fn dummy_outcome() -> FetchOutcome {
        FetchOutcome {
            snapshot: AnthropicSnapshot {
                plan: "Test".into(),
                session: UsageWindow {
                    utilization_pct: 25,
                    resets_at: None,
                    window_duration: chrono::Duration::hours(5),
                },
                weekly: UsageWindow {
                    utilization_pct: 10,
                    resets_at: None,
                    window_duration: chrono::Duration::days(7),
                },
                sonnet: None,
                scoped: vec![],
                extra: None,
            },
            stale: false,
            last_error: None,
            cache_age: None,
        }
    }

    #[test]
    fn render_with_theme_uses_cli_overrides() {
        let cli = {
            let mut c = cli_default();
            c.format = Some("test:{session_pct}".into());
            c.color_low = Some("#123456".into());
            c
        };
        let outcome = dummy_outcome();
        let theme = Theme::default().with_overrides(cli.color_low.clone(), None, None, None);
        let out = render_with_theme(&outcome, &theme, &cli);
        // Bar text should contain our format substitution, wrapped in the
        // overridden low-color span.
        assert!(out.text.contains("test:25"));
        assert!(out.text.contains("#123456"));
    }

    #[test]
    fn fallback_wraps_credentials_error_in_warning() {
        let err = AppError::Credentials("missing token".into());
        let out = fallback(&err, &cli_default());
        assert_eq!(out.text, "");
        assert!(out.tooltip.contains("missing token"));
    }

    #[test]
    fn watch_only_clears_the_screen_on_a_terminal() {
        // Redirected to a file or piped, the clear-screen escape is garbage in
        // the captured output.
        assert!(should_clear_screen(true));
        assert!(!should_clear_screen(false));
    }

    #[test]
    fn a_failed_cycle_persist_is_not_announced_to_waybar() {
        // Signalling after a failed persist made Waybar re-render the *same*
        // vendor, so the scroll looked swallowed. An empty vendor set is the
        // reachable failure: `cycle_at` errors and nothing is written.
        let td = tempfile::TempDir::new().unwrap();
        let path = td.path().join("active_vendor");
        let r = crate::active::cycle_at(&path, &[], crate::vendor::VendorId::Anthropic, 1);
        assert!(r.is_err());
        assert!(
            crate::active::read_from(&path).is_none(),
            "a failed cycle must not have persisted anything"
        );
    }

    #[test]
    fn fallback_reports_a_broken_config_without_breaking_exit_0() {
        // Propagating the config error must still land in the `⚠` fallback —
        // Waybar hides modules that exit non-zero, so a broken config has to
        // be *visible*, not fatal.
        let toml_err = toml::from_str::<Config>("[zai\nenabled = true\n").unwrap_err();
        let out = fallback(&AppError::Toml(toml_err), &cli_default());
        assert_eq!(out.text, "");
        assert!(out.tooltip.contains("TOML error"));
    }

    #[test]
    fn fallback_escapes_pango_and_keeps_valid_json() {
        let out = fallback(
            &AppError::Other("bad <markup> & value".into()),
            &cli_default(),
        );
        assert_eq!(out.tooltip, "bad &lt;markup&gt; &amp; value");
        assert!(serde_json::from_str::<serde_json::Value>(out.to_json_line().trim()).is_ok());
    }

    #[test]
    fn explicit_kimi_is_eligible_when_disabled_in_config() {
        use clap::Parser;
        let cli = Cli::parse_from(["ai-usagebar", "--vendor", "kimi"]);
        let config = Config::default();
        let vendor = cli.resolve_vendor_with(&config, None);
        assert_eq!(vendor, Vendor::Kimi);
        assert!(dispatch_is_eligible(&cli, &config, vendor));
    }

    #[test]
    fn implicit_disabled_vendor_is_not_dispatch_eligible() {
        let cli = cli_default();
        let config = Config::default();
        assert!(!dispatch_is_eligible(&cli, &config, Vendor::Kimi));
        // Normal implicit resolution avoids that disabled vendor entirely.
        assert_eq!(cli.resolve_vendor_with(&config, None), Vendor::Anthropic);
    }

    // --- issue #14: multi-account Anthropic target resolution ---------------
    // All hermetic: paths are only *resolved*, never opened, and every cache
    // uses an explicit --cache-dir (Cache::at) so no test touches real XDG.

    fn cli_with(account: Option<&str>, creds: Option<&str>, cache: Option<&str>) -> Cli {
        let mut c = cli_default();
        c.account = account.map(str::to_string);
        c.creds_path = creds.map(PathBuf::from);
        c.cache_dir = cache.map(PathBuf::from);
        c
    }

    fn config_with_account(label: &str, creds: &str) -> Config {
        let mut config = Config::default();
        config
            .anthropic
            .accounts
            .push(crate::config::AnthropicAccount {
                label: label.into(),
                credentials_path: creds.into(),
            });
        config
    }

    #[test]
    fn default_account_target_is_unchanged() {
        // No --account: creds come from --creds-path and the cache stays at the
        // vendor root (…/anthropic) — byte-identical to the pre-#14 path. An
        // explicit --creds-path is a strict (non-Keychain) target.
        let cli = cli_with(None, Some("/tmp/creds.json"), Some("/tmp/cache"));
        let (creds, cache) = anthropic_target(&cli, &Config::default()).unwrap();
        assert_eq!(
            creds,
            CredsTarget::Explicit(PathBuf::from("/tmp/creds.json"))
        );
        assert_eq!(cache.dir(), std::path::Path::new("/tmp/cache/anthropic"));
    }

    #[test]
    fn default_account_without_overrides_is_keychain_eligible() {
        // No --account, no --creds-path, no config path → the platform-default
        // location, the only target eligible for the macOS Keychain fallback.
        let cli = cli_with(None, None, Some("/tmp/cache"));
        let (creds, _cache) = anthropic_target(&cli, &Config::default()).unwrap();
        assert!(matches!(creds, CredsTarget::Default(_)));
    }

    #[test]
    fn named_account_uses_its_creds_and_label_subdir() {
        // A named account's file is Explicit: a missing/broken path must fail
        // loudly, never silently read another account's Keychain item (#15).
        let config = config_with_account("work", "/creds/work.json");
        let cli = cli_with(Some("work"), None, Some("/tmp/cache"));
        let (creds, cache) = anthropic_target(&cli, &config).unwrap();
        assert_eq!(
            creds,
            CredsTarget::Explicit(PathBuf::from("/creds/work.json"))
        );
        assert_eq!(
            cache.dir(),
            std::path::Path::new("/tmp/cache/anthropic/work")
        );
    }

    #[test]
    fn unknown_account_errors_listing_known_labels() {
        let config = config_with_account("work", "/creds/work.json");
        let cli = cli_with(Some("nope"), None, Some("/tmp/cache"));
        let err = anthropic_target(&cli, &config).unwrap_err();
        let msg = format!("{err:?}");
        assert!(msg.contains("nope"), "names the bad label: {msg}");
        assert!(msg.contains("work"), "lists known labels: {msg}");
    }

    #[test]
    fn account_conflicts_with_creds_path() {
        use clap::Parser;
        let res = Cli::try_parse_from(["ai-usagebar", "--account", "work", "--creds-path", "/x"]);
        assert!(res.is_err(), "--account and --creds-path must conflict");
    }
}