clauth 0.7.4

Manage multiple Claude Code accounts, monitor 5h/7d usage with configurable auto-switch and delegation with an MCP plugin. CLI + TUI.
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use super::*;

// 2026-05-17T14:20:00 UTC == 1779027600 epoch seconds.
const BASE_UTC: i64 = 1_779_027_600;

#[test]
fn short_label_drops_claude_prefix_and_keeps_max_multiplier() {
    assert_eq!(
        PlanTier::Max(Some(5)).short_label().as_deref(),
        Some("Max 5x")
    );
    assert_eq!(PlanTier::Max(None).short_label().as_deref(), Some("Max"));
    assert_eq!(PlanTier::Pro.short_label().as_deref(), Some("Pro"));
    // an unknown tier carries no label so the MCP omits it entirely.
    assert_eq!(PlanTier::Unknown.short_label(), None);
}

#[test]
fn parses_z_suffix() {
    assert_eq!(iso_to_epoch_secs("2026-05-17T14:20:00Z"), Some(BASE_UTC));
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00.121699Z"),
        Some(BASE_UTC)
    );
}

#[test]
fn parses_colon_offset() {
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00+00:00"),
        Some(BASE_UTC)
    );
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00.121699+00:00"),
        Some(BASE_UTC)
    );
    // +05:30 is 5h30m ahead, so the UTC instant is earlier.
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00+05:30"),
        Some(BASE_UTC - (5 * 3600 + 30 * 60))
    );
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00-05:30"),
        Some(BASE_UTC + (5 * 3600 + 30 * 60))
    );
}

#[test]
fn parses_colonless_offset() {
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00+0000"),
        Some(BASE_UTC)
    );
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00.121699+0000"),
        Some(BASE_UTC)
    );
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00+0530"),
        Some(BASE_UTC - (5 * 3600 + 30 * 60))
    );
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00-0530"),
        Some(BASE_UTC + (5 * 3600 + 30 * 60))
    );
}

#[test]
fn parses_bare_hour_offset() {
    assert_eq!(iso_to_epoch_secs("2026-05-17T14:20:00+00"), Some(BASE_UTC));
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00+05"),
        Some(BASE_UTC - 5 * 3600)
    );
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00-05"),
        Some(BASE_UTC + 5 * 3600)
    );
}

#[test]
fn colon_and_colonless_agree() {
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00+0530"),
        iso_to_epoch_secs("2026-05-17T14:20:00+05:30")
    );
    assert_eq!(
        iso_to_epoch_secs("2026-05-17T14:20:00-0800"),
        iso_to_epoch_secs("2026-05-17T14:20:00-08:00")
    );
}

#[test]
fn rejects_malformed() {
    // Too short to hold a date-time.
    assert_eq!(iso_to_epoch_secs("2026-05-17"), None);
    // Bad separators.
    assert_eq!(iso_to_epoch_secs("2026/05/17T14:20:00Z"), None);
    // Non-sign, non-Z trailing char.
    assert_eq!(iso_to_epoch_secs("2026-05-17T14:20:00X"), None);
    // Garbage in the offset.
    assert_eq!(iso_to_epoch_secs("2026-05-17T14:20:00+ab:cd"), None);
    assert_eq!(iso_to_epoch_secs("2026-05-17T14:20:00+5"), None);
    assert_eq!(iso_to_epoch_secs("2026-05-17T14:20:00+12345"), None);
    assert_eq!(iso_to_epoch_secs("2026-05-17T14:20:00+05:3"), None);
}

/// `epoch_secs_to_iso` is the exact inverse of `iso_to_epoch_secs`: a round
/// trip through the formatter lands on the same epoch, and the output uses the
/// `+00:00` shape the parser accepts.
#[test]
fn epoch_to_iso_round_trips() {
    assert_eq!(epoch_secs_to_iso(BASE_UTC), "2026-05-17T14:20:00+00:00");
    for secs in [0, BASE_UTC, 951_867_122, 4_102_444_799] {
        assert_eq!(
            iso_to_epoch_secs(&epoch_secs_to_iso(secs)),
            Some(secs),
            "round trip failed for {secs}"
        );
    }
    // Negative input clamps to epoch 0 instead of underflowing the calendar.
    assert_eq!(epoch_secs_to_iso(-1), "1970-01-01T00:00:00+00:00");
}

