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