ai-usagebar 0.21.0

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
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
//! TUI app state — vendors, tab selection, per-vendor snapshot cache.

use std::collections::HashSet;
use std::time::Duration;

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

use crate::cache::DEFAULT_TTL;
use crate::config::Config;
use crate::error::Result;
use crate::theme::Theme;
use crate::vendor::{VendorId, VendorOutcome};

/// What we display per vendor — raw snapshot + fetch metadata for native
/// panel rendering, or an error message when the fetch failed.
///
/// `Ready` is boxed because the snapshot is much larger than the other two
/// variants (silences `clippy::large_enum_variant`).
#[derive(Debug, Clone)]
pub enum TabState {
    Loading,
    Ready(Box<ReadyTab>),
    Error(String),
}

#[derive(Debug, Clone)]
pub struct ReadyTab {
    pub snapshot: crate::usage::VendorSnapshot,
    pub stale: bool,
    pub last_error: Option<(u16, String)>,
    /// Absolute moment the cache was written (i.e. the API response landed).
    /// Snapshotted once at TabState build time so the rendered "Updated …"
    /// timestamp stays stable across redraws instead of drifting with the
    /// passing wall clock.
    pub fetched_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// Identity of one TUI tab. Usually a whole vendor; for Anthropic it can also
/// name a specific configured account (issues #14 / #17). `account: None` is a
/// plain vendor tab — the default Claude account, or any non-Anthropic vendor.
/// `desktop` marks an account whose usage comes from the Claude Desktop app's
/// own token rather than a `claude` CLI credential.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TabId {
    pub vendor: VendorId,
    pub account: Option<String>,
    pub desktop: bool,
}

impl TabId {
    /// A plain vendor tab (default account for Anthropic).
    pub fn vendor(vendor: VendorId) -> Self {
        Self {
            vendor,
            account: None,
            desktop: false,
        }
    }

    /// A named Anthropic account tab (`[[anthropic.accounts]]` label).
    pub fn account(label: impl Into<String>) -> Self {
        Self {
            vendor: VendorId::Anthropic,
            account: Some(label.into()),
            desktop: false,
        }
    }

    /// An Anthropic account whose usage is read from the Claude Desktop app's
    /// own token store (a saved `~/.claude-acc/profiles/<label>` account).
    pub fn desktop_account(label: impl Into<String>) -> Self {
        Self {
            vendor: VendorId::Anthropic,
            account: Some(label.into()),
            desktop: true,
        }
    }
}

/// Expand enabled vendors into the tab list. Anthropic yields its default
/// account tab followed by one tab per `[[anthropic.accounts]]` entry, in
/// config order; every other vendor is a single tab. With no extra accounts
/// configured the result equals `config.enabled_vendors()` — identical tab set
/// and order to before (issue #14/#17 back-compat).
///
/// Config-only and pure — no Desktop profiles. Production uses
/// [`tabs_with_desktop`]; this stays for the hermetic unit tests and any caller
/// that only wants configured accounts.
pub fn tabs_from_config(config: &Config) -> Vec<TabId> {
    build_tabs(config, &[], &[])
}

/// The production tab list: configured accounts plus every saved Claude Desktop
/// profile that has usable credentials and is not already a working CLI account.
/// Desktop discovery is best-effort and macOS-only; anywhere else this equals
/// [`tabs_from_config`].
pub fn tabs_with_desktop(config: &Config) -> Vec<TabId> {
    let desktop = desktop_profile_labels(config);
    // A configured CLI account normally wins its label, but only if it can
    // actually authenticate. A half-finished `account add <label>` (config
    // entry written, login never completed) would otherwise mask a perfectly
    // good Desktop profile of the same name — the account shows an error
    // instead of its usage. Where that happens, let the Desktop source take
    // over. Checked only for labels that exist in both, so the credential probe
    // is rare.
    let broken = broken_cli_labels(config, &desktop);
    build_tabs(config, &desktop, &broken)
}

/// Core expansion, parameterized so it stays pure and unit-testable.
/// `desktop_labels` are Claude Desktop accounts; `broken_cli` names configured
/// CLI accounts to drop (their credential is unusable and a Desktop profile
/// covers them). Desktop accounts follow the CLI accounts, de-duplicated by
/// label (a *working* configured CLI account wins), and count toward "Anthropic
/// has accounts" for the default-tab suppression.
fn build_tabs(config: &Config, desktop_labels: &[String], broken_cli: &[String]) -> Vec<TabId> {
    let mut tabs = Vec::new();
    for vendor in config.enabled_vendors() {
        if vendor == VendorId::Anthropic {
            let accounts: Vec<_> = config
                .anthropic
                .all_accounts()
                .into_iter()
                .filter(|a| !broken_cli.iter().any(|b| b == &a.label))
                .collect();
            let cli_labels: HashSet<&str> = accounts.iter().map(|a| a.label.as_str()).collect();
            let desktop: Vec<&String> = desktop_labels
                .iter()
                .filter(|label| !cli_labels.contains(label.as_str()))
                .collect();
            // The default (unnamed) Claude tab is suppressible once every
            // account is named — but never when it would leave Anthropic with
            // no tab at all. Desktop accounts count as named accounts here.
            if config.anthropic.show_default_account || (accounts.is_empty() && desktop.is_empty())
            {
                tabs.push(TabId::vendor(vendor));
            }
            for acct in accounts {
                tabs.push(TabId::account(acct.label));
            }
            for label in desktop {
                tabs.push(TabId::desktop_account(label.clone()));
            }
        } else {
            tabs.push(TabId::vendor(vendor));
        }
    }
    tabs
}