/// `retry-after` parsing accepts the delta-seconds form and the IMF-fixdate
/// HTTP-date form; a future date becomes the delay until it, a past date is
/// `Duration::ZERO`, and garbage is no-hint (`None`).
#[test]
fn retry_after_parses_delta_seconds_and_http_date() {
    assert_eq!(parse_retry_after("5"), Some(Duration::from_secs(5)));
    assert_eq!(parse_retry_after(" 30 "), Some(Duration::from_secs(30)));
    assert_eq!(parse_retry_after("0"), Some(Duration::ZERO));
    assert_eq!(parse_retry_after(""), None);
    assert_eq!(parse_retry_after("-5"), None);
    assert_eq!(parse_retry_after("1.5"), None);

    // HTTP-date form, evaluated against a fixed instant for determinism.
    // "Wed, 21 Oct 2015 07:28:00 GMT" == 1_445_412_480 epoch seconds.
    let date = "Wed, 21 Oct 2015 07:28:00 GMT";
    assert_eq!(
        parse_retry_after_at(date, 1_445_412_480),
        Some(Duration::ZERO)
    );
    assert_eq!(
        parse_retry_after_at(date, 1_445_412_480 - 90),
        Some(Duration::from_secs(90)),
        "a future HTTP-date yields the delay until it"
    );
    assert_eq!(
        parse_retry_after_at(date, 1_445_412_480 + 120),
        Some(Duration::ZERO),
        "a past HTTP-date saturates to zero"
    );
    // Malformed HTTP-dates are no-hint.
    assert_eq!(
        parse_retry_after_at("Wed, 21 Foo 2015 07:28:00 GMT", 0),
        None
    );
    assert_eq!(parse_retry_after_at("21 Oct 2015 07:28:00 GMT", 0), None);
    assert_eq!(
        parse_retry_after_at("Wed, 21 Oct 2015 07:28:00 PST", 0),
        None
    );
}

/// `reserve_slot` spaces same-host requests by `REQUEST_SPACING_MS`: a cold slot
/// (now already past it) fires immediately, and a slot still ahead of now waits
/// until it — each reservation advancing that host's slot by exactly one spacing.
#[test]
fn reserve_slot_spaces_requests() {
    let now = 1_000_000u64;
    // Cold slot in the past → fire now, reserve one spacing out.
    let (next, wait) = reserve_slot(0, now);
    assert_eq!(wait, 0);
    assert_eq!(next, now + REQUEST_SPACING_MS);
    // Slot already ahead of now → wait until it, advance by one more spacing.
    let (next2, wait2) = reserve_slot(next, now);
    assert_eq!(wait2, REQUEST_SPACING_MS);
    assert_eq!(next2, next + REQUEST_SPACING_MS);
}

/// The ideal-pace marker tracks the fraction of the window already elapsed:
/// half-elapsed → 50%, just-opened → 0%, lapsed → clamped to 100%. Windows with
/// no reset time or no fixed duration return `None` (no marker).
#[test]
fn ideal_pace_tracks_elapsed_window_fraction() {
    let win = |reset_secs: i64| UsageWindow {
        utilization: 0.0,
        resets_at: Some(epoch_secs_to_iso(reset_secs)),
    };

    // 5h window with 2.5h left → half elapsed → 50%.
    let p = ideal_pace_pct(LABEL_5H, &win(BASE_UTC + 9_000), BASE_UTC).unwrap();
    assert!(
        (p - 50.0).abs() < 1e-6,
        "half-elapsed 5h window paces at 50%, got {p}"
    );

    // 7d window with its full duration left → just opened → 0%.
    let p = ideal_pace_pct(LABEL_7D, &win(BASE_UTC + 7 * 86_400), BASE_UTC).unwrap();
    assert!(
        p.abs() < 1e-6,
        "a freshly-opened window paces at 0%, got {p}"
    );

    // Reset already in the past → clamped to 100%.
    let p = ideal_pace_pct(LABEL_5H, &win(BASE_UTC - 1), BASE_UTC).unwrap();
    assert!(
        (p - 100.0).abs() < 1e-6,
        "a lapsed window paces at 100%, got {p}"
    );

    // No reset time, or a window with no fixed duration → no marker.
    let no_reset = UsageWindow {
        utilization: 0.0,
        resets_at: None,
    };
    assert_eq!(ideal_pace_pct(LABEL_5H, &no_reset, BASE_UTC), None);
    assert_eq!(
        ideal_pace_pct("extra", &win(BASE_UTC + 100), BASE_UTC),
        None
    );
}

