brokk-mj-controller 2.13.0

Daemon-side controller, session manager, and web server for Mjolnir
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
//! Claude Code `/usage` polling and parsing.
//!
//! The Claude ACP agent exposes token usage over ACP, but the subscription
//! quota shown by Claude Code lives behind its local `/usage` command.  Keep
//! this module independent from the UI state machine so the parser can be
//! tested against captured command output without spawning `claude`.

use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use serde_json::Value;

use crate::targets::{CancellableProcessExecutor, CommandExecutor, CommandOutput, CommandSpec};

const USAGE_TIMEOUT: Duration = Duration::from_secs(20);
const REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
const USAGE_URL: &str = "https://api.anthropic.com/api/oauth/usage";

/// Quota-row copy when the stored Claude OAuth access token is past `expiresAt`.
pub(crate) const LOGIN_EXPIRED: &str = "login expired";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaudeUsageReport {
    pub five_hour: Option<ClaudeUsageWindow>,
    pub week: Option<ClaudeUsageWindow>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaudeUsageWindow {
    pub remaining_percent: u8,
    /// Text following `reset` in Claude Code output, without the word itself.
    pub reset_context: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClaudeUsageError {
    TimedOut,
    NotSignedIn,
    LoginExpired,
    Refresh(String),
    Query(String),
    Parse,
}

impl fmt::Display for ClaudeUsageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TimedOut => write!(f, "claude /usage timed out"),
            Self::NotSignedIn => write!(f, "Claude Code is not signed in"),
            Self::LoginExpired => write!(f, "{LOGIN_EXPIRED}"),
            Self::Refresh(error) => write!(f, "refresh Claude login: {error}"),
            Self::Query(error) => write!(f, "query Claude usage: {error}"),
            Self::Parse => write!(f, "could not parse claude /usage output"),
        }
    }
}

/// Query the same OAuth usage endpoint as Claude Code's interactive `/usage`,
/// except on macOS, where Claude Code is asked directly.
///
/// The endpoint is authenticated with the access token from the profile home's
/// `.credentials.json`. On macOS that file does not exist: Claude Code keeps
/// the credentials in the Keychain, where only Claude Code itself reads them.
/// The API has no token to send there, so its print-mode `/usage` output is
/// the only quota macOS can report.
pub async fn query(
    home: PathBuf,
    environment: HashMap<String, String>,
) -> Result<ClaudeUsageReport, ClaudeUsageError> {
    let executor = Arc::new(CancellableProcessExecutor::with_timeout(REFRESH_TIMEOUT));
    if cfg!(target_os = "macos") {
        return query_cli_with(environment, executor).await;
    }
    query_with(home, environment, USAGE_URL, executor).await
}

/// Read the quota out of Claude Code's own `/usage` output.
async fn query_cli_with(
    environment: HashMap<String, String>,
    executor: Arc<dyn CommandExecutor + Send + Sync>,
) -> Result<ClaudeUsageReport, ClaudeUsageError> {
    let output = run_claude_usage(environment, executor, "read Claude usage")
        .await
        .map_err(ClaudeUsageError::Query)?;
    // Claude Code reports a missing login on stdout and exits zero, so both
    // streams are read before the status is judged.
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    // A report that parses is the answer. Classifying first would let the
    // free-form sections below the windows decide the result: a skill or MCP
    // server whose name happens to contain "unauthorized" is not a login
    // failure.
    if output.status == 0
        && let Some(report) = parse_cli_usage(&text)
    {
        return Ok(report);
    }
    if is_authentication_error(&text) {
        return Err(ClaudeUsageError::NotSignedIn);
    }
    if output.status != 0 {
        return Err(ClaudeUsageError::Query(format!(
            "claude /usage exited with status {}",
            output.status
        )));
    }
    Err(ClaudeUsageError::Parse)
}

