Skip to main content

ai_usagebar/tui/
app.rs

1//! TUI app state — vendors, tab selection, per-vendor snapshot cache.
2
3use std::collections::HashSet;
4use std::time::Duration;
5
6use chrono::Utc;
7use ratatui::layout::Rect;
8use reqwest::Client;
9
10use crate::cache::DEFAULT_TTL;
11use crate::config::{Config, CustomProviderConfig};
12use crate::error::{AppError, Result};
13use crate::theme::Theme;
14use crate::tui::settings::SettingsRow;
15use crate::vendor::{VendorId, VendorOutcome};
16
17/// What we display per vendor — raw snapshot + fetch metadata for native
18/// panel rendering, or an error message when the fetch failed.
19///
20/// `Ready` is boxed because the snapshot is much larger than the other two
21/// variants (silences `clippy::large_enum_variant`).
22#[derive(Debug, Clone)]
23pub enum TabState {
24    Loading,
25    Ready(Box<ReadyTab>),
26    Error {
27        message: String,
28        /// Vendor plan already known from credentials when the quota fetch
29        /// failed (Claude OAuth `subscriptionType`). Absent when the vendor
30        /// has no plan without a snapshot.
31        plan: Option<String>,
32    },
33}
34
35#[derive(Debug, Clone)]
36pub struct ReadyTab {
37    pub snapshot: crate::usage::VendorSnapshot,
38    pub stale: bool,
39    pub last_error: Option<(u16, String)>,
40    /// Absolute moment the cache was written (i.e. the API response landed).
41    /// Snapshotted once at TabState build time so the rendered "Updated …"
42    /// timestamp stays stable across redraws instead of drifting with the
43    /// passing wall clock.
44    pub fetched_at: Option<chrono::DateTime<chrono::Utc>>,
45    /// Bar-number settings this vendor was configured with — the tank size a
46    /// prepaid balance is metered against, and which of the two numbers goes on
47    /// the bar. Resolved from config at fetch time rather than stored in the
48    /// snapshot, so editing config.toml takes effect on the next redraw instead
49    /// of waiting for the cache to expire.
50    pub display: crate::balance::DisplayPrefs,
51}
52
53/// Where a tab's usage comes from: a built-in vendor, or a user-declared
54/// `[[custom]]` HTTP provider. A custom tab carries its own display names so
55/// the TUI and the report never need the config again just to label it.
56#[derive(Debug, Clone, PartialEq, Eq, Hash)]
57pub enum TabSource {
58    Builtin(VendorId),
59    Custom {
60        id: String,
61        name: String,
62        short_name: String,
63    },
64}
65
66impl TabState {
67    pub fn error(message: impl AsRef<str>) -> Self {
68        Self::error_with_plan(message, None)
69    }
70
71    pub fn error_with_plan(message: impl AsRef<str>, plan: Option<String>) -> Self {
72        let plan = plan.and_then(|plan| {
73            let cleaned = crate::display::sanitize_untrusted_field(plan.trim());
74            if cleaned.is_empty() || cleaned.eq_ignore_ascii_case("unknown") {
75                None
76            } else {
77                Some(cleaned)
78            }
79        });
80        Self::Error {
81            message: message.as_ref().to_string(),
82            plan,
83        }
84    }
85}
86
87/// Identity of one TUI tab. Usually a whole vendor; Claude and OpenRouter can
88/// also name a configured account. `account: None` is a plain vendor tab or
89/// that vendor's default account.
90/// `desktop` marks an account whose usage comes from the Claude Desktop app's
91/// own token rather than a `claude` CLI credential.
92/// Custom providers never carry an account or a desktop flag.
93#[derive(Debug, Clone, PartialEq, Eq, Hash)]
94pub struct TabId {
95    pub source: TabSource,
96    pub account: Option<String>,
97    pub desktop: bool,
98}
99
100impl TabId {
101    /// A plain vendor tab (default account for Anthropic).
102    pub fn vendor(vendor: VendorId) -> Self {
103        Self {
104            source: TabSource::Builtin(vendor),
105            account: None,
106            desktop: false,
107        }
108    }
109
110    /// A named Anthropic account tab (`[[anthropic.accounts]]` label).
111    pub fn account(label: impl Into<String>) -> Self {
112        Self::account_for(VendorId::Anthropic, label)
113    }
114
115    /// A named account for a vendor that supports account arrays.
116    pub fn account_for(vendor: VendorId, label: impl Into<String>) -> Self {
117        Self {
118            source: TabSource::Builtin(vendor),
119            account: Some(label.into()),
120            desktop: false,
121        }
122    }
123
124    /// An Anthropic account whose usage is read from the Claude Desktop app's
125    /// own token store (a saved `~/.claude-acc/profiles/<label>` account).
126    pub fn desktop_account(label: impl Into<String>) -> Self {
127        Self {
128            source: TabSource::Builtin(VendorId::Anthropic),
129            account: Some(label.into()),
130            desktop: true,
131        }
132    }
133
134    /// A user-declared `[[custom]]` provider tab.
135    pub fn custom(spec: &CustomProviderConfig) -> Self {
136        Self {
137            source: TabSource::Custom {
138                id: spec.id.clone(),
139                name: spec.name.clone(),
140                short_name: spec.short_name.clone(),
141            },
142            account: None,
143            desktop: false,
144        }
145    }
146
147    /// The built-in vendor behind this tab; `None` for a custom provider.
148    /// (Named `vendor_id` because `TabId::vendor` is the constructor.)
149    pub fn vendor_id(&self) -> Option<VendorId> {
150        match &self.source {
151            TabSource::Builtin(vendor) => Some(*vendor),
152            TabSource::Custom { .. } => None,
153        }
154    }
155}
156
157/// Expand enabled vendors into the tab list. Claude, OpenRouter, and Codex
158/// (OpenAI) yield their default account followed by configured named accounts;
159/// every other vendor is a single tab. With no extra accounts the result equals
160/// `config.enabled_vendors()`, preserving the historical tab set and order.
161///
162/// Config-only and pure — no Desktop profiles. Production uses
163/// [`tabs_with_desktop`]; this stays for the hermetic unit tests and any caller
164/// that only wants configured accounts.
165pub fn tabs_from_config(config: &Config) -> Vec<TabId> {
166    build_tabs(config, &[])
167}
168
169/// The production aggregate-view tab list: configured accounts plus every saved
170/// Claude Desktop profile that has usable credentials. Desktop discovery is
171/// best-effort and macOS-only; anywhere else this equals [`tabs_from_config`].
172pub fn tabs_with_desktop(config: &Config) -> Vec<TabId> {
173    build_tabs(config, &desktop_profile_labels(config))
174}
175
176/// Core expansion, parameterized on the Desktop account labels so it stays pure
177/// and unit-testable. Desktop accounts follow the CLI accounts and count toward
178/// "Anthropic has accounts" for the default-tab suppression.
179///
180/// In aggregate views, a label present in both a `[[anthropic.accounts]]` CLI
181/// entry and a Desktop profile is sourced from **Desktop**, and the CLI entry is
182/// dropped. The same account in two stores means two of them refreshing one
183/// rotating refresh token — each rotation invalidates the other's copy — and
184/// the CLI copy can even refresh to a stale/wrong identity that still
185/// authenticates but reports another account's (often zero) usage, which no
186/// credential-health check can catch. The app-maintained Desktop token is the
187/// one source that avoids both the rotation war and that silent misattribution.
188fn build_tabs(config: &Config, desktop_labels: &[String]) -> Vec<TabId> {
189    let desktop_set: HashSet<&str> = desktop_labels.iter().map(String::as_str).collect();
190    let mut tabs = Vec::new();
191    for vendor in config.enabled_vendors() {
192        if vendor == VendorId::Anthropic {
193            let accounts: Vec<_> = config
194                .anthropic
195                .all_accounts()
196                .into_iter()
197                .filter(|a| !desktop_set.contains(a.label.as_str()))
198                .collect();
199            // The default (unnamed) Claude tab is suppressible once every
200            // account is named — but never when it would leave Anthropic with
201            // no tab at all. Desktop accounts count as named accounts here.
202            if config.anthropic.show_default_account
203                || (accounts.is_empty() && desktop_labels.is_empty())
204            {
205                tabs.push(TabId::vendor(vendor));
206            }
207            for acct in accounts {
208                tabs.push(TabId::account(acct.label));
209            }
210            for label in desktop_labels {
211                tabs.push(TabId::desktop_account(label.clone()));
212            }
213        } else if let Some(accounts) = config.api_key_accounts(vendor) {
214            if config.show_default_api_key_account(vendor) || accounts.is_empty() {
215                tabs.push(TabId::vendor(vendor));
216            }
217            for account in accounts {
218                tabs.push(TabId::account_for(vendor, account.label.clone()));
219            }
220        } else if vendor == VendorId::Openai {
221            if config.openai.show_default_account || config.openai.accounts.is_empty() {
222                tabs.push(TabId::vendor(vendor));
223            }
224            for account in &config.openai.accounts {
225                tabs.push(TabId::account_for(vendor, account.label.clone()));
226            }
227        } else {
228            tabs.push(TabId::vendor(vendor));
229        }
230    }
231    // Custom providers follow every built-in vendor, in config order.
232    for spec in config.enabled_custom() {
233        tabs.push(TabId::custom(spec));
234    }
235    tabs
236}
237
238/// Labels of saved Claude Desktop profiles with usable credentials. macOS-only
239/// (elsewhere there is no Desktop app); best-effort, so an unreadable profile
240/// store just yields none rather than failing the whole tab list.
241#[cfg(target_os = "macos")]
242fn desktop_profile_labels(config: &Config) -> Vec<String> {
243    let Ok(paths) = crate::claude_desktop::Paths::resolve(&config.anthropic) else {
244        return Vec::new();
245    };
246    if !paths.available() {
247        return Vec::new();
248    }
249    crate::claude_desktop::load_profiles(&paths.profiles_dir)
250        .into_iter()
251        .filter(|p| p.has_credentials)
252        .map(|p| p.label)
253        .collect()
254}
255
256#[cfg(not(target_os = "macos"))]
257fn desktop_profile_labels(_config: &Config) -> Vec<String> {
258    Vec::new()
259}
260
261/// Mouse hit-test surface recorded by the last draw and consumed by the event
262/// loop. Draw is the single source of truth for where things are on screen, so
263/// the render pass records the interactive rects here instead of the input
264/// handler re-deriving layout.
265#[derive(Debug, Default, Clone)]
266pub struct HitTargets {
267    /// Vendor navigation entries: Overview first, then each tab by index.
268    pub nav_entries: Vec<(NavTarget, Rect)>,
269    /// Footer actions with a mouse-accessible keyboard equivalent.
270    pub footer_actions: Vec<(FooterAction, Rect)>,
271    /// Settings overlay interactive rows: the primary selector, key fields,
272    /// and save row.
273    pub settings_rows: Vec<(SettingsRow, Rect)>,
274}
275
276/// What a click in the vendor navigation selects.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum NavTarget {
279    Overview,
280    Tab(usize),
281}
282
283/// What a click in the footer invokes.
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
285pub enum FooterAction {
286    Refresh,
287    RefreshAll,
288    Settings,
289    Quit,
290}
291
292#[derive(Debug)]
293pub struct App {
294    pub tabs_meta: Vec<TabId>,
295    pub active: usize,
296    pub tabs: Vec<TabState>,
297    /// Tab identities with a request currently in flight. Kept separate from
298    /// `tabs` so a successful snapshot remains visible while it is refreshed.
299    refreshing_tabs: HashSet<TabId>,
300    /// Monotonically increasing identity for a complete tab-set replacement.
301    /// Background fetches carry this with their tab identity so results from a
302    /// previous Settings reload cannot land in a new tab at the old index.
303    pub tab_generation: u64,
304    /// When `true`, the Overview pane is selected (the virtual first tab that
305    /// summarizes every vendor at once) instead of a per-vendor detail tab.
306    pub overview: bool,
307    /// Which vendors the Overview lists (`[ui] overview_vendors`); `None` = all.
308    pub overview_vendors: Option<Vec<VendorId>>,
309    pub theme: Theme,
310    pub quit: bool,
311    /// When `Some`, the Settings overlay is open and consuming key events.
312    pub settings: Option<crate::tui::settings::SettingsState>,
313    /// Local context monitoring is separately opt-in and never changes the
314    /// vendor tab set.
315    pub context_enabled: bool,
316    /// Monotonic across overlay close/reopen cycles so an old detached scan
317    /// can never share the new overlay's first generation number.
318    pub context_generation: u64,
319    /// When `Some`, the local Claude Code context overlay owns keyboard input.
320    pub context: Option<crate::tui::context::ContextState>,
321    /// Presentation style for the vendor navigation box (`[ui] vendor_box`).
322    pub vendor_box: crate::config::VendorBoxStyle,
323    /// Interactive rects from the most recent draw, for mouse hit-testing.
324    pub hit: std::rc::Rc<std::cell::RefCell<HitTargets>>,
325}
326
327impl App {
328    pub fn new(tabs_meta: Vec<TabId>) -> Self {
329        // Production: resolve the palette from the environment (Omarchy theme
330        // if present, else One Dark).
331        Self::with_theme(tabs_meta, Theme::default().merged_with_omarchy())
332    }
333
334    /// Like [`App::new`] but with an explicit theme. Lets tests build an `App`
335    /// without reading the real Omarchy theme file
336    /// (`~/.local/state/omarchy/current/theme/colors.toml`) — `new` resolves
337    /// that path and the `$HOME` env var via `merged_with_omarchy`, which is
338    /// not hermetic. Production code uses `new`/`new_with_primary`.
339    pub fn with_theme(tabs_meta: Vec<TabId>, theme: Theme) -> Self {
340        let n = tabs_meta.len();
341        Self {
342            tabs_meta,
343            active: 0,
344            tabs: vec![TabState::Loading; n],
345            refreshing_tabs: HashSet::new(),
346            tab_generation: 0,
347            overview: false,
348            overview_vendors: None,
349            theme,
350            quit: false,
351            settings: None,
352            context_enabled: false,
353            context_generation: 0,
354            context: None,
355            vendor_box: crate::config::VendorBoxStyle::Sidebar,
356            hit: std::rc::Rc::new(std::cell::RefCell::new(HitTargets::default())),
357        }
358    }
359
360    /// Construct with an initial active tab — usually `[ui] primary` from
361    /// config. Silently falls through to index 0 if the requested vendor
362    /// isn't present (e.g. it was disabled).
363    pub fn new_with_primary(tabs_meta: Vec<TabId>, primary: Option<VendorId>) -> Self {
364        let mut app = Self::new(tabs_meta);
365        // Default landing is the Overview (show everything at once). An explicit
366        // `[ui] primary` opts into opening on that vendor's tab instead.
367        if primary.is_some() {
368            app.select_primary(primary);
369        } else {
370            app.overview = true;
371        }
372        app
373    }
374
375    pub fn active_tab_id(&self) -> Option<&TabId> {
376        self.tabs_meta.get(self.active)
377    }
378
379    pub fn active_vendor(&self) -> Option<VendorId> {
380        self.tabs_meta.get(self.active).and_then(TabId::vendor_id)
381    }
382
383    /// Replace the tab set — used after a Settings save reloads config, so
384    /// tabs added or removed in `config.toml` while the TUI is open (e.g. a
385    /// new `[[anthropic.accounts]]` entry) appear without a restart. Every
386    /// tab resets to `Loading` (the caller re-spawns fetches). The selected tab
387    /// is preserved by identity when possible; otherwise its old position is
388    /// clamped in case the list shrank.
389    pub fn set_tabs(&mut self, tabs_meta: Vec<TabId>) {
390        let selected = self.active_tab_id().cloned();
391        let fallback = self.active.min(tabs_meta.len().saturating_sub(1));
392        self.tab_generation = self.tab_generation.wrapping_add(1);
393        self.active = selected
394            .as_ref()
395            .and_then(|tab| tabs_meta.iter().position(|candidate| candidate == tab))
396            .unwrap_or(fallback);
397        self.tabs = vec![TabState::Loading; tabs_meta.len()];
398        self.tabs_meta = tabs_meta;
399        self.refreshing_tabs.clear();
400    }
401
402    /// Mark one tab as in flight. A ready snapshot stays in place; tabs that
403    /// have never succeeded still use the full `Loading` state. Returning
404    /// `false` suppresses duplicate requests for the same tab.
405    pub fn begin_refresh(&mut self, tab: &TabId) -> bool {
406        let Some(index) = self.tabs_meta.iter().position(|current| current == tab) else {
407            return false;
408        };
409        if !self.refreshing_tabs.insert(tab.clone()) {
410            return false;
411        }
412        if !matches!(self.tabs[index], TabState::Ready(_)) {
413            self.tabs[index] = TabState::Loading;
414        }
415        true
416    }
417
418    pub fn is_refreshing(&self, tab: &TabId) -> bool {
419        self.refreshing_tabs.contains(tab)
420    }
421
422    pub fn tab_is_refreshing(&self, index: usize) -> bool {
423        self.tabs_meta
424            .get(index)
425            .is_some_and(|tab| self.is_refreshing(tab))
426    }
427
428    /// Apply an asynchronous refresh only when it still belongs to this tab
429    /// generation and the captured tab identity still exists. Lookup by
430    /// identity, rather than the old positional index, also makes a reordered
431    /// tab list safe.
432    pub fn apply_refresh(&mut self, generation: u64, tab: &TabId, state: TabState) -> bool {
433        if generation != self.tab_generation {
434            return false;
435        }
436        let Some(index) = self.tabs_meta.iter().position(|current| current == tab) else {
437            return false;
438        };
439        let was_refreshing = self.refreshing_tabs.remove(tab);
440        // If revalidation fails after a successful snapshot, preserve the
441        // useful data but make the failure explicit. Initial failures still
442        // become the normal Error state because there is no data to preserve.
443        if was_refreshing
444            && let TabState::Ready(ready) = &mut self.tabs[index]
445            && let TabState::Error { message, .. } = state
446        {
447            ready.stale = true;
448            ready.last_error = Some((0, message));
449        } else {
450            self.tabs[index] = state;
451        }
452        true
453    }
454
455    /// Move to the first tab of `primary`'s vendor (the default account tab,
456    /// since it precedes any of that vendor's account tabs).
457    pub fn select_primary(&mut self, primary: Option<VendorId>) {
458        if let Some(p) = primary
459            && let Some(idx) = self.tabs_meta.iter().position(|t| t.vendor_id() == Some(p))
460        {
461            self.active = idx;
462            self.overview = false;
463        }
464    }
465
466    /// The selectable ring is `[Overview, tab0, tab1, …]`. `next_tab`/`prev_tab`
467    /// walk it, wrapping through the Overview at the ends.
468    pub fn next_tab(&mut self) {
469        if self.overview {
470            if !self.tabs_meta.is_empty() {
471                self.overview = false;
472                self.active = 0;
473            }
474        } else if self.active + 1 < self.tabs_meta.len() {
475            self.active += 1;
476        } else {
477            self.overview = true;
478        }
479    }
480
481    pub fn prev_tab(&mut self) {
482        if self.overview {
483            if !self.tabs_meta.is_empty() {
484                self.overview = false;
485                self.active = self.tabs_meta.len() - 1;
486            }
487        } else if self.active > 0 {
488            self.active -= 1;
489        } else {
490            self.overview = true;
491        }
492    }
493
494    /// Select the Overview pane (mouse click on the first nav entry).
495    pub fn select_overview(&mut self) {
496        self.overview = true;
497    }
498
499    /// Select a vendor tab by index (mouse click on a nav entry).
500    pub fn select_tab(&mut self, index: usize) {
501        if index < self.tabs_meta.len() {
502            self.active = index;
503            self.overview = false;
504        }
505    }
506
507    /// Apply a mouse click on a vendor-navigation entry.
508    pub fn nav_from_target(&mut self, target: NavTarget) {
509        match target {
510            NavTarget::Overview => self.select_overview(),
511            NavTarget::Tab(index) => self.select_tab(index),
512        }
513    }
514
515    /// Tabs the Overview should list: `overview_vendors` filtered against the
516    /// live tab set (preserving the config order), or all tabs when unset.
517    /// The filter names built-in vendors only, so a configured list excludes
518    /// every custom provider tab; the unset default includes them.
519    pub fn overview_tabs(&self) -> Vec<usize> {
520        match &self.overview_vendors {
521            None => (0..self.tabs_meta.len()).collect(),
522            Some(wanted) => wanted
523                .iter()
524                .flat_map(|v| {
525                    self.tabs_meta
526                        .iter()
527                        .enumerate()
528                        .filter(move |(_, t)| t.vendor_id() == Some(*v))
529                        .map(|(i, _)| i)
530                })
531                .collect(),
532        }
533    }
534}
535
536/// Fetch and render one tab — returns a `TabState`.
537pub async fn refresh_one(client: &Client, config: &Config, tab: &TabId) -> TabState {
538    match build_outcome(client, config, tab).await {
539        Ok(outcome) => {
540            // Resolve the cache age (a duration from "now" at fetch time) into an
541            // absolute instant ONCE. Without this, sections_for would recompute
542            // `Utc::now() - cache_age` on every draw and the displayed time would
543            // tick upward in real time instead of holding at the last refresh.
544            let now = Utc::now();
545            let off_the_wire = outcome.off_the_wire();
546            let fetched_at = outcome
547                .cache_age
548                .map(|age| now - chrono::Duration::from_std(age).unwrap_or_default());
549            let state = TabState::Ready(Box::new(ReadyTab {
550                snapshot: outcome.snapshot,
551                stale: outcome.stale,
552                last_error: outcome.last_error.map(|(code, message)| {
553                    (code, crate::display::sanitize_untrusted_field(&message))
554                }),
555                fetched_at,
556                display: match &tab.source {
557                    TabSource::Builtin(vendor) => config.display_prefs(*vendor),
558                    // A `[[custom]]` provider states its own percentages; it has
559                    // no balance to meter and no headline to choose.
560                    TabSource::Custom { .. } => crate::balance::DisplayPrefs::default(),
561                },
562            }));
563            // The single notification hook every frontend shares: TUI, `usage`
564            // report, tray, and the GNOME/KDE/Omarchy frontends all land here.
565            // Wire-fresh outcomes only — never cached, stale, or failed ones —
566            // and best-effort by construction: `run` returns nothing and cannot
567            // change this function's result or the caller's exit code.
568            if off_the_wire
569                && config.notifications.enabled
570                && let Some(input) = crate::notify::RefreshInput::from_tab(tab, &state, now)
571            {
572                let _ = crate::notify::run(input, config.notifications.threshold).await;
573            }
574            state
575        }
576        Err(e) => TabState::error_with_plan(
577            crate::display::sanitize_untrusted_field(&e.user_message()),
578            e.plan().map(str::to_string),
579        ),
580    }
581}
582
583/// Key and cache for an API-key vendor tab: a named account's key with its own
584/// `<slug>/<label>` cache, or the default key with the vendor-root cache, whose
585/// path never moves (issue #14).
586fn api_key_and_cache(
587    config: &Config,
588    vendor: VendorId,
589    account: Option<&str>,
590) -> Result<(String, crate::cache::Cache)> {
591    let api_key = config.resolve_account_api_key_for(vendor, account)?;
592    let cache = match account {
593        Some(label) => crate::cache::Cache::for_vendor_account(vendor.slug(), label)?,
594        None => crate::cache::Cache::for_vendor(vendor.slug())?,
595    };
596    Ok((api_key, cache))
597}
598
599async fn build_outcome(client: &Client, config: &Config, tab: &TabId) -> Result<VendorOutcome> {
600    let vendor = match &tab.source {
601        TabSource::Builtin(vendor) => *vendor,
602        TabSource::Custom { id, .. } => {
603            // A custom provider owns its TTL and its cache slot; the cache is
604            // keyed by the provider id under one shared `custom` vendor dir.
605            let spec = config.custom_by_id(id).ok_or_else(|| {
606                AppError::Other(format!("custom provider {id} is not configured"))
607            })?;
608            let api_key = spec.resolve_api_key()?;
609            let cache = crate::cache::Cache::for_vendor_account("custom", id)?;
610            let outcome =
611                crate::custom::fetch_snapshot(client, spec, &api_key, &cache, spec.cache_ttl())
612                    .await?;
613            return Ok(outcome.into());
614        }
615    };
616    match vendor {
617        VendorId::Anthropic => {
618            // A named account resolves to its own file + `anthropic/<label>`
619            // cache, shared with the widget via `account_target` (#14/#17).
620            // The default tab keeps the pre-existing resolution: config
621            // `credentials_path` is an explicit strict read, and only the
622            // platform default gets the macOS Keychain fallback.
623            let (creds_target, cache) = match tab.account.as_deref() {
624                Some(label) if tab.desktop => {
625                    crate::anthropic::desktop_creds::account_target(config, label)?
626                }
627                Some(label) => config.anthropic.account_target(label)?,
628                None => {
629                    let target = match config.anthropic.credentials_path.clone() {
630                        Some(p) => crate::anthropic::creds::CredsTarget::Explicit(p),
631                        None => crate::anthropic::creds::CredsTarget::Default(
632                            crate::anthropic::creds::default_path().unwrap_or_default(),
633                        ),
634                    };
635                    (target, crate::cache::Cache::for_vendor("anthropic")?)
636                }
637            };
638            let endpoints = crate::anthropic::fetch::Endpoints::default();
639            let outcome = crate::anthropic::fetch_snapshot(
640                client,
641                &creds_target,
642                &cache,
643                &endpoints,
644                DEFAULT_TTL,
645            )
646            .await?;
647            Ok(outcome.map(crate::usage::VendorSnapshot::Anthropic))
648        }
649        VendorId::AnthropicApi => {
650            let key = crate::config::resolve_api_key(
651                "Anthropic_API",
652                &config.anthropic_api.api_key_env,
653                config.anthropic_api.api_key.as_deref(),
654            )?;
655            let cache = crate::cache::Cache::for_vendor("anthropic_api")?;
656            let endpoints = crate::anthropic_api::fetch::Endpoints::default();
657            let outcome = crate::anthropic_api::fetch_snapshot(
658                client,
659                &key,
660                &cache,
661                &endpoints,
662                DEFAULT_TTL,
663                config.anthropic_api.monthly_limit,
664            )
665            .await?;
666            Ok(outcome.into())
667        }
668        VendorId::Openrouter => {
669            let (api_key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
670            let endpoints = crate::openrouter::fetch::Endpoints::default();
671            let outcome = crate::openrouter::fetch_snapshot(
672                client,
673                &api_key,
674                &cache,
675                &endpoints,
676                DEFAULT_TTL,
677            )
678            .await?;
679            Ok(outcome.into())
680        }
681        VendorId::Zai => {
682            let (api_key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
683            let endpoints = crate::zai::fetch::Endpoints::default();
684            let outcome = crate::zai::fetch_snapshot(
685                client,
686                &api_key,
687                &cache,
688                &endpoints,
689                DEFAULT_TTL,
690                config.zai.plan_tier.as_deref(),
691            )
692            .await?;
693            Ok(outcome.into())
694        }
695        VendorId::Openai => {
696            let label = tab.account.as_deref();
697            let cache = match label {
698                Some(label) => crate::cache::Cache::for_vendor_account("openai", label)?,
699                None => crate::cache::Cache::for_vendor("openai")?,
700            };
701            let route = || config.openai.fetch_auth_path(label);
702            let endpoints = crate::openai::fetch::Endpoints::default();
703            let outcome = crate::openai::fetch_snapshot_routed(
704                client,
705                route,
706                &cache,
707                &endpoints,
708                DEFAULT_TTL,
709            )
710            .await?;
711            Ok(outcome.into())
712        }
713        VendorId::Copilot => {
714            let token = config.copilot.resolve_token()?;
715            let cache = crate::cache::Cache::for_vendor("copilot")?;
716            let endpoints = crate::copilot::fetch::Endpoints::default();
717            let outcome =
718                crate::copilot::fetch_snapshot(client, &token, &cache, &endpoints, DEFAULT_TTL)
719                    .await?;
720            Ok(outcome.into())
721        }
722        VendorId::Deepseek => {
723            let (api_key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
724            let endpoints = crate::deepseek::fetch::Endpoints::default();
725            let outcome =
726                crate::deepseek::fetch_snapshot(client, &api_key, &cache, &endpoints, DEFAULT_TTL)
727                    .await?;
728            Ok(outcome.into())
729        }
730        VendorId::Deepinfra => {
731            let (api_key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
732            let endpoints = crate::deepinfra::fetch::Endpoints::default();
733            let outcome = crate::deepinfra::fetch::fetch_snapshot(
734                client,
735                &api_key,
736                &cache,
737                &endpoints,
738                DEFAULT_TTL,
739            )
740            .await?;
741            Ok(outcome.into())
742        }
743        VendorId::Kimi => {
744            let (auth, endpoints) = crate::kimi::resolve_auth(&config.kimi)?;
745            let cache = crate::cache::Cache::for_vendor("kimi")?;
746            let outcome = crate::kimi::fetch::fetch_snapshot_with_auth(
747                client,
748                &auth,
749                &cache,
750                &endpoints,
751                DEFAULT_TTL,
752            )
753            .await?;
754            Ok(outcome.into())
755        }
756        VendorId::Kilo => {
757            let (api_key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
758            let endpoints = crate::kilo::fetch::Endpoints::default();
759            let outcome = crate::kilo::fetch_snapshot(
760                client,
761                &api_key,
762                &cache,
763                &endpoints,
764                DEFAULT_TTL,
765                config.kilo.organization_id.as_deref(),
766            )
767            .await?;
768            Ok(outcome.into())
769        }
770        VendorId::Novita => {
771            let (api_key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
772            let endpoints = crate::novita::fetch::Endpoints::default();
773            let outcome =
774                crate::novita::fetch_snapshot(client, &api_key, &cache, &endpoints, DEFAULT_TTL)
775                    .await?;
776            Ok(outcome.into())
777        }
778        VendorId::Moonshot => {
779            let (api_key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
780            let (endpoints, currency) =
781                crate::moonshot::fetch::Endpoints::for_region(&config.moonshot.region);
782            let outcome = crate::moonshot::fetch_snapshot(
783                client,
784                &api_key,
785                &cache,
786                &endpoints,
787                DEFAULT_TTL,
788                currency,
789            )
790            .await?;
791            Ok(outcome.into())
792        }
793        VendorId::Grok => {
794            let (key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
795            let endpoints = crate::grok::fetch::Endpoints::default();
796            let outcome = crate::grok::fetch_snapshot(
797                client,
798                &key,
799                &cache,
800                &endpoints,
801                DEFAULT_TTL,
802                config.grok.team_id.as_deref(),
803            )
804            .await?;
805            Ok(outcome.into())
806        }
807        VendorId::Supergrok => {
808            let cache = crate::cache::Cache::for_vendor("supergrok")?;
809            let scope_paths = crate::supergrok::scope::ScopePaths::with_overrides(
810                config.supergrok.auth_path.as_deref(),
811                config.supergrok.config_path.as_deref(),
812            )?;
813            let outcome = crate::supergrok::fetch_snapshot(
814                &config.supergrok.grok_binary,
815                &scope_paths,
816                &cache,
817                DEFAULT_TTL,
818            )
819            .await?;
820            Ok(outcome.into())
821        }
822        VendorId::Antigravity => {
823            // No API key: the local Antigravity server is the source, and the
824            // saved Google session stands in while nothing is running.
825            let cache = crate::cache::Cache::for_vendor("antigravity")?;
826            let oauth = crate::antigravity::cloud::OauthClient::from_config(
827                config.antigravity.oauth_client_id.as_deref(),
828                config.antigravity.oauth_client_secret.as_deref(),
829            );
830            let outcome =
831                crate::antigravity::fetch_snapshot(client, &cache, DEFAULT_TTL, oauth.as_ref())
832                    .await?;
833            Ok(outcome.into())
834        }
835        VendorId::Grokbot => {
836            // The desktop app's own session is the login; refreshed pairs
837            // persist only inside the vendor cache.
838            let creds = crate::grokbot::resolve_credentials(&config.grokbot)?;
839            let cache = crate::cache::Cache::for_vendor("grokbot")?;
840            let endpoints = crate::grokbot::fetch::Endpoints::default();
841            let outcome = crate::grokbot::fetch::fetch_snapshot_with(
842                client,
843                &creds,
844                &cache,
845                &endpoints,
846                DEFAULT_TTL,
847            )
848            .await?;
849            Ok(outcome.into())
850        }
851        VendorId::ModelStudio => {
852            // The bl CLI's own console session is the login; its region/site
853            // pair picks the gateway, and only a token fingerprint persists.
854            let creds = crate::modelstudio::resolve_credentials(&config.modelstudio)?;
855            let cache = crate::cache::Cache::for_vendor("modelstudio")?;
856            let endpoints =
857                crate::modelstudio::fetch::Endpoints::for_gateway(creds.region, creds.site);
858            let outcome = crate::modelstudio::fetch_snapshot_with(
859                client,
860                &creds,
861                &cache,
862                &endpoints,
863                DEFAULT_TTL,
864            )
865            .await?;
866            Ok(outcome.into())
867        }
868        VendorId::Minimax => {
869            let (api_key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
870            let endpoints = crate::minimax::fetch::Endpoints::for_region(&config.minimax.region);
871            let outcome =
872                crate::minimax::fetch_snapshot(client, &api_key, &cache, &endpoints, DEFAULT_TTL)
873                    .await?;
874            Ok(outcome.into())
875        }
876        VendorId::Cursor => {
877            let cache = crate::cache::Cache::for_vendor("cursor")?;
878            let db_path = config
879                .cursor
880                .db_path
881                .clone()
882                .map(Ok)
883                .unwrap_or_else(crate::cursor::db::default_db_path)?;
884            let agent_auth_path = config
885                .cursor
886                .agent_auth_path
887                .clone()
888                .map(Ok)
889                .unwrap_or_else(crate::cursor::db::default_agent_auth_path)?;
890            let endpoints = crate::cursor::fetch::Endpoints::default();
891            let outcome = crate::cursor::fetch_snapshot(
892                client,
893                &db_path,
894                &agent_auth_path,
895                &cache,
896                &endpoints,
897                DEFAULT_TTL,
898            )
899            .await?;
900            Ok(outcome.into())
901        }
902        VendorId::Kiro => {
903            let cache = crate::cache::Cache::for_vendor("kiro")?;
904            let db_path = config
905                .kiro
906                .db_path
907                .clone()
908                .map(Ok)
909                .unwrap_or_else(crate::kiro::db::default_db_path)?;
910            let outcome =
911                crate::kiro::fetch_snapshot(client, &db_path, &cache, DEFAULT_TTL).await?;
912            Ok(outcome.into())
913        }
914        VendorId::NousResearch => {
915            let store = crate::nous::credentials::CredentialStore::default();
916            let endpoints = crate::nous::fetch::Endpoints::default();
917            let account = crate::nous::fetch::fetch_account_with_refresh(
918                client,
919                &store,
920                &endpoints,
921                Utc::now(),
922            )
923            .await?;
924            // Nous keeps no cache of its own, so every read is a live one.
925            Ok(crate::outcome::Outcome::fresh(
926                crate::usage::VendorSnapshot::NousResearch(account),
927            ))
928        }
929        VendorId::OpenCodeGo => {
930            let api_key = crate::config::resolve_api_key(
931                "OpenCode Go",
932                &config.opencode_go.api_key_env,
933                config.opencode_go.api_key.as_deref(),
934            )?;
935            let cache = crate::cache::Cache::for_vendor("opencode-go")?;
936            let endpoints = crate::opencode_go::fetch::Endpoints::default();
937            let outcome = crate::opencode_go::fetch::fetch_snapshot(
938                client,
939                &api_key,
940                &cache,
941                &endpoints,
942                DEFAULT_TTL,
943            )
944            .await?;
945            Ok(outcome.into())
946        }
947        VendorId::CommandCode => {
948            let credential =
949                crate::commandcode::creds::resolve(config.commandcode.auth_paths.as_deref())?;
950            let cache = crate::cache::Cache::for_vendor("commandcode")?;
951            let endpoints = crate::commandcode::fetch::Endpoints::default();
952            let outcome = crate::commandcode::fetch::fetch_snapshot(
953                client,
954                &credential.token,
955                &cache,
956                &endpoints,
957                DEFAULT_TTL,
958            )
959            .await?;
960            Ok(outcome.into())
961        }
962        VendorId::Ollama => {
963            let api_key = crate::config::resolve_api_key(
964                "Ollama",
965                &config.ollama.api_key_env,
966                config.ollama.api_key.as_deref(),
967            )?;
968            let cache = crate::cache::Cache::for_vendor("ollama")?;
969            let endpoints = crate::ollama::fetch::Endpoints::default();
970            let outcome = crate::ollama::fetch_snapshot(
971                client,
972                &api_key,
973                &config.ollama.plan,
974                &cache,
975                &endpoints,
976                DEFAULT_TTL,
977            )
978            .await?;
979            Ok(outcome.into())
980        }
981        VendorId::OrcaRouter => {
982            let (api_key, cache) = api_key_and_cache(config, vendor, tab.account.as_deref())?;
983            let endpoints = crate::orcarouter::fetch::Endpoints::default();
984            let outcome = crate::orcarouter::fetch_snapshot(
985                client,
986                &api_key,
987                &cache,
988                &endpoints,
989                DEFAULT_TTL,
990            )
991            .await?;
992            Ok(outcome.into())
993        }
994    }
995}
996
997/// Convenience for the watch-driven binary: how long to wait between
998/// automatic refreshes.
999pub const REFRESH_INTERVAL: Duration = Duration::from_secs(60);
1000
1001/// Gap between successive Anthropic fetches at refresh time. Every Anthropic
1002/// tab (the default account and each named/discovered account) hits the same
1003/// `/api/oauth/usage` + token-refresh endpoints, which rate-limit a burst of
1004/// simultaneous requests from one client — so with several accounts the TUI
1005/// would fire them all at once and some would come back `429`. Spacing them
1006/// out keeps every account refreshing politely.
1007pub const ANTHROPIC_REFRESH_STAGGER: Duration = Duration::from_millis(800);
1008
1009/// Per-tab startup delay for one `spawn_all` pass. Only Anthropic tabs are
1010/// staggered (they share the rate-limited endpoint and multiply with accounts);
1011/// every other vendor hits its own endpoint and starts immediately. The first
1012/// Anthropic tab also starts immediately; each subsequent one waits one more
1013/// `step`. Pure and position-based so it is unit-testable.
1014pub fn refresh_stagger(tabs: &[TabId], step: Duration) -> Vec<Duration> {
1015    let mut anthropic_seen: u32 = 0;
1016    tabs.iter()
1017        .map(|tab| {
1018            if tab.vendor_id() == Some(VendorId::Anthropic) {
1019                let delay = step * anthropic_seen;
1020                anthropic_seen += 1;
1021                delay
1022            } else {
1023                Duration::ZERO
1024            }
1025        })
1026        .collect()
1027}
1028
1029#[cfg(test)]
1030mod tests {
1031    use super::*;
1032    use chrono::TimeZone;
1033
1034    // Use `App::with_theme(.., Theme::default())` rather than `App::new`, which
1035    // would read the real Omarchy theme file + `$HOME`. The tab-selection logic
1036    // under test is theme-agnostic.
1037    #[test]
1038    fn refresh_stagger_spaces_out_anthropic_tabs_only() {
1039        let step = Duration::from_millis(800);
1040        let tabs = vec![
1041            TabId::vendor(VendorId::Anthropic), // default account
1042            TabId::account("work"),
1043            TabId::account("personal"),
1044            TabId::vendor(VendorId::Openai),
1045            TabId::vendor(VendorId::Zai),
1046        ];
1047        let delays = refresh_stagger(&tabs, step);
1048        assert_eq!(
1049            delays,
1050            vec![
1051                Duration::ZERO, // 1st anthropic — immediate
1052                step,           // 2nd anthropic
1053                step * 2,       // 3rd anthropic
1054                Duration::ZERO, // openai — own endpoint, immediate
1055                Duration::ZERO, // zai — own endpoint, immediate
1056            ]
1057        );
1058    }
1059
1060    #[test]
1061    fn refresh_stagger_is_a_noop_without_anthropic_accounts() {
1062        // A single Anthropic tab (or none) never waits.
1063        let tabs = vec![
1064            TabId::vendor(VendorId::Anthropic),
1065            TabId::vendor(VendorId::Openrouter),
1066        ];
1067        assert!(
1068            refresh_stagger(&tabs, Duration::from_millis(800))
1069                .iter()
1070                .all(|d| d.is_zero())
1071        );
1072    }
1073
1074    #[test]
1075    fn select_primary_moves_to_enabled_vendor() {
1076        let mut app = App::with_theme(
1077            vec![
1078                TabId::vendor(VendorId::Anthropic),
1079                TabId::vendor(VendorId::Openrouter),
1080            ],
1081            Theme::default(),
1082        );
1083        app.select_primary(Some(VendorId::Openrouter));
1084        assert_eq!(app.active_vendor(), Some(VendorId::Openrouter));
1085    }
1086
1087    #[test]
1088    fn select_primary_ignores_disabled_vendor() {
1089        let mut app = App::with_theme(vec![TabId::vendor(VendorId::Anthropic)], Theme::default());
1090        app.select_primary(Some(VendorId::Openai));
1091        assert_eq!(app.active_vendor(), Some(VendorId::Anthropic));
1092    }
1093
1094    #[test]
1095    fn nav_ring_wraps_through_the_overview_at_both_ends() {
1096        let mut app = App::with_theme(
1097            vec![
1098                TabId::vendor(VendorId::Anthropic),
1099                TabId::vendor(VendorId::Openai),
1100            ],
1101            Theme::default(),
1102        );
1103        app.overview = true;
1104
1105        app.next_tab(); // Overview -> first vendor
1106        assert!(!app.overview);
1107        assert_eq!(app.active, 0);
1108        app.next_tab();
1109        assert_eq!(app.active, 1);
1110        app.next_tab(); // last vendor -> Overview
1111        assert!(app.overview);
1112
1113        app.prev_tab(); // Overview -> last vendor
1114        assert!(!app.overview);
1115        assert_eq!(app.active, 1);
1116        app.prev_tab();
1117        assert_eq!(app.active, 0);
1118        app.prev_tab(); // first vendor -> Overview
1119        assert!(app.overview);
1120    }
1121
1122    #[test]
1123    fn mouse_nav_targets_select_overview_and_tabs() {
1124        let mut app = App::with_theme(
1125            vec![
1126                TabId::vendor(VendorId::Anthropic),
1127                TabId::vendor(VendorId::Openai),
1128            ],
1129            Theme::default(),
1130        );
1131        app.overview = true;
1132        app.nav_from_target(NavTarget::Tab(1));
1133        assert!(!app.overview);
1134        assert_eq!(app.active, 1);
1135        app.nav_from_target(NavTarget::Overview);
1136        assert!(app.overview);
1137        // Out-of-range tab indices are ignored.
1138        app.nav_from_target(NavTarget::Tab(99));
1139        assert!(app.overview);
1140    }
1141
1142    #[test]
1143    fn hit_targets_default_to_empty() {
1144        let app = App::with_theme(Vec::new(), Theme::default());
1145        assert!(app.hit.borrow().nav_entries.is_empty());
1146        assert!(app.hit.borrow().footer_actions.is_empty());
1147        assert!(app.hit.borrow().settings_rows.is_empty());
1148    }
1149
1150    #[test]
1151    fn overview_tabs_defaults_to_all_and_honors_the_config_filter() {
1152        let mut app = App::with_theme(
1153            vec![
1154                TabId::vendor(VendorId::Anthropic),
1155                TabId::vendor(VendorId::Openai),
1156                TabId::vendor(VendorId::Zai),
1157            ],
1158            Theme::default(),
1159        );
1160        assert_eq!(app.overview_tabs(), vec![0, 1, 2]);
1161
1162        // Subset in the given order.
1163        app.overview_vendors = Some(vec![VendorId::Zai, VendorId::Anthropic]);
1164        assert_eq!(app.overview_tabs(), vec![2, 0]);
1165
1166        // A listed-but-absent vendor is simply skipped.
1167        app.overview_vendors = Some(vec![VendorId::Grok, VendorId::Openai]);
1168        assert_eq!(app.overview_tabs(), vec![1]);
1169    }
1170
1171    fn config_with_accounts(labels: &[&str]) -> Config {
1172        let mut config = Config::default();
1173        // Keep only Anthropic enabled so the test asserts on account expansion,
1174        // not on the full default vendor set.
1175        config.openai.enabled = false;
1176        config.zai.enabled = false;
1177        config.openrouter.enabled = false;
1178        config.commandcode.enabled = false;
1179        config.anthropic.accounts = labels
1180            .iter()
1181            .map(|l| crate::config::AnthropicAccount {
1182                label: (*l).to_string(),
1183                credentials_path: format!("/creds/{l}.json").into(),
1184            })
1185            .collect();
1186        config
1187    }
1188
1189    #[test]
1190    fn show_default_account_false_hides_the_unnamed_claude_tab() {
1191        // With named accounts and show_default_account=false, only the named
1192        // tabs appear — no redundant default "Claude" tab.
1193        let mut config = config_with_accounts(&["work", "personal"]);
1194        config.anthropic.show_default_account = false;
1195        assert_eq!(
1196            tabs_from_config(&config),
1197            vec![TabId::account("work"), TabId::account("personal")]
1198        );
1199
1200        // But with no named accounts it is kept, so Anthropic never loses its
1201        // only tab.
1202        let mut empty = Config::default();
1203        empty.openai.enabled = false;
1204        empty.zai.enabled = false;
1205        empty.openrouter.enabled = false;
1206        empty.commandcode.enabled = false;
1207        empty.anthropic.show_default_account = false;
1208        assert_eq!(
1209            tabs_from_config(&empty),
1210            vec![TabId::vendor(VendorId::Anthropic)]
1211        );
1212    }
1213
1214    #[test]
1215    fn tabs_expand_anthropic_accounts_after_default() {
1216        // Default Claude tab first, then each account in config order.
1217        let tabs = tabs_from_config(&config_with_accounts(&["work", "personal"]));
1218        assert_eq!(
1219            tabs,
1220            vec![
1221                TabId::vendor(VendorId::Anthropic),
1222                TabId::account("work"),
1223                TabId::account("personal"),
1224            ]
1225        );
1226    }
1227
1228    #[test]
1229    fn tabs_without_accounts_are_just_enabled_vendors() {
1230        // No [[anthropic.accounts]] → one tab per enabled vendor, unchanged.
1231        let config = Config::default();
1232        let tabs = tabs_from_config(&config);
1233        let vendors: Vec<VendorId> = tabs.iter().filter_map(TabId::vendor_id).collect();
1234        assert_eq!(vendors, config.enabled_vendors());
1235        assert!(tabs.iter().all(|t| t.account.is_none()));
1236    }
1237
1238    #[test]
1239    fn tabs_expand_openrouter_accounts_without_changing_other_vendors() {
1240        let mut config = Config::default();
1241        config.anthropic.enabled = false;
1242        config.openai.enabled = false;
1243        config.zai.enabled = false;
1244        config.commandcode.enabled = false;
1245        config.openrouter.accounts = vec![
1246            crate::config::ApiKeyAccount {
1247                label: "work".into(),
1248                api_key_env: Some("OPENROUTER_WORK_API_KEY".into()),
1249                api_key: None,
1250            },
1251            crate::config::ApiKeyAccount {
1252                label: "personal".into(),
1253                api_key_env: None,
1254                api_key: Some("personal-key".into()),
1255            },
1256        ];
1257        assert_eq!(
1258            tabs_from_config(&config),
1259            vec![
1260                TabId::vendor(VendorId::Openrouter),
1261                TabId::account_for(VendorId::Openrouter, "work"),
1262                TabId::account_for(VendorId::Openrouter, "personal"),
1263            ]
1264        );
1265    }
1266
1267    #[test]
1268    fn openai_named_accounts_get_their_own_tabs_after_the_default() {
1269        let mut config = Config::default();
1270        config.anthropic.enabled = false;
1271        config.zai.enabled = false;
1272        config.openrouter.enabled = false;
1273        config.commandcode.enabled = false;
1274        config.openai.accounts.push(crate::config::OpenAiAccount {
1275            label: "work".into(),
1276            codex_auth_path: "/tmp/codex-work/auth.json".into(),
1277        });
1278        assert_eq!(
1279            tabs_from_config(&config),
1280            vec![
1281                TabId::vendor(VendorId::Openai),
1282                TabId::account_for(VendorId::Openai, "work"),
1283            ]
1284        );
1285    }
1286
1287    #[test]
1288    fn openrouter_can_hide_default_only_when_named_accounts_exist() {
1289        let mut config = Config::default();
1290        config.anthropic.enabled = false;
1291        config.openai.enabled = false;
1292        config.zai.enabled = false;
1293        config.commandcode.enabled = false;
1294        config.openrouter.show_default_account = false;
1295        assert_eq!(
1296            tabs_from_config(&config),
1297            vec![TabId::vendor(VendorId::Openrouter)]
1298        );
1299
1300        config
1301            .openrouter
1302            .accounts
1303            .push(crate::config::ApiKeyAccount {
1304                label: "work".into(),
1305                api_key_env: Some("OPENROUTER_WORK_API_KEY".into()),
1306                api_key: None,
1307            });
1308        assert_eq!(
1309            tabs_from_config(&config),
1310            vec![TabId::account_for(VendorId::Openrouter, "work")]
1311        );
1312    }
1313
1314    #[test]
1315    fn every_api_key_account_vendor_fans_out_like_openrouter() {
1316        let config_for = |vendor: VendorId, show_default: bool| -> Config {
1317            let section = vendor.config_section();
1318            // Switch off the vendors that are on by default, so the tab list
1319            // is this vendor's alone.
1320            let mut text: String = ["anthropic", "openai", "commandcode", "zai", "openrouter"]
1321                .into_iter()
1322                .filter(|other| *other != section)
1323                .map(|other| format!("[{other}]\nenabled = false\n"))
1324                .collect();
1325            text.push_str(&format!(
1326                "[{section}]\nenabled = true\nshow_default_account = {show_default}\n\
1327                 [[{section}.accounts]]\nlabel = \"work\"\napi_key = \"k1\"\n\
1328                 [[{section}.accounts]]\nlabel = \"personal\"\napi_key = \"k2\"\n"
1329            ));
1330            let config: Config = toml::from_str(&text).unwrap();
1331            config.validate().unwrap();
1332            config
1333        };
1334        for vendor in Config::API_KEY_ACCOUNT_VENDORS {
1335            let named = vec![
1336                TabId::account_for(vendor, "work"),
1337                TabId::account_for(vendor, "personal"),
1338            ];
1339            let mut with_default = vec![TabId::vendor(vendor)];
1340            with_default.extend(named.clone());
1341            assert_eq!(
1342                tabs_from_config(&config_for(vendor, true)),
1343                with_default,
1344                "{vendor:?}"
1345            );
1346            assert_eq!(
1347                tabs_from_config(&config_for(vendor, false)),
1348                named,
1349                "{vendor:?}"
1350            );
1351        }
1352    }
1353
1354    #[test]
1355    fn codex_can_hide_default_only_when_named_accounts_exist() {
1356        let mut config = Config::default();
1357        config.anthropic.enabled = false;
1358        config.zai.enabled = false;
1359        config.openrouter.enabled = false;
1360        config.commandcode.enabled = false;
1361        config.openai.show_default_account = false;
1362        assert_eq!(
1363            tabs_from_config(&config),
1364            vec![TabId::vendor(VendorId::Openai)]
1365        );
1366
1367        config.openai.accounts.push(crate::config::OpenAiAccount {
1368            label: "work".into(),
1369            codex_auth_path: "/tmp/codex-work/auth.json".into(),
1370        });
1371        assert_eq!(
1372            tabs_from_config(&config),
1373            vec![TabId::account_for(VendorId::Openai, "work")]
1374        );
1375    }
1376
1377    #[test]
1378    fn tabs_include_accounts_auto_discovered_from_accounts_dir() {
1379        // A CLAUDE_CONFIG_DIR-style directory becomes account tabs with no
1380        // explicit [[anthropic.accounts]] entry. Hermetic: real TempDir.
1381        let td = tempfile::tempdir().unwrap();
1382        for label in ["work", "personal"] {
1383            let dir = td.path().join(label);
1384            std::fs::create_dir_all(&dir).unwrap();
1385            std::fs::write(dir.join(".credentials.json"), "{}").unwrap();
1386        }
1387        let mut config = Config::default();
1388        config.openai.enabled = false;
1389        config.zai.enabled = false;
1390        config.openrouter.enabled = false;
1391        config.commandcode.enabled = false;
1392        config.anthropic.accounts_dir = Some(td.path().to_path_buf());
1393
1394        let tabs = tabs_from_config(&config);
1395        assert_eq!(
1396            tabs,
1397            vec![
1398                TabId::vendor(VendorId::Anthropic),
1399                TabId::account("personal"), // sorted by label
1400                TabId::account("work"),
1401            ]
1402        );
1403    }
1404
1405    #[test]
1406    fn desktop_labels_become_account_tabs_after_cli_accounts() {
1407        // Pure core: desktop accounts follow CLI accounts, in the order given.
1408        let config = config_with_accounts(&["work"]);
1409        let tabs = build_tabs(&config, &["gmail".into(), "hotmail".into()]);
1410        assert_eq!(
1411            tabs,
1412            vec![
1413                TabId::vendor(VendorId::Anthropic),
1414                TabId::account("work"),
1415                TabId::desktop_account("gmail"),
1416                TabId::desktop_account("hotmail"),
1417            ]
1418        );
1419    }
1420
1421    #[test]
1422    fn a_desktop_profile_wins_a_label_collision_with_a_cli_account() {
1423        // One tab per label; the Desktop source wins so the label is never fed
1424        // from two stores refreshing one rotating token (which invalidate each
1425        // other and can silently show a wrong account's usage). The CLI entry is
1426        // dropped; a CLI-only label (work) is untouched.
1427        let config = config_with_accounts(&["gmail", "work"]);
1428        let tabs = build_tabs(&config, &["gmail".into(), "hotmail".into()]);
1429        assert_eq!(
1430            tabs,
1431            vec![
1432                TabId::vendor(VendorId::Anthropic),
1433                TabId::account("work"),
1434                TabId::desktop_account("gmail"),
1435                TabId::desktop_account("hotmail"),
1436            ]
1437        );
1438    }
1439
1440    #[test]
1441    fn desktop_accounts_suppress_the_default_tab_like_named_ones() {
1442        // show_default_account=false + only Desktop accounts => no default tab,
1443        // exactly as if they were [[anthropic.accounts]] (the Desktop-only user).
1444        let mut config = config_with_accounts(&[]);
1445        config.cursor.enabled = false;
1446        config.anthropic.show_default_account = false;
1447
1448        // No accounts of either kind: the default tab survives (never leave
1449        // Anthropic tab-less).
1450        assert_eq!(
1451            build_tabs(&config, &[]),
1452            vec![TabId::vendor(VendorId::Anthropic)]
1453        );
1454        // A Desktop account is present: default suppressed, only the account.
1455        assert_eq!(
1456            build_tabs(&config, &["gmail".into()]),
1457            vec![TabId::desktop_account("gmail")]
1458        );
1459    }
1460
1461    #[test]
1462    fn set_tabs_resets_states_and_clamps_selection() {
1463        // Simulates a Settings save that shrank the tab list: the selection
1464        // must clamp into range and every tab must reset to Loading so the
1465        // caller's spawn_all repopulates against the new config.
1466        let mut app = App::with_theme(
1467            tabs_from_config(&config_with_accounts(&["work", "personal"])),
1468            Theme::default(),
1469        );
1470        app.active = 2; // "personal"
1471        app.tabs[0] = TabState::error("old");
1472        let old_tab = app.tabs_meta[0].clone();
1473        assert!(app.begin_refresh(&old_tab));
1474
1475        app.set_tabs(tabs_from_config(&config_with_accounts(&[])));
1476        assert_eq!(app.tabs_meta, vec![TabId::vendor(VendorId::Anthropic)]);
1477        assert_eq!(app.active, 0, "selection clamped after shrink");
1478        assert!(matches!(app.tabs[0], TabState::Loading));
1479        assert!(!app.is_refreshing(&old_tab));
1480    }
1481
1482    #[test]
1483    fn set_tabs_preserves_selected_identity_when_entries_are_inserted() {
1484        let mut app = App::with_theme(
1485            vec![
1486                TabId::vendor(VendorId::Anthropic),
1487                TabId::vendor(VendorId::Openai),
1488            ],
1489            Theme::default(),
1490        );
1491        app.active = 1;
1492
1493        app.set_tabs(vec![
1494            TabId::vendor(VendorId::Anthropic),
1495            TabId::account("work"),
1496            TabId::vendor(VendorId::Openai),
1497        ]);
1498
1499        assert_eq!(app.active, 2);
1500        assert_eq!(app.active_tab_id(), Some(&TabId::vendor(VendorId::Openai)));
1501    }
1502
1503    #[test]
1504    fn refresh_from_old_generation_is_discarded() {
1505        let mut app = App::with_theme(vec![TabId::vendor(VendorId::Anthropic)], Theme::default());
1506        let old_generation = app.tab_generation;
1507        app.set_tabs(vec![TabId::vendor(VendorId::Openai)]);
1508
1509        assert!(!app.apply_refresh(
1510            old_generation,
1511            &TabId::vendor(VendorId::Anthropic),
1512            TabState::error("old result"),
1513        ));
1514        assert!(matches!(app.tabs[0], TabState::Loading));
1515    }
1516
1517    #[test]
1518    fn refresh_identity_mismatch_is_discarded() {
1519        let mut app = App::with_theme(vec![TabId::vendor(VendorId::Anthropic)], Theme::default());
1520        let generation = app.tab_generation;
1521
1522        assert!(!app.apply_refresh(
1523            generation,
1524            &TabId::vendor(VendorId::Openai),
1525            TabState::error("wrong tab"),
1526        ));
1527        assert!(matches!(app.tabs[0], TabState::Loading));
1528    }
1529
1530    #[test]
1531    fn refresh_identity_lands_at_new_index_after_same_generation_reorder() {
1532        let anthropic = TabId::vendor(VendorId::Anthropic);
1533        let openai = TabId::vendor(VendorId::Openai);
1534        let mut app = App::with_theme(vec![anthropic.clone(), openai.clone()], Theme::default());
1535        let generation = app.tab_generation;
1536        assert!(app.begin_refresh(&anthropic));
1537
1538        // A reorder is safe because delivery resolves the captured identity,
1539        // not a stale positional index.
1540        app.tabs_meta.swap(0, 1);
1541        app.tabs.swap(0, 1);
1542        assert!(app.apply_refresh(generation, &anthropic, TabState::error("ready")));
1543        assert!(matches!(app.tabs[0], TabState::Loading));
1544        assert!(matches!(&app.tabs[1], TabState::Error { message, .. } if message == "ready"));
1545        assert!(!app.is_refreshing(&anthropic));
1546    }
1547
1548    fn ready_at(fetched_at: chrono::DateTime<Utc>) -> TabState {
1549        TabState::Ready(Box::new(ReadyTab {
1550            snapshot: crate::usage::VendorSnapshot::Openrouter(crate::usage::OpenRouterSnapshot {
1551                label: "test".into(),
1552                total_credits: 0.0,
1553                total_usage: 0.0,
1554                usage_daily: 0.0,
1555                usage_weekly: 0.0,
1556                usage_monthly: 0.0,
1557                is_free_tier: false,
1558                limit: None,
1559                limit_remaining: None,
1560            }),
1561            stale: false,
1562            last_error: None,
1563            fetched_at: Some(fetched_at),
1564            display: Default::default(),
1565        }))
1566    }
1567
1568    #[test]
1569    fn refresh_keeps_ready_snapshot_visible_and_suppresses_duplicates() {
1570        let tab = TabId::vendor(VendorId::Openrouter);
1571        let fetched_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap();
1572        let mut app = App::with_theme(vec![tab.clone()], Theme::default());
1573        app.tabs[0] = ready_at(fetched_at);
1574
1575        assert!(app.begin_refresh(&tab));
1576        assert!(
1577            !app.begin_refresh(&tab),
1578            "duplicate request must be suppressed"
1579        );
1580        assert!(app.is_refreshing(&tab));
1581        match &app.tabs[0] {
1582            TabState::Ready(ready) => assert_eq!(ready.fetched_at, Some(fetched_at)),
1583            other => panic!("ready snapshot disappeared during refresh: {other:?}"),
1584        }
1585    }
1586
1587    #[test]
1588    fn first_refresh_still_uses_loading_until_data_arrives() {
1589        let tab = TabId::vendor(VendorId::Openrouter);
1590        let mut app = App::with_theme(vec![tab.clone()], Theme::default());
1591
1592        assert!(app.begin_refresh(&tab));
1593        assert!(app.is_refreshing(&tab));
1594        assert!(matches!(app.tabs[0], TabState::Loading));
1595
1596        assert!(app.apply_refresh(app.tab_generation, &tab, TabState::error("not signed in"),));
1597        assert!(!app.is_refreshing(&tab));
1598        assert!(
1599            matches!(&app.tabs[0], TabState::Error { message, .. } if message == "not signed in")
1600        );
1601    }
1602
1603    #[test]
1604    fn successful_revalidation_replaces_snapshot_and_clears_indicator() {
1605        let tab = TabId::vendor(VendorId::Openrouter);
1606        let old_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap();
1607        let new_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 1, 0).unwrap();
1608        let mut app = App::with_theme(vec![tab.clone()], Theme::default());
1609        app.tabs[0] = ready_at(old_at);
1610
1611        assert!(app.begin_refresh(&tab));
1612        assert!(app.apply_refresh(app.tab_generation, &tab, ready_at(new_at)));
1613        assert!(!app.is_refreshing(&tab));
1614        match &app.tabs[0] {
1615            TabState::Ready(ready) => assert_eq!(ready.fetched_at, Some(new_at)),
1616            other => panic!("expected replacement snapshot, got {other:?}"),
1617        }
1618    }
1619
1620    #[test]
1621    fn failed_revalidation_preserves_snapshot_with_visible_warning() {
1622        let tab = TabId::vendor(VendorId::Openrouter);
1623        let fetched_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap();
1624        let mut app = App::with_theme(vec![tab.clone()], Theme::default());
1625        app.tabs[0] = ready_at(fetched_at);
1626
1627        assert!(app.begin_refresh(&tab));
1628        assert!(app.apply_refresh(app.tab_generation, &tab, TabState::error("refresh failed"),));
1629        assert!(!app.is_refreshing(&tab));
1630        match &app.tabs[0] {
1631            TabState::Ready(ready) => {
1632                assert_eq!(ready.fetched_at, Some(fetched_at));
1633                assert!(ready.stale);
1634                assert_eq!(ready.last_error, Some((0, "refresh failed".into())));
1635            }
1636            other => panic!("last successful snapshot was lost: {other:?}"),
1637        }
1638        let sections = crate::tui::panels::sections_for(&app.tabs[0], Utc::now(), 5);
1639        assert!(sections.iter().any(|section| matches!(
1640            section,
1641            crate::tui::panels::Section::Text { label, value }
1642                if label == "Warning" && value == "refresh failed"
1643        )));
1644    }
1645
1646    #[test]
1647    fn old_generation_result_does_not_clear_current_refresh() {
1648        let tab = TabId::vendor(VendorId::Openrouter);
1649        let mut app = App::with_theme(vec![tab.clone()], Theme::default());
1650        let old_generation = app.tab_generation;
1651        app.set_tabs(vec![tab.clone()]);
1652        assert!(app.begin_refresh(&tab));
1653
1654        assert!(!app.apply_refresh(old_generation, &tab, TabState::error("old result"),));
1655        assert!(app.is_refreshing(&tab));
1656        assert!(matches!(app.tabs[0], TabState::Loading));
1657    }
1658
1659    #[test]
1660    fn apply_refresh_stamps_fetched_at_on_only_the_matching_tab() {
1661        // Pins the per-tab `fetched_at` the header now reads: a landed Anthropic
1662        // response leaves the still-loading OpenAI tab with no time of its own.
1663        // Dropping the global `last_refresh` clock is not observable from here
1664        // (it was write-only) — that is asserted against the rendered header in
1665        // `view::tests::header_refresh_*`.
1666        let anthropic = TabId::vendor(VendorId::Anthropic);
1667        let openai = TabId::vendor(VendorId::Openai);
1668        let mut app = App::with_theme(vec![anthropic.clone(), openai], Theme::default());
1669        let generation = app.tab_generation;
1670        let fetched_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap();
1671
1672        assert!(app.apply_refresh(generation, &anthropic, ready_at(fetched_at)));
1673        match &app.tabs[0] {
1674            TabState::Ready(ready) => assert_eq!(ready.fetched_at, Some(fetched_at)),
1675            other => panic!("expected Anthropic tab Ready, got {other:?}"),
1676        }
1677        assert!(matches!(app.tabs[1], TabState::Loading));
1678    }
1679
1680    #[test]
1681    fn select_primary_lands_on_default_account_tab() {
1682        // With account tabs present, `primary = anthropic` selects the default
1683        // Claude tab (index 0), not one of its account tabs.
1684        let app = {
1685            let tabs = tabs_from_config(&config_with_accounts(&["work"]));
1686            let mut a = App::with_theme(tabs, Theme::default());
1687            a.select_primary(Some(VendorId::Anthropic));
1688            a
1689        };
1690        assert_eq!(app.active, 0);
1691        assert_eq!(
1692            app.active_tab_id(),
1693            Some(&TabId::vendor(VendorId::Anthropic))
1694        );
1695    }
1696
1697    fn custom_spec(id: &str, enabled: bool) -> CustomProviderConfig {
1698        CustomProviderConfig {
1699            id: id.into(),
1700            name: "My Tool".into(),
1701            short_name: "myt".into(),
1702            enabled,
1703            ..Default::default()
1704        }
1705    }
1706
1707    #[test]
1708    fn custom_providers_get_tabs_after_every_builtin() {
1709        let config = Config {
1710            custom: vec![custom_spec("mytool", true), custom_spec("other", true)],
1711            ..Default::default()
1712        };
1713        let tabs = tabs_from_config(&config);
1714        let builtin_count = config.enabled_vendors().len();
1715        assert_eq!(tabs.len(), builtin_count + 2);
1716        assert!(
1717            tabs[..builtin_count]
1718                .iter()
1719                .all(|t| matches!(t.source, TabSource::Builtin(_)))
1720        );
1721        assert_eq!(tabs[builtin_count], TabId::custom(&config.custom[0]));
1722        assert_eq!(tabs[builtin_count + 1], TabId::custom(&config.custom[1]));
1723        assert_eq!(
1724            tabs[builtin_count].source,
1725            TabSource::Custom {
1726                id: "mytool".into(),
1727                name: "My Tool".into(),
1728                short_name: "myt".into(),
1729            }
1730        );
1731        assert!(tabs[builtin_count].account.is_none());
1732        assert!(!tabs[builtin_count].desktop);
1733        assert_eq!(tabs[builtin_count].vendor_id(), None);
1734    }
1735
1736    #[test]
1737    fn disabled_custom_provider_has_no_tab() {
1738        let config = Config {
1739            custom: vec![custom_spec("mytool", false)],
1740            ..Default::default()
1741        };
1742        let tabs = tabs_from_config(&config);
1743        assert!(
1744            tabs.iter()
1745                .all(|t| matches!(t.source, TabSource::Builtin(_)))
1746        );
1747        assert_eq!(tabs.len(), config.enabled_vendors().len());
1748    }
1749
1750    #[test]
1751    fn custom_tabs_are_listed_by_the_default_overview_but_not_by_a_vendor_filter() {
1752        let spec = custom_spec("mytool", true);
1753        let mut app = App::with_theme(
1754            vec![
1755                TabId::vendor(VendorId::Anthropic),
1756                TabId::custom(&spec),
1757                TabId::vendor(VendorId::Openai),
1758            ],
1759            Theme::default(),
1760        );
1761        assert_eq!(app.overview_tabs(), vec![0, 1, 2]);
1762
1763        // `overview_vendors` names VendorIds only, so the custom tab drops out.
1764        app.overview_vendors = Some(vec![VendorId::Openai, VendorId::Anthropic]);
1765        assert_eq!(app.overview_tabs(), vec![2, 0]);
1766    }
1767
1768    #[test]
1769    fn a_custom_active_tab_has_no_vendor_and_never_staggers() {
1770        let spec = custom_spec("mytool", true);
1771        let tabs = vec![
1772            TabId::vendor(VendorId::Anthropic),
1773            TabId::custom(&spec),
1774            TabId::account("work"),
1775        ];
1776        let mut app = App::with_theme(tabs.clone(), Theme::default());
1777        app.active = 1;
1778        assert_eq!(app.active_vendor(), None);
1779        assert_eq!(app.active_tab_id(), Some(&TabId::custom(&spec)));
1780
1781        // select_primary never lands on a custom tab.
1782        app.select_primary(Some(VendorId::Anthropic));
1783        assert_eq!(app.active, 0);
1784
1785        let step = Duration::from_millis(800);
1786        assert_eq!(
1787            refresh_stagger(&tabs, step),
1788            vec![Duration::ZERO, Duration::ZERO, step]
1789        );
1790    }
1791}