ai-usagebar 1.39.1

Omarchy/Waybar widgets + TUI for tracking multi-provider AI plan usage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
//! Wrap `usage --json` for the popover and derive the tray icon severity.
//!
//! Pure JSON in, JSON out — no HWND, no `$HOME`, no clock. The host supplies
//! `now_ms` so tests pin the countdown.

use serde_json::{Value, json};

use super::icon::Severity;
use crate::display::sanitize_untrusted_field;

/// Default poll interval when `[tray] refresh_minutes` is unset. The provider
/// cache TTL stays 60 s; the tray just asks less often. The live value is
/// `HostFacts::refresh_secs`.
pub const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(300);

/// Everything the host knows that is not part of the usage report: its own
/// version, the Run-key state, the registered shortcut and the update
/// machinery. One struct so a new fact does not grow `wrap_report`'s arity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostFacts {
    /// Windows system accent colors for the Fluent popover; absent on other hosts.
    pub accent: Option<super::accent::Accent>,
    /// Seconds between full reports; `[tray] refresh_minutes` × 60.
    pub refresh_secs: u64,
    /// Canonical "Ctrl+Shift+U" spelling of the registered shortcut, or empty.
    pub shortcut: String,
    /// Why the last `set-shortcut` was refused (already taken, unparsable), or empty.
    pub shortcut_error: String,
    pub startup_enabled: bool,
    /// Latest known release when it is newer than `version`.
    pub update: Option<UpdateFact>,
    /// Wall-clock ms of the last successful or failed release check, 0 = never.
    pub update_checked_at: i64,
    /// "auto" | "notify" | "off".
    pub updates: String,
    pub version: String,
    /// Vendors whose active login the popover can switch. Only the macOS host
    /// fills this; an empty list hides the control everywhere else.
    pub accounts: Vec<AccountSwitchFact>,
    /// Every built-in provider, enabled or not, for Settings → Providers.
    pub providers: Vec<crate::catalog::VendorStatus>,
    /// Why the last enable/disable from the popover failed, or empty.
    pub providers_error: String,
}

/// One vendor's switchable logins, as the popover renders them beside each
/// account's card.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AccountSwitchFact {
    /// Report entry slug: "anthropic" or "openai".
    pub vendor: String,
    /// Label the vendor's default login belongs to; `None` when it is not a
    /// managed account.
    pub active: Option<String>,
    /// Labels that can be made active.
    pub labels: Vec<String>,
    /// Label of the last switch requested, running or finished; empty before
    /// the first one.
    pub target: String,
    /// Whether that switch is still running.
    pub switching: bool,
    /// Why that switch failed, or empty.
    pub error: String,
    /// An explicit trusted preparation CLI is configured (Desktop only).
    pub prepare_enabled: bool,
    pub prepare_target: String,
    pub preparing: bool,
    pub prepare_error: String,
    /// Server-confirmed reset, never a local five-hour estimate.
    pub prepared_reset: String,
}

/// State of a newer release as the popover renders it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UpdateFact {
    /// Human-readable reason when `state` is "failed", or empty.
    pub error: String,
    /// The release ships this OS/arch and the install directory is writable;
    /// otherwise the popover links the release page instead of installing.
    pub installable: bool,
    /// "checking" | "available" | "downloading" | "installing" | "failed".
    pub state: String,
    /// Release page for the human; never opened by the host itself.
    pub url: String,
    /// Bare "X.Y.Z".
    pub version: String,
}

/// Host facts are owned jointly: the event-loop thread edits the shortcut, the
/// worker edits the update state, and every report snapshots the whole thing.
pub type SharedFacts = std::sync::Arc<std::sync::Mutex<HostFacts>>;

/// Only the hosts read the whole record; the update worker edits in place.
#[cfg(any(windows, target_os = "macos"))]
pub fn facts_snapshot(facts: &SharedFacts) -> HostFacts {
    facts.lock().map(|f| f.clone()).unwrap_or_default()
}

pub fn with_facts(facts: &SharedFacts, edit: impl FnOnce(&mut HostFacts)) {
    if let Ok(mut guard) = facts.lock() {
        edit(&mut guard);
    }
}

impl HostFacts {
    pub fn new(version: &str, startup_enabled: bool) -> Self {
        Self {
            startup_enabled,
            updates: "notify".into(),
            version: version.into(),
            ..Self::default()
        }
    }
}