async fn query_with(
    home: PathBuf,
    environment: HashMap<String, String>,
    usage_url: &str,
    executor: Arc<dyn CommandExecutor + Send + Sync>,
) -> Result<ClaudeUsageReport, ClaudeUsageError> {
    let client = reqwest::Client::builder()
        .timeout(USAGE_TIMEOUT)
        .build()
        .map_err(|error| ClaudeUsageError::Query(error.to_string()))?;
    let credentials = read_credentials(&home).await?;
    match oauth_access_token(&credentials, mj_core::clock::epoch_millis()) {
        Ok(token) => match query_api(&client, usage_url, token).await {
            Err(ClaudeUsageError::LoginExpired) if oauth_has_refresh_token(&credentials) => {
                refresh_and_retry(
                    &client,
                    usage_url,
                    home,
                    environment,
                    executor,
                    Some(token.to_owned()),
                )
                .await
            }
            result => result,
        },
        Err(ClaudeUsageError::LoginExpired) if oauth_has_refresh_token(&credentials) => {
            refresh_and_retry(&client, usage_url, home, environment, executor, None).await
        }
        Err(error) => Err(error),
    }
}

async fn read_credentials(home: &std::path::Path) -> Result<Value, ClaudeUsageError> {
    let credentials = tokio::fs::read(home.join(".credentials.json"))
        .await
        .map_err(|_| ClaudeUsageError::NotSignedIn)?;
    serde_json::from_slice(&credentials).map_err(|_| ClaudeUsageError::NotSignedIn)
}

async fn query_api(
    client: &reqwest::Client,
    usage_url: &str,
    token: &str,
) -> Result<ClaudeUsageReport, ClaudeUsageError> {
    let response = client
        .get(usage_url)
        .bearer_auth(token)
        .header("anthropic-beta", "oauth-2025-04-20")
        .send()
        .await
        .map_err(|error| {
            if error.is_timeout() {
                ClaudeUsageError::TimedOut
            } else {
                ClaudeUsageError::Query(error.to_string())
            }
        })?;
    if matches!(response.status().as_u16(), 401 | 403) {
        return Err(ClaudeUsageError::LoginExpired);
    }
    if !response.status().is_success() {
        return Err(ClaudeUsageError::Query(format!(
            "HTTP {}",
            response.status()
        )));
    }
    let payload: Value = response
        .json()
        .await
        .map_err(|error| ClaudeUsageError::Query(error.to_string()))?;
    parse_api_usage(&payload).ok_or(ClaudeUsageError::Parse)
}

async fn refresh_and_retry(
    client: &reqwest::Client,
    usage_url: &str,
    home: PathBuf,
    environment: HashMap<String, String>,
    executor: Arc<dyn CommandExecutor + Send + Sync>,
    rejected_token: Option<String>,
) -> Result<ClaudeUsageReport, ClaudeUsageError> {
    let refresh_error = run_claude_refresh(environment, executor).await.err();
    let credentials = match read_credentials(&home).await {
        Ok(credentials) => credentials,
        Err(error) => return Err(refresh_error.unwrap_or(error)),
    };
    let token = match oauth_access_token(&credentials, mj_core::clock::epoch_millis()) {
        Ok(token) => token,
        Err(error) => return Err(refresh_error.unwrap_or(error)),
    };
    if rejected_token.as_deref() == Some(token)
        && let Some(error) = refresh_error
    {
        return Err(error);
    }
    query_api(client, usage_url, token).await
}

/// Run Claude Code's `/usage` in print mode. The refresh path wants only the
/// exit status out of it; macOS reads the quota from its stdout.
async fn run_claude_usage(
    environment: HashMap<String, String>,
    executor: Arc<dyn CommandExecutor + Send + Sync>,
    purpose: &'static str,
) -> Result<CommandOutput, String> {
    let mut command = CommandSpec::new(
        if cfg!(windows) {
            "claude.cmd"
        } else {
            "claude"
        },
        ["-p", "/usage", "--no-session-persistence"],
    )
    .purpose(purpose);
    command.env.extend(environment);
    tokio::task::spawn_blocking(move || executor.execute(&command))
        .await
        .map_err(|error| format!("worker failed: {error}"))?
        .map_err(|error| error.to_string())
}

async fn run_claude_refresh(
    environment: HashMap<String, String>,
    executor: Arc<dyn CommandExecutor + Send + Sync>,
) -> Result<(), ClaudeUsageError> {
    let output = run_claude_usage(environment, executor, "refresh Claude login")
        .await
        .map_err(ClaudeUsageError::Refresh)?;
    successful_refresh_output(output)
}

