Skip to main content

ai_usagebar/grokbot/
fetch.rs

1//! Fetch Grok Bot usage from
2//! `aiserver.v1.DashboardService/GetSandUsageStatus` (Connect-RPC), with the
3//! desktop app's own OAuth session (`creds.rs`). The session's access token
4//! has no locally recorded expiry, so the flow is: try it, and on a 401/403
5//! refresh through Cursor's public OAuth client, persist the rotated pair in
6//! ai-usagebar's vendor cache (`oauth.json`, scoped by a fingerprint of the
7//! refresh token, mode 0600 — never back to the app's file), and retry once.
8//! Cache/stale/error-fallback shape mirrors `kiro::fetch`.
9
10use std::time::Duration;
11
12use chrono::{DateTime, Utc};
13use serde::{Deserialize, Serialize};
14
15use crate::cache::{Cache, acquire_lock_async, atomic_write};
16use crate::error::{AppError, Result};
17use crate::usage::GrokbotSnapshot;
18use crate::vendor::{MAX_BODY_BYTES, read_body_capped};
19
20use super::creds::GrokbotCredentials;
21use super::types::SandUsageStatus;
22
23const HTTP_TIMEOUT: Duration = Duration::from_secs(10);
24const REFRESH_TIMEOUT: Duration = Duration::from_secs(15);
25const LOCK_TIMEOUT: Duration = Duration::from_secs(15);
26const OAUTH_CACHE_FILE: &str = "oauth.json";
27
28/// The public OAuth client id the Cursor CLI itself uses for its installed-app
29/// flow — public by definition (it ships in the CLI), embedded here for the
30/// same reason the Kimi Code CLI's is.
31pub const CLIENT_ID: &str = "KbZUR41cY7W6zRSdpSUJ7I7mLYBKOCmB";
32
33#[derive(Debug, Clone)]
34pub struct Endpoints {
35    /// `GetSandUsageStatus`.
36    pub usage: String,
37    /// OAuth token endpoint for the refresh grant.
38    pub token: String,
39}
40
41impl Default for Endpoints {
42    fn default() -> Self {
43        Self {
44            usage: "https://api2.cursor.sh/aiserver.v1.DashboardService/GetSandUsageStatus".into(),
45            token: "https://api2.cursor.sh/oauth/token".into(),
46        }
47    }
48}
49
50/// This vendor's [`Outcome`](crate::outcome::Outcome) — the shared shape,
51/// specialised to its snapshot.
52pub type FetchOutcome = crate::outcome::Outcome<GrokbotSnapshot>;
53
54/// The rotated token pair, persisted in the vendor cache. Keyed by a
55/// fingerprint of the refresh token, so a re-login in the app (which rewrites
56/// `sand-secrets.json` with a new pair) never inherits the old session's
57/// cached tokens — the kiro/minimax treatment.
58#[derive(Debug, Clone, Deserialize, Serialize)]
59struct PersistedOAuth {
60    fingerprint: String,
61    access_token: String,
62    refresh_token: String,
63}
64
65/// Production entry: resolve the desktop app's session, then fetch.
66pub async fn fetch_snapshot(
67    client: &reqwest::Client,
68    cfg: &crate::config::GrokbotConfig,
69    cache: &Cache,
70    cache_ttl: Duration,
71) -> Result<FetchOutcome> {
72    let creds = super::resolve_credentials(cfg)?;
73    fetch_snapshot_with(client, &creds, cache, &Endpoints::default(), cache_ttl).await
74}
75
76/// Fetch with the credential and endpoints resolved by the caller.
77pub async fn fetch_snapshot_with(
78    client: &reqwest::Client,
79    creds: &GrokbotCredentials,
80    cache: &Cache,
81    endpoints: &Endpoints,
82    cache_ttl: Duration,
83) -> Result<FetchOutcome> {
84    cache.ensure_dir()?;
85    let _lock = acquire_lock_async(&cache.lock_path(), LOCK_TIMEOUT).await?;
86
87    // The cache is scoped to the sign-in: a re-login in the app must not keep
88    // serving the previous session's payload.
89    if let Some(bytes) = cache.fresh_payload(cache_ttl)?
90        && let Ok(outcome) = reuse_cache(&bytes, cache, false, &creds.fingerprint)
91    {
92        return Ok(outcome);
93    }
94
95    match fetch_live(client, endpoints, cache, creds).await {
96        Ok(snap) => {
97            let bytes = serde_json::to_vec(&snap_to_json(&snap, &creds.fingerprint))?;
98            cache.write_payload(&bytes)?;
99            Ok(crate::outcome::Outcome::fresh(snap))
100        }
101        Err(e) if e.is_transient() => fallback_silent(cache, &creds.fingerprint, e),
102        Err(e) => {
103            cache.mark_stale();
104            if let Some((code, msg)) = error_to_pair(&e) {
105                cache.write_last_error(code, &msg);
106            }
107            fallback_with_error(cache, &creds.fingerprint, e)
108        }
109    }
110}
111
112fn fallback_silent(cache: &Cache, fingerprint: &str, original: AppError) -> Result<FetchOutcome> {
113    crate::outcome::fallback(cache, None, original, |bytes| {
114        parse_cache_at(bytes, fingerprint)
115    })
116}
117
118fn fallback_with_error(
119    cache: &Cache,
120    fingerprint: &str,
121    original: AppError,
122) -> Result<FetchOutcome> {
123    let last_error = error_to_pair(&original);
124    crate::outcome::fallback(cache, last_error, original, |bytes| {
125        parse_cache_at(bytes, fingerprint)
126    })
127}
128
129/// Never surface upstream bodies for auth failures: a 401/403 from a
130/// Bearer-token endpoint is not guaranteed not to echo something
131/// account-identifying back. Mirrors `kiro::fetch::error_to_pair`.
132fn error_to_pair(e: &AppError) -> Option<(u16, String)> {
133    match e {
134        AppError::Http { status, .. } if matches!(status, 401 | 403) => {
135            Some((*status, "Grok Bot authentication failed".into()))
136        }
137        AppError::Http { status, body } => Some((*status, body.clone())),
138        AppError::Credentials(msg) => Some((0, msg.clone())),
139        e => Some((0, e.to_string())),
140    }
141}
142
143fn reuse_cache(
144    bytes: &[u8],
145    cache: &Cache,
146    stale: bool,
147    fingerprint: &str,
148) -> Result<FetchOutcome> {
149    let snap = parse_cache_at(bytes, fingerprint)?;
150    Ok(crate::outcome::Outcome::cached(snap, cache, stale))
151}
152
153fn parse_cache_at(bytes: &[u8], fingerprint: &str) -> Result<GrokbotSnapshot> {
154    let v: serde_json::Value = serde_json::from_slice(bytes)?;
155    if v.get("account").and_then(serde_json::Value::as_str) != Some(fingerprint) {
156        return Err(AppError::Schema(
157            "grokbot cache belongs to a different sign-in; refetching".into(),
158        ));
159    }
160    let invalid = |field: &str| AppError::Schema(format!("grokbot cache: invalid {field}"));
161    let plan = v["plan"]
162        .as_str()
163        .filter(|plan| !plan.trim().is_empty())
164        .ok_or_else(|| invalid("plan"))?
165        .to_string();
166    let has_included_allowance = v["has_included_allowance"]
167        .as_bool()
168        .ok_or_else(|| invalid("has_included_allowance"))?;
169    let weekly_pct = v["weekly_pct"]
170        .as_i64()
171        .filter(|pct| (0..=100).contains(pct))
172        .ok_or_else(|| invalid("weekly_pct"))? as i32;
173    let period_start = parse_cache_datetime(&v["period_start"])?;
174    let reset_at = parse_cache_datetime(&v["reset_at"])?;
175    let window = match (period_start, reset_at) {
176        (Some(start), Some(reset)) if reset > start => Some(reset - start),
177        _ => None,
178    };
179    Ok(GrokbotSnapshot {
180        plan,
181        // Absent in caches written before the field existed.
182        billed_by: v["billed_by"]
183            .as_str()
184            .map(str::trim)
185            .filter(|name| !name.is_empty() && name.chars().count() <= 64)
186            .map(str::to_string),
187        has_included_allowance,
188        weekly_pct,
189        has_available_usage: v["has_available_usage"].as_bool().unwrap_or(false),
190        on_demand_enabled: v["on_demand_enabled"].as_bool().unwrap_or(false),
191        period_start,
192        reset_at,
193        window,
194    })
195}
196
197fn parse_cache_datetime(v: &serde_json::Value) -> Result<Option<DateTime<Utc>>> {
198    match v {
199        serde_json::Value::Null => Ok(None),
200        serde_json::Value::String(s) => DateTime::parse_from_rfc3339(s)
201            .map(|dt| Some(dt.with_timezone(&Utc)))
202            .map_err(|e| AppError::Schema(format!("grokbot cache: invalid timestamp: {e}"))),
203        _ => Err(AppError::Schema("grokbot cache: invalid timestamp".into())),
204    }
205}
206
207fn snap_to_json(snap: &GrokbotSnapshot, fingerprint: &str) -> serde_json::Value {
208    serde_json::json!({
209        "account": fingerprint,
210        "plan": snap.plan,
211        "billed_by": snap.billed_by,
212        "has_included_allowance": snap.has_included_allowance,
213        "weekly_pct": snap.weekly_pct,
214        "has_available_usage": snap.has_available_usage,
215        "on_demand_enabled": snap.on_demand_enabled,
216        "period_start": snap.period_start.map(|dt| dt.to_rfc3339()),
217        "reset_at": snap.reset_at.map(|dt| dt.to_rfc3339()),
218    })
219}
220
221fn oauth_cache_path(cache: &Cache) -> std::path::PathBuf {
222    cache.dir().join(OAUTH_CACHE_FILE)
223}
224
225fn read_persisted_oauth(cache: &Cache, fingerprint: &str) -> Result<Option<PersistedOAuth>> {
226    let path = oauth_cache_path(cache);
227    let bytes = match std::fs::read(&path) {
228        Ok(bytes) => bytes,
229        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
230        Err(e) => return Err(AppError::io_at(&path, e)),
231    };
232    let persisted: PersistedOAuth = serde_json::from_slice(&bytes).map_err(|e| {
233        AppError::Credentials(format!(
234            "ai-usagebar's cached Grok Bot credentials at {} are malformed ({e}); remove that file and try again",
235            crate::display::sanitize_untrusted_path(&path)
236        ))
237    })?;
238    // The app re-signed-in since this was persisted: a different refresh
239    // token means a different session, and the cached pair belongs to it.
240    if persisted.fingerprint != fingerprint {
241        return Ok(None);
242    }
243    if persisted.access_token.trim().is_empty() || persisted.refresh_token.trim().is_empty() {
244        return Err(AppError::Credentials(format!(
245            "ai-usagebar's cached Grok Bot credentials at {} are incomplete; remove that file and try again",
246            crate::display::sanitize_untrusted_path(&path)
247        )));
248    }
249    Ok(Some(persisted))
250}
251
252fn write_persisted_oauth(cache: &Cache, persisted: &PersistedOAuth) -> Result<()> {
253    let path = oauth_cache_path(cache);
254    let bytes = serde_json::to_vec_pretty(persisted)?;
255    atomic_write(&path, &bytes)?;
256    #[cfg(unix)]
257    {
258        use std::os::unix::fs::PermissionsExt;
259        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
260            .map_err(|e| AppError::io_at(&path, e))?;
261    }
262    Ok(())
263}
264
265async fn fetch_live(
266    client: &reqwest::Client,
267    endpoints: &Endpoints,
268    cache: &Cache,
269    creds: &GrokbotCredentials,
270) -> Result<GrokbotSnapshot> {
271    // A previously rotated pair wins over the app's file when it belongs to
272    // the same sign-in: the app does not rewrite its own file on refresh, so
273    // its access token is the older one.
274    let (access_token, refresh_token) = match read_persisted_oauth(cache, &creds.fingerprint)? {
275        Some(persisted) => (persisted.access_token, persisted.refresh_token),
276        None => (creds.access_token.clone(), creds.refresh_token.clone()),
277    };
278
279    let resp = usage_call(client, endpoints, &access_token).await?;
280    let status = resp.status();
281    if matches!(status.as_u16(), 401 | 403) {
282        // The access token died (no local expiry records when). Refresh with
283        // the paired refresh token and retry exactly once.
284        let refreshed = refresh(client, &endpoints.token, &refresh_token).await?;
285        let persisted = PersistedOAuth {
286            fingerprint: super::creds::fingerprint_of(&refreshed.refresh_token),
287            access_token: refreshed.access_token,
288            refresh_token: refreshed.refresh_token,
289        };
290        write_persisted_oauth(cache, &persisted).map_err(|e| {
291            AppError::Credentials(format!(
292                "the refreshed Grok Bot credentials could not be saved ({e}); sign in to the Grok Bot desktop app again if the refresh token was rotated"
293            ))
294        })?;
295        let retry = usage_call(client, endpoints, &persisted.access_token).await?;
296        return parse_usage_response(retry).await;
297    }
298    parse_usage_response(resp).await
299}
300
301/// One `GetSandUsageStatus` call: Connect-RPC with the app's client headers.
302///
303/// `x-cursor-checksum` is deliberately **not** sent: it is Cursor's machine
304/// checksum, which we cannot reproduce. Residual risk: the server could start
305/// requiring it, which would surface as a 4xx and the cached payload (or its
306/// absence) is the honest answer — flagged for the reporter's live test
307/// (#206).
308async fn usage_call(
309    client: &reqwest::Client,
310    endpoints: &Endpoints,
311    access_token: &str,
312) -> Result<reqwest::Response> {
313    tokio::time::timeout(
314        HTTP_TIMEOUT,
315        client
316            .post(&endpoints.usage)
317            .header("Content-Type", "application/json")
318            .header("Authorization", format!("Bearer {access_token}"))
319            .header("Connect-Protocol-Version", "1")
320            .header("x-cursor-client-type", "sand")
321            .header("x-cursor-client-version", "0.1.0")
322            .header("x-sand-box-namespace", "prod")
323            .header("x-ghost-mode", "true")
324            .header("x-request-id", request_id())
325            .body("{}")
326            .send(),
327    )
328    .await
329    .map_err(|_| AppError::Transport(format!("grokbot timeout: {}", endpoints.usage)))?
330    .map_err(|e| AppError::Transport(format!("grokbot transport: {e}")))
331}
332
333async fn parse_usage_response(resp: reqwest::Response) -> Result<GrokbotSnapshot> {
334    let status = resp.status();
335    if !status.is_success() {
336        // Never surface upstream/proxy bodies: they can contain credentials
337        // or arbitrary markup. The cache records the redacted form centrally.
338        let body = if matches!(status.as_u16(), 401 | 403) {
339            "Grok Bot authentication failed".into()
340        } else {
341            format!("Grok Bot API returned HTTP {}", status.as_u16())
342        };
343        return Err(AppError::Http {
344            status: status.as_u16(),
345            body,
346        });
347    }
348    let bytes = read_body_capped(resp, MAX_BODY_BYTES).await?;
349    let parsed: SandUsageStatus = serde_json::from_slice(&bytes)
350        .map_err(|e| AppError::Schema(format!("grokbot usage response: {e}")))?;
351    parsed.into_snapshot()
352}
353
354#[derive(Debug, Deserialize)]
355struct RefreshResponse {
356    access_token: String,
357    /// Absent means the refresh token was not rotated; keep the current one.
358    refresh_token: Option<String>,
359}
360
361async fn refresh(
362    client: &reqwest::Client,
363    token_url: &str,
364    refresh_token: &str,
365) -> Result<RefreshedPair> {
366    let body = serde_json::json!({
367        "client_id": CLIENT_ID,
368        "grant_type": "refresh_token",
369        "refresh_token": refresh_token,
370    });
371    let resp = tokio::time::timeout(REFRESH_TIMEOUT, client.post(token_url).json(&body).send())
372        .await
373        .map_err(|_| AppError::Transport(format!("grokbot token refresh timeout: {token_url}")))?
374        .map_err(|e| AppError::Transport(format!("grokbot token refresh: {e}")))?;
375    if !resp.status().is_success() {
376        return Err(AppError::Credentials(
377            "Grok Bot token refresh was rejected; sign in to the Grok Bot desktop app again".into(),
378        ));
379    }
380    let bytes = read_body_capped(resp, MAX_BODY_BYTES).await?;
381    let parsed: RefreshResponse = serde_json::from_slice(&bytes)
382        .map_err(|e| AppError::Schema(format!("grokbot token refresh response: {e}")))?;
383    if parsed.access_token.trim().is_empty() {
384        return Err(AppError::Schema(
385            "grokbot token refresh returned no access token".into(),
386        ));
387    }
388    Ok(RefreshedPair {
389        access_token: parsed.access_token,
390        refresh_token: parsed
391            .refresh_token
392            .filter(|token| !token.trim().is_empty())
393            .unwrap_or_else(|| refresh_token.to_string()),
394    })
395}
396
397struct RefreshedPair {
398    access_token: String,
399    refresh_token: String,
400}
401
402/// A UUID-v4-shaped request id for the `x-request-id` header. `uuid` is
403/// deliberately not a dependency: a Connect-RPC request id is a tracing
404/// value, not a credential, so one is minted from process/time/counter
405/// entropy mixed through SHA-256 (already in the tree) and shaped per
406/// RFC 4122 §4.4.
407fn request_id() -> String {
408    use sha2::{Digest, Sha256};
409    use std::sync::atomic::{AtomicU64, Ordering};
410    static COUNTER: AtomicU64 = AtomicU64::new(0);
411
412    let nanos = std::time::SystemTime::now()
413        .duration_since(std::time::UNIX_EPOCH)
414        .map(|d| d.as_nanos())
415        .unwrap_or(0);
416    let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
417    let digest = Sha256::digest(format!("grokbot:{}:{nanos}:{seq}", std::process::id()).as_bytes());
418    let mut bytes = [0u8; 16];
419    bytes.copy_from_slice(&digest[..16]);
420    bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
421    bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10
422    let mut out = String::with_capacity(36);
423    for (i, byte) in bytes.iter().enumerate() {
424        if matches!(i, 4 | 6 | 8 | 10) {
425            out.push('-');
426        }
427        use std::fmt::Write as _;
428        let _ = write!(out, "{byte:02x}");
429    }
430    out
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436    use tempfile::TempDir;
437
438    fn cache_fixture() -> (TempDir, Cache) {
439        let td = TempDir::new().unwrap();
440        let cache = Cache::at(td.path().join("grokbot"));
441        cache.ensure_dir().unwrap();
442        (td, cache)
443    }
444
445    fn test_endpoints(base: &str) -> Endpoints {
446        Endpoints {
447            usage: format!("{base}/aiserver.v1.DashboardService/GetSandUsageStatus"),
448            token: format!("{base}/oauth/token"),
449        }
450    }
451
452    fn test_creds() -> GrokbotCredentials {
453        GrokbotCredentials {
454            access_token: "at-stored".into(),
455            refresh_token: "rt-stored".into(),
456            fingerprint: super::super::creds::fingerprint_of("rt-stored"),
457        }
458    }
459
460    /// The reporter's capture, lightly trimmed.
461    fn usage_json() -> &'static str {
462        r#"{"currentPeriodStart":"2026-09-11T18:43:19.645Z","nextResetTimestampUtc":"2026-09-18T18:43:19.645Z","usagePercent":12,"hasAvailableUsage":true,"hasNonZeroIncludedLimit":true,"onDemandSettings":{"visible":true,"eligible":true,"enabled":false},"grokPlanLabel":"Grok Bot Plan","cursorPlanName":"Pro"}"#
463    }
464
465    fn sample_seed(fingerprint: &str) -> serde_json::Value {
466        serde_json::json!({
467            "account": fingerprint,
468            "plan": "Grok Bot Plan",
469            "has_included_allowance": true,
470            "weekly_pct": 30,
471            "has_available_usage": true,
472            "on_demand_enabled": false,
473            "period_start": "2026-09-11T18:43:19.645Z",
474            "reset_at": "2026-09-18T18:43:19.645Z",
475        })
476    }
477
478    /// The mock usage endpoint, matching every header the client must send.
479    fn usage_mock(server: &mut mockito::ServerGuard, bearer: &str) -> mockito::Mock {
480        server
481            .mock("POST", "/aiserver.v1.DashboardService/GetSandUsageStatus")
482            .match_header("authorization", format!("Bearer {bearer}").as_str())
483            .match_header("content-type", "application/json")
484            .match_header("connect-protocol-version", "1")
485            .match_header("x-cursor-client-type", "sand")
486            .match_header("x-cursor-client-version", "0.1.0")
487            .match_header("x-sand-box-namespace", "prod")
488            .match_header("x-ghost-mode", "true")
489            .match_header(
490                "x-request-id",
491                mockito::Matcher::Regex(r"^[0-9a-f-]{36}$".into()),
492            )
493            // We cannot reproduce Cursor's machine checksum; it must not go out.
494            .match_header("x-cursor-checksum", mockito::Matcher::Missing)
495            .match_body(mockito::Matcher::Json(serde_json::json!({})))
496    }
497
498    #[tokio::test]
499    async fn live_200_returns_a_snapshot_and_sends_the_connect_rpc_headers() {
500        let mut server = mockito::Server::new_async().await;
501        let m = usage_mock(&mut server, "at-stored")
502            .with_status(200)
503            .with_body(usage_json())
504            .create_async()
505            .await;
506
507        let (_td, cache) = cache_fixture();
508        let out = fetch_snapshot_with(
509            &reqwest::Client::new(),
510            &test_creds(),
511            &cache,
512            &test_endpoints(&server.url()),
513            Duration::ZERO,
514        )
515        .await
516        .unwrap();
517
518        m.assert_async().await;
519        assert_eq!(out.snapshot.plan, "Grok Bot Plan");
520        assert!(out.snapshot.has_included_allowance);
521        assert_eq!(out.snapshot.weekly_pct, 12);
522        assert_eq!(out.snapshot.window, Some(chrono::Duration::days(7)));
523        assert!(!out.stale);
524    }
525
526    #[tokio::test]
527    async fn a_401_refreshes_persists_and_retries_once() {
528        let mut server = mockito::Server::new_async().await;
529        let stale = usage_mock(&mut server, "at-stored")
530            .with_status(401)
531            .with_body(r#"{"error":"expired"}"#)
532            .expect(1)
533            .create_async()
534            .await;
535        let refresh = server
536            .mock("POST", "/oauth/token")
537            .match_body(mockito::Matcher::Json(serde_json::json!({
538                "client_id": CLIENT_ID,
539                "grant_type": "refresh_token",
540                "refresh_token": "rt-stored",
541            })))
542            .with_status(200)
543            .with_body(
544                r#"{"access_token":"at-fresh","refresh_token":"rt-rotated","expires_in":3600}"#,
545            )
546            .expect(1)
547            .create_async()
548            .await;
549        let retried = usage_mock(&mut server, "at-fresh")
550            .with_status(200)
551            .with_body(usage_json())
552            .expect(1)
553            .create_async()
554            .await;
555
556        let (_td, cache) = cache_fixture();
557        let out = fetch_snapshot_with(
558            &reqwest::Client::new(),
559            &test_creds(),
560            &cache,
561            &test_endpoints(&server.url()),
562            Duration::ZERO,
563        )
564        .await
565        .unwrap();
566
567        stale.assert_async().await;
568        refresh.assert_async().await;
569        retried.assert_async().await;
570        assert_eq!(out.snapshot.weekly_pct, 12);
571
572        // The rotated pair persisted to the vendor cache, scoped by the new
573        // refresh token's fingerprint — never back to the app's file.
574        let persisted: serde_json::Value =
575            serde_json::from_slice(&std::fs::read(oauth_cache_path(&cache)).unwrap()).unwrap();
576        assert_eq!(persisted["access_token"], "at-fresh");
577        assert_eq!(persisted["refresh_token"], "rt-rotated");
578        assert_eq!(
579            persisted["fingerprint"],
580            super::super::creds::fingerprint_of("rt-rotated")
581        );
582        #[cfg(unix)]
583        {
584            use std::os::unix::fs::PermissionsExt;
585            let mode = std::fs::metadata(oauth_cache_path(&cache))
586                .unwrap()
587                .permissions()
588                .mode();
589            assert_eq!(mode & 0o077, 0);
590        }
591    }
592
593    #[tokio::test]
594    async fn a_persisted_pair_is_used_in_place_of_the_apps_older_access_token() {
595        let mut server = mockito::Server::new_async().await;
596        let m = usage_mock(&mut server, "at-fresh")
597            .with_status(200)
598            .with_body(usage_json())
599            .create_async()
600            .await;
601
602        let (_td, cache) = cache_fixture();
603        write_persisted_oauth(
604            &cache,
605            &PersistedOAuth {
606                // Same sign-in as the app's file, so the rotation is honored.
607                fingerprint: super::super::creds::fingerprint_of("rt-stored"),
608                access_token: "at-fresh".into(),
609                refresh_token: "rt-stored".into(),
610            },
611        )
612        .unwrap();
613
614        let out = fetch_snapshot_with(
615            &reqwest::Client::new(),
616            &test_creds(),
617            &cache,
618            &test_endpoints(&server.url()),
619            Duration::ZERO,
620        )
621        .await
622        .unwrap();
623
624        m.assert_async().await;
625        assert_eq!(out.snapshot.weekly_pct, 12);
626    }
627
628    #[tokio::test]
629    async fn a_persisted_pair_from_a_previous_sign_in_is_ignored() {
630        let mut server = mockito::Server::new_async().await;
631        let m = usage_mock(&mut server, "at-stored")
632            .with_status(200)
633            .with_body(usage_json())
634            .create_async()
635            .await;
636
637        let (_td, cache) = cache_fixture();
638        write_persisted_oauth(
639            &cache,
640            &PersistedOAuth {
641                fingerprint: super::super::creds::fingerprint_of("rt-someone-else"),
642                access_token: "at-stranger".into(),
643                refresh_token: "rt-stranger".into(),
644            },
645        )
646        .unwrap();
647
648        let out = fetch_snapshot_with(
649            &reqwest::Client::new(),
650            &test_creds(),
651            &cache,
652            &test_endpoints(&server.url()),
653            Duration::ZERO,
654        )
655        .await
656        .unwrap();
657
658        m.assert_async().await;
659        assert_eq!(out.snapshot.weekly_pct, 12);
660    }
661
662    #[tokio::test]
663    async fn a_rejected_refresh_is_a_credentials_error_naming_the_app() {
664        let mut server = mockito::Server::new_async().await;
665        usage_mock(&mut server, "at-stored")
666            .with_status(401)
667            .create_async()
668            .await;
669        server
670            .mock("POST", "/oauth/token")
671            .with_status(400)
672            .with_body(r#"{"error":"invalid_grant"}"#)
673            .create_async()
674            .await;
675
676        let (_td, cache) = cache_fixture();
677        let err = fetch_snapshot_with(
678            &reqwest::Client::new(),
679            &test_creds(),
680            &cache,
681            &test_endpoints(&server.url()),
682            Duration::ZERO,
683        )
684        .await
685        .unwrap_err();
686
687        assert!(matches!(err, AppError::Credentials(_)), "{err:?}");
688        assert!(
689            err.to_string()
690                .contains("sign in to the Grok Bot desktop app"),
691            "{err}"
692        );
693        // The rejected pair must not persist.
694        assert!(!oauth_cache_path(&cache).exists());
695    }
696
697    #[tokio::test]
698    async fn http_500_falls_back_to_the_cache_with_a_redacted_body() {
699        let mut server = mockito::Server::new_async().await;
700        server
701            .mock("POST", "/aiserver.v1.DashboardService/GetSandUsageStatus")
702            .with_status(500)
703            .with_body("proxy secret: <token>")
704            .create_async()
705            .await;
706
707        let (_td, cache) = cache_fixture();
708        cache
709            .write_payload(
710                sample_seed(&test_creds().fingerprint)
711                    .to_string()
712                    .as_bytes(),
713            )
714            .unwrap();
715
716        let out = fetch_snapshot_with(
717            &reqwest::Client::new(),
718            &test_creds(),
719            &cache,
720            &test_endpoints(&server.url()),
721            Duration::ZERO,
722        )
723        .await
724        .unwrap();
725
726        assert!(out.stale);
727        assert_eq!(out.snapshot.weekly_pct, 30);
728        assert_eq!(
729            out.last_error,
730            Some((500, "Grok Bot API returned HTTP 500".into()))
731        );
732    }
733
734    #[tokio::test]
735    async fn http_401_after_refresh_also_falls_back_with_a_redacted_body() {
736        let mut server = mockito::Server::new_async().await;
737        server
738            .mock("POST", "/aiserver.v1.DashboardService/GetSandUsageStatus")
739            .with_status(403)
740            .with_body(r#"{"error":"the access token itself, echoed"}"#)
741            .create_async()
742            .await;
743        server
744            .mock("POST", "/oauth/token")
745            .with_status(200)
746            .with_body(r#"{"access_token":"at-fresh","refresh_token":"rt-rotated"}"#)
747            .create_async()
748            .await;
749
750        let (_td, cache) = cache_fixture();
751        let err = fetch_snapshot_with(
752            &reqwest::Client::new(),
753            &test_creds(),
754            &cache,
755            &test_endpoints(&server.url()),
756            Duration::ZERO,
757        )
758        .await
759        .unwrap_err();
760
761        match err {
762            AppError::Http { status, body } => {
763                assert_eq!(status, 403);
764                assert_eq!(body, "Grok Bot authentication failed");
765            }
766            other => panic!("expected Http 403, got {other:?}"),
767        }
768    }
769
770    #[tokio::test]
771    async fn a_fresh_cache_is_served_without_a_network_call() {
772        let (_td, cache) = cache_fixture();
773        cache
774            .write_payload(
775                sample_seed(&test_creds().fingerprint)
776                    .to_string()
777                    .as_bytes(),
778            )
779            .unwrap();
780
781        // No mock server at all: a cache hit must never reach the network.
782        let out = fetch_snapshot_with(
783            &reqwest::Client::new(),
784            &test_creds(),
785            &cache,
786            &test_endpoints("http://127.0.0.1:1"),
787            Duration::from_secs(60),
788        )
789        .await
790        .unwrap();
791
792        assert!(!out.stale);
793        assert_eq!(out.snapshot.weekly_pct, 30);
794        assert_eq!(out.snapshot.window, Some(chrono::Duration::days(7)));
795    }
796
797    #[tokio::test]
798    async fn a_cache_from_a_previous_sign_in_is_not_reused() {
799        let mut server = mockito::Server::new_async().await;
800        let m = usage_mock(&mut server, "at-stored")
801            .with_status(200)
802            .with_body(usage_json())
803            .create_async()
804            .await;
805
806        let (_td, cache) = cache_fixture();
807        cache
808            .write_payload(sample_seed("some-other-fingerprint").to_string().as_bytes())
809            .unwrap();
810
811        let out = fetch_snapshot_with(
812            &reqwest::Client::new(),
813            &test_creds(),
814            &cache,
815            &test_endpoints(&server.url()),
816            // A long TTL: only the fingerprint mismatch can explain a refetch.
817            Duration::from_secs(3600),
818        )
819        .await
820        .unwrap();
821
822        m.assert_async().await;
823        assert!(!out.stale);
824        assert_eq!(out.snapshot.weekly_pct, 12);
825    }
826
827    #[tokio::test]
828    async fn a_transport_error_with_a_stale_cache_uses_the_cache() {
829        let (_td, cache) = cache_fixture();
830        cache
831            .write_payload(
832                sample_seed(&test_creds().fingerprint)
833                    .to_string()
834                    .as_bytes(),
835            )
836            .unwrap();
837
838        let out = fetch_snapshot_with(
839            &reqwest::Client::new(),
840            &test_creds(),
841            &cache,
842            &test_endpoints("http://127.0.0.1:1"),
843            Duration::ZERO,
844        )
845        .await
846        .unwrap();
847
848        assert!(out.stale);
849        assert_eq!(out.snapshot.weekly_pct, 30);
850    }
851
852    #[test]
853    fn a_cache_with_an_out_of_range_percent_is_rejected() {
854        let mut v = sample_seed("fp");
855        v["weekly_pct"] = serde_json::json!(150);
856        let err = parse_cache_at(v.to_string().as_bytes(), "fp").unwrap_err();
857        assert!(err.to_string().contains("weekly_pct"), "{err}");
858    }
859
860    #[test]
861    fn a_snapshot_survives_the_cache_round_trip() {
862        let snap = GrokbotSnapshot {
863            plan: "Grok Bot Plan".into(),
864            billed_by: Some("Cursor Ultra".into()),
865            has_included_allowance: true,
866            weekly_pct: 42,
867            has_available_usage: true,
868            on_demand_enabled: true,
869            period_start: DateTime::parse_from_rfc3339("2026-09-11T18:43:19.645Z")
870                .map(|dt| dt.with_timezone(&Utc))
871                .ok(),
872            reset_at: DateTime::parse_from_rfc3339("2026-09-18T18:43:19.645Z")
873                .map(|dt| dt.with_timezone(&Utc))
874                .ok(),
875            window: Some(chrono::Duration::days(7)),
876        };
877        let bytes = serde_json::to_vec(&snap_to_json(&snap, "fp")).unwrap();
878        assert_eq!(parse_cache_at(&bytes, "fp").unwrap(), snap);
879        // A cache written before `billed_by` existed still parses, unnamed.
880        let mut older = snap_to_json(&snap, "fp");
881        older.as_object_mut().unwrap().remove("billed_by");
882        let parsed = parse_cache_at(older.to_string().as_bytes(), "fp").unwrap();
883        assert_eq!(parsed.billed_by, None);
884    }
885
886    #[test]
887    fn request_ids_are_uuid_v4_shaped_and_unique() {
888        let a = request_id();
889        let b = request_id();
890        assert_ne!(a, b);
891        for id in [&a, &b] {
892            assert_eq!(id.len(), 36, "{id}");
893            assert_eq!(&id[14..15], "4", "version nibble: {id}");
894            assert!(
895                matches!(&id[19..20], "8" | "9" | "a" | "b"),
896                "variant bits: {id}"
897            );
898            assert!(
899                id.chars().all(|c| c.is_ascii_hexdigit() || c == '-'),
900                "{id}"
901            );
902        }
903    }
904}