Skip to main content

ai_usagebar/widget/
render.rs

1//! Pango-markup rendering for the Anthropic widget — both the bar text and
2//! the bordered tooltip.
3//!
4//! Closely mirrors claudebar:625-860. Pure functions over an immutable
5//! [`RenderInput`] so all of the visual logic is unit-testable without I/O.
6
7use std::collections::HashMap;
8
9use chrono::{DateTime, Utc};
10
11use crate::anthropic::fetch::FetchOutcome;
12use crate::countdown;
13use crate::format::{placeholders, substitute, updated_at_hm};
14use crate::pacing;
15use crate::pango::{self, color_span, escape, severity_for};
16use crate::theme::Theme;
17use crate::tooltip::{self, Line};
18use crate::usage::anthropic_severity;
19use crate::waybar::{Class, WaybarOutput};
20
21/// Default format string when `--format` is omitted (claudebar:55).
22pub const DEFAULT_FORMAT: &str = "{session_pct}% · {session_reset}";
23
24/// All inputs needed to render the widget — packaged so tests can construct
25/// it without any I/O.
26pub struct RenderInput<'a> {
27    pub outcome: &'a FetchOutcome,
28    pub theme: &'a Theme,
29    pub format: &'a str,
30    pub tooltip_format: Option<&'a str>,
31    pub icon: Option<&'a str>,
32    pub pace_tolerance: u32,
33    pub format_pace_color: bool,
34    pub tooltip_pace_pts: bool,
35    pub now: DateTime<Utc>,
36}
37
38/// Compose the full Waybar output for an Anthropic snapshot.
39pub fn render_anthropic(input: &RenderInput) -> WaybarOutput {
40    let snap = &input.outcome.snapshot;
41    let class = Class::from(anthropic_severity(snap));
42    let bar_text = render_bar_text(input, class);
43    let tooltip = if let Some(fmt) = input.tooltip_format {
44        // Custom tooltip uses the same placeholder set as the bar.
45        let values = build_placeholders(input);
46        substitute(fmt, &values)
47    } else {
48        render_default_tooltip(input)
49    };
50
51    WaybarOutput {
52        text: bar_text,
53        tooltip,
54        class,
55    }
56}
57
58/// Build the bar-text string with all placeholders substituted and the
59/// surrounding `<span foreground='…'>` wrapper applied.
60fn render_bar_text(input: &RenderInput, class: Class) -> String {
61    let values = build_placeholders(input);
62    let mut text = substitute(input.format, &values);
63
64    // Append stale indicator (claudebar:687-690).
65    if input.outcome.stale {
66        text.push_str(" ⏸");
67    }
68
69    // Wrap in the global color or the neutral foreground (when individual
70    // pace placeholders supply their own color via --format-pace-color).
71    let wrapper_color = if input.format_pace_color && input.format.contains("_pace") {
72        input.theme.fg.clone()
73    } else {
74        bar_color_for(class, input.theme).to_string()
75    };
76    let icon_prefix = match input.icon {
77        Some(ic) if !ic.is_empty() => format!("{ic} "),
78        _ => String::new(),
79    };
80    color_span(&wrapper_color, &format!("{icon_prefix}{text}"))
81}
82
83fn bar_color_for(class: Class, theme: &Theme) -> &str {
84    match class {
85        Class::Low => &theme.green,
86        Class::Mid => &theme.yellow,
87        Class::High => &theme.orange,
88        Class::Critical => &theme.red,
89    }
90}
91
92/// Build the full placeholder map for an Anthropic snapshot.
93///
94/// Mirrors claudebar's "{...}" surface (claudebar:625-667). Per-window pacing
95/// is pre-computed once; bars are rendered both raw (for `{*_bar}`) and with
96/// elapsed-position markers in the tooltip when `--tooltip-pace-pts` is set.
97fn build_placeholders(input: &RenderInput) -> HashMap<&'static str, String> {
98    let snap = &input.outcome.snapshot;
99    let theme = input.theme;
100
101    let session = pacing::calc(
102        snap.session.utilization_pct,
103        snap.session.resets_at,
104        input.now,
105        snap.session.window_duration,
106        input.pace_tolerance,
107    );
108    let weekly = pacing::calc(
109        snap.weekly.utilization_pct,
110        snap.weekly.resets_at,
111        input.now,
112        snap.weekly.window_duration,
113        input.pace_tolerance,
114    );
115    let sonnet_window = snap.sonnet.as_ref();
116    let sonnet = sonnet_window.map(|w| {
117        pacing::calc(
118            w.utilization_pct,
119            w.resets_at,
120            input.now,
121            w.window_duration,
122            input.pace_tolerance,
123        )
124    });
125
126    let session_color = pango::severity_color(severity_for(snap.session.utilization_pct), theme);
127    let weekly_color = pango::severity_color(severity_for(snap.weekly.utilization_pct), theme);
128    let sonnet_color =
129        sonnet_window.map(|w| pango::severity_color(severity_for(w.utilization_pct), theme));
130    let extra_color = snap
131        .extra
132        .as_ref()
133        .map(|e| pango::severity_color(severity_for(e.percent()), theme));
134
135    let session_bar = pango::progress_bar(snap.session.utilization_pct, session_color, theme, None);
136    let weekly_bar = pango::progress_bar(snap.weekly.utilization_pct, weekly_color, theme, None);
137    let sonnet_bar = if let (Some(w), Some(c)) = (sonnet_window, sonnet_color) {
138        pango::progress_bar(w.utilization_pct, c, theme, None)
139    } else {
140        String::new()
141    };
142    let extra_bar = if let (Some(e), Some(c)) = (snap.extra.as_ref(), extra_color) {
143        pango::progress_bar(e.percent(), c, theme, None)
144    } else {
145        String::new()
146    };
147
148    // Primary model-scoped weekly window (the common case is exactly one, e.g.
149    // "Fable"). The tooltip renders every entry of `snap.scoped`, but the
150    // desktop surfaces (macOS menu bar, GNOME, Windows tray) redraw from
151    // `--format` and have a single per-model row — so expose the first scoped
152    // window through flat `{scoped_*}` placeholders they can read. Empty /
153    // neutral when the account has no scoped window.
154    let scoped0 = snap.scoped.first();
155    let scoped0_pacing = scoped0.map(|s| {
156        pacing::calc(
157            s.window.utilization_pct,
158            s.window.resets_at,
159            input.now,
160            s.window.window_duration,
161            input.pace_tolerance,
162        )
163    });
164    let scoped0_bar = if let Some(s) = scoped0 {
165        let c = pango::severity_color(severity_for(s.window.utilization_pct), theme);
166        pango::progress_bar(s.window.utilization_pct, c, theme, None)
167    } else {
168        String::new()
169    };
170
171    let mut v = placeholders(vec![
172        ("icon", "󰚩".to_string()),
173        ("vendor_short", "cld".to_string()),
174        ("plan", snap.plan.clone()),
175        ("session_pct", snap.session.utilization_pct.to_string()),
176        (
177            "session_reset",
178            countdown::format(snap.session.resets_at, input.now),
179        ),
180        ("session_elapsed", session.elapsed_pct.to_string()),
181        ("session_bar", session_bar.clone()),
182        ("weekly_pct", snap.weekly.utilization_pct.to_string()),
183        (
184            "weekly_reset",
185            countdown::format(snap.weekly.resets_at, input.now),
186        ),
187        ("weekly_elapsed", weekly.elapsed_pct.to_string()),
188        ("weekly_bar", weekly_bar.clone()),
189        (
190            "sonnet_pct",
191            sonnet_window
192                .map(|w| w.utilization_pct.to_string())
193                .unwrap_or_else(|| "0".into()),
194        ),
195        (
196            "sonnet_reset",
197            sonnet_window
198                .map(|w| countdown::format(w.resets_at, input.now))
199                .unwrap_or_else(|| "—".into()),
200        ),
201        (
202            "sonnet_elapsed",
203            sonnet
204                .as_ref()
205                .map(|s| s.elapsed_pct.to_string())
206                .unwrap_or_else(|| "0".into()),
207        ),
208        ("sonnet_bar", sonnet_bar.clone()),
209        // Model-scoped weekly window (first entry of `snap.scoped`, e.g. Fable).
210        (
211            "scoped_model",
212            scoped0.map(|s| s.label.clone()).unwrap_or_default(),
213        ),
214        (
215            "scoped_pct",
216            scoped0
217                .map(|s| s.window.utilization_pct.to_string())
218                .unwrap_or_else(|| "0".into()),
219        ),
220        (
221            "scoped_reset",
222            scoped0
223                .map(|s| countdown::format(s.window.resets_at, input.now))
224                .unwrap_or_else(|| "—".into()),
225        ),
226        (
227            "scoped_elapsed",
228            scoped0_pacing
229                .as_ref()
230                .map(|p| p.elapsed_pct.to_string())
231                .unwrap_or_else(|| "0".into()),
232        ),
233        ("scoped_bar", scoped0_bar.clone()),
234        (
235            "extra_spent",
236            snap.extra
237                .map(|e| e.spent.fmt_dollars())
238                .unwrap_or_default(),
239        ),
240        (
241            "extra_limit",
242            snap.extra
243                .map(|e| e.limit.fmt_dollars())
244                .unwrap_or_default(),
245        ),
246        (
247            "extra_pct",
248            snap.extra
249                .map(|e| e.percent().to_string())
250                .unwrap_or_else(|| "0".into()),
251        ),
252        ("extra_bar", extra_bar),
253    ]);
254
255    insert_pace(&mut v, "session", &session, input.format_pace_color, theme);
256    insert_pace(&mut v, "weekly", &weekly, input.format_pace_color, theme);
257    if let Some(sp) = sonnet.as_ref() {
258        insert_pace(&mut v, "sonnet", sp, input.format_pace_color, theme);
259    } else {
260        // Empty placeholders so `{sonnet_pace}` etc. don't render the literal
261        // brace text when sonnet is absent.
262        insert_pace(
263            &mut v,
264            "sonnet",
265            &pacing::Pacing::neutral(),
266            input.format_pace_color,
267            theme,
268        );
269    }
270    v
271}
272
273fn insert_pace(
274    map: &mut HashMap<&'static str, String>,
275    prefix: &'static str,
276    p: &pacing::Pacing,
277    pace_color: bool,
278    theme: &Theme,
279) {
280    let pace_glyph = p.ratio_pace.glyph();
281    let indicator_glyph = p.point_pace.glyph();
282    let delta = p.delta.to_string();
283    let abs_delta = p.delta.unsigned_abs().to_string();
284    let pct = &p.ratio_label;
285    let pts = &p.point_label;
286
287    let wrap = |s: &str| -> String {
288        if pace_color {
289            let sev = pacing::pace_severity(p.delta);
290            let color = pango::severity_color(sev, theme);
291            color_span(color, s)
292        } else {
293            s.to_string()
294        }
295    };
296
297    let keys: [(&'static str, String); 6] = match prefix {
298        "session" => [
299            ("session_pace", wrap(pace_glyph)),
300            ("session_pace_indicator", wrap(indicator_glyph)),
301            ("session_pace_pct", wrap(pct)),
302            ("session_pace_pts", wrap(pts)),
303            ("session_pace_delta", wrap(&delta)),
304            ("session_pace_abs_delta", wrap(&abs_delta)),
305        ],
306        "weekly" => [
307            ("weekly_pace", wrap(pace_glyph)),
308            ("weekly_pace_indicator", wrap(indicator_glyph)),
309            ("weekly_pace_pct", wrap(pct)),
310            ("weekly_pace_pts", wrap(pts)),
311            ("weekly_pace_delta", wrap(&delta)),
312            ("weekly_pace_abs_delta", wrap(&abs_delta)),
313        ],
314        "sonnet" => [
315            ("sonnet_pace", wrap(pace_glyph)),
316            ("sonnet_pace_indicator", wrap(indicator_glyph)),
317            ("sonnet_pace_pct", wrap(pct)),
318            ("sonnet_pace_pts", wrap(pts)),
319            ("sonnet_pace_delta", wrap(&delta)),
320            ("sonnet_pace_abs_delta", wrap(&abs_delta)),
321        ],
322        _ => return,
323    };
324    for (k, v) in keys {
325        map.insert(k, v);
326    }
327}
328
329/// The bordered Pango tooltip (claudebar:707-860).
330fn render_default_tooltip(input: &RenderInput) -> String {
331    let snap = &input.outcome.snapshot;
332    let theme = input.theme;
333    let blue = &theme.blue;
334    let dim = &theme.dim;
335    let fg = &theme.fg;
336
337    let session_color = pango::severity_color(severity_for(snap.session.utilization_pct), theme);
338    let weekly_color = pango::severity_color(severity_for(snap.weekly.utilization_pct), theme);
339
340    let session_pacing = pacing::calc(
341        snap.session.utilization_pct,
342        snap.session.resets_at,
343        input.now,
344        snap.session.window_duration,
345        input.pace_tolerance,
346    );
347    let weekly_pacing = pacing::calc(
348        snap.weekly.utilization_pct,
349        snap.weekly.resets_at,
350        input.now,
351        snap.weekly.window_duration,
352        input.pace_tolerance,
353    );
354
355    let session_bar = if input.tooltip_pace_pts {
356        pango::progress_bar(
357            snap.session.utilization_pct,
358            session_color,
359            theme,
360            Some(session_pacing.elapsed_pct),
361        )
362    } else {
363        pango::progress_bar(snap.session.utilization_pct, session_color, theme, None)
364    };
365    let weekly_bar = if input.tooltip_pace_pts {
366        pango::progress_bar(
367            snap.weekly.utilization_pct,
368            weekly_color,
369            theme,
370            Some(weekly_pacing.elapsed_pct),
371        )
372    } else {
373        pango::progress_bar(snap.weekly.utilization_pct, weekly_color, theme, None)
374    };
375
376    let session_pace_glyph = pick_pace_glyph(input.tooltip_pace_pts, &session_pacing);
377    let weekly_pace_glyph = pick_pace_glyph(input.tooltip_pace_pts, &weekly_pacing);
378
379    let mut lines: Vec<Line> = Vec::new();
380    let _ = pango::severity_color; // silence unused-import warning if any
381    lines.push(Line::Center(format!(
382        "<span font_weight='bold' foreground='{blue}'>Claude {plan}</span>",
383        plan = escape(&snap.plan)
384    )));
385    lines.push(Line::Sep);
386    lines.push(Line::Body("".into()));
387
388    lines.push(Line::Body(format!(
389        " <span foreground='{fg}'>  󰔟  Session</span>"
390    )));
391    lines.push(Line::Body(format!(
392        "   {bar}  <span font_weight='bold' foreground='{color}'>{pct}% {glyph}</span>",
393        bar = session_bar,
394        color = session_color,
395        pct = snap.session.utilization_pct,
396        glyph = session_pace_glyph
397    )));
398    lines.push(Line::Body(format!(
399        " <span foreground='{dim}'>  ⏱  Resets in {cd}</span>",
400        cd = escape(&countdown::format(snap.session.resets_at, input.now))
401    )));
402    lines.push(Line::Body("".into()));
403
404    lines.push(Line::Body(format!(
405        " <span foreground='{fg}'>  󰃰  Weekly</span>"
406    )));
407    lines.push(Line::Body(format!(
408        "   {bar}  <span font_weight='bold' foreground='{color}'>{pct}% {glyph}</span>",
409        bar = weekly_bar,
410        color = weekly_color,
411        pct = snap.weekly.utilization_pct,
412        glyph = weekly_pace_glyph
413    )));
414    lines.push(Line::Body(format!(
415        " <span foreground='{dim}'>  ⏱  Resets in {cd}</span>",
416        cd = escape(&countdown::format(snap.weekly.resets_at, input.now))
417    )));
418
419    if let Some(sw) = snap.sonnet.as_ref() {
420        let sonnet_color = pango::severity_color(severity_for(sw.utilization_pct), theme);
421        let sonnet_pacing = pacing::calc(
422            sw.utilization_pct,
423            sw.resets_at,
424            input.now,
425            sw.window_duration,
426            input.pace_tolerance,
427        );
428        let sonnet_bar = if input.tooltip_pace_pts {
429            pango::progress_bar(
430                sw.utilization_pct,
431                sonnet_color,
432                theme,
433                Some(sonnet_pacing.elapsed_pct),
434            )
435        } else {
436            pango::progress_bar(sw.utilization_pct, sonnet_color, theme, None)
437        };
438        lines.push(Line::Body("".into()));
439        lines.push(Line::Body(format!(
440            " <span foreground='{fg}'>  󱤔  Sonnet only</span>"
441        )));
442        lines.push(Line::Body(format!(
443            "   {bar}  <span font_weight='bold' foreground='{color}'>{pct}%</span>",
444            bar = sonnet_bar,
445            color = sonnet_color,
446            pct = sw.utilization_pct
447        )));
448        lines.push(Line::Body(format!(
449            " <span foreground='{dim}'>  ⏱  Resets in {cd}</span>",
450            cd = escape(&countdown::format(sw.resets_at, input.now))
451        )));
452    }
453
454    for sw in &snap.scoped {
455        let scoped_color = pango::severity_color(severity_for(sw.window.utilization_pct), theme);
456        let scoped_pacing = pacing::calc(
457            sw.window.utilization_pct,
458            sw.window.resets_at,
459            input.now,
460            sw.window.window_duration,
461            input.pace_tolerance,
462        );
463        let scoped_bar = if input.tooltip_pace_pts {
464            pango::progress_bar(
465                sw.window.utilization_pct,
466                scoped_color,
467                theme,
468                Some(scoped_pacing.elapsed_pct),
469            )
470        } else {
471            pango::progress_bar(sw.window.utilization_pct, scoped_color, theme, None)
472        };
473        lines.push(Line::Body("".into()));
474        lines.push(Line::Body(format!(
475            " <span foreground='{fg}'>  󰆧  {label} weekly</span>",
476            label = escape(&sw.label)
477        )));
478        lines.push(Line::Body(format!(
479            "   {bar}  <span font_weight='bold' foreground='{color}'>{pct}%</span>",
480            bar = scoped_bar,
481            color = scoped_color,
482            pct = sw.window.utilization_pct
483        )));
484        lines.push(Line::Body(format!(
485            " <span foreground='{dim}'>  ⏱  Resets in {cd}</span>",
486            cd = escape(&countdown::format(sw.window.resets_at, input.now))
487        )));
488    }
489
490    if let Some(extra) = snap.extra {
491        let extra_color = pango::severity_color(severity_for(extra.percent()), theme);
492        let extra_bar = pango::progress_bar(extra.percent(), extra_color, theme, None);
493        lines.push(Line::Body("".into()));
494        lines.push(Line::Sep);
495        lines.push(Line::Body(format!(
496            " <span foreground='{fg}'>  󰄑  Extra usage</span>"
497        )));
498        lines.push(Line::Body(format!(
499            "   {bar}  <span font_weight='bold' foreground='{color}'>{spent}</span>",
500            bar = extra_bar,
501            color = extra_color,
502            spent = escape(&extra.spent.fmt_dollars())
503        )));
504        lines.push(Line::Body(format!(
505            " <span foreground='{dim}'>  󰀓  Limit: {lim}</span>",
506            lim = escape(&extra.limit.fmt_dollars())
507        )));
508    }
509
510    if let Some((code, msg)) = input.outcome.last_error.as_ref()
511        && *code != 0
512    {
513        let (icon, color) = if *code >= 500 {
514            ("󰅚", theme.red.as_str())
515        } else {
516            ("󰀪", theme.orange.as_str())
517        };
518        lines.push(Line::Body("".into()));
519        lines.push(Line::Sep);
520        lines.push(Line::Body(format!(
521            " <span foreground='{color}'>  {icon}  HTTP {code}</span>"
522        )));
523        for wrapped in wrap_words(&escape(msg), 35) {
524            lines.push(Line::Body(format!(
525                "     <span foreground='{dim}'>{wrapped}</span>"
526            )));
527        }
528    }
529
530    let updated = updated_at_hm(input.now, input.outcome.cache_age);
531    lines.push(Line::Body("".into()));
532    lines.push(Line::Sep);
533    lines.push(Line::Body(format!(
534        " <span foreground='{dim}'>  󰅐  Updated {updated}</span>"
535    )));
536
537    tooltip::render_bordered(&lines, theme)
538}
539
540fn pick_pace_glyph(point_mode: bool, p: &pacing::Pacing) -> &'static str {
541    if point_mode {
542        p.point_pace.glyph()
543    } else {
544        p.ratio_pace.glyph()
545    }
546}
547
548/// Greedy word-wrap to a target column. Used for the API-error message
549/// in the tooltip (claudebar:779-790).
550fn wrap_words(s: &str, width: usize) -> Vec<String> {
551    let mut out = Vec::new();
552    let mut buf = String::new();
553    for word in s.split_whitespace() {
554        if buf.is_empty() {
555            buf = word.into();
556        } else if buf.len() + 1 + word.len() <= width {
557            buf.push(' ');
558            buf.push_str(word);
559        } else {
560            out.push(std::mem::take(&mut buf));
561            buf = word.into();
562        }
563    }
564    if !buf.is_empty() {
565        out.push(buf);
566    }
567    out
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573    use crate::anthropic::fetch::FetchOutcome;
574    use crate::usage::{AnthropicSnapshot, Cents, ExtraUsage, UsageWindow};
575    use chrono::TimeZone;
576
577    fn now() -> DateTime<Utc> {
578        Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap()
579    }
580
581    fn sample_outcome() -> FetchOutcome {
582        let session = UsageWindow {
583            utilization_pct: 62,
584            resets_at: Some(now() + chrono::Duration::minutes(90)),
585            window_duration: chrono::Duration::hours(5),
586        };
587        let weekly = UsageWindow {
588            utilization_pct: 27,
589            resets_at: Some(now() + chrono::Duration::days(4) + chrono::Duration::hours(1)),
590            window_duration: chrono::Duration::days(7),
591        };
592        let sonnet = UsageWindow {
593            utilization_pct: 4,
594            resets_at: Some(now() + chrono::Duration::hours(2) + chrono::Duration::minutes(24)),
595            window_duration: chrono::Duration::days(7),
596        };
597        let snap = AnthropicSnapshot {
598            plan: "Max 5x".into(),
599            session,
600            weekly,
601            sonnet: Some(sonnet),
602            scoped: vec![],
603            extra: Some(ExtraUsage {
604                limit: Cents(5000),
605                spent: Cents(250),
606            }),
607        };
608        FetchOutcome {
609            snapshot: snap,
610            stale: false,
611            last_error: None,
612            cache_age: Some(std::time::Duration::from_secs(30)),
613        }
614    }
615
616    fn input<'a>(outcome: &'a FetchOutcome, theme: &'a Theme) -> RenderInput<'a> {
617        RenderInput {
618            outcome,
619            theme,
620            format: DEFAULT_FORMAT,
621            tooltip_format: None,
622            icon: None,
623            pace_tolerance: 5,
624            format_pace_color: false,
625            tooltip_pace_pts: false,
626            now: now(),
627        }
628    }
629
630    #[test]
631    fn default_format_renders_pct_and_reset() {
632        let oc = sample_outcome();
633        let theme = Theme::default();
634        let out = render_anthropic(&input(&oc, &theme));
635        // Bar text wraps in a span; content should include "62%" and the
636        // session countdown "1h 30m".
637        assert!(out.text.contains("62%"));
638        assert!(out.text.contains("1h 30m"));
639        assert_eq!(out.class, Class::Mid); // session=62 → mid
640    }
641
642    #[test]
643    fn stale_appends_pause_indicator() {
644        let mut oc = sample_outcome();
645        oc.stale = true;
646        let theme = Theme::default();
647        let out = render_anthropic(&input(&oc, &theme));
648        assert!(out.text.contains("⏸"));
649    }
650
651    #[test]
652    fn icon_prepends() {
653        let oc = sample_outcome();
654        let theme = Theme::default();
655        let mut inp = input(&oc, &theme);
656        inp.icon = Some("󰚩");
657        let out = render_anthropic(&inp);
658        assert!(out.text.contains("󰚩 "));
659    }
660
661    #[test]
662    fn custom_tooltip_format_uses_placeholders() {
663        let oc = sample_outcome();
664        let theme = Theme::default();
665        let mut inp = input(&oc, &theme);
666        inp.tooltip_format = Some("S:{session_pct} W:{weekly_pct}");
667        let out = render_anthropic(&inp);
668        assert_eq!(out.tooltip, "S:62 W:27");
669    }
670
671    #[test]
672    fn scoped_placeholders_expose_model_scoped_window() {
673        // The desktop surfaces read these `{scoped_*}` fields to show the
674        // model-scoped weekly bar (e.g. Fable) that only lives in `limits[]`.
675        let mut oc = sample_outcome();
676        oc.snapshot.scoped = vec![crate::usage::ScopedWindow {
677            label: "Fable".into(),
678            window: UsageWindow {
679                utilization_pct: 84,
680                resets_at: Some(now() + chrono::Duration::days(5)),
681                window_duration: chrono::Duration::days(7),
682            },
683        }];
684        let theme = Theme::default();
685        let mut inp = input(&oc, &theme);
686        inp.tooltip_format = Some(
687            "M:{scoped_model} P:{scoped_pct} R:{scoped_reset} E:{scoped_elapsed} B:{scoped_bar}",
688        );
689        let out = render_anthropic(&inp);
690        assert!(out.tooltip.starts_with("M:Fable P:84 R:"));
691        for placeholder in [
692            "{scoped_model}",
693            "{scoped_pct}",
694            "{scoped_reset}",
695            "{scoped_elapsed}",
696            "{scoped_bar}",
697        ] {
698            assert!(!out.tooltip.contains(placeholder));
699        }
700    }
701
702    #[test]
703    fn scoped_placeholders_are_neutral_when_absent() {
704        let oc = sample_outcome(); // scoped: vec![]
705        let theme = Theme::default();
706        let mut inp = input(&oc, &theme);
707        inp.tooltip_format = Some("[{scoped_model}] {scoped_pct} {scoped_reset}");
708        let out = render_anthropic(&inp);
709        assert_eq!(out.tooltip, "[] 0 —");
710    }
711
712    #[test]
713    fn default_tooltip_contains_all_sections() {
714        let oc = sample_outcome();
715        let theme = Theme::default();
716        let out = render_anthropic(&input(&oc, &theme));
717        assert!(out.tooltip.contains("Claude Max 5x"));
718        assert!(out.tooltip.contains("Session"));
719        assert!(out.tooltip.contains("Weekly"));
720        assert!(out.tooltip.contains("Sonnet only"));
721        assert!(out.tooltip.contains("Extra usage"));
722        assert!(out.tooltip.contains("Updated"));
723        assert!(out.tooltip.contains("62%"));
724        assert!(out.tooltip.contains("27%"));
725        assert!(out.tooltip.contains("$2.50"));
726        assert!(out.tooltip.contains("$50.00"));
727    }
728
729    #[test]
730    fn tooltip_omits_sonnet_and_extra_when_absent() {
731        let mut oc = sample_outcome();
732        oc.snapshot.sonnet = None;
733        oc.snapshot.extra = None;
734        let theme = Theme::default();
735        let out = render_anthropic(&input(&oc, &theme));
736        assert!(!out.tooltip.contains("Sonnet only"));
737        assert!(!out.tooltip.contains("Extra usage"));
738        // Still contains the basics.
739        assert!(out.tooltip.contains("Session"));
740        assert!(out.tooltip.contains("Weekly"));
741    }
742
743    #[test]
744    fn tooltip_includes_http_error_when_last_error_present() {
745        let mut oc = sample_outcome();
746        oc.last_error = Some((429, "rate limited".into()));
747        let theme = Theme::default();
748        let out = render_anthropic(&input(&oc, &theme));
749        assert!(out.tooltip.contains("HTTP 429"));
750        assert!(out.tooltip.contains("rate limited"));
751    }
752
753    #[test]
754    fn tooltip_omits_http_zero() {
755        // claudebar treats code 0 (no HTTP response) as "don't render"
756        // because it would be misleading.
757        let mut oc = sample_outcome();
758        oc.last_error = Some((0, "n/a".into()));
759        let theme = Theme::default();
760        let out = render_anthropic(&input(&oc, &theme));
761        assert!(!out.tooltip.contains("HTTP 0"));
762    }
763
764    #[test]
765    fn worst_window_promotes_class_to_critical() {
766        let mut oc = sample_outcome();
767        oc.snapshot.weekly.utilization_pct = 95;
768        let theme = Theme::default();
769        let out = render_anthropic(&input(&oc, &theme));
770        assert_eq!(out.class, Class::Critical);
771    }
772
773    #[test]
774    fn pace_color_mode_uses_neutral_wrapper() {
775        let oc = sample_outcome();
776        let theme = Theme::default();
777        let mut inp = input(&oc, &theme);
778        inp.format = "{session_pct}% {session_pace}";
779        inp.format_pace_color = true;
780        let out = render_anthropic(&inp);
781        // Wrapper color should be the foreground (neutral), not severity.
782        assert!(out.text.contains(&theme.fg));
783    }
784
785    #[test]
786    fn wrap_words_breaks_on_width_boundary() {
787        let lines = wrap_words("aaa bbb ccc ddd eee fff", 8);
788        // "aaa bbb" (7) fits; "ccc ddd" (7) fits next; "eee fff" (7) next.
789        assert_eq!(lines, vec!["aaa bbb", "ccc ddd", "eee fff"]);
790    }
791}