ai-usagebar 0.20.0

Waybar widget + TUI for tracking AI plan usage across multiple providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Live API smoke test suite — DETECTS UNDOCUMENTED-ENDPOINT DRIFT.
//!
//! Hits the real Anthropic, OpenAI Codex, Z.AI, OpenRouter, and Kimi endpoints
//! using credentials from your shell. Asserts only the *fields we depend on*
//! so when a vendor renames or removes one, the failure points at the exact
//! field rather than dumping the whole response.
//!
//! These tests are `#[ignore]` so plain `cargo test` doesn't hit external
//! APIs (and won't fail on machines without creds). Run explicitly:
//!
//! ```bash
//! source ~/.config/zsh/secrets
//! cargo test --test live -- --ignored --nocapture
//! # or:
//! make smoke                         # runs every configured live smoke test
//! cargo test --test live kimi_live -- --ignored --nocapture
//! ```
//!
//! ## When a smoke test fails
//!
//! 1. Re-run with `--nocapture` to see the actual response shape.
//! 2. Paste the response + error into Claude Code and ask it to update the
//!    affected vendor's `types.rs` to match. The error messages here are
//!    deliberately verbose so the update is mechanical.
//! 3. After updating, re-run `cargo test --test live -- --ignored` to confirm.
//!
//! ## What gets tested (only the contract we rely on)
//!
//! - **Anthropic**: `five_hour.utilization` is 0..=100, `resets_at` parses
//!   as RFC3339, `extra_usage.{is_enabled,monthly_limit,used_credits}` round-trip.
//! - **OpenAI**: `rate_limit.primary_window.used_percent` is 0..=100, the
//!   id_token's exp claim is parseable.
//! - **Z.AI**: response is a `{code, data: {limits:[...], level}, success}`
//!   envelope and at least one `TOKENS_LIMIT` entry exists.
//! - **OpenRouter**: `/credits` returns `{data:{total_credits,total_usage}}`
//!   and `/key` returns `{data:{usage,is_free_tier}}`.
//! - **Kimi**: the public snapshot exposes parsed weekly limit/used/remaining
//!   counters and a bounded percentage. Its reset and selected 5-hour rolling
//!   window are optional, so the smoke test validates their public fields only
//!   when present; the snapshot does not expose raw wire duration/unit.
//!   `kimi_live` skips when optional `KIMI_API_KEY` is unset.
//! - **Cursor**: reads the session token from the local `state.vscdb`, then
//!   asserts `premium_pct` is 0..=100 and a future `premium_reset_at` was
//!   derived from `startOfMonth`. `cursor_live` skips when there is no Cursor
//!   install (no state DB and no `CURSOR_DB_PATH`).

use std::time::Duration;

use ai_usagebar::anthropic;
use ai_usagebar::cache::Cache;
use ai_usagebar::cursor;
use ai_usagebar::error::AppError;
use ai_usagebar::kimi;
use ai_usagebar::minimax;
use ai_usagebar::openai;
use ai_usagebar::openrouter;
use ai_usagebar::zai;

fn xdg_cache_for(test: &str) -> Cache {
    // Use a per-test scratch dir so smoke tests don't clobber the real cache.
    let base = std::env::temp_dir().join(format!("ai-usagebar-smoke-{test}"));
    let _ = std::fs::remove_dir_all(&base);
    Cache::at(base)
}

fn assert_pct(label: &str, p: i32) {
    assert!(
        (0..=100).contains(&p),
        "{label}: utilization {p} outside [0,100] — vendor shape changed?"
    );
}

fn is_missing_credentials(err: &AppError) -> bool {
    matches!(err, AppError::Io { source, .. } if source.kind() == std::io::ErrorKind::NotFound)
}