/// Window-anchored average pace = utilization spread over the time elapsed since
/// the window opened, in %/day — rotation-proof because it reads only `resets_at`
/// and the current utilization (no history). Gated below `min_elapsed_secs`, and
/// `None` without a reset time or fixed duration.
#[test]
fn window_avg_pace_is_util_over_elapsed_days() {
    let win = |util: f64, reset_secs: i64| UsageWindow {
        utilization: util,
        resets_at: Some(epoch_secs_to_iso(reset_secs)),
    };
    let duration = 7 * 86_400;

    // 7d window 12h into the week at 21% → 21 / 0.5d = 42 %/d.
    let reset = BASE_UTC + duration - 12 * 3600;
    let pace = window_avg_pace_per_day(LABEL_7D, &win(21.0, reset), BASE_UTC, 3600).unwrap();
    assert!((pace - 42.0).abs() < 1e-6, "12h/21% → 42 %/d, got {pace}");

    // Freshly opened (30 min elapsed) is below the 1h floor → None, no divide-by-~0.
    let reset = BASE_UTC + duration - 1800;
    assert_eq!(
        window_avg_pace_per_day(LABEL_7D, &win(5.0, reset), BASE_UTC, 3600),
        None
    );

    // No reset time, or a label with no fixed window → None.
    let no_reset = UsageWindow {
        utilization: 21.0,
        resets_at: None,
    };
    assert_eq!(
        window_avg_pace_per_day(LABEL_7D, &no_reset, BASE_UTC, 3600),
        None
    );
    assert_eq!(
        window_avg_pace_per_day("extra", &win(21.0, BASE_UTC + 100), BASE_UTC, 3600),
        None
    );
}

/// Provider window labels shaped `<n>h`/`<n>d` resolve to a duration so api-key
/// bars get the same pace + ideal-line as OAuth windows; named OAuth labels keep
/// their fixed durations and non-window/malformed labels stay `None`.
#[test]
fn window_duration_parses_provider_labels() {
    assert_eq!(window_duration_secs(LABEL_5H), Some(5 * 3600));
    assert_eq!(window_duration_secs(LABEL_7D), Some(7 * 86_400));
    // Dynamic per-model labels resolve to the 7-day window.
    assert_eq!(window_duration_secs("7d fable"), Some(7 * 86_400));
    assert_eq!(window_duration_secs("7d opus"), Some(7 * 86_400));
    assert_eq!(window_duration_secs("5h"), Some(5 * 3600));
    assert_eq!(window_duration_secs("30d"), Some(30 * 86_400));
    assert_eq!(window_duration_secs("14d"), Some(14 * 86_400));
    assert_eq!(window_duration_secs("balance"), None);
    assert_eq!(window_duration_secs("d"), None);
    assert_eq!(window_duration_secs("0d"), None);
    assert_eq!(window_duration_secs(""), None);
}

/// `/profile` re-fetch policy: fetches on first load (no stamp yet) and on a
/// `force` (401 retry), reuses the plan within the hourly TTL, re-pulls once it
/// lapses, and `expire_profile_ttl` (manual single refresh) re-arms it. A
/// persistently failing endpoint is still capped at one attempt per hour.
#[test]
fn take_profile_fetch_honors_ttl_force_and_expiry() {
    let t0 = 1_000_000_000_000u64;

    // First load (no stamp) → fetch; then the same name within the hour → reuse,
    // even though the prior attempt may have failed to yield a plan.
    assert!(
        take_profile_fetch("ttl-first", false, t0),
        "first load pulls /profile"
    );
    assert!(
        !take_profile_fetch("ttl-first", false, t0 + 60_000),
        "within the TTL the cached plan is reused — no per-tick re-pull"
    );

    // `force` overrides a fresh TTL (separate name to avoid cross-talk).
    assert!(take_profile_fetch("ttl-force", false, t0));
    assert!(
        take_profile_fetch("ttl-force", true, t0 + 60_000),
        "force (401 retry) re-pulls /profile despite a fresh TTL"
    );

    // Past the TTL → re-pull.
    assert!(take_profile_fetch("ttl-stale", false, t0));
    assert!(
        take_profile_fetch("ttl-stale", false, t0 + PROFILE_TTL_MS + 1),
        "a plan past the TTL is re-pulled"
    );

    // Manual single refresh expires the clock → re-pull even within the hour.
    assert!(take_profile_fetch("ttl-expire", false, t0));
    assert!(!take_profile_fetch("ttl-expire", false, t0 + 60_000));
    expire_profile_ttl("ttl-expire");
    assert!(
        take_profile_fetch("ttl-expire", false, t0 + 120_000),
        "expiring the TTL forces a re-pull"
    );
}