fn successful_refresh_output(output: CommandOutput) -> Result<(), ClaudeUsageError> {
    if output.status == 0 {
        Ok(())
    } else {
        Err(ClaudeUsageError::Refresh(format!(
            "Claude /usage exited with status {}",
            output.status
        )))
    }
}

fn oauth_access_token(credentials: &Value, now_ms: i64) -> Result<&str, ClaudeUsageError> {
    let oauth = credentials
        .get("claudeAiOauth")
        .ok_or(ClaudeUsageError::NotSignedIn)?;
    let token = oauth
        .get("accessToken")
        .and_then(Value::as_str)
        .filter(|token| !token.is_empty())
        .ok_or(ClaudeUsageError::NotSignedIn)?;
    if oauth_expires_at(oauth).is_some_and(|expires_at| expires_at <= now_ms) {
        return Err(ClaudeUsageError::LoginExpired);
    }
    Ok(token)
}

fn oauth_expires_at(oauth: &Value) -> Option<i64> {
    let value = oauth.get("expiresAt")?;
    value
        .as_i64()
        .or_else(|| value.as_u64().and_then(|ms| i64::try_from(ms).ok()))
        .or_else(|| value.as_str()?.parse().ok())
}

fn oauth_has_refresh_token(credentials: &Value) -> bool {
    credentials
        .pointer("/claudeAiOauth/refreshToken")
        .and_then(Value::as_str)
        .is_some_and(|token| !token.is_empty())
}

fn parse_api_usage(payload: &Value) -> Option<ClaudeUsageReport> {
    let mut five_hour = None;
    let mut weekly = Vec::new();

    if let Some(limits) = payload.get("limits").and_then(Value::as_array) {
        for limit in limits {
            let Some(kind) = limit.get("kind").and_then(Value::as_str) else {
                continue;
            };
            let Some(window) = api_window(limit, "percent") else {
                continue;
            };
            match kind {
                "session" => five_hour = Some(window),
                "weekly_all" => weekly.push(window),
                "weekly_scoped" if api_scope_name(limit).is_some_and(|name| name == "fable") => {
                    weekly.push(window);
                }
                _ => {}
            }
        }
    } else {
        five_hour = payload
            .get("five_hour")
            .filter(|value| !value.is_null())
            .and_then(|value| api_window(value, "utilization"));
        for key in ["seven_day", "seven_day_fable"] {
            if let Some(window) = payload
                .get(key)
                .filter(|value| !value.is_null())
                .and_then(|value| api_window(value, "utilization"))
            {
                weekly.push(window);
            }
        }
    }

    let week = weekly
        .into_iter()
        .min_by_key(|window| window.remaining_percent);
    (five_hour.is_some() || week.is_some()).then_some(ClaudeUsageReport { five_hour, week })
}

fn api_window(value: &Value, percent_key: &str) -> Option<ClaudeUsageWindow> {
    let used = value.get(percent_key)?.as_f64()?;
    let used = used.round().clamp(0.0, 100.0) as u8;
    Some(ClaudeUsageWindow {
        remaining_percent: 100 - used,
        reset_context: value
            .get("resets_at")
            .and_then(Value::as_str)
            .map(str::to_owned),
    })
}

/// Scrape `claude -p /usage` for the two windows the quota row shows.
///
/// The command prints one line per window, each naming its own percentage:
///
/// ```text
/// Current session: 6% used · resets Sep 18 at 6:20pm (Europe/Paris)
/// Current week (all models): 30% used · resets Sep 20 at 1:59pm (Europe/Paris)
/// Current week (Fable): 40% used · resets Sep 20 at 2pm (Europe/Paris)
/// ```
///
/// The sections below those quote unrelated percentages ("57% of your usage
/// was at >150k context", "Top skills: /code-review 3%"), so only a line whose
/// label is one of the windows is read, and only when the number is followed
/// by `used`. A percentage that means something else is worth reporting as
/// unparsed rather than reporting backwards.
fn parse_cli_usage(output: &str) -> Option<ClaudeUsageReport> {
    let mut five_hour = None;
    let mut weekly = Vec::new();

    for line in strip_ansi(output).lines() {
        let Some((label, rest)) = line.split_once(':') else {
            continue;
        };
        let label = label.trim().to_ascii_lowercase();
        if label != "current session" && !label.starts_with("current week") {
            continue;
        }
        let Some(window) = cli_window(rest) else {
            continue;
        };
        if label == "current session" {
            five_hour = Some(window);
        } else {
            weekly.push(window);
        }
    }

    // Two weekly windows can be in force at once, as an overall limit and a
    // per-model one. The binding limit is the one with the least left, which
    // is also what the API path reports.
    let week = weekly
        .into_iter()
        .min_by_key(|window| window.remaining_percent);
    (five_hour.is_some() || week.is_some()).then_some(ClaudeUsageReport { five_hour, week })
}