/// Configured CLI accounts that both (a) share a label with a Desktop profile
/// and (b) can't authenticate — so the Desktop source should win. Resolving the
/// credential may read the macOS Keychain, so this only runs for the rare label
/// present in both places.
fn broken_cli_labels(config: &Config, desktop_labels: &[String]) -> Vec<String> {
    use crate::anthropic::creds;
    config
        .anthropic
        .all_accounts()
        .into_iter()
        .filter(|a| desktop_labels.iter().any(|d| d == &a.label))
        .filter(|a| match config.anthropic.account_target(&a.label) {
            Ok((target, _)) => creds::resolve(&target)
                .map(|(c, _)| creds::is_unusable(&c.claude_ai_oauth))
                .unwrap_or(true),
            Err(_) => true,
        })
        .map(|a| a.label)
        .collect()
}

/// Labels of saved Claude Desktop profiles with usable credentials. macOS-only
/// (elsewhere there is no Desktop app); best-effort, so an unreadable profile
/// store just yields none rather than failing the whole tab list.
#[cfg(target_os = "macos")]
fn desktop_profile_labels(config: &Config) -> Vec<String> {
    let Ok(paths) = crate::claude_desktop::Paths::resolve(&config.anthropic) else {
        return Vec::new();
    };
    if !paths.available() {
        return Vec::new();
    }
    crate::claude_desktop::load_profiles(&paths.profiles_dir)
        .into_iter()
        .filter(|p| p.has_credentials)
        .map(|p| p.label)
        .collect()
}

#[cfg(not(target_os = "macos"))]
fn desktop_profile_labels(_config: &Config) -> Vec<String> {
    Vec::new()
}

#[derive(Debug)]
pub struct App {
    pub tabs_meta: Vec<TabId>,
    pub active: usize,
    pub tabs: Vec<TabState>,
    /// Tab identities with a request currently in flight. Kept separate from
    /// `tabs` so a successful snapshot remains visible while it is refreshed.
    refreshing_tabs: HashSet<TabId>,
    /// Monotonically increasing identity for a complete tab-set replacement.
    /// Background fetches carry this with their tab identity so results from a
    /// previous Settings reload cannot land in a new tab at the old index.
    pub tab_generation: u64,
    /// When `true`, the Overview pane is selected (the virtual first tab that
    /// summarizes every vendor at once) instead of a per-vendor detail tab.
    pub overview: bool,
    /// Which vendors the Overview lists (`[ui] overview_vendors`); `None` = all.
    pub overview_vendors: Option<Vec<VendorId>>,
    pub theme: Theme,
    pub quit: bool,
    /// When `Some`, the Settings overlay is open and consuming key events.
    pub settings: Option<crate::tui::settings::SettingsState>,
    /// Local context monitoring is separately opt-in and never changes the
    /// vendor tab set.
    pub context_enabled: bool,
    /// Monotonic across overlay close/reopen cycles so an old detached scan
    /// can never share the new overlay's first generation number.
    pub context_generation: u64,
    /// When `Some`, the local Claude Code context overlay owns keyboard input.
    pub context: Option<crate::tui::context::ContextState>,
    /// Presentation style for the vendor navigation box (`[ui] vendor_box`).
    pub vendor_box: crate::config::VendorBoxStyle,
}

impl App {
    pub fn new(tabs_meta: Vec<TabId>) -> Self {
        // Production: resolve the palette from the environment (Omarchy theme
        // if present, else One Dark).
        Self::with_theme(tabs_meta, Theme::default().merged_with_omarchy())
    }

    /// Like [`App::new`] but with an explicit theme. Lets tests build an `App`
    /// without reading the real Omarchy theme file
    /// (`$HOME/.config/omarchy/current/theme/colors.toml`) — `new` resolves
    /// that path and the `$HOME` env var via `merged_with_omarchy`, which is
    /// not hermetic. Production code uses `new`/`new_with_primary`.
    pub fn with_theme(tabs_meta: Vec<TabId>, theme: Theme) -> Self {
        let n = tabs_meta.len();
        Self {
            tabs_meta,
            active: 0,
            tabs: vec![TabState::Loading; n],
            refreshing_tabs: HashSet::new(),
            tab_generation: 0,
            overview: false,
            overview_vendors: None,
            theme,
            quit: false,
            settings: None,
            context_enabled: false,
            context_generation: 0,
            context: None,
            vendor_box: crate::config::VendorBoxStyle::Sidebar,
        }
    }

    /// Construct with an initial active tab — usually `[ui] primary` from
    /// config. Silently falls through to index 0 if the requested vendor
    /// isn't present (e.g. it was disabled).
    pub fn new_with_primary(tabs_meta: Vec<TabId>, primary: Option<VendorId>) -> Self {
        let mut app = Self::new(tabs_meta);
        // Default landing is the Overview (show everything at once). An explicit
        // `[ui] primary` opts into opening on that vendor's tab instead.
        if primary.is_some() {
            app.select_primary(primary);
        } else {
            app.overview = true;
        }
        app
    }

    pub fn active_tab_id(&self) -> Option<&TabId> {
        self.tabs_meta.get(self.active)
    }

    pub fn active_vendor(&self) -> Option<VendorId> {
        self.tabs_meta.get(self.active).map(|t| t.vendor)
    }