#[tokio::test]
#[ignore = "live API; run with --ignored"]
async fn anthropic_live() {
    let creds_path = anthropic::creds::default_path().expect("resolve home directory");
    // Creds live in this file (Linux) or the login Keychain (recent macOS, no
    // file) — CredsTarget::Default covers both. Skip cleanly when neither
    // source resolves — a no-op on machines without creds, as the module doc
    // promises, not a hard failure.
    let creds_target = anthropic::creds::CredsTarget::Default(creds_path);
    match anthropic::creds::resolve(&creds_target) {
        Ok(_) => {}
        Err(err) if is_missing_credentials(&err) => {
            eprintln!("anthropic_live: no Claude credentials (file or Keychain) — skipping");
            return;
        }
        Err(err) => panic!("anthropic_live: failed to read Claude credentials: {err}"),
    }
    let cache = xdg_cache_for("anthropic");
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(15))
        .build()
        .unwrap();
    let endpoints = anthropic::fetch::Endpoints::default();
    let out = anthropic::fetch_snapshot(
        &client,
        &creds_target,
        &cache,
        &endpoints,
        Duration::from_secs(0),
    )
    .await
    .expect("anthropic fetch should succeed against the real API");

    assert!(!out.snapshot.plan.is_empty(), "anthropic plan label empty");
    assert_pct("anthropic.session", out.snapshot.session.utilization_pct);
    assert_pct("anthropic.weekly", out.snapshot.weekly.utilization_pct);
    if let Some(s) = out.snapshot.sonnet.as_ref() {
        assert_pct("anthropic.sonnet", s.utilization_pct);
    }
    if let Some(e) = out.snapshot.extra.as_ref() {
        if let Some(l) = e.limit {
            assert!(l.0 >= 0, "anthropic extra.limit < 0");
        }
        // spent can equal or exceed limit briefly during reconciliation; just sanity-check.
        assert!(e.spent.0 >= 0, "anthropic extra.spent < 0");
    }
    println!(
        "✅ anthropic — plan={}, session={}%, weekly={}%, sonnet={:?}, extra={:?}",
        out.snapshot.plan,
        out.snapshot.session.utilization_pct,
        out.snapshot.weekly.utilization_pct,
        out.snapshot.sonnet.as_ref().map(|s| s.utilization_pct),
        out.snapshot
            .extra
            .as_ref()
            .map(|e| (e.fmt_spent(), e.fmt_limit())),
    );
}

#[tokio::test]
#[ignore = "live API; run with --ignored"]
async fn openai_live() {
    let creds_path = openai::creds::default_path().expect("resolve home directory");
    assert!(
        creds_path.exists(),
        "no Codex credentials at {} — log in with `codex login` first",
        creds_path.display()
    );
    let cache = xdg_cache_for("openai");
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(15))
        .build()
        .unwrap();
    let endpoints = openai::fetch::Endpoints::default();
    let out = openai::fetch_snapshot(
        &client,
        &creds_path,
        &cache,
        &endpoints,
        Duration::from_secs(0),
    )
    .await
    .expect("openai fetch should succeed against the real API");

    assert!(!out.snapshot.plan.is_empty(), "openai plan label empty");
    assert!(
        out.snapshot.session.is_some() || out.snapshot.weekly.is_some(),
        "openai returned no 5h or 7d usage window"
    );
    if let Some(session) = out.snapshot.session.as_ref() {
        assert_pct("openai.session", session.utilization_pct);
    }
    if let Some(weekly) = out.snapshot.weekly.as_ref() {
        assert_pct("openai.weekly", weekly.utilization_pct);
    }
    println!(
        "✅ openai — plan={}, session={:?}%, weekly={:?}%, credits={:?}",
        out.snapshot.plan,
        out.snapshot
            .session
            .as_ref()
            .map(|window| window.utilization_pct),
        out.snapshot
            .weekly
            .as_ref()
            .map(|window| window.utilization_pct),
        out.snapshot.credits.map(|c| c.balance),
    );
}

