ai-usagebar 1.32.0

Omarchy/Waybar widgets + TUI for tracking multi-provider AI plan usage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
//! Chart, logo or short-name strip for the macOS status item.
//!
//! `StripContent` owns visible groups and their values; the report supplies
//! the short name drawn in place of a mark, either because the provider has
//! no embedded mark or because the user chose the name look.

use serde_json::Value;

use super::strip::{StripContent, StripMetric, quota_group};

/// Artwork needed for the current status-item content.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum StatusItemContent {
    /// The static application icon is the empty-content fallback.
    AppIcon,
    /// Draw the usage bars.
    Chart,
    /// Draw provider logos and starred metric values.
    Logos,
}

/// The menu-bar look chosen in Settings → Menu Bar → Menu Bar Shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum MenuBarLook {
    /// The usage bars (default).
    Chart,
    /// Each provider's logo followed by its starred values.
    Logos,
    /// Each provider's short name (`cld`, `cdx`, …) followed by its starred
    /// values, the way the Quattro and Waybar bars tag a provider.
    Name,
}

impl MenuBarLook {
    /// Read `[tray] menu_bar_style`. Anything unrecognised keeps the chart, so
    /// a config written by a newer build never blanks the status item.
    pub(super) fn from_style(style: Option<&str>) -> Self {
        match style {
            Some("provider") => Self::Logos,
            Some("name") => Self::Name,
            _ => Self::Chart,
        }
    }

    /// The `[tray] menu_bar_style` value persisted for this look.
    pub(super) fn style(self) -> &'static str {
        match self {
            Self::Chart => "bars",
            Self::Logos => "provider",
            Self::Name => "name",
        }
    }

    /// The value the popover's picker uses for this look.
    pub(super) fn picker_value(self) -> &'static str {
        match self {
            Self::Chart => "chart",
            Self::Logos => "logos",
            Self::Name => "name",
        }
    }

    /// Parse the popover's picker value.
    pub(super) fn from_picker_value(value: &str) -> Option<Self> {
        match value {
            "chart" => Some(Self::Chart),
            "logos" => Some(Self::Logos),
            "name" => Some(Self::Name),
            _ => None,
        }
    }
}

/// Select status-item artwork, falling back to the app icon when content is empty.
pub(super) fn status_item_content(look: MenuBarLook, has_content: bool) -> StatusItemContent {
    if !has_content {
        StatusItemContent::AppIcon
    } else if look == MenuBarLook::Chart {
        StatusItemContent::Chart
    } else {
        StatusItemContent::Logos
    }
}

/// How the popover reads a quota (Preferences → Show Usage As). The menu
/// bar's percentages follow it, so the chip says `82%` left when the tab
/// that selects it does, not the `18%` used behind it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum UsageReading {
    Used,
    Left,
}

impl UsageReading {
    /// Read the `strip` IPC's `show_as`. Anything else keeps used, the
    /// reading the menu bar had before the popover reports one.
    pub(super) fn from_strip_ipc(value: &Value) -> Self {
        match value.get("show_as").and_then(Value::as_str) {
            Some("left") => Self::Left,
            _ => Self::Used,
        }
    }
}

/// A metric's text in `reading`: its remaining share in Left when it has a
/// percent, its report value otherwise.
fn metric_text(metric: &StripMetric, reading: UsageReading) -> &str {
    match (reading, metric.left_value.as_deref()) {
        (UsageReading::Left, Some(left)) => left,
        _ => metric.value.trim(),
    }
}

/// One entry of the emergency menu attached to the status item when the
/// popover's WKWebView could not be built (#249).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct FallbackItem {
    /// muda menu id the host matches `MenuEvent`s against.
    pub(super) id: &'static str,
    pub(super) label: &'static str,
}

/// The fallback status-item menu for the webview-less tray (#249): an
/// accessory app (no Dock icon, no app menu) otherwise has no quit affordance
/// short of `killall`. Refresh stays because the status-item readout works
/// without the webview; Quit terminates through the same loop exit the
/// popover's own Quit control uses.
pub(super) fn fallback_menu_items() -> [FallbackItem; 2] {
    [
        FallbackItem {
            id: "fallback-refresh",
            label: "Refresh",
        },
        FallbackItem {
            id: "fallback-quit",
            label: "Quit AI Usage",
        },
    ]
}

