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