Skip to main content

ai_usagebar/
usage.rs

1//! Canonical in-memory representation of "how much have I used my plan".
2//!
3//! Each vendor's snapshot lives in its own variant — this is deliberate.
4//! Anthropic exposes three windows + extra credits; OpenAI Codex exposes up to
5//! two windows + credit balance + message-count ranges; OpenRouter is a single
6//! credit-balance number with daily/weekly/monthly totals; Z.AI is a list of
7//! token + MCP buckets; DeepSeek is a credit balance; Kimi is a weekly quota
8//! plus a 5h rolling rate-limit window. Forcing them into a shared shape would
9//! either drop information or paper over genuine differences.
10//!
11//! Renderers (widget tooltip, TUI tab) consume a `VendorSnapshot` directly,
12//! not a flattened shape — so each vendor controls its own presentation while
13//! sharing the pacing math, color thresholds, and Pango primitives.
14
15use chrono::{DateTime, Utc};
16use serde::{Deserialize, Serialize};
17
18use crate::error::{AppError, Result};
19
20/// Reject a non-finite monetary value. A NaN or infinity reaching a balance
21/// field means the payload was not what we think it is; displaying it as money
22/// (or caching it as authoritative) is worse than failing loudly.
23pub fn finite_amount(vendor: &str, field: &str, v: f64) -> Result<f64> {
24    if v.is_finite() {
25        Ok(v)
26    } else {
27        Err(AppError::Schema(format!(
28            "{vendor}: `{field}` is not a finite number"
29        )))
30    }
31}
32
33/// Parse a monetary field that the wire encodes as a string. A malformed or
34/// empty value is a schema error, **not** a zero balance — silently reporting
35/// $0.00 for an error envelope is the failure mode this guards against.
36pub fn parse_amount(vendor: &str, field: &str, s: &str) -> Result<f64> {
37    let t = s.trim();
38    if t.is_empty() {
39        return Err(AppError::Schema(format!("{vendor}: `{field}` is empty")));
40    }
41    let v: f64 = t
42        .parse()
43        .map_err(|_| AppError::Schema(format!("{vendor}: `{field}` is not numeric (got {t:?})")))?;
44    finite_amount(vendor, field, v)
45}
46
47/// A single usage window — generic enough that every vendor with a notion of
48/// "% used vs. when does it reset" can express itself with it.
49///
50/// `utilization_pct` is `0..=100` (integer percent, matching claudebar's units).
51/// `resets_at` is `None` when the vendor doesn't report a reset time.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct UsageWindow {
54    pub utilization_pct: i32,
55    pub resets_at: Option<DateTime<Utc>>,
56    /// Window length (used for pacing math).
57    pub window_duration: chrono::Duration,
58}
59
60/// Money in minor currency units (historically always cents; see
61/// `ExtraUsage::decimal_places` for the actual scale) to dodge float roundoff.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct Cents(pub i64);
64
65/// Anthropic-specific snapshot — three rolling windows plus optional
66/// pay-as-you-go credit balance.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct AnthropicSnapshot {
69    /// "Claude Pro", "Claude Max 5x", "Claude Max 20x", etc.
70    pub plan: String,
71    pub session: UsageWindow,
72    pub weekly: UsageWindow,
73    /// Some vendors of Claude (Pro, some Max tiers) don't have a separate
74    /// Sonnet bucket — in which case this is None.
75    pub sonnet: Option<UsageWindow>,
76    /// Model-scoped weekly windows from the newer `limits[]` array
77    /// (`kind == "weekly_scoped"`), e.g. the Fable weekly cap. Labels come
78    /// from the API (`scope.model.display_name`), so new models show up
79    /// without a code change. Empty when the account has none.
80    pub scoped: Vec<ScopedWindow>,
81    /// `None` when the block is absent, the user disabled extra usage, or the
82    /// response has no spend worth reporting. Provider-disabled exhausted
83    /// usage stays visible with an explicit status.
84    pub extra: Option<ExtraUsage>,
85    /// Banked limit resets from the `cedar_ember` block — the same idea as
86    /// Codex's rate-limit reset credits and SuperGrok's remaining resets.
87    /// Empty when the account has no grant or the endpoint withheld the block.
88    pub reset_credits: ResetCredits,
89}
90
91/// A usage window scoped to a specific model, labeled by the API
92/// (e.g. "Fable"). Weekly (7d) duration.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct ScopedWindow {
95    pub label: String,
96    pub window: UsageWindow,
97}
98
99/// "Extra usage" pay-as-you-go block (claudebar's `extra_usage`).
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct ExtraUsage {
102    /// `None` when the payload carries no usable `monthly_limit` — an
103    /// explicit null (observed for plans without a spending cap, e.g. Claude
104    /// Pro, #30) or an absent field. Either way the spend is real and stays
105    /// visible; only the limit is unreported, and the renderers say exactly
106    /// that rather than inferring a plan tier from it.
107    pub limit: Option<Cents>,
108    pub spent: Cents,
109    /// ISO code from the block (`"BRL"`, `"USD"`, …). `None` on older payloads
110    /// that predate the field — formatted as `$` for back-compat, which was
111    /// the only behaviour before the field existed.
112    pub currency: Option<String>,
113    /// Minor-unit digits from the block's `decimal_places` (BRL/USD = 2,
114    /// JPY/KRW = 0). `None` means the wire did not report the scale. We keep
115    /// that absence instead of guessing from an incomplete currency table.
116    pub decimal_places: Option<u32>,
117    /// Why extra usage cannot currently continue. Enabled usage has `Active`.
118    pub status: ExtraUsageStatus,
119}
120
121#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
122pub enum ExtraUsageStatus {
123    #[default]
124    Active,
125    OutOfCredits,
126    MonthlyLimitReached,
127    Unavailable,
128}
129
130impl ExtraUsage {
131    /// Integer percentage of the monthly limit consumed (0..=100, saturating
132    /// at 0 when limit is non-positive — matches claudebar:540-542).
133    ///
134    /// With no cap there is no denominator, so no meaningful percentage
135    /// exists; 0 keeps the bar and severity calm rather than inventing one.
136    pub fn percent(&self) -> i32 {
137        match self.limit {
138            Some(l) if l.0 > 0 => ((self.spent.0 * 100) / l.0) as i32,
139            _ => 0,
140        }
141    }
142
143    pub fn fmt_spent(&self) -> String {
144        self.fmt_amount(self.spent)
145    }
146
147    pub fn fmt_limit(&self) -> Option<String> {
148        self.limit.map(|l| self.fmt_amount(l))
149    }
150
151    pub fn status_note(&self) -> Option<&'static str> {
152        match self.status {
153            ExtraUsageStatus::Active => None,
154            ExtraUsageStatus::OutOfCredits => Some("out of credits"),
155            ExtraUsageStatus::MonthlyLimitReached => Some("monthly limit reached"),
156            ExtraUsageStatus::Unavailable => Some("currently unavailable"),
157        }
158    }
159
160    fn fmt_amount(&self, amount: Cents) -> String {
161        match (self.decimal_places, self.currency.as_deref()) {
162            (Some(decimal_places), currency) => fmt_minor(amount.0, decimal_places, currency),
163            // Legacy payloads predate both fields and were always cents/USD.
164            // Preserve that established behaviour only when neither field can
165            // tell us otherwise.
166            (None, None) => fmt_minor(amount.0, 2, None),
167            // A currency code alone does not determine its ISO minor-unit
168            // exponent. Keep the amount truthful instead of silently dividing
169            // zero-, three-, or four-decimal currencies by the wrong scale.
170            (None, Some(currency)) => fmt_minor_units(amount.0, currency),
171        }
172    }
173}
174
175fn fmt_minor_units(minor: i64, currency: &str) -> String {
176    let sign = if minor < 0 { "-" } else { "" };
177    format!("{sign}{} minor units {currency}", minor.unsigned_abs())
178}
179
180/// Format an amount in minor units with its own currency and scale.
181///
182/// The scale is this function's own — `money` cannot express a zero- or
183/// three-decimal currency — but the *symbol* comes from
184/// [`crate::format::with_currency`], so the two cannot disagree about what a
185/// given code looks like.
186pub fn fmt_minor(minor: i64, decimal_places: u32, currency: Option<&str>) -> String {
187    let scale = 10_u64.pow(decimal_places);
188    // `unsigned_abs`, not negation: `-i64::MIN` overflows. Unreachable from
189    // the wire (the parse gate rejects negatives) but this is a pub fn.
190    let sign = if minor < 0 { "-" } else { "" };
191    let abs = minor.unsigned_abs();
192    let number = if decimal_places == 0 {
193        format!("{abs}")
194    } else {
195        format!(
196            "{}.{:0width$}",
197            abs / scale,
198            abs % scale,
199            width = decimal_places as usize
200        )
201    };
202    crate::format::with_currency(sign, &number, currency)
203}
204
205/// DeepSeek — credit balance from `/user/balance`.
206#[derive(Debug, Clone, PartialEq)]
207pub struct DeepseekSnapshot {
208    pub is_available: bool,
209    /// Current balance (prefer USD, fallback to CNY).
210    pub balance: f64,
211    /// Free-granted credits component.
212    pub granted: f64,
213    /// Topped-up (purchased) credits component.
214    pub topped_up: f64,
215    /// The currency of the above amounts (currently "USD" or "CNY").
216    pub currency: String,
217}
218
219impl Eq for DeepseekSnapshot {}
220
221impl Default for DeepseekSnapshot {
222    fn default() -> Self {
223        Self {
224            is_available: false,
225            balance: 0.0,
226            granted: 0.0,
227            topped_up: 0.0,
228            currency: String::new(),
229        }
230    }
231}
232
233/// DeepInfra prepaid balance and current-month usage from the documented
234/// `/payment/checklist` and `/payment/usage` billing endpoints.
235#[derive(Debug, Clone, PartialEq)]
236pub struct DeepInfraSnapshot {
237    /// General-purpose prepaid credit remaining, in US dollars.
238    pub balance: f64,
239    /// Current calendar-month spend, in US dollars.
240    pub monthly_spend: f64,
241    /// Optional monthly spending limit, in US dollars.
242    pub monthly_limit: Option<f64>,
243    /// Usage period in the API's `YYYY.MM` form.
244    pub period: String,
245}
246
247impl Eq for DeepInfraSnapshot {}
248
249impl DeepInfraSnapshot {
250    pub fn monthly_consumed_pct(&self) -> Option<i32> {
251        let limit = self.monthly_limit.filter(|limit| *limit > 0.0)?;
252        Some(
253            ((self.monthly_spend / limit) * 100.0)
254                .round()
255                .clamp(0.0, 9999.0) as i32,
256        )
257    }
258}
259
260/// One promo balance from Cursor's spending page
261/// (`GetClientVisibleCreditGrants`). Amounts are USD cents.
262/// `remaining_cents` is the figure to the left of the slash (`$21/$25`).
263///
264/// The grant may cover only one product (Cloud Agents, Bugbot, a single
265/// model). `display_name` is that product title when Cursor sent one. The
266/// row still says "Credits" when the name is not a title Cursor shows.
267#[derive(Debug, Clone, PartialEq, Eq)]
268pub struct CursorCreditGrant {
269    pub remaining_cents: i64,
270    pub total_cents: i64,
271    /// When the grant lapses. `None` when the payload has no expiry — some
272    /// account credits never do.
273    pub expires_at: Option<DateTime<Utc>>,
274    /// Vendor label. Empty when the grant has none.
275    pub display_name: String,
276}
277
278/// Cursor — the two included-usage pools the dashboard shows, from the
279/// undocumented `cursor.com/api/usage-summary` endpoint (the same one the
280/// dashboard's own frontend calls), authenticated with the session token the
281/// Cursor IDE wrote to its local `state.vscdb`.
282///
283/// Since Cursor's mid-2026 pricing, a plan's included compute is split into two
284/// quota pools, each shown as a percentage: **Cursor Models** (Auto + Composer,
285/// `autoPercentUsed`) and **Other Models** (named / third-party, `apiPercentUsed`).
286/// Overflow past either pool falls to on-demand spend. Percentages are integers
287/// (rounded from the wire floats) to match the dashboard and every other
288/// vendor's integer-percent convention; they can exceed 100 when a pool is over
289/// its included allowance.
290///
291/// [`CursorSnapshot::credits`] is a second, best-effort call
292/// (`GetClientVisibleCreditGrants`). An empty list means the account has no
293/// visible grant, or that call failed; either way the pools above still stand.
294#[derive(Debug, Clone, PartialEq, Eq)]
295pub struct CursorSnapshot {
296    /// Membership label, title-cased from `membershipType` (e.g. "Ultra").
297    pub plan: String,
298    /// "Cursor Models" pool — Auto + Composer (`autoPercentUsed`, rounded).
299    pub auto_pct: i32,
300    /// "Other Models" pool — named / third-party (`apiPercentUsed`, rounded).
301    pub api_pct: i32,
302    /// Overall included usage (`totalPercentUsed`, rounded) — the dashboard's
303    /// "you've used N% of your included total usage" headline.
304    pub total_pct: i32,
305    /// `true` when the plan reports `isUnlimited` — the pools don't cap and the
306    /// percentages are not meaningful.
307    pub unlimited: bool,
308    /// Whether on-demand (overage) spend is turned on (`onDemand.enabled`).
309    pub on_demand_enabled: bool,
310    /// On-demand spend in cents (`onDemand.used`), when Cursor reports it.
311    pub on_demand_used_cents: Option<i64>,
312    /// Configured on-demand spending limit in cents (`onDemand.limit`).
313    pub on_demand_limit_cents: Option<i64>,
314    /// End of the current billing cycle (`billingCycleEnd`) — when the pools
315    /// reset.
316    pub reset_at: Option<DateTime<Utc>>,
317    /// Start of the current billing cycle (`billingCycleStart`), when the API
318    /// sends it. With `reset_at` it gives the exact window length the pace
319    /// projection needs; absent, no window length is reported at all.
320    pub cycle_start: Option<DateTime<Utc>>,
321    /// Spending-page credit grants, soonest expiry first. Empty when the
322    /// account has none or the grant call did not succeed.
323    pub credits: Vec<CursorCreditGrant>,
324}
325
326impl CursorSnapshot {
327    /// Length of the current billing cycle, but only when the API stated both
328    /// ends and they are ordered. `None` otherwise — older responses and every
329    /// snapshot cached before `billingCycleStart` existed omit the start, and a
330    /// guessed month would reach a frontend as an exact window and be paced as
331    /// one. `window_secs` is absent instead; the reset time still shows.
332    pub fn cycle_window(&self) -> Option<chrono::Duration> {
333        match (self.cycle_start, self.reset_at) {
334            (Some(start), Some(end)) if end > start => Some(end - start),
335            _ => None,
336        }
337    }
338
339    /// The binding pool — whichever is closest to (or furthest past) its cap.
340    /// Drives the bar color and the single generic `session_pct` alias.
341    pub fn worst_pct(&self) -> i32 {
342        self.auto_pct.max(self.api_pct)
343    }
344}
345
346/// Kiro CLI (AWS CodeWhisperer / Q Developer backend) — a single credit pool
347/// from `AmazonCodeWhispererService.GetUsageLimits`, the same call kiro-cli's
348/// own `/usage` slash command makes. Authenticated with the AWS SSO OIDC
349/// bearer token kiro-cli already cached locally, refreshed with the paired
350/// refresh token when it's close to expiry — see `kiro::db` and `kiro::oauth`.
351#[derive(Debug, Clone, PartialEq)]
352pub struct KiroSnapshot {
353    /// Subscription tier label (`subscriptionInfo.subscriptionTitle`, e.g.
354    /// "KIRO POWER").
355    pub plan: String,
356    /// Credits consumed this cycle (`currentUsageWithPrecision`).
357    pub used: f64,
358    /// Credits included in the plan (`usageLimitWithPrecision`).
359    pub limit: f64,
360    /// When the credit pool resets (`nextDateReset`).
361    pub reset_at: Option<DateTime<Utc>>,
362}
363
364impl Eq for KiroSnapshot {}
365
366impl KiroSnapshot {
367    /// Percentage of the credit pool consumed, rounded. `0` when `limit` is
368    /// not positive — defensive; the API has not been observed to send that.
369    pub fn pct(&self) -> i32 {
370        if self.limit <= 0.0 {
371            return 0;
372        }
373        ((self.used / self.limit) * 100.0)
374            .round()
375            .clamp(0.0, 9999.0) as i32
376    }
377}
378
379/// Kimi Code — weekly subscription quota plus a 5h rolling rate-limit window.
380///
381/// Accounts on the newer `/coding/v1/usages` response shape have no weekly
382/// counters at all: the top-level `usage` block is replaced by a `usages` map
383/// of ratios, of which only `limit_month_total` — the combined monthly pool —
384/// is read. On such accounts `has_weekly` is false, the weekly counters stay
385/// zero (never fabricated), and the monthly pool arrives as
386/// `monthly_pct`/`monthly_reset_at`.
387#[derive(Debug, Clone, PartialEq, Eq)]
388pub struct KimiSnapshot {
389    pub plan: Option<String>,
390    pub weekly_limit: u64,
391    pub weekly_used: u64,
392    pub weekly_remaining: u64,
393    pub weekly_reset_at: Option<DateTime<Utc>>,
394    /// `false` on the newer `usages`-map shape, which exposes no weekly
395    /// bucket; renderers must drop the weekly row rather than draw zeros.
396    pub has_weekly: bool,
397    /// Combined monthly pool usage (0..=100) on the newer shape. The
398    /// `limit_month_code` entry is the Code slice *inside* that pool, never
399    /// its own allowance, so it is not carried here.
400    pub monthly_pct: Option<i32>,
401    pub monthly_reset_at: Option<DateTime<Utc>>,
402    pub window_limit: u64,
403    pub window_used: u64,
404    pub window_remaining: u64,
405    pub window_reset_at: Option<DateTime<Utc>>,
406}
407
408impl KimiSnapshot {
409    fn pct(used: u64, limit: u64) -> i32 {
410        if limit == 0 {
411            0
412        } else {
413            // Keep all quota values exact: f64 loses integer precision above
414            // 2^53. This is the integer equivalent of round(used / limit *
415            // 100), with saturation for inconsistent upstream counters.
416            let pct = ((used as u128 * 100) + (limit as u128 / 2)) / limit as u128;
417            pct.min(100) as i32
418        }
419    }
420
421    /// Percentage of the weekly subscription quota consumed (0..=100).
422    pub fn weekly_pct(&self) -> i32 {
423        Self::pct(self.weekly_used, self.weekly_limit)
424    }
425
426    /// Percentage of the rolling rate-limit window consumed (0..=100).
427    pub fn window_pct(&self) -> i32 {
428        Self::pct(self.window_used, self.window_limit)
429    }
430
431    /// Worst percentage across the windows this snapshot actually has: the
432    /// rolling window, the weekly quota when present, and the monthly pool
433    /// when present.
434    pub fn worst_pct(&self) -> i32 {
435        let mut worst = self.window_pct();
436        if self.has_weekly {
437            worst = worst.max(self.weekly_pct());
438        }
439        if let Some(monthly) = self.monthly_pct {
440            worst = worst.max(monthly);
441        }
442        worst
443    }
444}
445
446/// Discriminated union of vendor-specific snapshots. The widget and TUI match
447/// on this to pick a renderer.
448#[derive(Debug, Clone, PartialEq, Eq)]
449pub enum VendorSnapshot {
450    Anthropic(AnthropicSnapshot),
451    Openai(OpenAiSnapshot),
452    Copilot(crate::copilot::types::Snapshot),
453    Zai(ZaiSnapshot),
454    Openrouter(OpenRouterSnapshot),
455    Deepseek(DeepseekSnapshot),
456    Deepinfra(DeepInfraSnapshot),
457    Kimi(KimiSnapshot),
458    Kilo(KiloSnapshot),
459    Novita(NovitaSnapshot),
460    Synthetic(SyntheticSnapshot),
461    Moonshot(MoonshotSnapshot),
462    Grok(GrokSnapshot),
463    SuperGrok(SuperGrokSnapshot),
464    Grokbot(GrokbotSnapshot),
465    AnthropicApi(AnthropicApiSnapshot),
466    Antigravity(AntigravitySnapshot),
467    Cursor(CursorSnapshot),
468    Minimax(MinimaxSnapshot),
469    Kiro(KiroSnapshot),
470    NousResearch(crate::nous::types::AccountSnapshot),
471    OpenCodeGo(crate::opencode_go::types::Usage),
472    CommandCode(crate::commandcode::types::Snapshot),
473    Ollama(OllamaSnapshot),
474    OrcaRouter(OrcaRouterSnapshot),
475    ModelStudio(ModelStudioSnapshot),
476    Lyceum(LyceumSnapshot),
477    Devin(DevinSnapshot),
478    MuseCode(MuseSnapshot),
479    /// A `[[custom]]` provider. Which one is not in the snapshot: the caller
480    /// that fetched it holds the `CustomProviderConfig`, and the cache
481    /// directory is keyed by its `id`.
482    Custom(crate::custom::types::CustomSnapshot),
483    Cline(crate::cline::types::Snapshot),
484}
485
486impl VendorSnapshot {
487    /// Banked, user-redeemable resets, for the vendors that have them.
488    ///
489    /// The one place this table lives. It had already been written twice —
490    /// once for the report's `reset_credits` field and once for the
491    /// expiry notifications — and adding a third provider to only one of them
492    /// is a silent half-feature: the sidebar lists a grant the notifier never
493    /// warns about. `None` is the honest answer for every other vendor; it is
494    /// not the same as an empty [`ResetCredits`], which means "this provider
495    /// banks resets and you currently hold none".
496    pub fn reset_credits(&self) -> Option<&ResetCredits> {
497        match self {
498            Self::Anthropic(snapshot) => Some(&snapshot.reset_credits),
499            Self::Openai(snapshot) => Some(&snapshot.reset_credits),
500            Self::SuperGrok(snapshot) => Some(&snapshot.reset_credits),
501            _ => None,
502        }
503    }
504}
505
506/// Google Antigravity 2.0 / CLI snapshot. The API groups models into Gemini
507/// and third-party (Claude/GPT) buckets, and each group may carry a 5-hour and
508/// a weekly window — up to four, and not every product or plan offers all of
509/// them. Antigravity CLI 1.1.22 returns weekly buckets only, so every window is
510/// optional and a snapshot is valid when at least one arrived.
511#[derive(Debug, Clone, PartialEq)]
512pub struct AntigravitySnapshot {
513    pub plan: String,
514    /// Fingerprint of the signed-in account. Never displayed — it exists so a
515    /// cache written for one Google account is not served for another.
516    pub account: String,
517    /// Where the figures came from: a running local product, or the Cloud
518    /// Code API reached with the saved Google session when no local server
519    /// can answer — none is running, or `agy` withholds its CSRF token.
520    pub source: AntigravitySource,
521    /// Gemini group, 5-hour window.
522    pub session: Option<UsageWindow>,
523    /// Gemini group, weekly window.
524    pub weekly: Option<UsageWindow>,
525    /// Claude/GPT group, 5-hour window.
526    pub third_party_session: Option<UsageWindow>,
527    /// Claude/GPT group, weekly window.
528    pub third_party_weekly: Option<UsageWindow>,
529    /// Pools kept apart from the two shared groups, such as the weekly
530    /// "Gemini 4 Argon" limit on Pro plans, in the order the response listed
531    /// them. Empty for a product or plan that reports none.
532    pub model_pools: Vec<ModelPoolWindow>,
533}
534
535impl Eq for AntigravitySnapshot {}
536
537/// One window of an Antigravity per-model pool, named by the response's group
538/// display name. Its cadence is `window.window_duration`.
539#[derive(Debug, Clone, PartialEq)]
540pub struct ModelPoolWindow {
541    pub name: String,
542    pub window: UsageWindow,
543}
544
545impl Eq for ModelPoolWindow {}
546
547impl ModelPoolWindow {
548    /// Pools report the shared windows' two cadences, 5-hour and weekly.
549    pub fn is_weekly(&self) -> bool {
550        self.window.window_duration > chrono::Duration::hours(5)
551    }
552}
553
554/// Which path produced an [`AntigravitySnapshot`]. The local language server
555/// is the primary source; the remote API is the fallback for when no product
556/// is running, and the panel says so because the two can disagree briefly.
557#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
558pub enum AntigravitySource {
559    #[default]
560    Local,
561    Remote,
562    /// The running `agy` CLI's official status-line payload.
563    Statusline,
564    /// `agy`'s own reading, through `agy -p "/quota"`: the figures its Models
565    /// & Quota page shows, so the panel has nothing to qualify.
566    Agy,
567}
568
569impl AntigravitySource {
570    pub fn as_str(self) -> &'static str {
571        match self {
572            AntigravitySource::Local => "local",
573            AntigravitySource::Remote => "remote",
574            AntigravitySource::Statusline => "statusline",
575            AntigravitySource::Agy => "agy",
576        }
577    }
578
579    /// Inverse of [`as_str`](Self::as_str); anything unrecognised is `None` so
580    /// a cache reader can fall back to the default rather than guess.
581    pub fn parse(s: &str) -> Option<Self> {
582        match s {
583            "local" => Some(AntigravitySource::Local),
584            "remote" => Some(AntigravitySource::Remote),
585            "statusline" => Some(AntigravitySource::Statusline),
586            "agy" => Some(AntigravitySource::Agy),
587            _ => None,
588        }
589    }
590}
591
592/// MiniMax Token Plan — `/v1/token_plan/remains` returns one row per model
593/// bucket (`general` for text/coding, `video`), and each row carries its own
594/// rolling interval window plus a weekly window.
595///
596/// Two things the payload dictates rather than convention: the interval length
597/// is **not fixed** (`general` rolls every 5h, `video` every 24h), so the
598/// duration is derived from the row's own start/end rather than assumed; and
599/// the API reports the percentage **remaining**, which is inverted on the way
600/// in so these windows carry consumed-% like every other vendor's.
601#[derive(Debug, Clone, PartialEq, Eq)]
602pub struct MinimaxSnapshot {
603    pub plan: String,
604    /// `general` bucket — rolling interval window (5h on the observed plans).
605    pub session: UsageWindow,
606    /// `general` bucket — weekly window.
607    pub weekly: UsageWindow,
608    /// `video` bucket, `None` on plans that carry no video quota.
609    pub video_session: Option<UsageWindow>,
610    pub video_weekly: Option<UsageWindow>,
611}
612
613/// Anthropic Admin API — month-to-date spend (USD) from the cost report. The
614/// monthly `limit` is supplied from config (the API exposes neither the limit
615/// nor the remaining prepaid credit balance).
616#[derive(Debug, Clone, PartialEq)]
617pub struct AnthropicApiSnapshot {
618    pub spent: f64,
619    pub limit: Option<f64>,
620    /// Last UTC calendar day fully covered by the daily cost buckets.
621    pub covered_through: Option<chrono::NaiveDate>,
622}
623
624impl Eq for AnthropicApiSnapshot {}
625
626impl AnthropicApiSnapshot {
627    /// Spend as an integer percentage of the configured limit; `None` when no
628    /// positive limit is set.
629    pub fn pct(&self) -> Option<i32> {
630        self.limit
631            .filter(|l| l.is_finite() && *l > 0.0)
632            .map(|l| ((self.spent / l) * 100.0).round().clamp(0.0, 9999.0) as i32)
633    }
634
635    pub fn coverage_label(&self) -> String {
636        let Some(date) = self.covered_through else {
637            return "Completed daily buckets this month".into();
638        };
639        const MONTHS: [&str; 12] = [
640            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
641        ];
642        let month = MONTHS[chrono::Datelike::month0(&date) as usize];
643        format!(
644            "Month to date (through {month} {})",
645            chrono::Datelike::day(&date)
646        )
647    }
648}
649
650/// Kilo Code — remaining credit balance from `/api/profile/balance` (USD).
651/// No purchased-total is exposed on that endpoint, so there's no consumed-%.
652#[derive(Debug, Clone, PartialEq)]
653pub struct KiloSnapshot {
654    pub label: String,
655    pub balance: f64,
656}
657
658impl Eq for KiloSnapshot {}
659
660/// Novita AI — account balance from `/openapi/v1/billing/balance/detail`, with
661/// all amounts already converted from the API's 1/10000-USD integers to USD.
662#[derive(Debug, Clone, PartialEq)]
663pub struct NovitaSnapshot {
664    /// Spendable credit balance (`availableBalance`).
665    pub available: f64,
666    /// Remaining top-up (`cashBalance`).
667    pub cash: f64,
668    /// Credit limit — max you can owe (`creditLimit`).
669    pub credit_limit: f64,
670    /// Amount currently owed (`outstandingInvoices`).
671    pub outstanding: f64,
672}
673
674impl Eq for NovitaSnapshot {}
675
676/// Synthetic subscription quota from the documented `/v2/quotas`
677/// `subscription` object.
678#[derive(Debug, Clone, PartialEq)]
679pub struct SyntheticSnapshot {
680    pub subscription: UsageWindow,
681    pub requests: f64,
682    pub limit: f64,
683}
684
685impl Eq for SyntheticSnapshot {}
686
687/// Lyceum's platform credit balance is denominated in USD, not a percentage quota.
688#[derive(Debug, Clone, PartialEq, Serialize)]
689pub struct LyceumSnapshot {
690    pub available_credits: f64,
691    pub used_credits: f64,
692    pub total_credits_used: f64,
693    pub remaining_credits: f64,
694    pub monthly_free_credits: f64,
695    pub purchased_credits: f64,
696}
697impl Eq for LyceumSnapshot {}
698
699/// Moonshot / Kimi — account balance from `/v1/users/me/balance`. Currency is
700/// USD (`api.moonshot.ai`) or CNY (`api.moonshot.cn`); there's no currency
701/// field in the response, so it's carried here from the region config.
702#[derive(Debug, Clone, PartialEq)]
703pub struct MoonshotSnapshot {
704    /// Spendable balance (`available_balance` = cash + voucher). `<= 0` blocks
705    /// the inference API.
706    pub available: f64,
707    /// Voucher credit (`voucher_balance`).
708    pub voucher: f64,
709    /// Cash balance (`cash_balance`); can be negative (debt).
710    pub cash: f64,
711    /// "USD" or "CNY", implied by the host.
712    pub currency: String,
713}
714
715impl Eq for MoonshotSnapshot {}
716
717/// xAI (Grok) — prepaid credit balance in USD, derived from the Management
718/// API's `total.val` (USD cents, inverted-ledger; see `grok::types`).
719#[derive(Debug, Clone, PartialEq)]
720pub struct GrokSnapshot {
721    pub balance: f64,
722}
723
724impl Eq for GrokSnapshot {}
725
726/// SuperGrok subscription usage from Grok Build's billing endpoint (ACP as
727/// fallback) plus banked remaining-resets. Distinct from [`GrokSnapshot`]
728/// (Management API prepaid balance).
729#[derive(Debug, Clone, PartialEq)]
730pub struct SuperGrokSnapshot {
731    /// Subscription tier label when the billing response supplies one
732    /// (e.g. "SuperGrok", "SuperGrok Heavy"); otherwise `"SuperGrok"`.
733    pub plan: String,
734    /// Opaque digest of Grok auth/config state. Never displayed — cache
735    /// isolation only.
736    pub account: String,
737    /// Current included-credit usage percent. The field name is retained as a
738    /// compatibility alias for format/render code; [`Self::period`] says
739    /// whether the server's actual window is weekly or monthly.
740    pub weekly_pct: i32,
741    pub period: SuperGrokPeriod,
742    /// When the current usage period ends.
743    pub reset_at: Option<DateTime<Utc>>,
744    /// Remaining prepaid (purchased) API credit in USD, when present.
745    pub prepaid_balance: Option<f64>,
746    pub reset_credits: ResetCredits,
747    /// Per-product slices of the same included-credit pool (`GrokBuild`,
748    /// `GrokChat`, `GrokImagine`, …). Empty when the billing document omits
749    /// `productUsage`.
750    pub products: Vec<SuperGrokProduct>,
751}
752
753/// One SuperGrok product's share of the current included-credit window.
754#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
755pub struct SuperGrokProduct {
756    pub label: String,
757    pub percent: i32,
758}
759
760impl Eq for SuperGrokSnapshot {}
761
762#[derive(Debug, Clone, Copy, PartialEq, Eq)]
763pub enum SuperGrokPeriod {
764    Weekly,
765    Monthly,
766    Unknown,
767}
768
769impl SuperGrokPeriod {
770    pub fn label(self) -> &'static str {
771        match self {
772            Self::Weekly => "Weekly",
773            Self::Monthly => "Monthly",
774            Self::Unknown => "Current period",
775        }
776    }
777
778    pub fn short(self) -> &'static str {
779        match self {
780            Self::Weekly => "wk",
781            Self::Monthly => "mo",
782            Self::Unknown => "period",
783        }
784    }
785}
786
787/// Grok Bot desktop app — the weekly included-usage pool from
788/// `aiserver.v1.DashboardService/GetSandUsageStatus` (Connect-RPC), read with
789/// the app's own OAuth session. Distinct from [`GrokSnapshot`] (Management
790/// API prepaid dollars) and [`SuperGrokSnapshot`] (Grok Build subscription).
791#[derive(Debug, Clone, PartialEq, Eq)]
792pub struct GrokbotSnapshot {
793    /// `grokPlanLabel`, falling back to `cursorPlanName`, then "Grok Bot".
794    pub plan: String,
795    /// The subscription that bills the pool, from `billingBrand` and the plan
796    /// reported for it ("Cursor Ultra"). `None` for a brand not recognized yet,
797    /// which is left unnamed rather than guessed.
798    pub billed_by: Option<String>,
799    /// `hasNonZeroIncludedLimit`. When false the account carries no included
800    /// allowance at all — a distinct "no included allowance" state, never a
801    /// fabricated 0% meter.
802    pub has_included_allowance: bool,
803    /// `usagePercent` of the included pool (0..=100). Meaningful only when
804    /// `has_included_allowance` is set.
805    pub weekly_pct: i32,
806    /// `hasAvailableUsage` — the account can still serve requests, which at
807    /// 100% of the included pool means on-demand is picking up the rest.
808    pub has_available_usage: bool,
809    /// `onDemandSettings.enabled` — pay-as-you-go past the included pool.
810    pub on_demand_enabled: bool,
811    /// `currentPeriodStart`.
812    pub period_start: Option<DateTime<Utc>>,
813    /// `nextResetTimestampUtc`.
814    pub reset_at: Option<DateTime<Utc>>,
815    /// `reset_at − period_start` when both are reported (7 days on the
816    /// captured account) — computed, never assumed.
817    pub window: Option<chrono::Duration>,
818}
819
820impl GrokbotSnapshot {
821    /// The plan a frontend shows: the subscription that bills the pool
822    /// ("Cursor Ultra") over the app's own label, which reads "Grok Bot Plan"
823    /// on every account.
824    pub fn display_plan(&self) -> &str {
825        self.billed_by.as_deref().unwrap_or(&self.plan)
826    }
827
828    /// At 100% of the included pool, `hasAvailableUsage` can still be true
829    /// because on-demand keeps serving — say so, but only when the account
830    /// actually has on-demand switched on.
831    pub fn on_demand_note(&self) -> Option<&'static str> {
832        (self.has_included_allowance
833            && self.weekly_pct >= 100
834            && self.has_available_usage
835            && self.on_demand_enabled)
836            .then_some("included pool exhausted — on-demand may still be serving usage")
837    }
838}
839
840/// OpenAI Codex OAuth — exposes whichever rolling windows the API reports.
841#[derive(Debug, Clone, PartialEq, Eq)]
842pub struct OpenAiSnapshot {
843    pub plan: String,
844    /// 5h window, identified by its duration rather than its wire position.
845    pub session: Option<UsageWindow>,
846    /// 7d window, identified by its duration rather than its wire position.
847    pub weekly: Option<UsageWindow>,
848    /// Optional 7d code-review bucket.
849    pub code_review: Option<UsageWindow>,
850    /// Named limits beside the main one, each with its own windows. Empty for
851    /// an account that has none.
852    pub additional_limits: Vec<OpenAiNamedLimit>,
853    /// Models the account currently cannot dispatch to, with the time they
854    /// return when the API states one. Only unavailable models are kept: a
855    /// list of everything that *is* working is noise, and the reason this
856    /// exists is to explain a refusal no percentage accounts for.
857    pub unavailable_models: Vec<OpenAiUnavailableModel>,
858    /// Optional credit balance + approximate message-count ranges.
859    pub credits: Option<OpenAiCredits>,
860    pub reset_credits: ResetCredits,
861    /// Source of the snapshot — Codex OAuth vs admin-key fallback. Drives
862    /// the placeholder set and the "OpenAI does not expose this for Plus"
863    /// tooltip when the OAuth path isn't available.
864    pub source: OpenAiSource,
865}
866
867/// A named limit that sits beside Codex's main window — a reserved pool or a
868/// model-specific allowance. It can be exhausted while the headline window is
869/// nearly untouched, which is the case it exists to make visible.
870#[derive(Debug, Clone, PartialEq, Eq)]
871pub struct OpenAiNamedLimit {
872    /// The API's own name for it, shown as given.
873    pub name: String,
874    pub session: Option<UsageWindow>,
875    pub weekly: Option<UsageWindow>,
876}
877
878/// A model the account cannot currently dispatch to.
879#[derive(Debug, Clone, PartialEq, Eq)]
880pub struct OpenAiUnavailableModel {
881    pub model: String,
882    /// When the API says it returns. `None` means it did not say.
883    pub available_at: Option<DateTime<Utc>>,
884}
885
886/// Banked, user-redeemable quota resets — Codex's "rate limit reset credits"
887/// and SuperGrok's "remaining resets" are the same idea under two names: a
888/// count you have earned, each with its own expiry, redeemed by hand rather
889/// than arriving on the window's own schedule. Distinct from a
890/// [`UsageWindow::resets_at`], which needs no action and cannot be banked.
891///
892/// The redemption identifier each provider returns alongside these
893/// (`credits[].id`, `tokens[].token_id`) is deliberately *not* carried here:
894/// it is the handle that spends the credit, and nothing that renders a status
895/// bar needs it.
896#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
897pub struct ResetCredits {
898    pub available: u32,
899    /// One row per credit the provider described. May be shorter than
900    /// `available` — Codex's usage endpoint gives the count without the
901    /// per-credit detail, and the detail call is allowed to fail on its own.
902    #[serde(default)]
903    pub credits: Vec<ResetCredit>,
904}
905
906#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
907pub struct ResetCredit {
908    /// Provider label when one exists ("Full reset (Weekly + 5 hr)"). SuperGrok
909    /// tokens have no title.
910    #[serde(default, skip_serializing_if = "Option::is_none")]
911    pub title: Option<String>,
912    #[serde(default, skip_serializing_if = "Option::is_none")]
913    pub expires_at: Option<DateTime<Utc>>,
914}
915
916/// A provider's own label for a banked reset, rendered verbatim in Pango bar
917/// markup and in the `;;`-delimited desktop FORMAT protocol. Both vendors that
918/// carry one gate it here rather than each keeping a copy: an over-long or
919/// control-character-bearing title is dropped, leaving the expiry line alone,
920/// which still says everything the user has to act on.
921pub fn checked_reset_title(value: Option<String>) -> Option<String> {
922    const MAX_RESET_TITLE_CHARS: usize = 80;
923    let value = value
924        .map(|s| s.trim().to_string())
925        .filter(|s| !s.is_empty())?;
926    if value.chars().count() > MAX_RESET_TITLE_CHARS || value.chars().any(char::is_control) {
927        None
928    } else {
929        Some(value)
930    }
931}
932
933impl ResetCredits {
934    pub fn is_empty(&self) -> bool {
935        self.available == 0
936    }
937
938    pub fn next_expiry(&self) -> Option<DateTime<Utc>> {
939        self.credits
940            .iter()
941            .filter_map(|credit| credit.expires_at)
942            .min()
943    }
944}
945
946#[derive(Debug, Clone, Copy, PartialEq, Eq)]
947pub enum OpenAiSource {
948    CodexOauth,
949    AdminKeyMtd,
950    Unavailable,
951}
952
953#[derive(Debug, Clone, PartialEq, Eq)]
954pub struct OpenAiCredits {
955    /// Credit balance, formatted dollars ("$0.00", "$5.00", etc.) — kept as
956    /// a string because OpenAI returns it that way.
957    pub balance: String,
958    pub has_credits: bool,
959    pub unlimited: bool,
960    pub approx_local_messages: Option<(i64, i64)>,
961    pub approx_cloud_messages: Option<(i64, i64)>,
962}
963
964/// Z.AI / BigModel — list of buckets with discriminated types. We project the
965/// two we care about into named fields (5h tokens, weekly tokens, MCP).
966#[derive(Debug, Clone, PartialEq, Eq)]
967pub struct ZaiSnapshot {
968    pub plan: String,
969    pub session: Option<UsageWindow>,
970    pub weekly: Option<UsageWindow>,
971    pub mcp: Option<UsageWindow>,
972}
973
974/// Ollama Cloud — credit balances or legacy quota windows from
975/// `ollama.com/api/balance`. Older cached `/api/usage` payloads can also
976/// carry per-model counts and activity cost.
977#[derive(Debug, Clone, PartialEq, Eq)]
978pub struct OllamaSnapshot {
979    /// Display label, taken from the `[ollama] plan` config field. The API
980    /// itself does not report a plan name.
981    pub plan: String,
982    /// 5h rolling window (`limits.session`). `None` when the account has not
983    /// touched the cloud tier yet (the window is omitted from the response,
984    /// not reported as zero).
985    pub session: Option<UsageWindow>,
986    /// 7d rolling window (`limits.weekly`).
987    pub weekly: Option<UsageWindow>,
988    /// Calendar-month window (`limits.monthly`). Some Pro accounts report
989    /// this in place of `session`/`weekly` instead of alongside them.
990    pub monthly: Option<UsageWindow>,
991    /// Per-model request counts inside the session window, in the order the
992    /// API returned them. Renderers sort and truncate this for the tooltip.
993    pub session_models: Vec<OllamaModelUsage>,
994    /// Per-model request counts inside the weekly window.
995    pub weekly_models: Vec<OllamaModelUsage>,
996    /// Per-model request counts inside the monthly window.
997    pub monthly_models: Vec<OllamaModelUsage>,
998    /// `activity.cost` as a pre-formatted dollar string (`"0.00000"`,
999    /// `"1.23456"`). Already a string on the wire — the renderer decides
1000    /// whether to keep it verbatim or reformat.
1001    pub activity_cost: Option<String>,
1002    /// `activity.period.type` (`"last_4_weeks"` and friends). A short
1003    /// human-readable label the renderer can show next to the cost.
1004    pub activity_period: Option<String>,
1005    /// Monthly included credits and optional purchased credits, formatted
1006    /// through the shared money formatter for all desktop surfaces.
1007    pub credits: Option<OllamaCredits>,
1008}
1009
1010#[derive(Debug, Clone, PartialEq, Eq)]
1011pub struct OllamaCredits {
1012    pub balance: String,
1013    pub allowance: String,
1014    pub purchased: Option<String>,
1015}
1016
1017/// One row of `OllamaSnapshot::{session,weekly}_models`. The API carries the
1018/// per-model request count; the percentage of the window that this single
1019/// model represents is not reported, so the renderer derives it locally.
1020#[derive(Debug, Clone, PartialEq, Eq)]
1021pub struct OllamaModelUsage {
1022    pub name: String,
1023    pub request_count: u64,
1024}
1025
1026/// OpenRouter — credit balance + lifetime/daily/weekly/monthly usage from
1027/// `/api/v1/credits` and `/api/v1/key`.
1028#[derive(Debug, Clone, PartialEq)]
1029pub struct OpenRouterSnapshot {
1030    pub label: String,
1031    pub total_credits: f64,
1032    pub total_usage: f64,
1033    pub usage_daily: f64,
1034    pub usage_weekly: f64,
1035    pub usage_monthly: f64,
1036    pub is_free_tier: bool,
1037    pub limit: Option<f64>,
1038    pub limit_remaining: Option<f64>,
1039    pub recent_models: Vec<String>,
1040}
1041
1042impl Eq for OpenRouterSnapshot {}
1043
1044impl OpenRouterSnapshot {
1045    /// Spendable credit, **which can be negative**: OpenRouter lets an account
1046    /// run into debt, and clamping that to zero would report a healthy-looking
1047    /// `$0.00` to someone who has to top up before anything works again. The
1048    /// wire fields are each non-negative (see `openrouter::types`), so a
1049    /// negative result only ever means usage has overrun credits.
1050    pub fn balance(&self) -> f64 {
1051        self.total_credits - self.total_usage
1052    }
1053    /// Percentage of total_credits consumed (0..=100). Returns 0 when
1054    /// `total_credits` is 0 (free-tier-only accounts) — there is no
1055    /// denominator to be a percentage of. Severity does not come from this
1056    /// number alone: see [`crate::openrouter::vendor::severity`], which treats
1057    /// a negative [`Self::balance`] as critical regardless of the percentage.
1058    pub fn consumed_pct(&self) -> i32 {
1059        if self.total_credits <= 0.0 {
1060            return 0;
1061        }
1062        i32::from(crate::format::clamp_pct(
1063            (self.total_usage / self.total_credits) * 100.0,
1064        ))
1065    }
1066}
1067
1068/// OrcaRouter — prepaid credit card from the one-api compatible dashboard
1069/// billing endpoints (`/v1/dashboard/billing/usage` + `/subscription`), over an
1070/// API key. Usage arrives in **US cents** (`total_usage: 275` = $2.75); the
1071/// subscription's limit fields are USD and mean the *total* credit limit
1072/// (remaining + used), with `100000000` as the unlimited sentinel.
1073#[derive(Debug, Clone, PartialEq, Eq)]
1074pub struct OrcaRouterSnapshot {
1075    /// Cumulative spend, exact US cents (`total_usage`).
1076    pub spent_cents: i64,
1077    /// Total credit limit in exact US cents. `None` for unlimited keys (the
1078    /// `100000000` sentinel) or when the subscription response carried no
1079    /// limit field at all — either way the card is spend-only.
1080    pub limit_cents: Option<i64>,
1081    /// Key expiry (`access_until`, Unix seconds); `None` = no expiry (a wire
1082    /// `0` means the same thing).
1083    pub access_until: Option<DateTime<Utc>>,
1084}
1085
1086impl OrcaRouterSnapshot {
1087    pub fn spent_usd(&self) -> f64 {
1088        self.spent_cents as f64 / 100.0
1089    }
1090
1091    pub fn limit_usd(&self) -> Option<f64> {
1092        self.limit_cents.map(|c| c as f64 / 100.0)
1093    }
1094
1095    /// Remaining credit in exact cents. Can be negative (spend past the
1096    /// limit) — the sign belongs outside the symbol, like OpenRouter debt.
1097    pub fn remaining_cents(&self) -> Option<i64> {
1098        self.limit_cents.map(|limit| limit - self.spent_cents)
1099    }
1100
1101    pub fn remaining_usd(&self) -> Option<f64> {
1102        self.remaining_cents().map(|c| c as f64 / 100.0)
1103    }
1104
1105    /// Integer-percentage of the limit consumed, computed in cents so no
1106    /// float division is involved. `None` when there is no limit — an
1107    /// unlimited key has no percentage to be exact *about*.
1108    pub fn consumed_pct(&self) -> Option<i32> {
1109        self.limit_cents.filter(|l| *l > 0).map(|limit| {
1110            let pct = (self.spent_cents.saturating_mul(100)) / limit;
1111            pct.clamp(0, 100) as i32
1112        })
1113    }
1114}
1115
1116/// Alibaba Cloud Model Studio Token Plan — a 5-hour, a weekly and a monthly
1117/// ratio window, any of which the console account may not report. An absent
1118/// window is no-data (possibly unlimited), never 0%.
1119#[derive(Debug, Clone, PartialEq, Eq)]
1120pub struct ModelStudioSnapshot {
1121    /// 5-hour window. `None` when `per5HourPercentage` was absent.
1122    pub session: Option<UsageWindow>,
1123    /// Weekly window. `None` when `per1WeekPercentage` was absent.
1124    pub weekly: Option<UsageWindow>,
1125    /// Monthly window. `None` when `per1MonthPercentage` was absent. The
1126    /// reset is exact; the cycle length is plan-dependent, so no exact
1127    /// window duration is declared for it (same rule as Ollama's calendar
1128    /// month) and pacing is omitted wherever it would guess a denominator.
1129    pub monthly: Option<UsageWindow>,
1130}
1131
1132/// Muse Code subscription windows. Missing observations stay absent.
1133#[derive(Debug, Clone, PartialEq, Eq)]
1134pub struct MuseSnapshot {
1135    pub plan: String,
1136    pub session: Option<UsageWindow>,
1137    pub weekly: Option<UsageWindow>,
1138}
1139
1140/// Devin CLI quota snapshot. The CLI reports remaining percentages, while
1141/// renderers and report consumers use consumed percentages consistently.
1142#[derive(Debug, Clone, PartialEq, Eq)]
1143pub struct DevinSnapshot {
1144    pub daily: Option<UsageWindow>,
1145    pub weekly: Option<UsageWindow>,
1146    /// Exact value from the CLI's overageBalanceMicros field. Its USD meaning
1147    /// is empirically observed for the tested account, not a universal API
1148    /// contract; only renderers perform that display conversion.
1149    pub overage_balance_micros: Option<i64>,
1150}
1151
1152/// Worst-of severity class for the Waybar bar text color. Mirrors
1153/// claudebar:606-620 — "extra usage only matters when a rate limit hits 100%".
1154pub fn anthropic_severity(snap: &AnthropicSnapshot) -> crate::pacing::PaceSeverity {
1155    let mut max = snap.session.utilization_pct;
1156    if snap.weekly.utilization_pct > max {
1157        max = snap.weekly.utilization_pct;
1158    }
1159    if let Some(s) = &snap.sonnet
1160        && s.utilization_pct > max
1161    {
1162        max = s.utilization_pct;
1163    }
1164    for sw in &snap.scoped {
1165        if sw.window.utilization_pct > max {
1166            max = sw.window.utilization_pct;
1167        }
1168    }
1169    // Extra usage only promotes severity if a rate-limit window is at 100%.
1170    let any_at_cap = snap.session.utilization_pct >= 100
1171        || snap.weekly.utilization_pct >= 100
1172        || snap
1173            .sonnet
1174            .as_ref()
1175            .is_some_and(|s| s.utilization_pct >= 100)
1176        || snap.scoped.iter().any(|s| s.window.utilization_pct >= 100);
1177    if any_at_cap && let Some(extra) = snap.extra.as_ref() {
1178        let p = extra.percent();
1179        if p > max {
1180            max = p;
1181        }
1182    }
1183    crate::pango::severity_for(max)
1184}
1185
1186#[cfg(test)]
1187mod tests {
1188    use super::*;
1189    use crate::pacing::PaceSeverity;
1190    use chrono::Duration;
1191
1192    fn w(pct: i32) -> UsageWindow {
1193        UsageWindow {
1194            utilization_pct: pct,
1195            resets_at: None,
1196            window_duration: Duration::hours(5),
1197        }
1198    }
1199
1200    fn snap(s: i32, w_: i32, sonnet: Option<i32>, extra: Option<(i64, i64)>) -> AnthropicSnapshot {
1201        AnthropicSnapshot {
1202            plan: "Max 5x".into(),
1203            session: w(s),
1204            weekly: w(w_),
1205            sonnet: sonnet.map(w),
1206            scoped: vec![],
1207            extra: extra.map(|(limit, spent)| ExtraUsage {
1208                limit: Some(Cents(limit)),
1209                spent: Cents(spent),
1210                currency: None,
1211                decimal_places: Some(2),
1212                status: ExtraUsageStatus::Active,
1213            }),
1214            reset_credits: Default::default(),
1215        }
1216    }
1217
1218    #[test]
1219    fn fmt_minor_honors_currency_and_scale() {
1220        // No currency (older payloads) keeps the historical `$`.
1221        assert_eq!(fmt_minor(250, 2, None), "$2.50");
1222        // The #30 reporter's actual figures: BRL must not be claimed as `$`.
1223        assert_eq!(fmt_minor(14157, 2, Some("BRL")), "R$141.57");
1224        assert_eq!(fmt_minor(14157, 2, Some("USD")), "$141.57");
1225        // Zero-exponent currency: no decimal point, no /100.
1226        assert_eq!(fmt_minor(500, 0, Some("JPY")), "¥500");
1227        // Sign precedes the symbol, as `format::money` spells it.
1228        assert_eq!(fmt_minor(-150, 2, Some("BRL")), "-R$1.50");
1229        // Unknown code stays truthful as a suffix rather than guessing a symbol.
1230        assert_eq!(fmt_minor(1234, 2, Some("CHF")), "12.34 CHF");
1231    }
1232
1233    #[test]
1234    fn extra_usage_formats_in_its_own_currency() {
1235        let e = ExtraUsage {
1236            limit: None,
1237            spent: Cents(14157),
1238            currency: Some("BRL".into()),
1239            decimal_places: Some(2),
1240            status: ExtraUsageStatus::Active,
1241        };
1242        assert_eq!(e.fmt_spent(), "R$141.57");
1243        assert_eq!(e.fmt_limit(), None);
1244
1245        let capped = ExtraUsage {
1246            limit: Some(Cents(5000)),
1247            spent: Cents(250),
1248            currency: None,
1249            decimal_places: Some(2),
1250            status: ExtraUsageStatus::Active,
1251        };
1252        assert_eq!(capped.fmt_spent(), "$2.50");
1253        assert_eq!(capped.fmt_limit().as_deref(), Some("$50.00"));
1254    }
1255
1256    #[test]
1257    fn extra_percent_with_zero_limit_is_zero() {
1258        assert_eq!(
1259            ExtraUsage {
1260                limit: Some(Cents(0)),
1261                spent: Cents(100),
1262                currency: None,
1263                decimal_places: Some(2),
1264                status: ExtraUsageStatus::Active,
1265            }
1266            .percent(),
1267            0
1268        );
1269    }
1270
1271    #[test]
1272    fn extra_percent_truncates() {
1273        // Bash integer division — 33/100 -> 33%, 50/100 -> 50%.
1274        assert_eq!(
1275            ExtraUsage {
1276                limit: Some(Cents(10000)),
1277                spent: Cents(3333),
1278                currency: None,
1279                decimal_places: Some(2),
1280                status: ExtraUsageStatus::Active,
1281            }
1282            .percent(),
1283            33
1284        );
1285    }
1286
1287    #[test]
1288    fn severity_picks_worst_of_three_windows() {
1289        let s = snap(40, 60, Some(80), None);
1290        assert_eq!(anthropic_severity(&s), PaceSeverity::High); // 80 → high
1291    }
1292
1293    #[test]
1294    fn severity_ignores_extra_when_no_cap_hit() {
1295        // Extra at 95% but no rate-limit at 100% → extra is NOT promoted.
1296        let s = snap(50, 60, None, Some((10000, 9500)));
1297        assert_eq!(anthropic_severity(&s), PaceSeverity::Mid); // capped at 60
1298    }
1299
1300    #[test]
1301    fn severity_promotes_extra_when_session_at_100() {
1302        let s = snap(100, 50, None, Some((10000, 9500)));
1303        assert_eq!(anthropic_severity(&s), PaceSeverity::Critical); // 100 → critical
1304    }
1305
1306    #[test]
1307    fn severity_falls_through_to_extra_when_extra_higher_than_capped_window() {
1308        // session = 100, weekly = 50, extra = 100% → max should be 100.
1309        let s = snap(100, 50, None, Some((10000, 10000)));
1310        assert_eq!(anthropic_severity(&s), PaceSeverity::Critical);
1311    }
1312
1313    fn with_scoped(mut s: AnthropicSnapshot, pct: i32) -> AnthropicSnapshot {
1314        s.scoped.push(ScopedWindow {
1315            label: "Fable".into(),
1316            window: w(pct),
1317        });
1318        s
1319    }
1320
1321    #[test]
1322    fn severity_includes_scoped_windows() {
1323        // The PR #19 scenario: overall weekly at 55 (Mid) but a scoped Fable
1324        // week at 84 → the bar class must escalate to High.
1325        let s = with_scoped(snap(10, 55, None, None), 84);
1326        assert_eq!(anthropic_severity(&s), PaceSeverity::High);
1327    }
1328
1329    #[test]
1330    fn severity_promotes_extra_when_scoped_at_100() {
1331        // A scoped window at cap counts as a rate-limit cap hit, so extra
1332        // usage above the window max is promoted — same rule as session/weekly.
1333        let s = with_scoped(snap(10, 50, None, Some((10000, 9900))), 100);
1334        assert_eq!(anthropic_severity(&s), PaceSeverity::Critical);
1335    }
1336
1337    #[test]
1338    fn kimi_percent_is_exact_above_f64_precision() {
1339        let snap = KimiSnapshot {
1340            plan: None,
1341            weekly_limit: (1 << 53) + 1,
1342            weekly_used: 1 << 52,
1343            weekly_remaining: 0,
1344            weekly_reset_at: None,
1345            has_weekly: true,
1346            monthly_pct: None,
1347            monthly_reset_at: None,
1348            window_limit: u64::MAX,
1349            window_used: u64::MAX - 1,
1350            window_remaining: 0,
1351            window_reset_at: None,
1352        };
1353        assert_eq!(snap.weekly_pct(), 50);
1354        assert_eq!(snap.window_pct(), 100);
1355    }
1356
1357    #[test]
1358    fn kiro_pct_is_zero_without_a_positive_limit() {
1359        let snap = KiroSnapshot {
1360            plan: "FREE".into(),
1361            used: 5.0,
1362            limit: 0.0,
1363            reset_at: None,
1364        };
1365        assert_eq!(snap.pct(), 0);
1366    }
1367
1368    #[test]
1369    fn kiro_pct_rounds_the_credit_ratio() {
1370        let snap = KiroSnapshot {
1371            plan: "KIRO POWER".into(),
1372            used: 1.0,
1373            limit: 3.0,
1374            reset_at: None,
1375        };
1376        assert_eq!(snap.pct(), 33);
1377    }
1378}