/// The fallback menu exists **only** while the popover's webview is absent.
/// Normal operation keeps the status item menu-free (see `build_tray`) so
/// both mouse buttons reach the popover; attaching a menu makes AppKit
/// intercept clicks, which is exactly the trade wanted when there is no
/// popover to open.
pub(super) fn fallback_menu_attached(webview_built: bool) -> bool {
    !webview_built
}

/// One provider's visible logo (or short name) and starred values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct LogoSegment {
    /// Lowercase provider slug used to find its embedded mark.
    pub(super) slug: String,
    /// Report short name, drawn when the mark cannot be drawn, or beside it
    /// when `with_name` is set.
    pub(super) short_name: Option<String>,
    /// The name look: draw `short_name` after the mark rather than only
    /// where the mark is missing.
    pub(super) with_name: bool,
    /// Non-empty metric values in star order; their count is the rendered line count.
    pub(super) values: Vec<String>,
}

/// Build logo segments from the same starred metric groups used by the chart.
/// The name look keeps one provider, `selected` or its fallbacks, and its
/// highest window, like the Quattro bar's `icon SHORT 54%` chip, with the short name
/// beside the mark unless `show_short_name` is off; the logos look keeps
/// every group with up to two stacked values.
pub(super) fn logo_segments(
    content: &StripContent,
    report: &Value,
    look: MenuBarLook,
    selected: Option<&str>,
    show_short_name: bool,
    reading: UsageReading,
) -> Vec<LogoSegment> {
    if look == MenuBarLook::Name {
        return name_segment(content, report, selected, show_short_name, reading)
            .into_iter()
            .collect();
    }
    content
        .groups
        .iter()
        .filter_map(|(id, _, metrics)| segment(id, metrics, report, 2, false, reading))
        .collect()
}

/// The name look's one chip, for the popover's selected provider, else the
/// report's `primary`, else the first starred group, skipping any without a
/// value. Its value comes from every quota window of that provider, stars
/// aside, like the Quattro bar and the popover tab that selects it.
fn name_segment(
    content: &StripContent,
    report: &Value,
    selected: Option<&str>,
    show_short_name: bool,
    reading: UsageReading,
) -> Option<LogoSegment> {
    let primary = report.get("primary").and_then(Value::as_str);
    let starred = content.groups.iter().map(|(id, _, _)| id.as_str());
    [selected, primary]
        .into_iter()
        .flatten()
        .chain(starred)
        .find_map(|id| {
            let (id, _, metrics) = quota_group(report, id)?;
            name_chip(&id, &metrics, report, show_short_name, reading)
        })
}

/// The chip shows the provider's highest-percent metric, like the Quattro
/// bar's default `auto` window (`omarchy/Model.js` `maxPercent`): a spent
/// weekly window must not hide behind an idle 5h session reading 0%.
/// Without `show_short_name` the mark stands alone, like the logos look,
/// which still falls back to the name for a provider with no mark.
fn name_chip(
    id: &str,
    metrics: &[StripMetric],
    report: &Value,
    show_short_name: bool,
    reading: UsageReading,
) -> Option<LogoSegment> {
    let highest = highest_metric(metrics)?;
    segment(
        id,
        std::slice::from_ref(highest),
        report,
        1,
        show_short_name,
        reading,
    )
}

/// The bounded metric with the largest used fraction, the first one on a
/// tie; the first metric with a value when none is bounded.
fn highest_metric(metrics: &[StripMetric]) -> Option<&StripMetric> {
    let shown = || metrics.iter().filter(|m| !m.value.trim().is_empty());
    let highest_bounded =
        shown()
            .filter(|m| m.bounded)
            .fold(None, |best: Option<&StripMetric>, m| match best {
                Some(best) if best.fraction >= m.fraction => Some(best),
                _ => Some(m),
            });
    highest_bounded.or_else(|| shown().next())
}

/// One provider's segment: up to `value_cap` non-empty values in `reading`,
/// or `None` when it has no value or no usable slug.
fn segment(
    id: &str,
    metrics: &[StripMetric],
    report: &Value,
    value_cap: usize,
    with_name: bool,
    reading: UsageReading,
) -> Option<LogoSegment> {
    let values: Vec<String> = metrics
        .iter()
        .map(|metric| metric_text(metric, reading))
        .filter(|value| !value.is_empty())
        .map(str::to_owned)
        .take(value_cap)
        .collect();
    if values.is_empty() {
        return None;
    }
    let slug = id.split('@').next()?.to_ascii_lowercase();
    if slug.is_empty() {
        return None;
    }
    Some(LogoSegment {
        slug,
        short_name: short_name_for(report, id),
        with_name,
        values,
    })
}

