ai-usagebar 1.20.2

Omarchy/Waybar widgets + TUI for tracking multi-provider AI plan usage
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
//! 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::copilot;
use crate::cursor;
use crate::deepseek;
use crate::error::{AppError, Result};
use crate::grok;
use crate::grokbot;
use crate::kilo;
use crate::kimi;
use crate::kiro;
use crate::minimax;
use crate::moonshot;
use crate::novita;
use crate::ollama;
use crate::openai;
use crate::openrouter;
use crate::pango::escape;
use crate::supergrok;
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);
    validate_vendor_options(cli, vendor)?;
    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::Copilot => copilot_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::Supergrok => supergrok_output(cli, &config).await,
        Vendor::Grokbot => grokbot_output(cli, &config).await,
        Vendor::Antigravity => antigravity_output(cli, &config).await,
        Vendor::Cursor => cursor_output(cli, &config).await,
        Vendor::Minimax => minimax_output(cli, &config).await,
        Vendor::Kiro => kiro_output(cli, &config).await,
        Vendor::NousResearch => nous_output(cli).await,
        Vendor::OpenCodeGo => opencode_go_output(cli, &config).await,
        Vendor::CommandCode => commandcode_output(cli, &config).await,
        Vendor::Ollama => ollama_output(cli, &config).await,
    }
}

fn validate_vendor_options(cli: &Cli, vendor: Vendor) -> Result<()> {
    if cli.account.is_some()
        && !matches!(
            vendor,
            Vendor::Anthropic | Vendor::Openrouter | Vendor::Openai
        )
    {
        return Err(AppError::Other(
            "--account is supported only for Claude, OpenRouter, and Codex (OpenAI)".into(),
        ));
    }
    if cli.desktop && vendor != Vendor::Anthropic {
        return Err(AppError::Other(
            "--desktop is supported only for Claude accounts".into(),
        ));
    }
    Ok(())
}

/// 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())
}

/// Nous Research authenticates with the independent OAuth credential store.
async fn nous_output(cli: &Cli) -> Result<WaybarOutput> {
    let client = http_client()?;
    let store = crate::nous::credentials::CredentialStore::default();
    let endpoints = crate::nous::fetch::Endpoints::default();
    let account =
        crate::nous::fetch::fetch_account_with_refresh(&client, &store, &endpoints, Utc::now())
            .await?;
    let snapshot = account.clone();
    // Nous keeps no cache of its own, so every read is a live one.
    let outcome =
        crate::outcome::Outcome::fresh(crate::usage::VendorSnapshot::NousResearch(account));
    let theme = theme_from_cli(cli);
    Ok(crate::nous::vendor::render(
        &outcome,
        &snapshot,
        &theme,
        &RenderOpts::from_cli(cli),
        Utc::now(),
    ))
}

async fn opencode_go_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "OpenCode Go",
        &config.opencode_go.api_key_env,
        config.opencode_go.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "opencode-go")?;
    let endpoints = crate::opencode_go::fetch::Endpoints::default();
    let outcome = match crate::opencode_go::fetch::fetch_snapshot(
        &client,
        &api_key,
        &cache,
        &endpoints,
        DEFAULT_TTL,
    )
    .await
    {
        Ok(outcome) => outcome,
        Err(error) if error.is_transient() => {
            return Ok(WaybarOutput::loading(cli.icon.as_deref()));
        }
        Err(error) => return Err(error),
    };
    let snapshot = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    Ok(crate::opencode_go::vendor::render(
        &vendor_outcome,
        &snapshot,
        &theme_from_cli(cli),
        &RenderOpts::from_cli(cli),
        Utc::now(),
    ))
}

/// Command Code has no API key of its own: it reuses the OAuth credential a
/// local agent harness already holds, so there is nothing to resolve from
/// config beyond an optional override of where to look.
async fn commandcode_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let credential = crate::commandcode::creds::resolve(config.commandcode.auth_paths.as_deref())?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "commandcode")?;
    let endpoints = crate::commandcode::fetch::Endpoints::default();
    let outcome = match crate::commandcode::fetch::fetch_snapshot(
        &client,
        &credential.token,
        &cache,
        &endpoints,
        DEFAULT_TTL,
    )
    .await
    {
        Ok(outcome) => outcome,
        Err(error) if error.is_transient() => {
            return Ok(WaybarOutput::loading(cli.icon.as_deref()));
        }
        Err(error) => return Err(error),
    };
    let snapshot = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    Ok(crate::commandcode::vendor::render(
        &vendor_outcome,
        &snapshot,
        &theme_from_cli(cli),
        &RenderOpts::from_cli(cli),
        Utc::now(),
    ))
}

