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//! [kimi]       enabled = false
12//! [[custom]]   id = "mytool"   # user-defined HTTP provider, static token
13//! ```
14//!
15//! Every field is optional with sensible defaults — missing config file is
16//! treated as "use defaults". API keys are read from env vars (the relevant
17//! `*_api_key_env` field lets the user override which env var name).
18
19use std::collections::{BTreeMap, HashSet};
20use std::path::{Path, PathBuf};
21
22#[cfg(unix)]
23use std::os::unix::fs::{MetadataExt, PermissionsExt};
24
25use serde::{Deserialize, Serialize};
26
27use crate::anthropic::creds::CredsTarget;
28use crate::cache::Cache;
29use crate::error::{AppError, Result};
30use crate::vendor::VendorId;
31
32/// A misspelled section name is silently ignored without this: `[openrouer]`
33/// leaves OpenRouter on its defaults and the user sees the wrong vendor set
34/// with no diagnostic. Denying unknown keys is deliberately applied at the
35/// *section* level only — the set of sections is small and stable, whereas
36/// denying unknown keys inside every section would hard-fail configs that
37/// carry a field from a future or removed version.
38#[derive(Debug, Clone, Default, Deserialize, Serialize)]
39#[serde(default, deny_unknown_fields)]
40pub struct Config {
41    pub ui: UiConfig,
42    pub tray: TrayConfig,
43    pub context: ContextConfig,
44    pub anthropic: AnthropicConfig,
45    pub anthropic_api: AnthropicApiConfig,
46    pub openai: OpenAiConfig,
47    pub copilot: CopilotConfig,
48    pub zai: ZaiConfig,
49    pub openrouter: OpenRouterConfig,
50    pub deepseek: DeepseekConfig,
51    pub kimi: KimiConfig,
52    pub kilo: KiloConfig,
53    pub novita: NovitaConfig,
54    pub moonshot: MoonshotConfig,
55    pub grok: GrokConfig,
56    pub supergrok: SuperGrokConfig,
57    pub antigravity: AntigravityConfig,
58    pub cursor: CursorConfig,
59    pub minimax: MinimaxConfig,
60    pub kiro: KiroConfig,
61    pub nous: NousConfig,
62    #[serde(rename = "opencode-go")]
63    pub opencode_go: OpenCodeGoConfig,
64    pub commandcode: CommandCodeConfig,
65    pub ollama: OllamaConfig,
66    /// User-defined providers, one `[[custom]]` table each.
67    pub custom: Vec<CustomProviderConfig>,
68}
69
70/// UI / dispatch preferences. Currently just `primary` — which vendor the
71/// widget shows when `--vendor` is omitted, and which TUI tab is selected
72/// at startup.
73#[derive(Debug, Clone, Default, Deserialize, Serialize)]
74#[serde(default)]
75pub struct UiConfig {
76    /// `None` → fall back to anthropic for backward compatibility.
77    pub primary: Option<VendorId>,
78    /// Which vendors the Overview shows (the TUI's first tab and the macOS
79    /// menu-bar's top section), in this order. `None` → every enabled vendor,
80    /// in the canonical order.
81    pub overview_vendors: Option<Vec<VendorId>>,
82    /// Layout style for vendor navigation in the TUI: sidebar | navbar | none.
83    pub vendor_box: Option<VendorBoxStyle>,
84}
85
86impl UiConfig {
87    pub fn vendor_box(&self) -> VendorBoxStyle {
88        self.vendor_box.unwrap_or_default()
89    }
90}
91
92/// Windows tray popover preferences the host process needs before the
93/// WebView is up: the global shortcut it registers, how often it polls and
94/// how it treats new releases. Screen-only preferences (theme, density, time
95/// format) live in the popover's own storage instead.
96#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
97#[serde(default)]
98pub struct TrayConfig {
99    /// Global shortcut that toggles the popover, in the canonical
100    /// "Ctrl+Shift+U" spelling. `None` → no shortcut registered.
101    pub shortcut: Option<String>,
102    /// How often the tray re-reads every provider, in minutes: 1, 5 or 10.
103    /// The footer's Refresh is always immediate. `None` → 5.
104    pub refresh_minutes: Option<u64>,
105    /// What the tray does when a newer release is published.
106    pub updates: Option<UpdateMode>,
107}
108
109/// Poll intervals the tray offers, in minutes. The provider cache TTL is
110/// 60 s regardless; this only decides how often the tray asks.
111pub const TRAY_REFRESH_MINUTES: [u64; 3] = [1, 5, 10];
112const DEFAULT_TRAY_REFRESH_MINUTES: u64 = 5;
113
114impl TrayConfig {
115    pub fn refresh_minutes(&self) -> u64 {
116        self.refresh_minutes.unwrap_or(DEFAULT_TRAY_REFRESH_MINUTES)
117    }
118
119    pub fn updates(&self) -> UpdateMode {
120        self.updates.unwrap_or_default()
121    }
122}
123
124/// How the tray handles a newer release: install it unattended, show a
125/// banner with an Install button, or never check in the background.
126#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
127#[serde(rename_all = "lowercase")]
128pub enum UpdateMode {
129    Auto,
130    #[default]
131    Notify,
132    Off,
133}
134
135impl UpdateMode {
136    pub fn as_str(self) -> &'static str {
137        match self {
138            Self::Auto => "auto",
139            Self::Notify => "notify",
140            Self::Off => "off",
141        }
142    }
143
144    pub fn parse(text: &str) -> Option<Self> {
145        match text.trim().to_ascii_lowercase().as_str() {
146            "auto" => Some(Self::Auto),
147            "notify" => Some(Self::Notify),
148            "off" => Some(Self::Off),
149            _ => None,
150        }
151    }
152}
153
154/// Presentation style of the TUI vendor navigation box.
155#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
156#[serde(rename_all = "lowercase")]
157pub enum VendorBoxStyle {
158    /// Vertical sidebar box on wide terminals; falls back to top navbar on narrow terminals.
159    #[default]
160    Sidebar,
161    /// Horizontal navbar strip above the dashboard detail panel.
162    Navbar,
163    /// Completely hide vendor navigation (dashboards expand to fill full width).
164    None,
165}
166
167/// Where the context view docks in the dashboard body. `v` cycles it while the
168/// overlay is open; the config value is what it opens with.
169#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
170#[serde(rename_all = "lowercase")]
171pub enum ContextLayout {
172    /// Takes the whole body, the way a vendor panel does.
173    #[default]
174    Full,
175    /// Beside the dashboard.
176    Split,
177    /// Below the dashboard.
178    Bottom,
179}
180
181impl ContextLayout {
182    pub fn next(self) -> Self {
183        match self {
184            ContextLayout::Full => ContextLayout::Split,
185            ContextLayout::Split => ContextLayout::Bottom,
186            ContextLayout::Bottom => ContextLayout::Full,
187        }
188    }
189
190    pub fn label(self) -> &'static str {
191        match self {
192            ContextLayout::Full => "full",
193            ContextLayout::Split => "split",
194            ContextLayout::Bottom => "bottom",
195        }
196    }
197}
198
199/// Optional local Claude Code context-window monitor. This is deliberately
200/// separate from vendors: sessions are discovered from local transcripts and
201/// change while the TUI is running, whereas vendor tabs are config-declared
202/// account identities.
203#[derive(Debug, Clone, Default, Deserialize, Serialize)]
204#[serde(default)]
205pub struct ContextConfig {
206    /// Keep the filesystem scanner completely dormant unless explicitly
207    /// enabled. The `c` key and its footer hint are hidden while disabled.
208    pub enabled: bool,
209    /// Override Claude Code's normal `~/.claude/projects` transcript root.
210    pub projects_path: Option<PathBuf>,
211    /// Optional fallback denominator. When absent, sessions without an exact
212    /// model override show their input-token count without inventing a %.
213    pub context_window_tokens: Option<u64>,
214    /// Exact Claude model id -> context-window size. This takes precedence
215    /// over `context_window_tokens`, which keeps mixed 200K/1M histories safe.
216    pub model_context_window_tokens: BTreeMap<String, u64>,
217    /// Where the view opens: full | split | bottom.
218    pub layout: ContextLayout,
219}
220
221impl ContextConfig {
222    pub fn window_tokens_for(&self, model: Option<&str>) -> Option<u64> {
223        model
224            .and_then(|model| self.model_context_window_tokens.get(model).copied())
225            .filter(|tokens| *tokens > 0)
226            .or_else(|| self.context_window_tokens.filter(|tokens| *tokens > 0))
227    }
228}
229
230#[derive(Debug, Clone, Deserialize, Serialize)]
231#[serde(default)]
232pub struct AnthropicConfig {
233    pub enabled: bool,
234    /// Override the credentials file path (defaults to `~/.claude/.credentials.json`).
235    /// This is the *default* account; extra subscriptions go in `accounts`.
236    pub credentials_path: Option<PathBuf>,
237    /// Extra Anthropic accounts beyond the default, each selected on the CLI
238    /// with `--account <label>` (issue #14). Empty by default, so existing
239    /// single-account configs are byte-for-byte unchanged.
240    pub accounts: Vec<AnthropicAccount>,
241    /// Directory to auto-discover extra accounts from, in Claude Code's own
242    /// `CLAUDE_CONFIG_DIR` layout: each immediate subdirectory becomes an
243    /// account labeled by the subdirectory name. The credentials may live in
244    /// that directory's `.credentials.json` or in the macOS Keychain, so
245    /// discovery intentionally does not probe for the credentials file.
246    /// Merged with `accounts` (explicit wins on a label clash); each is
247    /// refreshed independently.
248    pub accounts_dir: Option<PathBuf>,
249    /// Whether the default (unnamed) Claude account gets its own tab. Defaults
250    /// to `true` for back-compat. Set `false` when every account is managed
251    /// explicitly (via `accounts`/`accounts_dir`) so the ambient
252    /// Keychain/`~/.claude` login doesn't add a redundant "Claude" tab. Ignored
253    /// when there are no named accounts, so Anthropic never loses its only tab.
254    pub show_default_account: bool,
255    /// Where the Claude **Desktop app**'s saved account profiles live. Defaults
256    /// to `~/.claude-acc/profiles`, the store claude-acc
257    /// (<https://github.com/ohmaseclaro/claude-acc>) creates — `account switch`
258    /// reads and writes that layout so the two tools stay interchangeable.
259    /// Unrelated to `accounts_dir`, which is the `claude` CLI's own accounts.
260    pub desktop_profiles_dir: Option<PathBuf>,
261}
262
263impl Default for AnthropicConfig {
264    fn default() -> Self {
265        Self {
266            enabled: true,
267            credentials_path: None,
268            accounts: Vec::new(),
269            accounts_dir: None,
270            show_default_account: true,
271            desktop_profiles_dir: None,
272        }
273    }
274}
275
276/// One extra Anthropic account beyond the default (issue #14). The default
277/// account stays the singular `[anthropic] credentials_path`; each entry here
278/// is an additional subscription selected on the CLI with `--account <label>`.
279///
280/// ```toml
281/// [[anthropic.accounts]]
282/// label = "work"
283/// credentials_path = "~/.config/ai-usagebar/accounts/work/.credentials.json"
284/// ```
285#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
286pub struct AnthropicAccount {
287    /// Stable name used on the CLI (`--account <label>`) and as the cache
288    /// subdir (`~/.cache/ai-usagebar/anthropic/<label>`).
289    pub label: String,
290    /// OAuth credentials file for this account (same JSON shape Claude Code
291    /// writes). Token refreshes are written back here, so each account keeps
292    /// itself alive independently.
293    pub credentials_path: PathBuf,
294}
295
296impl AnthropicAccount {
297    /// The `CLAUDE_CONFIG_DIR` this account occupies — the credential file's
298    /// own directory. Claude Code hashes exactly this path for the account's
299    /// Keychain item, so it is also the account's identity for
300    /// [`crate::anthropic::keychain`].
301    pub fn config_dir(&self) -> PathBuf {
302        self.credentials_path
303            .parent()
304            .map_or_else(|| self.credentials_path.clone(), Path::to_path_buf)
305    }
306}
307
308impl AnthropicConfig {
309    /// Every extra account: the explicit `[[anthropic.accounts]]` entries plus
310    /// any auto-discovered under [`accounts_dir`](AnthropicConfig::accounts_dir).
311    /// Explicit entries take precedence on a label clash. This is what tabs and
312    /// `--account` enumerate, so a discovered account behaves exactly like a
313    /// hand-written one (own cache subdir, independent refresh).
314    pub fn all_accounts(&self) -> Vec<AnthropicAccount> {
315        let mut out = self.accounts.clone();
316        if let Some(dir) = &self.accounts_dir {
317            for acct in discover_accounts(dir) {
318                if !out.iter().any(|a| a.label == acct.label) {
319                    out.push(acct);
320                }
321            }
322        }
323        out
324    }
325
326    /// Find an extra account by label (explicit or discovered), or error listing
327    /// the known labels so a typo fails loudly instead of silently hitting the
328    /// default. Returns an owned account because discovered entries are
329    /// synthesized, not stored.
330    pub fn account(&self, label: &str) -> Result<AnthropicAccount> {
331        validate_account_label(label)?;
332        let all = self.all_accounts();
333        all.iter().find(|a| a.label == label).cloned().ok_or_else(|| {
334            let known: Vec<&str> = all.iter().map(|a| a.label.as_str()).collect();
335            AppError::Credentials(format!(
336                "anthropic account {label:?} not found in [[anthropic.accounts]] or accounts_dir; \
337                 known labels: {known:?}"
338            ))
339        })
340    }
341
342    /// Resolve a named account to the credentials target + isolated cache it
343    /// fetches through: [`CredsTarget::Named`], which on macOS prefers the
344    /// Keychain item scoped to the file's own directory (that is where
345    /// `CLAUDE_CONFIG_DIR=<dir> claude` actually writes) and falls back to
346    /// the file elsewhere — never a *different* account's item, since the
347    /// hash is per-directory, so issue #15's cross-account concern doesn't
348    /// apply. Plus an `anthropic/<label>` cache subdir. Shared by the widget
349    /// (`--account`) and the TUI's per-account tab (#14, #17) so both resolve
350    /// accounts identically; the widget layers its `--cache-dir` override on
351    /// top of the cache returned here.
352    pub fn account_target(&self, label: &str) -> Result<(CredsTarget, Cache)> {
353        let active = crate::anthropic::cli_account::home_claude_json()
354            .ok()
355            .and_then(|path| {
356                crate::anthropic::cli_account::resolve_active_label(&path, &self.all_accounts())
357            });
358        self.account_target_with(label, active.as_deref())
359    }
360
361    /// The pure half of [`account_target`](AnthropicConfig::account_target),
362    /// with "which account the `claude` CLI is signed into" injected — the same
363    /// shape as `Cli::resolve_vendor_with`.
364    ///
365    /// When `label` *is* the live CLI login, its credential has been moved into
366    /// the default slot and removed from its named slot. Reading the default
367    /// one keeps exactly one live lineage, so a refresh here cannot invalidate
368    /// the credential `claude` is using (or the other way round). The cache directory
369    /// is unchanged either way, so the tab keeps its identity and its cached
370    /// usage across a switch.
371    pub fn account_target_with(
372        &self,
373        label: &str,
374        cli_active: Option<&str>,
375    ) -> Result<(CredsTarget, Cache)> {
376        let account = self.account(label)?;
377        let cache = Cache::for_vendor_account("anthropic", label)?;
378        if cli_active == Some(label) {
379            return Ok((
380                CredsTarget::Default(crate::anthropic::creds::default_path()?),
381                cache,
382            ));
383        }
384        Ok((
385            CredsTarget::Named {
386                config_dir: account.config_dir(),
387                path: account.credentials_path,
388            },
389            cache,
390        ))
391    }
392}
393
394/// The label doubles as a cache subdirectory name
395/// (`~/.cache/ai-usagebar/anthropic/<label>/`), which nests inside the default
396/// account's cache dir — so path separators, control characters, or reserved
397/// cache sidecar names would escape, spoof terminal output, or collide with the
398/// cache layout (`usage.json`, `.stale`, …).
399pub fn validate_account_label(label: &str) -> Result<()> {
400    validate_account_label_for("anthropic", label)
401}
402
403fn validate_account_label_for(vendor: &str, label: &str) -> Result<()> {
404    const RESERVED: [&str; 4] = ["usage.json", ".stale", ".last_error", ".fetch.lock"];
405    let bad = label.is_empty()
406        || label == "."
407        || label == ".."
408        || label.contains(['/', '\\'])
409        || label.contains(':')
410        || label.chars().any(char::is_control)
411        || RESERVED.contains(&label);
412    if bad {
413        return Err(AppError::Credentials(format!(
414            "invalid {vendor} account label {label:?}: must be a non-empty name \
415             without path separators, drive prefixes, control characters, or reserved cache names"
416        )));
417    }
418    Ok(())
419}
420
421/// Discover accounts under `accounts_dir` in the `CLAUDE_CONFIG_DIR` layout:
422/// each immediate subdirectory becomes an account labeled by the subdirectory
423/// name. Best-effort: an unreadable directory or unusable label is skipped
424/// silently rather than failing the whole config — discovery is convenience,
425/// while an explicit `[[anthropic.accounts]]` entry stays authoritative. The
426/// fetch path resolves credentials from either `.credentials.json` or the macOS
427/// Keychain. Sorted by label so the tab order is stable across runs.
428fn discover_accounts(accounts_dir: &std::path::Path) -> Vec<AnthropicAccount> {
429    let Ok(entries) = std::fs::read_dir(accounts_dir) else {
430        return Vec::new();
431    };
432    let mut found: Vec<AnthropicAccount> = entries
433        .flatten()
434        .filter_map(|entry| {
435            let path = entry.path();
436            if !path.is_dir() {
437                return None;
438            }
439            let label = path.file_name()?.to_str()?.to_string();
440            validate_account_label(&label).ok()?;
441            Some(AnthropicAccount {
442                label,
443                credentials_path: path.join(".credentials.json"),
444            })
445        })
446        .collect();
447    found.sort_by(|a, b| a.label.cmp(&b.label));
448    found
449}
450
451/// Render a path with `$HOME` collapsed back to `~`, matching the style the docs
452/// and existing `[[anthropic.accounts]]` entries use. Pure so it's testable;
453/// paths outside home are returned verbatim.
454pub fn tildify(path: &Path, home: &Path) -> String {
455    path.strip_prefix(home)
456        .map(|rest| {
457            let rendered = rest.display().to_string();
458            // Config paths use the same portable `~/...` spelling on every
459            // platform. A Windows `~\...` would not be expanded by the loader.
460            #[cfg(windows)]
461            let rendered = rendered.replace('\\', "/");
462            format!("~/{rendered}")
463        })
464        .unwrap_or_else(|_| path.display().to_string())
465}
466
467/// Where a newly-registered account's credentials file lives by default: next
468/// to `config.toml`, under `accounts/<label>/.credentials.json`. Returns the
469/// absolute path (for `mkdir`) — tilde-render it with [`tildify`] for display
470/// and for the value written into config.
471pub fn default_account_credentials_path(config_path: &Path, label: &str) -> PathBuf {
472    let base = config_path.parent().unwrap_or_else(|| Path::new("."));
473    base.join("accounts").join(label).join(".credentials.json")
474}
475
476/// Append a `[[anthropic.accounts]]` entry to a parsed config document, in
477/// place. Pure over a `toml_edit` document so the validation, duplicate check,
478/// and formatting are testable without disk. Preserves the rest of the file
479/// (comments, key order, other sections) — only the new array-of-tables entry
480/// is added. Errors on an invalid label or a label that already exists.
481pub fn add_anthropic_account_to_doc(
482    doc: &mut toml_edit::DocumentMut,
483    label: &str,
484    credentials_path: &str,
485) -> Result<()> {
486    use toml_edit::{Item, Table, value};
487
488    validate_account_label(label)?;
489
490    let anthropic = doc
491        .entry("anthropic")
492        .or_insert_with(|| Item::Table(Table::new()));
493    let anthropic = anthropic
494        .as_table_mut()
495        .ok_or_else(|| AppError::Other("[anthropic] in config.toml is not a table".into()))?;
496
497    let accounts = anthropic
498        .entry("accounts")
499        .or_insert_with(|| Item::ArrayOfTables(toml_edit::ArrayOfTables::new()));
500    let accounts = accounts.as_array_of_tables_mut().ok_or_else(|| {
501        AppError::Other("[[anthropic.accounts]] in config.toml is not an array of tables".into())
502    })?;
503
504    let exists = accounts
505        .iter()
506        .any(|t| t.get("label").and_then(Item::as_str) == Some(label));
507    if exists {
508        return Err(AppError::Credentials(format!(
509            "anthropic account {label:?} already exists in config.toml"
510        )));
511    }
512
513    let mut table = Table::new();
514    table["label"] = value(label);
515    table["credentials_path"] = value(credentials_path);
516    accounts.push(table);
517    Ok(())
518}
519
520/// Set or update a boolean field in a TOML section, preserving comments and
521/// formatting of unaffected nodes. Shared by the Settings overlay and
522/// [`enable_vendors_in`] so both writers shape `enabled = true` identically.
523pub(crate) fn set_bool(
524    doc: &mut toml_edit::DocumentMut,
525    section: &str,
526    key: &str,
527    new_value: bool,
528) -> Result<()> {
529    let table = doc
530        .entry(section)
531        .or_insert_with(toml_edit::table)
532        .as_table_mut()
533        .ok_or_else(|| AppError::Other(format!("config.toml: [{section}] is not a table")))?;
534
535    if let Some(item) = table.get_mut(key)
536        && let Some(v) = item.as_value_mut()
537    {
538        // Keep a trailing `# comment` on the line being rewritten: the value
539        // is the only thing that changed, and the note beside it is the
540        // user's.
541        let suffix = v.decor().suffix().cloned();
542        *v = toml_edit::Value::from(new_value);
543        v.decor_mut().set_prefix(" ");
544        if let Some(suffix) = suffix {
545            v.decor_mut().set_suffix(suffix);
546        }
547        return Ok(());
548    }
549    table.insert(key, toml_edit::value(new_value));
550    Ok(())
551}
552
553/// Set, replace or remove a scalar field in a TOML section, preserving
554/// comments and formatting of unaffected nodes. `None` removes the key so a
555/// cleared preference does not linger as an empty string. The value keeps
556/// its own TOML type on disk — an integer preference such as
557/// `refresh_minutes` must not be quoted, or `Config::load_from` rejects it.
558pub(crate) fn set_value(
559    doc: &mut toml_edit::DocumentMut,
560    section: &str,
561    key: &str,
562    new_value: Option<toml_edit::Value>,
563) -> Result<()> {
564    let table = doc
565        .entry(section)
566        .or_insert_with(toml_edit::table)
567        .as_table_mut()
568        .ok_or_else(|| AppError::Other(format!("config.toml: [{section}] is not a table")))?;
569
570    let Some(mut new_value) = new_value else {
571        table.remove(key);
572        return Ok(());
573    };
574    if let Some(item) = table.get_mut(key)
575        && let Some(v) = item.as_value_mut()
576    {
577        let suffix = v.decor().suffix().cloned();
578        new_value.decor_mut().set_prefix(" ");
579        if let Some(suffix) = suffix {
580            new_value.decor_mut().set_suffix(suffix);
581        }
582        *v = new_value;
583        return Ok(());
584    }
585    table.insert(key, toml_edit::Item::Value(new_value));
586    Ok(())
587}
588
589/// Write one `[tray]` preference into the config at `path`, creating the
590/// file when it doesn't exist and leaving every other line as it was.
591/// `None` removes the key. The value keeps the TOML type it is given
592/// (`"notify"` stays a string, `5` stays an integer). The tray host is the
593/// only writer.
594pub fn set_tray_value(path: &Path, key: &str, value: Option<toml_edit::Value>) -> Result<()> {
595    let mut doc = read_config_document(path)?;
596    let before = doc.to_string();
597    set_value(&mut doc, "tray", key, value)?;
598    if doc.to_string() == before {
599        return Ok(());
600    }
601    write_config_document(path, &doc)
602}
603
604/// Read `path` into a `toml_edit` document with comments intact. A missing
605/// file is an empty document, so a writer can create the config from nothing;
606/// any other I/O failure or a parse error is reported rather than clobbered.
607pub(crate) fn read_config_document(path: &Path) -> Result<toml_edit::DocumentMut> {
608    let original = match std::fs::read_to_string(path) {
609        Ok(contents) => contents,
610        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
611        Err(error) => return Err(AppError::io_at(path, error)),
612    };
613    if original.trim().is_empty() {
614        return Ok(toml_edit::DocumentMut::new());
615    }
616    original.parse().map_err(|e: toml_edit::TomlError| {
617        AppError::Other(format!("config.toml not parseable: {e}"))
618    })
619}
620
621/// Persist an edited config document: parent dir created, atomic
622/// tempfile-and-rename write, and `chmod 600` on Unix because the file may
623/// carry inline credentials. The one write path for every config editor.
624pub(crate) fn write_config_document(path: &Path, doc: &toml_edit::DocumentMut) -> Result<()> {
625    let bytes = doc.to_string();
626    crate::cache::atomic_write(path, bytes.as_bytes())?;
627
628    #[cfg(unix)]
629    {
630        if let Ok(meta) = std::fs::metadata(path) {
631            let mut perms = meta.permissions();
632            perms.set_mode(0o600);
633            let _ = std::fs::set_permissions(path, perms);
634        }
635    }
636    Ok(())
637}
638
639/// Flip `enabled = true` for each vendor's section in the config at `path`,
640/// creating the file when it doesn't exist and leaving every other line —
641/// comments, keys, unrelated sections — exactly as it was. Never writes
642/// `false`: `config.toml` stays the user's source of truth and this only ever
643/// widens it. A document that comes out textually unchanged (every vendor
644/// already enabled) is not rewritten, so an idempotent call doesn't touch the
645/// file's mtime or race a concurrent editor.
646pub fn enable_vendors_in(path: &Path, vendors: &[VendorId]) -> Result<Vec<VendorId>> {
647    let mut doc = read_config_document(path)?;
648    let before = doc.to_string();
649    let written: Vec<VendorId> = vendors
650        .iter()
651        .copied()
652        .filter(|vendor| !is_explicitly_disabled(&doc, *vendor))
653        .collect();
654    for vendor in &written {
655        set_bool(&mut doc, vendor.config_section(), "enabled", true)?;
656    }
657    if doc.to_string() == before {
658        return Ok(written);
659    }
660    write_config_document(path, &doc)?;
661    Ok(written)
662}
663
664/// Whether the config *says* `enabled = false` for this vendor, as opposed to
665/// not mentioning it.
666///
667/// This is the durable record of a user having turned a vendor off. `detect`
668/// also keeps a set of vendors it has already considered, but that lives in the
669/// cache directory, which is by convention safe to delete — so it cannot be the
670/// only thing standing between "the user opted out" and re-enabling a provider
671/// (and resuming requests to it) behind their back. The config file is the one
672/// place that outlives a cache wipe, so the explicit `false` is honored here,
673/// at the write, where no caller can route around it.
674fn is_explicitly_disabled(doc: &toml_edit::DocumentMut, vendor: VendorId) -> bool {
675    doc.get(vendor.config_section())
676        .and_then(|section| section.get("enabled"))
677        .and_then(|enabled| enabled.as_bool())
678        == Some(false)
679}
680
681#[derive(Debug, Clone, Deserialize, Serialize)]
682#[serde(default)]
683pub struct OpenAiConfig {
684    pub enabled: bool,
685    /// Override the Codex auth file path (defaults to `~/.codex/auth.json`).
686    pub codex_auth_path: Option<PathBuf>,
687    /// Extra Codex logins, each its own `auth.json`. Same shape as
688    /// [`AnthropicAccount`] and for the same reason: Codex is an OAuth vendor,
689    /// so an account *is* a credential file, and `openai::creds::write_back`
690    /// refreshes into whichever one it read.
691    #[serde(default)]
692    pub accounts: Vec<OpenAiAccount>,
693    /// Reserved, and inert: names the env var an API-key-only path *would*
694    /// read (admin key → `/v1/organization/costs`). Nothing consumes it —
695    /// OpenAI usage comes solely from Codex OAuth. Kept because that path is
696    /// still intended, not for back-compat: `[openai]` doesn't deny unknown
697    /// fields, so an existing `admin_key_env` would load either way. See
698    /// `config.example.toml`, which ships it commented out so nobody sets it
699    /// expecting an effect.
700    pub admin_key_env: String,
701}
702
703/// One extra Codex login.
704///
705/// ```toml
706/// [[openai.accounts]]
707/// label = "work"
708/// codex_auth_path = "~/.config/ai-usagebar/accounts/work-codex/auth.json"
709/// ```
710///
711/// A second login is made with `CODEX_HOME=~/.codex-work codex login`; point
712/// `codex_auth_path` at the `auth.json` it writes.
713#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
714pub struct OpenAiAccount {
715    /// Stable name used on the CLI (`--account <label>`) and as the cache
716    /// subdir (`~/.cache/ai-usagebar/openai/<label>`).
717    pub label: String,
718    /// Codex OAuth file for this account. Refreshed tokens are written back
719    /// here, so each account keeps itself alive independently.
720    pub codex_auth_path: PathBuf,
721}
722
723impl OpenAiConfig {
724    /// The auth file for `label`, or the singular/default one when `label` is
725    /// `None`. An unknown label is an error rather than a silent fall back to
726    /// the default account, which would report the wrong login's usage.
727    pub fn resolve_auth_path(&self, label: Option<&str>) -> Result<PathBuf> {
728        let Some(label) = label else {
729            return match &self.codex_auth_path {
730                Some(path) => Ok(path.clone()),
731                None => crate::openai::creds::default_path(),
732            };
733        };
734        self.accounts
735            .iter()
736            .find(|account| account.label == label)
737            .map(|account| account.codex_auth_path.clone())
738            .ok_or_else(|| {
739                AppError::Credentials(format!(
740                    "no OpenAI account named {label:?}. Add it under \
741                     [[openai.accounts]], or drop --account to use the default login."
742                ))
743            })
744    }
745}
746
747impl Default for OpenAiConfig {
748    fn default() -> Self {
749        Self {
750            enabled: true,
751            codex_auth_path: None,
752            accounts: Vec::new(),
753            admin_key_env: "OPENAI_ADMIN_KEY".to_string(),
754        }
755    }
756}
757
758/// GitHub Copilot quota from the private endpoint used by VS Code. The token
759/// comes from an explicit environment override or the official GitHub CLI;
760/// this app never reads, copies, or writes GitHub credential stores.
761#[derive(Debug, Clone, Default, Deserialize, Serialize)]
762#[serde(default)]
763pub struct CopilotConfig {
764    pub enabled: bool,
765    /// Path to the official GitHub CLI. Unset looks `gh` up on `PATH`, which
766    /// is how `gh` is normally installed; set it to pin the executable.
767    pub gh_binary: Option<PathBuf>,
768}
769
770impl CopilotConfig {
771    pub fn resolve_token(&self) -> Result<String> {
772        self.resolve_token_with(
773            |name| std::env::var_os(name),
774            &crate::copilot::credentials::SystemGhAuthTokenRunner,
775        )
776    }
777
778    fn resolve_token_with(
779        &self,
780        environment: impl Fn(&str) -> Option<std::ffi::OsString>,
781        runner: &impl crate::copilot::credentials::GhAuthTokenRunner,
782    ) -> Result<String> {
783        if let Some(value) = environment("GITHUB_COPILOT_TOKEN") {
784            let token = value.into_string().map_err(|_| {
785                AppError::Credentials(
786                    "GitHub Copilot: GITHUB_COPILOT_TOKEN is not valid UTF-8.".into(),
787                )
788            })?;
789            if !token.is_empty() {
790                return Ok(token);
791            }
792        }
793        crate::copilot::credentials::resolve_with(runner, self.gh_binary.as_deref())
794    }
795}
796
797#[derive(Debug, Clone, Default, Deserialize, Serialize)]
798#[serde(default)]
799pub struct NousConfig {
800    pub enabled: bool,
801}
802
803#[derive(Debug, Clone, Deserialize, Serialize)]
804#[serde(default)]
805pub struct OpenCodeGoConfig {
806    pub enabled: bool,
807    pub api_key_env: String,
808    pub api_key: Option<String>,
809}
810
811/// Command Code reads the OAuth credential from the official CLI or pi, so it
812/// has no API key of its own. `auth_paths` overrides that search list for a
813/// non-standard install.
814#[derive(Debug, Clone, Default, Deserialize, Serialize)]
815#[serde(default)]
816pub struct CommandCodeConfig {
817    pub enabled: bool,
818    pub auth_paths: Option<Vec<PathBuf>>,
819}
820
821/// Ollama Cloud (`ollama.com/api/usage`). Disabled by default: the local
822/// `ollama` daemon is the product most users reach for, and it has no quota
823/// route to query. Cloud quota is opt-in, with the key taken from
824/// `OLLAMA_API_KEY` (or `api_key` as a fallback for `chmod 600` configs).
825#[derive(Debug, Clone, Deserialize, Serialize)]
826#[serde(default)]
827pub struct OllamaConfig {
828    pub enabled: bool,
829    pub api_key_env: String,
830    pub api_key: Option<String>,
831    /// Display label for the plan row. The API itself does not report a plan
832    /// name; "pro" is what an Ollama Cloud Pro account shows in the UI.
833    pub plan: String,
834}
835
836impl Default for OllamaConfig {
837    fn default() -> Self {
838        Self {
839            enabled: false,
840            api_key_env: "OLLAMA_API_KEY".to_string(),
841            api_key: None,
842            plan: "pro".to_string(),
843        }
844    }
845}
846
847impl Default for OpenCodeGoConfig {
848    fn default() -> Self {
849        Self {
850            enabled: false,
851            api_key_env: "OPENCODE_GO_API_KEY".to_string(),
852            api_key: None,
853        }
854    }
855}
856
857#[derive(Debug, Clone, Deserialize, Serialize)]
858#[serde(default)]
859pub struct ZaiConfig {
860    pub enabled: bool,
861    /// Env var name to read the key from (env wins over `api_key`).
862    pub api_key_env: String,
863    /// Inline key (fallback when the env var is unset). Chmod 600 your
864    /// config file if you put a real key here.
865    pub api_key: Option<String>,
866    /// Optional plan tier label (lite/pro/max) — display-only.
867    pub plan_tier: Option<String>,
868}
869
870impl Default for ZaiConfig {
871    fn default() -> Self {
872        Self {
873            enabled: true,
874            api_key_env: "ZAI_API_KEY".to_string(),
875            api_key: None,
876            plan_tier: None,
877        }
878    }
879}
880
881#[derive(Debug, Clone, Deserialize, Serialize)]
882#[serde(default)]
883pub struct OpenRouterConfig {
884    pub enabled: bool,
885    /// Extra OpenRouter accounts beyond the default key. Each account gets a
886    /// separate aggregate-view entry and cache directory.
887    pub accounts: Vec<OpenRouterAccount>,
888    /// Whether aggregate views include the default (unnamed) key when named
889    /// accounts exist. Ignored when `accounts` is empty so OpenRouter never
890    /// loses its only tab.
891    pub show_default_account: bool,
892    pub api_key_env: String,
893    pub api_key: Option<String>,
894}
895
896impl Default for OpenRouterConfig {
897    fn default() -> Self {
898        Self {
899            enabled: true,
900            accounts: Vec::new(),
901            show_default_account: true,
902            api_key_env: "OPENROUTER_API_KEY".to_string(),
903            api_key: None,
904        }
905    }
906}
907
908/// One named OpenRouter account. The default account continues to use the
909/// singular `api_key_env` / `api_key` fields under `[openrouter]`.
910#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
911pub struct OpenRouterAccount {
912    /// Stable CLI/report label and account-scoped cache subdirectory.
913    pub label: String,
914    /// Optional environment variable containing this account's key.
915    #[serde(default)]
916    pub api_key_env: Option<String>,
917    /// Inline fallback when the account environment variable is unset.
918    #[serde(default)]
919    pub api_key: Option<String>,
920}
921
922impl OpenRouterConfig {
923    /// Find a named account or fail loudly instead of falling back to the
924    /// default key (which would show the wrong account's usage).
925    pub fn account(&self, label: &str) -> Result<&OpenRouterAccount> {
926        validate_account_label_for("openrouter", label)?;
927        self.accounts
928            .iter()
929            .find(|account| account.label == label)
930            .ok_or_else(|| {
931                let known: Vec<&str> = self
932                    .accounts
933                    .iter()
934                    .map(|account| account.label.as_str())
935                    .collect();
936                AppError::Credentials(format!(
937                    "openrouter account {label:?} not found in [[openrouter.accounts]]; \
938                     known labels: {known:?}"
939                ))
940            })
941    }
942
943    /// Resolve either the backward-compatible default key or one named
944    /// account. Configured values are never included in an error message.
945    pub fn resolve_api_key(&self, label: Option<&str>) -> Result<String> {
946        match label {
947            None => resolve_api_key("OpenRouter", &self.api_key_env, self.api_key.as_deref()),
948            Some(label) => {
949                let account = self.account(label)?;
950                resolve_api_key_in_section(
951                    &format!("OpenRouter account {label:?}"),
952                    "[[openrouter.accounts]]",
953                    account.api_key_env.as_deref().unwrap_or(""),
954                    account.api_key.as_deref(),
955                )
956            }
957        }
958    }
959}
960
961#[derive(Debug, Clone, Deserialize, Serialize)]
962#[serde(default)]
963pub struct DeepseekConfig {
964    pub enabled: bool,
965    pub api_key_env: String,
966    pub api_key: Option<String>,
967}
968
969impl Default for DeepseekConfig {
970    fn default() -> Self {
971        Self {
972            enabled: false,
973            api_key_env: "DEEPSEEK_API_KEY".to_string(),
974            api_key: None,
975        }
976    }
977}
978
979#[derive(Debug, Clone, Deserialize, Serialize)]
980#[serde(default)]
981pub struct KimiConfig {
982    pub enabled: bool,
983    pub api_key_env: String,
984    /// Optional: with no key set, the vendor falls back to the Kimi Code CLI's
985    /// own OAuth login, which is what a subscriber already has locally.
986    pub api_key: Option<String>,
987    /// Override for kimi-code's credential file (default
988    /// `~/.kimi-code/credentials/kimi-code.json`), mirroring `[cursor] db_path`
989    /// and `[kiro] db_path`. Useful with a relocated `KIMI_CODE_HOME`.
990    pub credentials_path: Option<PathBuf>,
991    /// `"auto"` follows kimi-code's own install marker (`~/.kimi-code/region`);
992    /// `"cn"` pins `api.kimi.com` / `auth.kimi.com`, `"global"` pins
993    /// `api.kimi.ai` / `auth.kimi.ai`. A token minted by one deployment means
994    /// nothing to the other, so this picks the instance, not a currency.
995    pub region: String,
996}
997
998impl Default for KimiConfig {
999    fn default() -> Self {
1000        Self {
1001            enabled: false,
1002            api_key_env: "KIMI_API_KEY".to_string(),
1003            api_key: None,
1004            credentials_path: None,
1005            region: "auto".to_string(),
1006        }
1007    }
1008}
1009
1010#[derive(Debug, Clone, Deserialize, Serialize)]
1011#[serde(default)]
1012pub struct KiloConfig {
1013    pub enabled: bool,
1014    pub api_key_env: String,
1015    pub api_key: Option<String>,
1016    /// Optional Kilo organization id — scopes the balance to a team via the
1017    /// `x-kilocode-organizationid` header. Omit for the personal balance.
1018    pub organization_id: Option<String>,
1019}
1020
1021impl Default for KiloConfig {
1022    fn default() -> Self {
1023        // Opt-in like DeepSeek: requires an explicit API key, so it defaults to
1024        // disabled and never affects existing installs.
1025        Self {
1026            enabled: false,
1027            api_key_env: "KILO_API_KEY".to_string(),
1028            api_key: None,
1029            organization_id: None,
1030        }
1031    }
1032}
1033
1034#[derive(Debug, Clone, Deserialize, Serialize)]
1035#[serde(default)]
1036pub struct NovitaConfig {
1037    pub enabled: bool,
1038    pub api_key_env: String,
1039    pub api_key: Option<String>,
1040}
1041
1042impl Default for NovitaConfig {
1043    fn default() -> Self {
1044        // Opt-in like DeepSeek/Kilo: needs an explicit API key.
1045        Self {
1046            enabled: false,
1047            api_key_env: "NOVITA_API_KEY".to_string(),
1048            api_key: None,
1049        }
1050    }
1051}
1052
1053#[derive(Debug, Clone, Deserialize, Serialize)]
1054#[serde(default)]
1055pub struct MinimaxConfig {
1056    pub enabled: bool,
1057    pub api_key_env: String,
1058    pub api_key: Option<String>,
1059    /// `"global"` → api.minimax.io; `"cn"` → api.minimaxi.com. Unlike
1060    /// Moonshot's, this does not change the unit — MiniMax reports quota as a
1061    /// percentage either way. It picks the *instance*: a key issued for one
1062    /// host is rejected by the other (`status_code 2049`), so pointing this at
1063    /// the wrong region reads as an invalid key rather than an empty plan.
1064    pub region: String,
1065}
1066
1067impl Default for MinimaxConfig {
1068    fn default() -> Self {
1069        // Opt-in like the other API-key vendors: needs an explicit key.
1070        Self {
1071            enabled: false,
1072            api_key_env: "MINIMAX_API_KEY".to_string(),
1073            api_key: None,
1074            region: "global".to_string(),
1075        }
1076    }
1077}
1078
1079#[derive(Debug, Clone, Deserialize, Serialize)]
1080#[serde(default)]
1081pub struct MoonshotConfig {
1082    pub enabled: bool,
1083    pub api_key_env: String,
1084    pub api_key: Option<String>,
1085    /// `"global"` → api.moonshot.ai (USD); `"cn"` → api.moonshot.cn (CNY).
1086    pub region: String,
1087}
1088
1089impl Default for MoonshotConfig {
1090    fn default() -> Self {
1091        // Opt-in like DeepSeek/Kilo/Novita: needs an explicit API key.
1092        Self {
1093            enabled: false,
1094            api_key_env: "MOONSHOT_API_KEY".to_string(),
1095            api_key: None,
1096            region: "global".to_string(),
1097        }
1098    }
1099}
1100
1101#[derive(Debug, Clone, Deserialize, Serialize)]
1102#[serde(default)]
1103pub struct GrokConfig {
1104    pub enabled: bool,
1105    /// Env var for the xAI **Management** key (distinct from the inference key).
1106    pub api_key_env: String,
1107    pub api_key: Option<String>,
1108    /// Optional team id. When absent, it's auto-resolved from the management
1109    /// key via `/auth/management-keys/validation`.
1110    pub team_id: Option<String>,
1111}
1112
1113impl Default for GrokConfig {
1114    fn default() -> Self {
1115        // Opt-in: needs a management key (and, for prepaid, a team).
1116        Self {
1117            enabled: false,
1118            api_key_env: "XAI_MANAGEMENT_KEY".to_string(),
1119            api_key: None,
1120            team_id: None,
1121        }
1122    }
1123}
1124
1125/// SuperGrok subscription auth — no API key of its own. Billing and banked
1126/// resets use the `key` already in Grok Build's `auth.json` (read-only).
1127/// Login, issuer, proxy, and token rotation stay inside Grok Build.
1128///
1129/// Opt-in like Cursor/Kiro (`enabled` defaults to `false`): it requires a
1130/// separate official executable and signed-in session, so it stays off until
1131/// the user explicitly turns it on.
1132#[derive(Debug, Clone, Deserialize, Serialize)]
1133#[serde(default)]
1134pub struct SuperGrokConfig {
1135    pub enabled: bool,
1136    /// Trusted official Grok Build executable. Defaults to its canonical
1137    /// `$GROK_HOME/bin/grok` (or `~/.grok/bin/grok`) installation path instead
1138    /// of searching PATH, where unrelated programs can share the name.
1139    pub grok_binary: PathBuf,
1140    /// Opaque auth/config files used only to fingerprint the active cache
1141    /// scope. Their contents are never parsed or copied to the cache.
1142    pub auth_path: Option<PathBuf>,
1143    pub config_path: Option<PathBuf>,
1144}
1145
1146impl Default for SuperGrokConfig {
1147    fn default() -> Self {
1148        Self {
1149            enabled: false,
1150            grok_binary: default_grok_binary(),
1151            auth_path: None,
1152            config_path: None,
1153        }
1154    }
1155}
1156
1157fn default_grok_binary() -> PathBuf {
1158    let executable = if cfg!(windows) { "grok.exe" } else { "grok" };
1159    let grok_home = std::env::var_os("GROK_HOME")
1160        .filter(|value| !value.is_empty())
1161        .map(PathBuf::from)
1162        .or_else(|| crate::cache::home_dir().ok().map(|home| home.join(".grok")));
1163    grok_home
1164        .map(|home| home.join("bin").join(executable))
1165        .unwrap_or_else(|| PathBuf::from(executable))
1166}
1167
1168/// Antigravity reads its quota from whichever local Antigravity product is
1169/// running, so it needs no credentials of its own. When no product is up it
1170/// falls back to the Google session Antigravity saved in the OS keyring and
1171/// talks to Cloud Code directly. Renewing that session needs Antigravity's
1172/// OAuth client id and secret, which are not shipped in source: set them here
1173/// (they are public installed-app credentials) or the fallback only lasts as
1174/// long as the saved access token does.
1175#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1176#[serde(default)]
1177pub struct AntigravityConfig {
1178    pub enabled: bool,
1179    /// OAuth client id used to refresh the keyring session.
1180    pub oauth_client_id: Option<String>,
1181    /// OAuth client secret paired with `oauth_client_id`. An
1182    /// installed-app secret is not confidential by Google's definition, but
1183    /// it is still treated as an inline credential for file-permission purposes.
1184    pub oauth_client_secret: Option<String>,
1185}
1186
1187/// Cursor reads its quota through a session token the Cursor IDE already
1188/// wrote to its local `state.vscdb` — no API key, but (unlike Antigravity)
1189/// there is a real on-disk path that can need overriding (e.g. a portable or
1190/// non-default Cursor install), mirroring `openai.codex_auth_path`.
1191///
1192/// Opt-in like DeepSeek/Kilo/etc (`enabled` defaults to `false`, matching
1193/// `bool::default()`): reads an undocumented endpoint via a session token
1194/// scraped from a local IDE file, so it stays off until the user explicitly
1195/// turns it on.
1196#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1197#[serde(default)]
1198pub struct CursorConfig {
1199    pub enabled: bool,
1200    /// Override Cursor's local state database path (defaults to the
1201    /// platform-standard `.../User/globalStorage/state.vscdb` — see
1202    /// `cursor::db::default_db_path`).
1203    pub db_path: Option<PathBuf>,
1204    /// Override the headless `cursor-agent` CLI's own login file (defaults to
1205    /// `.../cursor/auth.json` — see `cursor::db::default_agent_auth_path`).
1206    /// Used as a fallback when `db_path` doesn't exist, so a text-only
1207    /// machine that never runs the desktop IDE still gets usage.
1208    pub agent_auth_path: Option<PathBuf>,
1209}
1210
1211/// Kiro CLI reads its quota through the AWS SSO OIDC session kiro-cli already
1212/// wrote to its own local `data.sqlite3` — no API key, but (like Cursor) a
1213/// real on-disk path that can need overriding.
1214///
1215/// Opt-in like Cursor/DeepSeek/Kilo/etc (`enabled` defaults to `false`):
1216/// calls a reverse-engineered CodeWhisperer endpoint via a session token
1217/// scraped from a local CLI database, so it stays off until the user
1218/// explicitly turns it on.
1219#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1220#[serde(default)]
1221pub struct KiroConfig {
1222    pub enabled: bool,
1223    /// Override kiro-cli's local database path (defaults to the
1224    /// platform-standard `.../kiro-cli/data.sqlite3` — see
1225    /// `kiro::db::default_db_path`).
1226    pub db_path: Option<PathBuf>,
1227}
1228
1229#[derive(Debug, Clone, Deserialize, Serialize)]
1230#[serde(default)]
1231pub struct AnthropicApiConfig {
1232    pub enabled: bool,
1233    /// Env var for the Console **Admin key** (`sk-ant-admin01-…`), distinct from
1234    /// an inference key and from the Claude Code OAuth login.
1235    pub api_key_env: String,
1236    pub api_key: Option<String>,
1237    /// Monthly USD spend limit, used only for the spend-vs-limit % display. The
1238    /// API exposes neither this limit nor the remaining prepaid balance.
1239    pub monthly_limit: Option<f64>,
1240}
1241
1242impl Default for AnthropicApiConfig {
1243    fn default() -> Self {
1244        // Opt-in: needs an explicit Admin key.
1245        Self {
1246            enabled: false,
1247            api_key_env: "ANTHROPIC_ADMIN_KEY".to_string(),
1248            api_key: None,
1249            monthly_limit: None,
1250        }
1251    }
1252}
1253
1254/// A user-defined HTTP provider: one GET with a static token, projected onto
1255/// the shared report shape through RFC 6901 JSON Pointers.
1256///
1257/// Everything a built-in vendor hard-codes is a field here, which is why this
1258/// type validates so much more than the others: a typo in `[deepseek]` hits a
1259/// fixed endpoint and fails loudly, while a typo here quietly sends the user's
1260/// key to the wrong host. The `id` doubles as the cache directory name and the
1261/// `--vendor` selector, so it is held to the character class of the built-in
1262/// slugs.
1263#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
1264#[serde(default, remote = "Self")]
1265pub struct CustomProviderConfig {
1266    /// `[a-z0-9][a-z0-9_-]{0,31}`; unique, and never a built-in vendor's slug.
1267    pub id: String,
1268    /// Display name, 1 to 48 characters. Defaults to `id`.
1269    pub name: String,
1270    /// Exactly three lowercase ASCII letters, unique across built-in vendors
1271    /// and other custom providers — it is the `{vendor_short}` bar tag.
1272    pub short_name: String,
1273    pub enabled: bool,
1274    /// `https://` unless `allow_http`; never carries `user:pass@`.
1275    pub url: String,
1276    pub allow_http: bool,
1277    /// Env var read first; `""` means the inline `api_key` is the only source.
1278    pub api_key_env: String,
1279    pub api_key: Option<String>,
1280    /// The header that carries the key.
1281    pub auth_header: String,
1282    /// Sent as `"<scheme> <key>"`; `""` sends the bare key.
1283    pub auth_scheme: String,
1284    /// Extra non-secret headers.
1285    pub headers: BTreeMap<String, String>,
1286    /// Literal plan label.
1287    pub plan: Option<String>,
1288    /// Pointer to the plan label in the response; wins over `plan`.
1289    pub plan_path: Option<String>,
1290    /// Must be within `10..=3600`.
1291    pub cache_ttl_secs: u64,
1292    pub metrics: Vec<CustomMetricSpec>,
1293    pub texts: Vec<CustomTextSpec>,
1294}
1295
1296impl Default for CustomProviderConfig {
1297    fn default() -> Self {
1298        Self {
1299            id: String::new(),
1300            name: String::new(),
1301            short_name: String::new(),
1302            enabled: false,
1303            url: String::new(),
1304            allow_http: false,
1305            api_key_env: String::new(),
1306            api_key: None,
1307            auth_header: "Authorization".to_string(),
1308            auth_scheme: "Bearer".to_string(),
1309            headers: BTreeMap::new(),
1310            plan: None,
1311            plan_path: None,
1312            cache_ttl_secs: 60,
1313            metrics: Vec::new(),
1314            texts: Vec::new(),
1315        }
1316    }
1317}
1318
1319/// `name` defaults to `id`, which a per-field serde default cannot express (a
1320/// default sees no sibling field). The derive is routed through
1321/// `remote = "Self"` so the fill-in happens here, on every parse path, rather
1322/// than only in `Config::load_from`.
1323impl<'de> Deserialize<'de> for CustomProviderConfig {
1324    fn deserialize<D: serde::Deserializer<'de>>(
1325        deserializer: D,
1326    ) -> std::result::Result<Self, D::Error> {
1327        let mut this = Self::deserialize(deserializer)?;
1328        if this.name.is_empty() {
1329            this.name = this.id.clone();
1330        }
1331        Ok(this)
1332    }
1333}
1334
1335impl Serialize for CustomProviderConfig {
1336    fn serialize<S: serde::Serializer>(
1337        &self,
1338        serializer: S,
1339    ) -> std::result::Result<S::Ok, S::Error> {
1340        Self::serialize(self, serializer)
1341    }
1342}
1343
1344/// One percentage row. Either `percent` alone, or `used` and `limit`
1345/// together — never a mix, so a row cannot show a percentage from one field
1346/// and a footnote from another.
1347#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
1348#[serde(default)]
1349pub struct CustomMetricSpec {
1350    pub label: String,
1351    pub used: Option<String>,
1352    pub limit: Option<String>,
1353    pub percent: Option<String>,
1354    /// Pointer to an RFC 3339 string or a Unix epoch (seconds or milliseconds).
1355    pub resets_at: Option<String>,
1356    /// Window length for pacing, at least 60.
1357    pub window_secs: Option<u64>,
1358}
1359
1360/// One free-text row: a string, number, or boolean at `value`.
1361#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
1362#[serde(default)]
1363pub struct CustomTextSpec {
1364    pub label: String,
1365    pub value: String,
1366}
1367
1368impl CustomProviderConfig {
1369    /// The TOML locator for error messages: `[[custom]] id = "mytool"`.
1370    pub fn section_label(&self) -> String {
1371        format!("[[custom]] id = {:?}", self.id)
1372    }
1373
1374    /// Env var (when `api_key_env` is set) → inline `api_key` → a
1375    /// `Credentials` error that names the section and never the key.
1376    pub fn resolve_api_key(&self) -> Result<String> {
1377        if let Some(key) = optional_api_key(&self.api_key_env, self.api_key.as_deref()) {
1378            return Ok(key);
1379        }
1380        let advice = if self.api_key_env.is_empty() {
1381            "set `api_key`, or name an environment variable in `api_key_env`".to_string()
1382        } else {
1383            format!("export {} or set `api_key`", self.api_key_env)
1384        };
1385        Err(AppError::Credentials(format!(
1386            "custom {}: no API key. Either {advice} under {} in {}.",
1387            self.id,
1388            self.section_label(),
1389            config_path_hint()
1390        )))
1391    }
1392
1393    pub fn cache_ttl(&self) -> std::time::Duration {
1394        std::time::Duration::from_secs(self.cache_ttl_secs)
1395    }
1396
1397    /// Every rule that serde cannot express, each naming the section. Runs
1398    /// for disabled entries too: a broken entry is a broken config, and the
1399    /// day it is enabled is the wrong day to find out.
1400    fn validate(&self, index: usize) -> Result<()> {
1401        if !is_valid_custom_id(&self.id) {
1402            return Err(AppError::Other(format!(
1403                "[[custom]] entry #{}: id {:?} must match [a-z0-9][a-z0-9_-]{{0,31}}",
1404                index + 1,
1405                self.id
1406            )));
1407        }
1408        let section = self.section_label();
1409        let bad = |msg: String| AppError::Other(format!("{section}: {msg}"));
1410
1411        if VendorId::all().iter().any(|v| v.slug() == self.id) {
1412            return Err(bad(format!("id {:?} is a built-in vendor", self.id)));
1413        }
1414        let name_len = self.name.chars().count();
1415        if name_len == 0 || name_len > 48 || self.name.chars().any(char::is_control) {
1416            return Err(bad(
1417                "name must be 1 to 48 characters without control characters".into(),
1418            ));
1419        }
1420        if self.short_name.len() != 3 || !self.short_name.bytes().all(|b| b.is_ascii_lowercase()) {
1421            return Err(bad(format!(
1422                "short_name {:?} must be exactly 3 lowercase ASCII letters",
1423                self.short_name
1424            )));
1425        }
1426        let url = reqwest::Url::parse(&self.url)
1427            .map_err(|_| bad(format!("url {:?} is not a valid URL", self.url)))?;
1428        match url.scheme() {
1429            "https" => {}
1430            "http" if self.allow_http => {}
1431            "http" => {
1432                return Err(bad(
1433                    "url must use https:// (set allow_http = true to permit http://)".into(),
1434                ));
1435            }
1436            other => return Err(bad(format!("url scheme {other:?} is not http or https"))),
1437        }
1438        if !url.username().is_empty() || url.password().is_some() {
1439            return Err(bad("url must not carry credentials (user:pass@)".into()));
1440        }
1441        if url.host_str().is_none() {
1442            return Err(bad("url has no host".into()));
1443        }
1444        if !self.api_key_env.is_empty() && !is_valid_env_var_name(&self.api_key_env) {
1445            return Err(bad(format!(
1446                "api_key_env {:?} is not a valid environment variable name",
1447                self.api_key_env
1448            )));
1449        }
1450        validate_header_name(&section, "auth_header", &self.auth_header)?;
1451        if reqwest::header::HeaderValue::from_str(&format!("{} k", self.auth_scheme)).is_err() {
1452            return Err(bad(
1453                "auth_scheme contains characters that are not valid in an HTTP header".into(),
1454            ));
1455        }
1456        for (name, value) in &self.headers {
1457            validate_header_name(&section, "headers", name)?;
1458            if name.eq_ignore_ascii_case(&self.auth_header) {
1459                return Err(bad(format!(
1460                    "headers must not repeat auth_header {:?}",
1461                    self.auth_header
1462                )));
1463            }
1464            if reqwest::header::HeaderValue::from_str(value).is_err() {
1465                return Err(bad(format!(
1466                    "header {name:?} has a value that is not valid in an HTTP header"
1467                )));
1468            }
1469        }
1470        if let Some(plan) = &self.plan {
1471            validate_custom_label(&section, "plan", plan)?;
1472        }
1473        if let Some(pointer) = &self.plan_path {
1474            validate_pointer(&section, "plan_path", pointer)?;
1475        }
1476        if !(10..=3600).contains(&self.cache_ttl_secs) {
1477            return Err(bad(format!(
1478                "cache_ttl_secs must be between 10 and 3600, got {}",
1479                self.cache_ttl_secs
1480            )));
1481        }
1482        if self.metrics.is_empty() && self.texts.is_empty() {
1483            return Err(bad(
1484                "needs at least one [[custom.metrics]] or [[custom.texts]] entry".into(),
1485            ));
1486        }
1487        let mut metric_labels = HashSet::new();
1488        for metric in &self.metrics {
1489            validate_custom_label(&section, "metric label", &metric.label)?;
1490            if !metric_labels.insert(metric.label.as_str()) {
1491                return Err(bad(format!("duplicate metric label {:?}", metric.label)));
1492            }
1493            let pair = (metric.used.is_some(), metric.limit.is_some());
1494            let well_formed = if metric.percent.is_some() {
1495                pair == (false, false)
1496            } else {
1497                pair == (true, true)
1498            };
1499            if !well_formed {
1500                return Err(bad(format!(
1501                    "metric {:?} must set `percent`, or both `used` and `limit` (not a mix)",
1502                    metric.label
1503                )));
1504            }
1505            for (field, pointer) in [
1506                ("used", &metric.used),
1507                ("limit", &metric.limit),
1508                ("percent", &metric.percent),
1509                ("resets_at", &metric.resets_at),
1510            ] {
1511                if let Some(pointer) = pointer {
1512                    validate_pointer(&section, field, pointer)?;
1513                }
1514            }
1515            if let Some(secs) = metric.window_secs
1516                && secs < 60
1517            {
1518                return Err(bad(format!(
1519                    "metric {:?} window_secs must be at least 60, got {secs}",
1520                    metric.label
1521                )));
1522            }
1523        }
1524        let mut text_labels = HashSet::new();
1525        for text in &self.texts {
1526            validate_custom_label(&section, "text label", &text.label)?;
1527            if !text_labels.insert(text.label.as_str()) {
1528                return Err(bad(format!("duplicate text label {:?}", text.label)));
1529            }
1530            validate_pointer(&section, "value", &text.value)?;
1531        }
1532        Ok(())
1533    }
1534}
1535
1536fn is_valid_custom_id(id: &str) -> bool {
1537    let bytes = id.as_bytes();
1538    let Some(&first) = bytes.first() else {
1539        return false;
1540    };
1541    bytes.len() <= 32
1542        && (first.is_ascii_lowercase() || first.is_ascii_digit())
1543        && bytes
1544            .iter()
1545            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'))
1546}
1547
1548fn validate_pointer(section: &str, field: &str, pointer: &str) -> Result<()> {
1549    if !pointer.starts_with('/') || pointer.chars().any(char::is_control) {
1550        return Err(AppError::Other(format!(
1551            "{section}: {field} {pointer:?} must be an RFC 6901 JSON Pointer starting with '/'"
1552        )));
1553    }
1554    Ok(())
1555}
1556
1557fn validate_custom_label(section: &str, field: &str, label: &str) -> Result<()> {
1558    let len = label.chars().count();
1559    if len == 0 || len > 64 || label.chars().any(char::is_control) {
1560        return Err(AppError::Other(format!(
1561            "{section}: {field} {label:?} must be 1 to 64 characters without control characters"
1562        )));
1563    }
1564    Ok(())
1565}
1566
1567fn validate_header_name(section: &str, field: &str, name: &str) -> Result<()> {
1568    if name.is_empty() || reqwest::header::HeaderName::from_bytes(name.as_bytes()).is_err() {
1569        return Err(AppError::Other(format!(
1570            "{section}: {field} {name:?} is not a valid HTTP header name"
1571        )));
1572    }
1573    Ok(())
1574}
1575
1576/// Resolve an API key for a vendor: a valid env-var name wins, then inline
1577/// config, then a clear error naming both fields. Used by every API-key vendor.
1578pub fn resolve_api_key(
1579    vendor_label: &str,
1580    env_var_name: &str,
1581    inline: Option<&str>,
1582) -> crate::error::Result<String> {
1583    let section = match vendor_label {
1584        "OpenCode Go" => "[opencode-go]".to_string(),
1585        _ => format!("[{}]", vendor_label.to_lowercase()),
1586    };
1587    resolve_api_key_in_section(vendor_label, &section, env_var_name, inline)
1588}
1589
1590/// The env-then-inline lookup without the "or fail" ending, for vendors where
1591/// an absent API key is a legitimate state rather than an error — Kimi accepts
1592/// a Kimi Code CLI subscription login instead.
1593pub fn optional_api_key(env_var_name: &str, inline: Option<&str>) -> Option<String> {
1594    if is_valid_env_var_name(env_var_name)
1595        && let Ok(v) = std::env::var(env_var_name)
1596        && !v.is_empty()
1597    {
1598        return Some(v);
1599    }
1600    inline.filter(|v| !v.is_empty()).map(str::to_string)
1601}
1602
1603fn resolve_api_key_in_section(
1604    vendor_label: &str,
1605    section: &str,
1606    env_var_name: &str,
1607    inline: Option<&str>,
1608) -> crate::error::Result<String> {
1609    if let Some(key) = optional_api_key(env_var_name, inline) {
1610        return Ok(key);
1611    }
1612    let valid_env_name = is_valid_env_var_name(env_var_name);
1613    let advice = if valid_env_name {
1614        "set an API key in a valid environment variable or set `api_key`"
1615    } else {
1616        "fix the invalid `api_key_env` with a valid environment variable name or set `api_key`"
1617    };
1618    Err(crate::error::AppError::Credentials(format!(
1619        "{vendor_label}: no API key. Either {advice} under {section} in {}.",
1620        config_path_hint()
1621    )))
1622}
1623
1624pub(crate) fn is_valid_env_var_name(name: &str) -> bool {
1625    let mut chars = name.chars();
1626    let Some(first) = chars.next() else {
1627        return false;
1628    };
1629    (first.is_ascii_alphabetic() || first == '_')
1630        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1631}
1632
1633impl Config {
1634    /// Load from `~/.config/ai-usagebar/config.toml`. Returns defaults if the
1635    /// file doesn't exist; errors only on actual parse failures.
1636    pub fn load() -> Result<Self> {
1637        let Some(path) = resolved_path() else {
1638            return Ok(Self::default());
1639        };
1640        Self::load_from(&path)
1641    }
1642
1643    pub fn load_from(path: &std::path::Path) -> Result<Self> {
1644        match std::fs::read_to_string(path) {
1645            Ok(s) => {
1646                let mut config: Self = toml::from_str(&s)?;
1647                // `~` is shell syntax, not path syntax: `PathBuf` keeps it
1648                // literally, so a documented `credentials_path = "~/..."`
1649                // silently pointed at a directory named `~`.
1650                config.expand_paths();
1651                config.validate()?;
1652                #[cfg(unix)]
1653                config.protect_inline_secrets(path)?;
1654                // A custom provider's token variable is as secret as any
1655                // built-in one; subprocesses (`gh`, `grok`, `claude`) must
1656                // not inherit it.
1657                crate::vendor::register_secret_env_vars(&config.custom_secret_env_vars());
1658                Ok(config)
1659            }
1660            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
1661            Err(e) => Err(AppError::io_at(path, e)),
1662        }
1663    }
1664
1665    fn expand_paths(&mut self) {
1666        expand_tilde_opt(&mut self.context.projects_path);
1667        expand_tilde_opt(&mut self.anthropic.credentials_path);
1668        expand_tilde_opt(&mut self.anthropic.accounts_dir);
1669        expand_tilde_opt(&mut self.anthropic.desktop_profiles_dir);
1670        expand_tilde_opt(&mut self.openai.codex_auth_path);
1671        expand_tilde_opt(&mut self.cursor.db_path);
1672        expand_tilde_opt(&mut self.cursor.agent_auth_path);
1673        expand_tilde_opt(&mut self.kiro.db_path);
1674        expand_tilde_opt(&mut self.kimi.credentials_path);
1675        self.supergrok.grok_binary = expand_tilde(&self.supergrok.grok_binary);
1676        expand_tilde_opt(&mut self.supergrok.auth_path);
1677        expand_tilde_opt(&mut self.supergrok.config_path);
1678        for account in &mut self.anthropic.accounts {
1679            account.credentials_path = expand_tilde(&account.credentials_path);
1680        }
1681        for account in &mut self.openai.accounts {
1682            account.codex_auth_path = expand_tilde(&account.codex_auth_path);
1683        }
1684    }
1685
1686    /// Explicitly enumerate every inline credential field. Adding a new
1687    /// credential vendor must add it here so its config receives the same
1688    /// protection.
1689    #[cfg(unix)]
1690    fn has_inline_secrets(&self) -> bool {
1691        [
1692            self.zai.api_key.as_deref(),
1693            self.openrouter.api_key.as_deref(),
1694            self.deepseek.api_key.as_deref(),
1695            self.kimi.api_key.as_deref(),
1696            self.kilo.api_key.as_deref(),
1697            self.novita.api_key.as_deref(),
1698            self.minimax.api_key.as_deref(),
1699            self.moonshot.api_key.as_deref(),
1700            self.grok.api_key.as_deref(),
1701            self.anthropic_api.api_key.as_deref(),
1702            self.opencode_go.api_key.as_deref(),
1703            self.antigravity.oauth_client_secret.as_deref(),
1704        ]
1705        .into_iter()
1706        .chain(
1707            self.openrouter
1708                .accounts
1709                .iter()
1710                .map(|account| account.api_key.as_deref()),
1711        )
1712        .chain(self.custom.iter().map(|c| c.api_key.as_deref()))
1713        .any(|key| key.is_some_and(|key| !key.is_empty()))
1714    }
1715
1716    fn custom_secret_env_vars(&self) -> Vec<String> {
1717        self.custom
1718            .iter()
1719            .filter(|c| !c.api_key_env.is_empty())
1720            .map(|c| c.api_key_env.clone())
1721            .collect()
1722    }
1723
1724    /// The `[[custom]]` providers that are switched on, in config order.
1725    pub fn enabled_custom(&self) -> impl Iterator<Item = &CustomProviderConfig> {
1726        self.custom.iter().filter(|c| c.enabled)
1727    }
1728
1729    /// A `[[custom]]` provider by `id`, enabled or not.
1730    pub fn custom_by_id(&self, id: &str) -> Option<&CustomProviderConfig> {
1731        self.custom.iter().find(|c| c.id == id)
1732    }
1733
1734    #[cfg(unix)]
1735    fn protect_inline_secrets(&self, path: &Path) -> Result<()> {
1736        if !self.has_inline_secrets() {
1737            return Ok(());
1738        }
1739
1740        let metadata = std::fs::metadata(path).map_err(|_| {
1741            AppError::Credentials(format!(
1742                "config at {} contains inline credentials but its permissions could not be checked; fix permissions or move credentials to environment variables",
1743                path.display()
1744            ))
1745        })?;
1746        if inline_key_permission_decision(metadata.mode()) == InlineKeyPermissionDecision::Tighten {
1747            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|_| {
1748                AppError::Credentials(format!(
1749                    "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",
1750                    path.display()
1751                ))
1752            })?;
1753        }
1754        Ok(())
1755    }
1756
1757    pub fn is_enabled(&self, id: VendorId) -> bool {
1758        match id {
1759            VendorId::Anthropic => self.anthropic.enabled,
1760            VendorId::AnthropicApi => self.anthropic_api.enabled,
1761            VendorId::Openai => self.openai.enabled,
1762            VendorId::Copilot => self.copilot.enabled,
1763            VendorId::Zai => self.zai.enabled,
1764            VendorId::Openrouter => self.openrouter.enabled,
1765            VendorId::Deepseek => self.deepseek.enabled,
1766            VendorId::Kimi => self.kimi.enabled,
1767            VendorId::Kilo => self.kilo.enabled,
1768            VendorId::Novita => self.novita.enabled,
1769            VendorId::Moonshot => self.moonshot.enabled,
1770            VendorId::Grok => self.grok.enabled,
1771            VendorId::Supergrok => self.supergrok.enabled,
1772            VendorId::Antigravity => self.antigravity.enabled,
1773            VendorId::Cursor => self.cursor.enabled,
1774            VendorId::Minimax => self.minimax.enabled,
1775            VendorId::Kiro => self.kiro.enabled,
1776            VendorId::NousResearch => self.nous.enabled,
1777            VendorId::OpenCodeGo => self.opencode_go.enabled,
1778            VendorId::CommandCode => self.commandcode.enabled,
1779            VendorId::Ollama => self.ollama.enabled,
1780        }
1781    }
1782
1783    /// The environment variable this provider's API key is read from, honoring
1784    /// a per-vendor `api_key_env` override; `""` for a provider that takes no
1785    /// key. Matching on [`VendorId`] rather than on a section name is
1786    /// deliberate: a new key vendor that nobody adds here fails to compile,
1787    /// where a `_ =>` arm over `&str` sections would silently hand back the
1788    /// wrong default and report the provider as unconfigured for ever.
1789    pub fn api_key_env_for(&self, id: VendorId) -> &str {
1790        match id {
1791            VendorId::AnthropicApi => &self.anthropic_api.api_key_env,
1792            VendorId::Zai => &self.zai.api_key_env,
1793            VendorId::Openrouter => &self.openrouter.api_key_env,
1794            VendorId::Deepseek => &self.deepseek.api_key_env,
1795            VendorId::Kimi => &self.kimi.api_key_env,
1796            VendorId::Kilo => &self.kilo.api_key_env,
1797            VendorId::Novita => &self.novita.api_key_env,
1798            VendorId::Moonshot => &self.moonshot.api_key_env,
1799            VendorId::Grok => &self.grok.api_key_env,
1800            VendorId::Minimax => &self.minimax.api_key_env,
1801            VendorId::OpenCodeGo => &self.opencode_go.api_key_env,
1802            VendorId::Ollama => &self.ollama.api_key_env,
1803            // Fixed names: OAuth-first providers whose environment override is
1804            // not user-renameable, and the providers with no key at all.
1805            VendorId::Anthropic
1806            | VendorId::Openai
1807            | VendorId::Copilot
1808            | VendorId::Supergrok
1809            | VendorId::Antigravity
1810            | VendorId::Cursor
1811            | VendorId::Kiro
1812            | VendorId::NousResearch
1813            | VendorId::CommandCode => id.api_key_env(),
1814        }
1815    }
1816
1817    /// A non-empty inline `api_key` from this provider's config section. An
1818    /// empty string counts as unset, the same way the vendors' own
1819    /// `resolve_api_key` treats it.
1820    pub fn inline_api_key(&self, id: VendorId) -> Option<&str> {
1821        let raw = match id {
1822            VendorId::AnthropicApi => self.anthropic_api.api_key.as_deref(),
1823            VendorId::Zai => self.zai.api_key.as_deref(),
1824            VendorId::Openrouter => self.openrouter.api_key.as_deref(),
1825            VendorId::Deepseek => self.deepseek.api_key.as_deref(),
1826            VendorId::Kimi => self.kimi.api_key.as_deref(),
1827            VendorId::Kilo => self.kilo.api_key.as_deref(),
1828            VendorId::Novita => self.novita.api_key.as_deref(),
1829            VendorId::Moonshot => self.moonshot.api_key.as_deref(),
1830            VendorId::Grok => self.grok.api_key.as_deref(),
1831            VendorId::Minimax => self.minimax.api_key.as_deref(),
1832            VendorId::OpenCodeGo => self.opencode_go.api_key.as_deref(),
1833            VendorId::Ollama => self.ollama.api_key.as_deref(),
1834            VendorId::Anthropic
1835            | VendorId::Openai
1836            | VendorId::Copilot
1837            | VendorId::Supergrok
1838            | VendorId::Antigravity
1839            | VendorId::Cursor
1840            | VendorId::Kiro
1841            | VendorId::NousResearch
1842            | VendorId::CommandCode => None,
1843        };
1844        raw.filter(|key| !key.is_empty())
1845    }
1846
1847    pub fn enabled_vendors(&self) -> Vec<VendorId> {
1848        VendorId::all()
1849            .iter()
1850            .copied()
1851            .filter(|id| self.is_enabled(*id))
1852            .collect()
1853    }
1854
1855    /// Validate cross-entry constraints that serde cannot express. Account
1856    /// labels are both CLI selectors and TUI tab identities, so duplicates
1857    /// would make either destination ambiguous.
1858    pub fn validate(&self) -> Result<()> {
1859        if let Some(minutes) = self.tray.refresh_minutes
1860            && !TRAY_REFRESH_MINUTES.contains(&minutes)
1861        {
1862            return Err(AppError::Other(format!(
1863                "[tray] refresh_minutes must be one of 1, 5 or 10, got {minutes}"
1864            )));
1865        }
1866        if self.context.context_window_tokens == Some(0) {
1867            return Err(AppError::Other(
1868                "[context] context_window_tokens must be greater than zero".into(),
1869            ));
1870        }
1871        for (model, tokens) in &self.context.model_context_window_tokens {
1872            if model.trim().is_empty() {
1873                return Err(AppError::Other(
1874                    "[context] model_context_window_tokens keys must not be empty".into(),
1875                ));
1876            }
1877            if *tokens == 0 {
1878                return Err(AppError::Other(format!(
1879                    "[context] model_context_window_tokens entry {model:?} must be greater than zero"
1880                )));
1881            }
1882        }
1883        if let Some(limit) = self.anthropic_api.monthly_limit
1884            && (!limit.is_finite() || limit <= 0.0)
1885        {
1886            return Err(AppError::Other(
1887                "[anthropic_api] monthly_limit must be finite and greater than zero; \
1888                 remove it to show spend without a limit"
1889                    .into(),
1890            ));
1891        }
1892        if crate::kimi::oauth::Region::parse(&self.kimi.region).is_none()
1893            && !self.kimi.region.eq_ignore_ascii_case("auto")
1894        {
1895            return Err(AppError::Other(format!(
1896                "[kimi] region must be \"auto\", \"cn\", or \"global\", got {:?}",
1897                self.kimi.region
1898            )));
1899        }
1900        if !self.minimax.region.eq_ignore_ascii_case("global")
1901            && !self.minimax.region.eq_ignore_ascii_case("cn")
1902        {
1903            return Err(AppError::Other(format!(
1904                "[minimax] region must be \"global\" or \"cn\", got {:?}",
1905                self.minimax.region
1906            )));
1907        }
1908        if self.supergrok.grok_binary.as_os_str().is_empty() {
1909            return Err(AppError::Other(
1910                "[supergrok] grok_binary must not be empty".into(),
1911            ));
1912        }
1913        let mut labels = HashSet::new();
1914        for account in &self.anthropic.accounts {
1915            validate_account_label(&account.label)?;
1916            if !labels.insert(&account.label) {
1917                return Err(AppError::Credentials(format!(
1918                    "duplicate anthropic account label {:?}",
1919                    account.label
1920                )));
1921            }
1922        }
1923        let mut openai_labels = HashSet::new();
1924        for account in &self.openai.accounts {
1925            validate_account_label_for("openai", &account.label)?;
1926            if !openai_labels.insert(&account.label) {
1927                return Err(AppError::Credentials(format!(
1928                    "duplicate openai account label {:?}",
1929                    account.label
1930                )));
1931            }
1932        }
1933        let mut openrouter_labels = HashSet::new();
1934        for account in &self.openrouter.accounts {
1935            validate_account_label_for("openrouter", &account.label)?;
1936            if !openrouter_labels.insert(&account.label) {
1937                return Err(AppError::Credentials(format!(
1938                    "duplicate openrouter account label {:?}",
1939                    account.label
1940                )));
1941            }
1942            let has_env = account
1943                .api_key_env
1944                .as_deref()
1945                .is_some_and(|name| !name.is_empty());
1946            let has_inline = account
1947                .api_key
1948                .as_deref()
1949                .is_some_and(|key| !key.is_empty());
1950            if !has_env && !has_inline {
1951                return Err(AppError::Credentials(format!(
1952                    "openrouter account {:?} must set api_key_env or api_key",
1953                    account.label
1954                )));
1955            }
1956        }
1957        self.validate_custom()
1958    }
1959
1960    /// Per-entry rules live on `CustomProviderConfig`; the cross-entry ones —
1961    /// `id` and `short_name` uniqueness, including against the built-in
1962    /// vendors — need the whole list and live here.
1963    fn validate_custom(&self) -> Result<()> {
1964        let mut ids = HashSet::new();
1965        let mut short_names: HashSet<&str> =
1966            VendorId::all().iter().map(|v| v.short_name()).collect();
1967        for (index, custom) in self.custom.iter().enumerate() {
1968            custom.validate(index)?;
1969            if !ids.insert(custom.id.as_str()) {
1970                return Err(AppError::Other(format!(
1971                    "{}: duplicate id",
1972                    custom.section_label()
1973                )));
1974            }
1975            if !short_names.insert(custom.short_name.as_str()) {
1976                return Err(AppError::Other(format!(
1977                    "{}: short_name {:?} is already used by a built-in vendor or another [[custom]] entry",
1978                    custom.section_label(),
1979                    custom.short_name
1980                )));
1981            }
1982        }
1983        Ok(())
1984    }
1985}
1986
1987#[cfg(unix)]
1988#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1989enum InlineKeyPermissionDecision {
1990    Ok,
1991    Tighten,
1992}
1993
1994#[cfg(unix)]
1995fn inline_key_permission_decision(mode: u32) -> InlineKeyPermissionDecision {
1996    if mode & 0o077 == 0 {
1997        InlineKeyPermissionDecision::Ok
1998    } else {
1999        InlineKeyPermissionDecision::Tighten
2000    }
2001}
2002
2003pub fn default_path() -> Option<PathBuf> {
2004    let proj = directories::ProjectDirs::from("", "", "ai-usagebar")?;
2005    Some(proj.config_dir().join("config.toml"))
2006}
2007
2008/// The Unix-conventional location, which is what every doc, the config
2009/// example, and both desktop integrations have always pointed at. On Linux it
2010/// *is* [`default_path`]; on macOS `ProjectDirs` resolves to
2011/// `~/Library/Application Support/…` instead, so the two diverge.
2012fn legacy_xdg_path() -> Option<PathBuf> {
2013    let home = crate::cache::home_dir().ok()?;
2014    Some(home.join(".config").join("ai-usagebar").join("config.toml"))
2015}
2016
2017/// The config file actually in effect.
2018///
2019/// A `--config` override (see [`set_override_path`]) wins outright so a test
2020/// run never touches the real file. Otherwise [`default_path`] stays
2021/// canonical, but on macOS a file at the documented
2022/// `~/.config/ai-usagebar/config.toml` is honored when the canonical one does
2023/// not exist — otherwise everyone who followed the README (and both desktop
2024/// integrations, which read that path) silently got defaults. The legacy file
2025/// is never moved or rewritten: it may hold API keys, and relocating a secret
2026/// behind the user's back is not this tool's business.
2027pub fn resolved_path() -> Option<PathBuf> {
2028    if let Some(path) = override_path() {
2029        return Some(path);
2030    }
2031    let canonical = default_path();
2032    if let Some(p) = &canonical
2033        && p.exists()
2034    {
2035        return canonical;
2036    }
2037    if let Some(legacy) = legacy_xdg_path()
2038        && legacy.exists()
2039    {
2040        return Some(legacy);
2041    }
2042    canonical
2043}
2044
2045static PATH_OVERRIDE: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
2046
2047/// Point every config load, save, and hint at one explicit file — the
2048/// `--config` flag. Takes precedence over the canonical and legacy locations.
2049/// The file does not have to exist yet: loads treat it as defaults while
2050/// Settings saves create it. Process-wide, so call it once at startup before
2051/// any config is read.
2052pub fn set_override_path(path: &std::path::Path) {
2053    if let Ok(mut slot) = PATH_OVERRIDE.lock() {
2054        *slot = Some(path.to_path_buf());
2055    }
2056}
2057
2058/// Drop the override again. Used only by tests so they can restore the
2059/// process-wide state they changed.
2060#[doc(hidden)]
2061pub fn clear_override_path() {
2062    if let Ok(mut slot) = PATH_OVERRIDE.lock() {
2063        *slot = None;
2064    }
2065}
2066
2067fn override_path() -> Option<PathBuf> {
2068    PATH_OVERRIDE.lock().ok().and_then(|slot| slot.clone())
2069}
2070
2071/// Value of a `--config=PATH` argument, split at the OS-string level so a
2072/// path with bytes Windows/Unix can store but UTF-8 cannot represent (an
2073/// undecodable filename on Unix, a lone surrogate on Windows) survives
2074/// intact instead of being mangled by `to_string_lossy`. `None` when the
2075/// argument is not in that form. Used by both binaries' argv pre-parsers.
2076#[doc(hidden)]
2077pub fn config_flag_value(arg: &std::ffi::OsStr) -> Option<PathBuf> {
2078    #[cfg(unix)]
2079    {
2080        use std::os::unix::ffi::{OsStrExt, OsStringExt};
2081        let rest = arg.as_bytes().strip_prefix(b"--config=")?;
2082        Some(std::ffi::OsString::from_vec(rest.to_vec()).into())
2083    }
2084    #[cfg(windows)]
2085    {
2086        use std::os::windows::ffi::{OsStrExt, OsStringExt};
2087        const PREFIX: &[u16] = &[
2088            b'-' as u16,
2089            b'-' as u16,
2090            b'c' as u16,
2091            b'o' as u16,
2092            b'n' as u16,
2093            b'f' as u16,
2094            b'i' as u16,
2095            b'g' as u16,
2096            b'=' as u16,
2097        ];
2098        let wide: Vec<u16> = arg.encode_wide().collect();
2099        let rest = wide.strip_prefix(PREFIX)?;
2100        Some(std::ffi::OsString::from_wide(rest).into())
2101    }
2102    #[cfg(not(any(unix, windows)))]
2103    {
2104        Some(PathBuf::from(arg.to_str()?.strip_prefix("--config=")?))
2105    }
2106}
2107
2108/// Expand a leading `~` (or `~/`) against the user's home directory. Anything
2109/// else — including `~user` — is left untouched.
2110fn expand_tilde(p: &std::path::Path) -> PathBuf {
2111    let Some(s) = p.to_str() else {
2112        return p.to_path_buf();
2113    };
2114    let rest = if s == "~" {
2115        ""
2116    } else if let Some(r) = s.strip_prefix("~/") {
2117        r
2118    } else {
2119        return p.to_path_buf();
2120    };
2121    match crate::cache::home_dir() {
2122        Ok(home) if rest.is_empty() => home,
2123        Ok(home) => home.join(rest),
2124        Err(_) => p.to_path_buf(),
2125    }
2126}
2127
2128fn expand_tilde_opt(p: &mut Option<PathBuf>) {
2129    if let Some(inner) = p.as_ref() {
2130        *p = Some(expand_tilde(inner));
2131    }
2132}
2133
2134/// Resolved `config.toml` path as a string for user-facing messages. Uses the
2135/// platform's config dir (`directories::ProjectDirs`), so it reads correctly on
2136/// Linux, macOS, and Windows instead of hard-coding the Unix `~/.config` path.
2137/// Falls back to the bare filename if the path can't be resolved.
2138pub fn config_path_hint() -> String {
2139    resolved_path()
2140        .map(|p| p.display().to_string())
2141        .unwrap_or_else(|| "config.toml".to_string())
2142}
2143
2144#[cfg(test)]
2145mod tests {
2146    use super::*;
2147    use std::io::Write;
2148    use tempfile::NamedTempFile;
2149
2150    #[cfg(unix)]
2151    use std::os::unix::fs::{MetadataExt, PermissionsExt};
2152
2153    fn write_toml(s: &str) -> NamedTempFile {
2154        let mut f = NamedTempFile::new().unwrap();
2155        f.write_all(s.as_bytes()).unwrap();
2156        f.flush().unwrap();
2157        f
2158    }
2159
2160    /// The back-compat guarantee #134 asks for: a config with no
2161    /// `[[openai.accounts]]` resolves exactly what it resolved before, whether
2162    /// it sets `codex_auth_path` or leaves it to the default.
2163    #[test]
2164    fn openai_without_accounts_resolves_the_singular_path() {
2165        let explicit = OpenAiConfig {
2166            codex_auth_path: Some(PathBuf::from("/tmp/codex/auth.json")),
2167            ..OpenAiConfig::default()
2168        };
2169        assert_eq!(
2170            explicit.resolve_auth_path(None).unwrap(),
2171            PathBuf::from("/tmp/codex/auth.json")
2172        );
2173
2174        let bare = OpenAiConfig::default();
2175        assert_eq!(
2176            bare.resolve_auth_path(None).unwrap(),
2177            crate::openai::creds::default_path().unwrap(),
2178            "no codex_auth_path must still mean ~/.codex/auth.json"
2179        );
2180    }
2181
2182    /// Each named account resolves its own file, and the default login is still
2183    /// reachable alongside them.
2184    #[test]
2185    fn openai_named_accounts_resolve_their_own_auth_file() {
2186        let config: Config = toml::from_str(
2187            r#"
2188            [openai]
2189            codex_auth_path = "/tmp/personal/auth.json"
2190            [[openai.accounts]]
2191            label = "work"
2192            codex_auth_path = "/tmp/work/auth.json"
2193            "#,
2194        )
2195        .unwrap();
2196
2197        assert_eq!(
2198            config.openai.resolve_auth_path(Some("work")).unwrap(),
2199            PathBuf::from("/tmp/work/auth.json")
2200        );
2201        assert_eq!(
2202            config.openai.resolve_auth_path(None).unwrap(),
2203            PathBuf::from("/tmp/personal/auth.json")
2204        );
2205    }
2206
2207    /// An unknown label must fail rather than quietly fall back to the default
2208    /// login — reporting the wrong subscription's usage is worse than an error.
2209    #[test]
2210    fn an_unknown_openai_account_is_an_error_not_a_fallback() {
2211        let config = OpenAiConfig {
2212            codex_auth_path: Some(PathBuf::from("/tmp/personal/auth.json")),
2213            accounts: vec![OpenAiAccount {
2214                label: "work".into(),
2215                codex_auth_path: PathBuf::from("/tmp/work/auth.json"),
2216            }],
2217            ..OpenAiConfig::default()
2218        };
2219        let err = config
2220            .resolve_auth_path(Some("nope"))
2221            .unwrap_err()
2222            .to_string();
2223        assert!(err.contains("nope"), "{err}");
2224        assert!(err.contains("[[openai.accounts]]"), "{err}");
2225    }
2226
2227    #[test]
2228    fn defaults_enable_only_the_four_core_vendors() {
2229        let c = Config::default();
2230        assert!(c.is_enabled(VendorId::Anthropic));
2231        assert!(c.is_enabled(VendorId::Openai));
2232        assert!(c.is_enabled(VendorId::Zai));
2233        assert!(c.is_enabled(VendorId::Openrouter));
2234        for opt_in in [
2235            VendorId::AnthropicApi,
2236            VendorId::Copilot,
2237            VendorId::Deepseek,
2238            VendorId::Kimi,
2239            VendorId::Kilo,
2240            VendorId::Novita,
2241            VendorId::Moonshot,
2242            VendorId::Grok,
2243            VendorId::Supergrok,
2244            VendorId::Cursor,
2245            VendorId::Minimax,
2246            VendorId::Kiro,
2247        ] {
2248            assert!(!c.is_enabled(opt_in), "{opt_in:?}");
2249        }
2250        assert_eq!(c.enabled_vendors().len(), 4);
2251    }
2252
2253    #[test]
2254    fn new_provider_defaults_are_opt_in_and_use_exact_auth_contracts() {
2255        let config = Config::default();
2256        assert!(!config.is_enabled(VendorId::NousResearch));
2257        assert!(!config.is_enabled(VendorId::OpenCodeGo));
2258        assert_eq!(config.opencode_go.api_key_env, "OPENCODE_GO_API_KEY");
2259        assert!(config.opencode_go.api_key.is_none());
2260        assert!(!config.is_enabled(VendorId::Copilot));
2261    }
2262
2263    #[cfg(unix)]
2264    #[test]
2265    fn inline_credentials_are_protected() {
2266        let mut config = Config::default();
2267        config.opencode_go.api_key = Some("<redacted>".to_string());
2268        assert!(config.has_inline_secrets());
2269    }
2270
2271    #[test]
2272    fn antigravity_oauth_client_overrides_parse() {
2273        let config: Config = toml::from_str(
2274            "[antigravity]
2275enabled = true
2276oauth_client_id = \"test-client\"
2277oauth_client_secret = \"test-client-secret\"
2278",
2279        )
2280        .unwrap();
2281        assert!(config.antigravity.enabled);
2282        assert_eq!(
2283            config.antigravity.oauth_client_id.as_deref(),
2284            Some("test-client")
2285        );
2286        assert_eq!(
2287            config.antigravity.oauth_client_secret.as_deref(),
2288            Some("test-client-secret")
2289        );
2290        let bare: Config = toml::from_str(
2291            "[antigravity]
2292enabled = true
2293",
2294        )
2295        .unwrap();
2296        assert!(bare.antigravity.oauth_client_id.is_none());
2297        assert!(bare.antigravity.oauth_client_secret.is_none());
2298    }
2299
2300    #[cfg(unix)]
2301    #[test]
2302    fn antigravity_inline_oauth_secret_receives_config_file_protection() {
2303        let mut config = Config::default();
2304        config.antigravity.oauth_client_id = Some("test-client".into());
2305        assert!(!config.has_inline_secrets());
2306        config.antigravity.oauth_client_secret = Some("<redacted>".into());
2307        assert!(config.has_inline_secrets());
2308    }
2309
2310    #[cfg(unix)]
2311    #[test]
2312    fn openrouter_named_inline_keys_receive_config_file_protection() {
2313        let mut config = Config::default();
2314        config.openrouter.accounts.push(OpenRouterAccount {
2315            label: "work".into(),
2316            api_key_env: None,
2317            api_key: Some("<redacted>".into()),
2318        });
2319        assert!(config.has_inline_secrets());
2320    }
2321
2322    #[test]
2323    fn missing_file_uses_defaults() {
2324        let path = std::path::Path::new("/tmp/does-not-exist-ai-usagebar-test");
2325        let c = Config::load_from(path).unwrap();
2326        assert!(c.is_enabled(VendorId::Anthropic));
2327    }
2328
2329    #[test]
2330    fn parses_full_config() {
2331        let f = write_toml(
2332            r#"
2333            [anthropic]
2334            enabled = true
2335
2336            [openai]
2337            enabled = false
2338            admin_key_env = "MY_ADMIN_KEY"
2339
2340            [zai]
2341            enabled = true
2342            api_key_env = "MY_ZAI"
2343            plan_tier = "pro"
2344
2345            [openrouter]
2346            enabled = false
2347            "#,
2348        );
2349        let c = Config::load_from(f.path()).unwrap();
2350        assert!(c.is_enabled(VendorId::Anthropic));
2351        assert!(!c.is_enabled(VendorId::Openai));
2352        assert!(c.is_enabled(VendorId::Zai));
2353        assert!(!c.is_enabled(VendorId::Openrouter));
2354        assert_eq!(c.openai.admin_key_env, "MY_ADMIN_KEY");
2355        assert_eq!(c.zai.api_key_env, "MY_ZAI");
2356        assert_eq!(c.zai.plan_tier.as_deref(), Some("pro"));
2357        assert!(c.openrouter.accounts.is_empty());
2358        assert!(c.openrouter.show_default_account);
2359    }
2360
2361    #[test]
2362    fn partial_config_falls_back_to_defaults() {
2363        let f = write_toml(
2364            r#"[openai]
2365enabled = false
2366"#,
2367        );
2368        let c = Config::load_from(f.path()).unwrap();
2369        assert!(!c.is_enabled(VendorId::Openai));
2370        // Other vendors keep their defaults.
2371        assert!(c.is_enabled(VendorId::Anthropic));
2372        assert_eq!(c.openai.admin_key_env, "OPENAI_ADMIN_KEY");
2373    }
2374
2375    #[test]
2376    fn malformed_toml_returns_error() {
2377        let f = write_toml("this is not = = valid");
2378        assert!(Config::load_from(f.path()).is_err());
2379    }
2380
2381    #[cfg(unix)]
2382    #[test]
2383    fn load_from_tightens_world_readable_config_with_inline_api_key() {
2384        let file = write_toml("[zai]\napi_key = \"test-inline-key\"\n");
2385        std::fs::set_permissions(file.path(), std::fs::Permissions::from_mode(0o644)).unwrap();
2386
2387        Config::load_from(file.path()).unwrap();
2388
2389        assert_eq!(
2390            std::fs::metadata(file.path()).unwrap().mode() & 0o777,
2391            0o600
2392        );
2393    }
2394
2395    #[cfg(unix)]
2396    #[test]
2397    fn load_from_leaves_world_readable_config_without_inline_api_keys_unchanged() {
2398        let file = write_toml("[zai]\napi_key_env = \"TEST_ZAI_API_KEY\"\n");
2399        std::fs::set_permissions(file.path(), std::fs::Permissions::from_mode(0o644)).unwrap();
2400
2401        Config::load_from(file.path()).unwrap();
2402
2403        assert_eq!(
2404            std::fs::metadata(file.path()).unwrap().mode() & 0o777,
2405            0o644
2406        );
2407    }
2408
2409    #[cfg(unix)]
2410    #[test]
2411    fn inline_key_permission_decision_requires_tightening_for_group_or_other_bits() {
2412        assert_eq!(
2413            inline_key_permission_decision(0o600),
2414            InlineKeyPermissionDecision::Ok
2415        );
2416        assert_eq!(
2417            inline_key_permission_decision(0o640),
2418            InlineKeyPermissionDecision::Tighten
2419        );
2420        assert_eq!(
2421            inline_key_permission_decision(0o604),
2422            InlineKeyPermissionDecision::Tighten
2423        );
2424    }
2425
2426    #[test]
2427    fn anthropic_api_monthly_limit_must_be_positive_and_finite() {
2428        for value in ["0", "-1", "inf", "nan"] {
2429            let file = write_toml(&format!("[anthropic_api]\nmonthly_limit = {value}\n"));
2430            let error = Config::load_from(file.path()).unwrap_err().to_string();
2431            assert!(error.contains("monthly_limit"), "value {value}: {error}");
2432        }
2433
2434        let file = write_toml("[anthropic_api]\nmonthly_limit = 1000\n");
2435        assert_eq!(
2436            Config::load_from(file.path())
2437                .unwrap()
2438                .anthropic_api
2439                .monthly_limit,
2440            Some(1000.0)
2441        );
2442    }
2443
2444    #[test]
2445    fn minimax_region_accepts_only_known_instances() {
2446        for region in ["global", "GLOBAL", "cn", "CN"] {
2447            let file = write_toml(&format!("[minimax]\nregion = {region:?}\n"));
2448            assert_eq!(
2449                Config::load_from(file.path()).unwrap().minimax.region,
2450                region
2451            );
2452        }
2453
2454        for region in ["", "china", "us"] {
2455            let file = write_toml(&format!("[minimax]\nregion = {region:?}\n"));
2456            let error = Config::load_from(file.path()).unwrap_err().to_string();
2457            assert!(error.contains("[minimax] region"), "{error}");
2458        }
2459    }
2460
2461    #[test]
2462    fn kimi_region_accepts_auto_and_both_deployments() {
2463        for region in ["auto", "AUTO", "cn", "mainland-cn", "global"] {
2464            let file = write_toml(&format!("[kimi]\nregion = {region:?}\n"));
2465            assert_eq!(Config::load_from(file.path()).unwrap().kimi.region, region);
2466        }
2467
2468        for region in ["", "us", "oversea"] {
2469            let file = write_toml(&format!("[kimi]\nregion = {region:?}\n"));
2470            let error = Config::load_from(file.path()).unwrap_err().to_string();
2471            assert!(error.contains("[kimi] region"), "{error}");
2472        }
2473    }
2474
2475    #[test]
2476    fn kimi_defaults_to_auto_region_and_no_credential_override() {
2477        let defaults = KimiConfig::default();
2478        assert_eq!(defaults.region, "auto");
2479        assert_eq!(defaults.credentials_path, None);
2480        assert!(!defaults.enabled);
2481    }
2482
2483    #[test]
2484    fn kimi_credentials_path_expands_a_tilde() {
2485        let file = write_toml("[kimi]\ncredentials_path = \"~/kimi/creds.json\"\n");
2486        let path = Config::load_from(file.path())
2487            .unwrap()
2488            .kimi
2489            .credentials_path
2490            .unwrap();
2491        assert!(!path.starts_with("~"), "{}", path.display());
2492        assert!(path.ends_with("kimi/creds.json"), "{}", path.display());
2493    }
2494
2495    #[test]
2496    fn optional_api_key_reports_absence_instead_of_failing() {
2497        assert_eq!(
2498            optional_api_key("KIMI_API_KEY_DEFINITELY_UNSET", Some("inline")),
2499            Some("inline".to_string())
2500        );
2501        assert_eq!(
2502            optional_api_key("KIMI_API_KEY_DEFINITELY_UNSET", None),
2503            None
2504        );
2505        assert_eq!(optional_api_key("KIMI_API_KEY_UNSET", Some("")), None);
2506        // An unusable `api_key_env` still lets an inline key through, exactly
2507        // as `resolve_api_key` does.
2508        assert_eq!(
2509            optional_api_key("9INVALID", Some("inline")),
2510            Some("inline".to_string())
2511        );
2512    }
2513
2514    #[test]
2515    fn context_monitor_is_opt_in_and_window_sizes_are_explicit() {
2516        let defaults = Config::default();
2517        assert!(!defaults.context.enabled);
2518        assert_eq!(
2519            defaults.context.window_tokens_for(Some("claude-test")),
2520            None
2521        );
2522
2523        let file = write_toml(
2524            r#"
2525            [context]
2526            enabled = true
2527            context_window_tokens = 200000
2528
2529            [context.model_context_window_tokens]
2530            claude-opus-1m = 1000000
2531            "claude exact id" = 300000
2532            "#,
2533        );
2534        let config = Config::load_from(file.path()).unwrap();
2535        assert!(config.context.enabled);
2536        assert_eq!(
2537            config.context.window_tokens_for(Some("claude-opus-1m")),
2538            Some(1_000_000)
2539        );
2540        assert_eq!(
2541            config.context.window_tokens_for(Some("claude exact id")),
2542            Some(300_000)
2543        );
2544        assert_eq!(
2545            config.context.window_tokens_for(Some("another-model")),
2546            Some(200_000)
2547        );
2548    }
2549
2550    #[test]
2551    fn context_layout_defaults_to_full_and_parses_each_variant() {
2552        assert_eq!(Config::default().context.layout, ContextLayout::Full);
2553        for (text, want) in [
2554            ("full", ContextLayout::Full),
2555            ("split", ContextLayout::Split),
2556            ("bottom", ContextLayout::Bottom),
2557        ] {
2558            let file = write_toml(&format!("[context]\nlayout = \"{text}\"\n"));
2559            assert_eq!(Config::load_from(file.path()).unwrap().context.layout, want);
2560        }
2561        let file = write_toml("[context]\nlayout = \"floating\"\n");
2562        assert!(
2563            Config::load_from(file.path()).is_err(),
2564            "an unknown layout must be rejected, not silently defaulted"
2565        );
2566    }
2567
2568    #[test]
2569    fn vendor_box_defaults_to_sidebar_and_parses_each_variant() {
2570        assert_eq!(Config::default().ui.vendor_box(), VendorBoxStyle::Sidebar);
2571        for (text, want) in [
2572            ("sidebar", VendorBoxStyle::Sidebar),
2573            ("navbar", VendorBoxStyle::Navbar),
2574            ("none", VendorBoxStyle::None),
2575        ] {
2576            let file = write_toml(&format!("[ui]\nvendor_box = \"{text}\"\n"));
2577            assert_eq!(
2578                Config::load_from(file.path()).unwrap().ui.vendor_box(),
2579                want
2580            );
2581        }
2582        let file = write_toml("[ui]\nvendor_box = \"floating\"\n");
2583        assert!(
2584            Config::load_from(file.path()).is_err(),
2585            "an unknown vendor_box style must be rejected, not silently defaulted"
2586        );
2587    }
2588
2589    #[test]
2590    fn context_window_sizes_must_be_nonzero_and_model_ids_nonempty() {
2591        for source in [
2592            "[context]\ncontext_window_tokens = 0\n",
2593            "[context.model_context_window_tokens]\nclaude = 0\n",
2594            "[context.model_context_window_tokens]\n\" \" = 200000\n",
2595        ] {
2596            let file = write_toml(source);
2597            let error = Config::load_from(file.path()).unwrap_err().to_string();
2598            assert!(error.contains("context"), "{error}");
2599        }
2600    }
2601
2602    // serial guard for env-var manipulation tests so they don't race
2603    fn env_guard() -> std::sync::MutexGuard<'static, ()> {
2604        static M: std::sync::Mutex<()> = std::sync::Mutex::new(());
2605        M.lock().unwrap_or_else(|p| p.into_inner())
2606    }
2607
2608    #[test]
2609    fn resolve_api_key_prefers_env_over_inline() {
2610        let _g = env_guard();
2611        // Use a unique env var name so we don't clobber test parallelism.
2612        let var = "AI_USAGEBAR_TEST_ENV_WINS";
2613        // SAFETY: tests are single-threaded under env_guard.
2614        unsafe { std::env::set_var(var, "from-env") };
2615        let got = resolve_api_key("Zai", var, Some("from-inline")).unwrap();
2616        unsafe { std::env::remove_var(var) };
2617        assert_eq!(got, "from-env");
2618    }
2619
2620    #[test]
2621    fn resolve_api_key_falls_back_to_inline() {
2622        let _g = env_guard();
2623        let var = "AI_USAGEBAR_TEST_INLINE_FALLBACK";
2624        unsafe { std::env::remove_var(var) };
2625        let got = resolve_api_key("Zai", var, Some("inline-key")).unwrap();
2626        assert_eq!(got, "inline-key");
2627    }
2628
2629    #[test]
2630    fn copilot_token_prefers_explicit_environment_over_gh_cli() {
2631        struct NeverRun;
2632        impl crate::copilot::credentials::GhAuthTokenRunner for NeverRun {
2633            fn run(
2634                &self,
2635                _: &crate::copilot::credentials::GhAuthTokenCommand,
2636            ) -> std::io::Result<crate::copilot::credentials::GhAuthTokenOutput> {
2637                panic!("environment override must not invoke gh")
2638            }
2639        }
2640
2641        let token = CopilotConfig::default()
2642            .resolve_token_with(
2643                |name| (name == "GITHUB_COPILOT_TOKEN").then(|| "from-environment".into()),
2644                &NeverRun,
2645            )
2646            .unwrap();
2647        assert_eq!(token, "from-environment");
2648    }
2649
2650    #[test]
2651    fn copilot_token_uses_injected_gh_cli_and_hides_failure_output() {
2652        struct FailedGh;
2653        impl crate::copilot::credentials::GhAuthTokenRunner for FailedGh {
2654            fn run(
2655                &self,
2656                _: &crate::copilot::credentials::GhAuthTokenCommand,
2657            ) -> std::io::Result<crate::copilot::credentials::GhAuthTokenOutput> {
2658                Ok(crate::copilot::credentials::GhAuthTokenOutput {
2659                    success: false,
2660                    stdout: b"never-echo-gh-output".to_vec(),
2661                })
2662            }
2663        }
2664        let error = CopilotConfig::default()
2665            .resolve_token_with(|_| None, &FailedGh)
2666            .unwrap_err()
2667            .to_string();
2668        assert!(error.contains("gh auth login --web"));
2669        assert!(!error.contains("never-echo-gh-output"));
2670    }
2671
2672    #[test]
2673    fn resolve_api_key_errors_when_both_missing() {
2674        let _g = env_guard();
2675        let var = "AI_USAGEBAR_TEST_BOTH_MISSING";
2676        unsafe { std::env::remove_var(var) };
2677        let err = resolve_api_key("Zai", var, None).unwrap_err();
2678        match err {
2679            crate::error::AppError::Credentials(msg) => {
2680                assert!(
2681                    msg.contains("api_key"),
2682                    "error should suggest config field: {msg}"
2683                );
2684            }
2685            other => panic!("expected Credentials error, got {other:?}"),
2686        }
2687    }
2688
2689    #[test]
2690    fn resolve_api_key_uses_exact_opencode_go_section_name() {
2691        let _g = env_guard();
2692        unsafe { std::env::remove_var("OPENCODE_GO_API_KEY") };
2693        let err = resolve_api_key("OpenCode Go", "OPENCODE_GO_API_KEY", None).unwrap_err();
2694        let message = err.to_string();
2695        assert!(
2696            message.contains("[opencode-go]"),
2697            "wrong section hint: {message}"
2698        );
2699        assert!(
2700            !message.contains("[opencode go]"),
2701            "wrong section hint: {message}"
2702        );
2703    }
2704
2705    fn path_override_guard() -> std::sync::MutexGuard<'static, ()> {
2706        static M: std::sync::Mutex<()> = std::sync::Mutex::new(());
2707        M.lock().unwrap_or_else(|p| p.into_inner())
2708    }
2709
2710    /// Serializes the override tests *and* guarantees the process-wide
2711    /// override is dropped when the test ends — including via a panic, which
2712    /// a bare set/clear pair does not survive. A leaked override makes every
2713    /// later test in this process resolve a deleted temp file, turning one
2714    /// failure into a cascade of confusing sibling failures.
2715    struct ScopedPathOverride {
2716        _serial: std::sync::MutexGuard<'static, ()>,
2717    }
2718
2719    impl Drop for ScopedPathOverride {
2720        fn drop(&mut self) {
2721            clear_override_path();
2722        }
2723    }
2724
2725    fn scoped_path_override() -> ScopedPathOverride {
2726        ScopedPathOverride {
2727            _serial: path_override_guard(),
2728        }
2729    }
2730
2731    #[test]
2732    fn override_path_wins_over_canonical_and_legacy() {
2733        let _scoped = scoped_path_override();
2734        let file = NamedTempFile::new().unwrap();
2735        set_override_path(file.path());
2736        assert_eq!(resolved_path().as_deref(), Some(file.path()));
2737        assert_eq!(config_path_hint(), file.path().display().to_string());
2738        clear_override_path();
2739        // The usual locations decide again once the override is gone.
2740        let p = resolved_path().expect("a config path must resolve");
2741        assert!(p.ends_with("config.toml"));
2742    }
2743
2744    #[test]
2745    fn scoped_override_guard_clears_the_override_on_panic() {
2746        // Silence the simulated failure's hook output; the assertion below is
2747        // the real report.
2748        let hook = std::panic::take_hook();
2749        std::panic::set_hook(Box::new(|_| {}));
2750        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2751            let _scoped = scoped_path_override();
2752            set_override_path(std::path::Path::new("panicked-override.toml"));
2753            panic!("simulated mid-test failure");
2754        }))
2755        .is_err();
2756        std::panic::set_hook(hook);
2757        assert!(panicked, "the simulated failure must run");
2758        let _serial = path_override_guard();
2759        assert!(
2760            override_path().is_none(),
2761            "a panicking test must not leak the override into siblings"
2762        );
2763    }
2764
2765    #[test]
2766    fn config_path_hint_ends_with_config_toml() {
2767        let _g = path_override_guard();
2768        // Platform-resolved (Linux/macOS/Windows), but always ends in the
2769        // config filename — the trailing segment is what messages rely on.
2770        assert!(config_path_hint().ends_with("config.toml"));
2771    }
2772
2773    #[test]
2774    fn config_flag_value_splits_the_equals_form() {
2775        use std::ffi::OsStr;
2776        assert_eq!(
2777            config_flag_value(OsStr::new("--config=work.toml")).as_deref(),
2778            Some(std::path::Path::new("work.toml"))
2779        );
2780        assert_eq!(
2781            config_flag_value(OsStr::new("--config=")).as_deref(),
2782            Some(std::path::Path::new(""))
2783        );
2784        assert_eq!(config_flag_value(OsStr::new("--config")), None);
2785        assert_eq!(config_flag_value(OsStr::new("--config-file")), None);
2786        assert_eq!(config_flag_value(OsStr::new("account")), None);
2787    }
2788
2789    /// The `--config=PATH` form must preserve a path the platform can store
2790    /// but UTF-8 cannot represent — `to_string_lossy` would replace the bad
2791    /// bytes with U+FFFD and produce a false "config file not found".
2792    #[cfg(unix)]
2793    #[test]
2794    fn config_flag_value_keeps_undecodable_bytes_intact() {
2795        use std::ffi::OsString;
2796        use std::os::unix::ffi::{OsStrExt, OsStringExt};
2797        let raw = OsString::from_vec(b"--config=caf\xe9.toml".to_vec());
2798        let value = config_flag_value(&raw).expect("prefix matches");
2799        assert_eq!(value.as_os_str().as_bytes(), b"caf\xe9.toml");
2800    }
2801
2802    #[cfg(windows)]
2803    #[test]
2804    fn config_flag_value_keeps_lone_surrogates_intact() {
2805        use std::ffi::OsString;
2806        use std::os::windows::ffi::{OsStrExt, OsStringExt};
2807        let mut wide: Vec<u16> = "--config=".encode_utf16().collect();
2808        wide.push(0xDC00); // lone low surrogate: not valid Unicode
2809        wide.extend("x.toml".encode_utf16());
2810        let raw = OsString::from_wide(&wide);
2811        let value = config_flag_value(&raw).expect("prefix matches");
2812        let mut expected = vec![0xDC00u16];
2813        expected.extend("x.toml".encode_utf16());
2814        assert_eq!(
2815            value.as_os_str().encode_wide().collect::<Vec<_>>(),
2816            expected
2817        );
2818    }
2819
2820    #[test]
2821    fn resolve_api_key_treats_empty_env_as_unset() {
2822        let _g = env_guard();
2823        let var = "AI_USAGEBAR_TEST_EMPTY_ENV";
2824        unsafe { std::env::set_var(var, "") };
2825        let got = resolve_api_key("OpenRouter", var, Some("inline")).unwrap();
2826        unsafe { std::env::remove_var(var) };
2827        assert_eq!(got, "inline");
2828    }
2829
2830    #[test]
2831    fn resolve_api_key_rejects_invalid_env_var_name_without_leaking_it() {
2832        let _g = env_guard();
2833        // Simulates a user accidentally pasting the key into api_key_env.
2834        let bad = "sk-kimi-very-real-looking-pasted-secret";
2835        let err = resolve_api_key("Kimi", bad, None).unwrap_err();
2836        let msg = err.to_string();
2837        assert!(
2838            msg.contains("invalid") && msg.contains("api_key_env"),
2839            "error should explain misconfiguration: {msg}"
2840        );
2841        assert!(
2842            !msg.contains(bad),
2843            "error must not echo the misconfigured value: {msg}"
2844        );
2845        assert!(msg.contains("valid environment variable name"));
2846        assert!(
2847            msg.contains("[kimi]"),
2848            "error should point at the lowercase TOML section: {msg}"
2849        );
2850    }
2851
2852    #[test]
2853    fn resolve_api_key_invalid_env_name_falls_back_to_inline() {
2854        let _g = env_guard();
2855        let got = resolve_api_key("Kimi", "sk-pasted-secret", Some("inline-key")).unwrap();
2856        assert_eq!(got, "inline-key");
2857    }
2858
2859    #[test]
2860    fn resolve_api_key_never_leaks_valid_looking_configured_env_name() {
2861        let _g = env_guard();
2862        // This is syntactically a valid environment variable name, but could
2863        // be a pasted secret and must not be reflected in the error.
2864        let pasted_secret = "sk_pasted_secret";
2865        unsafe { std::env::remove_var(pasted_secret) };
2866        let err = resolve_api_key("Kimi", pasted_secret, None).unwrap_err();
2867        assert!(
2868            !err.to_string().contains(pasted_secret),
2869            "error must not echo configured api_key_env values"
2870        );
2871    }
2872
2873    #[test]
2874    fn is_valid_env_var_name_rules() {
2875        // Valid: alphabetic or underscore first, then alnum/underscore.
2876        for valid in ["KIMI_API_KEY", "_PRIVATE", "a", "Z9", "MY_ZAI_2"] {
2877            assert!(is_valid_env_var_name(valid), "{valid} should be valid");
2878        }
2879        // Invalid: empty, digit-first, or shell-illegal characters.
2880        for invalid in ["", "9LIVES", "sk-kimi", "MY KEY", "A.B", "sk/k"] {
2881            assert!(
2882                !is_valid_env_var_name(invalid),
2883                "{invalid} should be invalid"
2884            );
2885        }
2886    }
2887
2888    #[test]
2889    fn config_parses_with_inline_api_key_and_primary() {
2890        let f = write_toml(
2891            r#"
2892            [ui]
2893            primary = "openrouter"
2894
2895            [zai]
2896            enabled = true
2897            api_key_env = "MY_ZAI"
2898            api_key = "sk-zai-inline"
2899
2900            [openrouter]
2901            enabled = true
2902            api_key = "sk-or-inline"
2903            "#,
2904        );
2905        let c = Config::load_from(f.path()).unwrap();
2906        assert_eq!(c.ui.primary, Some(VendorId::Openrouter));
2907        assert_eq!(c.zai.api_key.as_deref(), Some("sk-zai-inline"));
2908        assert_eq!(c.openrouter.api_key.as_deref(), Some("sk-or-inline"));
2909    }
2910
2911    #[test]
2912    fn openrouter_named_accounts_preserve_the_default_contract() {
2913        let f = write_toml(
2914            r#"
2915            [openrouter]
2916            enabled = true
2917            api_key_env = "AI_USAGEBAR_TEST_OR_DEFAULT"
2918            api_key = "default-inline"
2919            show_default_account = false
2920
2921            [[openrouter.accounts]]
2922            label = "work"
2923            api_key_env = "OPENROUTER_WORK_API_KEY"
2924
2925            [[openrouter.accounts]]
2926            label = "personal"
2927            api_key = "personal-inline"
2928            "#,
2929        );
2930        let _g = env_guard();
2931        unsafe { std::env::remove_var("AI_USAGEBAR_TEST_OR_DEFAULT") };
2932        let config = Config::load_from(f.path()).unwrap();
2933        assert!(!config.openrouter.show_default_account);
2934        assert_eq!(config.openrouter.accounts.len(), 2);
2935        assert_eq!(
2936            config.openrouter.resolve_api_key(None).unwrap(),
2937            "default-inline"
2938        );
2939        assert_eq!(
2940            config.openrouter.resolve_api_key(Some("personal")).unwrap(),
2941            "personal-inline"
2942        );
2943    }
2944
2945    #[test]
2946    fn openrouter_named_accounts_reject_ambiguous_or_unsafe_labels() {
2947        for source in [
2948            r#"
2949            [[openrouter.accounts]]
2950            label = "work"
2951            api_key = "one"
2952            [[openrouter.accounts]]
2953            label = "work"
2954            api_key = "two"
2955            "#,
2956            r#"
2957            [[openrouter.accounts]]
2958            label = "../work"
2959            api_key = "one"
2960            "#,
2961            r#"
2962            [[openrouter.accounts]]
2963            label = "work"
2964            "#,
2965        ] {
2966            let f = write_toml(source);
2967            assert!(Config::load_from(f.path()).is_err(), "accepted {source}");
2968        }
2969    }
2970
2971    #[test]
2972    fn openrouter_unknown_account_never_falls_back_to_default_key() {
2973        let mut config = OpenRouterConfig {
2974            api_key: Some("default-secret".into()),
2975            ..OpenRouterConfig::default()
2976        };
2977        config.accounts.push(OpenRouterAccount {
2978            label: "work".into(),
2979            api_key_env: None,
2980            api_key: Some("work-secret".into()),
2981        });
2982        let message = config
2983            .resolve_api_key(Some("missing"))
2984            .unwrap_err()
2985            .to_string();
2986        assert!(message.contains("missing") && message.contains("work"));
2987        assert!(!message.contains("default-secret"));
2988        assert!(!message.contains("work-secret"));
2989    }
2990
2991    #[test]
2992    fn openrouter_account_key_errors_do_not_echo_configured_values() {
2993        let config = OpenRouterConfig {
2994            accounts: vec![OpenRouterAccount {
2995                label: "work".into(),
2996                api_key_env: Some("sk_pasted_secret".into()),
2997                api_key: None,
2998            }],
2999            ..OpenRouterConfig::default()
3000        };
3001        let _g = env_guard();
3002        unsafe { std::env::remove_var("sk_pasted_secret") };
3003        let message = config
3004            .resolve_api_key(Some("work"))
3005            .unwrap_err()
3006            .to_string();
3007        assert!(message.contains("[[openrouter.accounts]]"));
3008        assert!(!message.contains("sk_pasted_secret"));
3009    }
3010
3011    #[test]
3012    fn enabled_vendors_preserves_canonical_order() {
3013        // DeepSeek and Kimi are disabled by default (require explicit API key
3014        // config), so they are absent from the enabled list unless enabled.
3015        let c = Config::default();
3016        assert_eq!(
3017            c.enabled_vendors(),
3018            vec![
3019                VendorId::Anthropic,
3020                VendorId::Openai,
3021                VendorId::Zai,
3022                VendorId::Openrouter,
3023            ]
3024        );
3025    }
3026
3027    #[test]
3028    fn deepseek_appears_when_enabled() {
3029        let f = write_toml(
3030            r#"
3031            [deepseek]
3032            enabled = true
3033            api_key = "sk-test"
3034            "#,
3035        );
3036        let c = Config::load_from(f.path()).unwrap();
3037        assert!(c.is_enabled(VendorId::Deepseek));
3038        assert!(c.enabled_vendors().contains(&VendorId::Deepseek));
3039        assert_eq!(c.deepseek.api_key.as_deref(), Some("sk-test"));
3040    }
3041
3042    #[test]
3043    fn tilde_paths_are_expanded_on_load() {
3044        // `PathBuf` keeps `~` literally, so the documented
3045        // `credentials_path = "~/..."` used to resolve to a directory named
3046        // `~` relative to the process's cwd.
3047        let f = write_toml(
3048            r#"
3049            [context]
3050            projects_path = "~/.claude/projects"
3051
3052            [anthropic]
3053            credentials_path = "~/.claude/.credentials.json"
3054
3055            [[anthropic.accounts]]
3056            label = "work"
3057            credentials_path = "~/work.json"
3058            "#,
3059        );
3060        let c = Config::load_from(f.path()).unwrap();
3061        let home = crate::cache::home_dir().unwrap();
3062
3063        assert_eq!(c.context.projects_path, Some(home.join(".claude/projects")));
3064        let got = c.anthropic.credentials_path.unwrap();
3065        assert_eq!(got, home.join(".claude/.credentials.json"));
3066        assert!(!got.to_string_lossy().contains('~'));
3067        assert_eq!(
3068            c.anthropic.accounts[0].credentials_path,
3069            home.join("work.json")
3070        );
3071    }
3072
3073    #[test]
3074    fn absolute_and_relative_paths_are_left_alone() {
3075        let f = write_toml(
3076            r#"
3077            [anthropic]
3078            credentials_path = "/etc/creds.json"
3079            "#,
3080        );
3081        let c = Config::load_from(f.path()).unwrap();
3082        assert_eq!(
3083            c.anthropic.credentials_path.unwrap(),
3084            std::path::Path::new("/etc/creds.json")
3085        );
3086
3087        // `~user` is not ours to interpret.
3088        let f2 = write_toml(
3089            r#"
3090            [anthropic]
3091            credentials_path = "~someone/creds.json"
3092            "#,
3093        );
3094        let c2 = Config::load_from(f2.path()).unwrap();
3095        assert_eq!(
3096            c2.anthropic.credentials_path.unwrap(),
3097            std::path::Path::new("~someone/creds.json")
3098        );
3099    }
3100
3101    #[test]
3102    fn resolved_path_is_the_canonical_one_and_names_the_config_file() {
3103        let _g = path_override_guard();
3104        // Hermetic: only asserts the shape, never which file happens to exist
3105        // on the machine running the tests.
3106        let p = resolved_path().expect("a config path must resolve");
3107        assert!(p.ends_with("config.toml"));
3108        let canonical = default_path().unwrap();
3109        let legacy = legacy_xdg_path().unwrap();
3110        assert!(
3111            p == canonical || p == legacy,
3112            "resolved to an unexpected location: {}",
3113            p.display()
3114        );
3115    }
3116
3117    #[test]
3118    fn misspelled_section_is_rejected_not_ignored() {
3119        // The regression this guards: `[openrouer]` used to parse fine, leave
3120        // OpenRouter on its defaults, and give the user no hint at all.
3121        let f = write_toml(
3122            r#"
3123            [openrouer]
3124            enabled = true
3125            api_key = "sk-or-v1-typo"
3126            "#,
3127        );
3128        let err = Config::load_from(f.path()).unwrap_err().to_string();
3129        assert!(
3130            err.contains("openrouer"),
3131            "error should name the typo: {err}"
3132        );
3133    }
3134
3135    #[test]
3136    fn invalid_toml_is_an_error_not_silent_defaults() {
3137        let f = write_toml("[zai\nenabled = true\n");
3138        assert!(Config::load_from(f.path()).is_err());
3139    }
3140
3141    #[test]
3142    fn a_missing_file_is_still_just_defaults() {
3143        // Absence stays the legitimate "use defaults" case — only real parse
3144        // and I/O failures are errors.
3145        let dir = tempfile::tempdir().unwrap();
3146        let missing = dir.path().join("nope").join("config.toml");
3147        let c = Config::load_from(&missing).unwrap();
3148        assert!(c.is_enabled(VendorId::Anthropic));
3149    }
3150
3151    #[test]
3152    fn kimi_appears_when_enabled() {
3153        let f = write_toml(
3154            r#"
3155            [kimi]
3156            enabled = true
3157            api_key = "sk-test"
3158            "#,
3159        );
3160        let c = Config::load_from(f.path()).unwrap();
3161        assert!(c.is_enabled(VendorId::Kimi));
3162        assert!(c.enabled_vendors().contains(&VendorId::Kimi));
3163        assert_eq!(c.kimi.api_key.as_deref(), Some("sk-test"));
3164    }
3165
3166    #[test]
3167    fn enabled_deepseek_and_kimi_appear_in_canonical_order_ending_with_them() {
3168        let f = write_toml(
3169            r#"
3170            [deepseek]
3171            enabled = true
3172            api_key = "sk-ds"
3173
3174            [kimi]
3175            enabled = true
3176            api_key = "sk-kimi"
3177            "#,
3178        );
3179        let c = Config::load_from(f.path()).unwrap();
3180        assert_eq!(
3181            c.enabled_vendors(),
3182            vec![
3183                VendorId::Anthropic,
3184                VendorId::Openai,
3185                VendorId::Zai,
3186                VendorId::Openrouter,
3187                VendorId::Deepseek,
3188                VendorId::Kimi,
3189            ]
3190        );
3191    }
3192
3193    #[test]
3194    fn parses_anthropic_accounts_and_looks_them_up() {
3195        let f = write_toml(
3196            r#"
3197            [anthropic]
3198            enabled = true
3199
3200            [[anthropic.accounts]]
3201            label = "personal"
3202            credentials_path = "/creds/personal.json"
3203
3204            [[anthropic.accounts]]
3205            label = "work"
3206            credentials_path = "/creds/work.json"
3207            "#,
3208        );
3209        let c = Config::load_from(f.path()).unwrap();
3210        assert_eq!(c.anthropic.accounts.len(), 2);
3211        let work = c.anthropic.account("work").unwrap();
3212        assert_eq!(work.credentials_path, PathBuf::from("/creds/work.json"));
3213        // A typo names the offending label and lists the known ones.
3214        let err = format!("{:?}", c.anthropic.account("missing").unwrap_err());
3215        assert!(err.contains("missing") && err.contains("work"), "{err}");
3216    }
3217
3218    #[test]
3219    fn duplicate_anthropic_account_labels_are_rejected_on_load() {
3220        let f = write_toml(
3221            r#"
3222            [[anthropic.accounts]]
3223            label = "work"
3224            credentials_path = "/creds/work-one.json"
3225
3226            [[anthropic.accounts]]
3227            label = "work"
3228            credentials_path = "/creds/work-two.json"
3229            "#,
3230        );
3231        let err = Config::load_from(f.path()).unwrap_err().to_string();
3232        assert!(
3233            err.contains("duplicate anthropic account label \"work\""),
3234            "{err}"
3235        );
3236    }
3237
3238    #[test]
3239    fn account_label_rejects_path_like_names() {
3240        let cfg = AnthropicConfig::default();
3241        for bad in [
3242            "",
3243            ".",
3244            "..",
3245            "a/b",
3246            r"a\b",
3247            "C:work",
3248            "line\nbreak",
3249            "tab\tname",
3250            "usage.json",
3251            ".stale",
3252            ".last_error",
3253            ".fetch.lock",
3254        ] {
3255            let err = cfg.account(bad).unwrap_err();
3256            assert!(
3257                format!("{err:?}").contains("invalid anthropic account label"),
3258                "{bad:?} should be rejected as a label"
3259            );
3260        }
3261    }
3262
3263    #[test]
3264    fn anthropic_accounts_default_to_empty() {
3265        // No [[anthropic.accounts]] → the single default account, empty list,
3266        // nothing to migrate (issue #14, back-compat rule 1).
3267        assert!(Config::default().anthropic.accounts.is_empty());
3268        assert!(Config::default().anthropic.accounts_dir.is_none());
3269    }
3270
3271    // --- accounts_dir: CLAUDE_CONFIG_DIR-style auto-discovery ----------------
3272    // All hermetic: discovery reads a TempDir, never the user's real config.
3273
3274    /// Create `<root>/<label>/.credentials.json` (contents irrelevant here —
3275    /// discovery keys on the file existing, the fetch path parses it).
3276    fn seed_account_dir(root: &std::path::Path, label: &str) {
3277        let dir = root.join(label);
3278        std::fs::create_dir_all(&dir).unwrap();
3279        std::fs::write(dir.join(".credentials.json"), "{}").unwrap();
3280    }
3281
3282    #[test]
3283    fn discovers_account_dirs_in_claude_config_dir_layout() {
3284        let td = tempfile::tempdir().unwrap();
3285        seed_account_dir(td.path(), "work");
3286        seed_account_dir(td.path(), "personal");
3287        // Keychain-backed macOS logins may not write .credentials.json; their
3288        // config directories are still account entries.
3289        std::fs::create_dir_all(td.path().join("keychain-only")).unwrap();
3290        // A loose file (not a dir) is ignored.
3291        std::fs::write(td.path().join("stray.json"), "{}").unwrap();
3292
3293        let cfg = AnthropicConfig {
3294            accounts_dir: Some(td.path().to_path_buf()),
3295            ..Default::default()
3296        };
3297        let all = cfg.all_accounts();
3298        let labels: Vec<&str> = all.iter().map(|a| a.label.as_str()).collect();
3299        assert_eq!(labels, vec!["keychain-only", "personal", "work"]);
3300        assert_eq!(
3301            all[2].credentials_path,
3302            td.path().join("work").join(".credentials.json")
3303        );
3304    }
3305
3306    #[test]
3307    fn explicit_account_wins_over_a_discovered_one_with_the_same_label() {
3308        let td = tempfile::tempdir().unwrap();
3309        seed_account_dir(td.path(), "work");
3310        let cfg = AnthropicConfig {
3311            accounts: vec![AnthropicAccount {
3312                label: "work".into(),
3313                credentials_path: "/explicit/work.json".into(),
3314            }],
3315            accounts_dir: Some(td.path().to_path_buf()),
3316            ..Default::default()
3317        };
3318        let all = cfg.all_accounts();
3319        assert_eq!(all.len(), 1, "no duplicate label");
3320        assert_eq!(
3321            all[0].credentials_path,
3322            std::path::Path::new("/explicit/work.json"),
3323            "explicit entry wins"
3324        );
3325        // A discovered account is still reachable through `account()`.
3326        seed_account_dir(td.path(), "other");
3327        assert_eq!(cfg.account("other").unwrap().label, "other");
3328    }
3329
3330    #[test]
3331    fn missing_accounts_dir_is_silently_empty_not_an_error() {
3332        let cfg = AnthropicConfig {
3333            accounts_dir: Some("/nonexistent/ai-usagebar-accounts".into()),
3334            ..Default::default()
3335        };
3336        assert!(cfg.all_accounts().is_empty());
3337    }
3338
3339    #[test]
3340    fn openai_account_auth_paths_are_tilde_expanded_on_load() {
3341        let f = write_toml(
3342            r#"
3343            [[openai.accounts]]
3344            label = "work"
3345            codex_auth_path = "~/.codex-work/auth.json"
3346            "#,
3347        );
3348        let c = Config::load_from(f.path()).unwrap();
3349        let home = crate::cache::home_dir().unwrap();
3350        assert_eq!(
3351            c.openai.accounts[0].codex_auth_path,
3352            home.join(".codex-work/auth.json")
3353        );
3354    }
3355
3356    #[test]
3357    fn accounts_dir_is_tilde_expanded_on_load() {
3358        let f = write_toml(
3359            r#"
3360            [anthropic]
3361            accounts_dir = "~/.config/ai-usagebar/accounts"
3362            "#,
3363        );
3364        let c = Config::load_from(f.path()).unwrap();
3365        let home = crate::cache::home_dir().unwrap();
3366        assert_eq!(
3367            c.anthropic.accounts_dir,
3368            Some(home.join(".config/ai-usagebar/accounts"))
3369        );
3370    }
3371
3372    #[test]
3373    fn desktop_profiles_dir_is_tilde_expanded_on_load() {
3374        let f = write_toml(
3375            r#"
3376            [anthropic]
3377            desktop_profiles_dir = "~/.claude-acc/profiles"
3378            "#,
3379        );
3380        let c = Config::load_from(f.path()).unwrap();
3381        let home = crate::cache::home_dir().unwrap();
3382        assert_eq!(
3383            c.anthropic.desktop_profiles_dir,
3384            Some(home.join(".claude-acc/profiles"))
3385        );
3386    }
3387
3388    #[test]
3389    fn the_live_cli_account_is_read_from_the_default_credential_slot() {
3390        let cfg = AnthropicConfig {
3391            accounts: vec![
3392                AnthropicAccount {
3393                    label: "work".into(),
3394                    credentials_path: "/tmp/accounts/work/.credentials.json".into(),
3395                },
3396                AnthropicAccount {
3397                    label: "personal".into(),
3398                    credentials_path: "/tmp/accounts/personal/.credentials.json".into(),
3399                },
3400            ],
3401            ..Default::default()
3402        };
3403
3404        let (idle, idle_cache) = cfg.account_target_with("work", Some("personal")).unwrap();
3405        assert!(
3406            matches!(&idle, CredsTarget::Named { config_dir, .. }
3407                if config_dir == std::path::Path::new("/tmp/accounts/work")),
3408            "{idle:?}"
3409        );
3410
3411        // Same label, but it is the login `claude` itself is using: one lineage.
3412        let (live, live_cache) = cfg.account_target_with("work", Some("work")).unwrap();
3413        assert!(matches!(live, CredsTarget::Default(_)), "{live:?}");
3414
3415        // The cache must not move, or a switch would silently orphan the tab's
3416        // usage history and show "Loading…" until the next fetch.
3417        assert_eq!(idle_cache.dir(), live_cache.dir());
3418    }
3419
3420    #[test]
3421    fn no_live_cli_account_keeps_every_account_on_its_own_slot() {
3422        let cfg = AnthropicConfig {
3423            accounts: vec![AnthropicAccount {
3424                label: "work".into(),
3425                credentials_path: "/tmp/accounts/work/.credentials.json".into(),
3426            }],
3427            ..Default::default()
3428        };
3429        let (target, _) = cfg.account_target_with("work", None).unwrap();
3430        assert!(matches!(target, CredsTarget::Named { .. }), "{target:?}");
3431    }
3432
3433    /// The shipped example, which `make install` puts in
3434    /// `share/ai-usagebar/config.example.toml`. Repo-relative, so this stays
3435    /// hermetic — it never touches the user's real config.
3436    fn config_example() -> PathBuf {
3437        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.example.toml")
3438    }
3439
3440    #[test]
3441    fn shipped_example_parses_as_a_real_config() {
3442        // The example is documentation users copy verbatim, but nothing used
3443        // to parse it — so a renamed section or field could rot there
3444        // unnoticed, and `deny_unknown_fields` would reject the copy on the
3445        // user's machine instead of in CI.
3446        let c = Config::load_from(&config_example()).unwrap();
3447        assert!(!c.context.enabled);
3448        assert!(c.is_enabled(VendorId::Anthropic));
3449        assert!(c.is_enabled(VendorId::Openai));
3450        assert!(!c.is_enabled(VendorId::AnthropicApi));
3451        assert!(!c.is_enabled(VendorId::Deepseek));
3452        assert!(!c.is_enabled(VendorId::Kimi));
3453        assert!(!c.is_enabled(VendorId::Kilo));
3454        assert!(!c.is_enabled(VendorId::Novita));
3455        assert!(!c.is_enabled(VendorId::Moonshot));
3456        assert!(!c.is_enabled(VendorId::Grok));
3457        assert!(!c.is_enabled(VendorId::Cursor));
3458        assert!(!c.is_enabled(VendorId::Minimax));
3459    }
3460
3461    #[test]
3462    fn shipped_example_does_not_advertise_admin_key_env_as_working() {
3463        // The regression: the example shipped an *uncommented*
3464        // `admin_key_env = "OPENAI_ADMIN_KEY"`, indistinguishable from a live
3465        // setting. Nothing reads it, so a user could set it, skip
3466        // `codex login`, and wait for usage that never arrives.
3467        let text = std::fs::read_to_string(config_example()).unwrap();
3468        let live: Vec<&str> = text
3469            .lines()
3470            .map(str::trim)
3471            .filter(|l| l.contains("admin_key_env") && !l.starts_with('#'))
3472            .collect();
3473        assert!(
3474            live.is_empty(),
3475            "admin_key_env must stay commented out while it is inert: {live:?}"
3476        );
3477        // Still documented, though — silently dropping it would leave users
3478        // who already set it with no explanation of why it does nothing.
3479        assert!(
3480            text.contains("admin_key_env") && text.contains("RESERVED"),
3481            "the example should keep describing admin_key_env as reserved"
3482        );
3483    }
3484
3485    #[test]
3486    fn admin_key_env_is_accepted_but_changes_nothing() {
3487        // The field survives because the API-key-only path is still intended.
3488        // What has to hold today is narrower: setting it loads without error
3489        // and moves nothing the code actually acts on.
3490        let f = write_toml(
3491            r#"
3492            [openai]
3493            admin_key_env = "SOME_ADMIN_KEY"
3494            "#,
3495        );
3496        let c = Config::load_from(f.path()).unwrap();
3497        assert_eq!(c.openai.admin_key_env, "SOME_ADMIN_KEY");
3498        // Nothing else moved: OpenAI still resolves through Codex OAuth only.
3499        let default = OpenAiConfig::default();
3500        assert_eq!(c.openai.enabled, default.enabled);
3501        assert_eq!(c.openai.codex_auth_path, default.codex_auth_path);
3502        assert_eq!(c.enabled_vendors(), Config::default().enabled_vendors());
3503    }
3504
3505    #[test]
3506    fn config_example_documents_every_vendor_without_secrets() {
3507        let raw = std::fs::read_to_string(config_example()).unwrap();
3508        let cfg = Config::load_from(&config_example()).unwrap();
3509        // Every vendor the binary can dispatch needs a documented section, or
3510        // users have no way to discover how to turn it on.
3511        for id in VendorId::all() {
3512            let section = id.slug();
3513            assert!(
3514                raw.contains(&format!("[{section}]")),
3515                "config.example.toml has no [{section}] section"
3516            );
3517        }
3518
3519        // The example must not ship anything enabled-by-key-only, and must not
3520        // carry a real secret.
3521        assert!(!cfg.anthropic_api.enabled && cfg.anthropic_api.api_key.is_none());
3522        assert!(!cfg.kilo.enabled && cfg.kilo.api_key.is_none());
3523        assert!(!cfg.novita.enabled && cfg.novita.api_key.is_none());
3524        assert!(!cfg.moonshot.enabled && cfg.moonshot.api_key.is_none());
3525        assert!(!cfg.grok.enabled && cfg.grok.api_key.is_none());
3526        assert!(!cfg.supergrok.enabled);
3527        assert_eq!(cfg.supergrok.grok_binary, default_grok_binary());
3528        assert_eq!(
3529            cfg.supergrok
3530                .grok_binary
3531                .file_name()
3532                .and_then(|p| p.to_str()),
3533            Some(if cfg!(windows) { "grok.exe" } else { "grok" })
3534        );
3535        assert!(cfg.supergrok.auth_path.is_none());
3536        assert!(cfg.supergrok.config_path.is_none());
3537        assert!(!cfg.cursor.enabled && cfg.cursor.db_path.is_none());
3538        assert!(!cfg.kiro.enabled && cfg.kiro.db_path.is_none());
3539    }
3540
3541    #[test]
3542    fn supergrok_binary_must_not_be_empty() {
3543        let file = write_toml(
3544            r#"
3545            [supergrok]
3546            enabled = true
3547            grok_binary = ""
3548            "#,
3549        );
3550        let error = Config::load_from(file.path()).unwrap_err().to_string();
3551        assert!(error.contains("grok_binary must not be empty"));
3552    }
3553
3554    #[test]
3555    fn supergrok_paths_are_tilde_expanded() {
3556        let file = write_toml(
3557            r#"
3558            [supergrok]
3559            grok_binary = "~/bin/grok"
3560            auth_path = "~/.grok/auth.json"
3561            config_path = "~/.grok/config.toml"
3562            "#,
3563        );
3564        let config = Config::load_from(file.path()).unwrap();
3565        let home = crate::cache::home_dir().unwrap();
3566        assert_eq!(config.supergrok.grok_binary, home.join("bin/grok"));
3567        assert_eq!(
3568            config.supergrok.auth_path,
3569            Some(home.join(".grok/auth.json"))
3570        );
3571        assert_eq!(
3572            config.supergrok.config_path,
3573            Some(home.join(".grok/config.toml"))
3574        );
3575    }
3576
3577    #[test]
3578    fn kiro_db_path_is_tilde_expanded() {
3579        let f = write_toml(
3580            r#"
3581            [kiro]
3582            db_path = "~/kiro-data.sqlite3"
3583            "#,
3584        );
3585        let c = Config::load_from(f.path()).unwrap();
3586        let home = crate::cache::home_dir().unwrap();
3587        assert_eq!(c.kiro.db_path, Some(home.join("kiro-data.sqlite3")));
3588    }
3589
3590    #[test]
3591    fn kiro_appears_when_enabled() {
3592        let f = write_toml(
3593            r#"
3594            [kiro]
3595            enabled = true
3596            "#,
3597        );
3598        let c = Config::load_from(f.path()).unwrap();
3599        assert!(c.is_enabled(VendorId::Kiro));
3600        assert!(c.enabled_vendors().contains(&VendorId::Kiro));
3601    }
3602
3603    #[test]
3604    fn cursor_db_path_is_tilde_expanded() {
3605        let f = write_toml(
3606            r#"
3607            [cursor]
3608            db_path = "~/cursor-state.vscdb"
3609            "#,
3610        );
3611        let c = Config::load_from(f.path()).unwrap();
3612        let home = crate::cache::home_dir().unwrap();
3613        assert_eq!(c.cursor.db_path, Some(home.join("cursor-state.vscdb")));
3614    }
3615
3616    #[test]
3617    fn cursor_agent_auth_path_is_tilde_expanded() {
3618        let f = write_toml(
3619            r#"
3620            [cursor]
3621            agent_auth_path = "~/cursor-agent-auth.json"
3622            "#,
3623        );
3624        let c = Config::load_from(f.path()).unwrap();
3625        let home = crate::cache::home_dir().unwrap();
3626        assert_eq!(
3627            c.cursor.agent_auth_path,
3628            Some(home.join("cursor-agent-auth.json"))
3629        );
3630    }
3631
3632    #[test]
3633    fn cursor_appears_when_enabled() {
3634        let f = write_toml(
3635            r#"
3636            [cursor]
3637            enabled = true
3638            "#,
3639        );
3640        let c = Config::load_from(f.path()).unwrap();
3641        assert!(c.is_enabled(VendorId::Cursor));
3642        assert!(c.enabled_vendors().contains(&VendorId::Cursor));
3643    }
3644
3645    #[test]
3646    fn add_account_appends_and_preserves_existing() {
3647        let mut doc: toml_edit::DocumentMut = r#"
3648# keep me
3649[anthropic]
3650enabled = true
3651
3652[[anthropic.accounts]]
3653label = "personal"
3654credentials_path = "~/.config/ai-usagebar/accounts/personal/.credentials.json"
3655"#
3656        .parse()
3657        .unwrap();
3658        add_anthropic_account_to_doc(
3659            &mut doc,
3660            "work",
3661            "~/.config/ai-usagebar/accounts/work/.credentials.json",
3662        )
3663        .unwrap();
3664        let rendered = doc.to_string();
3665        assert!(rendered.contains("# keep me"), "comment must survive");
3666        // Round-trips through the real loader with both accounts intact and ordered.
3667        let f = write_toml(&rendered);
3668        let c = Config::load_from(f.path()).unwrap();
3669        let labels: Vec<&str> = c
3670            .anthropic
3671            .accounts
3672            .iter()
3673            .map(|a| a.label.as_str())
3674            .collect();
3675        assert_eq!(labels, vec!["personal", "work"]);
3676    }
3677
3678    #[test]
3679    fn add_account_to_empty_doc_is_loadable() {
3680        let mut doc = toml_edit::DocumentMut::new();
3681        add_anthropic_account_to_doc(&mut doc, "solo", "~/x/.credentials.json").unwrap();
3682        let f = write_toml(&doc.to_string());
3683        let c = Config::load_from(f.path()).unwrap();
3684        assert_eq!(c.anthropic.accounts.len(), 1);
3685        assert_eq!(c.anthropic.accounts[0].label, "solo");
3686    }
3687
3688    #[test]
3689    fn add_account_rejects_duplicate_label() {
3690        let mut doc: toml_edit::DocumentMut = r#"
3691[[anthropic.accounts]]
3692label = "work"
3693credentials_path = "~/w/.credentials.json"
3694"#
3695        .parse()
3696        .unwrap();
3697        assert!(
3698            add_anthropic_account_to_doc(&mut doc, "work", "~/other/.credentials.json").is_err(),
3699            "a duplicate label must be rejected, not appended"
3700        );
3701    }
3702
3703    #[test]
3704    fn add_account_rejects_bad_label() {
3705        let mut doc = toml_edit::DocumentMut::new();
3706        assert!(add_anthropic_account_to_doc(&mut doc, "a/b", "~/x/.credentials.json").is_err());
3707        assert!(add_anthropic_account_to_doc(&mut doc, "", "~/x/.credentials.json").is_err());
3708    }
3709
3710    #[test]
3711    fn tildify_collapses_home_only() {
3712        let home = Path::new("/Users/me");
3713        assert_eq!(tildify(&home.join("a/b"), home), "~/a/b");
3714        assert_eq!(tildify(Path::new("/etc/hosts"), home), "/etc/hosts");
3715    }
3716
3717    #[test]
3718    fn default_account_credentials_path_nests_under_config_dir() {
3719        let cfg = Path::new("/home/u/.config/ai-usagebar/config.toml");
3720        assert_eq!(
3721            default_account_credentials_path(cfg, "work"),
3722            Path::new("/home/u/.config/ai-usagebar/accounts/work/.credentials.json"),
3723        );
3724    }
3725    // ----- [[custom]] providers -----
3726
3727    const CUSTOM_BLOCK: &str = r#"
3728[[custom]]
3729id = "mytool"
3730name = "My Tool"
3731short_name = "myt"
3732enabled = true
3733url = "https://api.example.test/v1/usage"
3734api_key_env = "MYTOOL_API_KEY"
3735auth_header = "Authorization"
3736auth_scheme = "Bearer"
3737plan = "Pro"
3738cache_ttl_secs = 120
3739[custom.headers]
3740X-Org = "org_1"
3741[[custom.metrics]]
3742label = "Requests"
3743used = "/requests/used"
3744limit = "/requests/limit"
3745resets_at = "/requests/reset"
3746window_secs = 3600
3747[[custom.texts]]
3748label = "Tier"
3749value = "/tier"
3750"#;
3751
3752    fn custom_with(from: &str, to: &str) -> String {
3753        assert!(CUSTOM_BLOCK.contains(from), "fixture has no {from:?}");
3754        CUSTOM_BLOCK.replace(from, to)
3755    }
3756
3757    fn custom_error(toml: &str) -> String {
3758        Config::load_from(write_toml(toml).path())
3759            .unwrap_err()
3760            .to_string()
3761    }
3762
3763    fn assert_custom_rejected(toml: &str, needle: &str) {
3764        let msg = custom_error(toml);
3765        assert!(msg.contains(needle), "expected {needle:?} in: {msg}");
3766        assert!(
3767            msg.contains("[[custom]]"),
3768            "the error must locate the section: {msg}"
3769        );
3770    }
3771
3772    #[test]
3773    fn custom_block_parses_every_field() {
3774        let config = Config::load_from(write_toml(CUSTOM_BLOCK).path()).unwrap();
3775        assert_eq!(config.custom.len(), 1);
3776        let c = &config.custom[0];
3777        assert_eq!(c.id, "mytool");
3778        assert_eq!(c.name, "My Tool");
3779        assert_eq!(c.short_name, "myt");
3780        assert!(c.enabled);
3781        assert_eq!(c.url, "https://api.example.test/v1/usage");
3782        assert!(!c.allow_http);
3783        assert_eq!(c.api_key_env, "MYTOOL_API_KEY");
3784        assert_eq!(c.api_key, None);
3785        assert_eq!(c.auth_header, "Authorization");
3786        assert_eq!(c.auth_scheme, "Bearer");
3787        assert_eq!(c.headers.get("X-Org").map(String::as_str), Some("org_1"));
3788        assert_eq!(c.plan.as_deref(), Some("Pro"));
3789        assert_eq!(c.plan_path, None);
3790        assert_eq!(c.cache_ttl(), std::time::Duration::from_secs(120));
3791        assert_eq!(c.metrics.len(), 1);
3792        assert_eq!(c.metrics[0].label, "Requests");
3793        assert_eq!(c.metrics[0].used.as_deref(), Some("/requests/used"));
3794        assert_eq!(c.metrics[0].limit.as_deref(), Some("/requests/limit"));
3795        assert_eq!(c.metrics[0].percent, None);
3796        assert_eq!(c.metrics[0].resets_at.as_deref(), Some("/requests/reset"));
3797        assert_eq!(c.metrics[0].window_secs, Some(3600));
3798        assert_eq!(c.texts.len(), 1);
3799        assert_eq!(c.texts[0].label, "Tier");
3800        assert_eq!(c.texts[0].value, "/tier");
3801        assert_eq!(c.section_label(), r#"[[custom]] id = "mytool""#);
3802    }
3803
3804    #[test]
3805    fn custom_defaults_are_the_documented_ones_and_name_falls_back_to_id() {
3806        let config: Config = toml::from_str(
3807            r#"
3808            [[custom]]
3809            id = "bare"
3810            short_name = "bre"
3811            url = "https://example.test/u"
3812            [[custom.metrics]]
3813            label = "Q"
3814            percent = "/pct"
3815            "#,
3816        )
3817        .unwrap();
3818        let c = &config.custom[0];
3819        assert_eq!(c.name, "bare", "name must default to id on a plain parse");
3820        assert!(!c.enabled);
3821        assert!(!c.allow_http);
3822        assert_eq!(c.api_key_env, "");
3823        assert_eq!(c.auth_header, "Authorization");
3824        assert_eq!(c.auth_scheme, "Bearer");
3825        assert_eq!(c.cache_ttl_secs, 60);
3826        assert!(config.validate().is_ok());
3827        assert!(Config::default().custom.is_empty());
3828    }
3829
3830    #[test]
3831    fn custom_rejects_a_malformed_id() {
3832        let long = "a".repeat(33);
3833        for id in ["", "My Tool", "-lead", "UPPER", long.as_str()] {
3834            let msg = custom_error(&custom_with(r#"id = "mytool""#, &format!("id = {id:?}")));
3835            assert!(msg.contains("[[custom]] entry #1"), "{id:?}: {msg}");
3836            assert!(msg.contains("must match"), "{id:?}: {msg}");
3837        }
3838    }
3839
3840    #[test]
3841    fn custom_rejects_a_builtin_slug_as_id() {
3842        assert_custom_rejected(
3843            &custom_with(r#"id = "mytool""#, r#"id = "deepseek""#),
3844            "is a built-in vendor",
3845        );
3846        assert_custom_rejected(
3847            &custom_with(r#"id = "mytool""#, r#"id = "opencode-go""#),
3848            "is a built-in vendor",
3849        );
3850    }
3851
3852    #[test]
3853    fn custom_rejects_duplicate_ids() {
3854        let twice = format!(
3855            "{}{}",
3856            CUSTOM_BLOCK,
3857            custom_with(r#"short_name = "myt""#, r#"short_name = "myu""#)
3858        );
3859        assert_custom_rejected(&twice, "duplicate id");
3860    }
3861
3862    #[test]
3863    fn custom_rejects_a_name_over_48_chars() {
3864        let long = "n".repeat(49);
3865        assert_custom_rejected(
3866            &custom_with(r#"name = "My Tool""#, &format!("name = {long:?}")),
3867            "name must be 1 to 48 characters",
3868        );
3869    }
3870
3871    #[test]
3872    fn custom_rejects_a_short_name_that_is_not_three_lowercase_letters() {
3873        for short in ["my", "myto", "MYT", "m1t"] {
3874            assert_custom_rejected(
3875                &custom_with(r#"short_name = "myt""#, &format!("short_name = {short:?}")),
3876                "exactly 3 lowercase ASCII letters",
3877            );
3878        }
3879    }
3880
3881    #[test]
3882    fn custom_rejects_a_short_name_taken_by_a_builtin_or_another_entry() {
3883        assert_custom_rejected(
3884            &custom_with(r#"short_name = "myt""#, r#"short_name = "dsk""#),
3885            "already used by a built-in vendor",
3886        );
3887        let twice = format!(
3888            "{}{}",
3889            CUSTOM_BLOCK,
3890            custom_with(r#"id = "mytool""#, r#"id = "othertool""#)
3891        );
3892        assert_custom_rejected(&twice, "already used by a built-in vendor");
3893    }
3894
3895    #[test]
3896    fn custom_rejects_http_unless_allowed() {
3897        let plain = custom_with(
3898            r#"url = "https://api.example.test/v1/usage""#,
3899            r#"url = "http://localhost:8080/usage""#,
3900        );
3901        assert_custom_rejected(&plain, "url must use https://");
3902        let allowed = plain.replace(
3903            r#"url = "http://localhost:8080/usage""#,
3904            "url = \"http://localhost:8080/usage\"\nallow_http = true",
3905        );
3906        assert!(
3907            Config::load_from(write_toml(&allowed).path()).is_ok(),
3908            "allow_http must permit http://"
3909        );
3910    }
3911
3912    #[test]
3913    fn custom_rejects_a_url_with_userinfo_or_a_bad_scheme_or_garbage() {
3914        assert_custom_rejected(
3915            &custom_with(
3916                r#"url = "https://api.example.test/v1/usage""#,
3917                r#"url = "https://user:pw@api.example.test/v1/usage""#,
3918            ),
3919            "must not carry credentials",
3920        );
3921        assert_custom_rejected(
3922            &custom_with(
3923                r#"url = "https://api.example.test/v1/usage""#,
3924                r#"url = "not a url""#,
3925            ),
3926            "is not a valid URL",
3927        );
3928        assert_custom_rejected(
3929            &custom_with(
3930                r#"url = "https://api.example.test/v1/usage""#,
3931                r#"url = "ftp://api.example.test/v1/usage""#,
3932            ),
3933            "is not http or https",
3934        );
3935    }
3936
3937    #[test]
3938    fn custom_rejects_an_invalid_api_key_env() {
3939        assert_custom_rejected(
3940            &custom_with(
3941                r#"api_key_env = "MYTOOL_API_KEY""#,
3942                r#"api_key_env = "1BAD-NAME""#,
3943            ),
3944            "is not a valid environment variable name",
3945        );
3946        let none = custom_with(r#"api_key_env = "MYTOOL_API_KEY""#, r#"api_key_env = """#);
3947        assert!(
3948            Config::load_from(write_toml(&none).path()).is_ok(),
3949            "an empty api_key_env means inline-only and is valid"
3950        );
3951    }
3952
3953    #[test]
3954    fn custom_rejects_an_invalid_auth_header_name() {
3955        assert_custom_rejected(
3956            &custom_with(
3957                r#"auth_header = "Authorization""#,
3958                r#"auth_header = "X Api Key""#,
3959            ),
3960            "auth_header \"X Api Key\" is not a valid HTTP header name",
3961        );
3962    }
3963
3964    #[test]
3965    fn custom_rejects_a_control_char_in_auth_scheme() {
3966        assert_custom_rejected(
3967            &custom_with(
3968                r#"auth_scheme = "Bearer""#,
3969                "auth_scheme = \"Bearer\\u0007\"",
3970            ),
3971            "auth_scheme contains characters that are not valid",
3972        );
3973        let bare = custom_with(r#"auth_scheme = "Bearer""#, r#"auth_scheme = """#);
3974        assert!(
3975            Config::load_from(write_toml(&bare).path()).is_ok(),
3976            "an empty scheme (bare key) is valid"
3977        );
3978    }
3979
3980    #[test]
3981    fn custom_rejects_a_bad_extra_header() {
3982        assert_custom_rejected(
3983            &custom_with(r#"X-Org = "org_1""#, r#"authorization = "Bearer other""#),
3984            "headers must not repeat auth_header",
3985        );
3986        assert_custom_rejected(
3987            &custom_with(r#"X-Org = "org_1""#, r#""X Org" = "org_1""#),
3988            "is not a valid HTTP header name",
3989        );
3990        assert_custom_rejected(
3991            &custom_with(r#"X-Org = "org_1""#, "X-Org = \"org\\u0001\""),
3992            "has a value that is not valid in an HTTP header",
3993        );
3994    }
3995
3996    #[test]
3997    fn custom_rejects_cache_ttl_outside_10_to_3600() {
3998        for ttl in ["9", "3601"] {
3999            assert_custom_rejected(
4000                &custom_with("cache_ttl_secs = 120", &format!("cache_ttl_secs = {ttl}")),
4001                "cache_ttl_secs must be between 10 and 3600",
4002            );
4003        }
4004    }
4005
4006    #[test]
4007    fn custom_rejects_an_entry_with_no_metrics_or_texts() {
4008        let toml = r#"
4009[[custom]]
4010id = "empty"
4011short_name = "emp"
4012url = "https://example.test/u"
4013"#;
4014        assert_custom_rejected(toml, "at least one [[custom.metrics]] or [[custom.texts]]");
4015    }
4016
4017    #[test]
4018    fn custom_rejects_a_metric_mixing_percent_with_used_or_limit() {
4019        assert_custom_rejected(
4020            &custom_with(
4021                r#"limit = "/requests/limit""#,
4022                "limit = \"/requests/limit\"\npercent = \"/requests/pct\"",
4023            ),
4024            "must set `percent`, or both `used` and `limit`",
4025        );
4026        assert_custom_rejected(
4027            &custom_with("limit = \"/requests/limit\"\n", ""),
4028            "must set `percent`, or both `used` and `limit`",
4029        );
4030    }
4031
4032    #[test]
4033    fn custom_rejects_a_pointer_without_a_leading_slash() {
4034        assert_custom_rejected(
4035            &custom_with(r#"used = "/requests/used""#, r#"used = "requests.used""#),
4036            "used \"requests.used\" must be an RFC 6901 JSON Pointer",
4037        );
4038        assert_custom_rejected(
4039            &custom_with(r#"value = "/tier""#, r#"value = "tier""#),
4040            "value \"tier\" must be an RFC 6901 JSON Pointer",
4041        );
4042        assert_custom_rejected(
4043            &custom_with(r#"plan = "Pro""#, r#"plan_path = "plan""#),
4044            "plan_path \"plan\" must be an RFC 6901 JSON Pointer",
4045        );
4046        assert_custom_rejected(
4047            &custom_with(
4048                r#"resets_at = "/requests/reset""#,
4049                "resets_at = \"/re\\u001bset\"",
4050            ),
4051            "resets_at",
4052        );
4053    }
4054
4055    #[test]
4056    fn custom_rejects_a_label_outside_1_to_64_chars() {
4057        let long = "l".repeat(65);
4058        assert_custom_rejected(
4059            &custom_with(r#"label = "Requests""#, &format!("label = {long:?}")),
4060            "metric label",
4061        );
4062        assert_custom_rejected(
4063            &custom_with(r#"label = "Tier""#, r#"label = """#),
4064            "text label \"\" must be 1 to 64 characters",
4065        );
4066    }
4067
4068    #[test]
4069    fn custom_rejects_window_secs_under_60() {
4070        assert_custom_rejected(
4071            &custom_with("window_secs = 3600", "window_secs = 59"),
4072            "window_secs must be at least 60",
4073        );
4074    }
4075
4076    #[test]
4077    fn custom_rejects_duplicate_metric_and_text_labels() {
4078        let metric_twice = custom_with(
4079            "window_secs = 3600\n",
4080            "window_secs = 3600\n[[custom.metrics]]\nlabel = \"Requests\"\npercent = \"/pct\"\n",
4081        );
4082        assert_custom_rejected(&metric_twice, "duplicate metric label \"Requests\"");
4083        let text_twice =
4084            format!("{CUSTOM_BLOCK}[[custom.texts]]\nlabel = \"Tier\"\nvalue = \"/other\"\n");
4085        assert_custom_rejected(&text_twice, "duplicate text label \"Tier\"");
4086    }
4087
4088    #[test]
4089    fn enabled_custom_and_custom_by_id_select_entries() {
4090        let two = format!(
4091            "{}{}",
4092            CUSTOM_BLOCK,
4093            custom_with(r#"id = "mytool""#, r#"id = "off""#)
4094                .replace(r#"short_name = "myt""#, r#"short_name = "off""#)
4095                .replace("enabled = true", "enabled = false")
4096        );
4097        let config = Config::load_from(write_toml(&two).path()).unwrap();
4098        let enabled: Vec<&str> = config.enabled_custom().map(|c| c.id.as_str()).collect();
4099        assert_eq!(enabled, ["mytool"]);
4100        assert_eq!(
4101            config.custom_by_id("off").map(|c| c.name.as_str()),
4102            Some("My Tool")
4103        );
4104        assert!(config.custom_by_id("nope").is_none());
4105    }
4106
4107    #[cfg(unix)]
4108    #[test]
4109    fn has_inline_secrets_sees_a_custom_inline_key() {
4110        let without: Config = toml::from_str(CUSTOM_BLOCK).unwrap();
4111        assert!(!without.has_inline_secrets());
4112        let with: Config = toml::from_str(&custom_with(
4113            r#"api_key_env = "MYTOOL_API_KEY""#,
4114            "api_key_env = \"MYTOOL_API_KEY\"\napi_key = \"sk-inline\"",
4115        ))
4116        .unwrap();
4117        assert!(with.has_inline_secrets());
4118    }
4119
4120    #[test]
4121    fn custom_resolve_api_key_prefers_env_then_inline_then_errors_without_the_key() {
4122        let var = "AI_USAGEBAR_CUSTOM_TEST_KEY_51C2";
4123        let mut spec = CustomProviderConfig {
4124            id: "mytool".into(),
4125            api_key_env: var.into(),
4126            api_key: Some("sk-inline-secret".into()),
4127            ..CustomProviderConfig::default()
4128        };
4129        unsafe { std::env::set_var(var, "sk-env-secret") };
4130        let from_env = spec.resolve_api_key();
4131        unsafe { std::env::remove_var(var) };
4132        assert_eq!(from_env.unwrap(), "sk-env-secret");
4133
4134        assert_eq!(spec.resolve_api_key().unwrap(), "sk-inline-secret");
4135
4136        spec.api_key = Some(String::new());
4137        let err = spec.resolve_api_key().unwrap_err();
4138        assert!(matches!(err, AppError::Credentials(_)), "{err:?}");
4139        let msg = err.to_string();
4140        assert!(msg.contains(r#"[[custom]] id = "mytool""#), "{msg}");
4141        assert!(msg.contains(var), "{msg}");
4142        assert!(!msg.contains("secret"), "{msg}");
4143
4144        spec.api_key_env = String::new();
4145        let msg = spec.resolve_api_key().unwrap_err().to_string();
4146        assert!(msg.contains("set `api_key`"), "{msg}");
4147    }
4148
4149    #[test]
4150    fn loading_a_config_registers_custom_env_vars_for_scrubbing() {
4151        let var = "AI_USAGEBAR_CUSTOM_SCRUB_TEST_9B1D";
4152        assert!(!crate::vendor::vendor_secret_env_vars_to_remove(&[]).contains(&var));
4153        let file = write_toml(&custom_with("MYTOOL_API_KEY", var));
4154        Config::load_from(file.path()).unwrap();
4155        assert!(
4156            crate::vendor::vendor_secret_env_vars_to_remove(&[]).contains(&var),
4157            "a custom provider's env var must be scrubbed from subprocesses"
4158        );
4159    }
4160
4161    /// `VendorId::config_section` is what every by-name config writer uses;
4162    /// this proves each section name is one the parser actually recognizes
4163    /// (the `deny_unknown_fields` on `Config` makes a misspelling fail loudly)
4164    /// and lands on that vendor's `enabled` switch.
4165    #[test]
4166    fn every_config_section_parses_to_its_vendors_enabled_switch() {
4167        for vendor in VendorId::all() {
4168            let text = format!(
4169                "[{}]
4170enabled = true
4171",
4172                vendor.config_section()
4173            );
4174            let config: Config = toml::from_str(&text)
4175                .unwrap_or_else(|e| panic!("{}: {e}", vendor.config_section()));
4176            assert!(config.is_enabled(*vendor), "{}", vendor.config_section());
4177            let others = VendorId::all()
4178                .iter()
4179                .filter(|other| *other != vendor && config.is_enabled(**other))
4180                .count();
4181            assert_eq!(
4182                others,
4183                Config::default().enabled_vendors().len()
4184                    - usize::from(Config::default().is_enabled(*vendor)),
4185                "[{}] enabled a different vendor",
4186                vendor.config_section()
4187            );
4188        }
4189    }
4190
4191    #[test]
4192    fn tray_section_parses_and_defaults_to_notify() {
4193        let file = write_toml("[tray]\nshortcut = \"Ctrl+Shift+U\"\nupdates = \"auto\"\n");
4194        let config = Config::load_from(file.path()).unwrap();
4195        assert_eq!(config.tray.shortcut.as_deref(), Some("Ctrl+Shift+U"));
4196        assert_eq!(config.tray.updates(), UpdateMode::Auto);
4197
4198        let empty = Config::load_from(write_toml("[ui]\n").path()).unwrap();
4199        assert_eq!(empty.tray, TrayConfig::default());
4200        assert_eq!(empty.tray.updates(), UpdateMode::Notify);
4201        assert_eq!(UpdateMode::parse(" Off "), Some(UpdateMode::Off));
4202        assert_eq!(UpdateMode::parse("weekly"), None);
4203        assert_eq!(UpdateMode::Auto.as_str(), "auto");
4204    }
4205
4206    #[test]
4207    fn tray_section_rejects_a_misspelled_mode() {
4208        let file = write_toml("[tray]\nupdates = \"sometimes\"\n");
4209        assert!(Config::load_from(file.path()).is_err());
4210    }
4211
4212    #[test]
4213    fn tray_refresh_minutes_defaults_to_five_and_parses() {
4214        let empty = Config::load_from(write_toml("[ui]\n").path()).unwrap();
4215        assert_eq!(empty.tray.refresh_minutes, None);
4216        assert_eq!(empty.tray.refresh_minutes(), 5);
4217
4218        let file = write_toml("[tray]\nrefresh_minutes = 10\n");
4219        let config = Config::load_from(file.path()).unwrap();
4220        assert_eq!(config.tray.refresh_minutes(), 10);
4221    }
4222
4223    #[test]
4224    fn tray_refresh_minutes_rejects_values_outside_the_menu() {
4225        for minutes in ["3", "0"] {
4226            let file = write_toml(&format!("[tray]\nrefresh_minutes = {minutes}\n"));
4227            let error = Config::load_from(file.path()).unwrap_err().to_string();
4228            assert!(error.contains("[tray] refresh_minutes"), "{error}");
4229            assert!(error.contains("1, 5 or 10"), "{error}");
4230        }
4231    }
4232
4233    #[test]
4234    fn set_tray_value_writes_refresh_minutes_as_an_integer() {
4235        let dir = tempfile::tempdir().unwrap();
4236        let path = dir.path().join("config.toml");
4237        std::fs::write(&path, "[tray]\nrefresh_minutes = 5 # mine\n").unwrap();
4238
4239        set_tray_value(&path, "refresh_minutes", Some(10i64.into())).unwrap();
4240        let text = std::fs::read_to_string(&path).unwrap();
4241        assert_eq!(text, "[tray]\nrefresh_minutes = 10 # mine\n");
4242        assert_eq!(Config::load_from(&path).unwrap().tray.refresh_minutes(), 10);
4243
4244        set_tray_value(&path, "refresh_minutes", None).unwrap();
4245        assert_eq!(Config::load_from(&path).unwrap().tray.refresh_minutes(), 5);
4246    }
4247
4248    #[test]
4249    fn set_tray_value_creates_replaces_and_removes_keys() {
4250        let dir = tempfile::tempdir().unwrap();
4251        let path = dir.path().join("config.toml");
4252        std::fs::write(&path, "[ui]\n# primary = \"anthropic\"\n").unwrap();
4253
4254        set_tray_value(&path, "shortcut", Some("Ctrl+Shift+U".into())).unwrap();
4255        let text = std::fs::read_to_string(&path).unwrap();
4256        assert!(text.contains("# primary = \"anthropic\""), "{text}");
4257        assert!(
4258            text.contains("[tray]\nshortcut = \"Ctrl+Shift+U\""),
4259            "{text}"
4260        );
4261
4262        set_tray_value(&path, "shortcut", Some("Alt+F5".into())).unwrap();
4263        set_tray_value(&path, "updates", Some("off".into())).unwrap();
4264        let config = Config::load_from(&path).unwrap();
4265        assert_eq!(config.tray.shortcut.as_deref(), Some("Alt+F5"));
4266        assert_eq!(config.tray.updates(), UpdateMode::Off);
4267
4268        set_tray_value(&path, "shortcut", None).unwrap();
4269        let text = std::fs::read_to_string(&path).unwrap();
4270        assert!(!text.contains("shortcut"), "{text}");
4271        assert!(text.contains("updates = \"off\""), "{text}");
4272
4273        // Idempotent removal does not rewrite the file.
4274        let mtime = std::fs::metadata(&path).unwrap().modified().unwrap();
4275        set_tray_value(&path, "shortcut", None).unwrap();
4276        assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), mtime);
4277    }
4278
4279    #[test]
4280    fn set_value_keeps_the_trailing_comment_when_replacing() {
4281        let mut doc: toml_edit::DocumentMut =
4282            "[tray]\nshortcut = \"Ctrl+U\" # mine\n".parse().unwrap();
4283        set_value(&mut doc, "tray", "shortcut", Some("Alt+U".into())).unwrap();
4284        assert_eq!(doc.to_string(), "[tray]\nshortcut = \"Alt+U\" # mine\n");
4285    }
4286
4287    #[test]
4288    fn enable_vendors_in_creates_a_missing_config() {
4289        let dir = tempfile::TempDir::new().unwrap();
4290        let path = dir.path().join("sub").join("config.toml");
4291
4292        enable_vendors_in(&path, &[VendorId::Grok]).unwrap();
4293
4294        assert_eq!(
4295            std::fs::read_to_string(&path).unwrap(),
4296            "[grok]
4297enabled = true
4298"
4299        );
4300        assert!(Config::load_from(&path).unwrap().is_enabled(VendorId::Grok));
4301    }
4302
4303    #[test]
4304    fn enable_vendors_in_keeps_comments_and_appends_the_new_section() {
4305        let dir = tempfile::TempDir::new().unwrap();
4306        let path = dir.path().join("config.toml");
4307        let original = "# my settings
4308[zai]
4309api_key = \"x\" # keep
4310enabled = false
4311";
4312        std::fs::write(&path, original).unwrap();
4313
4314        enable_vendors_in(&path, &[VendorId::Grok, VendorId::OpenCodeGo]).unwrap();
4315
4316        let text = std::fs::read_to_string(&path).unwrap();
4317        assert!(
4318            text.starts_with(
4319                "# my settings
4320"
4321            ),
4322            "{text}"
4323        );
4324        assert!(
4325            text.contains(
4326                "api_key = \"x\" # keep
4327"
4328            ),
4329            "{text}"
4330        );
4331        assert!(
4332            text.contains(
4333                "[grok]
4334enabled = true
4335"
4336            ),
4337            "{text}"
4338        );
4339        assert!(
4340            text.contains(
4341                "[opencode-go]
4342enabled = true
4343"
4344            ),
4345            "{text}"
4346        );
4347        let config = Config::load_from(&path).unwrap();
4348        assert!(
4349            !config.is_enabled(VendorId::Zai),
4350            "never widens to false, never flips others"
4351        );
4352        assert!(config.is_enabled(VendorId::Grok));
4353        assert!(config.is_enabled(VendorId::OpenCodeGo));
4354    }
4355
4356    #[test]
4357    fn enable_vendors_in_leaves_an_explicit_false_alone() {
4358        let dir = tempfile::TempDir::new().unwrap();
4359        let path = dir.path().join("config.toml");
4360        let original = "[grok]
4361enabled = false # off
4362api_key = \"k\"
4363";
4364        std::fs::write(&path, original).unwrap();
4365
4366        // `enabled = false` in the file is the user having said no. Only the
4367        // automatic path goes through here — the Settings overlay writes with
4368        // `set_bool` — so nothing a person does by hand is blocked by this.
4369        let written = enable_vendors_in(&path, &[VendorId::Grok]).unwrap();
4370
4371        assert!(written.is_empty(), "{written:?}");
4372        assert_eq!(
4373            std::fs::read_to_string(&path).unwrap(),
4374            original,
4375            "the file must not be rewritten at all"
4376        );
4377    }
4378
4379    #[test]
4380    fn enable_vendors_in_adds_the_switch_when_the_config_never_mentioned_it() {
4381        let dir = tempfile::TempDir::new().unwrap();
4382        let path = dir.path().join("config.toml");
4383        std::fs::write(&path, "[grok]\napi_key = \"k\"\n").unwrap();
4384
4385        let written = enable_vendors_in(&path, &[VendorId::Grok]).unwrap();
4386
4387        assert_eq!(written, vec![VendorId::Grok]);
4388        assert!(Config::load_from(&path).unwrap().is_enabled(VendorId::Grok));
4389    }
4390
4391    #[test]
4392    fn enable_vendors_in_is_textually_idempotent() {
4393        let dir = tempfile::TempDir::new().unwrap();
4394        let path = dir.path().join("config.toml");
4395        let original = "[grok]
4396enabled = true
4397
4398# trailing
4399";
4400        std::fs::write(&path, original).unwrap();
4401        let before = std::fs::metadata(&path).unwrap().modified().unwrap();
4402
4403        enable_vendors_in(&path, &[VendorId::Grok]).unwrap();
4404
4405        assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
4406        assert_eq!(
4407            std::fs::metadata(&path).unwrap().modified().unwrap(),
4408            before,
4409            "an unchanged document must not be rewritten"
4410        );
4411    }
4412
4413    #[test]
4414    fn enable_vendors_in_with_nothing_to_enable_leaves_a_missing_file_missing() {
4415        let dir = tempfile::TempDir::new().unwrap();
4416        let path = dir.path().join("config.toml");
4417
4418        enable_vendors_in(&path, &[]).unwrap();
4419
4420        assert!(!path.exists());
4421    }
4422}