/// One window from the text after a `/usage` line's label.
fn cli_window(rest: &str) -> Option<ClaudeUsageWindow> {
    let (used, tail) = rest.trim_start().split_once('%')?;
    let used: f64 = used.trim().parse().ok()?;
    if !tail.trim_start().starts_with("used") {
        return None;
    }
    Some(ClaudeUsageWindow {
        remaining_percent: 100 - (used.round().clamp(0.0, 100.0) as u8),
        reset_context: tail
            .split_once("resets ")
            .map(|(_, context)| context.trim().to_owned())
            .filter(|context| !context.is_empty()),
    })
}

/// Claude Code paints `/usage` for a terminal, so its output can carry SGR
/// escapes even in print mode.
fn strip_ansi(input: &str) -> String {
    let mut output = String::with_capacity(input.len());
    let mut characters = input.chars();
    while let Some(character) = characters.next() {
        if character != '\u{1b}' {
            output.push(character);
            continue;
        }
        // CSI sequences end at their final byte; anything else ends at the
        // next character.
        if characters.next() == Some('[') {
            for character in characters.by_ref() {
                if character.is_ascii_alphabetic() {
                    break;
                }
            }
        }
    }
    output
}

fn is_authentication_error(detail: &str) -> bool {
    let lower = detail.to_ascii_lowercase();
    [
        "not logged in",
        "not signed in",
        "unauthenticated",
        "unauthorized",
        "please log in",
        "please login",
        "invalid api key",
    ]
    .iter()
    .any(|needle| lower.contains(needle))
}

