ai-usagebar 1.9.1

Omarchy/Waybar widgets + TUI for tracking multi-provider AI plan usage
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
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
//! Fetch Kimi usage from `/coding/v1/usages`.
//!
//! One endpoint, two credentials: an **API key**, or the **Kimi Code CLI's
//! OAuth session** — the credential a subscriber already has locally, with no
//! key to create or paste. See [`Auth`] and `oauth.rs`.

use std::path::{Path, PathBuf};
use std::time::Duration;

use chrono::{DateTime, Utc};

use crate::cache::{Cache, acquire_lock_async};
use crate::error::{AppError, Result};
use crate::usage::KimiSnapshot;

use super::oauth::{self, Region};
use super::types::{UsagesResponse, UserInfoResponse, humanize_membership_level};

pub const BASE_URL: &str = "https://api.kimi.com";
const HTTP_TIMEOUT: Duration = Duration::from_secs(10);
const REFRESH_TIMEOUT: Duration = Duration::from_secs(15);
const LOCK_TIMEOUT: Duration = Duration::from_secs(15);
/// Stable marker stored alongside code 0 for a successful HTTP response whose
/// payload no longer matches Kimi's undocumented usage schema.
pub const SCHEMA_DRIFT_MESSAGE: &str = "Kimi API schema drift";

#[derive(Debug, Clone)]
pub struct Endpoints {
    pub usages: String,
    /// Profile endpoint, read solely for the subscription's own tier name.
    pub me: String,
    /// OAuth token endpoint for the same deployment. Unused by the API-key
    /// path, which never refreshes anything.
    pub token: String,
}

impl Default for Endpoints {
    fn default() -> Self {
        Self::for_region(Region::MainlandCn)
    }
}

impl Endpoints {
    pub fn for_region(region: Region) -> Self {
        Self {
            usages: format!("{}/usages", region.api_base()),
            me: format!("{}/me", region.api_base()),
            token: oauth::token_endpoint(region.oauth_host()),
        }
    }
}

/// Where the bearer for `/coding/v1/usages` comes from.
#[derive(Debug, Clone)]
pub enum Auth {
    /// A platform API key (`KIMI_API_KEY` or `[kimi] api_key`).
    ApiKey(String),
    /// The Kimi Code CLI's own OAuth session — a subscription login.
    KimiCode(KimiCodeAuth),
}

/// The two paths inside a kimi-code home this vendor touches: the credential
/// file it reads and rewrites, and the lock target that serializes a refresh
/// against the CLI's own (see `lock.rs`).
#[derive(Debug, Clone)]
pub struct KimiCodeAuth {
    pub credentials_path: PathBuf,
    pub lock_target: PathBuf,
}

impl KimiCodeAuth {
    pub fn in_home(home: &Path) -> Self {
        Self {
            credentials_path: oauth::credentials_path_in(home),
            lock_target: oauth::lock_target_in(home),
        }
    }

    /// A credential file relocated by config (`[kimi] credentials_path`) still
    /// belongs to a kimi-code home; the lock target is derived from that home
    /// so both clients agree on which file the lock protects.
    pub fn with_credentials_path(home: &Path, credentials_path: PathBuf) -> Self {
        Self {
            credentials_path,
            lock_target: oauth::lock_target_in(home),
        }
    }
}

/// This vendor's [`Outcome`](crate::outcome::Outcome) — the shared shape,
/// specialised to its snapshot.
pub type FetchOutcome = crate::outcome::Outcome<KimiSnapshot>;

/// API-key fetch. Kept as-is for existing callers; the OAuth path goes
/// through [`fetch_snapshot_with_auth`].
pub async fn fetch_snapshot(
    client: &reqwest::Client,
    api_key: &str,
    cache: &Cache,
    endpoints: &Endpoints,
    cache_ttl: Duration,
) -> Result<FetchOutcome> {
    fetch_snapshot_with_auth(
        client,
        &Auth::ApiKey(api_key.to_string()),
        cache,
        endpoints,
        cache_ttl,
    )
    .await
}

pub async fn fetch_snapshot_with_auth(
    client: &reqwest::Client,
    auth: &Auth,
    cache: &Cache,
    endpoints: &Endpoints,
    cache_ttl: Duration,
) -> Result<FetchOutcome> {
    fetch_snapshot_at(client, auth, cache, endpoints, cache_ttl, Utc::now()).await
}

