vct-core 2.4.1

Vibe Coding Tracker core library - parse local AI coding assistant session data into CodeAnalysis results
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
//! Codex `wham/usage` + reset-credit details client and token refresh.
//!
//! Reads the bearer token + account id from `~/.codex/auth.json`, calls the
//! ChatGPT backend usage endpoint, and maps the response into the normalized
//! [`CodexQuotaSnapshot`]. On a 401 the caller refreshes the token via
//! [`refresh_codex`] (which rotates and writes back the refresh token) and
//! retries. Tokens are never logged nor stored in a `Debug`-formatted struct;
//! only the HTTP status appears in errors.

use crate::models::{
    CodexAuthJson, CodexQuotaSnapshot, CodexRefreshResponse, QuotaSource, QuotaWindow,
    WhamResetCreditsDetails, WhamUsageResponse, WhamWindow,
};
use crate::quota::refresh::{file_mtime, send_refresh, update_json_file_in_place};
use crate::utils::now_rfc3339_utc_nanos;
use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use std::path::Path;
use std::sync::OnceLock;

/// The ChatGPT backend usage endpoint (production default; injectable in tests).
pub(crate) const WHAM_URL: &str = "https://chatgpt.com/backend-api/wham/usage";
/// The earned reset-credit details endpoint (production default; injectable in tests).
pub(crate) const WHAM_RESET_CREDITS_URL: &str =
    "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
/// The Codex OAuth token endpoint (production default; injectable in tests).
pub(crate) const CODEX_TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
/// The Codex OAuth client id (public PKCE client).
const CODEX_CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
/// Fallback Codex CLI version for the User-Agent when `codex --version` cannot be
/// resolved. Bump occasionally.
const CODEX_FALLBACK_VERSION: &str = "0.142.5";
/// Codex CLI originator (headless invocation; the TUI reports `codex-tui`). Sent
/// only for client-identity parity; the ChatGPT usage endpoint does not need it.
const CODEX_ORIGINATOR: &str = "codex_cli_rs";

/// Builds the Codex CLI request User-Agent, e.g. `codex_cli_rs/0.142.5 (linux; x86_64)`.
///
/// The version is detected from the installed CLI (see
/// [`crate::quota::http::detect_cli_version`]); os/arch come from the build target.
fn codex_ua() -> &'static str {
    static UA: OnceLock<String> = OnceLock::new();
    UA.get_or_init(|| {
        format!(
            "codex_cli_rs/{} ({}; {})",
            crate::quota::http::detect_cli_version(
                "codex",
                "codex_version.json",
                CODEX_FALLBACK_VERSION
            ),
            std::env::consts::OS,
            std::env::consts::ARCH,
        )
    })
    .as_str()
}

/// Builds an authenticated Codex backend GET request with the CLI identity.
fn codex_get(
    client: &reqwest::blocking::Client,
    url: &str,
    token: &str,
    account_id: Option<&str>,
) -> reqwest::blocking::RequestBuilder {
    let req = client
        .get(url)
        .header(reqwest::header::USER_AGENT, codex_ua())
        .header("originator", CODEX_ORIGINATOR)
        .bearer_auth(token);
    match account_id {
        Some(id) => req.header("ChatGPT-Account-Id", id),
        None => req,
    }
}

/// Maps a wham/usage window into the normalized [`QuotaWindow`].
fn map_window(w: &WhamWindow, now: i64) -> QuotaWindow {
    let resets_at_unix = w
        .reset_at
        .or_else(|| w.reset_after_seconds.map(|s| now + s));
    QuotaWindow {
        used_percent: w.used_percent.unwrap_or(0.0),
        resets_at_unix,
    }
}