    /// Replace the tab set — used after a Settings save reloads config, so
    /// tabs added or removed in `config.toml` while the TUI is open (e.g. a
    /// new `[[anthropic.accounts]]` entry) appear without a restart. Every
    /// tab resets to `Loading` (the caller re-spawns fetches). The selected tab
    /// is preserved by identity when possible; otherwise its old position is
    /// clamped in case the list shrank.
    pub fn set_tabs(&mut self, tabs_meta: Vec<TabId>) {
        let selected = self.active_tab_id().cloned();
        let fallback = self.active.min(tabs_meta.len().saturating_sub(1));
        self.tab_generation = self.tab_generation.wrapping_add(1);
        self.active = selected
            .as_ref()
            .and_then(|tab| tabs_meta.iter().position(|candidate| candidate == tab))
            .unwrap_or(fallback);
        self.tabs = vec![TabState::Loading; tabs_meta.len()];
        self.tabs_meta = tabs_meta;
        self.refreshing_tabs.clear();
    }

    /// Mark one tab as in flight. A ready snapshot stays in place; tabs that
    /// have never succeeded still use the full `Loading` state. Returning
    /// `false` suppresses duplicate requests for the same tab.
    pub fn begin_refresh(&mut self, tab: &TabId) -> bool {
        let Some(index) = self.tabs_meta.iter().position(|current| current == tab) else {
            return false;
        };
        if !self.refreshing_tabs.insert(tab.clone()) {
            return false;
        }
        if !matches!(self.tabs[index], TabState::Ready(_)) {
            self.tabs[index] = TabState::Loading;
        }
        true
    }

    pub fn is_refreshing(&self, tab: &TabId) -> bool {
        self.refreshing_tabs.contains(tab)
    }

    pub fn tab_is_refreshing(&self, index: usize) -> bool {
        self.tabs_meta
            .get(index)
            .is_some_and(|tab| self.is_refreshing(tab))
    }

    /// Apply an asynchronous refresh only when it still belongs to this tab
    /// generation and the captured tab identity still exists. Lookup by
    /// identity, rather than the old positional index, also makes a reordered
    /// tab list safe.
    pub fn apply_refresh(&mut self, generation: u64, tab: &TabId, state: TabState) -> bool {
        if generation != self.tab_generation {
            return false;
        }
        let Some(index) = self.tabs_meta.iter().position(|current| current == tab) else {
            return false;
        };
        let was_refreshing = self.refreshing_tabs.remove(tab);
        // If revalidation fails after a successful snapshot, preserve the
        // useful data but make the failure explicit. Initial failures still
        // become the normal Error state because there is no data to preserve.
        if was_refreshing
            && let TabState::Ready(ready) = &mut self.tabs[index]
            && let TabState::Error(message) = state
        {
            ready.stale = true;
            ready.last_error = Some((0, message));
        } else {
            self.tabs[index] = state;
        }
        true
    }

    /// Move to the first tab of `primary`'s vendor (the default account tab,
    /// since it precedes any of that vendor's account tabs).
    pub fn select_primary(&mut self, primary: Option<VendorId>) {
        if let Some(p) = primary
            && let Some(idx) = self.tabs_meta.iter().position(|t| t.vendor == p)
        {
            self.active = idx;
            self.overview = false;
        }
    }

    /// The selectable ring is `[Overview, tab0, tab1, …]`. `next_tab`/`prev_tab`
    /// walk it, wrapping through the Overview at the ends.
    pub fn next_tab(&mut self) {
        if self.overview {
            if !self.tabs_meta.is_empty() {
                self.overview = false;
                self.active = 0;
            }
        } else if self.active + 1 < self.tabs_meta.len() {
            self.active += 1;
        } else {
            self.overview = true;
        }
    }

    pub fn prev_tab(&mut self) {
        if self.overview {
            if !self.tabs_meta.is_empty() {
                self.overview = false;
                self.active = self.tabs_meta.len() - 1;
            }
        } else if self.active > 0 {
            self.active -= 1;
        } else {
            self.overview = true;
        }
    }

    /// Tabs the Overview should list: `overview_vendors` filtered against the
    /// live tab set (preserving the config order), or all tabs when unset.
    pub fn overview_tabs(&self) -> Vec<usize> {
        match &self.overview_vendors {
            None => (0..self.tabs_meta.len()).collect(),
            Some(wanted) => wanted
                .iter()
                .flat_map(|v| {
                    self.tabs_meta
                        .iter()
                        .enumerate()
                        .filter(move |(_, t)| t.vendor == *v)
                        .map(|(i, _)| i)
                })
                .collect(),
        }
    }
}

/// Fetch and render one tab — returns a `TabState`.
pub async fn refresh_one(client: &Client, config: &Config, tab: &TabId) -> TabState {
    match build_outcome(client, config, tab).await {
        Ok(outcome) => {
            // Resolve the cache age (a duration from "now" at fetch time) into an
            // absolute instant ONCE. Without this, sections_for would recompute
            // `Utc::now() - cache_age` on every draw and the displayed time would
            // tick upward in real time instead of holding at the last refresh.
            let now = Utc::now();
            let fetched_at = outcome
                .cache_age
                .map(|age| now - chrono::Duration::from_std(age).unwrap_or_default());
            TabState::Ready(Box::new(ReadyTab {
                snapshot: outcome.snapshot,
                stale: outcome.stale,
                last_error: outcome.last_error.map(|(code, message)| {
                    (code, crate::display::sanitize_untrusted_field(&message))
                }),
                fetched_at,
            }))
        }
        Err(e) => TabState::Error(crate::display::sanitize_untrusted_field(&e.to_string())),
    }
}