/// Clock seam for the OAuth expiry decision, mirroring
/// `kiro::fetch::fetch_snapshot_at`.
async fn fetch_snapshot_at(
    client: &reqwest::Client,
    auth: &Auth,
    cache: &Cache,
    endpoints: &Endpoints,
    cache_ttl: Duration,
    now: DateTime<Utc>,
) -> Result<FetchOutcome> {
    cache.ensure_dir()?;
    let _lock = acquire_lock_async(&cache.lock_path(), LOCK_TIMEOUT).await?;

    if let Some(bytes) = cache.fresh_payload(cache_ttl)? {
        // Releases before the profile lookup cached `/usages`' internal enum
        // verbatim. Do not let a still-fresh legacy entry postpone `/me` until
        // the normal TTL expires: refresh it once and replace it with Kimi's
        // own tier name. If the network is down, the fallback path below still
        // serves the quota after humanizing the enum.
        if !cache_has_legacy_plan(&bytes)
            && let Ok(outcome) = reuse_cache(bytes, cache, false)
        {
            return Ok(outcome);
        }
    }
    // Corrupt fresh cache: fall through to live fetch rather than return a
    // fabricated zero snapshot.

    match fetch_live(client, endpoints, auth, now).await {
        Ok(snap) => {
            let bytes = serde_json::to_vec(&snap_to_json(&snap))?;
            cache.write_payload(&bytes)?;
            Ok(crate::outcome::Outcome::fresh(snap))
        }
        Err(e) if e.is_transient() => fallback_silent(cache, e),
        Err(e) => {
            cache.mark_stale();
            if let Some((code, msg)) = error_to_pair(&e) {
                cache.write_last_error(code, &msg);
            }
            fallback_with_error(cache, e)
        }
    }
}

fn fallback_silent(cache: &Cache, original: AppError) -> Result<FetchOutcome> {
    crate::outcome::fallback(cache, None, original, parse_cache)
}

fn fallback_with_error(cache: &Cache, original: AppError) -> Result<FetchOutcome> {
    let last_error = error_to_pair(&original);
    crate::outcome::fallback(cache, last_error, original, parse_cache)
}

fn error_to_pair(e: &AppError) -> Option<(u16, String)> {
    match e {
        AppError::Http { status, body } => Some((*status, body.clone())),
        // A 2xx response with an unknown shape is not an HTTP 422 response.
        AppError::Schema(_) => Some((0, SCHEMA_DRIFT_MESSAGE.into())),
        e => Some((0, e.to_string())),
    }
}

fn reuse_cache(bytes: Vec<u8>, cache: &Cache, stale: bool) -> Result<FetchOutcome> {
    let snap = parse_cache(&bytes)?;
    Ok(crate::outcome::Outcome::cached(snap, cache, stale))
}

fn parse_cache(bytes: &[u8]) -> Result<KimiSnapshot> {
    let v: serde_json::Value = serde_json::from_slice(bytes)?;
    Ok(KimiSnapshot {
        plan: v["plan"].as_str().map(|plan| {
            if plan.starts_with("LEVEL_") {
                humanize_membership_level(plan)
            } else {
                plan.to_string()
            }
        }),
        weekly_limit: parse_cache_u64(&v["weekly_limit"], "weekly_limit")?,
        weekly_used: parse_cache_u64(&v["weekly_used"], "weekly_used")?,
        weekly_remaining: parse_cache_u64(&v["weekly_remaining"], "weekly_remaining")?,
        weekly_reset_at: parse_cache_datetime(&v["weekly_reset_at"])?,
        window_limit: parse_cache_u64(&v["window_limit"], "window_limit")?,
        window_used: parse_cache_u64(&v["window_used"], "window_used")?,
        window_remaining: parse_cache_u64(&v["window_remaining"], "window_remaining")?,
        window_reset_at: parse_cache_datetime(&v["window_reset_at"])?,
    })
}

fn cache_has_legacy_plan(bytes: &[u8]) -> bool {
    serde_json::from_slice::<serde_json::Value>(bytes)
        .ok()
        .and_then(|value| value["plan"].as_str().map(str::to_owned))
        .is_some_and(|plan| plan.starts_with("LEVEL_"))
}

fn parse_cache_u64(v: &serde_json::Value, name: &str) -> Result<u64> {
    v.as_u64()
        .ok_or_else(|| AppError::Schema(format!("kimi cache: invalid {name}")))
}

fn parse_cache_datetime(v: &serde_json::Value) -> Result<Option<DateTime<Utc>>> {
    match v {
        serde_json::Value::Null => Ok(None),
        serde_json::Value::String(s) => DateTime::parse_from_rfc3339(s)
            .map(|dt| Some(dt.into()))
            .map_err(|e| AppError::Schema(format!("kimi cache: invalid reset timestamp: {e}"))),
        _ => Err(AppError::Schema(
            "kimi cache: invalid reset timestamp".into(),
        )),
    }
}

fn snap_to_json(snap: &KimiSnapshot) -> serde_json::Value {
    serde_json::json!({
        "plan": snap.plan,
        "weekly_limit": snap.weekly_limit,
        "weekly_used": snap.weekly_used,
        "weekly_remaining": snap.weekly_remaining,
        "weekly_reset_at": snap.weekly_reset_at.map(|dt| dt.to_rfc3339()),
        "window_limit": snap.window_limit,
        "window_used": snap.window_used,
        "window_remaining": snap.window_remaining,
        "window_reset_at": snap.window_reset_at.map(|dt| dt.to_rfc3339()),
    })
}