impl Default for HostFacts {
    fn default() -> Self {
        Self {
            accent: None,
            refresh_secs: POLL_INTERVAL.as_secs(),
            shortcut: String::new(),
            shortcut_error: String::new(),
            startup_enabled: false,
            update: None,
            update_checked_at: 0,
            updates: String::new(),
            version: String::new(),
            accounts: Vec::new(),
            providers: Vec::new(),
            providers_error: String::new(),
        }
    }
}

/// GitHub page this binary was built from (`Cargo.toml` `repository`), or
/// empty when that field is not a GitHub URL. The About screen opens it.
fn repository_page() -> String {
    let raw = crate::update::SOURCE_REPOSITORY
        .trim()
        .trim_end_matches('/');
    let raw = raw.strip_suffix(".git").unwrap_or(raw);
    if raw.starts_with("https://github.com/") {
        raw.to_string()
    } else {
        String::new()
    }
}

fn host_os() -> &'static str {
    if cfg!(target_os = "macos") {
        "macos"
    } else if cfg!(windows) {
        "windows"
    } else {
        "linux"
    }
}

/// Build the object the WebView's `apply` function consumes.
pub fn wrap_report(
    report_json: &str,
    facts: &HostFacts,
    now_ms: i64,
    host_error: Option<&str>,
) -> Value {
    let poll_ms = i64::try_from(facts.refresh_secs)
        .unwrap_or(i64::MAX / 1_000)
        .saturating_mul(1_000);
    let update = facts.update.as_ref().map(|u| {
        json!({
            "version": sanitize_untrusted_field(&u.version),
            "url": sanitize_untrusted_field(&u.url),
            "state": u.state,
            "error": sanitize_untrusted_field(&u.error),
            "installable": u.installable,
        })
    });
    let accounts: serde_json::Map<String, Value> = facts
        .accounts
        .iter()
        .map(|fact| {
            (
                fact.vendor.clone(),
                json!({
                    "active": fact.active.as_deref().map(sanitize_untrusted_field),
                    "labels": fact
                        .labels
                        .iter()
                        .map(|label| sanitize_untrusted_field(label))
                        .collect::<Vec<_>>(),
                    "target": sanitize_untrusted_field(&fact.target),
                    "switching": fact.switching,
                    "error": sanitize_untrusted_field(&fact.error),
                    "prepare_enabled": fact.prepare_enabled,
                    "prepare_target": sanitize_untrusted_field(&fact.prepare_target),
                    "preparing": fact.preparing,
                    "prepare_error": sanitize_untrusted_field(&fact.prepare_error),
                    "prepared_reset": fact.prepared_reset,
                }),
            )
        })
        .collect();
    let accent = facts.accent.as_ref().map(|accent| {
        json!({
            "light": accent.light,
            "dark": accent.dark,
        })
    });
    let mut payload = json!({
        "version": facts.version,
        "generated_at": now_ms,
        "next_refresh_at": now_ms.saturating_add(poll_ms),
        "refresh_minutes": facts.refresh_secs / 60,
        "startup_enabled": facts.startup_enabled,
        "os": host_os(),
        "shortcut": facts.shortcut,
        "shortcut_error": sanitize_untrusted_field(&facts.shortcut_error),
        "updates": facts.updates,
        "update": update,
        "update_checked_at": facts.update_checked_at,
        "repository": repository_page(),
        "accounts": accounts,
        "providers": super::providers::rows_json(&facts.providers, host_os() == "macos"),
        "providers_error": sanitize_untrusted_field(&facts.providers_error),
        "accent": accent,
        "host_error": host_error.map(sanitize_untrusted_field),
        "primary": Value::Null,
        "entries": [],
    });
    if host_error.is_some() {
        return payload;
    }
    match serde_json::from_str::<Value>(report_json) {
        Ok(Value::Object(map)) => {
            if let Some(obj) = payload.as_object_mut() {
                if let Some(primary) = map.get("primary") {
                    obj.insert("primary".into(), primary.clone());
                }
                if let Some(entries) = map.get("entries") {
                    obj.insert("entries".into(), with_sign_in_hints(entries));
                }
            }
            payload
        }
        _ => {
            payload["host_error"] = json!(sanitize_untrusted_field(
                "The usage report did not contain valid JSON."
            ));
            payload
        }
    }
}