/// Windows are derived from the normalized `limits[]` array, not the legacy
/// per-model top-level fields: `session` → 5h, `weekly_all` → 7d, and each
/// `weekly_scoped` entry becomes a dynamic `"7d <model>"` window — so a model
/// the server adds later (here Fable) is picked up with zero code change, and
/// `limits[]` wins over any stale top-level `five_hour`/`seven_day`. `spend`
/// parses its minor-unit money into dollars.
#[test]
fn limits_drive_windows_and_pick_up_new_models() {
    let json = r#"{
        "five_hour": {"utilization": 99, "resets_at": "2026-07-02T14:50:00+00:00"},
        "seven_day": {"utilization": 99, "resets_at": "2026-07-06T23:59:59+00:00"},
        "seven_day_opus": null,
        "limits": [
            {"kind": "session", "percent": 3, "resets_at": "2026-07-02T14:50:00+00:00"},
            {"kind": "weekly_all", "percent": 9, "resets_at": "2026-07-06T23:59:59+00:00"},
            {"kind": "weekly_scoped", "percent": 14, "resets_at": "2026-07-07T00:00:00+00:00",
             "scope": {"model": {"display_name": "Fable"}}}
        ],
        "spend": {"enabled": true, "percent": 32,
                  "used": {"amount_minor": 320, "currency": "USD", "exponent": 2},
                  "limit": {"amount_minor": 1000, "currency": "USD", "exponent": 2}}
    }"#;
    let raw: RawUsage = serde_json::from_str(json).unwrap();

    let w = windows_from_raw(&raw);
    // limits[] wins over the stale 99% top-level fields.
    assert_eq!(w.five_hour.map(|w| w.utilization), Some(3.0));
    assert_eq!(w.seven_day.map(|w| w.utilization), Some(9.0));
    // The new model is recognized purely from its scope name.
    assert_eq!(w.weekly_scoped.len(), 1);
    assert_eq!(w.weekly_scoped[0].label, "7d fable");
    assert_eq!(w.weekly_scoped[0].window.utilization, 14.0);
    assert_eq!(
        window_duration_secs(&w.weekly_scoped[0].label),
        Some(7 * 86_400)
    );

    let spend = SpendInfo::from_raw(raw.spend.as_ref().unwrap());
    assert!(spend.is_visible());
    assert_eq!(spend.used, Some(3.20));
    assert_eq!(spend.limit, Some(10.0));
    assert_eq!(spend.percent, Some(32.0));
    assert_eq!(spend.currency.as_deref(), Some("USD"));
}

/// A missing `session` / `weekly_all` limit falls back to the legacy top-level
/// window so an unmigrated account still renders 5h/7d; a disabled `spend` block
/// stays hidden.
#[test]
fn windows_fall_back_to_legacy_fields_when_limits_absent() {
    let json = r#"{
        "five_hour": {"utilization": 7, "resets_at": "2026-07-02T14:50:00+00:00"},
        "seven_day": {"utilization": 11, "resets_at": "2026-07-06T23:59:59+00:00"},
        "limits": [],
        "spend": {"enabled": false, "limit": null}
    }"#;
    let raw: RawUsage = serde_json::from_str(json).unwrap();

    let w = windows_from_raw(&raw);
    assert_eq!(w.five_hour.map(|w| w.utilization), Some(7.0));
    assert_eq!(w.seven_day.map(|w| w.utilization), Some(11.0));
    assert!(w.weekly_scoped.is_empty());
    assert!(!SpendInfo::from_raw(raw.spend.as_ref().unwrap()).is_visible());
}