fn api_scope_name(value: &Value) -> Option<String> {
    value
        .pointer("/scope/model/display_name")
        .and_then(Value::as_str)
        .map(str::to_ascii_lowercase)
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::extract::State;
    use axum::http::{HeaderMap, StatusCode};
    use axum::routing::get;
    use axum::{Json, Router};
    use std::sync::Mutex;

    /// Captured verbatim from `claude -p /usage --no-session-persistence`.
    const CLI_USAGE: &str = "\
You are currently using your subscription to power your Claude Code usage

Current session: 6% used · resets Sep 18 at 6:20pm (Europe/Paris)
Current week (all models): 30% used · resets Sep 20 at 1:59pm (Europe/Paris)
Current week (Fable): 40% used · resets Sep 20 at 2pm (Europe/Paris)

What's contributing to your limits usage?
Approximate, based on local sessions on this machine — does not include other devices or claude.ai. Behaviors are independent characteristics, not a breakdown.

Last 24h · 2108 requests · 13 sessions
  57% of your usage was at >150k context
  41% of your usage was while 4+ sessions ran in parallel
  31% of your usage came from subagent-heavy sessions
  Top skills: /code-review 3%
  Top MCP servers: claude-in-chrome 1%

Last 7d · 5966 requests · 78 sessions
  52% of your usage was at >150k context
  28% of your usage came from subagent-heavy sessions
  28% of your usage was while 4+ sessions ran in parallel
  Top skills: /code-review 2%
  Top subagents: Explore 2%, Plan 1%
  Top MCP servers: claude-in-chrome 2%
";

    #[test]
    fn cli_usage_reports_both_windows_and_the_binding_weekly_limit() {
        let report = parse_cli_usage(CLI_USAGE).expect("the captured output parses");

        let five_hour = report.five_hour.expect("session window");
        assert_eq!(five_hour.remaining_percent, 94);
        assert_eq!(
            five_hour.reset_context.as_deref(),
            Some("Sep 18 at 6:20pm (Europe/Paris)")
        );
        // 40% used is the weekly limit that binds first, not 30%.
        let week = report.week.expect("weekly window");
        assert_eq!(week.remaining_percent, 60);
        assert_eq!(
            week.reset_context.as_deref(),
            Some("Sep 20 at 2pm (Europe/Paris)")
        );
    }

    /// The later sections are full of percentages that are not quota.
    #[test]
    fn cli_usage_ignores_percentages_that_are_not_a_window() {
        let report = parse_cli_usage(
            "Last 24h · 2108 requests · 13 sessions\n  \
             57% of your usage was at >150k context\n  \
             Top skills: /code-review 3%\n",
        );
        assert_eq!(report, None);
    }

    #[test]
    fn cli_usage_survives_terminal_colouring() {
        let coloured = "\u{1b}[1mCurrent session:\u{1b}[0m \u{1b}[32m6% used\u{1b}[0m · resets Sep 18 at 6:20pm\n";
        let report = parse_cli_usage(coloured).expect("coloured output parses");
        assert_eq!(report.five_hour.unwrap().remaining_percent, 94);
    }

    /// A window whose number stops meaning "used" must read as unparsed
    /// rather than as its own complement.
    #[test]
    fn cli_usage_refuses_a_percentage_it_cannot_interpret() {
        assert_eq!(
            parse_cli_usage("Current session: 6% left · resets Sep 18 at 6:20pm\n"),
            None
        );
    }

    #[derive(Clone)]
    struct RefreshExecutor {
        home: PathBuf,
        replacement: Option<Value>,
        status: i32,
        commands: Arc<Mutex<Vec<CommandSpec>>>,
    }

    impl CommandExecutor for RefreshExecutor {
        fn execute(&self, command: &CommandSpec) -> anyhow::Result<CommandOutput> {
            self.commands.lock().unwrap().push(command.clone());
            if let Some(replacement) = &self.replacement {
                std::fs::write(
                    self.home.join(".credentials.json"),
                    serde_json::to_vec(replacement)?,
                )?;
            }
            Ok(CommandOutput {
                status: self.status,
                stdout: b"Approximate local usage".to_vec(),
                stderr: Vec::new(),
            })
        }
    }

    #[derive(Clone)]
    struct UsageServerState {
        reject_first: bool,
        authorizations: Arc<Mutex<Vec<String>>>,
    }

    async fn test_usage(
        State(state): State<UsageServerState>,
        headers: HeaderMap,
    ) -> (StatusCode, Json<Value>) {
        let authorization = headers
            .get(reqwest::header::AUTHORIZATION)
            .and_then(|value| value.to_str().ok())
            .unwrap_or_default()
            .to_owned();
        let mut authorizations = state.authorizations.lock().unwrap();
        let reject = state.reject_first && authorizations.is_empty();
        authorizations.push(authorization);
        drop(authorizations);
        if reject {
            return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({})));
        }
        (
            StatusCode::OK,
            Json(serde_json::json!({
                "five_hour": {"utilization": 25.0, "resets_at": "2026-08-23T00:00:00Z"},
                "seven_day": {"utilization": 40.0, "resets_at": "2026-08-29T00:00:00Z"}
            })),
        )
    }

    async fn spawn_usage_server(
        reject_first: bool,
    ) -> (String, UsageServerState, tokio::task::JoinHandle<()>) {
        let state = UsageServerState {
            reject_first,
            authorizations: Arc::new(Mutex::new(Vec::new())),
        };
        let app = Router::new()
            .route("/usage", get(test_usage))
            .with_state(state.clone());
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        (format!("http://{address}/usage"), state, server)
    }

    fn credentials(token: &str, refresh: Option<&str>, expires_at: i64) -> Value {
        let mut oauth = serde_json::json!({
            "accessToken": token,
            "expiresAt": expires_at,
        });
        if let Some(refresh) = refresh {
            oauth["refreshToken"] = Value::String(refresh.to_owned());
        }
        serde_json::json!({"claudeAiOauth": oauth})
    }

    #[tokio::test]
    async fn expired_login_asks_claude_to_refresh_without_persisting_a_session() {
        let home = tempfile::tempdir().unwrap();
        let path = home.path().join(".credentials.json");
        std::fs::write(
            &path,
            serde_json::to_vec(&credentials("old", Some("refresh"), 1)).unwrap(),
        )
        .unwrap();
        let fresh = credentials(
            "fresh",
            Some("rotated"),
            mj_core::clock::epoch_millis() + 60_000,
        );
        let commands = Arc::new(Mutex::new(Vec::new()));
        let executor = RefreshExecutor {
            home: home.path().to_path_buf(),
            replacement: Some(fresh),
            status: 0,
            commands: commands.clone(),
        };
        let (usage_url, server_state, server) = spawn_usage_server(false).await;
        let environment = HashMap::from([(
            "CLAUDE_CONFIG_DIR".to_owned(),
            home.path().to_string_lossy().into_owned(),
        )]);

        let report = query_with(
            home.path().to_path_buf(),
            environment.clone(),
            &usage_url,
            Arc::new(executor),
        )
        .await
        .unwrap();

        assert_eq!(report.five_hour.unwrap().remaining_percent, 75);
        let commands = commands.lock().unwrap();
        assert_eq!(commands.len(), 1);
        assert_eq!(
            commands[0].args,
            ["-p", "/usage", "--no-session-persistence"]
        );
        assert_eq!(commands[0].env, environment.into_iter().collect());
        assert_eq!(
            server_state.authorizations.lock().unwrap().as_slice(),
            ["Bearer fresh"]
        );
        server.abort();
    }

    #[tokio::test]
    async fn authoritative_rejection_refreshes_once_and_retries_with_new_credentials() {
        let home = tempfile::tempdir().unwrap();
        let fresh_expiry = mj_core::clock::epoch_millis() + 60_000;
        std::fs::write(
            home.path().join(".credentials.json"),
            serde_json::to_vec(&credentials("old", Some("refresh"), fresh_expiry)).unwrap(),
        )
        .unwrap();
        let commands = Arc::new(Mutex::new(Vec::new()));
        let executor = RefreshExecutor {
            home: home.path().to_path_buf(),
            replacement: Some(credentials("fresh", Some("rotated"), fresh_expiry)),
            status: 0,
            commands: commands.clone(),
        };
        let (usage_url, server_state, server) = spawn_usage_server(true).await;

        query_with(
            home.path().to_path_buf(),
            HashMap::new(),
            &usage_url,
            Arc::new(executor),
        )
        .await
        .unwrap();

        assert_eq!(commands.lock().unwrap().len(), 1);
        assert_eq!(
            server_state.authorizations.lock().unwrap().as_slice(),
            ["Bearer old", "Bearer fresh"]
        );
        server.abort();
    }

    #[tokio::test]
    async fn valid_credentials_query_authoritative_usage_without_launching_claude() {
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join(".credentials.json"),
            serde_json::to_vec(&credentials(
                "current",
                Some("refresh"),
                mj_core::clock::epoch_millis() + 60_000,
            ))
            .unwrap(),
        )
        .unwrap();
        let commands = Arc::new(Mutex::new(Vec::new()));
        let executor = RefreshExecutor {
            home: home.path().to_path_buf(),
            replacement: None,
            status: 0,
            commands: commands.clone(),
        };
        let (usage_url, server_state, server) = spawn_usage_server(false).await;

        query_with(
            home.path().to_path_buf(),
            HashMap::new(),
            &usage_url,
            Arc::new(executor),
        )
        .await
        .unwrap();

        assert!(commands.lock().unwrap().is_empty());
        assert_eq!(
            server_state.authorizations.lock().unwrap().as_slice(),
            ["Bearer current"]
        );
        server.abort();
    }

    #[tokio::test]
    async fn failed_refresh_of_a_rejected_token_is_not_mislabeled_login_expired() {
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join(".credentials.json"),
            serde_json::to_vec(&credentials(
                "rejected",
                Some("refresh"),
                mj_core::clock::epoch_millis() + 60_000,
            ))
            .unwrap(),
        )
        .unwrap();
        let executor = RefreshExecutor {
            home: home.path().to_path_buf(),
            replacement: None,
            status: 1,
            commands: Arc::new(Mutex::new(Vec::new())),
        };
        let (usage_url, server_state, server) = spawn_usage_server(true).await;

        let error = query_with(
            home.path().to_path_buf(),
            HashMap::new(),
            &usage_url,
            Arc::new(executor),
        )
        .await
        .unwrap_err();

        assert!(matches!(error, ClaudeUsageError::Refresh(_)));
        assert_eq!(
            server_state.authorizations.lock().unwrap().as_slice(),
            ["Bearer rejected"]
        );
        server.abort();
    }

    #[tokio::test]
    async fn failed_cli_is_accepted_when_credentials_were_refreshed_concurrently() {
        let home = tempfile::tempdir().unwrap();
        std::fs::write(
            home.path().join(".credentials.json"),
            serde_json::to_vec(&credentials("old", Some("refresh"), 1)).unwrap(),
        )
        .unwrap();
        let executor = RefreshExecutor {
            home: home.path().to_path_buf(),
            replacement: Some(credentials(
                "fresh",
                Some("rotated"),
                mj_core::clock::epoch_millis() + 60_000,
            )),
            status: 1,
            commands: Arc::new(Mutex::new(Vec::new())),
        };
        let (usage_url, _, server) = spawn_usage_server(false).await;

        let report = query_with(
            home.path().to_path_buf(),
            HashMap::new(),
            &usage_url,
            Arc::new(executor),
        )
        .await
        .unwrap();

        assert_eq!(report.week.unwrap().remaining_percent, 60);
        server.abort();
    }

    #[test]
    fn api_usage_uses_exhausted_fable_limit_over_overall_limit() {
        let report = parse_api_usage(&serde_json::json!({
            "limits": [
                {
                    "kind": "session",
                    "percent": 13.0,
                    "resets_at": "2026-08-18T23:30:00Z"
                },
                {
                    "kind": "weekly_all",
                    "percent": 96.0,
                    "resets_at": "2026-08-19T22:59:00Z"
                },
                {
                    "kind": "weekly_scoped",
                    "percent": 100.0,
                    "resets_at": "2026-08-19T22:59:00Z",
                    "scope": { "model": { "display_name": "Fable" } }
                }
            ]
        }))
        .expect("report");

        assert_eq!(report.five_hour.unwrap().remaining_percent, 87);
        let week = report.week.unwrap();
        assert_eq!(week.remaining_percent, 0);
        assert_eq!(week.reset_context.as_deref(), Some("2026-08-19T22:59:00Z"));
    }

    #[test]
    fn api_usage_ignores_other_model_scoped_weekly_limits() {
        let report = parse_api_usage(&serde_json::json!({
            "limits": [
                { "kind": "weekly_all", "percent": 40.0 },
                {
                    "kind": "weekly_scoped",
                    "percent": 90.0,
                    "scope": { "model": { "display_name": "Opus" } }
                },
                {
                    "kind": "weekly_scoped",
                    "percent": 50.0,
                    "scope": { "model": { "display_name": "Fable" } }
                }
            ]
        }))
        .expect("report");

        assert_eq!(report.week.unwrap().remaining_percent, 50);
    }

    #[test]
    fn expired_oauth_access_token_is_login_expired() {
        let credentials = serde_json::json!({
            "claudeAiOauth": {
                "accessToken": "sk-ant-oat01-test",
                "expiresAt": 1_000
            }
        });
        assert_eq!(
            oauth_access_token(&credentials, 1_001),
            Err(ClaudeUsageError::LoginExpired)
        );
        assert_eq!(
            oauth_access_token(&credentials, 1_000),
            Err(ClaudeUsageError::LoginExpired)
        );
    }

    #[test]
    fn current_oauth_access_token_is_usable() {
        let credentials = serde_json::json!({
            "claudeAiOauth": {
                "accessToken": "sk-ant-oat01-test",
                "expiresAt": 2_000
            }
        });
        assert_eq!(
            oauth_access_token(&credentials, 1_999).expect("token"),
            "sk-ant-oat01-test"
        );
    }

    #[test]
    fn oauth_access_token_without_expiry_is_usable() {
        let credentials = serde_json::json!({
            "claudeAiOauth": { "accessToken": "sk-ant-oat01-test" }
        });
        assert_eq!(
            oauth_access_token(&credentials, 9_000).expect("token"),
            "sk-ant-oat01-test"
        );
    }

    #[test]
    fn missing_oauth_access_token_is_not_signed_in() {
        assert_eq!(
            oauth_access_token(&serde_json::json!({}), 1),
            Err(ClaudeUsageError::NotSignedIn)
        );
        assert_eq!(
            oauth_access_token(
                &serde_json::json!({ "claudeAiOauth": { "accessToken": "" } }),
                1
            ),
            Err(ClaudeUsageError::NotSignedIn)
        );
    }
}