/// Attach each entry's sign-in sentence from [`VendorId::sign_in_hint`].
///
/// The popover needs a "how do I fix this?" line on an error card. It must not
/// keep its own table for that: a JS object literal silently omits a provider
/// nobody remembered, while the Rust match cannot compile without one. The
/// entry id is `vendor` or `vendor@account`, so the slug is the part before
/// `@`; an id that matches no vendor is left without a hint rather than guessed.
fn with_sign_in_hints(entries: &Value) -> Value {
    let Some(list) = entries.as_array() else {
        return entries.clone();
    };
    Value::Array(
        list.iter()
            .map(|entry| {
                let mut entry = entry.clone();
                let slug = entry
                    .get("id")
                    .and_then(Value::as_str)
                    .map(|id| id.split('@').next().unwrap_or(id).to_ascii_lowercase());
                let hint = slug.and_then(|slug| {
                    crate::vendor::VendorId::all()
                        .iter()
                        .find(|v| v.slug() == slug)
                        .map(|v| v.sign_in_hint())
                });
                if let (Some(hint), Some(obj)) = (hint, entry.as_object_mut()) {
                    obj.insert("sign_in".into(), json!(hint));
                }
                entry
            })
            .collect(),
    )
}

pub fn host_payload(value: &Value) -> String {
    value.to_string()
}

/// Worst severity across every metric, treating fetch/host errors as critical.
pub fn worst_severity(payload: &Value) -> Severity {
    if payload
        .get("host_error")
        .and_then(Value::as_str)
        .is_some_and(|s| !s.is_empty())
    {
        return Severity::Critical;
    }
    let mut worst = Severity::Low;
    let Some(entries) = payload.get("entries").and_then(Value::as_array) else {
        return worst;
    };
    for entry in entries {
        if entry.get("status").and_then(Value::as_str) == Some("error")
            || entry
                .get("error")
                .and_then(Value::as_str)
                .is_some_and(|s| !s.is_empty())
        {
            return Severity::Critical;
        }
        let Some(sections) = entry.get("sections").and_then(Value::as_array) else {
            continue;
        };
        let metrics: Vec<&Value> = sections
            .iter()
            .filter(|section| section.get("type").and_then(Value::as_str) == Some("metric"))
            .collect();
        // A grouped row (the Claude entry's context sessions, SuperGrok's
        // product slices) sits under its own heading below the meters and is
        // not a quota window: it counts only when the entry has nothing else,
        // the partition `strip::quota_group` already applies.
        let has_window = metrics.iter().any(|section| !is_grouped(section));
        for section in metrics {
            if has_window && is_grouped(section) {
                continue;
            }
            if let Some(sev) = section
                .get("severity")
                .and_then(Value::as_str)
                .and_then(Severity::from_report_str)
                && sev.rank() > worst.rank()
            {
                worst = sev;
            }
        }
    }
    worst
}

/// Whether a metric sits under a group heading, which the report marks with a
/// non-empty `group`.
fn is_grouped(section: &Value) -> bool {
    section
        .get("group")
        .and_then(Value::as_str)
        .is_some_and(|group| !group.is_empty())
}

#[cfg(test)]
mod tests {