/// Resolve the bearer for this fetch. The API key is already one; a Kimi Code
/// login may first need a refresh, which rotates the CLI's stored token pair
/// and is therefore serialized against the CLI itself.
async fn bearer_token(
    client: &reqwest::Client,
    endpoints: &Endpoints,
    auth: &Auth,
    now: DateTime<Utc>,
) -> Result<String> {
    let kimi_code = match auth {
        Auth::ApiKey(key) => return Ok(key.clone()),
        Auth::KimiCode(kimi_code) => kimi_code,
    };

    let creds = oauth::read_from(&kimi_code.credentials_path)?;
    if !oauth::needs_refresh(creds.expires_at, now.timestamp()) {
        return Ok(creds.access_token);
    }

    let _lock = super::lock::acquire(&kimi_code.lock_target).await?;
    // Re-read under the lock: the CLI (or another ai-usagebar process) may
    // have refreshed while we waited, and reusing our pre-lock copy would burn
    // an already-rotated refresh token.
    let creds = oauth::read_from(&kimi_code.credentials_path)?;
    if !oauth::needs_refresh(creds.expires_at, now.timestamp()) {
        return Ok(creds.access_token);
    }

    let refreshed = tokio::time::timeout(
        REFRESH_TIMEOUT,
        oauth::refresh(
            client,
            &endpoints.token,
            oauth::CLIENT_ID,
            &creds.refresh_token,
        ),
    )
    .await
    .map_err(|_| AppError::Transport(format!("kimi token refresh timeout: {}", endpoints.token)))?
    .map_err(|e| match e {
        AppError::Transport(msg) => AppError::Transport(msg),
        e => AppError::Credentials(format!(
            "Kimi Code CLI token refresh failed ({e}). Run `kimi` and log in again."
        )),
    })?;

    let next = oauth::apply_refresh(&creds, refreshed, now.timestamp());
    oauth::write_to(&kimi_code.credentials_path, &next).map_err(|e| {
        // The rotation already happened upstream, so a failed write-back means
        // the CLI is now holding a dead refresh token: say so plainly instead
        // of leaving the user to discover it at their next `kimi` run.
        AppError::Credentials(format!(
            "the refreshed Kimi Code CLI credentials could not be saved ({e}); run `kimi` and log in again"
        ))
    })?;
    Ok(next.access_token)
}

/// Ask `/coding/v1/me` for the subscription's own tier name ("Allegretto"),
/// which is the only place the vendor spells its plans the way its pricing
/// page does — `/usages` only carries the `LEVEL_*` wire enum.
///
/// Best-effort by construction: every failure returns `None` and leaves the
/// humanized enum in place. A missing plan label must never cost the user
/// their quota numbers, and this endpoint is documented (by kimi-code's own
/// error text) to 404 for accounts without a coding profile.
async fn plan_label(client: &reqwest::Client, url: &str, token: &str) -> Option<String> {
    let resp = tokio::time::timeout(
        HTTP_TIMEOUT,
        client
            .get(url)
            .header("Authorization", format!("Bearer {token}"))
            .header("Accept", "application/json")
            .send(),
    )
    .await
    .ok()?
    .ok()?;
    if !resp.status().is_success() {
        return None;
    }
    let bytes = crate::vendor::read_body_capped(resp, crate::vendor::MAX_BODY_BYTES)
        .await
        .ok()?;
    serde_json::from_slice::<UserInfoResponse>(&bytes)
        .ok()?
        .plan_label()
}