#[tokio::test]
#[ignore = "live API; run with --ignored"]
async fn zai_live() {
    let api_key = std::env::var("ZAI_API_KEY")
        .expect("ZAI_API_KEY must be set (source ~/.config/zsh/secrets)");
    let cache = xdg_cache_for("zai");
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(15))
        .build()
        .unwrap();
    let endpoints = zai::fetch::Endpoints::default();
    let out = zai::fetch_snapshot(
        &client,
        &api_key,
        &cache,
        &endpoints,
        Duration::from_secs(0),
        None,
    )
    .await
    .expect("zai fetch should succeed against the real API");

    assert!(!out.snapshot.plan.is_empty(), "zai plan label empty");
    // Z.AI may legitimately return 0% on a fresh account, but at least one
    // bucket should exist — if all three are None, the schema changed.
    let has_any = out.snapshot.session.is_some()
        || out.snapshot.weekly.is_some()
        || out.snapshot.mcp.is_some();
    assert!(has_any, "zai snapshot has no buckets — shape changed?");
    for (label, w) in [
        ("session", &out.snapshot.session),
        ("weekly", &out.snapshot.weekly),
        ("mcp", &out.snapshot.mcp),
    ] {
        if let Some(w) = w.as_ref() {
            assert_pct(&format!("zai.{label}"), w.utilization_pct);
        }
    }
    println!(
        "✅ zai — plan={}, session={:?}%, weekly={:?}%, mcp={:?}%",
        out.snapshot.plan,
        out.snapshot.session.as_ref().map(|w| w.utilization_pct),
        out.snapshot.weekly.as_ref().map(|w| w.utilization_pct),
        out.snapshot.mcp.as_ref().map(|w| w.utilization_pct),
    );
}

#[tokio::test]
#[ignore = "live API; run with --ignored"]
async fn openrouter_live() {
    let api_key = std::env::var("OPENROUTER_API_KEY")
        .expect("OPENROUTER_API_KEY must be set (source ~/.config/zsh/secrets)");
    let cache = xdg_cache_for("openrouter");
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(15))
        .build()
        .unwrap();
    let endpoints = openrouter::fetch::Endpoints::default();
    let out = openrouter::fetch_snapshot(
        &client,
        &api_key,
        &cache,
        &endpoints,
        Duration::from_secs(0),
    )
    .await
    .expect("openrouter fetch should succeed against the real API");

    assert!(out.snapshot.total_credits >= 0.0, "or.total_credits < 0");
    assert!(out.snapshot.total_usage >= 0.0, "or.total_usage < 0");
    // total_usage being slightly larger than total_credits is possible during
    // reconciliation (debt allowed); don't assert otherwise.
    println!(
        "✅ openrouter — label={}, balance=${:.2}, used=${:.2}, monthly=${:.2}, free={}",
        out.snapshot.label,
        out.snapshot.balance(),
        out.snapshot.total_usage,
        out.snapshot.usage_monthly,
        out.snapshot.is_free_tier,
    );
}

#[tokio::test]
#[ignore = "live API; run with --ignored"]
async fn kimi_live() {
    let Ok(api_key) = std::env::var("KIMI_API_KEY") else {
        eprintln!("kimi_live: KIMI_API_KEY is unset — skipping optional Kimi smoke test");
        return;
    };
    if api_key.trim().is_empty() {
        eprintln!("kimi_live: KIMI_API_KEY is empty — skipping optional Kimi smoke test");
        return;
    }
    let cache = xdg_cache_for("kimi");
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(15))
        .build()
        .unwrap();
    let endpoints = kimi::fetch::Endpoints::default();
    let out = kimi::fetch_snapshot(
        &client,
        &api_key,
        &cache,
        &endpoints,
        Duration::from_secs(0),
    )
    .await
    .expect("kimi fetch should succeed against the real API");

    // Kimi permits missing or inconsistent counters, and the production
    // snapshot deliberately preserves them. Exercise all weekly fields while
    // checking the production-facing normalized percentage only.
    assert_pct("kimi.weekly", out.snapshot.weekly_pct());
    // A nonzero public limit means the parser selected its optional rolling
    // window. The public snapshot does not retain the wire duration/unit, so
    // it can only validate that window's normalized percentage and counters.
    if out.snapshot.window_limit > 0 {
        assert_pct("kimi.window", out.snapshot.window_pct());
    }
    println!(
        "✅ kimi — plan={:?}, weekly={} / {} ({} remaining; reset {:?}), window={} / {} ({} remaining; reset {:?})",
        out.snapshot.plan,
        out.snapshot.weekly_used,
        out.snapshot.weekly_limit,
        out.snapshot.weekly_remaining,
        out.snapshot.weekly_reset_at,
        out.snapshot.window_used,
        out.snapshot.window_limit,
        out.snapshot.window_remaining,
        out.snapshot.window_reset_at,
    );
}