/// `SpendInfo` money conversion + visibility edge cases (the bar is built blind
/// against the schema since no reachable account enables it): `exponent` scales
/// the minor units and defaults to cents when absent, a missing `limit` yields a
/// used-only bar, currency passes through, and a disabled block with no cap stays
/// hidden.
#[test]
fn spend_money_conversion_and_visibility() {
    let parse = |json: &str| SpendInfo::from_raw(&serde_json::from_str::<RawSpend>(json).unwrap());

    // exponent 3 → thousandths; non-USD currency preserved.
    let s = parse(
        r#"{"enabled": true, "percent": 50,
            "used": {"amount_minor": 1500, "currency": "EUR", "exponent": 3},
            "limit": {"amount_minor": 3000, "currency": "EUR", "exponent": 3}}"#,
    );
    assert_eq!(s.used, Some(1.5));
    assert_eq!(s.limit, Some(3.0));
    assert_eq!(s.currency.as_deref(), Some("EUR"));
    assert!(s.is_visible());

    // Missing exponent defaults to cents (2); missing limit → used-only, still
    // visible because the cap is enabled.
    let s = parse(r#"{"enabled": true, "used": {"amount_minor": 250, "currency": "USD"}}"#);
    assert_eq!(s.used, Some(2.5));
    assert_eq!(s.limit, None);
    assert!(s.is_visible());

    // A cap present but currently disabled is still worth showing.
    assert!(parse(r#"{"enabled": false, "limit": {"amount_minor": 1000}}"#).is_visible());

    // Fully disabled, no cap → hidden.
    let s = parse(r#"{"enabled": false}"#);
    assert!(!s.is_visible());
    assert_eq!(s.used, None);
}

/// The speculative fields (per-window `*_dollars`, surface-scoped limits,
/// `extra_usage.daily/weekly`) are null on every reachable account and their
/// shapes are unconfirmed, so they parse defensively: money in either shape, a
/// surface-named scoped label, and a period breakdown — and an unexpected shape
/// is ignored, never a `/usage` parse failure.
#[test]
fn blind_fields_parse_defensively() {
    // Lenient money: bare number = dollars, `{amount_minor,exponent}` = minor
    // units, `{amount}` = dollars, anything else = None.
    assert_eq!(json_to_dollars(&serde_json::json!(12.5)), Some(12.5));
    assert_eq!(
        json_to_dollars(&serde_json::json!({"amount_minor": 1234, "exponent": 2})),
        Some(12.34)
    );
    assert_eq!(
        json_to_dollars(&serde_json::json!({"amount": "7.5"})),
        Some(7.5)
    );
    assert_eq!(json_to_dollars(&serde_json::json!("garbage")), None);
    assert_eq!(json_to_dollars(&serde_json::json!({})), None);

    let json = r#"{
        "five_hour": {"utilization": 40, "resets_at": "2026-07-02T14:50:00+00:00",
                      "used_dollars": {"amount_minor": 320, "exponent": 2},
                      "limit_dollars": 10},
        "limits": [
            {"kind": "session", "percent": 40, "resets_at": "2026-07-02T14:50:00+00:00"},
            {"kind": "weekly_scoped", "percent": 5, "resets_at": "2026-07-07T00:00:00+00:00",
             "scope": {"surface": {"display_name": "Code"}}}
        ],
        "extra_usage": {"is_enabled": true, "currency": "USD",
                        "daily": {"used_credits": 1.5, "utilization": 15},
                        "weekly": 999}
    }"#;
    let raw: RawUsage = serde_json::from_str(json).unwrap();
    let w = windows_from_raw(&raw);

    // #5: both dollar shapes land on the 5h window (from the top-level object).
    let d = w.window_dollars.iter().find(|d| d.label == "5h").unwrap();
    assert_eq!(d.used, Some(3.20));
    assert_eq!(d.limit, Some(10.0));

    // #6: a surface-scoped limit (no model) is labeled from the surface name.
    assert_eq!(w.weekly_scoped.len(), 1);
    assert_eq!(w.weekly_scoped[0].label, "7d code");

    // #7: an object daily breakdown extracts; a bare-number weekly is ignored,
    // not a parse error.
    let extra = raw.extra_usage.as_ref().unwrap();
    let daily = ExtraPeriod::from_value(extra.daily.as_ref().unwrap()).unwrap();
    assert_eq!(daily.utilization, Some(15.0));
    assert_eq!(daily.used_credits, Some(1.5));
    assert!(ExtraPeriod::from_value(extra.weekly.as_ref().unwrap()).is_none());
}