async fn fetch_live(
    client: &reqwest::Client,
    endpoints: &Endpoints,
    auth: &Auth,
    now: DateTime<Utc>,
) -> Result<KimiSnapshot> {
    let url = &endpoints.usages;
    let token = bearer_token(client, endpoints, auth, now).await?;
    // Concurrent, not sequential: the plan label is a second request against
    // the same deployment, and a widget tick should cost one round-trip's
    // latency, not two.
    let (usages, label) = tokio::join!(
        tokio::time::timeout(
            HTTP_TIMEOUT,
            client
                .get(url)
                .header("Authorization", format!("Bearer {token}"))
                .header("Accept", "application/json")
                .send(),
        ),
        plan_label(client, &endpoints.me, &token),
    );
    let resp = usages.map_err(|_| AppError::Transport(format!("kimi timeout: {url}")))??;

    let status = resp.status();

    if !status.is_success() {
        // Never surface upstream/proxy bodies: they can contain credentials or
        // arbitrary markup. Keep the cached diagnostic useful but generic.
        let body = if matches!(status.as_u16(), 401 | 403) {
            "Kimi authentication failed".into()
        } else {
            format!("Kimi API returned HTTP {}", status.as_u16())
        };
        return Err(AppError::Http {
            status: status.as_u16(),
            body,
        });
    }

    let bytes = crate::vendor::read_body_capped(resp, crate::vendor::MAX_BODY_BYTES).await?;
    let r: UsagesResponse = serde_json::from_slice(&bytes)
        .map_err(|e| AppError::Schema(format!("kimi usages response: {e}")))?;
    let mut snap = r.into_snapshot()?;
    if let Some(label) = label {
        snap.plan = Some(label);
    }
    Ok(snap)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn cache_fixture() -> (TempDir, Cache) {
        let td = TempDir::new().unwrap();
        let cache = Cache::at(td.path().join("kimi"));
        cache.ensure_dir().unwrap();
        (td, cache)
    }

    /// Both endpoints point at the same mock server, so an OAuth test can
    /// serve `/api/oauth/token` and `/coding/v1/usages` from one mockito.
    fn test_endpoints(base: &str) -> Endpoints {
        Endpoints {
            usages: format!("{base}/coding/v1/usages"),
            me: format!("{base}/coding/v1/me"),
            token: format!("{base}/api/oauth/token"),
        }
    }

    fn sample_json() -> &'static str {
        r#"{
            "user": { "membership": { "level": "LEVEL_INTERMEDIATE" } },
            "usage": { "limit": "100", "used": "26", "remaining": "74", "resetTime": "2026-02-11T17:32:50.757941Z" },
            "limits": [
                {
                    "window": { "duration": 300, "timeUnit": "TIME_UNIT_MINUTE" },
                    "detail": { "limit": "100", "used": "15", "remaining": "85", "resetTime": "2026-02-07T12:32:50.757941Z" }
                }
            ]
        }"#
    }

    fn sample_seed() -> serde_json::Value {
        serde_json::json!({
            "plan": "LEVEL_INTERMEDIATE",
            "weekly_limit": 100,
            "weekly_used": 30,
            "weekly_remaining": 70,
            "weekly_reset_at": "2026-02-11T17:32:50.757941Z",
            "window_limit": 100,
            "window_used": 20,
            "window_remaining": 80,
            "window_reset_at": "2026-02-07T12:32:50.757941Z"
        })
    }

    #[tokio::test]
    async fn live_200_returns_snapshot_and_sends_headers() {
        let mut server = mockito::Server::new_async().await;
        let m = server
            .mock("GET", "/coding/v1/usages")
            .with_status(200)
            .with_body(sample_json())
            .match_header("authorization", "Bearer sk-test")
            .match_header("accept", "application/json")
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        let client = reqwest::Client::new();
        let endpoints = test_endpoints(&server.url());
        let out = fetch_snapshot(
            &client,
            "sk-test",
            &cache,
            &endpoints,
            Duration::from_secs(0),
        )
        .await
        .unwrap();
        m.assert_async().await;
        // No /me mock on this server, so the humanized wire enum stands.
        assert_eq!(out.snapshot.plan, Some("Intermediate".into()));
        assert_eq!(out.snapshot.weekly_limit, 100);
        assert_eq!(out.snapshot.weekly_used, 26);
        assert_eq!(out.snapshot.weekly_remaining, 74);
        assert_eq!(out.snapshot.window_limit, 100);
        assert_eq!(out.snapshot.window_used, 15);
        assert!(!out.stale);
    }

    #[tokio::test]
    async fn http_401_falls_back_to_cache() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(401)
            .with_body(r#"{"error": "invalid api key"}"#)
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        cache
            .write_payload(sample_seed().to_string().as_bytes())
            .unwrap();

        let client = reqwest::Client::new();
        let endpoints = test_endpoints(&server.url());
        let out = fetch_snapshot(
            &client,
            "bad-key",
            &cache,
            &endpoints,
            Duration::from_secs(0),
        )
        .await
        .unwrap();
        assert!(out.stale);
        assert_eq!(out.snapshot.weekly_used, 30);
        assert_eq!(out.last_error.as_ref().map(|(c, _)| *c), Some(401));
    }

    #[tokio::test]
    async fn http_500_falls_back_to_cache() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(500)
            .with_body(r#"{"error": "internal server error"}"#)
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        cache
            .write_payload(sample_seed().to_string().as_bytes())
            .unwrap();

        let client = reqwest::Client::new();
        let endpoints = test_endpoints(&server.url());
        let out = fetch_snapshot(
            &client,
            "sk-test",
            &cache,
            &endpoints,
            Duration::from_secs(0),
        )
        .await
        .unwrap();
        assert!(out.stale);
        assert_eq!(out.last_error.as_ref().map(|(c, _)| *c), Some(500));
    }

    #[tokio::test]
    async fn http_401_without_cache_returns_http_error() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(401)
            .with_body(r#"{"error": "invalid api key"}"#)
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        let client = reqwest::Client::new();
        let endpoints = test_endpoints(&server.url());
        let err = fetch_snapshot(
            &client,
            "bad-key",
            &cache,
            &endpoints,
            Duration::from_secs(0),
        )
        .await
        .unwrap_err();
        match err {
            AppError::Http { status, .. } => assert_eq!(status, 401),
            other => panic!("expected Http 401, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn malformed_numeric_200_returns_schema_error() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(200)
            .with_body(r#"{"usage": {"limit": "100", "used": "garbage"}}"#)
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        let client = reqwest::Client::new();
        let endpoints = test_endpoints(&server.url());
        let err = fetch_snapshot(
            &client,
            "sk-test",
            &cache,
            &endpoints,
            Duration::from_secs(0),
        )
        .await
        .unwrap_err();
        assert!(
            err.to_string().contains("used") || err.to_string().contains("Schema"),
            "expected schema error, got {err}"
        );
    }

    #[tokio::test]
    async fn malformed_numeric_200_with_seeded_cache_returns_stale_snapshot_and_preserves_cache() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(200)
            .with_body(r#"{"usage": {"limit": "100", "used": "garbage"}}"#)
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        let seeded = sample_seed().to_string();
        cache.write_payload(seeded.as_bytes()).unwrap();

        let client = reqwest::Client::new();
        let endpoints = test_endpoints(&server.url());
        let out = fetch_snapshot(
            &client,
            "sk-test",
            &cache,
            &endpoints,
            Duration::from_secs(0),
        )
        .await
        .unwrap();

        assert!(out.stale);
        assert_eq!(out.snapshot.weekly_used, 30);
        assert_eq!(out.snapshot.window_used, 20);
        assert_eq!(out.last_error, Some((0, SCHEMA_DRIFT_MESSAGE.into())));

        // The payload file must still contain the original seeded snapshot.
        let payload = std::fs::read_to_string(cache.payload_path()).unwrap();
        assert_eq!(payload, seeded);
    }

    #[tokio::test]
    async fn error_object_200_returns_schema_error() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(200)
            .with_body(r#"{"error": "invalid token"}"#)
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        let client = reqwest::Client::new();
        let endpoints = test_endpoints(&server.url());
        let err = fetch_snapshot(
            &client,
            "sk-test",
            &cache,
            &endpoints,
            Duration::from_secs(0),
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("usage block"), "got {err}");
    }

    #[tokio::test]
    async fn corrupt_fresh_cache_ignored() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(200)
            .with_body(sample_json())
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        cache.write_payload(b"not valid json".as_slice()).unwrap();

        let client = reqwest::Client::new();
        let endpoints = test_endpoints(&server.url());
        let out = fetch_snapshot(
            &client,
            "sk-test",
            &cache,
            &endpoints,
            Duration::from_secs(60),
        )
        .await
        .unwrap();
        assert_eq!(out.snapshot.weekly_used, 26);
        assert!(!out.stale);
    }

    #[tokio::test]
    async fn a_fresh_legacy_plan_cache_is_upgraded_through_the_profile_endpoint() {
        let mut server = mockito::Server::new_async().await;
        let usages = server
            .mock("GET", "/coding/v1/usages")
            .with_status(200)
            .with_body(sample_json())
            .create_async()
            .await;
        let me = server
            .mock("GET", "/coding/v1/me")
            .with_status(200)
            .with_body(r#"{"user_level_name":"Allegretto"}"#)
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        cache
            .write_payload(sample_seed().to_string().as_bytes())
            .unwrap();

        let out = fetch_snapshot(
            &reqwest::Client::new(),
            "sk-test",
            &cache,
            &test_endpoints(&server.url()),
            Duration::from_secs(60),
        )
        .await
        .unwrap();

        usages.assert_async().await;
        me.assert_async().await;
        assert_eq!(out.snapshot.plan, Some("Allegretto".into()));
        let cached: serde_json::Value =
            serde_json::from_slice(&std::fs::read(cache.payload_path()).unwrap()).unwrap();
        assert_eq!(cached["plan"], "Allegretto");
    }

    #[test]
    fn a_legacy_plan_is_humanized_when_only_fallback_cache_is_available() {
        let bytes = sample_seed().to_string();
        let snap = parse_cache(bytes.as_bytes()).unwrap();
        assert_eq!(snap.plan, Some("Intermediate".into()));
    }

    #[tokio::test]
    async fn corrupt_stale_cache_returns_error() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(401)
            .with_body(r#"{"error": "invalid api key"}"#)
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        cache.write_payload(b"not valid json".as_slice()).unwrap();

        let client = reqwest::Client::new();
        let endpoints = test_endpoints(&server.url());
        let err = fetch_snapshot(
            &client,
            "bad-key",
            &cache,
            &endpoints,
            Duration::from_secs(0),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, AppError::Http { status, .. } if status == 401),
            "expected 401, got {err:?}"
        );
    }

    #[tokio::test]
    async fn transport_error_with_stale_cache_uses_cache() {
        // Use a URL that will not resolve to trigger a transport error.
        let (_td, cache) = cache_fixture();
        cache
            .write_payload(sample_seed().to_string().as_bytes())
            .unwrap();

        let client = reqwest::Client::new();
        let endpoints = test_endpoints("http://localhost:1");
        let out = fetch_snapshot(
            &client,
            "sk-test",
            &cache,
            &endpoints,
            Duration::from_secs(0),
        )
        .await
        .unwrap();
        assert!(out.stale);
        assert_eq!(out.snapshot.weekly_used, 30);
    }

    #[tokio::test]
    async fn missing_counters_with_seeded_cache_preserves_snapshot() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(200)
            .with_body(r#"{"usage":{"limit":100}}"#)
            .create_async()
            .await;
        let (_td, cache) = cache_fixture();
        let seeded = sample_seed().to_string();
        cache.write_payload(seeded.as_bytes()).unwrap();
        let out = fetch_snapshot(
            &reqwest::Client::new(),
            "sk-test",
            &cache,
            &test_endpoints(&server.url()),
            Duration::ZERO,
        )
        .await
        .unwrap();
        assert!(out.stale);
        assert_eq!(out.snapshot.weekly_used, 30);
        assert_eq!(
            std::fs::read_to_string(cache.payload_path()).unwrap(),
            seeded
        );
    }

    #[tokio::test]
    async fn unrecognized_window_with_seeded_cache_preserves_snapshot() {
        let mut server = mockito::Server::new_async().await;
        server.mock("GET", "/coding/v1/usages").with_status(200)
            .with_body(r#"{"usage":{"limit":100,"used":10},"limits":[{"window":{"duration":4,"timeUnit":"TIME_UNIT_HOUR"},"detail":{"limit":100,"used":10}}]}"#).create_async().await;
        let (_td, cache) = cache_fixture();
        let seeded = sample_seed().to_string();
        cache.write_payload(seeded.as_bytes()).unwrap();
        let out = fetch_snapshot(
            &reqwest::Client::new(),
            "sk-test",
            &cache,
            &test_endpoints(&server.url()),
            Duration::ZERO,
        )
        .await
        .unwrap();
        assert!(out.stale);
        assert_eq!(out.snapshot.window_used, 20);
        assert_eq!(
            std::fs::read_to_string(cache.payload_path()).unwrap(),
            seeded
        );
    }

    #[tokio::test]
    async fn http_error_body_is_redacted() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(500)
            .with_body("proxy secret: <token>")
            .create_async()
            .await;
        let (_td, cache) = cache_fixture();
        let err = fetch_snapshot(
            &reqwest::Client::new(),
            "sk-test",
            &cache,
            &test_endpoints(&server.url()),
            Duration::ZERO,
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, AppError::Http { status: 500, ref body } if body == "Kimi API returned HTTP 500")
        );
    }

    // ---- Kimi Code CLI (subscription) credential path ----

    /// A kimi-code home with a stored login. `expires_at` is relative to
    /// `NOW_SECS`, the instant every OAuth test below passes in.
    const NOW_SECS: i64 = 1_800_000_000;

    fn kimi_code_home(td: &TempDir, expires_in: i64) -> (PathBuf, KimiCodeAuth) {
        let home = td.path().join(".kimi-code");
        let auth = KimiCodeAuth::in_home(&home);
        std::fs::create_dir_all(auth.credentials_path.parent().unwrap()).unwrap();
        std::fs::write(
            &auth.credentials_path,
            serde_json::json!({
                "access_token": "cli-at",
                "refresh_token": "cli-rt",
                "expires_at": NOW_SECS + expires_in,
                "expires_in": 900,
                "scope": "kimi-code",
                "token_type": "Bearer",
            })
            .to_string(),
        )
        .unwrap();
        (home, auth)
    }

    fn now() -> DateTime<Utc> {
        DateTime::from_timestamp(NOW_SECS, 0).unwrap()
    }

    #[tokio::test]
    async fn a_valid_cli_token_is_used_as_is_and_never_refreshed() {
        let mut server = mockito::Server::new_async().await;
        let usages = server
            .mock("GET", "/coding/v1/usages")
            .match_header("authorization", "Bearer cli-at")
            .with_status(200)
            .with_body(sample_json())
            .create_async()
            .await;
        let refresh = server
            .mock("POST", "/api/oauth/token")
            .expect(0)
            .create_async()
            .await;

        let (td, cache) = cache_fixture();
        let (_home, auth) = kimi_code_home(&td, 600);
        let out = fetch_snapshot_at(
            &reqwest::Client::new(),
            &Auth::KimiCode(auth.clone()),
            &cache,
            &test_endpoints(&server.url()),
            Duration::ZERO,
            now(),
        )
        .await
        .unwrap();

        usages.assert_async().await;
        refresh.assert_async().await;
        assert_eq!(out.snapshot.weekly_used, 26);
        let stored = std::fs::read_to_string(&auth.credentials_path).unwrap();
        assert!(stored.contains("cli-rt"), "an unused token must not rotate");
    }

    #[tokio::test]
    async fn an_expiring_cli_token_is_refreshed_and_the_rotation_is_written_back() {
        let mut server = mockito::Server::new_async().await;
        let refresh = server
            .mock("POST", "/api/oauth/token")
            .match_body(mockito::Matcher::UrlEncoded(
                "refresh_token".into(),
                "cli-rt".into(),
            ))
            .with_status(200)
            .with_body(
                r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":900,
                    "scope":"kimi-code","token_type":"Bearer"}"#,
            )
            .create_async()
            .await;
        let usages = server
            .mock("GET", "/coding/v1/usages")
            .match_header("authorization", "Bearer fresh-at")
            .with_status(200)
            .with_body(sample_json())
            .create_async()
            .await;

        let (td, cache) = cache_fixture();
        // Inside the refresh buffer: still valid, but not for long enough.
        let (home, auth) = kimi_code_home(&td, 30);
        let out = fetch_snapshot_at(
            &reqwest::Client::new(),
            &Auth::KimiCode(auth.clone()),
            &cache,
            &test_endpoints(&server.url()),
            Duration::ZERO,
            now(),
        )
        .await
        .unwrap();

        refresh.assert_async().await;
        usages.assert_async().await;
        assert_eq!(out.snapshot.weekly_used, 26);

        let stored: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&auth.credentials_path).unwrap()).unwrap();
        assert_eq!(stored["access_token"], "fresh-at");
        assert_eq!(
            stored["refresh_token"], "fresh-rt",
            "the CLI's own store must carry the rotated token, or its next run is dead"
        );
        assert_eq!(stored["expires_at"], NOW_SECS + 900);
        // The lock is the CLI's own target, and it must not be left behind.
        assert!(!super::super::lock::lock_dir_for(&auth.lock_target).exists());
        assert!(home.join("oauth").is_dir());
    }

    #[tokio::test]
    async fn a_rejected_refresh_reports_a_credential_error_naming_the_cli() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("POST", "/api/oauth/token")
            .with_status(401)
            .with_body(r#"{"error":"invalid_grant"}"#)
            .create_async()
            .await;

        let (td, cache) = cache_fixture();
        let (_home, auth) = kimi_code_home(&td, -60);
        let err = fetch_snapshot_at(
            &reqwest::Client::new(),
            &Auth::KimiCode(auth),
            &cache,
            &test_endpoints(&server.url()),
            Duration::ZERO,
            now(),
        )
        .await
        .unwrap_err();
        let message = err.to_string();
        assert!(matches!(err, AppError::Credentials(_)), "{err:?}");
        assert!(message.contains("log in again"), "{message}");
    }

    #[tokio::test]
    async fn a_logged_out_cli_falls_back_to_cache_with_a_credential_warning() {
        let (td, cache) = cache_fixture();
        let (_home, auth) = kimi_code_home(&td, 600);
        std::fs::write(
            &auth.credentials_path,
            r#"{"access_token":"","refresh_token":"","expires_at":0}"#,
        )
        .unwrap();
        cache
            .write_payload(sample_seed().to_string().as_bytes())
            .unwrap();

        let out = fetch_snapshot_at(
            &reqwest::Client::new(),
            &Auth::KimiCode(auth),
            &cache,
            &test_endpoints("http://localhost:1"),
            Duration::ZERO,
            now(),
        )
        .await
        .unwrap();
        assert!(out.stale);
        assert_eq!(out.snapshot.weekly_used, 30);
        let (code, message) = out.last_error.unwrap();
        assert_eq!(code, 0);
        assert!(message.contains("logged out"), "{message}");
    }

    #[tokio::test]
    async fn a_peer_refresh_during_the_wait_is_picked_up_instead_of_rotating_again() {
        let mut server = mockito::Server::new_async().await;
        let refresh = server
            .mock("POST", "/api/oauth/token")
            .expect(0)
            .create_async()
            .await;
        let usages = server
            .mock("GET", "/coding/v1/usages")
            .match_header("authorization", "Bearer peer-at")
            .with_status(200)
            .with_body(sample_json())
            .create_async()
            .await;

        let (td, cache) = cache_fixture();
        let (_home, auth) = kimi_code_home(&td, -60);
        // Stand in for the CLI finishing its own refresh while we queued: the
        // re-read under the lock must win over the copy read before it.
        let peer = serde_json::json!({
            "access_token": "peer-at",
            "refresh_token": "peer-rt",
            "expires_at": NOW_SECS + 900,
            "expires_in": 900,
            "scope": "kimi-code",
            "token_type": "Bearer",
        });
        std::fs::write(&auth.credentials_path, peer.to_string()).unwrap();

        let out = fetch_snapshot_at(
            &reqwest::Client::new(),
            &Auth::KimiCode(auth),
            &cache,
            &test_endpoints(&server.url()),
            Duration::ZERO,
            now(),
        )
        .await
        .unwrap();
        refresh.assert_async().await;
        usages.assert_async().await;
        assert_eq!(out.snapshot.weekly_used, 26);
    }

    #[test]
    fn endpoints_follow_the_region() {
        let cn = Endpoints::for_region(Region::MainlandCn);
        assert_eq!(cn.usages, "https://api.kimi.com/coding/v1/usages");
        assert_eq!(cn.token, "https://auth.kimi.com/api/oauth/token");
        let global = Endpoints::for_region(Region::Global);
        assert_eq!(global.usages, "https://api.kimi.ai/coding/v1/usages");
        assert_eq!(global.token, "https://auth.kimi.ai/api/oauth/token");
        // The default stays the endpoint the API-key path has always used.
        assert_eq!(Endpoints::default().usages, cn.usages);
    }

    #[tokio::test]
    async fn the_vendors_own_tier_name_replaces_the_wire_enum() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(200)
            .with_body(sample_json())
            .create_async()
            .await;
        let me = server
            .mock("GET", "/coding/v1/me")
            .match_header("authorization", "Bearer sk-test")
            .with_status(200)
            .with_body(r#"{"user_id":"u-1","user_level":25,"user_level_name":"Allegretto"}"#)
            .create_async()
            .await;

        let (_td, cache) = cache_fixture();
        let out = fetch_snapshot(
            &reqwest::Client::new(),
            "sk-test",
            &cache,
            &test_endpoints(&server.url()),
            Duration::ZERO,
        )
        .await
        .unwrap();
        me.assert_async().await;
        assert_eq!(out.snapshot.plan, Some("Allegretto".into()));
        // …and it survives the cache round-trip, not just the live fetch.
        let cached: serde_json::Value =
            serde_json::from_slice(&std::fs::read(cache.payload_path()).unwrap()).unwrap();
        assert_eq!(cached["plan"], "Allegretto");
    }

    #[tokio::test]
    async fn a_profile_endpoint_that_fails_costs_the_label_and_nothing_else() {
        // 404 is documented by kimi-code's own error text for accounts with no
        // coding profile; the quota numbers must still come through.
        for status in [404, 401, 500] {
            let mut server = mockito::Server::new_async().await;
            server
                .mock("GET", "/coding/v1/usages")
                .with_status(200)
                .with_body(sample_json())
                .create_async()
                .await;
            server
                .mock("GET", "/coding/v1/me")
                .with_status(status)
                .with_body(r#"{"error":"nope"}"#)
                .create_async()
                .await;

            let (_td, cache) = cache_fixture();
            let out = fetch_snapshot(
                &reqwest::Client::new(),
                "sk-test",
                &cache,
                &test_endpoints(&server.url()),
                Duration::ZERO,
            )
            .await
            .unwrap();
            assert_eq!(out.snapshot.plan, Some("Intermediate".into()), "{status}");
            assert_eq!(out.snapshot.weekly_used, 26, "{status}");
            assert!(out.last_error.is_none(), "{status}: must not warn");
        }
    }

    #[tokio::test]
    async fn an_unreachable_profile_endpoint_does_not_fail_the_fetch() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", "/coding/v1/usages")
            .with_status(200)
            .with_body(sample_json())
            .create_async()
            .await;
        let mut endpoints = test_endpoints(&server.url());
        endpoints.me = "http://localhost:1/coding/v1/me".into();

        let (_td, cache) = cache_fixture();
        let out = fetch_snapshot(
            &reqwest::Client::new(),
            "sk-test",
            &cache,
            &endpoints,
            Duration::ZERO,
        )
        .await
        .unwrap();
        assert_eq!(out.snapshot.plan, Some("Intermediate".into()));
        assert!(!out.stale);
    }

    #[test]
    fn a_relocated_credential_file_keeps_the_homes_lock_target() {
        let home = Path::new("/home/u/.kimi-code");
        let auth =
            KimiCodeAuth::with_credentials_path(home, PathBuf::from("/elsewhere/kimi-code.json"));
        assert_eq!(
            auth.credentials_path,
            PathBuf::from("/elsewhere/kimi-code.json")
        );
        assert_eq!(auth.lock_target, oauth::lock_target_in(home));
    }
}