/// Ollama Cloud: Bearer key against `ollama.com/api/usage`. The local
/// `ollama` daemon at 127.0.0.1:11434 has no quota route and is never
/// contacted; the Ed25519 key the CLI keeps in `~/.ollama/id_ed25519` is a
/// registry credential, not a quota one, and is never read.
async fn ollama_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "Ollama",
        &config.ollama.api_key_env,
        config.ollama.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "ollama")?;
    let endpoints = ollama::fetch::Endpoints::default();
    let outcome = match ollama::fetch_snapshot(
        &client,
        &api_key,
        &config.ollama.plan,
        &cache,
        &endpoints,
        DEFAULT_TTL,
    )
    .await
    {
        Ok(outcome) => outcome,
        Err(error) if error.is_transient() => {
            return Ok(WaybarOutput::loading(cli.icon.as_deref()));
        }
        Err(error) => return Err(error),
    };
    let snapshot = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    Ok(ollama::vendor::render(
        &vendor_outcome,
        &snapshot,
        &theme_from_cli(cli),
        &RenderOpts::from_cli(cli),
        Utc::now(),
    ))
}

/// 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. With
/// none running, the Google session it saved is used instead; the config only
/// supplies the OAuth client that session is refreshed with.
async fn antigravity_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let client = http_client()?;
    let cache = vendor_cache(cli, "antigravity")?;
    let oauth = antigravity::cloud::OauthClient::from_config(
        config.antigravity.oauth_client_id.as_deref(),
        config.antigravity.oauth_client_secret.as_deref(),
    );
    let outcome =
        match antigravity::fetch_snapshot(&client, &cache, DEFAULT_TTL, oauth.as_ref()).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(),
    ))
}

/// Cursor authenticates via a session token the Cursor IDE already wrote to
/// its local `state.vscdb` — no API key to resolve, but (unlike Antigravity)
/// a real on-disk path that can be overridden, mirroring OpenAI's
/// `codex_auth_path`.
async fn cursor_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let client = http_client()?;
    let cache = vendor_cache(cli, "cursor")?;
    let db_path = match config.cursor.db_path.as_deref() {
        Some(p) => p.to_path_buf(),
        None => cursor::db::default_db_path()?,
    };
    let agent_auth_path = match config.cursor.agent_auth_path.as_deref() {
        Some(p) => p.to_path_buf(),
        None => cursor::db::default_agent_auth_path()?,
    };
    let endpoints = cursor::fetch::Endpoints::default();
    let outcome = match cursor::fetch_snapshot(
        &client,
        &db_path,
        &agent_auth_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(cursor::vendor::render(
        &vendor_outcome,
        &snap,
        &theme,
        &opts,
        chrono::Utc::now(),
    ))
}

/// Kiro CLI authenticates via the AWS SSO OIDC session kiro-cli already wrote
/// to its own local `data.sqlite3` — no API key to resolve, but (like Cursor)
/// a real on-disk path that can be overridden.
async fn kiro_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let client = http_client()?;
    let cache = vendor_cache(cli, "kiro")?;
    let db_path = match config.kiro.db_path.as_deref() {
        Some(p) => p.to_path_buf(),
        None => kiro::db::default_db_path()?,
    };
    let outcome = match kiro::fetch_snapshot(&client, &db_path, &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(kiro::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(),
    ))
}

/// SuperGrok reads billing over the CLI's documented HTTPS endpoint (or, as a
/// fallback, its ACP process). The login's `key` is used only inside one
/// outgoing Authorization header — never cached, refreshed, or written back.
async fn supergrok_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let cache = vendor_cache(cli, "supergrok")?;
    let scope_paths = supergrok::scope::ScopePaths::with_overrides(
        config.supergrok.auth_path.as_deref(),
        config.supergrok.config_path.as_deref(),
    )?;
    let outcome = match supergrok::fetch_snapshot(
        &config.supergrok.grok_binary,
        &scope_paths,
        &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(supergrok::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 minimax_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let api_key = crate::config::resolve_api_key(
        "MiniMax",
        &config.minimax.api_key_env,
        config.minimax.api_key.as_deref(),
    )?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "minimax")?;
    let endpoints = minimax::fetch::Endpoints::for_region(&config.minimax.region);
    let outcome =
        match minimax::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(minimax::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(),
    ))
}

/// Resolve a Codex login and its cache as one identity, the way
/// [`openrouter_target`] does for a key. The default login keeps the historical
/// vendor-root cache; each named account is isolated below `openai/<label>`, so
/// two ChatGPT subscriptions never serve each other's usage from a warm cache.
fn openai_target(cli: &Cli, config: &Config) -> Result<(std::path::PathBuf, Cache)> {
    let label = cli.account.as_deref();
    let creds_path = config.openai.resolve_auth_path(label)?;
    let cache = match (cli.cache_dir.as_deref(), label) {
        (Some(root), Some(label)) => Cache::at(root.join("openai").join(label)),
        (Some(root), None) => Cache::at(root.join("openai")),
        (None, Some(label)) => Cache::for_vendor_account("openai", label)?,
        (None, None) => Cache::for_vendor("openai")?,
    };
    Ok((creds_path, cache))
}