    /// The popover renders "how do I fix this?" on an error card. That sentence
    /// must come from the host: the frontend kept its own table first, and it
    /// disagreed with `VendorId` for five of eight providers before shipping.
    #[test]
    fn every_entry_carries_its_sign_in_hint_from_the_vendor() {
        let report = r#"{"primary":"anthropic","entries":[
            {"id":"anthropic","status":"error","error":"not signed in"},
            {"id":"openai@work","status":"error","error":"not signed in"},
            {"id":"cursor","status":"ready"},
            {"id":"custom:mytool","status":"ready"}
        ]}"#;
        let payload = wrap_report(report, &facts("1.0.0", false), 0, None);
        let entries = payload["entries"].as_array().expect("entries");

        assert_eq!(
            entries[0]["sign_in"],
            json!(crate::vendor::VendorId::Anthropic.sign_in_hint())
        );
        // "vendor@account" resolves on the vendor half.
        assert_eq!(
            entries[1]["sign_in"],
            json!(crate::vendor::VendorId::Openai.sign_in_hint())
        );
        // A vendor that has no CLI login still says how to sign in.
        assert_eq!(
            entries[2]["sign_in"],
            json!(crate::vendor::VendorId::Cursor.sign_in_hint())
        );
        // An id that is not a built-in vendor gets no invented hint.
        assert!(entries[3].get("sign_in").is_none(), "{:?}", entries[3]);
    }

    #[test]
    fn popover_keeps_all_distinct_antigravity_account_cards() {
        let entries = (0..5)
            .map(|index| {
                json!({
                    "id": format!("antigravity@{index:012x}"),
                    "name": "antigravity · a***@example.com",
                    "display_name": "Antigravity · a***@example.com",
                    "status": "ready",
                    "sections": [{
                        "type": "metric",
                        "label": format!("Weekly {index}"),
                        "percent": index * 10,
                        "value": format!("{}%", index * 10),
                        "detail": format!("Resets in {index}d"),
                        "severity": "low",
                        "reset_at": null
                    }]
                })
            })
            .collect::<Vec<_>>();
        let report = json!({ "primary": "antigravity", "entries": entries }).to_string();
        let payload = wrap_report(&report, &facts("1.0.0", false), 0, None);
        let cards = payload["entries"].as_array().unwrap();
        let ids = cards
            .iter()
            .map(|card| card["id"].as_str().unwrap())
            .collect::<std::collections::HashSet<_>>();
        assert_eq!(cards.len(), 5);
        assert_eq!(ids.len(), 5);
        assert!(
            cards
                .iter()
                .all(|card| card["display_name"] == "Antigravity · a***@example.com")
        );
        assert!(
            cards
                .iter()
                .all(|card| card["sign_in"] == crate::vendor::VendorId::Antigravity.sign_in_hint())
        );
        assert_eq!(cards[4]["sections"][0]["detail"], "Resets in 4d");
    }

    /// Every id `usage --json` can emit must resolve, or the popover shows a
    /// generic line for a provider we do know how to sign in.
    #[test]
    fn every_vendor_slug_resolves_to_a_hint() {
        for vendor in crate::vendor::VendorId::all() {
            let report = format!(
                r#"{{"entries":[{{"id":"{}","status":"error","error":"x"}}]}}"#,
                vendor.slug()
            );
            let payload = wrap_report(&report, &facts("1.0.0", false), 0, None);
            let hint = payload["entries"][0]["sign_in"].as_str().unwrap_or("");
            assert!(!hint.is_empty(), "{} has no sign-in hint", vendor.slug());
        }
    }
    use super::*;

    fn sample_report() -> String {
        json!({
            "primary": "anthropic",
            "entries": [
                {
                    "id": "anthropic",
                    "name": "anthropic",
                    "display_name": "Claude",
                    "short_name": "cld",
                    "plan": "Team 5x",
                    "status": "ready",
                    "error": null,
                    "stale": false,
                    "sections": [
                        {
                            "type": "metric",
                            "label": "Weekly",
                            "percent": 19,
                            "value": "19%",
                            "detail": "Resets in 1d 16h",
                            "severity": "low",
                            "reset_at": null
                        },
                        {
                            "type": "metric",
                            "label": "Session",
                            "percent": 0,
                            "value": "0%",
                            "detail": "",
                            "severity": "low",
                            "reset_at": null
                        }
                    ]
                },
                {
                    "id": "openai",
                    "short_name": "gpt",
                    "status": "ready",
                    "error": null,
                    "sections": [{
                        "type": "metric",
                        "label": "Session",
                        "percent": 91,
                        "value": "91%",
                        "detail": "",
                        "severity": "critical",
                        "reset_at": null
                    }]
                }
            ]
        })
        .to_string()
    }

    fn facts(version: &str, startup_enabled: bool) -> HostFacts {
        HostFacts::new(version, startup_enabled)
    }

    #[test]
    fn wrap_copies_entries_and_stamps_refresh() {
        let payload = wrap_report(&sample_report(), &facts("1.10.0", true), 1_000, None);
        assert_eq!(payload["version"], "1.10.0");
        assert_eq!(payload["generated_at"], 1_000);
        assert_eq!(payload["next_refresh_at"], 301_000);
        assert_eq!(payload["refresh_minutes"], 5);
        assert_eq!(payload["startup_enabled"], true);
        assert_eq!(payload["accent"], Value::Null);
        let os = payload["os"].as_str().unwrap_or("");
        assert!(
            os == "macos" || os == "windows" || os == "linux",
            "unexpected os {os}"
        );
        assert_eq!(payload["shortcut"], "");
        assert_eq!(payload["shortcut_error"], "");
        assert_eq!(payload["updates"], "notify");
        assert!(payload["update"].is_null());
        assert_eq!(payload["update_checked_at"], 0);
        assert!(
            payload["repository"]
                .as_str()
                .unwrap_or("")
                .starts_with("https://github.com/")
        );
        assert!(payload["host_error"].is_null());
        assert_eq!(payload["primary"], "anthropic");
        assert_eq!(payload["entries"][0]["short_name"], "cld");
    }

    #[test]
    fn wrap_carries_fluent_accent_colors() {
        let mut host = facts("1.10.0", false);
        host.accent = Some(super::super::accent::Accent {
            light: "#123456".into(),
            dark: "#abcdef".into(),
        });
        let payload = wrap_report(&sample_report(), &host, 0, None);

        // ASSERT: both validated host colors reach the JSON root unchanged.
        assert_eq!(payload["accent"]["light"], "#123456");
        assert_eq!(payload["accent"]["dark"], "#abcdef");
    }

    #[test]
    fn wrap_carries_shortcut_and_update_facts_sanitized() {
        let mut host = facts("1.10.0", false);
        host.shortcut = "Ctrl+Shift+U".into();
        host.shortcut_error = "already taken\u{1b}[31m".into();
        host.updates = "auto".into();
        host.update_checked_at = 42;
        host.update = Some(UpdateFact {
            error: String::new(),
            installable: true,
            state: "available".into(),
            url: "https://github.com/akitaonrails/ai-usagebar/releases/tag/v1.11.0".into(),
            version: "1.11.0".into(),
        });
        let payload = wrap_report(&sample_report(), &host, 0, None);
        assert_eq!(payload["shortcut"], "Ctrl+Shift+U");
        assert!(
            !payload["shortcut_error"]
                .as_str()
                .unwrap()
                .contains('\u{1b}')
        );
        assert_eq!(payload["updates"], "auto");
        assert_eq!(payload["update_checked_at"], 42);
        assert_eq!(payload["update"]["version"], "1.11.0");
        assert_eq!(payload["update"]["state"], "available");
        assert_eq!(payload["update"]["error"], "");
        assert_eq!(payload["update"]["installable"], true);
    }

    #[test]
    fn host_error_wins_over_report_body() {
        let payload = wrap_report(
            "not-json",
            &facts("1.0.0", false),
            0,
            Some("no vendors enabled"),
        );
        assert_eq!(payload["host_error"], "no vendors enabled");
        assert_eq!(payload["entries"].as_array().unwrap().len(), 0);
        assert_eq!(worst_severity(&payload), Severity::Critical);
    }

    #[test]
    fn invalid_report_json_becomes_a_host_error() {
        let payload = wrap_report("{", &facts("1.0.0", false), 0, None);
        assert!(
            payload["host_error"]
                .as_str()
                .unwrap()
                .contains("valid JSON")
        );
        assert_eq!(worst_severity(&payload), Severity::Critical);
    }

    #[test]
    fn worst_severity_is_the_hottest_metric_not_the_primary() {
        let payload = wrap_report(&sample_report(), &facts("1.10.0", false), 0, None);
        assert_eq!(worst_severity(&payload), Severity::Critical);
    }

    /// A context session row (`group: "Sessions"`) is a breakdown under its
    /// own heading, not a quota window: a session at 90% of its context must
    /// not paint the tray icon critical while the quota sits at 29%.
    #[test]
    fn worst_severity_ignores_grouped_rows_behind_a_window() {
        let report = json!({
            "primary": "anthropic",
            "entries": [{
                "id": "anthropic",
                "short_name": "cld",
                "status": "ready",
                "error": null,
                "sections": [
                    {
                        "type": "metric",
                        "label": "Session (5h)",
                        "percent": 29,
                        "value": "29%",
                        "detail": "",
                        "severity": "low",
                        "reset_at": null
                    },
                    {
                        "type": "metric",
                        "label": "ship the release",
                        "group": "Sessions",
                        "percent": 90,
                        "value": "90%",
                        "detail": "",
                        "severity": "critical",
                        "reset_at": null
                    }
                ]
            }]
        })
        .to_string();
        let payload = wrap_report(&report, &facts("1.10.0", false), 0, None);
        assert_eq!(worst_severity(&payload), Severity::Low);
    }

    /// With no ungrouped metric the grouped rows still stand in, as they do
    /// for the menu bar's quota group.
    #[test]
    fn worst_severity_falls_back_to_grouped_rows_without_a_window() {
        let report = json!({
            "primary": "anthropic",
            "entries": [{
                "id": "anthropic",
                "short_name": "cld",
                "status": "ready",
                "error": null,
                "sections": [{
                    "type": "metric",
                    "label": "ship the release",
                    "group": "Sessions",
                    "percent": 90,
                    "value": "90%",
                    "detail": "",
                    "severity": "critical",
                    "reset_at": null
                }]
            }]
        })
        .to_string();
        let payload = wrap_report(&report, &facts("1.10.0", false), 0, None);
        assert_eq!(worst_severity(&payload), Severity::Critical);
    }

    #[test]
    fn entry_error_is_critical_and_lands_in_the_tooltip() {
        let report = json!({
            "primary": "openai",
            "entries": [{
                "id": "openai",
                "short_name": "gpt",
                "status": "error",
                "error": "not signed in",
                "sections": []
            }]
        })
        .to_string();
        let payload = wrap_report(&report, &facts("1.10.0", false), 0, None);
        assert_eq!(worst_severity(&payload), Severity::Critical);
    }

    #[test]
    fn empty_report_uses_a_generic_tooltip() {
        let payload = wrap_report("{}", &facts("1.0.0", false), 0, None);
        assert_eq!(worst_severity(&payload), Severity::Low);
        assert_eq!(POLL_INTERVAL.as_secs(), 300);
    }

    #[test]
    fn next_refresh_follows_the_configured_interval() {
        let mut host = facts("1.10.0", false);
        host.refresh_secs = 60;
        let payload = wrap_report(&sample_report(), &host, 1_000, None);
        assert_eq!(payload["next_refresh_at"], 61_000);
        assert_eq!(payload["refresh_minutes"], 1);

        host.refresh_secs = 600;
        let payload = wrap_report(&sample_report(), &host, 1_000, None);
        assert_eq!(payload["next_refresh_at"], 601_000);
        assert_eq!(payload["refresh_minutes"], 10);
    }

    #[test]
    fn switchable_accounts_are_keyed_by_vendor() {
        let mut host = facts("1.10.0", false);
        host.accounts = vec![AccountSwitchFact {
            vendor: "openai".into(),
            active: Some("main".into()),
            labels: vec!["main".into(), "work\u{1b}[31m".into()],
            target: "work".into(),
            switching: false,
            error: "no stored Codex login".into(),
            ..AccountSwitchFact::default()
        }];
        let payload = wrap_report(&sample_report(), &host, 0, None);
        let openai = &payload["accounts"]["openai"];
        assert_eq!(openai["active"], "main");
        assert_eq!(openai["labels"][0], "main");
        assert!(!openai["labels"][1].as_str().unwrap().contains('\u{1b}'));
        assert_eq!(openai["target"], "work");
        assert_eq!(openai["switching"], false);
        assert_eq!(openai["error"], "no stored Codex login");
        assert!(payload["accounts"].get("anthropic").is_none());
    }

    #[test]
    fn desktop_prepare_facts_are_explicit_and_sanitized() {
        let mut host = facts("1.34.0", false);
        host.accounts = vec![AccountSwitchFact {
            vendor: "claude-desktop".into(),
            active: Some("one".into()),
            labels: vec!["one".into(), "two".into()],
            prepare_enabled: true,
            prepare_target: "two".into(),
            preparing: true,
            prepare_error: "offline\u{1b}[31m".into(),
            prepared_reset: "2026-10-10T19:00:00Z".into(),
            ..AccountSwitchFact::default()
        }];
        let payload = wrap_report(&sample_report(), &host, 0, None);
        let desktop = &payload["accounts"]["claude-desktop"];
        assert_eq!(desktop["prepare_enabled"], true);
        assert_eq!(desktop["prepare_target"], "two");
        assert_eq!(desktop["preparing"], true);
        assert!(
            !desktop["prepare_error"]
                .as_str()
                .unwrap()
                .contains('\u{1b}')
        );
        assert_eq!(desktop["prepared_reset"], "2026-10-10T19:00:00Z");
    }

    #[test]
    fn no_switchable_accounts_is_an_empty_object() {
        let payload = wrap_report(&sample_report(), &facts("1.10.0", false), 0, None);
        assert_eq!(payload["accounts"], json!({}));
    }
}