/// Maps a wham/usage response body into a [`CodexQuotaSnapshot`] (pure).
///
/// # Errors
///
/// Returns an error if the body is not valid JSON in the expected shape.
pub fn map_wham_response(body: &str, now: i64) -> Result<CodexQuotaSnapshot> {
    let resp: WhamUsageResponse =
        serde_json::from_str(body).context("Failed to parse wham/usage response")?;

    let (primary, secondary, rate_reached) = match &resp.rate_limit {
        Some(rl) => (
            rl.primary_window.as_ref().map(|w| map_window(w, now)),
            rl.secondary_window.as_ref().map(|w| map_window(w, now)),
            rl.limit_reached,
        ),
        None => (None, None, None),
    };

    let (credits_balance, has_credits, unlimited, overage, approx_messages) = match &resp.credits {
        Some(c) => (
            c.balance.clone(),
            c.has_credits,
            c.unlimited,
            c.overage_limit_reached,
            approx_pair(&c.approx_local_messages),
        ),
        None => (None, None, None, None, None),
    };

    let (spend_reached, spend_limit) = match &resp.spend_control {
        Some(s) => (s.reached, s.individual_limit),
        None => (None, None),
    };

    // A limit is "reached" if the rate window, the credit overage, or the spend
    // cap says so. Stay `None` only when no source reports at all.
    let reached = [rate_reached, overage, spend_reached];
    let limit_reached = reached
        .iter()
        .any(Option::is_some)
        .then(|| reached.contains(&Some(true)));

    Ok(CodexQuotaSnapshot {
        source: QuotaSource::Api,
        fetched_at: now,
        plan_type: resp.plan_type,
        primary,
        secondary,
        credits_balance,
        has_credits,
        unlimited,
        reset_credits_available: resp
            .rate_limit_reset_credits
            .and_then(|r| r.available_count),
        reset_credit_expirations: None,
        approx_messages,
        spend_limit,
        limit_reached,
        needs_login: false,
    })
}

/// Maps reset-credit details into the authoritative count plus sorted expiry
/// times for credits whose status is `available`.
///
/// The expiry list may be shorter than the count because the backend can cap
/// detail rows. `None` entries sort last and mean the credit never expires.
///
/// # Errors
///
/// Returns an error when the response shape or an available credit's RFC3339
/// expiry is malformed.
pub fn map_reset_credits_response(body: &str) -> Result<(i64, Vec<Option<i64>>)> {
    let resp: WhamResetCreditsDetails = serde_json::from_str(body)
        .context("Failed to parse wham/rate-limit-reset-credits response")?;
    let available_count = resp.available_count.max(0);

    let mut expirations = Vec::new();
    for credit in resp.credits.into_iter().filter(|c| c.status == "available") {
        let expires_at = credit
            .expires_at
            .as_deref()
            .map(|timestamp| {
                chrono::DateTime::parse_from_rfc3339(timestamp)
                    .with_context(|| format!("invalid expires_at for reset credit `{}`", credit.id))
                    .map(|parsed| parsed.timestamp())
            })
            .transpose()?;
        expirations.push(expires_at);
    }
    expirations.sort_by_key(|expires_at| expires_at.unwrap_or(i64::MAX));

    Ok((available_count, expirations))
}

/// Extracts an `[low, high]` approximate-messages pair, dropping the all-zero
/// case (no credits → nothing useful to show).
fn approx_pair(v: &Option<Vec<i64>>) -> Option<(i64, i64)> {
    let v = v.as_ref()?;
    let low = *v.first()?;
    let high = *v.get(1).unwrap_or(&low);
    (high > 0).then_some((low, high))
}

/// Parses `~/.codex/auth.json`, returning `(access_token, account_id)` (pure).
///
/// # Errors
///
/// Returns an error if the JSON is malformed or has no `tokens.access_token`.
pub fn parse_auth(body: &str) -> Result<(String, Option<String>)> {
    let auth: CodexAuthJson = serde_json::from_str(body).context("Failed to parse auth.json")?;
    let tokens = auth.tokens.context("auth.json has no tokens")?;
    let access_token = tokens
        .access_token
        .filter(|t| !t.is_empty())
        .context("auth.json has no tokens.access_token")?;
    Ok((access_token, tokens.account_id))
}