async fn openai_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let client = http_client()?;
    let (creds_path, cache) = openai_target(cli, config)?;
    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 copilot_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let token = config.copilot.resolve_token()?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "copilot")?;
    let endpoints = copilot::fetch::Endpoints::default();
    let outcome =
        match copilot::fetch_snapshot(&client, &token, &cache, &endpoints, DEFAULT_TTL).await {
            Ok(outcome) => outcome,
            Err(error) if error.is_transient() => {
                return Ok(WaybarOutput::loading(cli.icon.as_deref()));
            }
            Err(error) => return Err(error),
        };
    let snapshot = outcome.snapshot.clone();
    let vendor_outcome: VendorOutcome = outcome.into();
    Ok(copilot::vendor::render(
        &vendor_outcome,
        &snapshot,
        &theme_from_cli(cli),
        &RenderOpts::from_cli(cli),
        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, cache) = openrouter_target(cli, config)?;
    let client = http_client()?;
    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(),
    ))
}

/// Resolve an OpenRouter key and its cache as one identity. The unnamed key
/// keeps the historical vendor-root cache; each named key is isolated below
/// `openrouter/<label>` so fresh data can never cross accounts.
fn openrouter_target(cli: &Cli, config: &Config) -> Result<(String, Cache)> {
    let label = cli.account.as_deref();
    let api_key = config.openrouter.resolve_api_key(label)?;
    let cache = match (cli.cache_dir.as_deref(), label) {
        (Some(root), Some(label)) => Cache::at(root.join("openrouter").join(label)),
        (Some(root), None) => Cache::at(root.join("openrouter")),
        (None, Some(label)) => Cache::for_vendor_account("openrouter", label)?,
        (None, None) => Cache::for_vendor("openrouter")?,
    };
    Ok((api_key, cache))
}

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 (auth, endpoints) = kimi::resolve_auth(&config.kimi)?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "kimi")?;
    let outcome = match kimi::fetch::fetch_snapshot_with_auth(
        &client,
        &auth,
        &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(),
    ))
}

