Skip to main content

ai_usagebar/
config.rs

1//! Config file at `~/.config/ai-usagebar/config.toml`.
2//!
3//! Layout:
4//! ```toml
5//! [anthropic]  enabled = true
6//! [openai]     enabled = true   # Codex OAuth from ~/.codex/auth.json
7//! [copilot]    enabled = false  # GitHub CLI OAuth, or an explicit env override
8//! [zai]        enabled = true
9//! [openrouter] enabled = true
10//! [deepseek]   enabled = false
11//! [deepinfra]  enabled = false
12//! [kimi]       enabled = false
13//! [grokbot]    enabled = false  # Grok Bot desktop app's own session
14//! [modelstudio] enabled = false # `bl` CLI's own console login (Token Plan)
15//! [[custom]]   id = "mytool"   # user-defined HTTP provider, static token
16//! ```
17//!
18//! Every field is optional with sensible defaults — missing config file is
19//! treated as "use defaults". API keys are read from env vars (the relevant
20//! `*_api_key_env` field lets the user override which env var name).
21
22use std::collections::{BTreeMap, HashSet};
23use std::path::{Path, PathBuf};
24
25#[cfg(unix)]
26use std::os::unix::fs::{MetadataExt, PermissionsExt};
27
28use serde::{Deserialize, Serialize};
29
30use crate::anthropic::creds::CredsTarget;
31use crate::balance::{DisplayPrefs, Headline};
32use crate::cache::Cache;
33use crate::error::{AppError, Result};
34use crate::vendor::VendorId;
35
36/// A misspelled section name is silently ignored without this: `[openrouer]`
37/// leaves OpenRouter on its defaults and the user sees the wrong vendor set
38/// with no diagnostic. Denying unknown keys is deliberately applied at the
39/// *section* level only — the set of sections is small and stable, whereas
40/// denying unknown keys inside every section would hard-fail configs that
41/// carry a field from a future or removed version.
42#[derive(Debug, Clone, Default, Deserialize, Serialize)]
43#[serde(default, deny_unknown_fields)]
44pub struct Config {
45    pub ui: UiConfig,
46    pub tray: TrayConfig,
47    pub context: ContextConfig,
48    pub anthropic: AnthropicConfig,
49    pub anthropic_api: AnthropicApiConfig,
50    pub openai: OpenAiConfig,
51    pub copilot: CopilotConfig,
52    pub zai: ZaiConfig,
53    pub openrouter: OpenRouterConfig,
54    pub deepseek: DeepseekConfig,
55    pub deepinfra: DeepInfraConfig,
56    pub kimi: KimiConfig,
57    pub kilo: KiloConfig,
58    pub novita: NovitaConfig,
59    pub synthetic: SyntheticConfig,
60    pub moonshot: MoonshotConfig,
61    pub grok: GrokConfig,
62    pub supergrok: SuperGrokConfig,
63    pub grokbot: GrokbotConfig,
64    pub antigravity: AntigravityConfig,
65    pub cursor: CursorConfig,
66    pub minimax: MinimaxConfig,
67    pub kiro: KiroConfig,
68    pub nous: NousConfig,
69    #[serde(rename = "opencode-go")]
70    pub opencode_go: OpenCodeGoConfig,
71    pub commandcode: CommandCodeConfig,
72    pub ollama: OllamaConfig,
73    pub orcarouter: OrcaRouterConfig,
74    pub modelstudio: ModelStudioConfig,
75    pub lyceum: LyceumConfig,
76    pub devin: DevinConfig,
77    #[serde(rename = "muse-code")]
78    pub muse: MuseConfig,
79    /// Quota-threshold desktop notifications (`[notifications]`).
80    pub notifications: NotificationsConfig,
81    /// User-defined providers, one `[[custom]]` table each.
82    pub custom: Vec<CustomProviderConfig>,
83    pub cline: ClineConfig,
84}
85
86/// UI / dispatch preferences. Currently just `primary` — which vendor the
87/// widget shows when `--vendor` is omitted, and which TUI tab is selected
88/// at startup.
89#[derive(Debug, Clone, Default, Deserialize, Serialize)]
90#[serde(default)]
91pub struct UiConfig {
92    /// `None` → fall back to anthropic for backward compatibility.
93    pub primary: Option<VendorId>,
94    /// Which vendors the Overview shows (the TUI's first tab and the macOS
95    /// menu-bar's top section), in this order. The TUI tab bar leads with the
96    /// same list; enabled vendors left off it follow in the canonical order.
97    /// `None` → every enabled vendor, in the canonical order.
98    pub overview_vendors: Option<Vec<VendorId>>,
99    /// Layout style for vendor navigation in the TUI: sidebar | navbar | none.
100    pub vendor_box: Option<VendorBoxStyle>,
101}
102
103impl UiConfig {
104    pub fn vendor_box(&self) -> VendorBoxStyle {
105        self.vendor_box.unwrap_or_default()
106    }
107}
108
109/// Tray preferences the host process needs before the WebView is up: shortcut,
110/// polling, updates, and the macOS menu-bar summary. Screen-only preferences
111/// (theme, density, time format) live in the popover's own storage instead.
112#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
113#[serde(default)]
114pub struct TrayConfig {
115    /// Global shortcut that toggles the popover, in the canonical
116    /// "Ctrl+Shift+U" spelling. `None` → no shortcut registered.
117    pub shortcut: Option<String>,
118    /// How often the tray re-reads every provider, in minutes: 1, 5, 10, 15, 30 or 60.
119    /// The footer's Refresh is always immediate. `None` → 5.
120    pub refresh_minutes: Option<u64>,
121    /// What the tray does when a newer release is published.
122    pub updates: Option<UpdateMode>,
123    /// macOS menu-bar presentation: `bars` (default), `provider` (logos) or
124    /// `name` (the selected provider's logo, short name and value).
125    pub menu_bar_style: Option<String>,
126    /// Whether the `name` style draws the short name beside the logo.
127    /// `None` → shown. A provider with no logo shows its name regardless.
128    pub menu_bar_short_name: Option<bool>,
129}
130
131/// Poll intervals the tray offers, in minutes. The provider cache TTL is
132/// 60 s regardless; this only decides how often the tray asks.
133pub const TRAY_REFRESH_MINUTES: [u64; 6] = [1, 5, 10, 15, 30, 60];
134const DEFAULT_TRAY_REFRESH_MINUTES: u64 = 5;
135
136/// Quota-threshold desktop notifications. On by default at 97%: the bar's
137/// whole job is to make an exhausted window visible before a request fails,
138/// and a notification is that signal for a window you are not looking at.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
140#[serde(default)]
141pub struct NotificationsConfig {
142    pub enabled: bool,
143    /// Percentage of a quota window at which a notification fires (1..=100;
144    /// 100 means only an exhausted window notifies).
145    pub threshold: u8,
146}
147
148impl Default for NotificationsConfig {
149    fn default() -> Self {
150        Self {
151            enabled: true,
152            threshold: 97,
153        }
154    }
155}
156
157impl TrayConfig {
158    pub fn refresh_minutes(&self) -> u64 {
159        self.refresh_minutes.unwrap_or(DEFAULT_TRAY_REFRESH_MINUTES)
160    }
161
162    pub fn updates(&self) -> UpdateMode {
163        self.updates.unwrap_or_default()
164    }
165
166    pub fn menu_bar_short_name(&self) -> bool {
167        self.menu_bar_short_name.unwrap_or(true)
168    }
169}
170
171/// How the tray handles a newer release: install it unattended, show a
172/// banner with an Install button, or never check in the background.
173#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
174#[serde(rename_all = "lowercase")]
175pub enum UpdateMode {
176    Auto,
177    #[default]
178    Notify,
179    Off,
180}
181
182impl UpdateMode {
183    pub fn as_str(self) -> &'static str {
184        match self {
185            Self::Auto => "auto",
186            Self::Notify => "notify",
187            Self::Off => "off",
188        }
189    }
190
191    pub fn parse(text: &str) -> Option<Self> {
192        match text.trim().to_ascii_lowercase().as_str() {
193            "auto" => Some(Self::Auto),
194            "notify" => Some(Self::Notify),
195            "off" => Some(Self::Off),
196            _ => None,
197        }
198    }
199}
200
201/// Presentation style of the TUI vendor navigation box.
202#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
203#[serde(rename_all = "lowercase")]
204pub enum VendorBoxStyle {
205    /// Vertical sidebar box on wide terminals; falls back to top navbar on narrow terminals.
206    #[default]
207    Sidebar,
208    /// Horizontal navbar strip above the dashboard detail panel.
209    Navbar,
210    /// Completely hide vendor navigation (dashboards expand to fill full width).
211    None,
212}
213
214/// Where the context view docks in the dashboard body. `v` cycles it while the
215/// overlay is open; the config value is what it opens with.
216#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
217#[serde(rename_all = "lowercase")]
218pub enum ContextLayout {
219    /// Takes the whole body, the way a vendor panel does.
220    #[default]
221    Full,
222    /// Beside the dashboard.
223    Split,
224    /// Below the dashboard.
225    Bottom,
226}
227
228impl ContextLayout {
229    pub fn next(self) -> Self {
230        match self {
231            ContextLayout::Full => ContextLayout::Split,
232            ContextLayout::Split => ContextLayout::Bottom,
233            ContextLayout::Bottom => ContextLayout::Full,
234        }
235    }
236
237    pub fn label(self) -> &'static str {
238        match self {
239            ContextLayout::Full => "full",
240            ContextLayout::Split => "split",
241            ContextLayout::Bottom => "bottom",
242        }
243    }
244}
245
246/// Optional local Claude Code context-window monitor. This is deliberately
247/// separate from vendors: sessions are discovered from local transcripts and
248/// change while the TUI is running, whereas vendor tabs are config-declared
249/// account identities.
250#[derive(Debug, Clone, Default, Deserialize, Serialize)]
251#[serde(default)]
252pub struct ContextConfig {
253    /// Keep the filesystem scanner completely dormant unless explicitly
254    /// enabled. The `c` key and its footer hint are hidden while disabled.
255    pub enabled: bool,
256    /// Override Claude Code's normal `~/.claude/projects` transcript root.
257    pub projects_path: Option<PathBuf>,
258    /// Optional fallback denominator. When absent, sessions without an exact
259    /// model override show their input-token count without inventing a %.
260    pub context_window_tokens: Option<u64>,
261    /// Exact Claude model id -> context-window size. This takes precedence
262    /// over `context_window_tokens`, which keeps mixed 200K/1M histories safe.
263    pub model_context_window_tokens: BTreeMap<String, u64>,
264    /// Where the view opens: full | split | bottom.
265    pub layout: ContextLayout,
266}
267
268impl ContextConfig {
269    pub fn window_tokens_for(&self, model: Option<&str>) -> Option<u64> {
270        model
271            .and_then(|model| self.model_context_window_tokens.get(model).copied())
272            .filter(|tokens| *tokens > 0)
273            .or_else(|| self.context_window_tokens.filter(|tokens| *tokens > 0))
274    }
275}
276
277#[derive(Debug, Clone, Deserialize, Serialize)]
278#[serde(default)]
279pub struct AnthropicConfig {
280    pub enabled: bool,
281    /// Override the credentials file path (defaults to `~/.claude/.credentials.json`).
282    /// This is the *default* account; extra subscriptions go in `accounts`.
283    pub credentials_path: Option<PathBuf>,
284    /// Extra Anthropic accounts beyond the default, each selected on the CLI
285    /// with `--account <label>` (issue #14). Empty by default, so existing
286    /// single-account configs are byte-for-byte unchanged.
287    pub accounts: Vec<AnthropicAccount>,
288    /// Directory to auto-discover extra accounts from, in Claude Code's own
289    /// `CLAUDE_CONFIG_DIR` layout: each immediate subdirectory becomes an
290    /// account labeled by the subdirectory name. The credentials may live in
291    /// that directory's `.credentials.json` or in the macOS Keychain, so
292    /// discovery intentionally does not probe for the credentials file.
293    /// Merged with `accounts` (explicit wins on a label clash); each is
294    /// refreshed independently.
295    pub accounts_dir: Option<PathBuf>,
296    /// Whether the default (unnamed) Claude account gets its own tab. Defaults
297    /// to `true` for back-compat. Set `false` when every account is managed
298    /// explicitly (via `accounts`/`accounts_dir`) so the ambient
299    /// Keychain/`~/.claude` login doesn't add a redundant "Claude" tab. Ignored
300    /// when there are no named accounts, so Anthropic never loses its only tab.
301    pub show_default_account: bool,
302    /// Where the Claude **Desktop app**'s saved account profiles live. Defaults
303    /// to `~/.claude-acc/profiles`, the store claude-acc
304    /// (<https://github.com/ohmaseclaro/claude-acc>) creates — `account switch`
305    /// reads and writes that layout so the two tools stay interchangeable.
306    /// Unrelated to `accounts_dir`, which is the `claude` CLI's own accounts.
307    pub desktop_profiles_dir: Option<PathBuf>,
308    /// Explicit trusted official Claude Code CLI/wrapper for a manual, isolated
309    /// preparation turn. None disables the action; never resolved via PATH.
310    pub desktop_prepare_binary: Option<PathBuf>,
311}
312
313impl Default for AnthropicConfig {
314    fn default() -> Self {
315        Self {
316            enabled: true,
317            credentials_path: None,
318            accounts: Vec::new(),
319            accounts_dir: None,
320            show_default_account: true,
321            desktop_profiles_dir: None,
322            desktop_prepare_binary: None,
323        }
324    }
325}
326
327/// One extra Anthropic account beyond the default (issue #14). The default
328/// account stays the singular `[anthropic] credentials_path`; each entry here
329/// is an additional subscription selected on the CLI with `--account <label>`.
330///
331/// ```toml
332/// [[anthropic.accounts]]
333/// label = "work"
334/// credentials_path = "~/.config/ai-usagebar/accounts/work/.credentials.json"
335/// ```
336#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
337pub struct AnthropicAccount {
338    /// Stable name used on the CLI (`--account <label>`) and as the cache
339    /// subdir (`~/.cache/ai-usagebar/anthropic/<label>`).
340    pub label: String,
341    /// OAuth credentials file for this account (same JSON shape Claude Code
342    /// writes). Token refreshes are written back here, so each account keeps
343    /// itself alive independently.
344    pub credentials_path: PathBuf,
345}
346
347impl AnthropicAccount {
348    /// The `CLAUDE_CONFIG_DIR` this account occupies — the credential file's
349    /// own directory. Claude Code hashes exactly this path for the account's
350    /// Keychain item, so it is also the account's identity for
351    /// [`crate::anthropic::keychain`].
352    pub fn config_dir(&self) -> PathBuf {
353        self.credentials_path
354            .parent()
355            .map_or_else(|| self.credentials_path.clone(), Path::to_path_buf)
356    }
357}
358
359impl AnthropicConfig {
360    /// Every extra account: the explicit `[[anthropic.accounts]]` entries plus
361    /// any auto-discovered under [`accounts_dir`](AnthropicConfig::accounts_dir).
362    /// Explicit entries take precedence on a label clash. This is what tabs and
363    /// `--account` enumerate, so a discovered account behaves exactly like a
364    /// hand-written one (own cache subdir, independent refresh).
365    pub fn all_accounts(&self) -> Vec<AnthropicAccount> {
366        let mut out = self.accounts.clone();
367        if let Some(dir) = &self.accounts_dir {
368            for acct in discover_accounts(dir) {
369                if !out.iter().any(|a| a.label == acct.label) {
370                    out.push(acct);
371                }
372            }
373        }
374        out
375    }
376
377    /// Find an extra account by label (explicit or discovered), or error listing
378    /// the known labels so a typo fails loudly instead of silently hitting the
379    /// default. Returns an owned account because discovered entries are
380    /// synthesized, not stored.
381    pub fn account(&self, label: &str) -> Result<AnthropicAccount> {
382        validate_account_label(label)?;
383        let all = self.all_accounts();
384        all.iter().find(|a| a.label == label).cloned().ok_or_else(|| {
385            let known: Vec<&str> = all.iter().map(|a| a.label.as_str()).collect();
386            AppError::Credentials(format!(
387                "anthropic account {label:?} not found in [[anthropic.accounts]] or accounts_dir; \
388                 known labels: {known:?}"
389            ))
390        })
391    }
392
393    /// Resolve a named account to the credentials target + isolated cache it
394    /// fetches through: [`CredsTarget::Named`], which on macOS prefers the
395    /// Keychain item scoped to the file's own directory (that is where
396    /// `CLAUDE_CONFIG_DIR=<dir> claude` actually writes) and falls back to
397    /// the file elsewhere — never a *different* account's item, since the
398    /// hash is per-directory, so issue #15's cross-account concern doesn't
399    /// apply. Plus an `anthropic/<label>` cache subdir. Shared by the widget
400    /// (`--account`) and the TUI's per-account tab (#14, #17) so both resolve
401    /// accounts identically; the widget layers its `--cache-dir` override on
402    /// top of the cache returned here.
403    pub fn account_target(&self, label: &str) -> Result<(CredsTarget, Cache)> {
404        self.account_target_with(label, self.active_cli_label().as_deref())
405    }
406
407    /// The named account the `claude` CLI is signed into right now, if any —
408    /// the `cli_active` that [`account_target_with`] takes. Reads
409    /// `~/.claude.json`, so tests inject the label instead.
410    ///
411    /// [`account_target_with`]: AnthropicConfig::account_target_with
412    pub fn active_cli_label(&self) -> Option<String> {
413        crate::anthropic::cli_account::home_claude_json()
414            .ok()
415            .and_then(|path| {
416                crate::anthropic::cli_account::resolve_active_label(&path, &self.all_accounts())
417            })
418    }
419
420    /// What the default (unlabelled) Claude entry reads: config
421    /// `credentials_path` as an explicit strict read, otherwise the platform
422    /// default, which alone gets the macOS Keychain fallback.
423    pub fn default_creds_target(&self) -> CredsTarget {
424        match self.credentials_path.clone() {
425            Some(path) => CredsTarget::Explicit(path),
426            None => {
427                CredsTarget::Default(crate::anthropic::creds::default_path().unwrap_or_default())
428            }
429        }
430    }
431
432    /// The pure half of [`account_target`](AnthropicConfig::account_target),
433    /// with "which account the `claude` CLI is signed into" injected — the same
434    /// shape as `Cli::resolve_vendor_with`. Probes the account's own credential
435    /// file with [`Path::exists`]; [`account_target_probing`] takes that probe
436    /// as an argument.
437    ///
438    /// [`account_target_probing`]: AnthropicConfig::account_target_probing
439    pub fn account_target_with(
440        &self,
441        label: &str,
442        cli_active: Option<&str>,
443    ) -> Result<(CredsTarget, Cache)> {
444        self.account_target_probing(label, cli_active, |path| path.exists())
445    }
446
447    /// The pure core: `exists` answers whether the account's own credential
448    /// file is there.
449    ///
450    /// When `label` *is* the live CLI login, `account switch` has moved its
451    /// credential into the default slot **and removed it from the named
452    /// one** — so reading the default keeps exactly one live lineage, and a
453    /// refresh here cannot invalidate the credential `claude` is using (or the
454    /// other way round). That only holds while the named slot really is empty,
455    /// which is why it is probed rather than assumed: a `CLAUDE_CONFIG_DIR`
456    /// layout keeps a live credential in every directory, and two of those
457    /// directories can hold the *same* account, which is what
458    /// `resolve_active_label` matches on. Believing the marker there sent every
459    /// fetch for that label to `~/.claude/.credentials.json` — a slot the user
460    /// never logs into, whose refresh token had expired, so a working account
461    /// reported "run `claude` to re-auth" while its own file sat live and
462    /// unread next to it.
463    ///
464    /// The cache directory is unchanged either way, so the tab keeps its
465    /// identity and its cached usage across a switch.
466    pub fn account_target_probing(
467        &self,
468        label: &str,
469        cli_active: Option<&str>,
470        exists: impl Fn(&Path) -> bool,
471    ) -> Result<(CredsTarget, Cache)> {
472        let account = self.account(label)?;
473        let cache = Cache::for_vendor_account("anthropic", label)?;
474        if cli_active == Some(label) && !exists(&account.credentials_path) {
475            return Ok((
476                CredsTarget::Default(crate::anthropic::creds::default_path()?),
477                cache,
478            ));
479        }
480        Ok((
481            CredsTarget::Named {
482                config_dir: account.config_dir(),
483                path: account.credentials_path,
484            },
485            cache,
486        ))
487    }
488}
489
490/// The label doubles as a cache subdirectory name
491/// (`~/.cache/ai-usagebar/anthropic/<label>/`), which nests inside the default
492/// account's cache dir — so path separators, control characters, or reserved
493/// cache sidecar names would escape, spoof terminal output, or collide with the
494/// cache layout (`usage.json`, `.stale`, …).
495pub fn validate_account_label(label: &str) -> Result<()> {
496    validate_account_label_for("anthropic", label)
497}
498
499fn validate_account_label_for(vendor: &str, label: &str) -> Result<()> {
500    const RESERVED: [&str; 4] = ["usage.json", ".stale", ".last_error", ".fetch.lock"];
501    let bad = label.is_empty()
502        || label == "."
503        || label == ".."
504        || label.contains(['/', '\\'])
505        || label.contains(':')
506        || label.chars().any(char::is_control)
507        || RESERVED.contains(&label);
508    if bad {
509        return Err(AppError::Credentials(format!(
510            "invalid {vendor} account label {label:?}: must be a non-empty name \
511             without path separators, drive prefixes, control characters, or reserved cache names"
512        )));
513    }
514    Ok(())
515}
516
517/// Discover accounts under `accounts_dir` in the `CLAUDE_CONFIG_DIR` layout:
518/// each immediate subdirectory becomes an account labeled by the subdirectory
519/// name. Best-effort: an unreadable directory or unusable label is skipped
520/// silently rather than failing the whole config — discovery is convenience,
521/// while an explicit `[[anthropic.accounts]]` entry stays authoritative. The
522/// fetch path resolves credentials from either `.credentials.json` or the macOS
523/// Keychain. Sorted by label so the tab order is stable across runs.
524fn discover_accounts(accounts_dir: &std::path::Path) -> Vec<AnthropicAccount> {
525    let Ok(entries) = std::fs::read_dir(accounts_dir) else {
526        return Vec::new();
527    };
528    let mut found: Vec<AnthropicAccount> = entries
529        .flatten()
530        .filter_map(|entry| {
531            let path = entry.path();
532            if !path.is_dir() {
533                return None;
534            }
535            let label = path.file_name()?.to_str()?.to_string();
536            validate_account_label(&label).ok()?;
537            Some(AnthropicAccount {
538                label,
539                credentials_path: path.join(".credentials.json"),
540            })
541        })
542        .collect();
543    found.sort_by(|a, b| a.label.cmp(&b.label));
544    found
545}
546
547/// Render a path with `$HOME` collapsed back to `~`, matching the style the docs
548/// and existing `[[anthropic.accounts]]` entries use. Pure so it's testable;
549/// paths outside home are returned verbatim.
550pub fn tildify(path: &Path, home: &Path) -> String {
551    path.strip_prefix(home)
552        .map(|rest| {
553            let rendered = rest.display().to_string();
554            // Config paths use the same portable `~/...` spelling on every
555            // platform. A Windows `~\...` would not be expanded by the loader.
556            #[cfg(windows)]
557            let rendered = rendered.replace('\\', "/");
558            format!("~/{rendered}")
559        })
560        .unwrap_or_else(|_| path.display().to_string())
561}
562
563/// Where a newly-registered account's credentials file lives by default: next
564/// to `config.toml`, under `accounts/<label>/.credentials.json`. Returns the
565/// absolute path (for `mkdir`) — tilde-render it with [`tildify`] for display
566/// and for the value written into config.
567pub fn default_account_credentials_path(config_path: &Path, label: &str) -> PathBuf {
568    let base = config_path.parent().unwrap_or_else(|| Path::new("."));
569    base.join("accounts").join(label).join(".credentials.json")
570}
571
572/// Append a `[[anthropic.accounts]]` entry to a parsed config document, in
573/// place. Pure over a `toml_edit` document so the validation, duplicate check,
574/// and formatting are testable without disk. Preserves the rest of the file
575/// (comments, key order, other sections) — only the new array-of-tables entry
576/// is added. Errors on an invalid label or a label that already exists.
577pub fn add_anthropic_account_to_doc(
578    doc: &mut toml_edit::DocumentMut,
579    label: &str,
580    credentials_path: &str,
581) -> Result<()> {
582    use toml_edit::{Item, Table, value};
583
584    validate_account_label(label)?;
585
586    let anthropic = doc
587        .entry("anthropic")
588        .or_insert_with(|| Item::Table(Table::new()));
589    let anthropic = anthropic
590        .as_table_mut()
591        .ok_or_else(|| AppError::Other("[anthropic] in config.toml is not a table".into()))?;
592
593    let accounts = anthropic
594        .entry("accounts")
595        .or_insert_with(|| Item::ArrayOfTables(toml_edit::ArrayOfTables::new()));
596    let accounts = accounts.as_array_of_tables_mut().ok_or_else(|| {
597        AppError::Other("[[anthropic.accounts]] in config.toml is not an array of tables".into())
598    })?;
599
600    let exists = accounts
601        .iter()
602        .any(|t| t.get("label").and_then(Item::as_str) == Some(label));
603    if exists {
604        return Err(AppError::Credentials(format!(
605            "anthropic account {label:?} already exists in config.toml"
606        )));
607    }
608
609    let mut table = Table::new();
610    table["label"] = value(label);
611    table["credentials_path"] = value(credentials_path);
612    accounts.push(table);
613    Ok(())
614}
615
616/// Where a newly-registered Codex account's `auth.json` lives by default:
617/// `~/.codex-<label>/auth.json`, the `CODEX_HOME` the docs have always
618/// suggested for a second login.
619pub fn default_codex_auth_path(home: &Path, label: &str) -> PathBuf {
620    home.join(format!(".codex-{label}")).join("auth.json")
621}
622
623/// Append a `[[openai.accounts]]` entry to a parsed config document, in place.
624/// The Codex counterpart of [`add_anthropic_account_to_doc`], with the same
625/// guarantees: only the new entry is added, and an invalid or duplicate label
626/// is an error.
627pub fn add_openai_account_to_doc(
628    doc: &mut toml_edit::DocumentMut,
629    label: &str,
630    codex_auth_path: &str,
631) -> Result<()> {
632    use toml_edit::{Item, Table, value};
633
634    validate_account_label_for("openai", label)?;
635
636    let openai = doc
637        .entry("openai")
638        .or_insert_with(|| Item::Table(Table::new()));
639    let openai = openai
640        .as_table_mut()
641        .ok_or_else(|| AppError::Other("[openai] in config.toml is not a table".into()))?;
642
643    let accounts = openai
644        .entry("accounts")
645        .or_insert_with(|| Item::ArrayOfTables(toml_edit::ArrayOfTables::new()));
646    let accounts = accounts.as_array_of_tables_mut().ok_or_else(|| {
647        AppError::Other("[[openai.accounts]] in config.toml is not an array of tables".into())
648    })?;
649
650    if accounts
651        .iter()
652        .any(|t| t.get("label").and_then(Item::as_str) == Some(label))
653    {
654        return Err(AppError::Credentials(format!(
655            "openai account {label:?} already exists in config.toml"
656        )));
657    }
658
659    let mut table = Table::new();
660    table["label"] = value(label);
661    table["codex_auth_path"] = value(codex_auth_path);
662    accounts.push(table);
663    Ok(())
664}
665
666/// Set or update a boolean field in a TOML section, preserving comments and
667/// formatting of unaffected nodes. Shared by the Settings overlay and
668/// [`enable_vendors_in`] so both writers shape `enabled = true` identically.
669pub(crate) fn set_bool(
670    doc: &mut toml_edit::DocumentMut,
671    section: &str,
672    key: &str,
673    new_value: bool,
674) -> Result<()> {
675    let table = doc
676        .entry(section)
677        .or_insert_with(toml_edit::table)
678        .as_table_mut()
679        .ok_or_else(|| AppError::Other(format!("config.toml: [{section}] is not a table")))?;
680
681    if let Some(item) = table.get_mut(key)
682        && let Some(v) = item.as_value_mut()
683    {
684        // Keep a trailing `# comment` on the line being rewritten: the value
685        // is the only thing that changed, and the note beside it is the
686        // user's.
687        let suffix = v.decor().suffix().cloned();
688        *v = toml_edit::Value::from(new_value);
689        v.decor_mut().set_prefix(" ");
690        if let Some(suffix) = suffix {
691            v.decor_mut().set_suffix(suffix);
692        }
693        return Ok(());
694    }
695    table.insert(key, toml_edit::value(new_value));
696    Ok(())
697}
698
699/// Set, replace or remove a scalar field in a TOML section, preserving
700/// comments and formatting of unaffected nodes. `None` removes the key so a
701/// cleared preference does not linger as an empty string. The value keeps
702/// its own TOML type on disk — an integer preference such as
703/// `refresh_minutes` must not be quoted, or `Config::load_from` rejects it.
704pub(crate) fn set_value(
705    doc: &mut toml_edit::DocumentMut,
706    section: &str,
707    key: &str,
708    new_value: Option<toml_edit::Value>,
709) -> Result<()> {
710    let table = doc
711        .entry(section)
712        .or_insert_with(toml_edit::table)
713        .as_table_mut()
714        .ok_or_else(|| AppError::Other(format!("config.toml: [{section}] is not a table")))?;
715
716    let Some(mut new_value) = new_value else {
717        table.remove(key);
718        return Ok(());
719    };
720    if let Some(item) = table.get_mut(key)
721        && let Some(v) = item.as_value_mut()
722    {
723        let suffix = v.decor().suffix().cloned();
724        new_value.decor_mut().set_prefix(" ");
725        if let Some(suffix) = suffix {
726            new_value.decor_mut().set_suffix(suffix);
727        }
728        *v = new_value;
729        return Ok(());
730    }
731    table.insert(key, toml_edit::Item::Value(new_value));
732    Ok(())
733}
734
735/// Write one `[tray]` preference into the config at `path`, creating the
736/// file when it doesn't exist and leaving every other line as it was.
737/// `None` removes the key. The value keeps the TOML type it is given
738/// (`"notify"` stays a string, `5` stays an integer). The tray host is the
739/// only writer.
740pub fn set_tray_value(path: &Path, key: &str, value: Option<toml_edit::Value>) -> Result<()> {
741    let mut doc = read_config_document(path)?;
742    let before = doc.to_string();
743    set_value(&mut doc, "tray", key, value)?;
744    if doc.to_string() == before {
745        return Ok(());
746    }
747    write_config_document(path, &doc)
748}
749
750/// Persist one validated notification preference without disturbing other
751/// config sections or their comments.
752pub fn set_notification_value(path: &Path, key: &str, value: toml_edit::Value) -> Result<()> {
753    match key {
754        "enabled" if value.as_bool().is_some() => {}
755        "threshold" if value.as_integer().is_some_and(|n| (1..=100).contains(&n)) => {}
756        _ => {
757            return Err(AppError::Other(format!(
758                "invalid notification preference: {key}"
759            )));
760        }
761    }
762    let mut doc = read_config_document(path)?;
763    let before = doc.to_string();
764    set_value(&mut doc, "notifications", key, Some(value))?;
765    if doc.to_string() == before {
766        return Ok(());
767    }
768    write_config_document(path, &doc)
769}
770
771/// Flip one provider's `enabled` switch in the config at `path`, creating the
772/// file and the provider's section when either doesn't exist and leaving every
773/// other line — comments, keys, unrelated sections — exactly as it was
774/// (#244). An unchanged document is not rewritten. This is the whitelisted
775/// writer the settings surfaces go through; the slug is validated inside
776/// [`set_vendor_enabled_in_doc`], so no caller can create an arbitrary
777/// section or reach a `[[custom]]` entry from here.
778pub fn set_vendor_enabled(path: &Path, slug: &str, enabled: bool) -> Result<()> {
779    let mut doc = read_config_document(path)?;
780    let before = doc.to_string();
781    set_vendor_enabled_in_doc(&mut doc, slug, enabled)?;
782    if doc.to_string() == before {
783        return Ok(());
784    }
785    write_config_document(path, &doc)
786}
787
788/// The validated core of [`set_vendor_enabled`], over an already-open
789/// document: strictly `slug → VendorId → config_section()` — never a
790/// caller-chosen section name — then the shared comment-preserving
791/// [`set_bool`] both the Settings overlay and `enable_vendors_in` use.
792pub fn set_vendor_enabled_in_doc(
793    doc: &mut toml_edit::DocumentMut,
794    slug: &str,
795    enabled: bool,
796) -> Result<()> {
797    let Some(vendor) = VendorId::from_slug(slug) else {
798        return Err(AppError::Other(format!(
799            "unknown provider {slug:?}: not a built-in vendor"
800        )));
801    };
802    set_bool(doc, vendor.config_section(), "enabled", enabled)
803}
804
805/// A TOML error as `line L, column C: message`. `toml` and `toml_edit` both
806/// quote the offending source line in their `Display`, and in `config.toml`
807/// that line can hold an inline `api_key`: one missing quote around a key put
808/// the key in the widget's tooltip, in `usage --json` and on stderr. The
809/// position is enough to find the mistake.
810pub(crate) fn toml_error_summary(
811    input: &str,
812    span: Option<std::ops::Range<usize>>,
813    message: &str,
814) -> String {
815    let message = message.trim_end();
816    match span.and_then(|range| input.get(..range.start)) {
817        Some(before) => {
818            let line = before.matches('\n').count() + 1;
819            let line_start = before.rfind('\n').map_or(0, |i| i + 1);
820            let column = before[line_start..].chars().count() + 1;
821            format!("line {line}, column {column}: {message}")
822        }
823        None => message.to_string(),
824    }
825}
826
827/// Read `path` into a `toml_edit` document with comments intact. A missing
828/// file is an empty document, so a writer can create the config from nothing;
829/// any other I/O failure or a parse error is reported rather than clobbered.
830pub(crate) fn read_config_document(path: &Path) -> Result<toml_edit::DocumentMut> {
831    let original = match std::fs::read_to_string(path) {
832        Ok(contents) => contents,
833        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
834        Err(error) => return Err(AppError::io_at(path, error)),
835    };
836    if original.trim().is_empty() {
837        return Ok(toml_edit::DocumentMut::new());
838    }
839    original.parse().map_err(|e: toml_edit::TomlError| {
840        let summary = toml_error_summary(&original, e.span(), e.message());
841        AppError::Other(format!("config.toml not parseable: {summary}"))
842    })
843}
844
845/// Persist an edited config document: parent dir created, atomic
846/// tempfile-and-rename write, and `chmod 600` on Unix because the file may
847/// carry inline credentials. The one write path for every config editor.
848pub(crate) fn write_config_document(path: &Path, doc: &toml_edit::DocumentMut) -> Result<()> {
849    let bytes = doc.to_string();
850    crate::cache::atomic_write(path, bytes.as_bytes())?;
851
852    #[cfg(unix)]
853    {
854        if let Ok(meta) = std::fs::metadata(path) {
855            let mut perms = meta.permissions();
856            perms.set_mode(0o600);
857            let _ = std::fs::set_permissions(path, perms);
858        }
859    }
860    Ok(())
861}
862
863/// Flip `enabled = true` for each vendor's section in the config at `path`,
864/// creating the file when it doesn't exist and leaving every other line —
865/// comments, keys, unrelated sections — exactly as it was. Never writes
866/// `false`: `config.toml` stays the user's source of truth and this only ever
867/// widens it. A document that comes out textually unchanged (every vendor
868/// already enabled) is not rewritten, so an idempotent call doesn't touch the
869/// file's mtime or race a concurrent editor.
870pub fn enable_vendors_in(path: &Path, vendors: &[VendorId]) -> Result<Vec<VendorId>> {
871    let mut doc = read_config_document(path)?;
872    let before = doc.to_string();
873    let written: Vec<VendorId> = vendors
874        .iter()
875        .copied()
876        .filter(|vendor| !is_explicitly_disabled(&doc, *vendor))
877        .collect();
878    for vendor in &written {
879        set_bool(&mut doc, vendor.config_section(), "enabled", true)?;
880    }
881    if doc.to_string() == before {
882        return Ok(written);
883    }
884    write_config_document(path, &doc)?;
885    Ok(written)
886}
887
888/// Whether the config *says* `enabled = false` for this vendor, as opposed to
889/// not mentioning it.
890///
891/// This is the durable record of a user having turned a vendor off. `detect`
892/// also keeps a set of vendors it has already considered, but that lives in the
893/// cache directory, which is by convention safe to delete — so it cannot be the
894/// only thing standing between "the user opted out" and re-enabling a provider
895/// (and resuming requests to it) behind their back. The config file is the one
896/// place that outlives a cache wipe, so the explicit `false` is honored here,
897/// at the write, where no caller can route around it.
898fn is_explicitly_disabled(doc: &toml_edit::DocumentMut, vendor: VendorId) -> bool {
899    doc.get(vendor.config_section())
900        .and_then(|section| section.get("enabled"))
901        .and_then(|enabled| enabled.as_bool())
902        == Some(false)
903}
904
905#[derive(Debug, Clone, Deserialize, Serialize)]
906#[serde(default)]
907pub struct OpenAiConfig {
908    pub enabled: bool,
909    /// Override the Codex auth file path (defaults to `~/.codex/auth.json`).
910    pub codex_auth_path: Option<PathBuf>,
911    /// Extra Codex logins, each its own `auth.json`. Same shape as
912    /// [`AnthropicAccount`] and for the same reason: Codex is an OAuth vendor,
913    /// so an account *is* a credential file, and `openai::creds::write_back`
914    /// refreshes into whichever one it read.
915    #[serde(default)]
916    pub accounts: Vec<OpenAiAccount>,
917    /// Whether the default (unnamed) Codex login gets its own tab. Defaults to
918    /// `true`. Set `false` once every login is a named account — typically
919    /// after `account add <label> --codex --adopt-current` — so the default
920    /// `~/.codex/auth.json` does not also appear as a second copy of whichever
921    /// account is active. Ignored when there are no named accounts.
922    pub show_default_account: bool,
923    /// Reserved, and inert: names the env var an API-key-only path *would*
924    /// read (admin key → `/v1/organization/costs`). Nothing consumes it —
925    /// OpenAI usage comes solely from Codex OAuth. Kept because that path is
926    /// still intended, not for back-compat: `[openai]` doesn't deny unknown
927    /// fields, so an existing `admin_key_env` would load either way. See
928    /// `config.example.toml`, which ships it commented out so nobody sets it
929    /// expecting an effect.
930    pub admin_key_env: String,
931}
932
933/// One extra Codex login.
934///
935/// ```toml
936/// [[openai.accounts]]
937/// label = "work"
938/// codex_auth_path = "~/.config/ai-usagebar/accounts/work-codex/auth.json"
939/// ```
940///
941/// A second login is made with `CODEX_HOME=~/.codex-work codex login`; point
942/// `codex_auth_path` at the `auth.json` it writes.
943#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
944pub struct OpenAiAccount {
945    /// Stable name used on the CLI (`--account <label>`) and as the cache
946    /// subdir (`~/.cache/ai-usagebar/openai/<label>`).
947    pub label: String,
948    /// Codex OAuth file for this account. Refreshed tokens are written back
949    /// here, so each account keeps itself alive independently.
950    pub codex_auth_path: PathBuf,
951}
952
953impl OpenAiConfig {
954    /// The auth file for `label`, or the singular/default one when `label` is
955    /// `None`. An unknown label is an error rather than a silent fall back to
956    /// the default account, which would report the wrong login's usage.
957    pub fn resolve_auth_path(&self, label: Option<&str>) -> Result<PathBuf> {
958        let Some(label) = label else {
959            return match &self.codex_auth_path {
960                Some(path) => Ok(path.clone()),
961                None => crate::openai::creds::default_path(),
962            };
963        };
964        self.accounts
965            .iter()
966            .find(|account| account.label == label)
967            .map(|account| account.codex_auth_path.clone())
968            .ok_or_else(|| {
969                AppError::Credentials(format!(
970                    "no OpenAI account named {label:?}. Add it under \
971                     [[openai.accounts]], or drop --account to use the default login."
972                ))
973            })
974    }
975
976    /// The auth file a fetch for `label` reads. Unlike
977    /// [`resolve_auth_path`](OpenAiConfig::resolve_auth_path), this follows
978    /// `account switch --codex`: the active account's login has been moved
979    /// into the default slot, so it is read there. The answer holds only while
980    /// no switch runs, so a fetch asks it under the credentials lock; see
981    /// [`fetch_snapshot_routed`](crate::openai::fetch_snapshot_routed).
982    pub fn fetch_auth_path(&self, label: Option<&str>) -> Result<PathBuf> {
983        let Some(label) = label else {
984            return self.resolve_auth_path(None);
985        };
986        let default = self.resolve_auth_path(None)?;
987        let active = crate::openai::account::resolve_active_label(&default, &self.accounts);
988        self.fetch_auth_path_probing(label, active.as_deref(), Path::exists)
989    }
990
991    /// The pure core of [`fetch_auth_path`](OpenAiConfig::fetch_auth_path),
992    /// with the active label and the file probe injected. The own file is
993    /// probed rather than assumed gone: an account signed in again under its
994    /// own `CODEX_HOME` keeps reading that file.
995    pub fn fetch_auth_path_probing(
996        &self,
997        label: &str,
998        active: Option<&str>,
999        exists: impl Fn(&Path) -> bool,
1000    ) -> Result<PathBuf> {
1001        let own = self.resolve_auth_path(Some(label))?;
1002        if active == Some(label) && !exists(&own) {
1003            return self.resolve_auth_path(None);
1004        }
1005        Ok(own)
1006    }
1007}
1008
1009impl Default for OpenAiConfig {
1010    fn default() -> Self {
1011        Self {
1012            enabled: true,
1013            codex_auth_path: None,
1014            accounts: Vec::new(),
1015            show_default_account: true,
1016            admin_key_env: "OPENAI_ADMIN_KEY".to_string(),
1017        }
1018    }
1019}
1020
1021/// GitHub Copilot quota from the private endpoint used by VS Code. The token
1022/// comes from an explicit environment override or the official GitHub CLI;
1023/// this app never reads, copies, or writes GitHub credential stores.
1024#[derive(Debug, Clone, Deserialize, Serialize)]
1025#[serde(default)]
1026pub struct CopilotConfig {
1027    pub enabled: bool,
1028    /// Path to the official GitHub CLI. Unset looks `gh` up on `PATH`, which
1029    /// is how `gh` is normally installed; set it to pin the executable.
1030    pub gh_binary: Option<PathBuf>,
1031    /// Extra Copilot accounts beyond whichever one `gh` has active, each
1032    /// selected with `--account <label>` (issue #378). Empty by default, so an
1033    /// existing single-account config behaves exactly as before.
1034    pub accounts: Vec<CopilotAccount>,
1035    /// Whether the default (unnamed) Copilot account gets its own tab.
1036    /// Defaults to `true` for back-compat. Set `false` once every account is
1037    /// named, so the ambient active `gh` login does not also appear as a
1038    /// duplicate of whichever one it happens to be. Ignored when there are no
1039    /// named accounts, so Copilot never loses its only tab.
1040    pub show_default_account: bool,
1041}
1042
1043impl Default for CopilotConfig {
1044    fn default() -> Self {
1045        Self {
1046            // Unlike Claude and Codex, Copilot stays opt-in: enabling it
1047            // spawns `gh` on every refresh.
1048            enabled: false,
1049            gh_binary: None,
1050            accounts: Vec::new(),
1051            show_default_account: true,
1052        }
1053    }
1054}
1055
1056/// One named Copilot account, resolved through the GitHub CLI's own
1057/// multi-account support rather than by storing a token here.
1058///
1059/// ```toml
1060/// [[copilot.accounts]]
1061/// label = "work"
1062/// user = "my-work-login"
1063/// ```
1064///
1065/// Sign the second account in with `gh auth login` (gh keeps both on the same
1066/// host); `gh auth status` lists the login names. `user` is that login name,
1067/// not an email, and is validated against GitHub's login grammar before it
1068/// reaches the command line.
1069///
1070/// There is deliberately no `hostname` field yet. `gh` supports GitHub
1071/// Enterprise hosts, but the quota endpoint
1072/// (`https://api.github.com/copilot_internal/user`) is github.com-only, so
1073/// accepting a hostname would promise GHES support the fetch cannot keep.
1074#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
1075pub struct CopilotAccount {
1076    /// Stable name used on the CLI (`--account <label>`) and as the cache
1077    /// subdir (`~/.cache/ai-usagebar/copilot/<label>`).
1078    pub label: String,
1079    /// The GitHub login this account signs in as, passed to
1080    /// `gh auth token --user <user>`.
1081    pub user: String,
1082}
1083
1084impl CopilotConfig {
1085    /// The GitHub login for `label`, or `None` for the default account.
1086    /// An unknown label is an error rather than a silent fall back to the
1087    /// active `gh` account, which would report the wrong account's quota.
1088    pub fn resolve_user(&self, label: Option<&str>) -> Result<Option<&str>> {
1089        let Some(label) = label else {
1090            return Ok(None);
1091        };
1092        self.accounts
1093            .iter()
1094            .find(|account| account.label == label)
1095            .map(|account| Some(account.user.as_str()))
1096            .ok_or_else(|| {
1097                let known = self
1098                    .accounts
1099                    .iter()
1100                    .map(|account| account.label.as_str())
1101                    .collect::<Vec<_>>();
1102                AppError::Other(if known.is_empty() {
1103                    format!(
1104                        "copilot: no account {label:?} — [copilot] has no accounts array; \
1105                         add [[copilot.accounts]] with label and user"
1106                    )
1107                } else {
1108                    format!(
1109                        "copilot: no account {label:?}; known labels: {}",
1110                        known.join(", ")
1111                    )
1112                })
1113            })
1114    }
1115
1116    pub fn resolve_token(&self, label: Option<&str>) -> Result<String> {
1117        self.resolve_token_with(
1118            |name| std::env::var_os(name),
1119            &crate::copilot::credentials::SystemGhAuthTokenRunner,
1120            label,
1121        )
1122    }
1123
1124    fn resolve_token_with(
1125        &self,
1126        environment: impl Fn(&str) -> Option<std::ffi::OsString>,
1127        runner: &impl crate::copilot::credentials::GhAuthTokenRunner,
1128        label: Option<&str>,
1129    ) -> Result<String> {
1130        let user = self.resolve_user(label)?;
1131        if let Some(value) = environment("GITHUB_COPILOT_TOKEN") {
1132            let token = value.into_string().map_err(|_| {
1133                AppError::Credentials(
1134                    "GitHub Copilot: GITHUB_COPILOT_TOKEN is not valid UTF-8.".into(),
1135                )
1136            })?;
1137            if !token.is_empty() {
1138                // The override names no account, so pairing it with
1139                // `--account` would report one account's quota under another
1140                // one's label. Refuse instead of guessing which was meant.
1141                if let Some(label) = label {
1142                    return Err(AppError::Credentials(format!(
1143                        "GitHub Copilot: GITHUB_COPILOT_TOKEN is set, so it is unclear whether \
1144                         --account {label:?} should use that token or {user:?}'s `gh` login. \
1145                         Unset the variable to use named accounts."
1146                    )));
1147                }
1148                return Ok(token);
1149            }
1150        }
1151        crate::copilot::credentials::resolve_with(runner, self.gh_binary.as_deref(), user)
1152    }
1153}
1154
1155#[derive(Debug, Clone, Deserialize, Serialize)]
1156#[serde(default)]
1157pub struct NousConfig {
1158    pub enabled: bool,
1159    /// Which number goes on the bar: the consumed percentage of the monthly
1160    /// allocation (`percent`, the default) or the credits still usable
1161    /// (`amount`). See [`DisplayPrefs`].
1162    pub headline: Headline,
1163}
1164
1165impl Default for NousConfig {
1166    fn default() -> Self {
1167        Self {
1168            enabled: false,
1169            // A plan-usage vendor keeps its percentage; only [nous] can now
1170            // ask for the credits balance instead.
1171            headline: Headline::Percent,
1172        }
1173    }
1174}
1175
1176#[derive(Debug, Clone, Deserialize, Serialize)]
1177#[serde(default)]
1178pub struct OpenCodeGoConfig {
1179    pub enabled: bool,
1180    pub api_key_env: String,
1181    pub api_key: Option<String>,
1182    /// Override the search list for the official OpenCode CLI's `auth.json`
1183    /// (`$XDG_DATA_HOME/opencode` or `~/.local/share/opencode`), for a
1184    /// non-standard install. The key is read read-only, never copied.
1185    pub auth_paths: Option<Vec<PathBuf>>,
1186}
1187
1188/// Cline reads the OAuth credential the Cline CLI maintains in
1189/// `~/.cline/data/settings/providers.json`, so it needs no API key of its own;
1190/// `api_key`/`api_key_env` exist for a machine without the CLI, where a key
1191/// from app.cline.bot stands in. `auth_paths` overrides the search list for a
1192/// non-standard install.
1193#[derive(Debug, Clone, Deserialize, Serialize)]
1194#[serde(default)]
1195pub struct ClineConfig {
1196    pub enabled: bool,
1197    pub auth_paths: Option<Vec<PathBuf>>,
1198    pub api_key_env: String,
1199    pub api_key: Option<String>,
1200}
1201
1202impl Default for ClineConfig {
1203    fn default() -> Self {
1204        Self {
1205            enabled: false,
1206            auth_paths: None,
1207            api_key_env: crate::cline::creds::API_KEY_ENV.to_string(),
1208            api_key: None,
1209        }
1210    }
1211}
1212
1213/// Command Code reads the OAuth credential from the official CLI or pi, so it
1214/// has no API key of its own. `auth_paths` overrides that search list for a
1215/// non-standard install. It is disabled until explicitly enabled or detected
1216/// from a local credential.
1217#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1218#[serde(default)]
1219pub struct CommandCodeConfig {
1220    pub enabled: bool,
1221    pub auth_paths: Option<Vec<PathBuf>>,
1222}
1223
1224/// Ollama Cloud (`ollama.com/api/balance`). Disabled by default: the local
1225/// `ollama` daemon is the product most users reach for, and it has no quota
1226/// route to query. Cloud quota is opt-in, with the key taken from
1227/// `OLLAMA_API_KEY` (or `api_key` as a fallback for `chmod 600` configs).
1228#[derive(Debug, Clone, Deserialize, Serialize)]
1229#[serde(default)]
1230pub struct OllamaConfig {
1231    pub enabled: bool,
1232    pub api_key_env: String,
1233    pub api_key: Option<String>,
1234    /// Display label for the plan row. The API itself does not report a plan
1235    /// name; "pro" is what an Ollama Cloud Pro account shows in the UI.
1236    pub plan: String,
1237}
1238
1239impl Default for OllamaConfig {
1240    fn default() -> Self {
1241        Self {
1242            enabled: false,
1243            api_key_env: "OLLAMA_API_KEY".to_string(),
1244            api_key: None,
1245            plan: "pro".to_string(),
1246        }
1247    }
1248}
1249
1250/// OrcaRouter (`api.orcarouter.ai/v1/dashboard/billing/*`, one-api
1251/// compatible). Opt-in like DeepSeek/Kilo: needs an explicit API key.
1252#[derive(Debug, Clone, Deserialize, Serialize)]
1253#[serde(default)]
1254pub struct OrcaRouterConfig {
1255    pub enabled: bool,
1256    /// Extra accounts beyond the default key (#221's array, generalized).
1257    /// Each account gets a separate aggregate-view entry and cache directory.
1258    pub accounts: Vec<ApiKeyAccount>,
1259    /// Whether aggregate views include the default (unnamed) key when named
1260    /// accounts exist. Ignored when `accounts` is empty so OrcaRouter never
1261    /// loses its only tab.
1262    pub show_default_account: bool,
1263    pub api_key_env: String,
1264    pub api_key: Option<String>,
1265}
1266
1267impl Default for OrcaRouterConfig {
1268    fn default() -> Self {
1269        Self {
1270            enabled: false,
1271            accounts: Vec::new(),
1272            show_default_account: true,
1273            api_key_env: "ORCAROUTER_API_KEY".to_string(),
1274            api_key: None,
1275        }
1276    }
1277}
1278
1279/// Alibaba Cloud Model Studio (Token Plan) — a local-login vendor, like
1280/// Grok Bot: the credential is the official `bl` CLI's own console-login file
1281/// (`~/.bailian/config.json`, read-only; AK/SK refresh is out of scope).
1282/// No API key exists, so there is no `api_key_env`. The `BAILIAN_CONFIG_DIR`
1283/// environment variable overrides the directory at runtime; `config_dir`
1284/// here overrides it in config, and wins.
1285#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1286#[serde(default)]
1287pub struct ModelStudioConfig {
1288    /// Opt-in (defaults to `false`), like every vendor riding a local CLI's
1289    /// session.
1290    pub enabled: bool,
1291    /// Override for the `bl` CLI's config directory (default `~/.bailian`),
1292    /// mirroring `[grokbot] secrets_path`.
1293    pub config_dir: Option<PathBuf>,
1294}
1295
1296/// Muse Code subscription quota from the CLI's existing file-based login.
1297#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1298#[serde(default)]
1299pub struct MuseConfig {
1300    pub enabled: bool,
1301    pub credentials_path: Option<PathBuf>,
1302}
1303
1304/// Devin CLI quota — reuses its existing credentials file read-only. The
1305/// provider is opt-in and stores only a path override in ai-usagebar config.
1306#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1307#[serde(default)]
1308pub struct DevinConfig {
1309    pub enabled: bool,
1310    /// Override the CLI credential path; the default is the CLI's documented
1311    /// `%APPDATA%\devin\credentials.toml` on Windows and
1312    /// `${XDG_DATA_HOME:-~/.local/share}/devin/credentials.toml` elsewhere.
1313    pub credentials_path: Option<PathBuf>,
1314}
1315
1316impl Default for OpenCodeGoConfig {
1317    fn default() -> Self {
1318        Self {
1319            enabled: false,
1320            api_key_env: "OPENCODE_GO_API_KEY".to_string(),
1321            api_key: None,
1322            auth_paths: None,
1323        }
1324    }
1325}
1326
1327#[derive(Debug, Clone, Deserialize, Serialize)]
1328#[serde(default)]
1329pub struct ZaiConfig {
1330    pub enabled: bool,
1331    /// Extra accounts beyond the default key (#221's array, generalized).
1332    /// Each account gets a separate aggregate-view entry and cache directory.
1333    pub accounts: Vec<ApiKeyAccount>,
1334    /// Whether aggregate views include the default (unnamed) key when named
1335    /// accounts exist. Ignored when `accounts` is empty so Z.AI never
1336    /// loses its only tab.
1337    pub show_default_account: bool,
1338    /// Env var name to read the key from (env wins over `api_key`).
1339    pub api_key_env: String,
1340    /// Inline key (fallback when the env var is unset). Chmod 600 your
1341    /// config file if you put a real key here.
1342    pub api_key: Option<String>,
1343    /// Optional plan tier label (lite/pro/max) — display-only.
1344    pub plan_tier: Option<String>,
1345}
1346
1347impl Default for ZaiConfig {
1348    fn default() -> Self {
1349        Self {
1350            enabled: true,
1351            accounts: Vec::new(),
1352            show_default_account: true,
1353            api_key_env: "ZAI_API_KEY".to_string(),
1354            api_key: None,
1355            plan_tier: None,
1356        }
1357    }
1358}
1359
1360#[derive(Debug, Clone, Deserialize, Serialize)]
1361#[serde(default)]
1362pub struct OpenRouterConfig {
1363    pub enabled: bool,
1364    /// Extra OpenRouter accounts beyond the default key. Each account gets a
1365    /// separate aggregate-view entry and cache directory.
1366    pub accounts: Vec<ApiKeyAccount>,
1367    /// Whether aggregate views include the default (unnamed) key when named
1368    /// accounts exist. Ignored when `accounts` is empty so OpenRouter never
1369    /// loses its only tab.
1370    pub show_default_account: bool,
1371    pub api_key_env: String,
1372    pub api_key: Option<String>,
1373    /// Env var name for the optional OpenRouter *management* key. Only the
1374    /// `GET /api/v1/activity` call (recent models) uses it; when it resolves
1375    /// to nothing, that request is skipped instead of fired at a 401. The
1376    /// regular inference key is never sent to `/activity`.
1377    pub management_api_key_env: String,
1378    /// Which number goes on the bar. OpenRouter states its own denominator —
1379    /// credits purchased — so it is a quota vendor and defaults to `percent`.
1380    /// See [`DisplayPrefs`].
1381    ///
1382    /// There is deliberately **no** `display_limit` here. A setting that is
1383    /// accepted and then always ignored is a footgun, and the one case where it
1384    /// would not be ignored — a free-tier account whose `total_credits` is 0 —
1385    /// is the case where honouring it would be wrong: the percentage on the bar
1386    /// comes from `OpenRouterSnapshot::consumed_pct`, which is 0 without
1387    /// credits, so a tank would name the headline `percent` and then show 0%
1388    /// for an account with money in it.
1389    pub headline: Headline,
1390}
1391
1392impl Default for OpenRouterConfig {
1393    fn default() -> Self {
1394        Self {
1395            enabled: true,
1396            accounts: Vec::new(),
1397            show_default_account: true,
1398            api_key_env: "OPENROUTER_API_KEY".to_string(),
1399            api_key: None,
1400            management_api_key_env: "OPENROUTER_MANAGEMENT_API_KEY".to_string(),
1401            headline: Headline::Percent,
1402        }
1403    }
1404}
1405
1406/// One named API-key account — the shape every `[[<vendor>.accounts]]` array
1407/// shares. OpenRouter shipped it first (#221); the other API-key vendors
1408/// follow the same array. The default account continues to use the singular
1409/// `api_key_env` / `api_key` fields under the vendor's own section.
1410#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
1411pub struct ApiKeyAccount {
1412    /// Stable CLI/report label and account-scoped cache subdirectory.
1413    pub label: String,
1414    /// Optional environment variable containing this account's key.
1415    #[serde(default)]
1416    pub api_key_env: Option<String>,
1417    /// Inline fallback when the account environment variable is unset.
1418    #[serde(default)]
1419    pub api_key: Option<String>,
1420    /// Optional environment variable containing this account's OpenRouter
1421    /// management key (unlocks the recent-models activity). Only OpenRouter
1422    /// consults it.
1423    #[serde(default)]
1424    pub management_api_key_env: Option<String>,
1425}
1426
1427/// The `[[<slug>.accounts]]` lookup behind every API-key vendor: find a named
1428/// account or fail loudly instead of falling back to the default key (which
1429/// would show the wrong account's usage).
1430fn api_key_account<'a>(
1431    slug: &str,
1432    accounts: &'a [ApiKeyAccount],
1433    label: &str,
1434) -> Result<&'a ApiKeyAccount> {
1435    validate_account_label_for(slug, label)?;
1436    accounts
1437        .iter()
1438        .find(|account| account.label == label)
1439        .ok_or_else(|| {
1440            let known: Vec<&str> = accounts
1441                .iter()
1442                .map(|account| account.label.as_str())
1443                .collect();
1444            AppError::Credentials(format!(
1445                "{slug} account {label:?} not found in [[{slug}.accounts]]; \
1446                 known labels: {known:?}"
1447            ))
1448        })
1449}
1450
1451#[derive(Debug, Clone, Deserialize, Serialize)]
1452#[serde(default)]
1453pub struct DeepseekConfig {
1454    pub enabled: bool,
1455    /// Extra accounts beyond the default key (#221's array, generalized).
1456    /// Each account gets a separate aggregate-view entry and cache directory.
1457    pub accounts: Vec<ApiKeyAccount>,
1458    /// Whether aggregate views include the default (unnamed) key when named
1459    /// accounts exist. Ignored when `accounts` is empty so DeepSeek never
1460    /// loses its only tab.
1461    pub show_default_account: bool,
1462    pub api_key_env: String,
1463    pub api_key: Option<String>,
1464    /// Tank size in the currency `/user/balance` reports, so the remaining
1465    /// balance can be drawn as a meter. See [`DisplayPrefs`].
1466    pub display_limit: Option<f64>,
1467    /// Which number goes on the bar. See [`DisplayPrefs`].
1468    pub headline: Headline,
1469}
1470
1471impl Default for DeepseekConfig {
1472    fn default() -> Self {
1473        Self {
1474            enabled: false,
1475            accounts: Vec::new(),
1476            show_default_account: true,
1477            api_key_env: "DEEPSEEK_API_KEY".to_string(),
1478            api_key: None,
1479            display_limit: None,
1480            headline: Headline::Amount,
1481        }
1482    }
1483}
1484
1485#[derive(Debug, Clone, Deserialize, Serialize)]
1486#[serde(default)]
1487pub struct DeepInfraConfig {
1488    pub enabled: bool,
1489    pub accounts: Vec<ApiKeyAccount>,
1490    pub show_default_account: bool,
1491    pub api_key_env: String,
1492    pub api_key: Option<String>,
1493    /// Optional prepaid tank size in USD for rendering the balance as a meter.
1494    pub display_limit: Option<f64>,
1495    pub headline: Headline,
1496}
1497
1498impl Default for DeepInfraConfig {
1499    fn default() -> Self {
1500        Self {
1501            enabled: false,
1502            accounts: Vec::new(),
1503            show_default_account: true,
1504            api_key_env: "DEEPINFRA_API_KEY".to_string(),
1505            api_key: None,
1506            display_limit: None,
1507            headline: Headline::Amount,
1508        }
1509    }
1510}
1511
1512#[derive(Debug, Clone, Deserialize, Serialize)]
1513#[serde(default)]
1514pub struct KimiConfig {
1515    pub enabled: bool,
1516    pub api_key_env: String,
1517    /// Optional: with no key set, the vendor falls back to the Kimi Code CLI's
1518    /// own OAuth login, which is what a subscriber already has locally.
1519    pub api_key: Option<String>,
1520    /// Override for kimi-code's credential file (default
1521    /// `~/.kimi-code/credentials/kimi-code.json`), mirroring `[cursor] db_path`
1522    /// and `[kiro] db_path`. Useful with a relocated `KIMI_CODE_HOME`.
1523    pub credentials_path: Option<PathBuf>,
1524    /// `"auto"` follows kimi-code's own install marker (`~/.kimi-code/region`);
1525    /// `"cn"` pins `api.kimi.com` / `auth.kimi.com`, `"global"` pins
1526    /// `api.kimi.ai` / `auth.kimi.ai`. A token minted by one deployment means
1527    /// nothing to the other, so this picks the instance, not a currency.
1528    pub region: String,
1529}
1530
1531impl Default for KimiConfig {
1532    fn default() -> Self {
1533        Self {
1534            enabled: false,
1535            api_key_env: "KIMI_API_KEY".to_string(),
1536            api_key: None,
1537            credentials_path: None,
1538            region: "auto".to_string(),
1539        }
1540    }
1541}
1542
1543#[derive(Debug, Clone, Deserialize, Serialize)]
1544#[serde(default)]
1545pub struct KiloConfig {
1546    pub enabled: bool,
1547    /// Extra accounts beyond the default key (#221's array, generalized).
1548    /// Each account gets a separate aggregate-view entry and cache directory.
1549    pub accounts: Vec<ApiKeyAccount>,
1550    /// Whether aggregate views include the default (unnamed) key when named
1551    /// accounts exist. Ignored when `accounts` is empty so Kilo never
1552    /// loses its only tab.
1553    pub show_default_account: bool,
1554    pub api_key_env: String,
1555    pub api_key: Option<String>,
1556    /// Optional Kilo organization id — scopes the balance to a team via the
1557    /// `x-kilocode-organizationid` header. Omit for the personal balance.
1558    pub organization_id: Option<String>,
1559    /// Tank size in USD, so the remaining balance can be drawn as a meter.
1560    /// See [`DisplayPrefs`].
1561    pub display_limit: Option<f64>,
1562    /// Which number goes on the bar. See [`DisplayPrefs`].
1563    pub headline: Headline,
1564}
1565
1566impl Default for KiloConfig {
1567    fn default() -> Self {
1568        // Opt-in like DeepSeek: requires an explicit API key, so it defaults to
1569        // disabled and never affects existing installs.
1570        Self {
1571            enabled: false,
1572            accounts: Vec::new(),
1573            show_default_account: true,
1574            api_key_env: "KILO_API_KEY".to_string(),
1575            api_key: None,
1576            organization_id: None,
1577            display_limit: None,
1578            headline: Headline::Amount,
1579        }
1580    }
1581}
1582
1583#[derive(Debug, Clone, Deserialize, Serialize)]
1584#[serde(default)]
1585pub struct NovitaConfig {
1586    pub enabled: bool,
1587    /// Extra accounts beyond the default key (#221's array, generalized).
1588    /// Each account gets a separate aggregate-view entry and cache directory.
1589    pub accounts: Vec<ApiKeyAccount>,
1590    /// Whether aggregate views include the default (unnamed) key when named
1591    /// accounts exist. Ignored when `accounts` is empty so Novita never
1592    /// loses its only tab.
1593    pub show_default_account: bool,
1594    pub api_key_env: String,
1595    pub api_key: Option<String>,
1596    /// Tank size in USD, so the available balance can be drawn as a meter.
1597    /// Novita's `credit_limit` is a credit line, not a spend cap, so it is not
1598    /// a denominator. See [`DisplayPrefs`].
1599    pub display_limit: Option<f64>,
1600    /// Which number goes on the bar. See [`DisplayPrefs`].
1601    pub headline: Headline,
1602}
1603
1604impl Default for NovitaConfig {
1605    fn default() -> Self {
1606        // Opt-in like DeepSeek/Kilo/Novita: needs an explicit API key.
1607        Self {
1608            enabled: false,
1609            accounts: Vec::new(),
1610            show_default_account: true,
1611            api_key_env: "NOVITA_API_KEY".to_string(),
1612            api_key: None,
1613            display_limit: None,
1614            headline: Headline::Amount,
1615        }
1616    }
1617}
1618
1619#[derive(Debug, Clone, Deserialize, Serialize)]
1620#[serde(default)]
1621pub struct SyntheticConfig {
1622    pub enabled: bool,
1623    pub api_key_env: String,
1624    pub api_key: Option<String>,
1625}
1626
1627impl Default for SyntheticConfig {
1628    fn default() -> Self {
1629        Self {
1630            enabled: false,
1631            api_key_env: "SYNTHETIC_API_KEY".into(),
1632            api_key: None,
1633        }
1634    }
1635}
1636
1637#[derive(Debug, Clone, Deserialize, Serialize)]
1638#[serde(default)]
1639pub struct LyceumConfig {
1640    pub enabled: bool,
1641    pub accounts: Vec<ApiKeyAccount>,
1642    pub show_default_account: bool,
1643    pub api_key_env: String,
1644    pub api_key: Option<String>,
1645}
1646impl Default for LyceumConfig {
1647    fn default() -> Self {
1648        Self {
1649            enabled: false,
1650            accounts: Vec::new(),
1651            show_default_account: true,
1652            api_key_env: "LYCEUM_API_KEY".into(),
1653            api_key: None,
1654        }
1655    }
1656}
1657
1658#[derive(Debug, Clone, Deserialize, Serialize)]
1659#[serde(default)]
1660pub struct MinimaxConfig {
1661    pub enabled: bool,
1662    /// Extra accounts beyond the default key (#221's array, generalized).
1663    /// Each account gets a separate aggregate-view entry and cache directory.
1664    pub accounts: Vec<ApiKeyAccount>,
1665    /// Whether aggregate views include the default (unnamed) key when named
1666    /// accounts exist. Ignored when `accounts` is empty so MiniMax never
1667    /// loses its only tab.
1668    pub show_default_account: bool,
1669    pub api_key_env: String,
1670    pub api_key: Option<String>,
1671    /// `"global"` → api.minimax.io; `"cn"` → api.minimaxi.com. Unlike
1672    /// Moonshot's, this does not change the unit — MiniMax reports quota as a
1673    /// percentage either way. It picks the *instance*: a key issued for one
1674    /// host is rejected by the other (`status_code 2049`), so pointing this at
1675    /// the wrong region reads as an invalid key rather than an empty plan.
1676    pub region: String,
1677}
1678
1679impl Default for MinimaxConfig {
1680    fn default() -> Self {
1681        // Opt-in like the other API-key vendors: needs an explicit key.
1682        Self {
1683            enabled: false,
1684            accounts: Vec::new(),
1685            show_default_account: true,
1686            api_key_env: "MINIMAX_API_KEY".to_string(),
1687            api_key: None,
1688            region: "global".to_string(),
1689        }
1690    }
1691}
1692
1693#[derive(Debug, Clone, Deserialize, Serialize)]
1694#[serde(default)]
1695pub struct MoonshotConfig {
1696    pub enabled: bool,
1697    /// Extra accounts beyond the default key (#221's array, generalized).
1698    /// Each account gets a separate aggregate-view entry and cache directory.
1699    pub accounts: Vec<ApiKeyAccount>,
1700    /// Whether aggregate views include the default (unnamed) key when named
1701    /// accounts exist. Ignored when `accounts` is empty so Moonshot never
1702    /// loses its only tab.
1703    pub show_default_account: bool,
1704    pub api_key_env: String,
1705    pub api_key: Option<String>,
1706    /// `"global"` → api.moonshot.ai (USD); `"cn"` → api.moonshot.cn (CNY).
1707    pub region: String,
1708    /// Tank size in the currency the chosen region reports — USD for `global`,
1709    /// CNY for `cn`. See [`DisplayPrefs`].
1710    pub display_limit: Option<f64>,
1711    /// Which number goes on the bar. See [`DisplayPrefs`].
1712    pub headline: Headline,
1713}
1714
1715impl Default for MoonshotConfig {
1716    fn default() -> Self {
1717        // Opt-in like DeepSeek/Kilo/Novita: needs an explicit API key.
1718        Self {
1719            enabled: false,
1720            accounts: Vec::new(),
1721            show_default_account: true,
1722            api_key_env: "MOONSHOT_API_KEY".to_string(),
1723            api_key: None,
1724            region: "global".to_string(),
1725            display_limit: None,
1726            headline: Headline::Amount,
1727        }
1728    }
1729}
1730
1731#[derive(Debug, Clone, Deserialize, Serialize)]
1732#[serde(default)]
1733pub struct GrokConfig {
1734    pub enabled: bool,
1735    /// Extra accounts beyond the default key (#221's array, generalized).
1736    /// Each account gets a separate aggregate-view entry and cache directory.
1737    pub accounts: Vec<ApiKeyAccount>,
1738    /// Whether aggregate views include the default (unnamed) key when named
1739    /// accounts exist. Ignored when `accounts` is empty so Grok never
1740    /// loses its only tab.
1741    pub show_default_account: bool,
1742    /// Env var for the xAI **Management** key (distinct from the inference key).
1743    pub api_key_env: String,
1744    pub api_key: Option<String>,
1745    /// Optional team id. When absent, it's auto-resolved from the management
1746    /// key via `/auth/management-keys/validation`.
1747    pub team_id: Option<String>,
1748    /// Tank size in USD for the prepaid credit balance. See [`DisplayPrefs`].
1749    pub display_limit: Option<f64>,
1750    /// Which number goes on the bar. See [`DisplayPrefs`].
1751    pub headline: Headline,
1752}
1753
1754impl Default for GrokConfig {
1755    fn default() -> Self {
1756        // Opt-in: needs a management key (and, for prepaid, a team).
1757        Self {
1758            enabled: false,
1759            accounts: Vec::new(),
1760            show_default_account: true,
1761            api_key_env: "XAI_MANAGEMENT_KEY".to_string(),
1762            api_key: None,
1763            team_id: None,
1764            display_limit: None,
1765            headline: Headline::Amount,
1766        }
1767    }
1768}
1769
1770/// SuperGrok subscription auth — no API key of its own. Billing and banked
1771/// resets use the `key` already in Grok Build's `auth.json` (read-only).
1772/// Login, issuer, proxy, and token rotation stay inside Grok Build.
1773///
1774/// Opt-in like Cursor/Kiro (`enabled` defaults to `false`): it requires a
1775/// separate official executable and signed-in session, so it stays off until
1776/// the user explicitly turns it on.
1777#[derive(Debug, Clone, Deserialize, Serialize)]
1778#[serde(default)]
1779pub struct SuperGrokConfig {
1780    pub enabled: bool,
1781    /// Trusted official Grok Build executable. Defaults to its canonical
1782    /// `$GROK_HOME/bin/grok` (or `~/.grok/bin/grok`) installation path instead
1783    /// of searching PATH, where unrelated programs can share the name.
1784    pub grok_binary: PathBuf,
1785    /// Opaque auth/config files used only to fingerprint the active cache
1786    /// scope. Their contents are never parsed or copied to the cache.
1787    pub auth_path: Option<PathBuf>,
1788    pub config_path: Option<PathBuf>,
1789}
1790
1791impl Default for SuperGrokConfig {
1792    fn default() -> Self {
1793        Self {
1794            enabled: false,
1795            grok_binary: default_grok_binary(),
1796            auth_path: None,
1797            config_path: None,
1798        }
1799    }
1800}
1801
1802/// Grok Bot — the desktop app's weekly included-usage pool, from its own
1803/// Connect-RPC dashboard call. Distinct from `[grok]` (Management API prepaid
1804/// dollars) and `[supergrok]` (Grok Build subscription). No API key: the
1805/// credential is the app's own session in `sand-secrets.json` (read-only).
1806/// Linux and macOS; Windows fails closed at fetch time.
1807#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1808#[serde(default)]
1809pub struct GrokbotConfig {
1810    /// Opt-in (defaults to `false`), like every vendor riding a local app's
1811    /// session.
1812    pub enabled: bool,
1813    /// Override for the app's credential file (default
1814    /// `~/.config/Grok Bot/sand-secrets.json` on Linux,
1815    /// `~/Library/Application Support/Grok Bot/sand-secrets.json` on macOS),
1816    /// mirroring `[cursor] db_path` and `[kimi] credentials_path`.
1817    pub secrets_path: Option<PathBuf>,
1818}
1819
1820fn default_grok_binary() -> PathBuf {
1821    let executable = if cfg!(windows) { "grok.exe" } else { "grok" };
1822    let grok_home = std::env::var_os("GROK_HOME")
1823        .filter(|value| !value.is_empty())
1824        .map(PathBuf::from)
1825        .or_else(|| crate::cache::home_dir().ok().map(|home| home.join(".grok")));
1826    grok_home
1827        .map(|home| home.join("bin").join(executable))
1828        .unwrap_or_else(|| PathBuf::from(executable))
1829}
1830
1831/// Antigravity reads its quota from a usable local Antigravity product. When no
1832/// product is up — or `agy` requires the CSRF token it does not publish — it
1833/// falls back to the Google session Antigravity saved in the OS keyring and
1834/// talks to Cloud Code directly. Renewing that session needs Antigravity's
1835/// OAuth client id and secret, which are not shipped in source: set them here
1836/// (they are public installed-app credentials) or the fallback only lasts as
1837/// long as the saved access token does.
1838#[derive(Debug, Clone, Deserialize, Serialize)]
1839#[serde(default)]
1840pub struct AntigravityConfig {
1841    pub enabled: bool,
1842    /// OAuth client id used to refresh the keyring session.
1843    pub oauth_client_id: Option<String>,
1844    /// OAuth client secret paired with `oauth_client_id`. An
1845    /// installed-app secret is not confidential by Google's definition, but
1846    /// it is still treated as an inline credential for file-permission purposes.
1847    pub oauth_client_secret: Option<String>,
1848    /// Probe the Antigravity IDE's own language server as a quota source
1849    /// (default true). Set false when the IDE is installed but its sign-in is
1850    /// managed separately: a signed-out IDE language server answers 401/403,
1851    /// which outranks and masks a working `agy` session (#405).
1852    pub ide_language_server: bool,
1853}
1854
1855impl Default for AntigravityConfig {
1856    fn default() -> Self {
1857        Self {
1858            enabled: false,
1859            oauth_client_id: None,
1860            oauth_client_secret: None,
1861            ide_language_server: true,
1862        }
1863    }
1864}
1865
1866/// Cursor reads its quota through a session token the Cursor IDE already
1867/// wrote to its local `state.vscdb` — no API key, but (unlike Antigravity)
1868/// there is a real on-disk path that can need overriding (e.g. a portable or
1869/// non-default Cursor install), mirroring `openai.codex_auth_path`.
1870///
1871/// Opt-in like DeepSeek/Kilo/etc (`enabled` defaults to `false`, matching
1872/// `bool::default()`): reads an undocumented endpoint via a session token
1873/// scraped from a local IDE file, so it stays off until the user explicitly
1874/// turns it on.
1875#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1876#[serde(default)]
1877pub struct CursorConfig {
1878    pub enabled: bool,
1879    /// Override Cursor's local state database path (defaults to the
1880    /// platform-standard `.../User/globalStorage/state.vscdb` — see
1881    /// `cursor::db::default_db_path`).
1882    pub db_path: Option<PathBuf>,
1883    /// Override the headless `cursor-agent` CLI's own login file (defaults to
1884    /// `.../cursor/auth.json` — see `cursor::db::default_agent_auth_path`).
1885    /// Used as a fallback when `db_path` doesn't exist, so a text-only
1886    /// machine that never runs the desktop IDE still gets usage.
1887    pub agent_auth_path: Option<PathBuf>,
1888}
1889
1890/// Kiro CLI reads its quota through the AWS SSO OIDC session kiro-cli already
1891/// wrote to its own local `data.sqlite3` — no API key, but (like Cursor) a
1892/// real on-disk path that can need overriding.
1893///
1894/// Opt-in like Cursor/DeepSeek/Kilo/etc (`enabled` defaults to `false`):
1895/// calls a reverse-engineered CodeWhisperer endpoint via a session token
1896/// scraped from a local CLI database, so it stays off until the user
1897/// explicitly turns it on.
1898#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1899#[serde(default)]
1900pub struct KiroConfig {
1901    pub enabled: bool,
1902    /// Override kiro-cli's local database path (defaults to the
1903    /// platform-standard `.../kiro-cli/data.sqlite3` — see
1904    /// `kiro::db::default_db_path`).
1905    pub db_path: Option<PathBuf>,
1906}
1907
1908#[derive(Debug, Clone, Deserialize, Serialize)]
1909#[serde(default)]
1910pub struct AnthropicApiConfig {
1911    pub enabled: bool,
1912    /// Env var for the Console **Admin key** (`sk-ant-admin01-…`), distinct from
1913    /// an inference key and from the Claude Code OAuth login.
1914    pub api_key_env: String,
1915    pub api_key: Option<String>,
1916    /// Monthly USD spend limit, used only for the spend-vs-limit % display. The
1917    /// API exposes neither this limit nor the remaining prepaid balance.
1918    pub monthly_limit: Option<f64>,
1919}
1920
1921impl Default for AnthropicApiConfig {
1922    fn default() -> Self {
1923        // Opt-in: needs an explicit Admin key.
1924        Self {
1925            enabled: false,
1926            api_key_env: "ANTHROPIC_ADMIN_KEY".to_string(),
1927            api_key: None,
1928            monthly_limit: None,
1929        }
1930    }
1931}
1932
1933/// A user-defined HTTP provider: one GET with a static token, projected onto
1934/// the shared report shape through RFC 6901 JSON Pointers.
1935///
1936/// Everything a built-in vendor hard-codes is a field here, which is why this
1937/// type validates so much more than the others: a typo in `[deepseek]` hits a
1938/// fixed endpoint and fails loudly, while a typo here quietly sends the user's
1939/// key to the wrong host. The `id` doubles as the cache directory name and the
1940/// `--vendor` selector, so it is held to the character class of the built-in
1941/// slugs.
1942#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
1943#[serde(default, remote = "Self")]
1944pub struct CustomProviderConfig {
1945    /// `[a-z0-9][a-z0-9_-]{0,31}`; unique, and never a built-in vendor's slug.
1946    pub id: String,
1947    /// Display name, 1 to 48 characters. Defaults to `id`.
1948    pub name: String,
1949    /// Exactly three lowercase ASCII letters, unique across built-in vendors
1950    /// and other custom providers — it is the `{vendor_short}` bar tag.
1951    pub short_name: String,
1952    /// A built-in vendor slug whose mark supporting frontends may use.
1953    /// `None` preserves the custom provider's `short_name` tag.
1954    pub brand: Option<String>,
1955    pub enabled: bool,
1956    /// `https://` unless `allow_http`; never carries `user:pass@`.
1957    pub url: String,
1958    pub allow_http: bool,
1959    /// Env var read first; `""` means the inline `api_key` is the only source.
1960    pub api_key_env: String,
1961    pub api_key: Option<String>,
1962    /// The header that carries the key.
1963    pub auth_header: String,
1964    /// Sent as `"<scheme> <key>"`; `""` sends the bare key.
1965    pub auth_scheme: String,
1966    /// Extra non-secret headers.
1967    pub headers: BTreeMap<String, String>,
1968    /// Literal plan label.
1969    pub plan: Option<String>,
1970    /// Pointer to the plan label in the response; wins over `plan`.
1971    pub plan_path: Option<String>,
1972    /// Must be within `10..=3600`.
1973    pub cache_ttl_secs: u64,
1974    pub metrics: Vec<CustomMetricSpec>,
1975    pub texts: Vec<CustomTextSpec>,
1976}
1977
1978impl Default for CustomProviderConfig {
1979    fn default() -> Self {
1980        Self {
1981            id: String::new(),
1982            name: String::new(),
1983            short_name: String::new(),
1984            brand: None,
1985            enabled: false,
1986            url: String::new(),
1987            allow_http: false,
1988            api_key_env: String::new(),
1989            api_key: None,
1990            auth_header: "Authorization".to_string(),
1991            auth_scheme: "Bearer".to_string(),
1992            headers: BTreeMap::new(),
1993            plan: None,
1994            plan_path: None,
1995            cache_ttl_secs: 60,
1996            metrics: Vec::new(),
1997            texts: Vec::new(),
1998        }
1999    }
2000}
2001
2002/// `name` defaults to `id`, which a per-field serde default cannot express (a
2003/// default sees no sibling field). The derive is routed through
2004/// `remote = "Self"` so the fill-in happens here, on every parse path, rather
2005/// than only in `Config::load_from`.
2006impl<'de> Deserialize<'de> for CustomProviderConfig {
2007    fn deserialize<D: serde::Deserializer<'de>>(
2008        deserializer: D,
2009    ) -> std::result::Result<Self, D::Error> {
2010        let mut this = Self::deserialize(deserializer)?;
2011        if this.name.is_empty() {
2012            this.name = this.id.clone();
2013        }
2014        Ok(this)
2015    }
2016}
2017
2018impl Serialize for CustomProviderConfig {
2019    fn serialize<S: serde::Serializer>(
2020        &self,
2021        serializer: S,
2022    ) -> std::result::Result<S::Ok, S::Error> {
2023        Self::serialize(self, serializer)
2024    }
2025}
2026
2027/// One percentage row. Either `percent` alone, or `used` and `limit`
2028/// together — never a mix, so a row cannot show a percentage from one field
2029/// and a footnote from another.
2030#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
2031#[serde(default)]
2032pub struct CustomMetricSpec {
2033    pub label: String,
2034    pub used: Option<String>,
2035    pub limit: Option<String>,
2036    pub percent: Option<String>,
2037    /// Pointer to an RFC 3339 string or a Unix epoch (seconds or milliseconds).
2038    pub resets_at: Option<String>,
2039    /// Window length for pacing, at least 60.
2040    pub window_secs: Option<u64>,
2041}
2042
2043/// One free-text row: a string, number, or boolean at `value`.
2044#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
2045#[serde(default)]
2046pub struct CustomTextSpec {
2047    pub label: String,
2048    pub value: String,
2049}
2050
2051impl CustomProviderConfig {
2052    /// The TOML locator for error messages: `[[custom]] id = "mytool"`.
2053    pub fn section_label(&self) -> String {
2054        format!("[[custom]] id = {:?}", self.id)
2055    }
2056
2057    /// Env var (when `api_key_env` is set) → inline `api_key` → a
2058    /// `Credentials` error that names the section and never the key.
2059    pub fn resolve_api_key(&self) -> Result<String> {
2060        if let Some(key) = optional_api_key(&self.api_key_env, self.api_key.as_deref()) {
2061            return Ok(key);
2062        }
2063        let advice = if self.api_key_env.is_empty() {
2064            "set `api_key`, or name an environment variable in `api_key_env`".to_string()
2065        } else {
2066            format!("export {} or set `api_key`", self.api_key_env)
2067        };
2068        Err(AppError::Credentials(format!(
2069            "custom {}: no API key. Either {advice} under {} in {}.",
2070            self.id,
2071            self.section_label(),
2072            config_path_hint()
2073        )))
2074    }
2075
2076    pub fn cache_ttl(&self) -> std::time::Duration {
2077        std::time::Duration::from_secs(self.cache_ttl_secs)
2078    }
2079
2080    /// Every rule that serde cannot express, each naming the section. Runs
2081    /// for disabled entries too: a broken entry is a broken config, and the
2082    /// day it is enabled is the wrong day to find out.
2083    fn validate(&self, index: usize) -> Result<()> {
2084        if !is_valid_custom_id(&self.id) {
2085            return Err(AppError::Other(format!(
2086                "[[custom]] entry #{}: id {:?} must match [a-z0-9][a-z0-9_-]{{0,31}}",
2087                index + 1,
2088                self.id
2089            )));
2090        }
2091        let section = self.section_label();
2092        let bad = |msg: String| AppError::Other(format!("{section}: {msg}"));
2093
2094        if VendorId::all().iter().any(|v| v.slug() == self.id) {
2095            return Err(bad(format!("id {:?} is a built-in vendor", self.id)));
2096        }
2097        let name_len = self.name.chars().count();
2098        if name_len == 0 || name_len > 48 || self.name.chars().any(char::is_control) {
2099            return Err(bad(
2100                "name must be 1 to 48 characters without control characters".into(),
2101            ));
2102        }
2103        if self.short_name.len() != 3 || !self.short_name.bytes().all(|b| b.is_ascii_lowercase()) {
2104            return Err(bad(format!(
2105                "short_name {:?} must be exactly 3 lowercase ASCII letters",
2106                self.short_name
2107            )));
2108        }
2109        if let Some(brand) = &self.brand
2110            && !VendorId::all().iter().any(|v| v.slug() == brand)
2111        {
2112            return Err(bad(format!(
2113                "brand {brand:?} must name a built-in vendor (it borrows that \
2114                 vendor's mark); leave it unset to keep the short_name tag"
2115            )));
2116        }
2117        let url = reqwest::Url::parse(&self.url)
2118            .map_err(|_| bad(format!("url {:?} is not a valid URL", self.url)))?;
2119        match url.scheme() {
2120            "https" => {}
2121            "http" if self.allow_http => {}
2122            "http" => {
2123                return Err(bad(
2124                    "url must use https:// (set allow_http = true to permit http://)".into(),
2125                ));
2126            }
2127            other => return Err(bad(format!("url scheme {other:?} is not http or https"))),
2128        }
2129        if !url.username().is_empty() || url.password().is_some() {
2130            return Err(bad("url must not carry credentials (user:pass@)".into()));
2131        }
2132        if url.host_str().is_none() {
2133            return Err(bad("url has no host".into()));
2134        }
2135        if !self.api_key_env.is_empty() && !is_valid_env_var_name(&self.api_key_env) {
2136            // The value is not repeated: one that is not a variable name is
2137            // most likely a key pasted into the wrong field, and a config
2138            // error reaches every frontend.
2139            return Err(bad(
2140                "api_key_env is not a valid environment variable name".into()
2141            ));
2142        }
2143        validate_header_name(&section, "auth_header", &self.auth_header)?;
2144        if reqwest::header::HeaderValue::from_str(&format!("{} k", self.auth_scheme)).is_err() {
2145            return Err(bad(
2146                "auth_scheme contains characters that are not valid in an HTTP header".into(),
2147            ));
2148        }
2149        for (name, value) in &self.headers {
2150            validate_header_name(&section, "headers", name)?;
2151            if name.eq_ignore_ascii_case(&self.auth_header) {
2152                return Err(bad(format!(
2153                    "headers must not repeat auth_header {:?}",
2154                    self.auth_header
2155                )));
2156            }
2157            if reqwest::header::HeaderValue::from_str(value).is_err() {
2158                return Err(bad(format!(
2159                    "header {name:?} has a value that is not valid in an HTTP header"
2160                )));
2161            }
2162        }
2163        if let Some(plan) = &self.plan {
2164            validate_custom_label(&section, "plan", plan)?;
2165        }
2166        if let Some(pointer) = &self.plan_path {
2167            validate_pointer(&section, "plan_path", pointer)?;
2168        }
2169        if !(10..=3600).contains(&self.cache_ttl_secs) {
2170            return Err(bad(format!(
2171                "cache_ttl_secs must be between 10 and 3600, got {}",
2172                self.cache_ttl_secs
2173            )));
2174        }
2175        if self.metrics.is_empty() && self.texts.is_empty() {
2176            return Err(bad(
2177                "needs at least one [[custom.metrics]] or [[custom.texts]] entry".into(),
2178            ));
2179        }
2180        let mut metric_labels = HashSet::new();
2181        for metric in &self.metrics {
2182            validate_custom_label(&section, "metric label", &metric.label)?;
2183            if !metric_labels.insert(metric.label.as_str()) {
2184                return Err(bad(format!("duplicate metric label {:?}", metric.label)));
2185            }
2186            let pair = (metric.used.is_some(), metric.limit.is_some());
2187            let well_formed = if metric.percent.is_some() {
2188                pair == (false, false)
2189            } else {
2190                pair == (true, true)
2191            };
2192            if !well_formed {
2193                return Err(bad(format!(
2194                    "metric {:?} must set `percent`, or both `used` and `limit` (not a mix)",
2195                    metric.label
2196                )));
2197            }
2198            for (field, pointer) in [
2199                ("used", &metric.used),
2200                ("limit", &metric.limit),
2201                ("percent", &metric.percent),
2202                ("resets_at", &metric.resets_at),
2203            ] {
2204                if let Some(pointer) = pointer {
2205                    validate_pointer(&section, field, pointer)?;
2206                }
2207            }
2208            if let Some(secs) = metric.window_secs
2209                && secs < 60
2210            {
2211                return Err(bad(format!(
2212                    "metric {:?} window_secs must be at least 60, got {secs}",
2213                    metric.label
2214                )));
2215            }
2216        }
2217        let mut text_labels = HashSet::new();
2218        for text in &self.texts {
2219            validate_custom_label(&section, "text label", &text.label)?;
2220            if !text_labels.insert(text.label.as_str()) {
2221                return Err(bad(format!("duplicate text label {:?}", text.label)));
2222            }
2223            validate_pointer(&section, "value", &text.value)?;
2224        }
2225        Ok(())
2226    }
2227}
2228
2229fn is_valid_custom_id(id: &str) -> bool {
2230    let bytes = id.as_bytes();
2231    let Some(&first) = bytes.first() else {
2232        return false;
2233    };
2234    bytes.len() <= 32
2235        && (first.is_ascii_lowercase() || first.is_ascii_digit())
2236        && bytes
2237            .iter()
2238            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'))
2239}
2240
2241fn validate_pointer(section: &str, field: &str, pointer: &str) -> Result<()> {
2242    if !pointer.starts_with('/') || pointer.chars().any(char::is_control) {
2243        return Err(AppError::Other(format!(
2244            "{section}: {field} {pointer:?} must be an RFC 6901 JSON Pointer starting with '/'"
2245        )));
2246    }
2247    Ok(())
2248}
2249
2250fn validate_custom_label(section: &str, field: &str, label: &str) -> Result<()> {
2251    let len = label.chars().count();
2252    if len == 0 || len > 64 || label.chars().any(char::is_control) {
2253        return Err(AppError::Other(format!(
2254            "{section}: {field} {label:?} must be 1 to 64 characters without control characters"
2255        )));
2256    }
2257    Ok(())
2258}
2259
2260fn validate_header_name(section: &str, field: &str, name: &str) -> Result<()> {
2261    if name.is_empty() || reqwest::header::HeaderName::from_bytes(name.as_bytes()).is_err() {
2262        return Err(AppError::Other(format!(
2263            "{section}: {field} {name:?} is not a valid HTTP header name"
2264        )));
2265    }
2266    Ok(())
2267}
2268
2269/// Resolve an API key for a vendor: a valid env-var name wins, then inline
2270/// config, then a clear error naming both fields. Used by every API-key vendor.
2271pub fn resolve_api_key(
2272    vendor_label: &str,
2273    env_var_name: &str,
2274    inline: Option<&str>,
2275) -> crate::error::Result<String> {
2276    let section = match vendor_label {
2277        "OpenCode Go" => "[opencode-go]".to_string(),
2278        _ => format!("[{}]", vendor_label.to_lowercase()),
2279    };
2280    resolve_api_key_in_section(vendor_label, &section, env_var_name, inline)
2281}
2282
2283/// The env-then-inline lookup without the "or fail" ending, for vendors where
2284/// an absent API key is a legitimate state rather than an error — Kimi accepts
2285/// a Kimi Code CLI subscription login instead.
2286pub fn optional_api_key(env_var_name: &str, inline: Option<&str>) -> Option<String> {
2287    optional_api_key_with(env_var_name, inline, |name| std::env::var(name).ok())
2288}
2289
2290fn optional_api_key_with(
2291    env_var_name: &str,
2292    inline: Option<&str>,
2293    environment: impl FnOnce(&str) -> Option<String>,
2294) -> Option<String> {
2295    if is_valid_env_var_name(env_var_name)
2296        && let Some(v) = environment(env_var_name)
2297        && !v.is_empty()
2298    {
2299        return Some(v);
2300    }
2301    inline.filter(|v| !v.is_empty()).map(str::to_string)
2302}
2303
2304fn resolve_api_key_in_section(
2305    vendor_label: &str,
2306    section: &str,
2307    env_var_name: &str,
2308    inline: Option<&str>,
2309) -> crate::error::Result<String> {
2310    if let Some(key) = optional_api_key(env_var_name, inline) {
2311        return Ok(key);
2312    }
2313    let valid_env_name = is_valid_env_var_name(env_var_name);
2314    let advice = if valid_env_name {
2315        "set an API key in a valid environment variable or set `api_key`"
2316    } else {
2317        "fix the invalid `api_key_env` with a valid environment variable name or set `api_key`"
2318    };
2319    Err(crate::error::AppError::Credentials(format!(
2320        "{vendor_label}: no API key. Either {advice} under {section} in {}.",
2321        config_path_hint()
2322    )))
2323}
2324
2325pub(crate) fn is_valid_env_var_name(name: &str) -> bool {
2326    let mut chars = name.chars();
2327    let Some(first) = chars.next() else {
2328        return false;
2329    };
2330    (first.is_ascii_alphabetic() || first == '_')
2331        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
2332}
2333
2334impl Config {
2335    /// Load from `~/.config/ai-usagebar/config.toml`. Returns defaults if the
2336    /// file doesn't exist; errors only on actual parse failures.
2337    pub fn load() -> Result<Self> {
2338        let Some(path) = resolved_path() else {
2339            return Ok(Self::default());
2340        };
2341        Self::load_from(&path)
2342    }
2343
2344    pub fn load_from(path: &std::path::Path) -> Result<Self> {
2345        match std::fs::read_to_string(path) {
2346            Ok(s) => {
2347                let mut config: Self = toml::from_str(&s).map_err(|mut e| {
2348                    let span = e.span();
2349                    // Without its input the error's `Display` drops the quoted
2350                    // line but keeps the key path, `in deepseek.headline`.
2351                    e.set_input(None);
2352                    let summary = toml_error_summary(&s, span, &e.to_string());
2353                    AppError::Other(format!("config.toml: {summary}"))
2354                })?;
2355                // `~` is shell syntax, not path syntax: `PathBuf` keeps it
2356                // literally, so a documented `credentials_path = "~/..."`
2357                // silently pointed at a directory named `~`.
2358                config.expand_paths();
2359                config.validate()?;
2360                #[cfg(unix)]
2361                config.protect_inline_secrets(path)?;
2362                // A custom provider's token variable is as secret as any
2363                // built-in one; subprocesses (`gh`, `grok`, `claude`) must
2364                // not inherit it. Nor a named account's, or a renamed one.
2365                crate::vendor::register_secret_env_vars(&config.custom_secret_env_vars());
2366                crate::vendor::register_secret_env_vars(&config.provider_secret_env_vars());
2367                Ok(config)
2368            }
2369            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
2370            Err(e) => Err(AppError::io_at(path, e)),
2371        }
2372    }
2373
2374    fn expand_paths(&mut self) {
2375        expand_tilde_opt(&mut self.context.projects_path);
2376        expand_tilde_opt(&mut self.anthropic.credentials_path);
2377        expand_tilde_opt(&mut self.anthropic.accounts_dir);
2378        expand_tilde_opt(&mut self.anthropic.desktop_profiles_dir);
2379        expand_tilde_opt(&mut self.anthropic.desktop_prepare_binary);
2380        expand_tilde_opt(&mut self.openai.codex_auth_path);
2381        expand_tilde_opt(&mut self.cursor.db_path);
2382        expand_tilde_opt(&mut self.cursor.agent_auth_path);
2383        expand_tilde_opt(&mut self.kiro.db_path);
2384        expand_tilde_opt(&mut self.kimi.credentials_path);
2385        expand_tilde_opt(&mut self.grokbot.secrets_path);
2386        expand_tilde_opt(&mut self.modelstudio.config_dir);
2387        expand_tilde_opt(&mut self.devin.credentials_path);
2388        expand_tilde_opt(&mut self.muse.credentials_path);
2389        self.supergrok.grok_binary = expand_tilde(&self.supergrok.grok_binary);
2390        expand_tilde_opt(&mut self.supergrok.auth_path);
2391        expand_tilde_opt(&mut self.supergrok.config_path);
2392        expand_tilde_opt(&mut self.copilot.gh_binary);
2393        if let Some(paths) = &mut self.cline.auth_paths {
2394            for path in paths {
2395                *path = expand_tilde(path);
2396            }
2397        }
2398        for account in &mut self.anthropic.accounts {
2399            account.credentials_path = expand_tilde(&account.credentials_path);
2400        }
2401        for account in &mut self.openai.accounts {
2402            account.codex_auth_path = expand_tilde(&account.codex_auth_path);
2403        }
2404        if let Some(paths) = &mut self.commandcode.auth_paths {
2405            for path in paths {
2406                *path = expand_tilde(path);
2407            }
2408        }
2409    }
2410
2411    /// Explicitly enumerate every inline credential field. Adding a new
2412    /// credential vendor must add it here so its config receives the same
2413    /// protection.
2414    #[cfg(unix)]
2415    fn has_inline_secrets(&self) -> bool {
2416        [
2417            self.zai.api_key.as_deref(),
2418            self.openrouter.api_key.as_deref(),
2419            self.deepseek.api_key.as_deref(),
2420            self.deepinfra.api_key.as_deref(),
2421            self.kimi.api_key.as_deref(),
2422            self.kilo.api_key.as_deref(),
2423            self.novita.api_key.as_deref(),
2424            self.synthetic.api_key.as_deref(),
2425            self.minimax.api_key.as_deref(),
2426            self.moonshot.api_key.as_deref(),
2427            self.grok.api_key.as_deref(),
2428            self.anthropic_api.api_key.as_deref(),
2429            self.opencode_go.api_key.as_deref(),
2430            self.ollama.api_key.as_deref(),
2431            self.orcarouter.api_key.as_deref(),
2432            self.lyceum.api_key.as_deref(),
2433            self.antigravity.oauth_client_secret.as_deref(),
2434            self.cline.api_key.as_deref(),
2435        ]
2436        .into_iter()
2437        .chain(
2438            Self::API_KEY_ACCOUNT_VENDORS
2439                .into_iter()
2440                .flat_map(|id| self.api_key_accounts(id).unwrap_or(&[]))
2441                .map(|account| account.api_key.as_deref()),
2442        )
2443        .chain(self.custom.iter().map(|c| c.api_key.as_deref()))
2444        .any(|key| key.is_some_and(|key| !key.is_empty()))
2445    }
2446
2447    fn custom_secret_env_vars(&self) -> Vec<String> {
2448        self.custom
2449            .iter()
2450            .filter(|c| !c.api_key_env.is_empty())
2451            .map(|c| c.api_key_env.clone())
2452            .collect()
2453    }
2454
2455    /// The variables built-in providers read keys from under names that
2456    /// `VENDOR_SECRET_ENV_VARS` cannot list: a renamed `api_key_env` or
2457    /// OpenRouter `management_api_key_env`, and each named account's
2458    /// (`DEEPSEEK_WORK_API_KEY`). Default names come back too and are skipped
2459    /// by the registration, as are empty ones.
2460    fn provider_secret_env_vars(&self) -> Vec<String> {
2461        let renamed = VendorId::all().iter().map(|&id| self.api_key_env_for(id));
2462        let management = std::iter::once(self.openrouter.management_api_key_env.as_str());
2463        let accounts = Self::API_KEY_ACCOUNT_VENDORS
2464            .into_iter()
2465            .flat_map(|id| self.api_key_accounts(id).unwrap_or(&[]))
2466            .flat_map(|account| [&account.api_key_env, &account.management_api_key_env])
2467            .filter_map(|name| name.as_deref());
2468        renamed
2469            .chain(management)
2470            .chain(accounts)
2471            .map(str::to_string)
2472            .collect()
2473    }
2474
2475    /// The `[[custom]]` providers that are switched on, in config order.
2476    pub fn enabled_custom(&self) -> impl Iterator<Item = &CustomProviderConfig> {
2477        self.custom.iter().filter(|c| c.enabled)
2478    }
2479
2480    /// A `[[custom]]` provider by `id`, enabled or not.
2481    pub fn custom_by_id(&self, id: &str) -> Option<&CustomProviderConfig> {
2482        self.custom.iter().find(|c| c.id == id)
2483    }
2484
2485    #[cfg(unix)]
2486    fn protect_inline_secrets(&self, path: &Path) -> Result<()> {
2487        if !self.has_inline_secrets() {
2488            return Ok(());
2489        }
2490
2491        let metadata = std::fs::metadata(path).map_err(|_| {
2492            AppError::Credentials(format!(
2493                "config at {} contains inline credentials but its permissions could not be checked; fix permissions or move credentials to environment variables",
2494                path.display()
2495            ))
2496        })?;
2497        if inline_key_permission_decision(metadata.mode()) == InlineKeyPermissionDecision::Tighten {
2498            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|_| {
2499                AppError::Credentials(format!(
2500                    "config at {} contains inline credentials but is group/other-readable and could not be tightened to 0600; fix permissions or move credentials to environment variables",
2501                    path.display()
2502                ))
2503            })?;
2504        }
2505        Ok(())
2506    }
2507
2508    pub fn is_enabled(&self, id: VendorId) -> bool {
2509        match id {
2510            VendorId::Anthropic => self.anthropic.enabled,
2511            VendorId::AnthropicApi => self.anthropic_api.enabled,
2512            VendorId::Openai => self.openai.enabled,
2513            VendorId::Copilot => self.copilot.enabled,
2514            VendorId::Zai => self.zai.enabled,
2515            VendorId::Openrouter => self.openrouter.enabled,
2516            VendorId::Deepseek => self.deepseek.enabled,
2517            VendorId::Deepinfra => self.deepinfra.enabled,
2518            VendorId::Kimi => self.kimi.enabled,
2519            VendorId::Kilo => self.kilo.enabled,
2520            VendorId::Novita => self.novita.enabled,
2521            VendorId::Synthetic => self.synthetic.enabled,
2522            VendorId::Moonshot => self.moonshot.enabled,
2523            VendorId::Grok => self.grok.enabled,
2524            VendorId::Supergrok => self.supergrok.enabled,
2525            VendorId::Grokbot => self.grokbot.enabled,
2526            VendorId::Antigravity => self.antigravity.enabled,
2527            VendorId::Cursor => self.cursor.enabled,
2528            VendorId::Minimax => self.minimax.enabled,
2529            VendorId::Kiro => self.kiro.enabled,
2530            VendorId::NousResearch => self.nous.enabled,
2531            VendorId::Cline => self.cline.enabled,
2532            VendorId::OpenCodeGo => self.opencode_go.enabled,
2533            VendorId::CommandCode => self.commandcode.enabled,
2534            VendorId::Ollama => self.ollama.enabled,
2535            VendorId::OrcaRouter => self.orcarouter.enabled,
2536            VendorId::ModelStudio => self.modelstudio.enabled,
2537            VendorId::Lyceum => self.lyceum.enabled,
2538            VendorId::Devin => self.devin.enabled,
2539            VendorId::MuseCode => self.muse.enabled,
2540        }
2541    }
2542
2543    /// The environment variable this provider's API key is read from, honoring
2544    /// a per-vendor `api_key_env` override; `""` for a provider that takes no
2545    /// key. Matching on [`VendorId`] rather than on a section name is
2546    /// deliberate: a new key vendor that nobody adds here fails to compile,
2547    /// where a `_ =>` arm over `&str` sections would silently hand back the
2548    /// wrong default and report the provider as unconfigured for ever.
2549    pub fn api_key_env_for(&self, id: VendorId) -> &str {
2550        match id {
2551            VendorId::AnthropicApi => &self.anthropic_api.api_key_env,
2552            VendorId::Zai => &self.zai.api_key_env,
2553            VendorId::Openrouter => &self.openrouter.api_key_env,
2554            VendorId::Deepseek => &self.deepseek.api_key_env,
2555            VendorId::Deepinfra => &self.deepinfra.api_key_env,
2556            VendorId::Kimi => &self.kimi.api_key_env,
2557            VendorId::Kilo => &self.kilo.api_key_env,
2558            VendorId::Novita => &self.novita.api_key_env,
2559            VendorId::Synthetic => &self.synthetic.api_key_env,
2560            VendorId::Moonshot => &self.moonshot.api_key_env,
2561            VendorId::Grok => &self.grok.api_key_env,
2562            VendorId::Minimax => &self.minimax.api_key_env,
2563            VendorId::OpenCodeGo => &self.opencode_go.api_key_env,
2564            VendorId::Ollama => &self.ollama.api_key_env,
2565            VendorId::OrcaRouter => &self.orcarouter.api_key_env,
2566            VendorId::Lyceum => &self.lyceum.api_key_env,
2567            VendorId::Cline => &self.cline.api_key_env,
2568            // Fixed names: OAuth-first providers whose environment override is
2569            // not user-renameable, and the providers with no key at all.
2570            VendorId::Anthropic
2571            | VendorId::Openai
2572            | VendorId::Copilot
2573            | VendorId::Supergrok
2574            | VendorId::Grokbot
2575            | VendorId::Antigravity
2576            | VendorId::Cursor
2577            | VendorId::Kiro
2578            | VendorId::NousResearch
2579            | VendorId::CommandCode
2580            | VendorId::ModelStudio
2581            | VendorId::Devin
2582            | VendorId::MuseCode => id.api_key_env(),
2583        }
2584    }
2585
2586    /// A non-empty inline `api_key` from this provider's config section. An
2587    /// empty string counts as unset, the same way the vendors' own
2588    /// `resolve_api_key` treats it.
2589    pub fn inline_api_key(&self, id: VendorId) -> Option<&str> {
2590        let raw = match id {
2591            VendorId::AnthropicApi => self.anthropic_api.api_key.as_deref(),
2592            VendorId::Zai => self.zai.api_key.as_deref(),
2593            VendorId::Openrouter => self.openrouter.api_key.as_deref(),
2594            VendorId::Deepseek => self.deepseek.api_key.as_deref(),
2595            VendorId::Deepinfra => self.deepinfra.api_key.as_deref(),
2596            VendorId::Kimi => self.kimi.api_key.as_deref(),
2597            VendorId::Kilo => self.kilo.api_key.as_deref(),
2598            VendorId::Novita => self.novita.api_key.as_deref(),
2599            VendorId::Synthetic => self.synthetic.api_key.as_deref(),
2600            VendorId::Moonshot => self.moonshot.api_key.as_deref(),
2601            VendorId::Grok => self.grok.api_key.as_deref(),
2602            VendorId::Minimax => self.minimax.api_key.as_deref(),
2603            VendorId::OpenCodeGo => self.opencode_go.api_key.as_deref(),
2604            VendorId::Ollama => self.ollama.api_key.as_deref(),
2605            VendorId::OrcaRouter => self.orcarouter.api_key.as_deref(),
2606            VendorId::Lyceum => self.lyceum.api_key.as_deref(),
2607            VendorId::Cline => self.cline.api_key.as_deref(),
2608            VendorId::Anthropic
2609            | VendorId::Openai
2610            | VendorId::Copilot
2611            | VendorId::Supergrok
2612            | VendorId::Grokbot
2613            | VendorId::Antigravity
2614            | VendorId::Cursor
2615            | VendorId::Kiro
2616            | VendorId::NousResearch
2617            | VendorId::CommandCode
2618            | VendorId::ModelStudio
2619            | VendorId::Devin
2620            | VendorId::MuseCode => None,
2621        };
2622        raw.filter(|key| !key.is_empty())
2623    }
2624
2625    /// The API-key vendors that take a `[[<vendor>.accounts]]` array —
2626    /// OpenRouter's (#221), generalized. Kimi is left out on purpose: its
2627    /// fallback is the Kimi Code CLI's single OAuth login, not a key.
2628    pub const API_KEY_ACCOUNT_VENDORS: [VendorId; 11] = [
2629        VendorId::Zai,
2630        VendorId::Openrouter,
2631        VendorId::Deepseek,
2632        VendorId::Deepinfra,
2633        VendorId::Kilo,
2634        VendorId::Novita,
2635        VendorId::Moonshot,
2636        VendorId::Grok,
2637        VendorId::Minimax,
2638        VendorId::OrcaRouter,
2639        VendorId::Lyceum,
2640    ];
2641
2642    /// The named `[[<vendor>.accounts]]` array, or `None` for a vendor that
2643    /// has no such array (see [`Self::API_KEY_ACCOUNT_VENDORS`]).
2644    pub fn api_key_accounts(&self, id: VendorId) -> Option<&[ApiKeyAccount]> {
2645        match id {
2646            VendorId::Zai => Some(&self.zai.accounts),
2647            VendorId::Openrouter => Some(&self.openrouter.accounts),
2648            VendorId::Deepseek => Some(&self.deepseek.accounts),
2649            VendorId::Deepinfra => Some(&self.deepinfra.accounts),
2650            VendorId::Kilo => Some(&self.kilo.accounts),
2651            VendorId::Novita => Some(&self.novita.accounts),
2652            VendorId::Moonshot => Some(&self.moonshot.accounts),
2653            VendorId::Grok => Some(&self.grok.accounts),
2654            VendorId::Minimax => Some(&self.minimax.accounts),
2655            VendorId::OrcaRouter => Some(&self.orcarouter.accounts),
2656            VendorId::Lyceum => Some(&self.lyceum.accounts),
2657            _ => None,
2658        }
2659    }
2660
2661    /// Whether the default key keeps its tab next to the named accounts.
2662    /// `true` for every vendor without an accounts array.
2663    pub fn show_default_api_key_account(&self, id: VendorId) -> bool {
2664        match id {
2665            VendorId::Zai => self.zai.show_default_account,
2666            VendorId::Openrouter => self.openrouter.show_default_account,
2667            VendorId::Deepseek => self.deepseek.show_default_account,
2668            VendorId::Deepinfra => self.deepinfra.show_default_account,
2669            VendorId::Kilo => self.kilo.show_default_account,
2670            VendorId::Novita => self.novita.show_default_account,
2671            VendorId::Moonshot => self.moonshot.show_default_account,
2672            VendorId::Grok => self.grok.show_default_account,
2673            VendorId::Minimax => self.minimax.show_default_account,
2674            VendorId::OrcaRouter => self.orcarouter.show_default_account,
2675            VendorId::Lyceum => self.lyceum.show_default_account,
2676            _ => true,
2677        }
2678    }
2679
2680    /// The default key, or one named `[[<vendor>.accounts]]` key, for a vendor
2681    /// in [`Self::API_KEY_ACCOUNT_VENDORS`]. The default path is exactly the
2682    /// single-key resolution each vendor always had, error text included. A
2683    /// label for a vendor without the array fails loudly rather than falling
2684    /// back to the default key, which would show the wrong account's usage.
2685    pub fn resolve_account_api_key_for(&self, id: VendorId, label: Option<&str>) -> Result<String> {
2686        // The missing-key error predates `display_name()`; Z.AI's always said
2687        // "Zai", and its section is derived from this spelling.
2688        let name = match id {
2689            VendorId::Zai => "Zai",
2690            other => other.display_name(),
2691        };
2692        let Some(label) = label else {
2693            return resolve_api_key(name, self.api_key_env_for(id), self.inline_api_key(id));
2694        };
2695        let slug = id.config_section();
2696        let account = api_key_account(slug, self.api_key_accounts(id).unwrap_or(&[]), label)?;
2697        // Names the account and its array section; never a configured value.
2698        resolve_api_key_in_section(
2699            &format!("{name} account {label:?}"),
2700            &format!("[[{slug}.accounts]]"),
2701            account.api_key_env.as_deref().unwrap_or(""),
2702            account.api_key.as_deref(),
2703        )
2704    }
2705
2706    /// The optional OpenRouter *management* key for the default or a named
2707    /// account. `None` means none is configured, in which case the caller
2708    /// skips the `/api/v1/activity` request rather than firing a doomed 401 —
2709    /// the regular inference key is never sent there. A named account only
2710    /// resolves a management key when it names its own
2711    /// `management_api_key_env`; it never inherits the default account's.
2712    pub fn openrouter_management_key(&self, label: Option<&str>) -> Option<String> {
2713        let env_name = match label {
2714            Some(label) => api_key_account("openrouter", &self.openrouter.accounts, label)
2715                .ok()?
2716                .management_api_key_env
2717                .as_deref()?,
2718            None => self.openrouter.management_api_key_env.as_str(),
2719        };
2720        optional_api_key(env_name, None)
2721    }
2722
2723    /// Bar-number settings for one vendor.
2724    ///
2725    /// Only the prepaid-balance vendors declare these; everything else keeps
2726    /// the quota shape ([`DisplayPrefs::default`]) and is unaffected.
2727    pub fn display_prefs(&self, vendor: VendorId) -> DisplayPrefs {
2728        match vendor {
2729            VendorId::Deepseek => {
2730                DisplayPrefs::balance(self.deepseek.display_limit, self.deepseek.headline)
2731            }
2732            VendorId::Deepinfra => {
2733                DisplayPrefs::balance(self.deepinfra.display_limit, self.deepinfra.headline)
2734            }
2735            VendorId::Kilo => DisplayPrefs::balance(self.kilo.display_limit, self.kilo.headline),
2736            VendorId::Novita => {
2737                DisplayPrefs::balance(self.novita.display_limit, self.novita.headline)
2738            }
2739            VendorId::Moonshot => {
2740                DisplayPrefs::balance(self.moonshot.display_limit, self.moonshot.headline)
2741            }
2742            VendorId::Grok => DisplayPrefs::balance(self.grok.display_limit, self.grok.headline),
2743            // No tank: OpenRouter reports its own credits. See
2744            // [`OpenRouterConfig::headline`].
2745            VendorId::Openrouter => DisplayPrefs::balance(None, self.openrouter.headline),
2746            // No user tank: the percentage's own denominator is the plan's
2747            // monthly allocation, so only the headline choice applies.
2748            VendorId::NousResearch => DisplayPrefs::balance(None, self.nous.headline),
2749            _ => DisplayPrefs::default(),
2750        }
2751    }
2752
2753    pub fn enabled_vendors(&self) -> Vec<VendorId> {
2754        VendorId::all()
2755            .iter()
2756            .copied()
2757            .filter(|id| self.is_enabled(*id))
2758            .collect()
2759    }
2760
2761    /// Validate cross-entry constraints that serde cannot express. Account
2762    /// labels are both CLI selectors and TUI tab identities, so duplicates
2763    /// would make either destination ambiguous.
2764    pub fn validate(&self) -> Result<()> {
2765        if let Some(minutes) = self.tray.refresh_minutes
2766            && !TRAY_REFRESH_MINUTES.contains(&minutes)
2767        {
2768            return Err(AppError::Other(format!(
2769                "[tray] refresh_minutes must be one of 1, 5, 10, 15, 30 or 60, got {minutes}"
2770            )));
2771        }
2772        if !(1..=100).contains(&self.notifications.threshold) {
2773            return Err(AppError::Other(format!(
2774                "[notifications] threshold must be between 1 and 100, got {}",
2775                self.notifications.threshold
2776            )));
2777        }
2778        if self.context.context_window_tokens == Some(0) {
2779            return Err(AppError::Other(
2780                "[context] context_window_tokens must be greater than zero".into(),
2781            ));
2782        }
2783        for (model, tokens) in &self.context.model_context_window_tokens {
2784            if model.trim().is_empty() {
2785                return Err(AppError::Other(
2786                    "[context] model_context_window_tokens keys must not be empty".into(),
2787                ));
2788            }
2789            if *tokens == 0 {
2790                return Err(AppError::Other(format!(
2791                    "[context] model_context_window_tokens entry {model:?} must be greater than zero"
2792                )));
2793            }
2794        }
2795        if let Some(limit) = self.anthropic_api.monthly_limit
2796            && (!limit.is_finite() || limit <= 0.0)
2797        {
2798            return Err(AppError::Other(
2799                "[anthropic_api] monthly_limit must be finite and greater than zero; \
2800                 remove it to show spend without a limit"
2801                    .into(),
2802            ));
2803        }
2804        // Same rule as `monthly_limit` above: a tank size that cannot divide is
2805        // a typo, and silently ignoring it would draw a meter the user never
2806        // asked for — or none, with no diagnostic either way.
2807        for (section, limit) in [
2808            ("deepseek", self.deepseek.display_limit),
2809            ("deepinfra", self.deepinfra.display_limit),
2810            ("kilo", self.kilo.display_limit),
2811            ("novita", self.novita.display_limit),
2812            ("moonshot", self.moonshot.display_limit),
2813            ("grok", self.grok.display_limit),
2814        ] {
2815            if let Some(limit) = limit
2816                && (!limit.is_finite() || limit <= 0.0)
2817            {
2818                return Err(AppError::Other(format!(
2819                    "[{section}] display_limit must be finite and greater than zero; \
2820                     remove it to show the balance without a limit"
2821                )));
2822            }
2823        }
2824        if crate::kimi::oauth::Region::parse(&self.kimi.region).is_none()
2825            && !self.kimi.region.eq_ignore_ascii_case("auto")
2826        {
2827            return Err(AppError::Other(format!(
2828                "[kimi] region must be \"auto\", \"cn\", or \"global\", got {:?}",
2829                self.kimi.region
2830            )));
2831        }
2832        if !self.minimax.region.eq_ignore_ascii_case("global")
2833            && !self.minimax.region.eq_ignore_ascii_case("cn")
2834        {
2835            return Err(AppError::Other(format!(
2836                "[minimax] region must be \"global\" or \"cn\", got {:?}",
2837                self.minimax.region
2838            )));
2839        }
2840        if self.supergrok.grok_binary.as_os_str().is_empty() {
2841            return Err(AppError::Other(
2842                "[supergrok] grok_binary must not be empty".into(),
2843            ));
2844        }
2845        let mut labels = HashSet::new();
2846        for account in &self.anthropic.accounts {
2847            validate_account_label(&account.label)?;
2848            if !labels.insert(&account.label) {
2849                return Err(AppError::Credentials(format!(
2850                    "duplicate anthropic account label {:?}",
2851                    account.label
2852                )));
2853            }
2854        }
2855        let mut openai_labels = HashSet::new();
2856        for account in &self.openai.accounts {
2857            validate_account_label_for("openai", &account.label)?;
2858            if !openai_labels.insert(&account.label) {
2859                return Err(AppError::Credentials(format!(
2860                    "duplicate openai account label {:?}",
2861                    account.label
2862                )));
2863            }
2864        }
2865        // Every `[[<vendor>.accounts]]` array follows OpenRouter's rules: labels
2866        // become cache subdirectories, stay unique as CLI selectors and tab
2867        // identities, and each entry names a key source.
2868        for id in Self::API_KEY_ACCOUNT_VENDORS {
2869            let slug = id.config_section();
2870            let mut labels = HashSet::new();
2871            for account in self.api_key_accounts(id).unwrap_or(&[]) {
2872                validate_account_label_for(slug, &account.label)?;
2873                if !labels.insert(&account.label) {
2874                    return Err(AppError::Credentials(format!(
2875                        "duplicate {slug} account label {:?}",
2876                        account.label
2877                    )));
2878                }
2879                let has_env = account
2880                    .api_key_env
2881                    .as_deref()
2882                    .is_some_and(|name| !name.is_empty());
2883                let has_inline = account
2884                    .api_key
2885                    .as_deref()
2886                    .is_some_and(|key| !key.is_empty());
2887                if !has_env && !has_inline {
2888                    return Err(AppError::Credentials(format!(
2889                        "{slug} account {:?} must set api_key_env or api_key",
2890                        account.label
2891                    )));
2892                }
2893            }
2894        }
2895        self.validate_custom()
2896    }
2897
2898    /// Per-entry rules live on `CustomProviderConfig`; the cross-entry ones —
2899    /// `id` and `short_name` uniqueness, including against the built-in
2900    /// vendors — need the whole list and live here.
2901    fn validate_custom(&self) -> Result<()> {
2902        let mut ids = HashSet::new();
2903        let mut short_names: HashSet<&str> =
2904            VendorId::all().iter().map(|v| v.short_name()).collect();
2905        for (index, custom) in self.custom.iter().enumerate() {
2906            custom.validate(index)?;
2907            if !ids.insert(custom.id.as_str()) {
2908                return Err(AppError::Other(format!(
2909                    "{}: duplicate id",
2910                    custom.section_label()
2911                )));
2912            }
2913            if !short_names.insert(custom.short_name.as_str()) {
2914                return Err(AppError::Other(format!(
2915                    "{}: short_name {:?} is already used by a built-in vendor or another [[custom]] entry",
2916                    custom.section_label(),
2917                    custom.short_name
2918                )));
2919            }
2920        }
2921        Ok(())
2922    }
2923}
2924
2925#[cfg(unix)]
2926#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2927enum InlineKeyPermissionDecision {
2928    Ok,
2929    Tighten,
2930}
2931
2932#[cfg(unix)]
2933fn inline_key_permission_decision(mode: u32) -> InlineKeyPermissionDecision {
2934    if mode & 0o077 == 0 {
2935        InlineKeyPermissionDecision::Ok
2936    } else {
2937        InlineKeyPermissionDecision::Tighten
2938    }
2939}
2940
2941pub fn default_path() -> Option<PathBuf> {
2942    let proj = directories::ProjectDirs::from("", "", "ai-usagebar")?;
2943    Some(proj.config_dir().join("config.toml"))
2944}
2945
2946/// The Unix-conventional location, which is what every doc, the config
2947/// example, and both desktop integrations have always pointed at. On Linux it
2948/// *is* [`default_path`]; on macOS `ProjectDirs` resolves to
2949/// `~/Library/Application Support/…` instead, so the two diverge.
2950fn legacy_xdg_path() -> Option<PathBuf> {
2951    let home = crate::cache::home_dir().ok()?;
2952    Some(home.join(".config").join("ai-usagebar").join("config.toml"))
2953}
2954
2955/// The config file actually in effect.
2956///
2957/// A `--config` override (see [`set_override_path`]) wins outright so a test
2958/// run never touches the real file. Otherwise [`default_path`] stays
2959/// canonical, but on macOS a file at the documented
2960/// `~/.config/ai-usagebar/config.toml` is honored when the canonical one does
2961/// not exist — otherwise everyone who followed the README (and both desktop
2962/// integrations, which read that path) silently got defaults. The legacy file
2963/// is never moved or rewritten: it may hold API keys, and relocating a secret
2964/// behind the user's back is not this tool's business.
2965pub fn resolved_path() -> Option<PathBuf> {
2966    if let Some(path) = override_path() {
2967        return Some(path);
2968    }
2969    let canonical = default_path();
2970    if let Some(p) = &canonical
2971        && p.exists()
2972    {
2973        return canonical;
2974    }
2975    if let Some(legacy) = legacy_xdg_path()
2976        && legacy.exists()
2977    {
2978        return Some(legacy);
2979    }
2980    canonical
2981}
2982
2983static PATH_OVERRIDE: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
2984
2985/// Point every config load, save, and hint at one explicit file — the
2986/// `--config` flag. Takes precedence over the canonical and legacy locations.
2987/// The file does not have to exist yet: loads treat it as defaults while
2988/// Settings saves create it. Process-wide, so call it once at startup before
2989/// any config is read.
2990pub fn set_override_path(path: &std::path::Path) {
2991    if let Ok(mut slot) = PATH_OVERRIDE.lock() {
2992        *slot = Some(path.to_path_buf());
2993    }
2994}
2995
2996/// Drop the override again. Used only by tests so they can restore the
2997/// process-wide state they changed.
2998#[doc(hidden)]
2999pub fn clear_override_path() {
3000    if let Ok(mut slot) = PATH_OVERRIDE.lock() {
3001        *slot = None;
3002    }
3003}
3004
3005fn override_path() -> Option<PathBuf> {
3006    PATH_OVERRIDE.lock().ok().and_then(|slot| slot.clone())
3007}
3008
3009/// Value of a `--config=PATH` argument, split at the OS-string level so a
3010/// path with bytes Windows/Unix can store but UTF-8 cannot represent (an
3011/// undecodable filename on Unix, a lone surrogate on Windows) survives
3012/// intact instead of being mangled by `to_string_lossy`. `None` when the
3013/// argument is not in that form. Used by both binaries' argv pre-parsers.
3014#[doc(hidden)]
3015pub fn config_flag_value(arg: &std::ffi::OsStr) -> Option<PathBuf> {
3016    #[cfg(unix)]
3017    {
3018        use std::os::unix::ffi::{OsStrExt, OsStringExt};
3019        let rest = arg.as_bytes().strip_prefix(b"--config=")?;
3020        Some(std::ffi::OsString::from_vec(rest.to_vec()).into())
3021    }
3022    #[cfg(windows)]
3023    {
3024        use std::os::windows::ffi::{OsStrExt, OsStringExt};
3025        const PREFIX: &[u16] = &[
3026            b'-' as u16,
3027            b'-' as u16,
3028            b'c' as u16,
3029            b'o' as u16,
3030            b'n' as u16,
3031            b'f' as u16,
3032            b'i' as u16,
3033            b'g' as u16,
3034            b'=' as u16,
3035        ];
3036        let wide: Vec<u16> = arg.encode_wide().collect();
3037        let rest = wide.strip_prefix(PREFIX)?;
3038        Some(std::ffi::OsString::from_wide(rest).into())
3039    }
3040    #[cfg(not(any(unix, windows)))]
3041    {
3042        Some(PathBuf::from(arg.to_str()?.strip_prefix("--config=")?))
3043    }
3044}
3045
3046/// Expand a leading `~` (or `~/`) against the user's home directory. Anything
3047/// else — including `~user` — is left untouched.
3048fn expand_tilde(p: &std::path::Path) -> PathBuf {
3049    let Some(s) = p.to_str() else {
3050        return p.to_path_buf();
3051    };
3052    let rest = if s == "~" {
3053        ""
3054    } else if let Some(r) = s.strip_prefix("~/") {
3055        r
3056    } else {
3057        return p.to_path_buf();
3058    };
3059    match crate::cache::home_dir() {
3060        Ok(home) if rest.is_empty() => home,
3061        Ok(home) => home.join(rest),
3062        Err(_) => p.to_path_buf(),
3063    }
3064}
3065
3066fn expand_tilde_opt(p: &mut Option<PathBuf>) {
3067    if let Some(inner) = p.as_ref() {
3068        *p = Some(expand_tilde(inner));
3069    }
3070}
3071
3072/// Resolved `config.toml` path as a string for user-facing messages. Uses the
3073/// platform's config dir (`directories::ProjectDirs`), so it reads correctly on
3074/// Linux, macOS, and Windows instead of hard-coding the Unix `~/.config` path.
3075/// Falls back to the bare filename if the path can't be resolved.
3076pub fn config_path_hint() -> String {
3077    resolved_path()
3078        .map(|p| p.display().to_string())
3079        .unwrap_or_else(|| "config.toml".to_string())
3080}
3081
3082#[cfg(test)]
3083mod tests {
3084    use super::*;
3085    use std::io::Write;
3086    use tempfile::NamedTempFile;
3087
3088    #[cfg(unix)]
3089    use std::os::unix::fs::{MetadataExt, PermissionsExt};
3090
3091    fn write_toml(s: &str) -> NamedTempFile {
3092        let mut f = NamedTempFile::new().unwrap();
3093        f.write_all(s.as_bytes()).unwrap();
3094        f.flush().unwrap();
3095        f
3096    }
3097
3098    /// The back-compat guarantee #134 asks for: a config with no
3099    /// `[[openai.accounts]]` resolves exactly what it resolved before, whether
3100    /// it sets `codex_auth_path` or leaves it to the default.
3101    #[test]
3102    fn openai_without_accounts_resolves_the_singular_path() {
3103        let explicit = OpenAiConfig {
3104            codex_auth_path: Some(PathBuf::from("/tmp/codex/auth.json")),
3105            ..OpenAiConfig::default()
3106        };
3107        assert_eq!(
3108            explicit.resolve_auth_path(None).unwrap(),
3109            PathBuf::from("/tmp/codex/auth.json")
3110        );
3111
3112        let bare = OpenAiConfig::default();
3113        assert_eq!(
3114            bare.resolve_auth_path(None).unwrap(),
3115            crate::openai::creds::default_path().unwrap(),
3116            "no codex_auth_path must still mean ~/.codex/auth.json"
3117        );
3118    }
3119
3120    /// Each named account resolves its own file, and the default login is still
3121    /// reachable alongside them.
3122    #[test]
3123    fn openai_named_accounts_resolve_their_own_auth_file() {
3124        let config: Config = toml::from_str(
3125            r#"
3126            [openai]
3127            codex_auth_path = "/tmp/personal/auth.json"
3128            [[openai.accounts]]
3129            label = "work"
3130            codex_auth_path = "/tmp/work/auth.json"
3131            "#,
3132        )
3133        .unwrap();
3134
3135        assert_eq!(
3136            config.openai.resolve_auth_path(Some("work")).unwrap(),
3137            PathBuf::from("/tmp/work/auth.json")
3138        );
3139        assert_eq!(
3140            config.openai.resolve_auth_path(None).unwrap(),
3141            PathBuf::from("/tmp/personal/auth.json")
3142        );
3143    }
3144
3145    /// An unknown label must fail rather than quietly fall back to the default
3146    /// login — reporting the wrong subscription's usage is worse than an error.
3147    #[test]
3148    fn an_unknown_openai_account_is_an_error_not_a_fallback() {
3149        let config = OpenAiConfig {
3150            codex_auth_path: Some(PathBuf::from("/tmp/personal/auth.json")),
3151            accounts: vec![OpenAiAccount {
3152                label: "work".into(),
3153                codex_auth_path: PathBuf::from("/tmp/work/auth.json"),
3154            }],
3155            ..OpenAiConfig::default()
3156        };
3157        let err = config
3158            .resolve_auth_path(Some("nope"))
3159            .unwrap_err()
3160            .to_string();
3161        assert!(err.contains("nope"), "{err}");
3162        assert!(err.contains("[[openai.accounts]]"), "{err}");
3163    }
3164
3165    fn two_codex_accounts() -> OpenAiConfig {
3166        OpenAiConfig {
3167            codex_auth_path: Some(PathBuf::from("/tmp/codex/auth.json")),
3168            accounts: vec![
3169                OpenAiAccount {
3170                    label: "main".into(),
3171                    codex_auth_path: PathBuf::from("/tmp/codex-main/auth.json"),
3172                },
3173                OpenAiAccount {
3174                    label: "work".into(),
3175                    codex_auth_path: PathBuf::from("/tmp/codex-work/auth.json"),
3176                },
3177            ],
3178            ..OpenAiConfig::default()
3179        }
3180    }
3181
3182    #[test]
3183    fn the_active_codex_account_is_read_from_the_default_slot() {
3184        let config = two_codex_accounts();
3185        assert_eq!(
3186            config
3187                .fetch_auth_path_probing("work", Some("work"), |_| false)
3188                .unwrap(),
3189            PathBuf::from("/tmp/codex/auth.json")
3190        );
3191        assert_eq!(
3192            config
3193                .fetch_auth_path_probing("main", Some("work"), |_| false)
3194                .unwrap(),
3195            PathBuf::from("/tmp/codex-main/auth.json")
3196        );
3197    }
3198
3199    #[test]
3200    fn an_active_codex_account_with_its_own_file_keeps_reading_it() {
3201        let config = two_codex_accounts();
3202        assert_eq!(
3203            config
3204                .fetch_auth_path_probing("work", Some("work"), |_| true)
3205                .unwrap(),
3206            PathBuf::from("/tmp/codex-work/auth.json")
3207        );
3208    }
3209
3210    #[test]
3211    fn adding_an_openai_account_keeps_the_rest_of_the_file() {
3212        let mut doc: toml_edit::DocumentMut = "# mine\n[zai]\nenabled = true\n".parse().unwrap();
3213        add_openai_account_to_doc(&mut doc, "work", "~/.codex-work/auth.json").unwrap();
3214        let text = doc.to_string();
3215        assert!(
3216            text.starts_with("# mine\n[zai]\nenabled = true\n"),
3217            "{text}"
3218        );
3219        let parsed: Config = toml::from_str(&text).unwrap();
3220        assert_eq!(parsed.openai.accounts[0].label, "work");
3221        assert!(add_openai_account_to_doc(&mut doc, "work", "x").is_err());
3222        assert!(add_openai_account_to_doc(&mut doc, "../x", "x").is_err());
3223    }
3224
3225    #[test]
3226    fn defaults_enable_only_the_four_core_vendors() {
3227        let c = Config::default();
3228        assert!(c.is_enabled(VendorId::Anthropic));
3229        assert!(c.is_enabled(VendorId::Openai));
3230        assert!(c.is_enabled(VendorId::Zai));
3231        assert!(c.is_enabled(VendorId::Openrouter));
3232        for opt_in in [
3233            VendorId::AnthropicApi,
3234            VendorId::Copilot,
3235            VendorId::Deepseek,
3236            VendorId::Kimi,
3237            VendorId::Kilo,
3238            VendorId::Novita,
3239            VendorId::Moonshot,
3240            VendorId::Grok,
3241            VendorId::Supergrok,
3242            VendorId::Grokbot,
3243            VendorId::Cursor,
3244            VendorId::Minimax,
3245            VendorId::Kiro,
3246            VendorId::CommandCode,
3247            VendorId::OrcaRouter,
3248            VendorId::ModelStudio,
3249            VendorId::Devin,
3250        ] {
3251            assert!(!c.is_enabled(opt_in), "{opt_in:?}");
3252        }
3253        assert_eq!(c.enabled_vendors().len(), 4);
3254    }
3255
3256    #[test]
3257    fn commandcode_is_opt_in_when_loading_existing_configs() {
3258        let absent: Config = toml::from_str("[openai]\nenabled = true\n").unwrap();
3259        assert!(!absent.is_enabled(VendorId::CommandCode));
3260
3261        let opted_in: Config = toml::from_str("[commandcode]\nenabled = true\n").unwrap();
3262        assert!(opted_in.is_enabled(VendorId::CommandCode));
3263
3264        let opted_out: Config = toml::from_str("[commandcode]\nenabled = false\n").unwrap();
3265        assert!(!opted_out.is_enabled(VendorId::CommandCode));
3266    }
3267
3268    #[test]
3269    fn new_provider_defaults_are_opt_in_and_use_exact_auth_contracts() {
3270        let config = Config::default();
3271        assert!(!config.is_enabled(VendorId::NousResearch));
3272        assert!(!config.is_enabled(VendorId::OpenCodeGo));
3273        assert_eq!(config.opencode_go.api_key_env, "OPENCODE_GO_API_KEY");
3274        assert!(config.opencode_go.api_key.is_none());
3275        assert!(!config.is_enabled(VendorId::Copilot));
3276    }
3277
3278    #[cfg(unix)]
3279    #[test]
3280    fn inline_credentials_are_protected() {
3281        let mut config = Config::default();
3282        config.opencode_go.api_key = Some("<redacted>".to_string());
3283        assert!(config.has_inline_secrets());
3284    }
3285
3286    #[test]
3287    fn antigravity_oauth_client_overrides_parse() {
3288        let config: Config = toml::from_str(
3289            "[antigravity]
3290enabled = true
3291oauth_client_id = \"test-client\"
3292oauth_client_secret = \"test-client-secret\"
3293",
3294        )
3295        .unwrap();
3296        assert!(config.antigravity.enabled);
3297        assert_eq!(
3298            config.antigravity.oauth_client_id.as_deref(),
3299            Some("test-client")
3300        );
3301        assert_eq!(
3302            config.antigravity.oauth_client_secret.as_deref(),
3303            Some("test-client-secret")
3304        );
3305        let bare: Config = toml::from_str(
3306            "[antigravity]
3307enabled = true
3308",
3309        )
3310        .unwrap();
3311        assert!(bare.antigravity.oauth_client_id.is_none());
3312        assert!(bare.antigravity.oauth_client_secret.is_none());
3313    }
3314
3315    /// #405: the IDE language-server opt-out parses, and the default keeps
3316    /// probing it so discovery is unchanged for everyone else.
3317    #[test]
3318    fn antigravity_ide_language_server_defaults_to_probing() {
3319        assert!(Config::default().antigravity.ide_language_server);
3320        let bare: Config = toml::from_str(
3321            "[antigravity]
3322enabled = true
3323",
3324        )
3325        .unwrap();
3326        assert!(bare.antigravity.ide_language_server);
3327        let opted_out: Config = toml::from_str(
3328            "[antigravity]
3329enabled = true
3330ide_language_server = false
3331",
3332        )
3333        .unwrap();
3334        assert!(!opted_out.antigravity.ide_language_server);
3335    }
3336
3337    #[cfg(unix)]
3338    #[test]
3339    fn antigravity_inline_oauth_secret_receives_config_file_protection() {
3340        let mut config = Config::default();
3341        config.antigravity.oauth_client_id = Some("test-client".into());
3342        assert!(!config.has_inline_secrets());
3343        config.antigravity.oauth_client_secret = Some("<redacted>".into());
3344        assert!(config.has_inline_secrets());
3345    }
3346
3347    #[cfg(unix)]
3348    #[test]
3349    fn openrouter_named_inline_keys_receive_config_file_protection() {
3350        let mut config = Config::default();
3351        config.openrouter.accounts.push(ApiKeyAccount {
3352            label: "work".into(),
3353            api_key_env: None,
3354            api_key: Some("<redacted>".into()),
3355            management_api_key_env: None,
3356        });
3357        assert!(config.has_inline_secrets());
3358    }
3359
3360    #[cfg(unix)]
3361    #[test]
3362    fn every_named_inline_api_key_receives_config_file_protection() {
3363        for vendor in Config::API_KEY_ACCOUNT_VENDORS {
3364            let section = vendor.config_section();
3365            let config: Config = toml::from_str(&format!(
3366                "[[{section}.accounts]]\nlabel = \"work\"\napi_key = \"<redacted>\"\n"
3367            ))
3368            .unwrap();
3369            assert!(config.has_inline_secrets(), "{vendor:?}");
3370        }
3371    }
3372
3373    /// `has_inline_secrets` lists the fields by hand, and Ollama's was missed
3374    /// once. Walk every vendor instead: whatever `inline_api_key` resolves as
3375    /// a key must also put the config file under 0600 protection.
3376    #[cfg(unix)]
3377    #[test]
3378    fn every_inline_api_key_receives_config_file_protection() {
3379        for &vendor in VendorId::all() {
3380            let section = vendor.config_section();
3381            let config: Config =
3382                toml::from_str(&format!("[{section}]\napi_key = \"<redacted>\"\n")).unwrap();
3383            if config.inline_api_key(vendor).is_some() {
3384                assert!(config.has_inline_secrets(), "{vendor:?}");
3385            }
3386        }
3387    }
3388
3389    #[test]
3390    fn missing_file_uses_defaults() {
3391        let path = std::path::Path::new("/tmp/does-not-exist-ai-usagebar-test");
3392        let c = Config::load_from(path).unwrap();
3393        assert!(c.is_enabled(VendorId::Anthropic));
3394    }
3395
3396    #[test]
3397    fn parses_full_config() {
3398        let f = write_toml(
3399            r#"
3400            [anthropic]
3401            enabled = true
3402
3403            [openai]
3404            enabled = false
3405            admin_key_env = "MY_ADMIN_KEY"
3406
3407            [zai]
3408            enabled = true
3409            api_key_env = "MY_ZAI"
3410            plan_tier = "pro"
3411
3412            [openrouter]
3413            enabled = false
3414            "#,
3415        );
3416        let c = Config::load_from(f.path()).unwrap();
3417        assert!(c.is_enabled(VendorId::Anthropic));
3418        assert!(!c.is_enabled(VendorId::Openai));
3419        assert!(c.is_enabled(VendorId::Zai));
3420        assert!(!c.is_enabled(VendorId::Openrouter));
3421        assert_eq!(c.openai.admin_key_env, "MY_ADMIN_KEY");
3422        assert_eq!(c.zai.api_key_env, "MY_ZAI");
3423        assert_eq!(c.zai.plan_tier.as_deref(), Some("pro"));
3424        assert!(c.openrouter.accounts.is_empty());
3425        assert!(c.openrouter.show_default_account);
3426    }
3427
3428    #[test]
3429    fn partial_config_falls_back_to_defaults() {
3430        let f = write_toml(
3431            r#"[openai]
3432enabled = false
3433"#,
3434        );
3435        let c = Config::load_from(f.path()).unwrap();
3436        assert!(!c.is_enabled(VendorId::Openai));
3437        // Other vendors keep their defaults.
3438        assert!(c.is_enabled(VendorId::Anthropic));
3439        assert_eq!(c.openai.admin_key_env, "OPENAI_ADMIN_KEY");
3440    }
3441
3442    #[test]
3443    fn malformed_toml_returns_error() {
3444        let f = write_toml("this is not = = valid");
3445        assert!(Config::load_from(f.path()).is_err());
3446    }
3447
3448    #[cfg(unix)]
3449    #[test]
3450    fn load_from_tightens_world_readable_config_with_inline_api_key() {
3451        let file = write_toml("[zai]\napi_key = \"test-inline-key\"\n");
3452        std::fs::set_permissions(file.path(), std::fs::Permissions::from_mode(0o644)).unwrap();
3453
3454        Config::load_from(file.path()).unwrap();
3455
3456        assert_eq!(
3457            std::fs::metadata(file.path()).unwrap().mode() & 0o777,
3458            0o600
3459        );
3460    }
3461
3462    #[cfg(unix)]
3463    #[test]
3464    fn load_from_leaves_world_readable_config_without_inline_api_keys_unchanged() {
3465        let file = write_toml("[zai]\napi_key_env = \"TEST_ZAI_API_KEY\"\n");
3466        std::fs::set_permissions(file.path(), std::fs::Permissions::from_mode(0o644)).unwrap();
3467
3468        Config::load_from(file.path()).unwrap();
3469
3470        assert_eq!(
3471            std::fs::metadata(file.path()).unwrap().mode() & 0o777,
3472            0o644
3473        );
3474    }
3475
3476    #[cfg(unix)]
3477    #[test]
3478    fn inline_key_permission_decision_requires_tightening_for_group_or_other_bits() {
3479        assert_eq!(
3480            inline_key_permission_decision(0o600),
3481            InlineKeyPermissionDecision::Ok
3482        );
3483        assert_eq!(
3484            inline_key_permission_decision(0o640),
3485            InlineKeyPermissionDecision::Tighten
3486        );
3487        assert_eq!(
3488            inline_key_permission_decision(0o604),
3489            InlineKeyPermissionDecision::Tighten
3490        );
3491    }
3492
3493    #[test]
3494    fn anthropic_api_monthly_limit_must_be_positive_and_finite() {
3495        for value in ["0", "-1", "inf", "nan"] {
3496            let file = write_toml(&format!("[anthropic_api]\nmonthly_limit = {value}\n"));
3497            let error = Config::load_from(file.path()).unwrap_err().to_string();
3498            assert!(error.contains("monthly_limit"), "value {value}: {error}");
3499        }
3500
3501        let file = write_toml("[anthropic_api]\nmonthly_limit = 1000\n");
3502        assert_eq!(
3503            Config::load_from(file.path())
3504                .unwrap()
3505                .anthropic_api
3506                .monthly_limit,
3507            Some(1000.0)
3508        );
3509    }
3510
3511    #[test]
3512    fn display_limit_must_be_positive_and_finite_on_every_balance_vendor() {
3513        // `[openrouter]` is absent on purpose: it has no `display_limit`.
3514        for section in ["deepseek", "kilo", "novita", "moonshot", "grok"] {
3515            for value in ["0", "-1", "inf", "nan"] {
3516                let file = write_toml(&format!("[{section}]\ndisplay_limit = {value}\n"));
3517                let error = Config::load_from(file.path()).unwrap_err().to_string();
3518                assert!(
3519                    error.contains(&format!("[{section}] display_limit")),
3520                    "{section} = {value}: {error}"
3521                );
3522            }
3523            let file = write_toml(&format!("[{section}]\ndisplay_limit = 200\n"));
3524            let config = Config::load_from(file.path()).unwrap();
3525            assert_eq!(
3526                config.display_prefs(vendor_of(section)).display_limit,
3527                Some(200.0),
3528                "{section}"
3529            );
3530        }
3531    }
3532
3533    /// No baked-in tank: a vendor nobody configured has no denominator.
3534    #[test]
3535    fn display_limit_is_absent_until_the_user_states_one() {
3536        let config = Config::default();
3537        for vendor in VendorId::all() {
3538            assert_eq!(
3539                config.display_prefs(*vendor).display_limit,
3540                None,
3541                "{vendor:?}"
3542            );
3543        }
3544    }
3545
3546    /// A balance vendor headlines its money; a vendor with a denominator of its
3547    /// own headlines the percentage. Everything else keeps the quota default.
3548    #[test]
3549    fn the_default_headline_follows_the_kind_of_vendor() {
3550        let config = Config::default();
3551        for vendor in [
3552            VendorId::Deepseek,
3553            VendorId::Kilo,
3554            VendorId::Novita,
3555            VendorId::Moonshot,
3556            VendorId::Grok,
3557        ] {
3558            assert_eq!(
3559                config.display_prefs(vendor).headline,
3560                Headline::Amount,
3561                "{vendor:?}"
3562            );
3563        }
3564        assert_eq!(
3565            config.display_prefs(VendorId::Openrouter).headline,
3566            Headline::Percent
3567        );
3568        assert_eq!(
3569            config.display_prefs(VendorId::Anthropic),
3570            DisplayPrefs::default()
3571        );
3572    }
3573
3574    #[test]
3575    fn the_headline_is_configurable_per_vendor_and_a_typo_is_loud() {
3576        let file = write_toml("[deepseek]\nheadline = \"percent\"\n");
3577        assert_eq!(
3578            Config::load_from(file.path())
3579                .unwrap()
3580                .display_prefs(VendorId::Deepseek)
3581                .headline,
3582            Headline::Percent
3583        );
3584
3585        let file = write_toml("[openrouter]\nheadline = \"amount\"\n");
3586        assert_eq!(
3587            Config::load_from(file.path())
3588                .unwrap()
3589                .display_prefs(VendorId::Openrouter)
3590                .headline,
3591            Headline::Amount
3592        );
3593
3594        let file = write_toml("[deepseek]\nheadline = \"dollars\"\n");
3595        let error = Config::load_from(file.path()).unwrap_err().to_string();
3596        assert!(error.contains("headline"), "{error}");
3597    }
3598
3599    /// `[openrouter]` has no tank at all. The API reports credits purchased, so
3600    /// there is nothing to fall back to — and in the one case where a tank
3601    /// would not be ignored (a free-tier account with `total_credits == 0`)
3602    /// honouring it would put "0%" on the bar for an account with money in it,
3603    /// because the percentage comes from the snapshot, not from the tank.
3604    #[test]
3605    fn openrouter_has_no_display_limit_to_be_ignored() {
3606        let file = write_toml("[openrouter]\ndisplay_limit = 200\nheadline = \"percent\"\n");
3607        let config = Config::load_from(file.path()).unwrap();
3608        let prefs = config.display_prefs(VendorId::Openrouter);
3609        assert_eq!(prefs.display_limit, None);
3610        assert_eq!(prefs.headline, Headline::Percent);
3611    }
3612
3613    /// Setting a tank does not move the money off the bar by itself; the two
3614    /// are independent choices.
3615    #[test]
3616    fn a_display_limit_alone_leaves_the_headline_where_it_was() {
3617        let file = write_toml("[deepseek]\ndisplay_limit = 200\n");
3618        let prefs = Config::load_from(file.path())
3619            .unwrap()
3620            .display_prefs(VendorId::Deepseek);
3621        assert_eq!(prefs.display_limit, Some(200.0));
3622        assert_eq!(prefs.headline, Headline::Amount);
3623    }
3624
3625    fn vendor_of(section: &str) -> VendorId {
3626        VendorId::all()
3627            .iter()
3628            .copied()
3629            .find(|vendor| vendor.config_section() == section)
3630            .unwrap_or_else(|| panic!("no vendor for [{section}]"))
3631    }
3632
3633    #[test]
3634    fn minimax_region_accepts_only_known_instances() {
3635        for region in ["global", "GLOBAL", "cn", "CN"] {
3636            let file = write_toml(&format!("[minimax]\nregion = {region:?}\n"));
3637            assert_eq!(
3638                Config::load_from(file.path()).unwrap().minimax.region,
3639                region
3640            );
3641        }
3642
3643        for region in ["", "china", "us"] {
3644            let file = write_toml(&format!("[minimax]\nregion = {region:?}\n"));
3645            let error = Config::load_from(file.path()).unwrap_err().to_string();
3646            assert!(error.contains("[minimax] region"), "{error}");
3647        }
3648    }
3649
3650    #[test]
3651    fn kimi_region_accepts_auto_and_both_deployments() {
3652        for region in ["auto", "AUTO", "cn", "mainland-cn", "global"] {
3653            let file = write_toml(&format!("[kimi]\nregion = {region:?}\n"));
3654            assert_eq!(Config::load_from(file.path()).unwrap().kimi.region, region);
3655        }
3656
3657        for region in ["", "us", "oversea"] {
3658            let file = write_toml(&format!("[kimi]\nregion = {region:?}\n"));
3659            let error = Config::load_from(file.path()).unwrap_err().to_string();
3660            assert!(error.contains("[kimi] region"), "{error}");
3661        }
3662    }
3663
3664    #[test]
3665    fn kimi_defaults_to_auto_region_and_no_credential_override() {
3666        let defaults = KimiConfig::default();
3667        assert_eq!(defaults.region, "auto");
3668        assert_eq!(defaults.credentials_path, None);
3669        assert!(!defaults.enabled);
3670    }
3671
3672    #[test]
3673    fn kimi_credentials_path_expands_a_tilde() {
3674        let file = write_toml("[kimi]\ncredentials_path = \"~/kimi/creds.json\"\n");
3675        let path = Config::load_from(file.path())
3676            .unwrap()
3677            .kimi
3678            .credentials_path
3679            .unwrap();
3680        assert!(!path.starts_with("~"), "{}", path.display());
3681        assert!(path.ends_with("kimi/creds.json"), "{}", path.display());
3682    }
3683
3684    #[test]
3685    fn grokbot_is_opt_in_and_takes_no_api_key() {
3686        let defaults = GrokbotConfig::default();
3687        assert!(!defaults.enabled);
3688        assert_eq!(defaults.secrets_path, None);
3689        // No key surface of any kind: the app's own session is the login.
3690        let config = Config::default();
3691        assert_eq!(config.api_key_env_for(VendorId::Grokbot), "");
3692        assert_eq!(config.inline_api_key(VendorId::Grokbot), None);
3693
3694        let file = write_toml("[grokbot]\nenabled = true\n");
3695        let config = Config::load_from(file.path()).unwrap();
3696        assert!(config.is_enabled(VendorId::Grokbot));
3697        assert!(config.enabled_vendors().contains(&VendorId::Grokbot));
3698    }
3699
3700    #[test]
3701    fn grokbot_secrets_path_expands_a_tilde() {
3702        let file = write_toml("[grokbot]\nsecrets_path = \"~/gb/secrets.json\"\n");
3703        let path = Config::load_from(file.path())
3704            .unwrap()
3705            .grokbot
3706            .secrets_path
3707            .unwrap();
3708        assert!(!path.starts_with("~"), "{}", path.display());
3709        assert!(path.ends_with("gb/secrets.json"), "{}", path.display());
3710    }
3711
3712    #[test]
3713    fn modelstudio_is_opt_in_and_takes_no_api_key() {
3714        let defaults = ModelStudioConfig::default();
3715        assert!(!defaults.enabled);
3716        assert_eq!(defaults.config_dir, None);
3717        // No key surface of any kind: the bl CLI's console session is the login.
3718        let config = Config::default();
3719        assert_eq!(config.api_key_env_for(VendorId::ModelStudio), "");
3720        assert_eq!(config.inline_api_key(VendorId::ModelStudio), None);
3721
3722        let file = write_toml("[modelstudio]\nenabled = true\n");
3723        let config = Config::load_from(file.path()).unwrap();
3724        assert!(config.is_enabled(VendorId::ModelStudio));
3725        assert!(config.enabled_vendors().contains(&VendorId::ModelStudio));
3726    }
3727
3728    #[test]
3729    fn modelstudio_config_dir_expands_a_tilde() {
3730        let file = write_toml("[modelstudio]\nconfig_dir = \"~/bl\"\n");
3731        let path = Config::load_from(file.path())
3732            .unwrap()
3733            .modelstudio
3734            .config_dir
3735            .unwrap();
3736        assert!(!path.starts_with("~"), "{}", path.display());
3737        assert!(path.ends_with("bl"), "{}", path.display());
3738    }
3739
3740    #[test]
3741    fn devin_is_opt_in_and_takes_no_api_key() {
3742        let defaults = DevinConfig::default();
3743        assert!(!defaults.enabled);
3744        assert_eq!(defaults.credentials_path, None);
3745
3746        let config = Config::default();
3747        assert_eq!(config.api_key_env_for(VendorId::Devin), "");
3748        assert_eq!(config.inline_api_key(VendorId::Devin), None);
3749
3750        let file = write_toml("[devin]\nenabled = true\n");
3751        let config = Config::load_from(file.path()).unwrap();
3752        assert!(config.is_enabled(VendorId::Devin));
3753        assert!(config.enabled_vendors().contains(&VendorId::Devin));
3754    }
3755
3756    #[test]
3757    fn devin_credentials_path_expands_a_tilde() {
3758        let file = write_toml("[devin]\ncredentials_path = \"~/devin/credentials.toml\"\n");
3759        let path = Config::load_from(file.path())
3760            .unwrap()
3761            .devin
3762            .credentials_path
3763            .unwrap();
3764        assert!(!path.starts_with("~"), "{}", path.display());
3765        assert!(
3766            path.ends_with("devin/credentials.toml"),
3767            "{}",
3768            path.display()
3769        );
3770    }
3771
3772    #[test]
3773    fn lyceum_is_opt_in_and_uses_shared_api_key_account_resolution() {
3774        let defaults = LyceumConfig::default();
3775        assert!(!defaults.enabled);
3776        assert_eq!(defaults.api_key_env, "LYCEUM_API_KEY");
3777        let override_file = write_toml("[lyceum]\napi_key_env = \"LYCEUM_CUSTOM_TEST_KEY\"\n");
3778        let override_config = Config::load_from(override_file.path()).unwrap();
3779        assert_eq!(
3780            override_config.api_key_env_for(VendorId::Lyceum),
3781            "LYCEUM_CUSTOM_TEST_KEY"
3782        );
3783        let file = write_toml(
3784            r#"[lyceum]
3785enabled = true
3786api_key_env = ""
3787api_key = "synthetic-inline"
3788[[lyceum.accounts]]
3789label = "work"
3790api_key = "synthetic-account"
3791"#,
3792        );
3793        let config = Config::load_from(file.path()).unwrap();
3794        assert!(config.is_enabled(VendorId::Lyceum));
3795        assert_eq!(config.api_key_env_for(VendorId::Lyceum), "");
3796        assert_eq!(
3797            config
3798                .resolve_account_api_key_for(VendorId::Lyceum, None)
3799                .unwrap(),
3800            "synthetic-inline"
3801        );
3802        assert_eq!(
3803            config
3804                .resolve_account_api_key_for(VendorId::Lyceum, Some("work"))
3805                .unwrap(),
3806            "synthetic-account"
3807        );
3808    }
3809
3810    #[test]
3811    fn optional_api_key_reports_absence_instead_of_failing() {
3812        assert_eq!(
3813            optional_api_key("9INVALID", Some("inline")),
3814            Some("inline".to_string())
3815        );
3816        assert_eq!(optional_api_key("9INVALID", None), None);
3817        assert_eq!(optional_api_key("9INVALID", Some("")), None);
3818    }
3819
3820    #[test]
3821    fn optional_api_key_prefers_env_and_falls_through_to_inline() {
3822        let from_env = |name: &str| (name == "TEST_API_KEY").then(|| "from-env".to_string());
3823        assert_eq!(
3824            optional_api_key_with("TEST_API_KEY", Some("from-config"), from_env),
3825            Some("from-env".to_string())
3826        );
3827        assert_eq!(
3828            optional_api_key_with("TEST_API_KEY", Some("from-config"), |_| None),
3829            Some("from-config".to_string())
3830        );
3831        assert_eq!(
3832            optional_api_key_with("TEST_API_KEY", Some("from-config"), |_| {
3833                Some(String::new())
3834            }),
3835            Some("from-config".to_string())
3836        );
3837        assert_eq!(optional_api_key_with("TEST_API_KEY", None, |_| None), None);
3838    }
3839
3840    #[test]
3841    fn context_monitor_is_opt_in_and_window_sizes_are_explicit() {
3842        let defaults = Config::default();
3843        assert!(!defaults.context.enabled);
3844        assert_eq!(
3845            defaults.context.window_tokens_for(Some("claude-test")),
3846            None
3847        );
3848
3849        let file = write_toml(
3850            r#"
3851            [context]
3852            enabled = true
3853            context_window_tokens = 200000
3854
3855            [context.model_context_window_tokens]
3856            claude-opus-1m = 1000000
3857            "claude exact id" = 300000
3858            "#,
3859        );
3860        let config = Config::load_from(file.path()).unwrap();
3861        assert!(config.context.enabled);
3862        assert_eq!(
3863            config.context.window_tokens_for(Some("claude-opus-1m")),
3864            Some(1_000_000)
3865        );
3866        assert_eq!(
3867            config.context.window_tokens_for(Some("claude exact id")),
3868            Some(300_000)
3869        );
3870        assert_eq!(
3871            config.context.window_tokens_for(Some("another-model")),
3872            Some(200_000)
3873        );
3874    }
3875
3876    #[test]
3877    fn context_layout_defaults_to_full_and_parses_each_variant() {
3878        assert_eq!(Config::default().context.layout, ContextLayout::Full);
3879        for (text, want) in [
3880            ("full", ContextLayout::Full),
3881            ("split", ContextLayout::Split),
3882            ("bottom", ContextLayout::Bottom),
3883        ] {
3884            let file = write_toml(&format!("[context]\nlayout = \"{text}\"\n"));
3885            assert_eq!(Config::load_from(file.path()).unwrap().context.layout, want);
3886        }
3887        let file = write_toml("[context]\nlayout = \"floating\"\n");
3888        assert!(
3889            Config::load_from(file.path()).is_err(),
3890            "an unknown layout must be rejected, not silently defaulted"
3891        );
3892    }
3893
3894    #[test]
3895    fn vendor_box_defaults_to_sidebar_and_parses_each_variant() {
3896        assert_eq!(Config::default().ui.vendor_box(), VendorBoxStyle::Sidebar);
3897        for (text, want) in [
3898            ("sidebar", VendorBoxStyle::Sidebar),
3899            ("navbar", VendorBoxStyle::Navbar),
3900            ("none", VendorBoxStyle::None),
3901        ] {
3902            let file = write_toml(&format!("[ui]\nvendor_box = \"{text}\"\n"));
3903            assert_eq!(
3904                Config::load_from(file.path()).unwrap().ui.vendor_box(),
3905                want
3906            );
3907        }
3908        let file = write_toml("[ui]\nvendor_box = \"floating\"\n");
3909        assert!(
3910            Config::load_from(file.path()).is_err(),
3911            "an unknown vendor_box style must be rejected, not silently defaulted"
3912        );
3913    }
3914
3915    #[test]
3916    fn context_window_sizes_must_be_nonzero_and_model_ids_nonempty() {
3917        for source in [
3918            "[context]\ncontext_window_tokens = 0\n",
3919            "[context.model_context_window_tokens]\nclaude = 0\n",
3920            "[context.model_context_window_tokens]\n\" \" = 200000\n",
3921        ] {
3922            let file = write_toml(source);
3923            let error = Config::load_from(file.path()).unwrap_err().to_string();
3924            assert!(error.contains("context"), "{error}");
3925        }
3926    }
3927
3928    // serial guard for env-var manipulation tests so they don't race
3929    fn env_guard() -> std::sync::MutexGuard<'static, ()> {
3930        static M: std::sync::Mutex<()> = std::sync::Mutex::new(());
3931        M.lock().unwrap_or_else(|p| p.into_inner())
3932    }
3933
3934    #[test]
3935    fn resolve_api_key_prefers_env_over_inline() {
3936        let _g = env_guard();
3937        // Use a unique env var name so we don't clobber test parallelism.
3938        let var = "AI_USAGEBAR_TEST_ENV_WINS";
3939        // SAFETY: tests are single-threaded under env_guard.
3940        unsafe { std::env::set_var(var, "from-env") };
3941        let got = resolve_api_key("Zai", var, Some("from-inline")).unwrap();
3942        unsafe { std::env::remove_var(var) };
3943        assert_eq!(got, "from-env");
3944    }
3945
3946    #[test]
3947    fn resolve_api_key_falls_back_to_inline() {
3948        let _g = env_guard();
3949        let var = "AI_USAGEBAR_TEST_INLINE_FALLBACK";
3950        unsafe { std::env::remove_var(var) };
3951        let got = resolve_api_key("Zai", var, Some("inline-key")).unwrap();
3952        assert_eq!(got, "inline-key");
3953    }
3954
3955    #[test]
3956    fn copilot_token_prefers_explicit_environment_over_gh_cli() {
3957        struct NeverRun;
3958        impl crate::copilot::credentials::GhAuthTokenRunner for NeverRun {
3959            fn run(
3960                &self,
3961                _: &crate::copilot::credentials::GhAuthTokenCommand,
3962            ) -> std::io::Result<crate::copilot::credentials::GhAuthTokenOutput> {
3963                panic!("environment override must not invoke gh")
3964            }
3965        }
3966
3967        let token = CopilotConfig::default()
3968            .resolve_token_with(
3969                |name| (name == "GITHUB_COPILOT_TOKEN").then(|| "from-environment".into()),
3970                &NeverRun,
3971                None,
3972            )
3973            .unwrap();
3974        assert_eq!(token, "from-environment");
3975    }
3976
3977    /// `--account` names a `gh` login; `GITHUB_COPILOT_TOKEN` names nothing.
3978    /// Honoring both would label one account's quota with another's name, so
3979    /// the combination is refused rather than silently resolved either way.
3980    #[test]
3981    fn copilot_rejects_an_environment_override_combined_with_a_named_account() {
3982        struct NeverRun;
3983        impl crate::copilot::credentials::GhAuthTokenRunner for NeverRun {
3984            fn run(
3985                &self,
3986                _: &crate::copilot::credentials::GhAuthTokenCommand,
3987            ) -> std::io::Result<crate::copilot::credentials::GhAuthTokenOutput> {
3988                panic!("the conflict must be refused before gh runs")
3989            }
3990        }
3991        let config = CopilotConfig {
3992            accounts: vec![CopilotAccount {
3993                label: "work".into(),
3994                user: "octocat".into(),
3995            }],
3996            ..CopilotConfig::default()
3997        };
3998        let error = config
3999            .resolve_token_with(
4000                |name| (name == "GITHUB_COPILOT_TOKEN").then(|| "from-environment".into()),
4001                &NeverRun,
4002                Some("work"),
4003            )
4004            .unwrap_err()
4005            .to_string();
4006        assert!(error.contains("GITHUB_COPILOT_TOKEN is set"), "{error}");
4007        assert!(error.contains("work"), "{error}");
4008    }
4009
4010    /// An unknown label must not fall back to the active `gh` account: that
4011    /// would report some other account's quota under the requested name.
4012    #[test]
4013    fn copilot_unknown_account_label_errors_listing_the_known_ones() {
4014        let config = CopilotConfig {
4015            accounts: vec![CopilotAccount {
4016                label: "work".into(),
4017                user: "octocat".into(),
4018            }],
4019            ..CopilotConfig::default()
4020        };
4021        assert_eq!(config.resolve_user(None).unwrap(), None);
4022        assert_eq!(config.resolve_user(Some("work")).unwrap(), Some("octocat"));
4023        let error = config
4024            .resolve_user(Some("personal"))
4025            .unwrap_err()
4026            .to_string();
4027        assert!(error.contains("personal"), "{error}");
4028        assert!(error.contains("work"), "{error}");
4029
4030        // With no accounts array at all, say so instead of listing nothing.
4031        let error = CopilotConfig::default()
4032            .resolve_user(Some("work"))
4033            .unwrap_err()
4034            .to_string();
4035        assert!(error.contains("no accounts array"), "{error}");
4036    }
4037
4038    /// Back-compat: an existing single-account config keeps the default tab
4039    /// and resolves exactly as before.
4040    #[test]
4041    fn copilot_defaults_keep_the_unnamed_account_visible() {
4042        let config = CopilotConfig::default();
4043        assert!(config.show_default_account);
4044        assert!(config.accounts.is_empty());
4045        assert!(!config.enabled, "Copilot stays opt-in");
4046    }
4047
4048    #[test]
4049    fn copilot_token_uses_injected_gh_cli_and_hides_failure_output() {
4050        struct FailedGh;
4051        impl crate::copilot::credentials::GhAuthTokenRunner for FailedGh {
4052            fn run(
4053                &self,
4054                _: &crate::copilot::credentials::GhAuthTokenCommand,
4055            ) -> std::io::Result<crate::copilot::credentials::GhAuthTokenOutput> {
4056                Ok(crate::copilot::credentials::GhAuthTokenOutput {
4057                    success: false,
4058                    stdout: b"never-echo-gh-output".to_vec(),
4059                })
4060            }
4061        }
4062        let error = CopilotConfig::default()
4063            .resolve_token_with(|_| None, &FailedGh, None)
4064            .unwrap_err()
4065            .to_string();
4066        assert!(error.contains("gh auth login --web"));
4067        assert!(!error.contains("never-echo-gh-output"));
4068    }
4069
4070    #[test]
4071    fn resolve_api_key_errors_when_both_missing() {
4072        let _g = env_guard();
4073        let var = "AI_USAGEBAR_TEST_BOTH_MISSING";
4074        unsafe { std::env::remove_var(var) };
4075        let err = resolve_api_key("Zai", var, None).unwrap_err();
4076        match err {
4077            crate::error::AppError::Credentials(msg) => {
4078                assert!(
4079                    msg.contains("api_key"),
4080                    "error should suggest config field: {msg}"
4081                );
4082            }
4083            other => panic!("expected Credentials error, got {other:?}"),
4084        }
4085    }
4086
4087    #[test]
4088    fn resolve_api_key_uses_exact_opencode_go_section_name() {
4089        let _g = env_guard();
4090        unsafe { std::env::remove_var("OPENCODE_GO_API_KEY") };
4091        let err = resolve_api_key("OpenCode Go", "OPENCODE_GO_API_KEY", None).unwrap_err();
4092        let message = err.to_string();
4093        assert!(
4094            message.contains("[opencode-go]"),
4095            "wrong section hint: {message}"
4096        );
4097        assert!(
4098            !message.contains("[opencode go]"),
4099            "wrong section hint: {message}"
4100        );
4101    }
4102
4103    fn path_override_guard() -> std::sync::MutexGuard<'static, ()> {
4104        static M: std::sync::Mutex<()> = std::sync::Mutex::new(());
4105        M.lock().unwrap_or_else(|p| p.into_inner())
4106    }
4107
4108    /// Serializes the override tests *and* guarantees the process-wide
4109    /// override is dropped when the test ends — including via a panic, which
4110    /// a bare set/clear pair does not survive. A leaked override makes every
4111    /// later test in this process resolve a deleted temp file, turning one
4112    /// failure into a cascade of confusing sibling failures.
4113    struct ScopedPathOverride {
4114        _serial: std::sync::MutexGuard<'static, ()>,
4115    }
4116
4117    impl Drop for ScopedPathOverride {
4118        fn drop(&mut self) {
4119            clear_override_path();
4120        }
4121    }
4122
4123    fn scoped_path_override() -> ScopedPathOverride {
4124        ScopedPathOverride {
4125            _serial: path_override_guard(),
4126        }
4127    }
4128
4129    #[test]
4130    fn override_path_wins_over_canonical_and_legacy() {
4131        let _scoped = scoped_path_override();
4132        let file = NamedTempFile::new().unwrap();
4133        set_override_path(file.path());
4134        assert_eq!(resolved_path().as_deref(), Some(file.path()));
4135        assert_eq!(config_path_hint(), file.path().display().to_string());
4136        clear_override_path();
4137        // The usual locations decide again once the override is gone.
4138        let p = resolved_path().expect("a config path must resolve");
4139        assert!(p.ends_with("config.toml"));
4140    }
4141
4142    #[test]
4143    fn scoped_override_guard_clears_the_override_on_panic() {
4144        // Silence the simulated failure's hook output; the assertion below is
4145        // the real report.
4146        let hook = std::panic::take_hook();
4147        std::panic::set_hook(Box::new(|_| {}));
4148        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4149            let _scoped = scoped_path_override();
4150            set_override_path(std::path::Path::new("panicked-override.toml"));
4151            panic!("simulated mid-test failure");
4152        }))
4153        .is_err();
4154        std::panic::set_hook(hook);
4155        assert!(panicked, "the simulated failure must run");
4156        let _serial = path_override_guard();
4157        assert!(
4158            override_path().is_none(),
4159            "a panicking test must not leak the override into siblings"
4160        );
4161    }
4162
4163    #[test]
4164    fn config_path_hint_ends_with_config_toml() {
4165        let _g = path_override_guard();
4166        // Platform-resolved (Linux/macOS/Windows), but always ends in the
4167        // config filename — the trailing segment is what messages rely on.
4168        assert!(config_path_hint().ends_with("config.toml"));
4169    }
4170
4171    #[test]
4172    fn config_flag_value_splits_the_equals_form() {
4173        use std::ffi::OsStr;
4174        assert_eq!(
4175            config_flag_value(OsStr::new("--config=work.toml")).as_deref(),
4176            Some(std::path::Path::new("work.toml"))
4177        );
4178        assert_eq!(
4179            config_flag_value(OsStr::new("--config=")).as_deref(),
4180            Some(std::path::Path::new(""))
4181        );
4182        assert_eq!(config_flag_value(OsStr::new("--config")), None);
4183        assert_eq!(config_flag_value(OsStr::new("--config-file")), None);
4184        assert_eq!(config_flag_value(OsStr::new("account")), None);
4185    }
4186
4187    /// The `--config=PATH` form must preserve a path the platform can store
4188    /// but UTF-8 cannot represent — `to_string_lossy` would replace the bad
4189    /// bytes with U+FFFD and produce a false "config file not found".
4190    #[cfg(unix)]
4191    #[test]
4192    fn config_flag_value_keeps_undecodable_bytes_intact() {
4193        use std::ffi::OsString;
4194        use std::os::unix::ffi::{OsStrExt, OsStringExt};
4195        let raw = OsString::from_vec(b"--config=caf\xe9.toml".to_vec());
4196        let value = config_flag_value(&raw).expect("prefix matches");
4197        assert_eq!(value.as_os_str().as_bytes(), b"caf\xe9.toml");
4198    }
4199
4200    #[cfg(windows)]
4201    #[test]
4202    fn config_flag_value_keeps_lone_surrogates_intact() {
4203        use std::ffi::OsString;
4204        use std::os::windows::ffi::{OsStrExt, OsStringExt};
4205        let mut wide: Vec<u16> = "--config=".encode_utf16().collect();
4206        wide.push(0xDC00); // lone low surrogate: not valid Unicode
4207        wide.extend("x.toml".encode_utf16());
4208        let raw = OsString::from_wide(&wide);
4209        let value = config_flag_value(&raw).expect("prefix matches");
4210        let mut expected = vec![0xDC00u16];
4211        expected.extend("x.toml".encode_utf16());
4212        assert_eq!(
4213            value.as_os_str().encode_wide().collect::<Vec<_>>(),
4214            expected
4215        );
4216    }
4217
4218    #[test]
4219    fn resolve_api_key_treats_empty_env_as_unset() {
4220        let _g = env_guard();
4221        let var = "AI_USAGEBAR_TEST_EMPTY_ENV";
4222        unsafe { std::env::set_var(var, "") };
4223        let got = resolve_api_key("OpenRouter", var, Some("inline")).unwrap();
4224        unsafe { std::env::remove_var(var) };
4225        assert_eq!(got, "inline");
4226    }
4227
4228    #[test]
4229    fn resolve_api_key_rejects_invalid_env_var_name_without_leaking_it() {
4230        let _g = env_guard();
4231        // Simulates a user accidentally pasting the key into api_key_env.
4232        let bad = "sk-kimi-very-real-looking-pasted-secret";
4233        let err = resolve_api_key("Kimi", bad, None).unwrap_err();
4234        let msg = err.to_string();
4235        assert!(
4236            msg.contains("invalid") && msg.contains("api_key_env"),
4237            "error should explain misconfiguration: {msg}"
4238        );
4239        assert!(
4240            !msg.contains(bad),
4241            "error must not echo the misconfigured value: {msg}"
4242        );
4243        assert!(msg.contains("valid environment variable name"));
4244        assert!(
4245            msg.contains("[kimi]"),
4246            "error should point at the lowercase TOML section: {msg}"
4247        );
4248    }
4249
4250    #[test]
4251    fn resolve_api_key_invalid_env_name_falls_back_to_inline() {
4252        let _g = env_guard();
4253        let got = resolve_api_key("Kimi", "sk-pasted-secret", Some("inline-key")).unwrap();
4254        assert_eq!(got, "inline-key");
4255    }
4256
4257    #[test]
4258    fn resolve_api_key_never_leaks_valid_looking_configured_env_name() {
4259        let _g = env_guard();
4260        // This is syntactically a valid environment variable name, but could
4261        // be a pasted secret and must not be reflected in the error.
4262        let pasted_secret = "sk_pasted_secret";
4263        unsafe { std::env::remove_var(pasted_secret) };
4264        let err = resolve_api_key("Kimi", pasted_secret, None).unwrap_err();
4265        assert!(
4266            !err.to_string().contains(pasted_secret),
4267            "error must not echo configured api_key_env values"
4268        );
4269    }
4270
4271    #[test]
4272    fn is_valid_env_var_name_rules() {
4273        // Valid: alphabetic or underscore first, then alnum/underscore.
4274        for valid in ["KIMI_API_KEY", "_PRIVATE", "a", "Z9", "MY_ZAI_2"] {
4275            assert!(is_valid_env_var_name(valid), "{valid} should be valid");
4276        }
4277        // Invalid: empty, digit-first, or shell-illegal characters.
4278        for invalid in ["", "9LIVES", "sk-kimi", "MY KEY", "A.B", "sk/k"] {
4279            assert!(
4280                !is_valid_env_var_name(invalid),
4281                "{invalid} should be invalid"
4282            );
4283        }
4284    }
4285
4286    #[test]
4287    fn config_parses_with_inline_api_key_and_primary() {
4288        let f = write_toml(
4289            r#"
4290            [ui]
4291            primary = "openrouter"
4292
4293            [zai]
4294            enabled = true
4295            api_key_env = "MY_ZAI"
4296            api_key = "sk-zai-inline"
4297
4298            [openrouter]
4299            enabled = true
4300            api_key = "sk-or-inline"
4301            "#,
4302        );
4303        let c = Config::load_from(f.path()).unwrap();
4304        assert_eq!(c.ui.primary, Some(VendorId::Openrouter));
4305        assert_eq!(c.zai.api_key.as_deref(), Some("sk-zai-inline"));
4306        assert_eq!(c.openrouter.api_key.as_deref(), Some("sk-or-inline"));
4307    }
4308
4309    #[test]
4310    fn openrouter_named_accounts_preserve_the_default_contract() {
4311        let f = write_toml(
4312            r#"
4313            [openrouter]
4314            enabled = true
4315            api_key_env = "AI_USAGEBAR_TEST_OR_DEFAULT"
4316            api_key = "default-inline"
4317            show_default_account = false
4318
4319            [[openrouter.accounts]]
4320            label = "work"
4321            api_key_env = "OPENROUTER_WORK_API_KEY"
4322
4323            [[openrouter.accounts]]
4324            label = "personal"
4325            api_key = "personal-inline"
4326            "#,
4327        );
4328        let _g = env_guard();
4329        unsafe { std::env::remove_var("AI_USAGEBAR_TEST_OR_DEFAULT") };
4330        let config = Config::load_from(f.path()).unwrap();
4331        assert!(!config.openrouter.show_default_account);
4332        assert_eq!(config.openrouter.accounts.len(), 2);
4333        assert_eq!(
4334            config
4335                .resolve_account_api_key_for(VendorId::Openrouter, None)
4336                .unwrap(),
4337            "default-inline"
4338        );
4339        assert_eq!(
4340            config
4341                .resolve_account_api_key_for(VendorId::Openrouter, Some("personal"))
4342                .unwrap(),
4343            "personal-inline"
4344        );
4345    }
4346
4347    #[test]
4348    fn openrouter_named_accounts_reject_ambiguous_or_unsafe_labels() {
4349        for source in [
4350            r#"
4351            [[openrouter.accounts]]
4352            label = "work"
4353            api_key = "one"
4354            [[openrouter.accounts]]
4355            label = "work"
4356            api_key = "two"
4357            "#,
4358            r#"
4359            [[openrouter.accounts]]
4360            label = "../work"
4361            api_key = "one"
4362            "#,
4363            r#"
4364            [[openrouter.accounts]]
4365            label = "work"
4366            "#,
4367        ] {
4368            let f = write_toml(source);
4369            assert!(Config::load_from(f.path()).is_err(), "accepted {source}");
4370        }
4371    }
4372
4373    #[test]
4374    fn openrouter_unknown_account_never_falls_back_to_default_key() {
4375        let mut config = Config::default();
4376        config.openrouter.api_key = Some("default-secret".into());
4377        config.openrouter.accounts.push(ApiKeyAccount {
4378            label: "work".into(),
4379            api_key_env: None,
4380            api_key: Some("work-secret".into()),
4381            management_api_key_env: None,
4382        });
4383        let message = config
4384            .resolve_account_api_key_for(VendorId::Openrouter, Some("missing"))
4385            .unwrap_err()
4386            .to_string();
4387        assert!(message.contains("missing") && message.contains("work"));
4388        assert!(!message.contains("default-secret"));
4389        assert!(!message.contains("work-secret"));
4390    }
4391
4392    #[test]
4393    fn openrouter_account_key_errors_do_not_echo_configured_values() {
4394        let mut config = Config::default();
4395        config.openrouter.accounts.push(ApiKeyAccount {
4396            label: "work".into(),
4397            api_key_env: Some("sk_pasted_secret".into()),
4398            api_key: None,
4399            management_api_key_env: None,
4400        });
4401        let _g = env_guard();
4402        unsafe { std::env::remove_var("sk_pasted_secret") };
4403        let message = config
4404            .resolve_account_api_key_for(VendorId::Openrouter, Some("work"))
4405            .unwrap_err()
4406            .to_string();
4407        assert!(message.contains("[[openrouter.accounts]]"));
4408        assert!(!message.contains("sk_pasted_secret"));
4409    }
4410
4411    #[test]
4412    fn openrouter_management_key_resolves_per_account_and_never_inherits() {
4413        let mut config = Config::default();
4414        config.openrouter.accounts = vec![
4415            ApiKeyAccount {
4416                label: "work".into(),
4417                api_key_env: None,
4418                api_key: Some("work-key".into()),
4419                management_api_key_env: Some("AI_USAGEBAR_TEST_OR_MGMT_WORK".into()),
4420            },
4421            ApiKeyAccount {
4422                label: "plain".into(),
4423                api_key_env: None,
4424                api_key: Some("plain-key".into()),
4425                management_api_key_env: None,
4426            },
4427        ];
4428        let _g = env_guard();
4429        unsafe { std::env::remove_var("OPENROUTER_MANAGEMENT_API_KEY") };
4430        unsafe { std::env::set_var("AI_USAGEBAR_TEST_OR_MGMT_WORK", "mgmt-work") };
4431
4432        // The default account reads OPENROUTER_MANAGEMENT_API_KEY — unset here.
4433        assert_eq!(config.openrouter_management_key(None), None);
4434        // A named account with its own var resolves it.
4435        assert_eq!(
4436            config.openrouter_management_key(Some("work")).as_deref(),
4437            Some("mgmt-work")
4438        );
4439        // A named account without one resolves nothing, even when the default
4440        // account's var is set — accounts never inherit across identities.
4441        unsafe { std::env::set_var("OPENROUTER_MANAGEMENT_API_KEY", "mgmt-default") };
4442        assert_eq!(
4443            config.openrouter_management_key(None).as_deref(),
4444            Some("mgmt-default")
4445        );
4446        assert_eq!(config.openrouter_management_key(Some("plain")), None);
4447        // An unknown label resolves nothing rather than the default's key.
4448        assert_eq!(config.openrouter_management_key(Some("typo")), None);
4449
4450        // The [openrouter] override renames the default account's var.
4451        config.openrouter.management_api_key_env = "AI_USAGEBAR_TEST_OR_MGMT_DEFAULT".into();
4452        unsafe { std::env::set_var("AI_USAGEBAR_TEST_OR_MGMT_DEFAULT", "mgmt-renamed") };
4453        assert_eq!(
4454            config.openrouter_management_key(None).as_deref(),
4455            Some("mgmt-renamed")
4456        );
4457        unsafe { std::env::remove_var("OPENROUTER_MANAGEMENT_API_KEY") };
4458        unsafe { std::env::remove_var("AI_USAGEBAR_TEST_OR_MGMT_WORK") };
4459        unsafe { std::env::remove_var("AI_USAGEBAR_TEST_OR_MGMT_DEFAULT") };
4460    }
4461
4462    #[test]
4463    fn every_api_key_account_vendor_validates_its_array_like_openrouter() {
4464        for vendor in Config::API_KEY_ACCOUNT_VENDORS {
4465            let section = vendor.config_section();
4466            let parse = |accounts: &str| -> Result<Config> {
4467                let config: Config =
4468                    toml::from_str(&format!("[{section}]\nenabled = true\n{accounts}")).unwrap();
4469                config.validate().map(|()| config)
4470            };
4471            let config = parse(&format!(
4472                "[[{section}.accounts]]\nlabel = \"work\"\napi_key = \"k\"\n"
4473            ))
4474            .unwrap();
4475            assert_eq!(
4476                config.api_key_accounts(vendor).unwrap().len(),
4477                1,
4478                "{vendor:?}"
4479            );
4480            assert!(config.show_default_api_key_account(vendor), "{vendor:?}");
4481
4482            let duplicate = parse(&format!(
4483                "[[{section}.accounts]]\nlabel = \"work\"\napi_key = \"a\"\n\
4484                 [[{section}.accounts]]\nlabel = \"work\"\napi_key = \"b\"\n"
4485            ))
4486            .unwrap_err()
4487            .to_string();
4488            assert!(
4489                duplicate.contains(&format!("duplicate {section} account label")),
4490                "{duplicate}"
4491            );
4492
4493            let keyless = parse(&format!("[[{section}.accounts]]\nlabel = \"work\"\n"))
4494                .unwrap_err()
4495                .to_string();
4496            assert!(
4497                keyless.contains("must set api_key_env or api_key"),
4498                "{keyless}"
4499            );
4500
4501            // A label becomes a cache subdirectory, so a path is refused.
4502            assert!(
4503                parse(&format!(
4504                    "[[{section}.accounts]]\nlabel = \"../x\"\napi_key = \"k\"\n"
4505                ))
4506                .is_err(),
4507                "{vendor:?}"
4508            );
4509        }
4510    }
4511
4512    #[test]
4513    fn named_api_key_accounts_resolve_their_own_key_and_never_the_default() {
4514        let mut config = Config::default();
4515        config.deepseek.api_key_env.clear();
4516        config.deepseek.api_key = Some("default-key".into());
4517        config.deepseek.accounts.push(ApiKeyAccount {
4518            label: "work".into(),
4519            api_key_env: Some("AI_USAGEBAR_TEST_DEEPSEEK_WORK".into()),
4520            api_key: Some("work-inline".into()),
4521            management_api_key_env: None,
4522        });
4523        let _g = env_guard();
4524        unsafe { std::env::set_var("AI_USAGEBAR_TEST_DEEPSEEK_WORK", "work-env") };
4525        let resolve = |label| config.resolve_account_api_key_for(VendorId::Deepseek, label);
4526        assert_eq!(resolve(None).unwrap(), "default-key");
4527        assert_eq!(resolve(Some("work")).unwrap(), "work-env", "env wins");
4528        unsafe { std::env::remove_var("AI_USAGEBAR_TEST_DEEPSEEK_WORK") };
4529        assert_eq!(resolve(Some("work")).unwrap(), "work-inline");
4530
4531        let unknown = resolve(Some("typo")).unwrap_err().to_string();
4532        assert!(unknown.contains("[[deepseek.accounts]]"), "{unknown}");
4533        assert!(
4534            unknown.contains("\"work\""),
4535            "lists known labels: {unknown}"
4536        );
4537        assert!(!unknown.contains("default-key"), "{unknown}");
4538    }
4539
4540    #[test]
4541    fn the_default_key_error_keeps_each_vendors_historic_wording() {
4542        let mut config = Config::default();
4543        config.zai.api_key_env.clear();
4544        config.minimax.api_key_env.clear();
4545        let zai = config
4546            .resolve_account_api_key_for(VendorId::Zai, None)
4547            .unwrap_err()
4548            .to_string();
4549        let expected = resolve_api_key("Zai", "", None).unwrap_err().to_string();
4550        assert_eq!(zai, expected);
4551        assert!(zai.contains("[zai]"), "{zai}");
4552        let minimax = config
4553            .resolve_account_api_key_for(VendorId::Minimax, None)
4554            .unwrap_err()
4555            .to_string();
4556        assert_eq!(
4557            minimax,
4558            resolve_api_key("MiniMax", "", None)
4559                .unwrap_err()
4560                .to_string()
4561        );
4562    }
4563
4564    #[test]
4565    fn enabled_vendors_preserves_canonical_order() {
4566        // DeepSeek and Kimi are disabled by default (require explicit API key
4567        // config), so they are absent from the enabled list unless enabled.
4568        let c = Config::default();
4569        assert_eq!(
4570            c.enabled_vendors(),
4571            vec![
4572                VendorId::Anthropic,
4573                VendorId::Openai,
4574                VendorId::Zai,
4575                VendorId::Openrouter,
4576            ]
4577        );
4578    }
4579
4580    #[test]
4581    fn deepseek_appears_when_enabled() {
4582        let f = write_toml(
4583            r#"
4584            [deepseek]
4585            enabled = true
4586            api_key = "sk-test"
4587            "#,
4588        );
4589        let c = Config::load_from(f.path()).unwrap();
4590        assert!(c.is_enabled(VendorId::Deepseek));
4591        assert!(c.enabled_vendors().contains(&VendorId::Deepseek));
4592        assert_eq!(c.deepseek.api_key.as_deref(), Some("sk-test"));
4593    }
4594
4595    #[test]
4596    fn tilde_paths_are_expanded_on_load() {
4597        // `PathBuf` keeps `~` literally, so the documented
4598        // `credentials_path = "~/..."` used to resolve to a directory named
4599        // `~` relative to the process's cwd.
4600        let f = write_toml(
4601            r#"
4602            [context]
4603            projects_path = "~/.claude/projects"
4604
4605            [anthropic]
4606            credentials_path = "~/.claude/.credentials.json"
4607
4608            [[anthropic.accounts]]
4609            label = "work"
4610            credentials_path = "~/work.json"
4611            "#,
4612        );
4613        let c = Config::load_from(f.path()).unwrap();
4614        let home = crate::cache::home_dir().unwrap();
4615
4616        assert_eq!(c.context.projects_path, Some(home.join(".claude/projects")));
4617        let got = c.anthropic.credentials_path.unwrap();
4618        assert_eq!(got, home.join(".claude/.credentials.json"));
4619        assert!(!got.to_string_lossy().contains('~'));
4620        assert_eq!(
4621            c.anthropic.accounts[0].credentials_path,
4622            home.join("work.json")
4623        );
4624    }
4625
4626    #[test]
4627    fn absolute_and_relative_paths_are_left_alone() {
4628        let f = write_toml(
4629            r#"
4630            [anthropic]
4631            credentials_path = "/etc/creds.json"
4632            "#,
4633        );
4634        let c = Config::load_from(f.path()).unwrap();
4635        assert_eq!(
4636            c.anthropic.credentials_path.unwrap(),
4637            std::path::Path::new("/etc/creds.json")
4638        );
4639
4640        // `~user` is not ours to interpret.
4641        let f2 = write_toml(
4642            r#"
4643            [anthropic]
4644            credentials_path = "~someone/creds.json"
4645            "#,
4646        );
4647        let c2 = Config::load_from(f2.path()).unwrap();
4648        assert_eq!(
4649            c2.anthropic.credentials_path.unwrap(),
4650            std::path::Path::new("~someone/creds.json")
4651        );
4652    }
4653
4654    #[test]
4655    fn resolved_path_is_the_canonical_one_and_names_the_config_file() {
4656        let _g = path_override_guard();
4657        // Hermetic: only asserts the shape, never which file happens to exist
4658        // on the machine running the tests.
4659        let p = resolved_path().expect("a config path must resolve");
4660        assert!(p.ends_with("config.toml"));
4661        let canonical = default_path().unwrap();
4662        let legacy = legacy_xdg_path().unwrap();
4663        assert!(
4664            p == canonical || p == legacy,
4665            "resolved to an unexpected location: {}",
4666            p.display()
4667        );
4668    }
4669
4670    #[test]
4671    fn misspelled_section_is_rejected_not_ignored() {
4672        // The regression this guards: `[openrouer]` used to parse fine, leave
4673        // OpenRouter on its defaults, and give the user no hint at all.
4674        let f = write_toml(
4675            r#"
4676            [openrouer]
4677            enabled = true
4678            api_key = "sk-or-v1-typo"
4679            "#,
4680        );
4681        let err = Config::load_from(f.path()).unwrap_err().to_string();
4682        assert!(
4683            err.contains("openrouer"),
4684            "error should name the typo: {err}"
4685        );
4686    }
4687
4688    #[test]
4689    fn invalid_toml_is_an_error_not_silent_defaults() {
4690        let f = write_toml("[zai\nenabled = true\n");
4691        assert!(Config::load_from(f.path()).is_err());
4692    }
4693
4694    /// A missing quote is the commonest way to break the file, and the line
4695    /// it breaks can be an inline key: the error must point at that line
4696    /// without repeating it.
4697    #[test]
4698    fn a_parse_error_names_the_line_without_quoting_it() {
4699        let f = write_toml("[openrouter]\nenabled = true\napi_key = sk-or-v1-unquoted\n");
4700        let err = Config::load_from(f.path()).unwrap_err().to_string();
4701        assert!(err.contains("line 3,"), "{err}");
4702        assert!(!err.contains("sk-or-v1-unquoted"), "{err}");
4703    }
4704
4705    /// The writers read the same file through `toml_edit`, whose errors quote
4706    /// the line too.
4707    #[test]
4708    fn a_writer_parse_error_names_the_line_without_quoting_it() {
4709        let (_dir, path) =
4710            crate::cache::closed_temp_file("config.toml", Some("[zai]\napi_key = zk-unquoted\n"));
4711        let err = read_config_document(&path).unwrap_err().to_string();
4712        assert!(err.contains("line 2,"), "{err}");
4713        assert!(!err.contains("zk-unquoted"), "{err}");
4714    }
4715
4716    #[test]
4717    fn toml_error_summary_keeps_the_position_and_the_message() {
4718        let input = "a = 1\nkey = sk-secret\n";
4719        assert_eq!(
4720            toml_error_summary(input, Some(12..21), "string values must be quoted\n"),
4721            "line 2, column 7: string values must be quoted"
4722        );
4723        assert_eq!(toml_error_summary(input, None, "bad"), "bad");
4724    }
4725
4726    #[test]
4727    fn a_missing_file_is_still_just_defaults() {
4728        // Absence stays the legitimate "use defaults" case — only real parse
4729        // and I/O failures are errors.
4730        let dir = tempfile::tempdir().unwrap();
4731        let missing = dir.path().join("nope").join("config.toml");
4732        let c = Config::load_from(&missing).unwrap();
4733        assert!(c.is_enabled(VendorId::Anthropic));
4734    }
4735
4736    #[test]
4737    fn kimi_appears_when_enabled() {
4738        let f = write_toml(
4739            r#"
4740            [kimi]
4741            enabled = true
4742            api_key = "sk-test"
4743            "#,
4744        );
4745        let c = Config::load_from(f.path()).unwrap();
4746        assert!(c.is_enabled(VendorId::Kimi));
4747        assert!(c.enabled_vendors().contains(&VendorId::Kimi));
4748        assert_eq!(c.kimi.api_key.as_deref(), Some("sk-test"));
4749    }
4750
4751    #[test]
4752    fn enabled_deepseek_and_kimi_appear_in_canonical_order_ending_with_them() {
4753        let f = write_toml(
4754            r#"
4755            [deepseek]
4756            enabled = true
4757            api_key = "sk-ds"
4758
4759            [kimi]
4760            enabled = true
4761            api_key = "sk-kimi"
4762            "#,
4763        );
4764        let c = Config::load_from(f.path()).unwrap();
4765        assert_eq!(
4766            c.enabled_vendors(),
4767            vec![
4768                VendorId::Anthropic,
4769                VendorId::Openai,
4770                VendorId::Zai,
4771                VendorId::Openrouter,
4772                VendorId::Deepseek,
4773                VendorId::Kimi,
4774            ]
4775        );
4776    }
4777
4778    #[test]
4779    fn parses_anthropic_accounts_and_looks_them_up() {
4780        let f = write_toml(
4781            r#"
4782            [anthropic]
4783            enabled = true
4784
4785            [[anthropic.accounts]]
4786            label = "personal"
4787            credentials_path = "/creds/personal.json"
4788
4789            [[anthropic.accounts]]
4790            label = "work"
4791            credentials_path = "/creds/work.json"
4792            "#,
4793        );
4794        let c = Config::load_from(f.path()).unwrap();
4795        assert_eq!(c.anthropic.accounts.len(), 2);
4796        let work = c.anthropic.account("work").unwrap();
4797        assert_eq!(work.credentials_path, PathBuf::from("/creds/work.json"));
4798        // A typo names the offending label and lists the known ones.
4799        let err = format!("{:?}", c.anthropic.account("missing").unwrap_err());
4800        assert!(err.contains("missing") && err.contains("work"), "{err}");
4801    }
4802
4803    #[test]
4804    fn duplicate_anthropic_account_labels_are_rejected_on_load() {
4805        let f = write_toml(
4806            r#"
4807            [[anthropic.accounts]]
4808            label = "work"
4809            credentials_path = "/creds/work-one.json"
4810
4811            [[anthropic.accounts]]
4812            label = "work"
4813            credentials_path = "/creds/work-two.json"
4814            "#,
4815        );
4816        let err = Config::load_from(f.path()).unwrap_err().to_string();
4817        assert!(
4818            err.contains("duplicate anthropic account label \"work\""),
4819            "{err}"
4820        );
4821    }
4822
4823    #[test]
4824    fn account_label_rejects_path_like_names() {
4825        let cfg = AnthropicConfig::default();
4826        for bad in [
4827            "",
4828            ".",
4829            "..",
4830            "a/b",
4831            r"a\b",
4832            "C:work",
4833            "line\nbreak",
4834            "tab\tname",
4835            "usage.json",
4836            ".stale",
4837            ".last_error",
4838            ".fetch.lock",
4839        ] {
4840            let err = cfg.account(bad).unwrap_err();
4841            assert!(
4842                format!("{err:?}").contains("invalid anthropic account label"),
4843                "{bad:?} should be rejected as a label"
4844            );
4845        }
4846    }
4847
4848    #[test]
4849    fn anthropic_accounts_default_to_empty() {
4850        // No [[anthropic.accounts]] → the single default account, empty list,
4851        // nothing to migrate (issue #14, back-compat rule 1).
4852        assert!(Config::default().anthropic.accounts.is_empty());
4853        assert!(Config::default().anthropic.accounts_dir.is_none());
4854    }
4855
4856    // --- accounts_dir: CLAUDE_CONFIG_DIR-style auto-discovery ----------------
4857    // All hermetic: discovery reads a TempDir, never the user's real config.
4858
4859    /// Create `<root>/<label>/.credentials.json` (contents irrelevant here —
4860    /// discovery keys on the file existing, the fetch path parses it).
4861    fn seed_account_dir(root: &std::path::Path, label: &str) {
4862        let dir = root.join(label);
4863        std::fs::create_dir_all(&dir).unwrap();
4864        std::fs::write(dir.join(".credentials.json"), "{}").unwrap();
4865    }
4866
4867    #[test]
4868    fn discovers_account_dirs_in_claude_config_dir_layout() {
4869        let td = tempfile::tempdir().unwrap();
4870        seed_account_dir(td.path(), "work");
4871        seed_account_dir(td.path(), "personal");
4872        // Keychain-backed macOS logins may not write .credentials.json; their
4873        // config directories are still account entries.
4874        std::fs::create_dir_all(td.path().join("keychain-only")).unwrap();
4875        // A loose file (not a dir) is ignored.
4876        std::fs::write(td.path().join("stray.json"), "{}").unwrap();
4877
4878        let cfg = AnthropicConfig {
4879            accounts_dir: Some(td.path().to_path_buf()),
4880            ..Default::default()
4881        };
4882        let all = cfg.all_accounts();
4883        let labels: Vec<&str> = all.iter().map(|a| a.label.as_str()).collect();
4884        assert_eq!(labels, vec!["keychain-only", "personal", "work"]);
4885        assert_eq!(
4886            all[2].credentials_path,
4887            td.path().join("work").join(".credentials.json")
4888        );
4889    }
4890
4891    #[test]
4892    fn explicit_account_wins_over_a_discovered_one_with_the_same_label() {
4893        let td = tempfile::tempdir().unwrap();
4894        seed_account_dir(td.path(), "work");
4895        let cfg = AnthropicConfig {
4896            accounts: vec![AnthropicAccount {
4897                label: "work".into(),
4898                credentials_path: "/explicit/work.json".into(),
4899            }],
4900            accounts_dir: Some(td.path().to_path_buf()),
4901            ..Default::default()
4902        };
4903        let all = cfg.all_accounts();
4904        assert_eq!(all.len(), 1, "no duplicate label");
4905        assert_eq!(
4906            all[0].credentials_path,
4907            std::path::Path::new("/explicit/work.json"),
4908            "explicit entry wins"
4909        );
4910        // A discovered account is still reachable through `account()`.
4911        seed_account_dir(td.path(), "other");
4912        assert_eq!(cfg.account("other").unwrap().label, "other");
4913    }
4914
4915    #[test]
4916    fn missing_accounts_dir_is_silently_empty_not_an_error() {
4917        let cfg = AnthropicConfig {
4918            accounts_dir: Some("/nonexistent/ai-usagebar-accounts".into()),
4919            ..Default::default()
4920        };
4921        assert!(cfg.all_accounts().is_empty());
4922    }
4923
4924    #[test]
4925    fn openai_account_auth_paths_are_tilde_expanded_on_load() {
4926        let f = write_toml(
4927            r#"
4928            [[openai.accounts]]
4929            label = "work"
4930            codex_auth_path = "~/.codex-work/auth.json"
4931            "#,
4932        );
4933        let c = Config::load_from(f.path()).unwrap();
4934        let home = crate::cache::home_dir().unwrap();
4935        assert_eq!(
4936            c.openai.accounts[0].codex_auth_path,
4937            home.join(".codex-work/auth.json")
4938        );
4939    }
4940
4941    #[test]
4942    fn accounts_dir_is_tilde_expanded_on_load() {
4943        let f = write_toml(
4944            r#"
4945            [anthropic]
4946            accounts_dir = "~/.config/ai-usagebar/accounts"
4947            "#,
4948        );
4949        let c = Config::load_from(f.path()).unwrap();
4950        let home = crate::cache::home_dir().unwrap();
4951        assert_eq!(
4952            c.anthropic.accounts_dir,
4953            Some(home.join(".config/ai-usagebar/accounts"))
4954        );
4955    }
4956
4957    #[test]
4958    fn desktop_profiles_dir_is_tilde_expanded_on_load() {
4959        let f = write_toml(
4960            r#"
4961            [anthropic]
4962            desktop_profiles_dir = "~/.claude-acc/profiles"
4963            "#,
4964        );
4965        let c = Config::load_from(f.path()).unwrap();
4966        let home = crate::cache::home_dir().unwrap();
4967        assert_eq!(
4968            c.anthropic.desktop_profiles_dir,
4969            Some(home.join(".claude-acc/profiles"))
4970        );
4971    }
4972
4973    #[test]
4974    fn the_live_cli_account_is_read_from_the_default_credential_slot() {
4975        let cfg = AnthropicConfig {
4976            accounts: vec![
4977                AnthropicAccount {
4978                    label: "work".into(),
4979                    credentials_path: "/tmp/accounts/work/.credentials.json".into(),
4980                },
4981                AnthropicAccount {
4982                    label: "personal".into(),
4983                    credentials_path: "/tmp/accounts/personal/.credentials.json".into(),
4984                },
4985            ],
4986            ..Default::default()
4987        };
4988
4989        let (idle, idle_cache) = cfg.account_target_with("work", Some("personal")).unwrap();
4990        assert!(
4991            matches!(&idle, CredsTarget::Named { config_dir, .. }
4992                if config_dir == std::path::Path::new("/tmp/accounts/work")),
4993            "{idle:?}"
4994        );
4995
4996        // Same label, but it is the login `claude` itself is using: one lineage.
4997        let (live, live_cache) = cfg.account_target_with("work", Some("work")).unwrap();
4998        assert!(matches!(live, CredsTarget::Default(_)), "{live:?}");
4999
5000        // The cache must not move, or a switch would silently orphan the tab's
5001        // usage history and show "Loading…" until the next fetch.
5002        assert_eq!(idle_cache.dir(), live_cache.dir());
5003    }
5004
5005    #[test]
5006    fn the_live_cli_account_keeps_its_own_slot_while_that_file_is_there() {
5007        // Two CLAUDE_CONFIG_DIRs can hold the same account, and each keeps its
5008        // own live credential — `resolve_active_label` matches the account, not
5009        // the lineage. Reading the default slot then hands back a credential
5010        // the user never logs into.
5011        let cfg = AnthropicConfig {
5012            accounts: vec![AnthropicAccount {
5013                label: "personal".into(),
5014                credentials_path: "/tmp/accounts/personal/.credentials.json".into(),
5015            }],
5016            ..Default::default()
5017        };
5018
5019        let (present, _) = cfg
5020            .account_target_probing("personal", Some("personal"), |_| true)
5021            .unwrap();
5022        assert!(
5023            matches!(&present, CredsTarget::Named { path, .. }
5024                if path == Path::new("/tmp/accounts/personal/.credentials.json")),
5025            "{present:?}"
5026        );
5027
5028        // Emptied by `account switch`: the credential really did move.
5029        let (moved, _) = cfg
5030            .account_target_probing("personal", Some("personal"), |_| false)
5031            .unwrap();
5032        assert!(matches!(moved, CredsTarget::Default(_)), "{moved:?}");
5033    }
5034
5035    #[test]
5036    fn the_default_entry_reads_config_credentials_path_strictly() {
5037        let cfg = AnthropicConfig {
5038            credentials_path: Some("/tmp/claude-home/.credentials.json".into()),
5039            ..Default::default()
5040        };
5041
5042        assert!(
5043            matches!(&cfg.default_creds_target(), CredsTarget::Explicit(path)
5044                if path == Path::new("/tmp/claude-home/.credentials.json")),
5045        );
5046        // Without one, the platform default — the only target with a Keychain fallback.
5047        assert!(matches!(
5048            AnthropicConfig::default().default_creds_target(),
5049            CredsTarget::Default(_)
5050        ));
5051    }
5052
5053    #[test]
5054    fn the_live_cli_accounts_own_file_is_probed_on_disk() {
5055        // `account_target_probing` proves the decision; only the entry point
5056        // proves that the shipping caller probes at all. Fails on main, where
5057        // the live label is routed to the default slot unconditionally.
5058        let creds = NamedTempFile::new().unwrap();
5059        let cfg = AnthropicConfig {
5060            accounts: vec![AnthropicAccount {
5061                label: "personal".into(),
5062                credentials_path: creds.path().to_path_buf(),
5063            }],
5064            ..Default::default()
5065        };
5066        let (target, _) = cfg
5067            .account_target_with("personal", Some("personal"))
5068            .unwrap();
5069        assert!(
5070            matches!(&target, CredsTarget::Named { path, .. } if path == creds.path()),
5071            "read {target:?} instead of the account's own file"
5072        );
5073    }
5074
5075    #[test]
5076    fn no_live_cli_account_keeps_every_account_on_its_own_slot() {
5077        let cfg = AnthropicConfig {
5078            accounts: vec![AnthropicAccount {
5079                label: "work".into(),
5080                credentials_path: "/tmp/accounts/work/.credentials.json".into(),
5081            }],
5082            ..Default::default()
5083        };
5084        let (target, _) = cfg.account_target_with("work", None).unwrap();
5085        assert!(matches!(target, CredsTarget::Named { .. }), "{target:?}");
5086    }
5087
5088    /// The shipped example, which `make install` puts in
5089    /// `share/ai-usagebar/config.example.toml`. Repo-relative, so this stays
5090    /// hermetic — it never touches the user's real config.
5091    fn config_example() -> PathBuf {
5092        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.example.toml")
5093    }
5094
5095    #[test]
5096    fn shipped_example_parses_as_a_real_config() {
5097        // The example is documentation users copy verbatim, but nothing used
5098        // to parse it — so a renamed section or field could rot there
5099        // unnoticed, and `deny_unknown_fields` would reject the copy on the
5100        // user's machine instead of in CI.
5101        let c = Config::load_from(&config_example()).unwrap();
5102        assert!(!c.context.enabled);
5103        assert!(c.is_enabled(VendorId::Anthropic));
5104        assert!(c.is_enabled(VendorId::Openai));
5105        assert!(!c.is_enabled(VendorId::AnthropicApi));
5106        assert!(!c.is_enabled(VendorId::Deepseek));
5107        assert!(!c.is_enabled(VendorId::Kimi));
5108        assert!(!c.is_enabled(VendorId::Kilo));
5109        assert!(!c.is_enabled(VendorId::Novita));
5110        assert!(!c.is_enabled(VendorId::Moonshot));
5111        assert!(!c.is_enabled(VendorId::Grok));
5112        assert!(!c.is_enabled(VendorId::Cursor));
5113        assert!(!c.is_enabled(VendorId::Minimax));
5114    }
5115
5116    #[test]
5117    fn shipped_example_does_not_advertise_admin_key_env_as_working() {
5118        // The regression: the example shipped an *uncommented*
5119        // `admin_key_env = "OPENAI_ADMIN_KEY"`, indistinguishable from a live
5120        // setting. Nothing reads it, so a user could set it, skip
5121        // `codex login`, and wait for usage that never arrives.
5122        let text = std::fs::read_to_string(config_example()).unwrap();
5123        let live: Vec<&str> = text
5124            .lines()
5125            .map(str::trim)
5126            .filter(|l| l.contains("admin_key_env") && !l.starts_with('#'))
5127            .collect();
5128        assert!(
5129            live.is_empty(),
5130            "admin_key_env must stay commented out while it is inert: {live:?}"
5131        );
5132        // Still documented, though — silently dropping it would leave users
5133        // who already set it with no explanation of why it does nothing.
5134        assert!(
5135            text.contains("admin_key_env") && text.contains("RESERVED"),
5136            "the example should keep describing admin_key_env as reserved"
5137        );
5138    }
5139
5140    #[test]
5141    fn admin_key_env_is_accepted_but_changes_nothing() {
5142        // The field survives because the API-key-only path is still intended.
5143        // What has to hold today is narrower: setting it loads without error
5144        // and moves nothing the code actually acts on.
5145        let f = write_toml(
5146            r#"
5147            [openai]
5148            admin_key_env = "SOME_ADMIN_KEY"
5149            "#,
5150        );
5151        let c = Config::load_from(f.path()).unwrap();
5152        assert_eq!(c.openai.admin_key_env, "SOME_ADMIN_KEY");
5153        // Nothing else moved: OpenAI still resolves through Codex OAuth only.
5154        let default = OpenAiConfig::default();
5155        assert_eq!(c.openai.enabled, default.enabled);
5156        assert_eq!(c.openai.codex_auth_path, default.codex_auth_path);
5157        assert_eq!(c.enabled_vendors(), Config::default().enabled_vendors());
5158    }
5159
5160    #[test]
5161    fn config_example_documents_every_vendor_without_secrets() {
5162        let raw = std::fs::read_to_string(config_example()).unwrap();
5163        let cfg = Config::load_from(&config_example()).unwrap();
5164        // Every vendor the binary can dispatch needs a documented section, or
5165        // users have no way to discover how to turn it on.
5166        for id in VendorId::all() {
5167            let section = id.slug();
5168            assert!(
5169                raw.contains(&format!("[{section}]")),
5170                "config.example.toml has no [{section}] section"
5171            );
5172        }
5173
5174        // The example must not ship anything enabled-by-key-only, and must not
5175        // carry a real secret.
5176        assert!(!cfg.anthropic_api.enabled && cfg.anthropic_api.api_key.is_none());
5177        assert!(!cfg.kilo.enabled && cfg.kilo.api_key.is_none());
5178        assert!(!cfg.novita.enabled && cfg.novita.api_key.is_none());
5179        assert!(!cfg.moonshot.enabled && cfg.moonshot.api_key.is_none());
5180        assert!(!cfg.grok.enabled && cfg.grok.api_key.is_none());
5181        assert!(!cfg.supergrok.enabled);
5182        assert_eq!(cfg.supergrok.grok_binary, default_grok_binary());
5183        assert_eq!(
5184            cfg.supergrok
5185                .grok_binary
5186                .file_name()
5187                .and_then(|p| p.to_str()),
5188            Some(if cfg!(windows) { "grok.exe" } else { "grok" })
5189        );
5190        assert!(cfg.supergrok.auth_path.is_none());
5191        assert!(cfg.supergrok.config_path.is_none());
5192        assert!(!cfg.cursor.enabled && cfg.cursor.db_path.is_none());
5193        assert!(!cfg.kiro.enabled && cfg.kiro.db_path.is_none());
5194    }
5195
5196    #[test]
5197    fn supergrok_binary_must_not_be_empty() {
5198        let file = write_toml(
5199            r#"
5200            [supergrok]
5201            enabled = true
5202            grok_binary = ""
5203            "#,
5204        );
5205        let error = Config::load_from(file.path()).unwrap_err().to_string();
5206        assert!(error.contains("grok_binary must not be empty"));
5207    }
5208
5209    #[test]
5210    fn supergrok_paths_are_tilde_expanded() {
5211        let file = write_toml(
5212            r#"
5213            [supergrok]
5214            grok_binary = "~/bin/grok"
5215            auth_path = "~/.grok/auth.json"
5216            config_path = "~/.grok/config.toml"
5217            "#,
5218        );
5219        let config = Config::load_from(file.path()).unwrap();
5220        let home = crate::cache::home_dir().unwrap();
5221        assert_eq!(config.supergrok.grok_binary, home.join("bin/grok"));
5222        assert_eq!(
5223            config.supergrok.auth_path,
5224            Some(home.join(".grok/auth.json"))
5225        );
5226        assert_eq!(
5227            config.supergrok.config_path,
5228            Some(home.join(".grok/config.toml"))
5229        );
5230    }
5231
5232    /// `config.example.toml` documents `auth_paths = ["~/.commandcode/auth.json"]`;
5233    /// `gh_binary` is the Copilot counterpart of `grok_binary` above.
5234    #[test]
5235    fn commandcode_and_copilot_paths_are_tilde_expanded() {
5236        let file = write_toml(
5237            r#"
5238            [commandcode]
5239            auth_paths = ["~/.commandcode/auth.json", "/etc/commandcode/auth.json"]
5240
5241            [copilot]
5242            gh_binary = "~/bin/gh"
5243            "#,
5244        );
5245        let config = Config::load_from(file.path()).unwrap();
5246        let home = crate::cache::home_dir().unwrap();
5247        assert_eq!(
5248            config.commandcode.auth_paths,
5249            Some(vec![
5250                home.join(".commandcode/auth.json"),
5251                PathBuf::from("/etc/commandcode/auth.json"),
5252            ])
5253        );
5254        assert_eq!(config.copilot.gh_binary, Some(home.join("bin/gh")));
5255    }
5256
5257    #[test]
5258    fn kiro_db_path_is_tilde_expanded() {
5259        let f = write_toml(
5260            r#"
5261            [kiro]
5262            db_path = "~/kiro-data.sqlite3"
5263            "#,
5264        );
5265        let c = Config::load_from(f.path()).unwrap();
5266        let home = crate::cache::home_dir().unwrap();
5267        assert_eq!(c.kiro.db_path, Some(home.join("kiro-data.sqlite3")));
5268    }
5269
5270    #[test]
5271    fn kiro_appears_when_enabled() {
5272        let f = write_toml(
5273            r#"
5274            [kiro]
5275            enabled = true
5276            "#,
5277        );
5278        let c = Config::load_from(f.path()).unwrap();
5279        assert!(c.is_enabled(VendorId::Kiro));
5280        assert!(c.enabled_vendors().contains(&VendorId::Kiro));
5281    }
5282
5283    #[test]
5284    fn cursor_db_path_is_tilde_expanded() {
5285        let f = write_toml(
5286            r#"
5287            [cursor]
5288            db_path = "~/cursor-state.vscdb"
5289            "#,
5290        );
5291        let c = Config::load_from(f.path()).unwrap();
5292        let home = crate::cache::home_dir().unwrap();
5293        assert_eq!(c.cursor.db_path, Some(home.join("cursor-state.vscdb")));
5294    }
5295
5296    #[test]
5297    fn cursor_agent_auth_path_is_tilde_expanded() {
5298        let f = write_toml(
5299            r#"
5300            [cursor]
5301            agent_auth_path = "~/cursor-agent-auth.json"
5302            "#,
5303        );
5304        let c = Config::load_from(f.path()).unwrap();
5305        let home = crate::cache::home_dir().unwrap();
5306        assert_eq!(
5307            c.cursor.agent_auth_path,
5308            Some(home.join("cursor-agent-auth.json"))
5309        );
5310    }
5311
5312    #[test]
5313    fn cursor_appears_when_enabled() {
5314        let f = write_toml(
5315            r#"
5316            [cursor]
5317            enabled = true
5318            "#,
5319        );
5320        let c = Config::load_from(f.path()).unwrap();
5321        assert!(c.is_enabled(VendorId::Cursor));
5322        assert!(c.enabled_vendors().contains(&VendorId::Cursor));
5323    }
5324
5325    #[test]
5326    fn add_account_appends_and_preserves_existing() {
5327        let mut doc: toml_edit::DocumentMut = r#"
5328# keep me
5329[anthropic]
5330enabled = true
5331
5332[[anthropic.accounts]]
5333label = "personal"
5334credentials_path = "~/.config/ai-usagebar/accounts/personal/.credentials.json"
5335"#
5336        .parse()
5337        .unwrap();
5338        add_anthropic_account_to_doc(
5339            &mut doc,
5340            "work",
5341            "~/.config/ai-usagebar/accounts/work/.credentials.json",
5342        )
5343        .unwrap();
5344        let rendered = doc.to_string();
5345        assert!(rendered.contains("# keep me"), "comment must survive");
5346        // Round-trips through the real loader with both accounts intact and ordered.
5347        let f = write_toml(&rendered);
5348        let c = Config::load_from(f.path()).unwrap();
5349        let labels: Vec<&str> = c
5350            .anthropic
5351            .accounts
5352            .iter()
5353            .map(|a| a.label.as_str())
5354            .collect();
5355        assert_eq!(labels, vec!["personal", "work"]);
5356    }
5357
5358    #[test]
5359    fn add_account_to_empty_doc_is_loadable() {
5360        let mut doc = toml_edit::DocumentMut::new();
5361        add_anthropic_account_to_doc(&mut doc, "solo", "~/x/.credentials.json").unwrap();
5362        let f = write_toml(&doc.to_string());
5363        let c = Config::load_from(f.path()).unwrap();
5364        assert_eq!(c.anthropic.accounts.len(), 1);
5365        assert_eq!(c.anthropic.accounts[0].label, "solo");
5366    }
5367
5368    #[test]
5369    fn add_account_rejects_duplicate_label() {
5370        let mut doc: toml_edit::DocumentMut = r#"
5371[[anthropic.accounts]]
5372label = "work"
5373credentials_path = "~/w/.credentials.json"
5374"#
5375        .parse()
5376        .unwrap();
5377        assert!(
5378            add_anthropic_account_to_doc(&mut doc, "work", "~/other/.credentials.json").is_err(),
5379            "a duplicate label must be rejected, not appended"
5380        );
5381    }
5382
5383    #[test]
5384    fn add_account_rejects_bad_label() {
5385        let mut doc = toml_edit::DocumentMut::new();
5386        assert!(add_anthropic_account_to_doc(&mut doc, "a/b", "~/x/.credentials.json").is_err());
5387        assert!(add_anthropic_account_to_doc(&mut doc, "", "~/x/.credentials.json").is_err());
5388    }
5389
5390    #[test]
5391    fn tildify_collapses_home_only() {
5392        let home = Path::new("/Users/me");
5393        assert_eq!(tildify(&home.join("a/b"), home), "~/a/b");
5394        assert_eq!(tildify(Path::new("/etc/hosts"), home), "/etc/hosts");
5395    }
5396
5397    #[test]
5398    fn default_account_credentials_path_nests_under_config_dir() {
5399        let cfg = Path::new("/home/u/.config/ai-usagebar/config.toml");
5400        assert_eq!(
5401            default_account_credentials_path(cfg, "work"),
5402            Path::new("/home/u/.config/ai-usagebar/accounts/work/.credentials.json"),
5403        );
5404    }
5405    // ----- [[custom]] providers -----
5406
5407    const CUSTOM_BLOCK: &str = r#"
5408[[custom]]
5409id = "mytool"
5410name = "My Tool"
5411short_name = "myt"
5412enabled = true
5413url = "https://api.example.test/v1/usage"
5414api_key_env = "MYTOOL_API_KEY"
5415auth_header = "Authorization"
5416auth_scheme = "Bearer"
5417plan = "Pro"
5418cache_ttl_secs = 120
5419[custom.headers]
5420X-Org = "org_1"
5421[[custom.metrics]]
5422label = "Requests"
5423used = "/requests/used"
5424limit = "/requests/limit"
5425resets_at = "/requests/reset"
5426window_secs = 3600
5427[[custom.texts]]
5428label = "Tier"
5429value = "/tier"
5430"#;
5431
5432    fn custom_with(from: &str, to: &str) -> String {
5433        assert!(CUSTOM_BLOCK.contains(from), "fixture has no {from:?}");
5434        CUSTOM_BLOCK.replace(from, to)
5435    }
5436
5437    fn custom_error(toml: &str) -> String {
5438        Config::load_from(write_toml(toml).path())
5439            .unwrap_err()
5440            .to_string()
5441    }
5442
5443    fn assert_custom_rejected(toml: &str, needle: &str) {
5444        let msg = custom_error(toml);
5445        assert!(msg.contains(needle), "expected {needle:?} in: {msg}");
5446        assert!(
5447            msg.contains("[[custom]]"),
5448            "the error must locate the section: {msg}"
5449        );
5450    }
5451
5452    #[test]
5453    fn custom_block_parses_every_field() {
5454        let config = Config::load_from(write_toml(CUSTOM_BLOCK).path()).unwrap();
5455        assert_eq!(config.custom.len(), 1);
5456        let c = &config.custom[0];
5457        assert_eq!(c.id, "mytool");
5458        assert_eq!(c.name, "My Tool");
5459        assert_eq!(c.short_name, "myt");
5460        assert_eq!(
5461            c.brand, None,
5462            "a custom provider has no mark unless it asks"
5463        );
5464        assert!(c.enabled);
5465        assert_eq!(c.url, "https://api.example.test/v1/usage");
5466        assert!(!c.allow_http);
5467        assert_eq!(c.api_key_env, "MYTOOL_API_KEY");
5468        assert_eq!(c.api_key, None);
5469        assert_eq!(c.auth_header, "Authorization");
5470        assert_eq!(c.auth_scheme, "Bearer");
5471        assert_eq!(c.headers.get("X-Org").map(String::as_str), Some("org_1"));
5472        assert_eq!(c.plan.as_deref(), Some("Pro"));
5473        assert_eq!(c.plan_path, None);
5474        assert_eq!(c.cache_ttl(), std::time::Duration::from_secs(120));
5475        assert_eq!(c.metrics.len(), 1);
5476        assert_eq!(c.metrics[0].label, "Requests");
5477        assert_eq!(c.metrics[0].used.as_deref(), Some("/requests/used"));
5478        assert_eq!(c.metrics[0].limit.as_deref(), Some("/requests/limit"));
5479        assert_eq!(c.metrics[0].percent, None);
5480        assert_eq!(c.metrics[0].resets_at.as_deref(), Some("/requests/reset"));
5481        assert_eq!(c.metrics[0].window_secs, Some(3600));
5482        assert_eq!(c.texts.len(), 1);
5483        assert_eq!(c.texts[0].label, "Tier");
5484        assert_eq!(c.texts[0].value, "/tier");
5485        assert_eq!(c.section_label(), r#"[[custom]] id = "mytool""#);
5486    }
5487
5488    #[test]
5489    fn custom_defaults_are_the_documented_ones_and_name_falls_back_to_id() {
5490        let config: Config = toml::from_str(
5491            r#"
5492            [[custom]]
5493            id = "bare"
5494            short_name = "bre"
5495            url = "https://example.test/u"
5496            [[custom.metrics]]
5497            label = "Q"
5498            percent = "/pct"
5499            "#,
5500        )
5501        .unwrap();
5502        let c = &config.custom[0];
5503        assert_eq!(c.name, "bare", "name must default to id on a plain parse");
5504        assert!(!c.enabled);
5505        assert!(!c.allow_http);
5506        assert_eq!(c.api_key_env, "");
5507        assert_eq!(c.auth_header, "Authorization");
5508        assert_eq!(c.auth_scheme, "Bearer");
5509        assert_eq!(c.cache_ttl_secs, 60);
5510        assert!(config.validate().is_ok());
5511        assert!(Config::default().custom.is_empty());
5512    }
5513
5514    #[test]
5515    fn custom_brand_names_a_builtin_vendor_and_nothing_else() {
5516        let config = Config::load_from(
5517            write_toml(&custom_with(
5518                r#"short_name = "myt""#,
5519                "short_name = \"myt\"\nbrand = \"opencode-go\"",
5520            ))
5521            .path(),
5522        )
5523        .unwrap();
5524        assert_eq!(config.custom[0].brand.as_deref(), Some("opencode-go"));
5525
5526        // The mark is borrowed from a vendor, so only a vendor can name one.
5527        // A free-form slug here would reach the frontend as artwork it does
5528        // not ship and draw nothing at all.
5529        for brand in ["opencode", "OpenCode-Go", "mytool", ""] {
5530            assert_custom_rejected(
5531                &custom_with(
5532                    r#"short_name = "myt""#,
5533                    &format!("short_name = \"myt\"\nbrand = {brand:?}"),
5534                ),
5535                "must name a built-in vendor",
5536            );
5537        }
5538    }
5539
5540    #[test]
5541    fn custom_rejects_a_malformed_id() {
5542        let long = "a".repeat(33);
5543        for id in ["", "My Tool", "-lead", "UPPER", long.as_str()] {
5544            let msg = custom_error(&custom_with(r#"id = "mytool""#, &format!("id = {id:?}")));
5545            assert!(msg.contains("[[custom]] entry #1"), "{id:?}: {msg}");
5546            assert!(msg.contains("must match"), "{id:?}: {msg}");
5547        }
5548    }
5549
5550    #[test]
5551    fn custom_rejects_a_builtin_slug_as_id() {
5552        assert_custom_rejected(
5553            &custom_with(r#"id = "mytool""#, r#"id = "deepseek""#),
5554            "is a built-in vendor",
5555        );
5556        assert_custom_rejected(
5557            &custom_with(r#"id = "mytool""#, r#"id = "opencode-go""#),
5558            "is a built-in vendor",
5559        );
5560    }
5561
5562    #[test]
5563    fn custom_rejects_duplicate_ids() {
5564        let twice = format!(
5565            "{}{}",
5566            CUSTOM_BLOCK,
5567            custom_with(r#"short_name = "myt""#, r#"short_name = "myu""#)
5568        );
5569        assert_custom_rejected(&twice, "duplicate id");
5570    }
5571
5572    #[test]
5573    fn custom_rejects_a_name_over_48_chars() {
5574        let long = "n".repeat(49);
5575        assert_custom_rejected(
5576            &custom_with(r#"name = "My Tool""#, &format!("name = {long:?}")),
5577            "name must be 1 to 48 characters",
5578        );
5579    }
5580
5581    #[test]
5582    fn custom_rejects_a_short_name_that_is_not_three_lowercase_letters() {
5583        for short in ["my", "myto", "MYT", "m1t"] {
5584            assert_custom_rejected(
5585                &custom_with(r#"short_name = "myt""#, &format!("short_name = {short:?}")),
5586                "exactly 3 lowercase ASCII letters",
5587            );
5588        }
5589    }
5590
5591    #[test]
5592    fn custom_rejects_a_short_name_taken_by_a_builtin_or_another_entry() {
5593        assert_custom_rejected(
5594            &custom_with(r#"short_name = "myt""#, r#"short_name = "dsk""#),
5595            "already used by a built-in vendor",
5596        );
5597        let twice = format!(
5598            "{}{}",
5599            CUSTOM_BLOCK,
5600            custom_with(r#"id = "mytool""#, r#"id = "othertool""#)
5601        );
5602        assert_custom_rejected(&twice, "already used by a built-in vendor");
5603    }
5604
5605    #[test]
5606    fn custom_rejects_http_unless_allowed() {
5607        let plain = custom_with(
5608            r#"url = "https://api.example.test/v1/usage""#,
5609            r#"url = "http://localhost:8080/usage""#,
5610        );
5611        assert_custom_rejected(&plain, "url must use https://");
5612        let allowed = plain.replace(
5613            r#"url = "http://localhost:8080/usage""#,
5614            "url = \"http://localhost:8080/usage\"\nallow_http = true",
5615        );
5616        assert!(
5617            Config::load_from(write_toml(&allowed).path()).is_ok(),
5618            "allow_http must permit http://"
5619        );
5620    }
5621
5622    #[test]
5623    fn custom_rejects_a_url_with_userinfo_or_a_bad_scheme_or_garbage() {
5624        assert_custom_rejected(
5625            &custom_with(
5626                r#"url = "https://api.example.test/v1/usage""#,
5627                r#"url = "https://user:pw@api.example.test/v1/usage""#,
5628            ),
5629            "must not carry credentials",
5630        );
5631        assert_custom_rejected(
5632            &custom_with(
5633                r#"url = "https://api.example.test/v1/usage""#,
5634                r#"url = "not a url""#,
5635            ),
5636            "is not a valid URL",
5637        );
5638        assert_custom_rejected(
5639            &custom_with(
5640                r#"url = "https://api.example.test/v1/usage""#,
5641                r#"url = "ftp://api.example.test/v1/usage""#,
5642            ),
5643            "is not http or https",
5644        );
5645    }
5646
5647    #[test]
5648    fn custom_rejects_an_invalid_api_key_env() {
5649        assert_custom_rejected(
5650            &custom_with(
5651                r#"api_key_env = "MYTOOL_API_KEY""#,
5652                r#"api_key_env = "1BAD-NAME""#,
5653            ),
5654            "is not a valid environment variable name",
5655        );
5656        let none = custom_with(r#"api_key_env = "MYTOOL_API_KEY""#, r#"api_key_env = """#);
5657        assert!(
5658            Config::load_from(write_toml(&none).path()).is_ok(),
5659            "an empty api_key_env means inline-only and is valid"
5660        );
5661    }
5662
5663    /// A value that is not a variable name is most likely a key pasted into
5664    /// the wrong field, and this error fails the whole config load: it names
5665    /// the field and never repeats the value.
5666    #[test]
5667    fn custom_invalid_api_key_env_is_not_repeated() {
5668        let msg = custom_error(&custom_with(
5669            r#"api_key_env = "MYTOOL_API_KEY""#,
5670            r#"api_key_env = "sk-live-pasted-secret""#,
5671        ));
5672        assert!(msg.contains("api_key_env"), "{msg}");
5673        assert!(!msg.contains("sk-live-pasted-secret"), "{msg}");
5674    }
5675
5676    #[test]
5677    fn custom_rejects_an_invalid_auth_header_name() {
5678        assert_custom_rejected(
5679            &custom_with(
5680                r#"auth_header = "Authorization""#,
5681                r#"auth_header = "X Api Key""#,
5682            ),
5683            "auth_header \"X Api Key\" is not a valid HTTP header name",
5684        );
5685    }
5686
5687    #[test]
5688    fn custom_rejects_a_control_char_in_auth_scheme() {
5689        assert_custom_rejected(
5690            &custom_with(
5691                r#"auth_scheme = "Bearer""#,
5692                "auth_scheme = \"Bearer\\u0007\"",
5693            ),
5694            "auth_scheme contains characters that are not valid",
5695        );
5696        let bare = custom_with(r#"auth_scheme = "Bearer""#, r#"auth_scheme = """#);
5697        assert!(
5698            Config::load_from(write_toml(&bare).path()).is_ok(),
5699            "an empty scheme (bare key) is valid"
5700        );
5701    }
5702
5703    #[test]
5704    fn custom_rejects_a_bad_extra_header() {
5705        assert_custom_rejected(
5706            &custom_with(r#"X-Org = "org_1""#, r#"authorization = "Bearer other""#),
5707            "headers must not repeat auth_header",
5708        );
5709        assert_custom_rejected(
5710            &custom_with(r#"X-Org = "org_1""#, r#""X Org" = "org_1""#),
5711            "is not a valid HTTP header name",
5712        );
5713        assert_custom_rejected(
5714            &custom_with(r#"X-Org = "org_1""#, "X-Org = \"org\\u0001\""),
5715            "has a value that is not valid in an HTTP header",
5716        );
5717    }
5718
5719    #[test]
5720    fn custom_rejects_cache_ttl_outside_10_to_3600() {
5721        for ttl in ["9", "3601"] {
5722            assert_custom_rejected(
5723                &custom_with("cache_ttl_secs = 120", &format!("cache_ttl_secs = {ttl}")),
5724                "cache_ttl_secs must be between 10 and 3600",
5725            );
5726        }
5727    }
5728
5729    #[test]
5730    fn custom_rejects_an_entry_with_no_metrics_or_texts() {
5731        let toml = r#"
5732[[custom]]
5733id = "empty"
5734short_name = "emp"
5735url = "https://example.test/u"
5736"#;
5737        assert_custom_rejected(toml, "at least one [[custom.metrics]] or [[custom.texts]]");
5738    }
5739
5740    #[test]
5741    fn custom_rejects_a_metric_mixing_percent_with_used_or_limit() {
5742        assert_custom_rejected(
5743            &custom_with(
5744                r#"limit = "/requests/limit""#,
5745                "limit = \"/requests/limit\"\npercent = \"/requests/pct\"",
5746            ),
5747            "must set `percent`, or both `used` and `limit`",
5748        );
5749        assert_custom_rejected(
5750            &custom_with("limit = \"/requests/limit\"\n", ""),
5751            "must set `percent`, or both `used` and `limit`",
5752        );
5753    }
5754
5755    #[test]
5756    fn custom_rejects_a_pointer_without_a_leading_slash() {
5757        assert_custom_rejected(
5758            &custom_with(r#"used = "/requests/used""#, r#"used = "requests.used""#),
5759            "used \"requests.used\" must be an RFC 6901 JSON Pointer",
5760        );
5761        assert_custom_rejected(
5762            &custom_with(r#"value = "/tier""#, r#"value = "tier""#),
5763            "value \"tier\" must be an RFC 6901 JSON Pointer",
5764        );
5765        assert_custom_rejected(
5766            &custom_with(r#"plan = "Pro""#, r#"plan_path = "plan""#),
5767            "plan_path \"plan\" must be an RFC 6901 JSON Pointer",
5768        );
5769        assert_custom_rejected(
5770            &custom_with(
5771                r#"resets_at = "/requests/reset""#,
5772                "resets_at = \"/re\\u001bset\"",
5773            ),
5774            "resets_at",
5775        );
5776    }
5777
5778    #[test]
5779    fn custom_rejects_a_label_outside_1_to_64_chars() {
5780        let long = "l".repeat(65);
5781        assert_custom_rejected(
5782            &custom_with(r#"label = "Requests""#, &format!("label = {long:?}")),
5783            "metric label",
5784        );
5785        assert_custom_rejected(
5786            &custom_with(r#"label = "Tier""#, r#"label = """#),
5787            "text label \"\" must be 1 to 64 characters",
5788        );
5789    }
5790
5791    #[test]
5792    fn custom_rejects_window_secs_under_60() {
5793        assert_custom_rejected(
5794            &custom_with("window_secs = 3600", "window_secs = 59"),
5795            "window_secs must be at least 60",
5796        );
5797    }
5798
5799    #[test]
5800    fn custom_rejects_duplicate_metric_and_text_labels() {
5801        let metric_twice = custom_with(
5802            "window_secs = 3600\n",
5803            "window_secs = 3600\n[[custom.metrics]]\nlabel = \"Requests\"\npercent = \"/pct\"\n",
5804        );
5805        assert_custom_rejected(&metric_twice, "duplicate metric label \"Requests\"");
5806        let text_twice =
5807            format!("{CUSTOM_BLOCK}[[custom.texts]]\nlabel = \"Tier\"\nvalue = \"/other\"\n");
5808        assert_custom_rejected(&text_twice, "duplicate text label \"Tier\"");
5809    }
5810
5811    #[test]
5812    fn enabled_custom_and_custom_by_id_select_entries() {
5813        let two = format!(
5814            "{}{}",
5815            CUSTOM_BLOCK,
5816            custom_with(r#"id = "mytool""#, r#"id = "off""#)
5817                .replace(r#"short_name = "myt""#, r#"short_name = "off""#)
5818                .replace("enabled = true", "enabled = false")
5819        );
5820        let config = Config::load_from(write_toml(&two).path()).unwrap();
5821        let enabled: Vec<&str> = config.enabled_custom().map(|c| c.id.as_str()).collect();
5822        assert_eq!(enabled, ["mytool"]);
5823        assert_eq!(
5824            config.custom_by_id("off").map(|c| c.name.as_str()),
5825            Some("My Tool")
5826        );
5827        assert!(config.custom_by_id("nope").is_none());
5828    }
5829
5830    #[cfg(unix)]
5831    #[test]
5832    fn has_inline_secrets_sees_a_custom_inline_key() {
5833        let without: Config = toml::from_str(CUSTOM_BLOCK).unwrap();
5834        assert!(!without.has_inline_secrets());
5835        let with: Config = toml::from_str(&custom_with(
5836            r#"api_key_env = "MYTOOL_API_KEY""#,
5837            "api_key_env = \"MYTOOL_API_KEY\"\napi_key = \"sk-inline\"",
5838        ))
5839        .unwrap();
5840        assert!(with.has_inline_secrets());
5841    }
5842
5843    #[test]
5844    fn custom_resolve_api_key_prefers_env_then_inline_then_errors_without_the_key() {
5845        let var = "AI_USAGEBAR_CUSTOM_TEST_KEY_51C2";
5846        let mut spec = CustomProviderConfig {
5847            id: "mytool".into(),
5848            api_key_env: var.into(),
5849            api_key: Some("sk-inline-secret".into()),
5850            ..CustomProviderConfig::default()
5851        };
5852        unsafe { std::env::set_var(var, "sk-env-secret") };
5853        let from_env = spec.resolve_api_key();
5854        unsafe { std::env::remove_var(var) };
5855        assert_eq!(from_env.unwrap(), "sk-env-secret");
5856
5857        assert_eq!(spec.resolve_api_key().unwrap(), "sk-inline-secret");
5858
5859        spec.api_key = Some(String::new());
5860        let err = spec.resolve_api_key().unwrap_err();
5861        assert!(matches!(err, AppError::Credentials(_)), "{err:?}");
5862        let msg = err.to_string();
5863        assert!(msg.contains(r#"[[custom]] id = "mytool""#), "{msg}");
5864        assert!(msg.contains(var), "{msg}");
5865        assert!(!msg.contains("secret"), "{msg}");
5866
5867        spec.api_key_env = String::new();
5868        let msg = spec.resolve_api_key().unwrap_err().to_string();
5869        assert!(msg.contains("set `api_key`"), "{msg}");
5870    }
5871
5872    #[test]
5873    fn loading_a_config_registers_custom_env_vars_for_scrubbing() {
5874        let var = "AI_USAGEBAR_CUSTOM_SCRUB_TEST_9B1D";
5875        assert!(!crate::vendor::vendor_secret_env_vars_to_remove(&[]).contains(&var));
5876        let file = write_toml(&custom_with("MYTOOL_API_KEY", var));
5877        Config::load_from(file.path()).unwrap();
5878        assert!(
5879            crate::vendor::vendor_secret_env_vars_to_remove(&[]).contains(&var),
5880            "a custom provider's env var must be scrubbed from subprocesses"
5881        );
5882    }
5883
5884    #[test]
5885    fn loading_a_config_registers_account_and_renamed_env_vars_for_scrubbing() {
5886        let account = "AI_USAGEBAR_ACCOUNT_SCRUB_TEST_4C2E";
5887        let renamed = "AI_USAGEBAR_RENAMED_SCRUB_TEST_7A3F";
5888        let before = crate::vendor::vendor_secret_env_vars_to_remove(&[]);
5889        assert!(!before.contains(&account));
5890        assert!(!before.contains(&renamed));
5891        let file = write_toml(&format!(
5892            "[zai]\napi_key_env = \"{renamed}\"\n\
5893             [[deepseek.accounts]]\nlabel = \"work\"\napi_key_env = \"{account}\"\n"
5894        ));
5895        Config::load_from(file.path()).unwrap();
5896        let after = crate::vendor::vendor_secret_env_vars_to_remove(&[]);
5897        assert!(after.contains(&account), "a named account's key variable");
5898        assert!(after.contains(&renamed), "a renamed api_key_env");
5899    }
5900
5901    #[test]
5902    fn loading_a_config_registers_openrouter_management_env_vars_for_scrubbing() {
5903        let renamed = "AI_USAGEBAR_MGMT_RENAMED_SCRUB_TEST_5D1B";
5904        let account = "AI_USAGEBAR_MGMT_ACCOUNT_SCRUB_TEST_8E6C";
5905        let before = crate::vendor::vendor_secret_env_vars_to_remove(&[]);
5906        assert!(!before.contains(&renamed));
5907        assert!(!before.contains(&account));
5908        let file = write_toml(&format!(
5909            "[openrouter]\nmanagement_api_key_env = \"{renamed}\"\n\
5910             [[openrouter.accounts]]\nlabel = \"work\"\napi_key_env = \"OR_WORK_KEY\"\n\
5911             management_api_key_env = \"{account}\"\n"
5912        ));
5913        Config::load_from(file.path()).unwrap();
5914        let after = crate::vendor::vendor_secret_env_vars_to_remove(&[]);
5915        assert!(after.contains(&renamed), "a renamed management_api_key_env");
5916        assert!(
5917            after.contains(&account),
5918            "an account's management_api_key_env"
5919        );
5920    }
5921
5922    /// `[cline] api_key_env` is read by the fetch, so the shared resolver has
5923    /// to answer the same name: the catalog reports and probes it, and the
5924    /// scrub list is built from it. Cline's arm sat with the fixed-name
5925    /// providers, so a renamed variable configured the fetch alone.
5926    #[test]
5927    fn loading_a_config_resolves_and_scrubs_a_renamed_cline_env_var() {
5928        let renamed = "AI_USAGEBAR_CLINE_RENAMED_SCRUB_TEST_2F8A";
5929        assert!(!crate::vendor::vendor_secret_env_vars_to_remove(&[]).contains(&renamed));
5930        let file = write_toml(&format!("[cline]\napi_key_env = \"{renamed}\"\n"));
5931        let config = Config::load_from(file.path()).unwrap();
5932        assert_eq!(config.api_key_env_for(VendorId::Cline), renamed);
5933        assert!(
5934            crate::vendor::vendor_secret_env_vars_to_remove(&[]).contains(&renamed),
5935            "a renamed Cline key variable must be scrubbed from subprocesses"
5936        );
5937    }
5938
5939    /// `VendorId::config_section` is what every by-name config writer uses;
5940    /// this proves each section name is one the parser actually recognizes
5941    /// (the `deny_unknown_fields` on `Config` makes a misspelling fail loudly)
5942    /// and lands on that vendor's `enabled` switch.
5943    #[test]
5944    fn every_config_section_parses_to_its_vendors_enabled_switch() {
5945        for vendor in VendorId::all() {
5946            let text = format!(
5947                "[{}]
5948enabled = true
5949",
5950                vendor.config_section()
5951            );
5952            let config: Config = toml::from_str(&text)
5953                .unwrap_or_else(|e| panic!("{}: {e}", vendor.config_section()));
5954            assert!(config.is_enabled(*vendor), "{}", vendor.config_section());
5955            let others = VendorId::all()
5956                .iter()
5957                .filter(|other| *other != vendor && config.is_enabled(**other))
5958                .count();
5959            assert_eq!(
5960                others,
5961                Config::default().enabled_vendors().len()
5962                    - usize::from(Config::default().is_enabled(*vendor)),
5963                "[{}] enabled a different vendor",
5964                vendor.config_section()
5965            );
5966        }
5967    }
5968
5969    #[test]
5970    fn tray_section_parses_and_defaults_to_notify() {
5971        let file = write_toml("[tray]\nshortcut = \"Ctrl+Shift+U\"\nupdates = \"auto\"\n");
5972        let config = Config::load_from(file.path()).unwrap();
5973        assert_eq!(config.tray.shortcut.as_deref(), Some("Ctrl+Shift+U"));
5974        assert_eq!(config.tray.updates(), UpdateMode::Auto);
5975
5976        let empty = Config::load_from(write_toml("[ui]\n").path()).unwrap();
5977        assert_eq!(empty.tray, TrayConfig::default());
5978        assert_eq!(empty.tray.updates(), UpdateMode::Notify);
5979        assert_eq!(UpdateMode::parse(" Off "), Some(UpdateMode::Off));
5980        assert_eq!(UpdateMode::parse("weekly"), None);
5981        assert_eq!(UpdateMode::Auto.as_str(), "auto");
5982    }
5983
5984    #[test]
5985    fn tray_ignores_removed_menu_bar_keys_for_back_compatibility() {
5986        let legacy = write_toml(
5987            "[tray]\nmenu_bar_show_all = false\nmenu_bar_hide_value = true\nmenu_bar_names = \"short\"\nmenu_bar_provider = \"anthropic\"\nmenu_bar_window = \"weekly\"\n",
5988        );
5989        let config = Config::load_from(legacy.path()).unwrap();
5990        assert_eq!(config.tray, TrayConfig::default());
5991    }
5992
5993    #[test]
5994    fn tray_section_rejects_a_misspelled_mode() {
5995        let file = write_toml("[tray]\nupdates = \"sometimes\"\n");
5996        assert!(Config::load_from(file.path()).is_err());
5997    }
5998
5999    #[test]
6000    fn tray_refresh_minutes_defaults_to_five_and_parses() {
6001        let empty = Config::load_from(write_toml("[ui]\n").path()).unwrap();
6002        assert_eq!(empty.tray.refresh_minutes, None);
6003        assert_eq!(empty.tray.refresh_minutes(), 5);
6004
6005        let file = write_toml("[tray]\nrefresh_minutes = 10\n");
6006        let config = Config::load_from(file.path()).unwrap();
6007        assert_eq!(config.tray.refresh_minutes(), 10);
6008    }
6009
6010    #[test]
6011    fn tray_refresh_minutes_rejects_values_outside_the_menu() {
6012        for minutes in ["3", "0", "120"] {
6013            let file = write_toml(&format!("[tray]\nrefresh_minutes = {minutes}\n"));
6014            let error = Config::load_from(file.path()).unwrap_err().to_string();
6015            assert!(error.contains("[tray] refresh_minutes"), "{error}");
6016            assert!(error.contains("1, 5, 10, 15, 30 or 60"), "{error}");
6017        }
6018    }
6019
6020    #[test]
6021    fn notifications_default_on_at_97_and_parse_overrides() {
6022        let empty = Config::load_from(write_toml("[ui]\n").path()).unwrap();
6023        assert!(empty.notifications.enabled);
6024        assert_eq!(empty.notifications.threshold, 97);
6025
6026        let file = write_toml("[notifications]\nenabled = false\nthreshold = 100\n");
6027        let config = Config::load_from(file.path()).unwrap();
6028        assert!(!config.notifications.enabled);
6029        assert_eq!(config.notifications.threshold, 100);
6030    }
6031
6032    #[test]
6033    fn notifications_threshold_rejects_values_outside_1_to_100() {
6034        for threshold in ["0", "101", "255"] {
6035            let file = write_toml(&format!("[notifications]\nthreshold = {threshold}\n"));
6036            let error = Config::load_from(file.path()).unwrap_err().to_string();
6037            assert!(
6038                error.contains("[notifications] threshold must be between 1 and 100"),
6039                "threshold {threshold}: {error}"
6040            );
6041        }
6042        // The boundaries themselves are valid.
6043        for threshold in ["1", "50", "100"] {
6044            let file = write_toml(&format!("[notifications]\nthreshold = {threshold}\n"));
6045            let config = Config::load_from(file.path()).unwrap();
6046            assert_eq!(config.notifications.threshold.to_string(), threshold);
6047        }
6048    }
6049
6050    #[test]
6051    fn notification_preferences_round_trip_without_changing_other_sections() {
6052        let dir = tempfile::tempdir().unwrap();
6053        let path = dir.path().join("config.toml");
6054        std::fs::write(&path, "# keep this\n[tray]\nrefresh_minutes = 10\n").unwrap();
6055        set_notification_value(&path, "enabled", false.into()).unwrap();
6056        set_notification_value(&path, "threshold", 85i64.into()).unwrap();
6057        let text = std::fs::read_to_string(&path).unwrap();
6058        assert!(text.contains("# keep this\n[tray]\nrefresh_minutes = 10"));
6059        let config = Config::load_from(&path).unwrap();
6060        assert!(!config.notifications.enabled);
6061        assert_eq!(config.notifications.threshold, 85);
6062        assert!(set_notification_value(&path, "threshold", 101i64.into()).is_err());
6063        assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
6064    }
6065
6066    /// #244's whitelist: a real slug round-trips onto that vendor's `enabled`
6067    /// switch (creating the section when the config never had one) while the
6068    /// rest of the file is untouched, and a slug that names no built-in vendor
6069    /// is refused without writing anything.
6070    #[test]
6071    fn vendor_enabled_round_trips_and_rejects_unknown_slugs() {
6072        let dir = tempfile::tempdir().unwrap();
6073        let path = dir.path().join("config.toml");
6074        std::fs::write(&path, "# keep\n[zai]\nenabled = true # mine\n").unwrap();
6075
6076        set_vendor_enabled(&path, "zai", false).unwrap();
6077        let text = std::fs::read_to_string(&path).unwrap();
6078        assert!(text.starts_with("# keep\n"), "{text}");
6079        assert!(text.contains("enabled = false # mine"), "{text}");
6080        assert!(!config_enabled(&path, VendorId::Zai));
6081
6082        set_vendor_enabled(&path, "grok", true).unwrap();
6083        let config = Config::load_from(&path).unwrap();
6084        assert!(config.is_enabled(VendorId::Grok));
6085        assert!(
6086            !config.is_enabled(VendorId::Deepseek),
6087            "only the named vendor moves; untouched opt-in vendors stay off"
6088        );
6089        assert!(
6090            config.is_enabled(VendorId::Openai),
6091            "an untouched default-on vendor is not switched off either"
6092        );
6093
6094        for bad in ["", "custom", "not-a-vendor", "anthropic "] {
6095            let error = set_vendor_enabled(&path, bad, true)
6096                .unwrap_err()
6097                .to_string();
6098            assert!(error.contains("unknown provider"), "{bad}: {error}");
6099        }
6100        // A refused write leaves the file byte-for-byte alone.
6101        assert!(
6102            std::fs::read_to_string(&path)
6103                .unwrap()
6104                .contains("enabled = false # mine")
6105        );
6106    }
6107
6108    /// The doc-level core only ever lands on the vendor's own section, and an
6109    /// idempotent call does not rewrite the file.
6110    #[test]
6111    fn set_vendor_enabled_in_doc_targets_the_section_and_stays_idempotent() {
6112        let dir = tempfile::tempdir().unwrap();
6113        let path = dir.path().join("config.toml");
6114        std::fs::write(&path, "[grok]\nenabled = true\napi_key = \"k\"\n").unwrap();
6115        let before = std::fs::metadata(&path).unwrap().modified().unwrap();
6116
6117        set_vendor_enabled(&path, "grok", true).unwrap();
6118
6119        assert_eq!(
6120            std::fs::read_to_string(&path).unwrap(),
6121            "[grok]\nenabled = true\napi_key = \"k\"\n"
6122        );
6123        assert_eq!(
6124            std::fs::metadata(&path).unwrap().modified().unwrap(),
6125            before
6126        );
6127
6128        let mut doc = toml_edit::DocumentMut::new();
6129        set_vendor_enabled_in_doc(&mut doc, "opencode-go", true).unwrap();
6130        assert_eq!(doc.to_string(), "[opencode-go]\nenabled = true\n");
6131        assert!(set_vendor_enabled_in_doc(&mut doc, "mytool", true).is_err());
6132    }
6133
6134    fn config_enabled(path: &std::path::Path, vendor: VendorId) -> bool {
6135        Config::load_from(path).unwrap().is_enabled(vendor)
6136    }
6137
6138    #[test]
6139    fn menu_bar_short_name_defaults_on_and_persists_as_a_bool() {
6140        let dir = tempfile::tempdir().unwrap();
6141        let path = dir.path().join("config.toml");
6142        std::fs::write(&path, "[tray]\n").unwrap();
6143        assert!(Config::load_from(&path).unwrap().tray.menu_bar_short_name());
6144
6145        set_tray_value(&path, "menu_bar_short_name", Some(false.into())).unwrap();
6146        let text = std::fs::read_to_string(&path).unwrap();
6147        assert_eq!(text, "[tray]\nmenu_bar_short_name = false\n");
6148        assert!(!Config::load_from(&path).unwrap().tray.menu_bar_short_name());
6149    }
6150
6151    #[test]
6152    fn set_tray_value_writes_refresh_minutes_as_an_integer() {
6153        let dir = tempfile::tempdir().unwrap();
6154        let path = dir.path().join("config.toml");
6155        std::fs::write(&path, "[tray]\nrefresh_minutes = 5 # mine\n").unwrap();
6156
6157        set_tray_value(&path, "refresh_minutes", Some(10i64.into())).unwrap();
6158        let text = std::fs::read_to_string(&path).unwrap();
6159        assert_eq!(text, "[tray]\nrefresh_minutes = 10 # mine\n");
6160        assert_eq!(Config::load_from(&path).unwrap().tray.refresh_minutes(), 10);
6161
6162        set_tray_value(&path, "refresh_minutes", None).unwrap();
6163        assert_eq!(Config::load_from(&path).unwrap().tray.refresh_minutes(), 5);
6164    }
6165
6166    #[test]
6167    fn set_tray_value_creates_replaces_and_removes_keys() {
6168        let dir = tempfile::tempdir().unwrap();
6169        let path = dir.path().join("config.toml");
6170        std::fs::write(&path, "[ui]\n# primary = \"anthropic\"\n").unwrap();
6171
6172        set_tray_value(&path, "shortcut", Some("Ctrl+Shift+U".into())).unwrap();
6173        let text = std::fs::read_to_string(&path).unwrap();
6174        assert!(text.contains("# primary = \"anthropic\""), "{text}");
6175        assert!(
6176            text.contains("[tray]\nshortcut = \"Ctrl+Shift+U\""),
6177            "{text}"
6178        );
6179
6180        set_tray_value(&path, "shortcut", Some("Alt+F5".into())).unwrap();
6181        set_tray_value(&path, "updates", Some("off".into())).unwrap();
6182        let config = Config::load_from(&path).unwrap();
6183        assert_eq!(config.tray.shortcut.as_deref(), Some("Alt+F5"));
6184        assert_eq!(config.tray.updates(), UpdateMode::Off);
6185
6186        set_tray_value(&path, "shortcut", None).unwrap();
6187        let text = std::fs::read_to_string(&path).unwrap();
6188        assert!(!text.contains("shortcut"), "{text}");
6189        assert!(text.contains("updates = \"off\""), "{text}");
6190
6191        // Idempotent removal does not rewrite the file.
6192        let mtime = std::fs::metadata(&path).unwrap().modified().unwrap();
6193        set_tray_value(&path, "shortcut", None).unwrap();
6194        assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), mtime);
6195    }
6196
6197    #[test]
6198    fn set_value_keeps_the_trailing_comment_when_replacing() {
6199        let mut doc: toml_edit::DocumentMut =
6200            "[tray]\nshortcut = \"Ctrl+U\" # mine\n".parse().unwrap();
6201        set_value(&mut doc, "tray", "shortcut", Some("Alt+U".into())).unwrap();
6202        assert_eq!(doc.to_string(), "[tray]\nshortcut = \"Alt+U\" # mine\n");
6203    }
6204
6205    #[test]
6206    fn enable_vendors_in_creates_a_missing_config() {
6207        let dir = tempfile::TempDir::new().unwrap();
6208        let path = dir.path().join("sub").join("config.toml");
6209
6210        enable_vendors_in(&path, &[VendorId::Grok]).unwrap();
6211
6212        assert_eq!(
6213            std::fs::read_to_string(&path).unwrap(),
6214            "[grok]
6215enabled = true
6216"
6217        );
6218        assert!(Config::load_from(&path).unwrap().is_enabled(VendorId::Grok));
6219    }
6220
6221    #[test]
6222    fn enable_vendors_in_keeps_comments_and_appends_the_new_section() {
6223        let dir = tempfile::TempDir::new().unwrap();
6224        let path = dir.path().join("config.toml");
6225        let original = "# my settings
6226[zai]
6227api_key = \"x\" # keep
6228enabled = false
6229";
6230        std::fs::write(&path, original).unwrap();
6231
6232        enable_vendors_in(&path, &[VendorId::Grok, VendorId::OpenCodeGo]).unwrap();
6233
6234        let text = std::fs::read_to_string(&path).unwrap();
6235        assert!(
6236            text.starts_with(
6237                "# my settings
6238"
6239            ),
6240            "{text}"
6241        );
6242        assert!(
6243            text.contains(
6244                "api_key = \"x\" # keep
6245"
6246            ),
6247            "{text}"
6248        );
6249        assert!(
6250            text.contains(
6251                "[grok]
6252enabled = true
6253"
6254            ),
6255            "{text}"
6256        );
6257        assert!(
6258            text.contains(
6259                "[opencode-go]
6260enabled = true
6261"
6262            ),
6263            "{text}"
6264        );
6265        let config = Config::load_from(&path).unwrap();
6266        assert!(
6267            !config.is_enabled(VendorId::Zai),
6268            "never widens to false, never flips others"
6269        );
6270        assert!(config.is_enabled(VendorId::Grok));
6271        assert!(config.is_enabled(VendorId::OpenCodeGo));
6272    }
6273
6274    #[test]
6275    fn enable_vendors_in_leaves_an_explicit_false_alone() {
6276        let dir = tempfile::TempDir::new().unwrap();
6277        let path = dir.path().join("config.toml");
6278        let original = "[grok]
6279enabled = false # off
6280api_key = \"k\"
6281";
6282        std::fs::write(&path, original).unwrap();
6283
6284        // `enabled = false` in the file is the user having said no. Only the
6285        // automatic path goes through here — the Settings overlay writes with
6286        // `set_bool` — so nothing a person does by hand is blocked by this.
6287        let written = enable_vendors_in(&path, &[VendorId::Grok]).unwrap();
6288
6289        assert!(written.is_empty(), "{written:?}");
6290        assert_eq!(
6291            std::fs::read_to_string(&path).unwrap(),
6292            original,
6293            "the file must not be rewritten at all"
6294        );
6295    }
6296
6297    #[test]
6298    fn enable_vendors_in_adds_the_switch_when_the_config_never_mentioned_it() {
6299        let dir = tempfile::TempDir::new().unwrap();
6300        let path = dir.path().join("config.toml");
6301        std::fs::write(&path, "[grok]\napi_key = \"k\"\n").unwrap();
6302
6303        let written = enable_vendors_in(&path, &[VendorId::Grok]).unwrap();
6304
6305        assert_eq!(written, vec![VendorId::Grok]);
6306        assert!(Config::load_from(&path).unwrap().is_enabled(VendorId::Grok));
6307    }
6308
6309    #[test]
6310    fn enable_vendors_in_is_textually_idempotent() {
6311        let dir = tempfile::TempDir::new().unwrap();
6312        let path = dir.path().join("config.toml");
6313        let original = "[grok]
6314enabled = true
6315
6316# trailing
6317";
6318        std::fs::write(&path, original).unwrap();
6319        let before = std::fs::metadata(&path).unwrap().modified().unwrap();
6320
6321        enable_vendors_in(&path, &[VendorId::Grok]).unwrap();
6322
6323        assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
6324        assert_eq!(
6325            std::fs::metadata(&path).unwrap().modified().unwrap(),
6326            before,
6327            "an unchanged document must not be rewritten"
6328        );
6329    }
6330
6331    #[test]
6332    fn enable_vendors_in_with_nothing_to_enable_leaves_a_missing_file_missing() {
6333        let dir = tempfile::TempDir::new().unwrap();
6334        let path = dir.path().join("config.toml");
6335
6336        enable_vendors_in(&path, &[]).unwrap();
6337
6338        assert!(!path.exists());
6339    }
6340}