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
65impl Cents {
66 /// Format as `[-]$D.CC`. Negative values render `-$D.CC` (not `$-D.CC`),
67 /// matching claudebar's `_fmt_dollars` (claudebar:532-537).
68 pub fn fmt_dollars(self) -> String {
69 let (sign, abs) = if self.0 < 0 {
70 ("-", -self.0)
71 } else {
72 ("", self.0)
73 };
74 format!("{sign}${}.{:02}", abs / 100, abs % 100)
75 }
76}
77
78/// Anthropic-specific snapshot — three rolling windows plus optional
79/// pay-as-you-go credit balance.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct AnthropicSnapshot {
82 /// "Claude Pro", "Claude Max 5x", "Claude Max 20x", etc.
83 pub plan: String,
84 pub session: UsageWindow,
85 pub weekly: UsageWindow,
86 /// Some vendors of Claude (Pro, some Max tiers) don't have a separate
87 /// Sonnet bucket — in which case this is None.
88 pub sonnet: Option<UsageWindow>,
89 /// Model-scoped weekly windows from the newer `limits[]` array
90 /// (`kind == "weekly_scoped"`), e.g. the Fable weekly cap. Labels come
91 /// from the API (`scope.model.display_name`), so new models show up
92 /// without a code change. Empty when the account has none.
93 pub scoped: Vec<ScopedWindow>,
94 /// `None` when `extra_usage.is_enabled` is false or the block is absent.
95 pub extra: Option<ExtraUsage>,
96}
97
98/// A usage window scoped to a specific model, labeled by the API
99/// (e.g. "Fable"). Weekly (7d) duration.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct ScopedWindow {
102 pub label: String,
103 pub window: UsageWindow,
104}
105
106/// "Extra usage" pay-as-you-go block (claudebar's `extra_usage`).
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct ExtraUsage {
109 /// `None` when the payload carries no usable `monthly_limit` — an
110 /// explicit null (observed for plans without a spending cap, e.g. Claude
111 /// Pro, #30) or an absent field. Either way the spend is real and stays
112 /// visible; only the limit is unreported, and the renderers say exactly
113 /// that rather than inferring a plan tier from it.
114 pub limit: Option<Cents>,
115 pub spent: Cents,
116 /// ISO code from the block (`"BRL"`, `"USD"`, …). `None` on older payloads
117 /// that predate the field — formatted as `$` for back-compat, which was
118 /// the only behaviour before the field existed.
119 pub currency: Option<String>,
120 /// Minor-unit digits from the block's `decimal_places` (BRL/USD = 2,
121 /// JPY/KRW = 0). `None` means the wire did not report the scale. We keep
122 /// that absence instead of guessing from an incomplete currency table.
123 pub decimal_places: Option<u32>,
124}
125
126impl ExtraUsage {
127 /// Integer percentage of the monthly limit consumed (0..=100, saturating
128 /// at 0 when limit is non-positive — matches claudebar:540-542).
129 ///
130 /// With no cap there is no denominator, so no meaningful percentage
131 /// exists; 0 keeps the bar and severity calm rather than inventing one.
132 pub fn percent(&self) -> i32 {
133 match self.limit {
134 Some(l) if l.0 > 0 => ((self.spent.0 * 100) / l.0) as i32,
135 _ => 0,
136 }
137 }
138
139 pub fn fmt_spent(&self) -> String {
140 self.fmt_amount(self.spent)
141 }
142
143 pub fn fmt_limit(&self) -> Option<String> {
144 self.limit.map(|l| self.fmt_amount(l))
145 }
146
147 fn fmt_amount(&self, amount: Cents) -> String {
148 match (self.decimal_places, self.currency.as_deref()) {
149 (Some(decimal_places), currency) => fmt_minor(amount.0, decimal_places, currency),
150 // Legacy payloads predate both fields and were always cents/USD.
151 // Preserve that established behaviour only when neither field can
152 // tell us otherwise.
153 (None, None) => fmt_minor(amount.0, 2, None),
154 // A currency code alone does not determine its ISO minor-unit
155 // exponent. Keep the amount truthful instead of silently dividing
156 // zero-, three-, or four-decimal currencies by the wrong scale.
157 (None, Some(currency)) => fmt_minor_units(amount.0, currency),
158 }
159 }
160}
161
162fn fmt_minor_units(minor: i64, currency: &str) -> String {
163 let sign = if minor < 0 { "-" } else { "" };
164 format!("{sign}{} minor units {currency}", minor.unsigned_abs())
165}
166
167/// Format an amount in minor units with its own currency and scale.
168///
169/// The scale is this function's own — `money` cannot express a zero- or
170/// three-decimal currency — but the *symbol* comes from
171/// [`crate::format::with_currency`], so the two cannot disagree about what a
172/// given code looks like.
173pub fn fmt_minor(minor: i64, decimal_places: u32, currency: Option<&str>) -> String {
174 let scale = 10_u64.pow(decimal_places);
175 // `unsigned_abs`, not negation: `-i64::MIN` overflows. Unreachable from
176 // the wire (the parse gate rejects negatives) but this is a pub fn.
177 let sign = if minor < 0 { "-" } else { "" };
178 let abs = minor.unsigned_abs();
179 let number = if decimal_places == 0 {
180 format!("{abs}")
181 } else {
182 format!(
183 "{}.{:0width$}",
184 abs / scale,
185 abs % scale,
186 width = decimal_places as usize
187 )
188 };
189 crate::format::with_currency(sign, &number, currency)
190}
191
192/// DeepSeek — credit balance from `/user/balance`.
193#[derive(Debug, Clone, PartialEq)]
194pub struct DeepseekSnapshot {
195 pub is_available: bool,
196 /// Current balance (prefer USD, fallback to CNY).
197 pub balance: f64,
198 /// Free-granted credits component.
199 pub granted: f64,
200 /// Topped-up (purchased) credits component.
201 pub topped_up: f64,
202 /// The currency of the above amounts (currently "USD" or "CNY").
203 pub currency: String,
204}
205
206impl Eq for DeepseekSnapshot {}
207
208impl Default for DeepseekSnapshot {
209 fn default() -> Self {
210 Self {
211 is_available: false,
212 balance: 0.0,
213 granted: 0.0,
214 topped_up: 0.0,
215 currency: String::new(),
216 }
217 }
218}
219
220/// Cursor — the two included-usage pools the dashboard shows, from the
221/// undocumented `cursor.com/api/usage-summary` endpoint (the same one the
222/// dashboard's own frontend calls), authenticated with the session token the
223/// Cursor IDE wrote to its local `state.vscdb`.
224///
225/// Since Cursor's mid-2026 pricing, a plan's included compute is split into two
226/// quota pools, each shown as a percentage: **Cursor Models** (Auto + Composer,
227/// `autoPercentUsed`) and **Other Models** (named / third-party, `apiPercentUsed`).
228/// Overflow past either pool falls to on-demand spend. Percentages are integers
229/// (rounded from the wire floats) to match the dashboard and every other
230/// vendor's integer-percent convention; they can exceed 100 when a pool is over
231/// its included allowance.
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct CursorSnapshot {
234 /// Membership label, title-cased from `membershipType` (e.g. "Ultra").
235 pub plan: String,
236 /// "Cursor Models" pool — Auto + Composer (`autoPercentUsed`, rounded).
237 pub auto_pct: i32,
238 /// "Other Models" pool — named / third-party (`apiPercentUsed`, rounded).
239 pub api_pct: i32,
240 /// Overall included usage (`totalPercentUsed`, rounded) — the dashboard's
241 /// "you've used N% of your included total usage" headline.
242 pub total_pct: i32,
243 /// `true` when the plan reports `isUnlimited` — the pools don't cap and the
244 /// percentages are not meaningful.
245 pub unlimited: bool,
246 /// Whether on-demand (overage) spend is turned on (`onDemand.enabled`).
247 pub on_demand_enabled: bool,
248 /// On-demand spend in cents (`onDemand.used`), when Cursor reports it.
249 pub on_demand_used_cents: Option<i64>,
250 /// Configured on-demand spending limit in cents (`onDemand.limit`).
251 pub on_demand_limit_cents: Option<i64>,
252 /// End of the current billing cycle (`billingCycleEnd`) — when the pools
253 /// reset.
254 pub reset_at: Option<DateTime<Utc>>,
255 /// Start of the current billing cycle (`billingCycleStart`), when the API
256 /// sends it. With `reset_at` it gives the exact window length the pace
257 /// projection needs; absent, no window length is reported at all.
258 pub cycle_start: Option<DateTime<Utc>>,
259}
260
261impl CursorSnapshot {
262 /// Length of the current billing cycle, but only when the API stated both
263 /// ends and they are ordered. `None` otherwise — older responses and every
264 /// snapshot cached before `billingCycleStart` existed omit the start, and a
265 /// guessed month would reach a frontend as an exact window and be paced as
266 /// one. `window_secs` is absent instead; the reset time still shows.
267 pub fn cycle_window(&self) -> Option<chrono::Duration> {
268 match (self.cycle_start, self.reset_at) {
269 (Some(start), Some(end)) if end > start => Some(end - start),
270 _ => None,
271 }
272 }
273
274 /// The binding pool — whichever is closest to (or furthest past) its cap.
275 /// Drives the bar color and the single generic `session_pct` alias.
276 pub fn worst_pct(&self) -> i32 {
277 self.auto_pct.max(self.api_pct)
278 }
279}
280
281/// Kiro CLI (AWS CodeWhisperer / Q Developer backend) — a single credit pool
282/// from `AmazonCodeWhispererService.GetUsageLimits`, the same call kiro-cli's
283/// own `/usage` slash command makes. Authenticated with the AWS SSO OIDC
284/// bearer token kiro-cli already cached locally, refreshed with the paired
285/// refresh token when it's close to expiry — see `kiro::db` and `kiro::oauth`.
286#[derive(Debug, Clone, PartialEq)]
287pub struct KiroSnapshot {
288 /// Subscription tier label (`subscriptionInfo.subscriptionTitle`, e.g.
289 /// "KIRO POWER").
290 pub plan: String,
291 /// Credits consumed this cycle (`currentUsageWithPrecision`).
292 pub used: f64,
293 /// Credits included in the plan (`usageLimitWithPrecision`).
294 pub limit: f64,
295 /// When the credit pool resets (`nextDateReset`).
296 pub reset_at: Option<DateTime<Utc>>,
297}
298
299impl Eq for KiroSnapshot {}
300
301impl KiroSnapshot {
302 /// Percentage of the credit pool consumed, rounded. `0` when `limit` is
303 /// not positive — defensive; the API has not been observed to send that.
304 pub fn pct(&self) -> i32 {
305 if self.limit <= 0.0 {
306 return 0;
307 }
308 ((self.used / self.limit) * 100.0)
309 .round()
310 .clamp(0.0, 9999.0) as i32
311 }
312}
313
314/// Kimi Code — weekly subscription quota plus a 5h rolling rate-limit window.
315#[derive(Debug, Clone, PartialEq, Eq)]
316pub struct KimiSnapshot {
317 pub plan: Option<String>,
318 pub weekly_limit: u64,
319 pub weekly_used: u64,
320 pub weekly_remaining: u64,
321 pub weekly_reset_at: Option<DateTime<Utc>>,
322 pub window_limit: u64,
323 pub window_used: u64,
324 pub window_remaining: u64,
325 pub window_reset_at: Option<DateTime<Utc>>,
326}
327
328impl KimiSnapshot {
329 fn pct(used: u64, limit: u64) -> i32 {
330 if limit == 0 {
331 0
332 } else {
333 // Keep all quota values exact: f64 loses integer precision above
334 // 2^53. This is the integer equivalent of round(used / limit *
335 // 100), with saturation for inconsistent upstream counters.
336 let pct = ((used as u128 * 100) + (limit as u128 / 2)) / limit as u128;
337 pct.min(100) as i32
338 }
339 }
340
341 /// Percentage of the weekly subscription quota consumed (0..=100).
342 pub fn weekly_pct(&self) -> i32 {
343 Self::pct(self.weekly_used, self.weekly_limit)
344 }
345
346 /// Percentage of the rolling rate-limit window consumed (0..=100).
347 pub fn window_pct(&self) -> i32 {
348 Self::pct(self.window_used, self.window_limit)
349 }
350}
351
352/// Discriminated union of vendor-specific snapshots. The widget and TUI match
353/// on this to pick a renderer.
354#[derive(Debug, Clone, PartialEq, Eq)]
355pub enum VendorSnapshot {
356 Anthropic(AnthropicSnapshot),
357 Openai(OpenAiSnapshot),
358 Copilot(crate::copilot::types::Snapshot),
359 Zai(ZaiSnapshot),
360 Openrouter(OpenRouterSnapshot),
361 Deepseek(DeepseekSnapshot),
362 Kimi(KimiSnapshot),
363 Kilo(KiloSnapshot),
364 Novita(NovitaSnapshot),
365 Moonshot(MoonshotSnapshot),
366 Grok(GrokSnapshot),
367 SuperGrok(SuperGrokSnapshot),
368 AnthropicApi(AnthropicApiSnapshot),
369 Antigravity(AntigravitySnapshot),
370 Cursor(CursorSnapshot),
371 Minimax(MinimaxSnapshot),
372 Kiro(KiroSnapshot),
373 NousResearch(crate::nous::types::AccountSnapshot),
374 OpenCodeGo(crate::opencode_go::types::Usage),
375 CommandCode(crate::commandcode::types::Snapshot),
376 Ollama(OllamaSnapshot),
377 /// A `[[custom]]` provider. Which one is not in the snapshot: the caller
378 /// that fetched it holds the `CustomProviderConfig`, and the cache
379 /// directory is keyed by its `id`.
380 Custom(crate::custom::types::CustomSnapshot),
381}
382
383/// Google Antigravity 2.0 / CLI snapshot. The API groups models into Gemini
384/// and third-party (Claude/GPT) buckets, and each group may carry a 5-hour and
385/// a weekly window — up to four, and not every product or plan offers all of
386/// them. Antigravity CLI 1.1.22 returns weekly buckets only, so every window is
387/// optional and a snapshot is valid when at least one arrived.
388#[derive(Debug, Clone, PartialEq)]
389pub struct AntigravitySnapshot {
390 pub plan: String,
391 /// Fingerprint of the signed-in account. Never displayed — it exists so a
392 /// cache written for one Google account is not served for another.
393 pub account: String,
394 /// Where the figures came from: a running local product, or the Cloud
395 /// Code API reached with the saved Google session while nothing runs.
396 pub source: AntigravitySource,
397 /// Gemini group, 5-hour window.
398 pub session: Option<UsageWindow>,
399 /// Gemini group, weekly window.
400 pub weekly: Option<UsageWindow>,
401 /// Claude/GPT group, 5-hour window.
402 pub third_party_session: Option<UsageWindow>,
403 /// Claude/GPT group, weekly window.
404 pub third_party_weekly: Option<UsageWindow>,
405}
406
407impl Eq for AntigravitySnapshot {}
408
409/// Which path produced an [`AntigravitySnapshot`]. The local language server
410/// is the primary source; the remote API is the fallback for when no product
411/// is running, and the panel says so because the two can disagree briefly.
412#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
413pub enum AntigravitySource {
414 #[default]
415 Local,
416 Remote,
417}
418
419impl AntigravitySource {
420 pub fn as_str(self) -> &'static str {
421 match self {
422 AntigravitySource::Local => "local",
423 AntigravitySource::Remote => "remote",
424 }
425 }
426
427 /// Inverse of [`as_str`](Self::as_str); anything unrecognised is `None` so
428 /// a cache reader can fall back to the default rather than guess.
429 pub fn parse(s: &str) -> Option<Self> {
430 match s {
431 "local" => Some(AntigravitySource::Local),
432 "remote" => Some(AntigravitySource::Remote),
433 _ => None,
434 }
435 }
436}
437
438/// MiniMax Token Plan — `/v1/token_plan/remains` returns one row per model
439/// bucket (`general` for text/coding, `video`), and each row carries its own
440/// rolling interval window plus a weekly window.
441///
442/// Two things the payload dictates rather than convention: the interval length
443/// is **not fixed** (`general` rolls every 5h, `video` every 24h), so the
444/// duration is derived from the row's own start/end rather than assumed; and
445/// the API reports the percentage **remaining**, which is inverted on the way
446/// in so these windows carry consumed-% like every other vendor's.
447#[derive(Debug, Clone, PartialEq, Eq)]
448pub struct MinimaxSnapshot {
449 pub plan: String,
450 /// `general` bucket — rolling interval window (5h on the observed plans).
451 pub session: UsageWindow,
452 /// `general` bucket — weekly window.
453 pub weekly: UsageWindow,
454 /// `video` bucket, `None` on plans that carry no video quota.
455 pub video_session: Option<UsageWindow>,
456 pub video_weekly: Option<UsageWindow>,
457}
458
459/// Anthropic Admin API — month-to-date spend (USD) from the cost report. The
460/// monthly `limit` is supplied from config (the API exposes neither the limit
461/// nor the remaining prepaid credit balance).
462#[derive(Debug, Clone, PartialEq)]
463pub struct AnthropicApiSnapshot {
464 pub spent: f64,
465 pub limit: Option<f64>,
466}
467
468impl Eq for AnthropicApiSnapshot {}
469
470impl AnthropicApiSnapshot {
471 /// Spend as an integer percentage of the configured limit; `None` when no
472 /// positive limit is set.
473 pub fn pct(&self) -> Option<i32> {
474 self.limit
475 .filter(|l| l.is_finite() && *l > 0.0)
476 .map(|l| ((self.spent / l) * 100.0).round().clamp(0.0, 9999.0) as i32)
477 }
478}
479
480/// Kilo Code — remaining credit balance from `/api/profile/balance` (USD).
481/// No purchased-total is exposed on that endpoint, so there's no consumed-%.
482#[derive(Debug, Clone, PartialEq)]
483pub struct KiloSnapshot {
484 pub label: String,
485 pub balance: f64,
486}
487
488impl Eq for KiloSnapshot {}
489
490/// Novita AI — account balance from `/openapi/v1/billing/balance/detail`, with
491/// all amounts already converted from the API's 1/10000-USD integers to USD.
492#[derive(Debug, Clone, PartialEq)]
493pub struct NovitaSnapshot {
494 /// Spendable credit balance (`availableBalance`).
495 pub available: f64,
496 /// Remaining top-up (`cashBalance`).
497 pub cash: f64,
498 /// Credit limit — max you can owe (`creditLimit`).
499 pub credit_limit: f64,
500 /// Amount currently owed (`outstandingInvoices`).
501 pub outstanding: f64,
502}
503
504impl Eq for NovitaSnapshot {}
505
506/// Moonshot / Kimi — account balance from `/v1/users/me/balance`. Currency is
507/// USD (`api.moonshot.ai`) or CNY (`api.moonshot.cn`); there's no currency
508/// field in the response, so it's carried here from the region config.
509#[derive(Debug, Clone, PartialEq)]
510pub struct MoonshotSnapshot {
511 /// Spendable balance (`available_balance` = cash + voucher). `<= 0` blocks
512 /// the inference API.
513 pub available: f64,
514 /// Voucher credit (`voucher_balance`).
515 pub voucher: f64,
516 /// Cash balance (`cash_balance`); can be negative (debt).
517 pub cash: f64,
518 /// "USD" or "CNY", implied by the host.
519 pub currency: String,
520}
521
522impl Eq for MoonshotSnapshot {}
523
524/// xAI (Grok) — prepaid credit balance in USD, derived from the Management
525/// API's `total.val` (USD cents, inverted-ledger; see `grok::types`).
526#[derive(Debug, Clone, PartialEq)]
527pub struct GrokSnapshot {
528 pub balance: f64,
529}
530
531impl Eq for GrokSnapshot {}
532
533/// SuperGrok subscription usage from Grok Build's billing endpoint (ACP as
534/// fallback) plus banked remaining-resets. Distinct from [`GrokSnapshot`]
535/// (Management API prepaid balance).
536#[derive(Debug, Clone, PartialEq)]
537pub struct SuperGrokSnapshot {
538 /// Subscription tier label when the billing response supplies one
539 /// (e.g. "SuperGrok", "SuperGrok Heavy"); otherwise `"SuperGrok"`.
540 pub plan: String,
541 /// Opaque digest of Grok auth/config state. Never displayed — cache
542 /// isolation only.
543 pub account: String,
544 /// Current included-credit usage percent. The field name is retained as a
545 /// compatibility alias for format/render code; [`Self::period`] says
546 /// whether the server's actual window is weekly or monthly.
547 pub weekly_pct: i32,
548 pub period: SuperGrokPeriod,
549 /// When the current usage period ends.
550 pub reset_at: Option<DateTime<Utc>>,
551 /// Remaining prepaid (purchased) API credit in USD, when present.
552 pub prepaid_balance: Option<f64>,
553 pub reset_credits: ResetCredits,
554}
555
556impl Eq for SuperGrokSnapshot {}
557
558#[derive(Debug, Clone, Copy, PartialEq, Eq)]
559pub enum SuperGrokPeriod {
560 Weekly,
561 Monthly,
562 Unknown,
563}
564
565impl SuperGrokPeriod {
566 pub fn label(self) -> &'static str {
567 match self {
568 Self::Weekly => "Weekly",
569 Self::Monthly => "Monthly",
570 Self::Unknown => "Current period",
571 }
572 }
573
574 pub fn short(self) -> &'static str {
575 match self {
576 Self::Weekly => "wk",
577 Self::Monthly => "mo",
578 Self::Unknown => "period",
579 }
580 }
581}
582
583/// OpenAI Codex OAuth — exposes whichever rolling windows the API reports.
584#[derive(Debug, Clone, PartialEq, Eq)]
585pub struct OpenAiSnapshot {
586 pub plan: String,
587 /// 5h window, identified by its duration rather than its wire position.
588 pub session: Option<UsageWindow>,
589 /// 7d window, identified by its duration rather than its wire position.
590 pub weekly: Option<UsageWindow>,
591 /// Optional 7d code-review bucket.
592 pub code_review: Option<UsageWindow>,
593 /// Named limits beside the main one, each with its own windows. Empty for
594 /// an account that has none.
595 pub additional_limits: Vec<OpenAiNamedLimit>,
596 /// Models the account currently cannot dispatch to, with the time they
597 /// return when the API states one. Only unavailable models are kept: a
598 /// list of everything that *is* working is noise, and the reason this
599 /// exists is to explain a refusal no percentage accounts for.
600 pub unavailable_models: Vec<OpenAiUnavailableModel>,
601 /// Optional credit balance + approximate message-count ranges.
602 pub credits: Option<OpenAiCredits>,
603 pub reset_credits: ResetCredits,
604 /// Source of the snapshot — Codex OAuth vs admin-key fallback. Drives
605 /// the placeholder set and the "OpenAI does not expose this for Plus"
606 /// tooltip when the OAuth path isn't available.
607 pub source: OpenAiSource,
608}
609
610/// A named limit that sits beside Codex's main window — a reserved pool or a
611/// model-specific allowance. It can be exhausted while the headline window is
612/// nearly untouched, which is the case it exists to make visible.
613#[derive(Debug, Clone, PartialEq, Eq)]
614pub struct OpenAiNamedLimit {
615 /// The API's own name for it, shown as given.
616 pub name: String,
617 pub session: Option<UsageWindow>,
618 pub weekly: Option<UsageWindow>,
619}
620
621/// A model the account cannot currently dispatch to.
622#[derive(Debug, Clone, PartialEq, Eq)]
623pub struct OpenAiUnavailableModel {
624 pub model: String,
625 /// When the API says it returns. `None` means it did not say.
626 pub available_at: Option<DateTime<Utc>>,
627}
628
629/// Banked, user-redeemable quota resets — Codex's "rate limit reset credits"
630/// and SuperGrok's "remaining resets" are the same idea under two names: a
631/// count you have earned, each with its own expiry, redeemed by hand rather
632/// than arriving on the window's own schedule. Distinct from a
633/// [`UsageWindow::resets_at`], which needs no action and cannot be banked.
634///
635/// The redemption identifier each provider returns alongside these
636/// (`credits[].id`, `tokens[].token_id`) is deliberately *not* carried here:
637/// it is the handle that spends the credit, and nothing that renders a status
638/// bar needs it.
639#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
640pub struct ResetCredits {
641 pub available: u32,
642 /// One row per credit the provider described. May be shorter than
643 /// `available` — Codex's usage endpoint gives the count without the
644 /// per-credit detail, and the detail call is allowed to fail on its own.
645 #[serde(default)]
646 pub credits: Vec<ResetCredit>,
647}
648
649#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
650pub struct ResetCredit {
651 /// Provider label when one exists ("Full reset (Weekly + 5 hr)"). SuperGrok
652 /// tokens have no title.
653 #[serde(default, skip_serializing_if = "Option::is_none")]
654 pub title: Option<String>,
655 #[serde(default, skip_serializing_if = "Option::is_none")]
656 pub expires_at: Option<DateTime<Utc>>,
657}
658
659impl ResetCredits {
660 pub fn is_empty(&self) -> bool {
661 self.available == 0
662 }
663
664 pub fn next_expiry(&self) -> Option<DateTime<Utc>> {
665 self.credits
666 .iter()
667 .filter_map(|credit| credit.expires_at)
668 .min()
669 }
670}
671
672#[derive(Debug, Clone, Copy, PartialEq, Eq)]
673pub enum OpenAiSource {
674 CodexOauth,
675 AdminKeyMtd,
676 Unavailable,
677}
678
679#[derive(Debug, Clone, PartialEq, Eq)]
680pub struct OpenAiCredits {
681 /// Credit balance, formatted dollars ("$0.00", "$5.00", etc.) — kept as
682 /// a string because OpenAI returns it that way.
683 pub balance: String,
684 pub has_credits: bool,
685 pub unlimited: bool,
686 pub approx_local_messages: Option<(i64, i64)>,
687 pub approx_cloud_messages: Option<(i64, i64)>,
688}
689
690/// Z.AI / BigModel — list of buckets with discriminated types. We project the
691/// two we care about into named fields (5h tokens, weekly tokens, MCP).
692#[derive(Debug, Clone, PartialEq, Eq)]
693pub struct ZaiSnapshot {
694 pub plan: String,
695 pub session: Option<UsageWindow>,
696 pub weekly: Option<UsageWindow>,
697 pub mcp: Option<UsageWindow>,
698}
699
700/// Ollama Cloud — the session and weekly usage windows served by
701/// `ollama.com/api/usage`, plus a per-model breakdown. The response also
702/// carries an `activity.cost` string for the current period; we keep it raw
703/// (it is already dollar-formatted upstream) and let the renderer place it.
704#[derive(Debug, Clone, PartialEq, Eq)]
705pub struct OllamaSnapshot {
706 /// Display label, taken from the `[ollama] plan` config field. The API
707 /// itself does not report a plan name.
708 pub plan: String,
709 /// 5h rolling window (`limits.session`). `None` when the account has not
710 /// touched the cloud tier yet (the window is omitted from the response,
711 /// not reported as zero).
712 pub session: Option<UsageWindow>,
713 /// 7d rolling window (`limits.weekly`).
714 pub weekly: Option<UsageWindow>,
715 /// Per-model request counts inside the session window, in the order the
716 /// API returned them. Renderers sort and truncate this for the tooltip.
717 pub session_models: Vec<OllamaModelUsage>,
718 /// Per-model request counts inside the weekly window.
719 pub weekly_models: Vec<OllamaModelUsage>,
720 /// `activity.cost` as a pre-formatted dollar string (`"0.00000"`,
721 /// `"1.23456"`). Already a string on the wire — the renderer decides
722 /// whether to keep it verbatim or reformat.
723 pub activity_cost: Option<String>,
724 /// `activity.period.type` (`"last_4_weeks"` and friends). A short
725 /// human-readable label the renderer can show next to the cost.
726 pub activity_period: Option<String>,
727}
728
729/// One row of `OllamaSnapshot::{session,weekly}_models`. The API carries the
730/// per-model request count; the percentage of the window that this single
731/// model represents is not reported, so the renderer derives it locally.
732#[derive(Debug, Clone, PartialEq, Eq)]
733pub struct OllamaModelUsage {
734 pub name: String,
735 pub request_count: u64,
736}
737
738/// OpenRouter — credit balance + lifetime/daily/weekly/monthly usage from
739/// `/api/v1/credits` and `/api/v1/key`.
740#[derive(Debug, Clone, PartialEq)]
741pub struct OpenRouterSnapshot {
742 pub label: String,
743 pub total_credits: f64,
744 pub total_usage: f64,
745 pub usage_daily: f64,
746 pub usage_weekly: f64,
747 pub usage_monthly: f64,
748 pub is_free_tier: bool,
749 pub limit: Option<f64>,
750 pub limit_remaining: Option<f64>,
751}
752
753impl Eq for OpenRouterSnapshot {}
754
755impl OpenRouterSnapshot {
756 /// Spendable credit, **which can be negative**: OpenRouter lets an account
757 /// run into debt, and clamping that to zero would report a healthy-looking
758 /// `$0.00` to someone who has to top up before anything works again. The
759 /// wire fields are each non-negative (see `openrouter::types`), so a
760 /// negative result only ever means usage has overrun credits.
761 pub fn balance(&self) -> f64 {
762 self.total_credits - self.total_usage
763 }
764 /// Percentage of total_credits consumed (0..=100). Returns 0 when
765 /// `total_credits` is 0 (free-tier-only accounts) — there is no
766 /// denominator to be a percentage of. Severity does not come from this
767 /// number alone: see [`crate::openrouter::vendor::severity`], which treats
768 /// a negative [`Self::balance`] as critical regardless of the percentage.
769 pub fn consumed_pct(&self) -> i32 {
770 if self.total_credits <= 0.0 {
771 return 0;
772 }
773 ((self.total_usage / self.total_credits) * 100.0)
774 .round()
775 .clamp(0.0, 100.0) as i32
776 }
777}
778
779/// Worst-of severity class for the Waybar bar text color. Mirrors
780/// claudebar:606-620 — "extra usage only matters when a rate limit hits 100%".
781pub fn anthropic_severity(snap: &AnthropicSnapshot) -> crate::pacing::PaceSeverity {
782 let mut max = snap.session.utilization_pct;
783 if snap.weekly.utilization_pct > max {
784 max = snap.weekly.utilization_pct;
785 }
786 if let Some(s) = &snap.sonnet
787 && s.utilization_pct > max
788 {
789 max = s.utilization_pct;
790 }
791 for sw in &snap.scoped {
792 if sw.window.utilization_pct > max {
793 max = sw.window.utilization_pct;
794 }
795 }
796 // Extra usage only promotes severity if a rate-limit window is at 100%.
797 let any_at_cap = snap.session.utilization_pct >= 100
798 || snap.weekly.utilization_pct >= 100
799 || snap
800 .sonnet
801 .as_ref()
802 .is_some_and(|s| s.utilization_pct >= 100)
803 || snap.scoped.iter().any(|s| s.window.utilization_pct >= 100);
804 if any_at_cap && let Some(extra) = snap.extra.as_ref() {
805 let p = extra.percent();
806 if p > max {
807 max = p;
808 }
809 }
810 crate::pango::severity_for(max)
811}
812
813#[cfg(test)]
814mod tests {
815 use super::*;
816 use crate::pacing::PaceSeverity;
817 use chrono::Duration;
818
819 fn w(pct: i32) -> UsageWindow {
820 UsageWindow {
821 utilization_pct: pct,
822 resets_at: None,
823 window_duration: Duration::hours(5),
824 }
825 }
826
827 fn snap(s: i32, w_: i32, sonnet: Option<i32>, extra: Option<(i64, i64)>) -> AnthropicSnapshot {
828 AnthropicSnapshot {
829 plan: "Max 5x".into(),
830 session: w(s),
831 weekly: w(w_),
832 sonnet: sonnet.map(w),
833 scoped: vec![],
834 extra: extra.map(|(limit, spent)| ExtraUsage {
835 limit: Some(Cents(limit)),
836 spent: Cents(spent),
837 currency: None,
838 decimal_places: Some(2),
839 }),
840 }
841 }
842
843 #[test]
844 fn fmt_minor_honors_currency_and_scale() {
845 // No currency (older payloads) keeps the historical `$`.
846 assert_eq!(fmt_minor(250, 2, None), "$2.50");
847 // The #30 reporter's actual figures: BRL must not be claimed as `$`.
848 assert_eq!(fmt_minor(14157, 2, Some("BRL")), "R$141.57");
849 assert_eq!(fmt_minor(14157, 2, Some("USD")), "$141.57");
850 // Zero-exponent currency: no decimal point, no /100.
851 assert_eq!(fmt_minor(500, 0, Some("JPY")), "¥500");
852 // Sign precedes the symbol, matching `fmt_dollars`.
853 assert_eq!(fmt_minor(-150, 2, Some("BRL")), "-R$1.50");
854 // Unknown code stays truthful as a suffix rather than guessing a symbol.
855 assert_eq!(fmt_minor(1234, 2, Some("CHF")), "12.34 CHF");
856 }
857
858 #[test]
859 fn extra_usage_formats_in_its_own_currency() {
860 let e = ExtraUsage {
861 limit: None,
862 spent: Cents(14157),
863 currency: Some("BRL".into()),
864 decimal_places: Some(2),
865 };
866 assert_eq!(e.fmt_spent(), "R$141.57");
867 assert_eq!(e.fmt_limit(), None);
868
869 let capped = ExtraUsage {
870 limit: Some(Cents(5000)),
871 spent: Cents(250),
872 currency: None,
873 decimal_places: Some(2),
874 };
875 assert_eq!(capped.fmt_spent(), "$2.50");
876 assert_eq!(capped.fmt_limit().as_deref(), Some("$50.00"));
877 }
878
879 #[test]
880 fn cents_format_positive() {
881 assert_eq!(Cents(0).fmt_dollars(), "$0.00");
882 assert_eq!(Cents(50).fmt_dollars(), "$0.50");
883 assert_eq!(Cents(250).fmt_dollars(), "$2.50");
884 assert_eq!(Cents(5000).fmt_dollars(), "$50.00");
885 }
886
887 #[test]
888 fn cents_format_negative_uses_leading_sign() {
889 // claudebar bug-fix: never "$-1.-50" — sign goes before the dollar sign.
890 assert_eq!(Cents(-150).fmt_dollars(), "-$1.50");
891 assert_eq!(Cents(-1).fmt_dollars(), "-$0.01");
892 }
893
894 #[test]
895 fn extra_percent_with_zero_limit_is_zero() {
896 assert_eq!(
897 ExtraUsage {
898 limit: Some(Cents(0)),
899 spent: Cents(100),
900 currency: None,
901 decimal_places: Some(2),
902 }
903 .percent(),
904 0
905 );
906 }
907
908 #[test]
909 fn extra_percent_truncates() {
910 // Bash integer division — 33/100 -> 33%, 50/100 -> 50%.
911 assert_eq!(
912 ExtraUsage {
913 limit: Some(Cents(10000)),
914 spent: Cents(3333),
915 currency: None,
916 decimal_places: Some(2),
917 }
918 .percent(),
919 33
920 );
921 }
922
923 #[test]
924 fn severity_picks_worst_of_three_windows() {
925 let s = snap(40, 60, Some(80), None);
926 assert_eq!(anthropic_severity(&s), PaceSeverity::High); // 80 → high
927 }
928
929 #[test]
930 fn severity_ignores_extra_when_no_cap_hit() {
931 // Extra at 95% but no rate-limit at 100% → extra is NOT promoted.
932 let s = snap(50, 60, None, Some((10000, 9500)));
933 assert_eq!(anthropic_severity(&s), PaceSeverity::Mid); // capped at 60
934 }
935
936 #[test]
937 fn severity_promotes_extra_when_session_at_100() {
938 let s = snap(100, 50, None, Some((10000, 9500)));
939 assert_eq!(anthropic_severity(&s), PaceSeverity::Critical); // 100 → critical
940 }
941
942 #[test]
943 fn severity_falls_through_to_extra_when_extra_higher_than_capped_window() {
944 // session = 100, weekly = 50, extra = 100% → max should be 100.
945 let s = snap(100, 50, None, Some((10000, 10000)));
946 assert_eq!(anthropic_severity(&s), PaceSeverity::Critical);
947 }
948
949 fn with_scoped(mut s: AnthropicSnapshot, pct: i32) -> AnthropicSnapshot {
950 s.scoped.push(ScopedWindow {
951 label: "Fable".into(),
952 window: w(pct),
953 });
954 s
955 }
956
957 #[test]
958 fn severity_includes_scoped_windows() {
959 // The PR #19 scenario: overall weekly at 55 (Mid) but a scoped Fable
960 // week at 84 → the bar class must escalate to High.
961 let s = with_scoped(snap(10, 55, None, None), 84);
962 assert_eq!(anthropic_severity(&s), PaceSeverity::High);
963 }
964
965 #[test]
966 fn severity_promotes_extra_when_scoped_at_100() {
967 // A scoped window at cap counts as a rate-limit cap hit, so extra
968 // usage above the window max is promoted — same rule as session/weekly.
969 let s = with_scoped(snap(10, 50, None, Some((10000, 9900))), 100);
970 assert_eq!(anthropic_severity(&s), PaceSeverity::Critical);
971 }
972
973 #[test]
974 fn kimi_percent_is_exact_above_f64_precision() {
975 let snap = KimiSnapshot {
976 plan: None,
977 weekly_limit: (1 << 53) + 1,
978 weekly_used: 1 << 52,
979 weekly_remaining: 0,
980 weekly_reset_at: None,
981 window_limit: u64::MAX,
982 window_used: u64::MAX - 1,
983 window_remaining: 0,
984 window_reset_at: None,
985 };
986 assert_eq!(snap.weekly_pct(), 50);
987 assert_eq!(snap.window_pct(), 100);
988 }
989
990 #[test]
991 fn kiro_pct_is_zero_without_a_positive_limit() {
992 let snap = KiroSnapshot {
993 plan: "FREE".into(),
994 used: 5.0,
995 limit: 0.0,
996 reset_at: None,
997 };
998 assert_eq!(snap.pct(), 0);
999 }
1000
1001 #[test]
1002 fn kiro_pct_rounds_the_credit_ratio() {
1003 let snap = KiroSnapshot {
1004 plan: "KIRO POWER".into(),
1005 used: 1.0,
1006 limit: 3.0,
1007 reset_at: None,
1008 };
1009 assert_eq!(snap.pct(), 33);
1010 }
1011}