#[tokio::test]
#[ignore = "live API; run with --ignored"]
async fn cursor_live() {
    // Cursor has no API key — the credential is the session token the Cursor
    // IDE wrote to its local state DB. So this test needs a real Cursor install
    // (or `CURSOR_DB_PATH` pointing at a copied `state.vscdb`) and skips
    // otherwise, the same way `kimi_live` skips without a key. Nothing to fetch
    // on a CI box with no Cursor.
    let db_path = match std::env::var("CURSOR_DB_PATH") {
        Ok(p) if !p.trim().is_empty() => std::path::PathBuf::from(p),
        _ => cursor::db::default_db_path().expect("resolve platform config dir"),
    };
    if !db_path.exists() {
        eprintln!(
            "cursor_live: no Cursor state DB at {} — skipping (sign in to the Cursor IDE, or set CURSOR_DB_PATH)",
            db_path.display()
        );
        return;
    }

    let cache = xdg_cache_for("cursor");
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(15))
        .build()
        .unwrap();
    let endpoints = cursor::fetch::Endpoints::default();
    let out = cursor::fetch_snapshot(
        &client,
        &db_path,
        &cache,
        &endpoints,
        Duration::from_secs(0),
    )
    .await
    .expect("cursor fetch should succeed against the real API");

    // The fields the widget depends on: two pool percentages (>= 0; a pool can
    // exceed 100 when over its included allowance, so only the low bound is
    // asserted) and a future billing-cycle reset.
    assert!(
        out.snapshot.auto_pct >= 0 && out.snapshot.api_pct >= 0,
        "cursor: negative pool percentage — shape changed? auto={} api={}",
        out.snapshot.auto_pct,
        out.snapshot.api_pct
    );
    assert!(!out.snapshot.plan.is_empty(), "cursor plan label empty");
    assert!(
        out.snapshot
            .reset_at
            .is_some_and(|r| r > chrono::Utc::now()),
        "cursor: reset_at should be a future instant, got {:?}",
        out.snapshot.reset_at
    );
    println!(
        "✅ cursor — plan={}, Cursor Models {}%, Other Models {}%, total {}%, on-demand={}, reset {:?}",
        out.snapshot.plan,
        out.snapshot.auto_pct,
        out.snapshot.api_pct,
        out.snapshot.total_pct,
        out.snapshot.on_demand_enabled,
        out.snapshot.reset_at,
    );
}

/// MiniMax Token Plan — optional: skipped unless a subscription key is present.
///
/// The endpoint answers HTTP 200 even for auth failures, so a green run here is
/// what proves the in-band `base_resp.status_code` check is still doing its job:
/// a wrong key surfaces as an error rather than an all-zero plan.
#[tokio::test]
#[ignore = "live API; run with --ignored"]
async fn minimax_live() {
    let Ok(api_key) = std::env::var("MINIMAX_API_KEY") else {
        eprintln!("minimax_live: MINIMAX_API_KEY is unset — skipping optional MiniMax smoke test");
        return;
    };
    if api_key.trim().is_empty() {
        eprintln!("minimax_live: MINIMAX_API_KEY is empty — skipping optional MiniMax smoke test");
        return;
    }
    let cache = xdg_cache_for("minimax");
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(15))
        .build()
        .unwrap();
    let endpoints = minimax::fetch::Endpoints::default();
    let out = minimax::fetch_snapshot(
        &client,
        &api_key,
        &cache,
        &endpoints,
        Duration::from_secs(0),
    )
    .await
    .expect("minimax fetch should succeed against the real API");

    assert_pct("minimax.session", out.snapshot.session.utilization_pct);
    assert_pct("minimax.weekly", out.snapshot.weekly.utilization_pct);
    // The interval length is read from the payload rather than assumed: it has
    // been observed at both 4h and 5h on the same account. A non-positive one
    // would divide the pace math by nothing.
    assert!(
        out.snapshot.session.window_duration > chrono::Duration::zero(),
        "minimax: interval window has no length — payload shape changed?"
    );
    if let Some(v) = out.snapshot.video_session.as_ref() {
        assert_pct("minimax.video", v.utilization_pct);
    }
    println!(
        "✅ minimax: {} · session {}% · weekly {}% · video {:?}",
        out.snapshot.plan,
        out.snapshot.session.utilization_pct,
        out.snapshot.weekly.utilization_pct,
        out.snapshot
            .video_session
            .as_ref()
            .map(|w| w.utilization_pct),
    );
}