/// Outcome of a single wham/usage request.
pub enum WhamResult {
    /// Mapped snapshot.
    Ok(CodexQuotaSnapshot),
    /// 401 → refresh and retry.
    Unauthorized,
    /// Network / non-401 error → keep last-known-good.
    Transient,
}

/// Outcome of the optional reset-credit details request.
pub enum ResetCreditsResult {
    /// Authoritative count plus sorted available-credit expirations.
    Ok {
        available_count: i64,
        expirations: Vec<Option<i64>>,
    },
    /// 401: the caller may refresh the token and retry once.
    Unauthorized,
    /// Network, parse, or other HTTP error: keep the usage summary.
    Transient,
}

/// Calls the wham endpoint at `wham_url` with an explicit bearer token.
pub fn call_wham(
    client: &reqwest::blocking::Client,
    token: &str,
    account_id: Option<&str>,
    now: i64,
    wham_url: &str,
) -> WhamResult {
    let resp = match codex_get(client, wham_url, token, account_id).send() {
        Ok(r) => r,
        Err(e) => {
            log::warn!("codex quota fetch: request failed: {e}");
            return WhamResult::Transient;
        }
    };
    let status = resp.status();
    if status == reqwest::StatusCode::UNAUTHORIZED {
        return WhamResult::Unauthorized;
    }
    if !status.is_success() {
        log::warn!("codex quota fetch: HTTP {status}");
        return WhamResult::Transient;
    }
    match resp.text() {
        Ok(text) => match map_wham_response(&text, now) {
            Ok(snap) => WhamResult::Ok(snap),
            Err(e) => {
                log::warn!("codex quota fetch: failed to parse usage response: {e}");
                WhamResult::Transient
            }
        },
        Err(e) => {
            log::warn!("codex quota fetch: failed to read response body: {e}");
            WhamResult::Transient
        }
    }
}

/// Calls `wham/usage`, then enriches a successful snapshot with earned reset
/// credit details. The details request is best-effort: any HTTP or parse error
/// preserves the count returned by `wham/usage` and does not fail the panel.
pub fn call_wham_with_reset_credits(
    client: &reqwest::blocking::Client,
    token: &str,
    account_id: Option<&str>,
    now: i64,
    wham_url: &str,
    reset_credits_url: &str,
) -> WhamResult {
    let mut snap = match call_wham(client, token, account_id, now, wham_url) {
        WhamResult::Ok(snap) => snap,
        WhamResult::Unauthorized => return WhamResult::Unauthorized,
        WhamResult::Transient => return WhamResult::Transient,
    };

    match call_reset_credit_details(client, token, account_id, reset_credits_url) {
        ResetCreditsResult::Ok {
            available_count,
            expirations,
        } => {
            snap.reset_credits_available = Some(available_count);
            snap.reset_credit_expirations = Some(expirations);
        }
        ResetCreditsResult::Unauthorized | ResetCreditsResult::Transient => {}
    }

    WhamResult::Ok(snap)
}

/// Calls and maps the earned reset-credit details endpoint.
pub fn call_reset_credit_details(
    client: &reqwest::blocking::Client,
    token: &str,
    account_id: Option<&str>,
    reset_credits_url: &str,
) -> ResetCreditsResult {
    let resp = match codex_get(client, reset_credits_url, token, account_id).send() {
        Ok(resp) => resp,
        Err(e) => {
            log::warn!("codex reset-credit details fetch: request failed: {e}");
            return ResetCreditsResult::Transient;
        }
    };
    let status = resp.status();
    if status == reqwest::StatusCode::UNAUTHORIZED {
        return ResetCreditsResult::Unauthorized;
    }
    if !status.is_success() {
        log::warn!("codex reset-credit details fetch: HTTP {status}");
        return ResetCreditsResult::Transient;
    }
    let text = match resp.text() {
        Ok(text) => text,
        Err(e) => {
            log::warn!("codex reset-credit details fetch: failed to read response body: {e}");
            return ResetCreditsResult::Transient;
        }
    };
    match map_reset_credits_response(&text) {
        Ok((available_count, expirations)) => ResetCreditsResult::Ok {
            available_count,
            expirations,
        },
        Err(e) => {
            log::warn!("codex reset-credit details fetch: failed to parse response: {e}");
            ResetCreditsResult::Transient
        }
    }
}

