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