/// Grok Bot has no key of its own: the desktop app's session is the login, so
/// the only config input is where that file lives.
async fn grokbot_output(cli: &Cli, config: &Config) -> Result<WaybarOutput> {
    let creds = grokbot::resolve_credentials(&config.grokbot)?;
    let client = http_client()?;
    let cache = vendor_cache(cli, "grokbot")?;
    let endpoints = grokbot::fetch::Endpoints::default();
    let outcome =
        match grokbot::fetch::fetch_snapshot_with(&client, &creds, &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(grokbot::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)
}

pub(crate) fn http_client() -> Result<Client> {
    Client::builder()
        .timeout(HTTP_CLIENT_TIMEOUT)
        .redirect(crate::vendor::same_origin_redirect_policy())
        .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() {
        // `--account <label> --desktop`: read the Claude Desktop app's own token
        // for that saved profile (the menu bar's overview path). `--cache-dir`
        // still relocates the cache for scripted/multi-monitor setups.
        Some(label) if cli.desktop => {
            let (target, default_cache) =
                crate::anthropic::desktop_creds::account_target(config, label)?;
            let cache = match cli.cache_dir.as_deref() {
                Some(p) => Cache::at(p.join("anthropic").join(label)),
                None => default_cache,
            };
            Ok((target, cache))
        }
        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, .. } if matches!(status, 401 | 403) => {
            format!("HTTP {status}\n{}", crate::error::AUTH_FAILURE_MESSAGE)
        }
        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}"),
        AppError::WithPlan { source, .. } => return fallback(source, _cli),
    };
    // Tooltips are Pango markup. Escape error text before serializing it so an
    // error cannot inject markup; serde still produces valid one-line JSON.
    // `escape` also runs `display::sanitize_untrusted_field`, which is what
    // bounds and de-controls the vendor body this tooltip can carry.
    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"));
    }

    /// A vendor body reaches this tooltip verbatim on a cold cache — nothing
    /// on the way has been through `Cache::write_last_error`. What protects it
    /// is that `pango::escape` runs `sanitize_untrusted_field` first, so bidi
    /// overrides (which reorder the text around them and survive XML escaping)
    /// and a body up to the 2 MiB `MAX_BODY_BYTES` ceiling are both handled.
    /// That is load-bearing and easy to lose if `escape` is ever reduced to
    /// plain XML escaping, so pin it here at the sink that depends on it.
    #[test]
    fn fallback_strips_control_characters_and_caps_a_hostile_body() {
        let hostile = "start\u{202E}reordered\u{1B}[31m".to_string()
            + &"A".repeat(crate::display::MAX_UNTRUSTED_FIELD_CHARS);
        let out = fallback(
            &AppError::Http {
                status: 500,
                body: hostile,
            },
            &cli_default(),
        );

        assert_eq!(out.text, "\u{26a0}");
        assert!(!out.tooltip.contains('\u{202E}'), "bidi override survived");
        assert!(!out.tooltip.contains('\u{1B}'), "escape sequence survived");
        assert!(
            out.tooltip.chars().count() <= crate::display::MAX_UNTRUSTED_FIELD_CHARS,
            "uncapped tooltip of {} chars",
            out.tooltip.chars().count()
        );
        // The diagnostic itself still survives the cleaning.
        assert!(out.tooltip.contains("HTTP 500"), "{}", out.tooltip);
    }

    #[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");
        let json: serde_json::Value = serde_json::from_str(out.to_json_line().trim()).unwrap();
        assert_eq!(json["text"], "");
        assert_eq!(json["tooltip"], "bad &lt;markup&gt; &amp; value");
    }

    #[test]
    fn fallback_does_not_expose_authentication_response_bodies() {
        let out = fallback(
            &AppError::Http {
                status: 401,
                body: "PANCEA user@example.test <credential>&token".into(),
            },
            &cli_default(),
        );
        assert!(out.tooltip.contains(crate::error::AUTH_FAILURE_MESSAGE));
        assert!(!out.tooltip.contains("PANCEA"));
        assert!(!out.tooltip.contains("user@example.test"));
        assert!(!out.tooltip.contains("&amp;token"));
    }

    #[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 read strictly first; the Keychain fallback
        // (if the file is missing/unusable) is scoped to its own directory, so
        // it can never silently read a *different* account's 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::Named {
                path: PathBuf::from("/creds/work.json"),
                config_dir: PathBuf::from("/creds"),
            }
        );
        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");
    }

    #[test]
    fn openrouter_named_account_uses_its_key_and_cache_subdir() {
        let mut config = Config::default();
        config
            .openrouter
            .accounts
            .push(crate::config::OpenRouterAccount {
                label: "work".into(),
                api_key_env: None,
                api_key: Some("work-key".into()),
            });
        config
            .openrouter
            .accounts
            .push(crate::config::OpenRouterAccount {
                label: "personal".into(),
                api_key_env: None,
                api_key: Some("personal-key".into()),
            });
        let root = tempfile::tempdir().unwrap();
        let root_str = root.path().to_str().unwrap();
        let cli = cli_with(Some("work"), None, Some(root_str));
        let (key, cache) = openrouter_target(&cli, &config).unwrap();
        assert_eq!(key, "work-key");
        assert_eq!(cache.dir(), root.path().join("openrouter/work"));
        cache.write_payload(b"work-only").unwrap();

        let personal_cli = cli_with(Some("personal"), None, Some(root_str));
        let (personal_key, personal_cache) = openrouter_target(&personal_cli, &config).unwrap();
        assert_eq!(personal_key, "personal-key");
        assert!(
            personal_cache.maybe_payload().unwrap().is_none(),
            "a named account must not reuse another account's fresh cache"
        );
    }

    #[test]
    fn openrouter_default_target_keeps_the_original_cache_path() {
        let mut config = Config::default();
        config.openrouter.api_key_env.clear();
        config.openrouter.api_key = Some("default-key".into());
        let cli = cli_with(None, None, Some("/tmp/cache"));
        let (key, cache) = openrouter_target(&cli, &config).unwrap();
        assert_eq!(key, "default-key");
        assert_eq!(cache.dir(), std::path::Path::new("/tmp/cache/openrouter"));
    }

    #[test]
    fn account_flag_rejects_unrelated_vendors() {
        let cli = cli_with(Some("work"), None, Some("/tmp/cache"));
        assert!(validate_vendor_options(&cli, Vendor::Zai).is_err());
        assert!(validate_vendor_options(&cli, Vendor::Anthropic).is_ok());
        assert!(validate_vendor_options(&cli, Vendor::Openrouter).is_ok());
        assert!(validate_vendor_options(&cli, Vendor::Openai).is_ok());
    }

    #[test]
    fn desktop_flag_remains_claude_only() {
        let mut cli = cli_with(Some("work"), None, Some("/tmp/cache"));
        cli.desktop = true;
        assert!(validate_vendor_options(&cli, Vendor::Openrouter).is_err());
        assert!(validate_vendor_options(&cli, Vendor::Anthropic).is_ok());
    }
}