/// Fetches the raw `wham/usage` response for `vct fetch codex`.
///
/// Uses the stored access token verbatim (no refresh, no file writes) and
/// returns `(status_code, body)`. A non-2xx status is left for the caller to
/// surface.
///
/// # Errors
///
/// Returns an error if `auth.json` is missing, has no access token, or the
/// request cannot be sent.
pub fn fetch_codex_raw(client: &reqwest::blocking::Client) -> Result<(u16, String)> {
    let auth_path = crate::utils::resolve_paths()?.codex_dir.join("auth.json");
    fetch_codex_raw_from(client, WHAM_URL, &auth_path)
}

/// The injectable core of [`fetch_codex_raw`]: reads the token from an explicit
/// `auth.json` path and fetches the raw usage body from an explicit `wham_url`.
/// Production passes [`WHAM_URL`] + `~/.codex/auth.json`; tests point them at a
/// local mock server and a temp auth file.
pub(crate) fn fetch_codex_raw_from(
    client: &reqwest::blocking::Client,
    wham_url: &str,
    auth_path: &Path,
) -> Result<(u16, String)> {
    let body = std::fs::read_to_string(auth_path).with_context(|| {
        format!(
            "no Codex credentials at {} ({})",
            auth_path.display(),
            crate::quota::CODEX_LOGIN_HINT
        )
    })?;
    let (access_token, account_id) = parse_auth(&body)?;
    let resp = codex_get(client, wham_url, &access_token, account_id.as_deref())
        .send()
        .context("Failed to send Codex usage request")?;
    let status = resp.status().as_u16();
    let text = resp
        .text()
        .context("Failed to read Codex usage response body")?;
    Ok((status, text))
}