/// Build tooltip lines for the starred groups in `reading`, or the app name
/// when none have values.
pub(super) fn tooltip(content: &StripContent, reading: UsageReading) -> String {
    let lines: Vec<String> = content
        .groups
        .iter()
        .filter_map(|(_, name, metrics)| {
            let values: Vec<&str> = metrics
                .iter()
                .map(|metric| metric_text(metric, reading))
                .filter(|value| !value.is_empty())
                .collect();
            if values.is_empty() {
                return None;
            }
            Some(format!("{} · {}", safe_text(name), values.join(" ")))
        })
        .collect();
    if lines.is_empty() {
        "AI Usage".into()
    } else {
        lines.join("\n")
    }
}

fn short_name_for(report: &Value, id: &str) -> Option<String> {
    report
        .get("entries")?
        .as_array()?
        .iter()
        .find(|entry| entry.get("id").and_then(Value::as_str) == Some(id))?
        .get("short_name")?
        .as_str()
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .map(safe_text)
}

fn safe_text(value: &str) -> String {
    value
        .chars()
        .filter(|c| !c.is_control())
        .collect::<String>()
        .trim()
        .to_owned()
}

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

    #[test]
    fn empty_modes_fall_back_to_static_app_icon() {
        for look in [MenuBarLook::Chart, MenuBarLook::Logos, MenuBarLook::Name] {
            assert_eq!(
                status_item_content(look, false),
                StatusItemContent::AppIcon,
                "{look:?}"
            );
        }
        assert_eq!(
            status_item_content(MenuBarLook::Chart, true),
            StatusItemContent::Chart
        );
        assert_eq!(
            status_item_content(MenuBarLook::Logos, true),
            StatusItemContent::Logos
        );
        // Name reuses the strip image: only the label differs from Logos.
        assert_eq!(
            status_item_content(MenuBarLook::Name, true),
            StatusItemContent::Logos
        );
    }

    #[test]
    fn menu_bar_look_round_trips_through_config_and_picker() {
        for look in [MenuBarLook::Chart, MenuBarLook::Logos, MenuBarLook::Name] {
            assert_eq!(MenuBarLook::from_style(Some(look.style())), look);
            assert_eq!(
                MenuBarLook::from_picker_value(look.picker_value()),
                Some(look)
            );
        }
    }

    /// An unset, unknown or future `menu_bar_style` keeps the chart default.
    #[test]
    fn menu_bar_look_defaults_to_the_chart() {
        assert_eq!(MenuBarLook::from_style(None), MenuBarLook::Chart);
        assert_eq!(MenuBarLook::from_style(Some("bars")), MenuBarLook::Chart);
        assert_eq!(
            MenuBarLook::from_style(Some("sparkles")),
            MenuBarLook::Chart
        );
        assert_eq!(MenuBarLook::from_picker_value("sparkles"), None);
    }

    /// #249: the emergency menu attaches only when the webview is absent, so
    /// normal operation — menu-free status item, clicks open the popover — is
    /// untouched.
    #[test]
    fn fallback_menu_attaches_only_without_the_webview() {
        assert!(!fallback_menu_attached(true));
        assert!(fallback_menu_attached(false));
    }

    /// The host matches `MenuEvent` ids against these strings, so they must be
    /// unique and Quit must be the terminal action of the menu.
    #[test]
    fn fallback_menu_items_have_unique_nonempty_ids_ending_in_quit() {
        let items = fallback_menu_items();
        assert!(items.iter().all(|item| !item.id.is_empty()));
        assert!(items.iter().all(|item| !item.label.is_empty()));
        let ids: Vec<&str> = items.iter().map(|item| item.id).collect();
        let mut unique = ids.clone();
        unique.sort_unstable();
        unique.dedup();
        assert_eq!(ids.len(), unique.len(), "ids must be unique: {ids:?}");
        assert_eq!(items[items.len() - 1].id, "fallback-quit");
        assert_eq!(items[0].id, "fallback-refresh");
    }

    #[test]
    fn logo_segments_keep_one_star_value_and_use_star_order() {
        let content = StripContent {
            groups: vec![
                ("anthropic".into(), "Claude".into(), vec![metric("41%")]),
                (
                    "openai".into(),
                    "Codex".into(),
                    vec![metric("9%"), metric("5%")],
                ),
            ],
            bars: Vec::new(),
        };
        let report = json!({"entries":[]});

        let segments = logo_segments(
            &content,
            &report,
            MenuBarLook::Logos,
            None,
            true,
            UsageReading::Used,
        );
        assert_eq!(segments.len(), 2);
        assert_eq!(segments[0].slug, "anthropic");
        assert_eq!(segments[0].values, vec![String::from("41%")]);
        assert_eq!(segments[1].slug, "openai");
        assert_eq!(
            segments[1].values,
            vec![String::from("9%"), String::from("5%")]
        );
    }

    #[test]
    fn logo_segments_skip_groups_without_values() {
        let content = StripContent {
            groups: vec![
                ("cursor".into(), "Cursor".into(), vec![metric("  ")]),
                ("zai".into(), "Z.AI".into(), vec![metric("12%")]),
            ],
            bars: Vec::new(),
        };

        let segments = logo_segments(
            &content,
            &json!({"entries":[]}),
            MenuBarLook::Logos,
            None,
            true,
            UsageReading::Used,
        );
        assert_eq!(segments.len(), 1);
        assert_eq!(segments[0].slug, "zai");
        assert_eq!(segments[0].values, vec![String::from("12%")]);
    }

    #[test]
    fn content_without_metric_values_stays_empty_in_both_modes() {
        let report = json!({"entries":[
            {"id":"claude", "display_name":"Claude", "sections":[
                {"type":"metric", "label":"Weekly"}
            ]}
        ]});
        let content = super::super::strip::content_from_payload(
            &report,
            &super::super::strip::Stars::new(),
            &[],
        );

        assert!(content.groups.is_empty());
        assert!(content.bars.is_empty());
        assert!(
            logo_segments(
                &content,
                &report,
                MenuBarLook::Logos,
                None,
                true,
                UsageReading::Used
            )
            .is_empty()
        );
    }

    #[test]
    fn logo_segments_use_report_short_name_when_mark_is_unknown() {
        let content = StripContent {
            groups: vec![(
                "unknown@work".into(),
                "Unknown Provider".into(),
                vec![metric("8%")],
            )],
            bars: Vec::new(),
        };
        let report = json!({"entries":[
            {"id":"unknown@work", "short_name":"unk"}
        ]});

        let segments = logo_segments(
            &content,
            &report,
            MenuBarLook::Logos,
            None,
            true,
            UsageReading::Used,
        );
        assert_eq!(segments[0].slug, "unknown");
        assert!(super::super::marks::mark_svg(&segments[0].slug).is_none());
        assert_eq!(segments[0].short_name.as_deref(), Some("unk"));
    }

    /// A ready report entry with one metric section per `(label, percent)`.
    fn entry(id: &str, short_name: &str, windows: &[(&str, f64)]) -> Value {
        let sections: Vec<Value> = windows
            .iter()
            .map(|(label, percent)| {
                json!({"type":"metric", "label":label, "percent":percent,
                       "value":format!("{percent}%")})
            })
            .collect();
        json!({"id":id, "short_name":short_name, "status":"ready", "sections":sections})
    }

    /// Strip content where each provider has one starred metric, in order.
    fn starred(ids: &[&str]) -> StripContent {
        StripContent {
            groups: ids
                .iter()
                .map(|id| (id.to_string(), id.to_string(), vec![metric("1%")]))
                .collect(),
            bars: Vec::new(),
        }
    }

    /// The name look keeps the mark and adds the short name beside it; the
    /// logos look keeps the mark alone.
    #[test]
    fn name_look_adds_the_short_name_beside_the_mark() {
        let content = starred(&["anthropic"]);
        let report = json!({"entries":[entry("anthropic", "cld", &[("Session", 41.0)])]});

        let chip = logo_segments(
            &content,
            &report,
            MenuBarLook::Name,
            None,
            true,
            UsageReading::Used,
        );
        assert!(chip[0].with_name);
        assert_eq!(chip[0].short_name.as_deref(), Some("cld"));
        assert!(super::super::marks::mark_svg(&chip[0].slug).is_some());

        let logos = logo_segments(
            &content,
            &report,
            MenuBarLook::Logos,
            None,
            true,
            UsageReading::Used,
        );
        assert!(!logos[0].with_name);
    }

    /// With the short name turned off the chip is the mark and the value; a
    /// provider with no mark still gets its name, since nothing else would
    /// tell which provider the value belongs to.
    #[test]
    fn name_look_can_leave_out_the_short_name() {
        let content = starred(&["kimi", "unknown"]);
        let report = json!({"primary":null,"entries":[
            entry("kimi", "kmi", &[("Weekly", 42.0)]),
            entry("unknown", "unk", &[("Usage", 8.0)]),
        ]});

        let chip = logo_segments(
            &content,
            &report,
            MenuBarLook::Name,
            Some("kimi"),
            false,
            UsageReading::Used,
        );
        assert!(!chip[0].with_name);
        assert!(super::super::marks::mark_svg(&chip[0].slug).is_some());
        assert_eq!(chip[0].values, vec![String::from("42%")]);

        let shown = logo_segments(
            &content,
            &report,
            MenuBarLook::Name,
            Some("kimi"),
            true,
            UsageReading::Used,
        );
        assert!(shown[0].with_name);

        let unmarked = logo_segments(
            &content,
            &report,
            MenuBarLook::Name,
            Some("unknown"),
            false,
            UsageReading::Used,
        );
        assert!(super::super::marks::mark_svg(&unmarked[0].slug).is_none());
        assert_eq!(unmarked[0].short_name.as_deref(), Some("unk"));
    }

    fn two_groups() -> StripContent {
        StripContent {
            groups: vec![
                (
                    "anthropic".into(),
                    "Claude".into(),
                    vec![metric("54%"), metric("16%")],
                ),
                ("openai".into(), "Codex".into(), vec![metric("100%")]),
            ],
            bars: Vec::new(),
        }
    }

    fn two_entries(primary: Option<&str>) -> Value {
        json!({"primary":primary, "entries":[
            entry("anthropic", "cld", &[("Session", 54.0), ("Weekly", 16.0)]),
            entry("openai", "gpt", &[("Session", 100.0)]),
        ]})
    }

    /// Quattro draws one chip for the selected provider: one provider and one
    /// value, where the logos look stacks two values for every provider.
    #[test]
    fn name_look_shows_only_the_selected_provider_and_one_value() {
        let report = two_entries(Some("anthropic"));
        let chip = |selected| {
            logo_segments(
                &two_groups(),
                &report,
                MenuBarLook::Name,
                selected,
                true,
                UsageReading::Used,
            )
        };

        let codex = chip(Some("openai"));
        assert_eq!(codex.len(), 1);
        assert_eq!(codex[0].slug, "openai");
        assert_eq!(codex[0].values, vec![String::from("100%")]);
        assert_eq!(chip(Some("anthropic"))[0].values, vec![String::from("54%")]);

        let logos = logo_segments(
            &two_groups(),
            &report,
            MenuBarLook::Logos,
            Some("openai"),
            true,
            UsageReading::Used,
        );
        assert_eq!(logos.len(), 2);
        assert_eq!(logos[0].values.len(), 2);
    }

    /// Before the popover reports a selection the report's `primary` stands
    /// in, then the first starred provider; a stale selection (the provider
    /// was disabled) falls through the same way.
    #[test]
    fn name_look_falls_back_from_selection_to_primary_to_first() {
        let slug = |report: &Value, selected: Option<&str>| {
            logo_segments(
                &two_groups(),
                report,
                MenuBarLook::Name,
                selected,
                true,
                UsageReading::Used,
            )[0]
            .slug
            .clone()
        };

        assert_eq!(slug(&two_entries(Some("openai")), None), "openai");
        assert_eq!(slug(&two_entries(Some("openai")), Some("gone")), "openai");
        assert_eq!(slug(&two_entries(None), None), "anthropic");
        assert_eq!(slug(&two_entries(None), Some("gone")), "anthropic");
    }

    /// Stars do not decide the name look: a selected provider with nothing
    /// starred draws its own chip, never the primary's.
    #[test]
    fn name_look_shows_a_selected_provider_that_has_no_star() {
        let report = json!({"primary":"zai","entries":[
            entry("zai", "zai", &[("Session", 0.0)]),
            entry("supergrok", "sgk", &[("Weekly usage", 7.0)]),
        ]});
        let content = starred(&["zai"]);

        let chip = logo_segments(
            &content,
            &report,
            MenuBarLook::Name,
            Some("supergrok"),
            true,
            UsageReading::Used,
        );
        assert_eq!(chip.len(), 1);
        assert_eq!(chip[0].slug, "supergrok");
        assert_eq!(chip[0].short_name.as_deref(), Some("sgk"));
        assert_eq!(chip[0].values, vec![String::from("7%")]);

        let unselected = logo_segments(
            &content,
            &report,
            MenuBarLook::Name,
            None,
            true,
            UsageReading::Used,
        );
        assert_eq!(unselected[0].slug, "zai");
    }

    /// A provider with no value, or one whose fetch failed, is not a
    /// candidate, so the name look never draws a bare name with no number.
    #[test]
    fn name_look_skips_a_selected_provider_without_a_value() {
        let report = json!({"primary":null,"entries":[
            {"id":"cursor", "status":"ready", "sections":[{"type":"metric", "label":"Usage"}]},
            {"id":"kimi", "status":"error", "sections":[
                {"type":"metric", "label":"Weekly", "percent":40, "value":"40%"}]},
            entry("zai", "zai", &[("Session", 12.0)]),
        ]});
        let content = starred(&["cursor", "kimi", "zai"]);

        for selected in ["cursor", "kimi"] {
            let segments = logo_segments(
                &content,
                &report,
                MenuBarLook::Name,
                Some(selected),
                true,
                UsageReading::Used,
            );
            assert_eq!(segments.len(), 1);
            assert_eq!(segments[0].slug, "zai");
        }
    }

    #[test]
    fn tooltip_lists_each_starred_group_and_uses_generic_empty_text() {
        let content = StripContent {
            groups: vec![
                (
                    "anthropic".into(),
                    "Claude".into(),
                    vec![metric("41%"), metric("5%")],
                ),
                ("openai".into(), "Codex".into(), vec![metric("9%")]),
                ("cursor".into(), "Cursor".into(), vec![metric("")]),
            ],
            bars: Vec::new(),
        };

        assert_eq!(
            tooltip(&content, UsageReading::Used),
            "Claude · 41% 5%\nCodex · 9%"
        );
        assert_eq!(
            tooltip(
                &StripContent {
                    groups: Vec::new(),
                    bars: Vec::new(),
                },
                UsageReading::Used
            ),
            "AI Usage"
        );
    }

    fn metric(value: &str) -> super::super::strip::StripMetric {
        super::super::strip::StripMetric {
            provider_id: String::new(),
            provider_name: String::new(),
            key: String::new(),
            label: String::new(),
            value: value.to_owned(),
            fraction: 0.0,
            bounded: true,
            left_value: None,
            grouped: false,
        }
    }

    fn used(value: &str, fraction: f64) -> super::super::strip::StripMetric {
        super::super::strip::StripMetric {
            fraction,
            ..metric(value)
        }
    }

    /// Like Quattro's `auto` window the chip shows the highest percent among
    /// every quota window, stars aside: a spent weekly window reads `100%`
    /// over an idle 5h session, and Z.AI's third, monthly MCP window at 18%
    /// reads `18%` over two at 0%. The logos look keeps the starred values.
    #[test]
    fn name_look_shows_the_highest_quota_window() {
        let chip = |zai: Value| {
            let report = json!({"primary":null, "entries":[zai]});
            logo_segments(
                &starred(&["zai"]),
                &report,
                MenuBarLook::Name,
                Some("zai"),
                true,
                UsageReading::Used,
            )[0]
            .values
            .clone()
        };
        let spent_weekly = entry("zai", "zai", &[("Session (5h)", 0.0), ("Weekly", 100.0)]);
        assert_eq!(chip(spent_weekly), vec![String::from("100%")]);
        let monthly_third = entry(
            "zai",
            "zai",
            &[
                ("Session (5h)", 0.0),
                ("Weekly", 0.0),
                ("MCP tools (monthly)", 18.0),
            ],
        );
        assert_eq!(chip(monthly_third), vec![String::from("18%")]);
        let balance_first = json!({"id":"zai", "status":"ready", "sections":[
            {"type":"metric", "label":"Balance", "value":"$40"},
            {"type":"metric", "label":"Weekly", "percent":12, "value":"12%"}]});
        assert_eq!(chip(balance_first), vec![String::from("12%")]);

        let starred_session = StripContent {
            groups: vec![("zai".into(), "Z.AI".into(), vec![used("0%", 0.0)])],
            bars: Vec::new(),
        };
        let logos = logo_segments(
            &starred_session,
            &json!({"entries":[]}),
            MenuBarLook::Logos,
            None,
            true,
            UsageReading::Used,
        );
        assert_eq!(logos[0].values, vec![String::from("0%")]);
    }

    /// A grouped row (Claude's CLI sessions, SuperGrok's product slices) is a
    /// breakdown, not a window: it never outranks one, like Quattro's
    /// `selectMetric`, and stands in only when the provider has nothing else.
    #[test]
    fn name_look_ranks_grouped_rows_only_without_a_window() {
        let report = json!({"primary":null, "entries":[
            {"id":"anthropic", "status":"ready", "sections":[
                {"type":"metric", "label":"Session", "percent":0, "value":"0%"},
                {"type":"metric", "label":"cli-1", "group":"Sessions", "percent":90, "value":"90%"}]},
            {"id":"supergrok", "status":"ready", "sections":[
                {"type":"metric", "label":"Grok", "group":"Products", "percent":7, "value":"7%"}]},
        ]});
        let content = starred(&["anthropic", "supergrok"]);
        let value = |selected| {
            logo_segments(
                &content,
                &report,
                MenuBarLook::Name,
                Some(selected),
                true,
                UsageReading::Used,
            )[0]
            .values
            .clone()
        };

        assert_eq!(value("anthropic"), vec![String::from("0%")]);
        assert_eq!(value("supergrok"), vec![String::from("7%")]);
    }

    /// In the popover's Left reading the menu bar says what is left, like the
    /// tab that selects the chip: Z.AI's monthly window at 18% used reads
    /// `82%`. The chip still picks the most-used window, so `82%` is the
    /// tightest one. A value with no percent reads the same either way.
    #[test]
    fn menu_bar_text_follows_the_left_reading() {
        let report = json!({"primary":null, "entries":[
            entry("zai", "zai", &[("Session (5h)", 0.0), ("Weekly", 0.0), ("MCP tools (monthly)", 18.0)]),
            {"id":"openrouter", "status":"ready", "sections":[
                {"type":"metric", "label":"Balance", "value":"$40"}]},
        ]});
        let content = super::super::strip::content_from_payload(
            &report,
            &super::super::strip::Stars::new(),
            &[],
        );
        let chip = |selected, reading| {
            logo_segments(
                &content,
                &report,
                MenuBarLook::Name,
                Some(selected),
                true,
                reading,
            )[0]
            .values
            .clone()
        };

        assert_eq!(chip("zai", UsageReading::Left), vec![String::from("82%")]);
        assert_eq!(chip("zai", UsageReading::Used), vec![String::from("18%")]);
        assert_eq!(
            chip("openrouter", UsageReading::Left),
            vec![String::from("$40")]
        );

        let logos = logo_segments(
            &content,
            &report,
            MenuBarLook::Logos,
            None,
            true,
            UsageReading::Left,
        );
        assert_eq!(
            logos[0].values,
            vec![String::from("100%"), String::from("100%")]
        );
        assert_eq!(
            tooltip(&content, UsageReading::Left),
            "zai · 100% 100%\nopenrouter · $40"
        );
    }

    /// The popover sends `show_as` with every `strip` message; an older or
    /// unknown value keeps the used reading the menu bar always had.
    #[test]
    fn usage_reading_comes_from_the_strip_ipc() {
        let reading = |value: Value| UsageReading::from_strip_ipc(&value);
        assert_eq!(reading(json!({"show_as":"left"})), UsageReading::Left);
        assert_eq!(reading(json!({"show_as":"used"})), UsageReading::Used);
        assert_eq!(reading(json!({"show_as":"sideways"})), UsageReading::Used);
        assert_eq!(reading(json!({})), UsageReading::Used);
    }
}