async fn build_outcome(client: &Client, config: &Config, tab: &TabId) -> Result<VendorOutcome> {
    match tab.vendor {
        VendorId::Anthropic => {
            // A named account resolves to its own file + `anthropic/<label>`
            // cache, shared with the widget via `account_target` (#14/#17).
            // The default tab keeps the pre-existing resolution: config
            // `credentials_path` is an explicit strict read, and only the
            // platform default gets the macOS Keychain fallback.
            let (creds_target, cache) = match tab.account.as_deref() {
                Some(label) if tab.desktop => {
                    crate::anthropic::desktop_creds::account_target(config, label)?
                }
                Some(label) => config.anthropic.account_target(label)?,
                None => {
                    let target = match config.anthropic.credentials_path.clone() {
                        Some(p) => crate::anthropic::creds::CredsTarget::Explicit(p),
                        None => crate::anthropic::creds::CredsTarget::Default(
                            crate::anthropic::creds::default_path().unwrap_or_default(),
                        ),
                    };
                    (target, crate::cache::Cache::for_vendor("anthropic")?)
                }
            };
            let endpoints = crate::anthropic::fetch::Endpoints::default();
            let outcome = crate::anthropic::fetch_snapshot(
                client,
                &creds_target,
                &cache,
                &endpoints,
                DEFAULT_TTL,
            )
            .await?;
            Ok(crate::vendor::VendorOutcome {
                snapshot: crate::usage::VendorSnapshot::Anthropic(outcome.snapshot),
                stale: outcome.stale,
                last_error: outcome.last_error,
                cache_age: outcome.cache_age,
            })
        }
        VendorId::AnthropicApi => {
            let key = crate::config::resolve_api_key(
                "Anthropic_API",
                &config.anthropic_api.api_key_env,
                config.anthropic_api.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("anthropic_api")?;
            let endpoints = crate::anthropic_api::fetch::Endpoints::default();
            let outcome = crate::anthropic_api::fetch_snapshot(
                client,
                &key,
                &cache,
                &endpoints,
                DEFAULT_TTL,
                config.anthropic_api.monthly_limit,
            )
            .await?;
            Ok(outcome.into())
        }
        VendorId::Openrouter => {
            let api_key = crate::config::resolve_api_key(
                "OpenRouter",
                &config.openrouter.api_key_env,
                config.openrouter.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("openrouter")?;
            let endpoints = crate::openrouter::fetch::Endpoints::default();
            let outcome = crate::openrouter::fetch_snapshot(
                client,
                &api_key,
                &cache,
                &endpoints,
                DEFAULT_TTL,
            )
            .await?;
            Ok(outcome.into())
        }
        VendorId::Zai => {
            let api_key = crate::config::resolve_api_key(
                "Zai",
                &config.zai.api_key_env,
                config.zai.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("zai")?;
            let endpoints = crate::zai::fetch::Endpoints::default();
            let outcome = crate::zai::fetch_snapshot(
                client,
                &api_key,
                &cache,
                &endpoints,
                DEFAULT_TTL,
                config.zai.plan_tier.as_deref(),
            )
            .await?;
            Ok(outcome.into())
        }
        VendorId::Openai => {
            let cache = crate::cache::Cache::for_vendor("openai")?;
            let creds_path = config
                .openai
                .codex_auth_path
                .clone()
                .unwrap_or_else(|| crate::openai::creds::default_path().unwrap_or_default());
            let endpoints = crate::openai::fetch::Endpoints::default();
            let outcome =
                crate::openai::fetch_snapshot(client, &creds_path, &cache, &endpoints, DEFAULT_TTL)
                    .await?;
            Ok(outcome.into())
        }
        VendorId::Deepseek => {
            let api_key = crate::config::resolve_api_key(
                "DeepSeek",
                &config.deepseek.api_key_env,
                config.deepseek.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("deepseek")?;
            let endpoints = crate::deepseek::fetch::Endpoints::default();
            let outcome =
                crate::deepseek::fetch_snapshot(client, &api_key, &cache, &endpoints, DEFAULT_TTL)
                    .await?;
            Ok(outcome.into())
        }
        VendorId::Kimi => {
            let api_key = crate::config::resolve_api_key(
                "Kimi",
                &config.kimi.api_key_env,
                config.kimi.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("kimi")?;
            let endpoints = crate::kimi::fetch::Endpoints::default();
            let outcome =
                crate::kimi::fetch_snapshot(client, &api_key, &cache, &endpoints, DEFAULT_TTL)
                    .await?;
            Ok(outcome.into())
        }
        VendorId::Kilo => {
            let api_key = crate::config::resolve_api_key(
                "Kilo",
                &config.kilo.api_key_env,
                config.kilo.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("kilo")?;
            let endpoints = crate::kilo::fetch::Endpoints::default();
            let outcome = crate::kilo::fetch_snapshot(
                client,
                &api_key,
                &cache,
                &endpoints,
                DEFAULT_TTL,
                config.kilo.organization_id.as_deref(),
            )
            .await?;
            Ok(outcome.into())
        }
        VendorId::Novita => {
            let api_key = crate::config::resolve_api_key(
                "Novita",
                &config.novita.api_key_env,
                config.novita.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("novita")?;
            let endpoints = crate::novita::fetch::Endpoints::default();
            let outcome =
                crate::novita::fetch_snapshot(client, &api_key, &cache, &endpoints, DEFAULT_TTL)
                    .await?;
            Ok(outcome.into())
        }
        VendorId::Moonshot => {
            let api_key = crate::config::resolve_api_key(
                "Moonshot",
                &config.moonshot.api_key_env,
                config.moonshot.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("moonshot")?;
            let (endpoints, currency) =
                crate::moonshot::fetch::Endpoints::for_region(&config.moonshot.region);
            let outcome = crate::moonshot::fetch_snapshot(
                client,
                &api_key,
                &cache,
                &endpoints,
                DEFAULT_TTL,
                currency,
            )
            .await?;
            Ok(outcome.into())
        }
        VendorId::Grok => {
            let key = crate::config::resolve_api_key(
                "Grok",
                &config.grok.api_key_env,
                config.grok.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("grok")?;
            let endpoints = crate::grok::fetch::Endpoints::default();
            let outcome = crate::grok::fetch_snapshot(
                client,
                &key,
                &cache,
                &endpoints,
                DEFAULT_TTL,
                config.grok.team_id.as_deref(),
            )
            .await?;
            Ok(outcome.into())
        }
        VendorId::Antigravity => {
            // No credentials: the local Antigravity server is the source.
            let cache = crate::cache::Cache::for_vendor("antigravity")?;
            let outcome = crate::antigravity::fetch_snapshot(client, &cache, DEFAULT_TTL).await?;
            Ok(outcome.into())
        }
        VendorId::Minimax => {
            let api_key = crate::config::resolve_api_key(
                "MiniMax",
                &config.minimax.api_key_env,
                config.minimax.api_key.as_deref(),
            )?;
            let cache = crate::cache::Cache::for_vendor("minimax")?;
            let endpoints = crate::minimax::fetch::Endpoints::for_region(&config.minimax.region);
            let outcome =
                crate::minimax::fetch_snapshot(client, &api_key, &cache, &endpoints, DEFAULT_TTL)
                    .await?;
            Ok(outcome.into())
        }
        VendorId::Cursor => {
            let cache = crate::cache::Cache::for_vendor("cursor")?;
            let db_path = config
                .cursor
                .db_path
                .clone()
                .map(Ok)
                .unwrap_or_else(crate::cursor::db::default_db_path)?;
            let endpoints = crate::cursor::fetch::Endpoints::default();
            let outcome =
                crate::cursor::fetch_snapshot(client, &db_path, &cache, &endpoints, DEFAULT_TTL)
                    .await?;
            Ok(outcome.into())
        }
    }
}

/// Convenience for the watch-driven binary: how long to wait between
/// automatic refreshes.
pub const REFRESH_INTERVAL: Duration = Duration::from_secs(60);

/// Gap between successive Anthropic fetches at refresh time. Every Anthropic
/// tab (the default account and each named/discovered account) hits the same
/// `/api/oauth/usage` + token-refresh endpoints, which rate-limit a burst of
/// simultaneous requests from one client — so with several accounts the TUI
/// would fire them all at once and some would come back `429`. Spacing them
/// out keeps every account refreshing politely.
pub const ANTHROPIC_REFRESH_STAGGER: Duration = Duration::from_millis(800);

/// Per-tab startup delay for one `spawn_all` pass. Only Anthropic tabs are
/// staggered (they share the rate-limited endpoint and multiply with accounts);
/// every other vendor hits its own endpoint and starts immediately. The first
/// Anthropic tab also starts immediately; each subsequent one waits one more
/// `step`. Pure and position-based so it is unit-testable.
pub fn refresh_stagger(tabs: &[TabId], step: Duration) -> Vec<Duration> {
    let mut anthropic_seen: u32 = 0;
    tabs.iter()
        .map(|tab| {
            if tab.vendor == VendorId::Anthropic {
                let delay = step * anthropic_seen;
                anthropic_seen += 1;
                delay
            } else {
                Duration::ZERO
            }
        })
        .collect()
}

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

    // Use `App::with_theme(.., Theme::default())` rather than `App::new`, which
    // would read the real Omarchy theme file + `$HOME`. The tab-selection logic
    // under test is theme-agnostic.
    #[test]
    fn refresh_stagger_spaces_out_anthropic_tabs_only() {
        let step = Duration::from_millis(800);
        let tabs = vec![
            TabId::vendor(VendorId::Anthropic), // default account
            TabId::account("work"),
            TabId::account("personal"),
            TabId::vendor(VendorId::Openai),
            TabId::vendor(VendorId::Zai),
        ];
        let delays = refresh_stagger(&tabs, step);
        assert_eq!(
            delays,
            vec![
                Duration::ZERO, // 1st anthropic — immediate
                step,           // 2nd anthropic
                step * 2,       // 3rd anthropic
                Duration::ZERO, // openai — own endpoint, immediate
                Duration::ZERO, // zai — own endpoint, immediate
            ]
        );
    }

    #[test]
    fn refresh_stagger_is_a_noop_without_anthropic_accounts() {
        // A single Anthropic tab (or none) never waits.
        let tabs = vec![
            TabId::vendor(VendorId::Anthropic),
            TabId::vendor(VendorId::Openrouter),
        ];
        assert!(
            refresh_stagger(&tabs, Duration::from_millis(800))
                .iter()
                .all(|d| d.is_zero())
        );
    }

    #[test]
    fn select_primary_moves_to_enabled_vendor() {
        let mut app = App::with_theme(
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::vendor(VendorId::Openrouter),
            ],
            Theme::default(),
        );
        app.select_primary(Some(VendorId::Openrouter));
        assert_eq!(app.active_vendor(), Some(VendorId::Openrouter));
    }

    #[test]
    fn select_primary_ignores_disabled_vendor() {
        let mut app = App::with_theme(vec![TabId::vendor(VendorId::Anthropic)], Theme::default());
        app.select_primary(Some(VendorId::Openai));
        assert_eq!(app.active_vendor(), Some(VendorId::Anthropic));
    }

    #[test]
    fn nav_ring_wraps_through_the_overview_at_both_ends() {
        let mut app = App::with_theme(
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::vendor(VendorId::Openai),
            ],
            Theme::default(),
        );
        app.overview = true;

        app.next_tab(); // Overview -> first vendor
        assert!(!app.overview);
        assert_eq!(app.active, 0);
        app.next_tab();
        assert_eq!(app.active, 1);
        app.next_tab(); // last vendor -> Overview
        assert!(app.overview);

        app.prev_tab(); // Overview -> last vendor
        assert!(!app.overview);
        assert_eq!(app.active, 1);
        app.prev_tab();
        assert_eq!(app.active, 0);
        app.prev_tab(); // first vendor -> Overview
        assert!(app.overview);
    }

    #[test]
    fn overview_tabs_defaults_to_all_and_honors_the_config_filter() {
        let mut app = App::with_theme(
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::vendor(VendorId::Openai),
                TabId::vendor(VendorId::Zai),
            ],
            Theme::default(),
        );
        assert_eq!(app.overview_tabs(), vec![0, 1, 2]);

        // Subset in the given order.
        app.overview_vendors = Some(vec![VendorId::Zai, VendorId::Anthropic]);
        assert_eq!(app.overview_tabs(), vec![2, 0]);

        // A listed-but-absent vendor is simply skipped.
        app.overview_vendors = Some(vec![VendorId::Grok, VendorId::Openai]);
        assert_eq!(app.overview_tabs(), vec![1]);
    }

    fn config_with_accounts(labels: &[&str]) -> Config {
        let mut config = Config::default();
        // Keep only Anthropic enabled so the test asserts on account expansion,
        // not on the full default vendor set.
        config.openai.enabled = false;
        config.zai.enabled = false;
        config.openrouter.enabled = false;
        config.anthropic.accounts = labels
            .iter()
            .map(|l| crate::config::AnthropicAccount {
                label: (*l).to_string(),
                credentials_path: format!("/creds/{l}.json").into(),
            })
            .collect();
        config
    }

    #[test]
    fn show_default_account_false_hides_the_unnamed_claude_tab() {
        // With named accounts and show_default_account=false, only the named
        // tabs appear — no redundant default "Claude" tab.
        let mut config = config_with_accounts(&["work", "personal"]);
        config.anthropic.show_default_account = false;
        assert_eq!(
            tabs_from_config(&config),
            vec![TabId::account("work"), TabId::account("personal")]
        );

        // But with no named accounts it is kept, so Anthropic never loses its
        // only tab.
        let mut empty = Config::default();
        empty.openai.enabled = false;
        empty.zai.enabled = false;
        empty.openrouter.enabled = false;
        empty.anthropic.show_default_account = false;
        assert_eq!(
            tabs_from_config(&empty),
            vec![TabId::vendor(VendorId::Anthropic)]
        );
    }

    #[test]
    fn tabs_expand_anthropic_accounts_after_default() {
        // Default Claude tab first, then each account in config order.
        let tabs = tabs_from_config(&config_with_accounts(&["work", "personal"]));
        assert_eq!(
            tabs,
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::account("work"),
                TabId::account("personal"),
            ]
        );
    }

    #[test]
    fn tabs_without_accounts_are_just_enabled_vendors() {
        // No [[anthropic.accounts]] → one tab per enabled vendor, unchanged.
        let config = Config::default();
        let tabs = tabs_from_config(&config);
        let vendors: Vec<VendorId> = tabs.iter().map(|t| t.vendor).collect();
        assert_eq!(vendors, config.enabled_vendors());
        assert!(tabs.iter().all(|t| t.account.is_none()));
    }

    #[test]
    fn tabs_include_accounts_auto_discovered_from_accounts_dir() {
        // A CLAUDE_CONFIG_DIR-style directory becomes account tabs with no
        // explicit [[anthropic.accounts]] entry. Hermetic: real TempDir.
        let td = tempfile::tempdir().unwrap();
        for label in ["work", "personal"] {
            let dir = td.path().join(label);
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join(".credentials.json"), "{}").unwrap();
        }
        let mut config = Config::default();
        config.openai.enabled = false;
        config.zai.enabled = false;
        config.openrouter.enabled = false;
        config.anthropic.accounts_dir = Some(td.path().to_path_buf());

        let tabs = tabs_from_config(&config);
        assert_eq!(
            tabs,
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::account("personal"), // sorted by label
                TabId::account("work"),
            ]
        );
    }

    #[test]
    fn desktop_labels_become_account_tabs_after_cli_accounts() {
        // Pure core: desktop accounts follow CLI accounts, in the order given.
        let config = config_with_accounts(&["work"]);
        let tabs = build_tabs(&config, &["gmail".into(), "hotmail".into()], &[]);
        assert_eq!(
            tabs,
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::account("work"),
                TabId::desktop_account("gmail"),
                TabId::desktop_account("hotmail"),
            ]
        );
    }

    #[test]
    fn a_cli_account_shadows_a_desktop_profile_of_the_same_label() {
        // One tab per label; the explicitly configured CLI account wins.
        let config = config_with_accounts(&["gmail"]);
        let tabs = build_tabs(&config, &["gmail".into(), "hotmail".into()], &[]);
        assert_eq!(
            tabs,
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::account("gmail"),
                TabId::desktop_account("hotmail"),
            ]
        );
    }

    #[test]
    fn a_broken_cli_account_yields_its_label_to_the_desktop_profile() {
        // The exact failure a half-finished `account add gmail` caused: a CLI
        // account is configured but unusable, and a Desktop profile of the same
        // name exists. Passed in `broken_cli`, the CLI account is dropped and the
        // Desktop source surfaces instead of an error tab.
        let config = config_with_accounts(&["gmail"]);
        let tabs = build_tabs(&config, &["gmail".into()], &["gmail".into()]);
        assert_eq!(
            tabs,
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::desktop_account("gmail"),
            ]
        );
    }

    #[test]
    fn desktop_accounts_suppress_the_default_tab_like_named_ones() {
        // show_default_account=false + only Desktop accounts => no default tab,
        // exactly as if they were [[anthropic.accounts]] (the Desktop-only user).
        let mut config = config_with_accounts(&[]);
        config.cursor.enabled = false;
        config.anthropic.show_default_account = false;

        // No accounts of either kind: the default tab survives (never leave
        // Anthropic tab-less).
        assert_eq!(
            build_tabs(&config, &[], &[]),
            vec![TabId::vendor(VendorId::Anthropic)]
        );
        // A Desktop account is present: default suppressed, only the account.
        assert_eq!(
            build_tabs(&config, &["gmail".into()], &[]),
            vec![TabId::desktop_account("gmail")]
        );
    }

    #[test]
    fn set_tabs_resets_states_and_clamps_selection() {
        // Simulates a Settings save that shrank the tab list: the selection
        // must clamp into range and every tab must reset to Loading so the
        // caller's spawn_all repopulates against the new config.
        let mut app = App::with_theme(
            tabs_from_config(&config_with_accounts(&["work", "personal"])),
            Theme::default(),
        );
        app.active = 2; // "personal"
        app.tabs[0] = TabState::Error("old".into());
        let old_tab = app.tabs_meta[0].clone();
        assert!(app.begin_refresh(&old_tab));

        app.set_tabs(tabs_from_config(&config_with_accounts(&[])));
        assert_eq!(app.tabs_meta, vec![TabId::vendor(VendorId::Anthropic)]);
        assert_eq!(app.active, 0, "selection clamped after shrink");
        assert!(matches!(app.tabs[0], TabState::Loading));
        assert!(!app.is_refreshing(&old_tab));
    }

    #[test]
    fn set_tabs_preserves_selected_identity_when_entries_are_inserted() {
        let mut app = App::with_theme(
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::vendor(VendorId::Openai),
            ],
            Theme::default(),
        );
        app.active = 1;

        app.set_tabs(vec![
            TabId::vendor(VendorId::Anthropic),
            TabId::account("work"),
            TabId::vendor(VendorId::Openai),
        ]);

        assert_eq!(app.active, 2);
        assert_eq!(app.active_tab_id(), Some(&TabId::vendor(VendorId::Openai)));
    }

    #[test]
    fn refresh_from_old_generation_is_discarded() {
        let mut app = App::with_theme(vec![TabId::vendor(VendorId::Anthropic)], Theme::default());
        let old_generation = app.tab_generation;
        app.set_tabs(vec![TabId::vendor(VendorId::Openai)]);

        assert!(!app.apply_refresh(
            old_generation,
            &TabId::vendor(VendorId::Anthropic),
            TabState::Error("old result".into()),
        ));
        assert!(matches!(app.tabs[0], TabState::Loading));
    }

    #[test]
    fn refresh_identity_mismatch_is_discarded() {
        let mut app = App::with_theme(vec![TabId::vendor(VendorId::Anthropic)], Theme::default());
        let generation = app.tab_generation;

        assert!(!app.apply_refresh(
            generation,
            &TabId::vendor(VendorId::Openai),
            TabState::Error("wrong tab".into()),
        ));
        assert!(matches!(app.tabs[0], TabState::Loading));
    }

    #[test]
    fn refresh_identity_lands_at_new_index_after_same_generation_reorder() {
        let anthropic = TabId::vendor(VendorId::Anthropic);
        let openai = TabId::vendor(VendorId::Openai);
        let mut app = App::with_theme(vec![anthropic.clone(), openai.clone()], Theme::default());
        let generation = app.tab_generation;
        assert!(app.begin_refresh(&anthropic));

        // A reorder is safe because delivery resolves the captured identity,
        // not a stale positional index.
        app.tabs_meta.swap(0, 1);
        app.tabs.swap(0, 1);
        assert!(app.apply_refresh(generation, &anthropic, TabState::Error("ready".into())));
        assert!(matches!(app.tabs[0], TabState::Loading));
        assert!(matches!(&app.tabs[1], TabState::Error(message) if message == "ready"));
        assert!(!app.is_refreshing(&anthropic));
    }

    fn ready_at(fetched_at: chrono::DateTime<Utc>) -> TabState {
        TabState::Ready(Box::new(ReadyTab {
            snapshot: crate::usage::VendorSnapshot::Openrouter(crate::usage::OpenRouterSnapshot {
                label: "test".into(),
                total_credits: 0.0,
                total_usage: 0.0,
                usage_daily: 0.0,
                usage_weekly: 0.0,
                usage_monthly: 0.0,
                is_free_tier: false,
                limit: None,
                limit_remaining: None,
            }),
            stale: false,
            last_error: None,
            fetched_at: Some(fetched_at),
        }))
    }

    #[test]
    fn refresh_keeps_ready_snapshot_visible_and_suppresses_duplicates() {
        let tab = TabId::vendor(VendorId::Openrouter);
        let fetched_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap();
        let mut app = App::with_theme(vec![tab.clone()], Theme::default());
        app.tabs[0] = ready_at(fetched_at);

        assert!(app.begin_refresh(&tab));
        assert!(
            !app.begin_refresh(&tab),
            "duplicate request must be suppressed"
        );
        assert!(app.is_refreshing(&tab));
        match &app.tabs[0] {
            TabState::Ready(ready) => assert_eq!(ready.fetched_at, Some(fetched_at)),
            other => panic!("ready snapshot disappeared during refresh: {other:?}"),
        }
    }

    #[test]
    fn first_refresh_still_uses_loading_until_data_arrives() {
        let tab = TabId::vendor(VendorId::Openrouter);
        let mut app = App::with_theme(vec![tab.clone()], Theme::default());

        assert!(app.begin_refresh(&tab));
        assert!(app.is_refreshing(&tab));
        assert!(matches!(app.tabs[0], TabState::Loading));

        assert!(app.apply_refresh(
            app.tab_generation,
            &tab,
            TabState::Error("not signed in".into()),
        ));
        assert!(!app.is_refreshing(&tab));
        assert!(matches!(&app.tabs[0], TabState::Error(message) if message == "not signed in"));
    }

    #[test]
    fn successful_revalidation_replaces_snapshot_and_clears_indicator() {
        let tab = TabId::vendor(VendorId::Openrouter);
        let old_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap();
        let new_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 1, 0).unwrap();
        let mut app = App::with_theme(vec![tab.clone()], Theme::default());
        app.tabs[0] = ready_at(old_at);

        assert!(app.begin_refresh(&tab));
        assert!(app.apply_refresh(app.tab_generation, &tab, ready_at(new_at)));
        assert!(!app.is_refreshing(&tab));
        match &app.tabs[0] {
            TabState::Ready(ready) => assert_eq!(ready.fetched_at, Some(new_at)),
            other => panic!("expected replacement snapshot, got {other:?}"),
        }
    }

    #[test]
    fn failed_revalidation_preserves_snapshot_with_visible_warning() {
        let tab = TabId::vendor(VendorId::Openrouter);
        let fetched_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap();
        let mut app = App::with_theme(vec![tab.clone()], Theme::default());
        app.tabs[0] = ready_at(fetched_at);

        assert!(app.begin_refresh(&tab));
        assert!(app.apply_refresh(
            app.tab_generation,
            &tab,
            TabState::Error("refresh failed".into()),
        ));
        assert!(!app.is_refreshing(&tab));
        match &app.tabs[0] {
            TabState::Ready(ready) => {
                assert_eq!(ready.fetched_at, Some(fetched_at));
                assert!(ready.stale);
                assert_eq!(ready.last_error, Some((0, "refresh failed".into())));
            }
            other => panic!("last successful snapshot was lost: {other:?}"),
        }
        let sections = crate::tui::panels::sections_for(&app.tabs[0], Utc::now(), 5);
        assert!(sections.iter().any(|section| matches!(
            section,
            crate::tui::panels::Section::Text { label, value }
                if label == "Warning" && value == "refresh failed"
        )));
    }

    #[test]
    fn old_generation_result_does_not_clear_current_refresh() {
        let tab = TabId::vendor(VendorId::Openrouter);
        let mut app = App::with_theme(vec![tab.clone()], Theme::default());
        let old_generation = app.tab_generation;
        app.set_tabs(vec![tab.clone()]);
        assert!(app.begin_refresh(&tab));

        assert!(!app.apply_refresh(old_generation, &tab, TabState::Error("old result".into()),));
        assert!(app.is_refreshing(&tab));
        assert!(matches!(app.tabs[0], TabState::Loading));
    }

    #[test]
    fn apply_refresh_stamps_fetched_at_on_only_the_matching_tab() {
        // Pins the per-tab `fetched_at` the header now reads: a landed Anthropic
        // response leaves the still-loading OpenAI tab with no time of its own.
        // Dropping the global `last_refresh` clock is not observable from here
        // (it was write-only) — that is asserted against the rendered header in
        // `view::tests::header_refresh_*`.
        let anthropic = TabId::vendor(VendorId::Anthropic);
        let openai = TabId::vendor(VendorId::Openai);
        let mut app = App::with_theme(vec![anthropic.clone(), openai], Theme::default());
        let generation = app.tab_generation;
        let fetched_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap();

        assert!(app.apply_refresh(generation, &anthropic, ready_at(fetched_at)));
        match &app.tabs[0] {
            TabState::Ready(ready) => assert_eq!(ready.fetched_at, Some(fetched_at)),
            other => panic!("expected Anthropic tab Ready, got {other:?}"),
        }
        assert!(matches!(app.tabs[1], TabState::Loading));
    }

    #[test]
    fn select_primary_lands_on_default_account_tab() {
        // With account tabs present, `primary = anthropic` selects the default
        // Claude tab (index 0), not one of its account tabs.
        let app = {
            let tabs = tabs_from_config(&config_with_accounts(&["work"]));
            let mut a = App::with_theme(tabs, Theme::default());
            a.select_primary(Some(VendorId::Anthropic));
            a
        };
        assert_eq!(app.active, 0);
        assert_eq!(
            app.active_tab_id(),
            Some(&TabId::vendor(VendorId::Anthropic))
        );
    }
}