/// Refreshes the Codex token and writes it back (rotation-safe). Returns the new
/// access token.
///
/// The refresh token rotates: the response's new refresh token must be persisted
/// or the next refresh reuses the old one and 401s. The write-back re-checks the
/// file mtime and aborts if a concurrent Codex CLI rotated it first.
///
/// # Errors
///
/// Returns an error if the auth file has no refresh token, the request fails, or
/// the status is non-success. The token never appears in an error.
pub fn refresh_codex(
    client: &reqwest::blocking::Client,
    auth_path: &Path,
    token_url: &str,
) -> Result<String> {
    // Capture the mtime with the refresh token from the same read so the
    // write-back guards on the exact file version we send.
    let expected_mtime = file_mtime(auth_path);
    let body = std::fs::read_to_string(auth_path)
        .with_context(|| format!("Failed to read {}", auth_path.display()))?;
    let root: Value = serde_json::from_str(&body).context("Failed to parse auth.json")?;
    let refresh_token = root["tokens"]["refresh_token"]
        .as_str()
        .filter(|s| !s.is_empty())
        .context("auth.json has no tokens.refresh_token")?
        .to_string();

    let req_body = json!({
        "client_id": CODEX_CLIENT_ID,
        "grant_type": "refresh_token",
        "refresh_token": refresh_token,
    });
    let req = client
        .post(token_url)
        .header(reqwest::header::USER_AGENT, codex_ua())
        .header(reqwest::header::CONTENT_TYPE, "application/json")
        .json(&req_body);
    let (status, text) = send_refresh(req)?;
    if !status.is_success() {
        bail!("codex token refresh returned status {status}");
    }
    let parsed: CodexRefreshResponse =
        serde_json::from_str(&text).context("Failed to parse Codex refresh response")?;
    let access = parsed
        .access_token
        .clone()
        .filter(|s| !s.is_empty())
        .context("codex refresh response had no access_token")?;

    let wrote = update_json_file_in_place(auth_path, expected_mtime, |root| {
        let t = root
            .get_mut("tokens")
            .and_then(|v| v.as_object_mut())
            .context("auth.json missing tokens object")?;
        t.insert("access_token".into(), json!(access));
        if let Some(i) = &parsed.id_token
            && !i.is_empty()
        {
            t.insert("id_token".into(), json!(i));
        }
        if let Some(r) = &parsed.refresh_token
            && !r.is_empty()
        {
            t.insert("refresh_token".into(), json!(r));
        }
        root["last_refresh"] = json!(now_rfc3339_utc_nanos());
        Ok(())
    })?;
    // The refresh already rotated the refresh token server-side; if we could not
    // persist the new one, auth.json now holds a stale/invalid refresh token, so
    // treat it as a refresh failure rather than reporting success.
    if !wrote {
        bail!("codex token rotated but the new token could not be persisted");
    }
    Ok(access)
}

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

    const RESET_CREDITS_SAMPLE: &str = include_str!(
        "../../../../tests/fixtures/quota/wham_rate_limit_reset_credits_response.json"
    );
    const SAMPLE: &str = r#"{
      "plan_type": "plus",
      "rate_limit": {
        "allowed": true, "limit_reached": false,
        "primary_window":   { "used_percent": 27, "limit_window_seconds": 18000,  "reset_after_seconds": 16816, "reset_at": 1782770922 },
        "secondary_window": { "used_percent": 4,  "limit_window_seconds": 604800, "reset_after_seconds": 603616, "reset_at": 1783357722 }
      },
      "credits": { "has_credits": false, "unlimited": false, "balance": "0" },
      "rate_limit_reset_credits": { "available_count": 2 }
    }"#;

    #[test]
    fn maps_full_response() {
        let snap = map_wham_response(SAMPLE, 1_000_000).unwrap();
        assert_eq!(snap.source, QuotaSource::Api);
        assert_eq!(snap.plan_type.as_deref(), Some("plus"));
        assert_eq!(snap.primary.as_ref().unwrap().used_percent, 27.0);
        assert_eq!(
            snap.primary.as_ref().unwrap().resets_at_unix,
            Some(1782770922)
        );
        assert_eq!(snap.secondary.as_ref().unwrap().used_percent, 4.0);
        assert_eq!(snap.credits_balance.as_deref(), Some("0"));
        assert_eq!(snap.has_credits, Some(false));
        assert_eq!(snap.reset_credits_available, Some(2));
        assert!(snap.reset_credit_expirations.is_none());
        assert_eq!(snap.limit_reached, Some(false));
        assert!(!snap.needs_login);
    }

    #[test]
    fn maps_available_reset_credit_expirations_in_order() {
        let (count, expirations) = map_reset_credits_response(RESET_CREDITS_SAMPLE).unwrap();

        assert_eq!(count, 5, "top-level count stays authoritative");
        assert_eq!(expirations.len(), 3, "redeemed credit is excluded");
        assert!(expirations[0].unwrap() < expirations[1].unwrap());
        assert_eq!(expirations[2], None, "non-expiring credit sorts last");
    }

    #[test]
    fn rejects_malformed_available_credit_expiry() {
        let body = r#"{
          "credits": [{
            "id": "credit-1", "reset_type": "codex_rate_limits",
            "status": "available", "granted_at": "2026-07-01T00:00:00Z",
            "expires_at": "not-a-timestamp"
          }],
          "available_count": 1
        }"#;

        assert!(map_reset_credits_response(body).is_err());
    }

    #[test]
    fn accepts_numeric_credit_balance() {
        let body = r#"{"plan_type":"plus","credits":{"has_credits":true,"balance":12}}"#;
        let snap = map_wham_response(body, 1_000).unwrap();
        assert_eq!(snap.credits_balance.as_deref(), Some("12"));
        assert_eq!(snap.has_credits, Some(true));
    }

    #[test]
    fn window_uses_relative_reset_when_no_absolute() {
        let body =
            r#"{"rate_limit":{"primary_window":{"used_percent":10,"reset_after_seconds":100}}}"#;
        let snap = map_wham_response(body, 1_000).unwrap();
        assert_eq!(snap.primary.unwrap().resets_at_unix, Some(1_100));
    }

    #[test]
    fn parse_auth_extracts_token_and_account() {
        let body = r#"{"tokens":{"access_token":"tok","account_id":"acct"}}"#;
        let (tok, acct) = parse_auth(body).unwrap();
        assert_eq!(tok, "tok");
        assert_eq!(acct.as_deref(), Some("acct"));
    }

    #[test]
    fn parse_auth_errors_without_token() {
        assert!(parse_auth(r#"{"tokens":{"account_id":"acct"}}"#).is_err());
        assert!(parse_auth(r#"{}"#).is_err());
    }

    #[test]
    fn maps_spend_control_and_approx_messages() {
        let body = r#"{
          "plan_type": "plus",
          "credits": { "balance": "12", "has_credits": true, "overage_limit_reached": false,
                       "approx_local_messages": [120, 150], "approx_cloud_messages": [0, 0] },
          "spend_control": { "reached": false, "individual_limit": 50.0 }
        }"#;
        let snap = map_wham_response(body, 1_000).unwrap();
        assert_eq!(snap.approx_messages, Some((120, 150)));
        assert_eq!(snap.spend_limit, Some(50.0));
        assert_eq!(snap.limit_reached, Some(false));
    }

    #[test]
    fn overage_or_spend_trips_limit_reached() {
        let body = r#"{
          "rate_limit": { "limit_reached": false, "primary_window": { "used_percent": 10 } },
          "credits": { "overage_limit_reached": true },
          "spend_control": { "reached": false }
        }"#;
        let snap = map_wham_response(body, 1).unwrap();
        assert_eq!(snap.limit_reached, Some(true));
    }

    #[test]
    fn zero_approx_messages_are_dropped() {
        let body = r#"{ "credits": { "approx_local_messages": [0, 0] } }"#;
        let snap = map_wham_response(body, 1).unwrap();
        assert!(snap.approx_messages.is_none());
    }

    #[test]
    fn limit_reached_is_none_when_unreported() {
        // No rate_limit / credits / spend_control at all → stays None.
        let snap = map_wham_response(r#"{"plan_type":"plus"}"#, 1).unwrap();
        assert_eq!(snap.limit_reached, None);
    }

    /// Version probing is off outside the binary, so the User-Agent is built
    /// from the fallback and is stable enough to assert on.
    #[test]
    fn codex_ua_uses_the_fallback_version_under_test() {
        assert_eq!(
            codex_ua(),
            format!(
                "codex_cli_rs/{CODEX_FALLBACK_VERSION} ({}; {})",
                std::env::consts::OS,
                std::env::consts::ARCH
            )
        );
    }

    // ---- HTTP-layer test against a local mock server (no real API) ----

    #[test]
    fn fetch_codex_raw_from_reads_auth_and_returns_status_body() {
        use crate::quota::http::build_client;
        use httpmock::prelude::*;

        let server = MockServer::start();
        server.mock(|when, then| {
            when.method(GET).path("/wham");
            then.status(200).body(SAMPLE);
        });
        let dir = tempfile::tempdir().unwrap();
        let auth = dir.path().join("auth.json");
        std::fs::write(
            &auth,
            r#"{"tokens":{"access_token":"tok","account_id":"acct"}}"#,
        )
        .unwrap();

        let client = build_client().unwrap();
        let (status, body) =
            fetch_codex_raw_from(&client, &server.url("/wham"), &auth).expect("raw fetch");
        assert_eq!(status, 200);
        assert!(body.contains("plan_type"));
    }
}