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