ai-usagebar 1.7.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
//! OpenRouter renderer — bar text + bordered Pango tooltip.

use std::collections::HashMap;

use chrono::{DateTime, Utc};

use crate::format::{placeholders, substitute, updated_at_hm, usd};
use crate::pacing::PaceSeverity;
use crate::pango::{self, color_span, escape, severity_color, severity_for};
use crate::theme::Theme;
use crate::tooltip::{Line as TooltipLine, render_bordered};
use crate::usage::OpenRouterSnapshot;
use crate::vendor::{RenderOpts, VendorOutcome};
use crate::waybar::{Class, WaybarOutput};

use super::fetch::FetchOutcome;

pub const DEFAULT_FORMAT: &str = "${or_balance} · ${or_used_today}";

/// Build the placeholder map for the OpenRouter snapshot.
pub fn build_placeholders(snap: &OpenRouterSnapshot) -> HashMap<&'static str, String> {
    placeholders(vec![
        ("icon", "󱙺".to_string()),
        ("vendor_short", "opr".to_string()),
        // Cross-vendor aliases — for OpenRouter the "session" concept maps
        // to "credit consumed %", and there's no reset time so we render "—".
        ("session_pct", snap.consumed_pct().to_string()),
        ("session_reset", "".to_string()),
        ("weekly_pct", snap.consumed_pct().to_string()),
        ("weekly_reset", "".to_string()),
        ("plan", snap.label.clone()),
        ("or_label", snap.label.clone()),
        ("or_balance", usd(snap.balance())),
        ("or_total", usd(snap.total_credits)),
        ("or_used", usd(snap.total_usage)),
        ("or_used_today", usd(snap.usage_daily)),
        ("or_used_week", usd(snap.usage_weekly)),
        ("or_used_month", usd(snap.usage_monthly)),
        ("or_consumed_pct", snap.consumed_pct().to_string()),
        (
            "or_free_tier",
            (if snap.is_free_tier { "free" } else { "paid" }).into(),
        ),
        (
            "or_limit",
            snap.limit.map(usd).unwrap_or_else(|| "unlimited".into()),
        ),
        (
            "or_limit_remaining",
            snap.limit_remaining
                .map(usd)
                .unwrap_or_else(|| "unlimited".into()),
        ),
    ])
}

/// Compose the full Waybar output for an OpenRouter snapshot.
pub fn render(
    outcome: &VendorOutcome,
    snap: &OpenRouterSnapshot,
    theme: &Theme,
    opts: &RenderOpts,
    now: DateTime<Utc>,
) -> WaybarOutput {
    let class = Class::from(severity(snap));
    let format = opts
        .format
        .clone()
        .unwrap_or_else(|| DEFAULT_FORMAT.replace('$', ""));
    let mut values = build_placeholders(snap);
    // The default format above uses ${…} (legible in a shell context), so
    // strip the $ to match our placeholder syntax.
    values.insert("or_balance_bar", or_balance_bar(snap, theme));
    // Both sinks fed by this map (bar text and --tooltip-format) end up as
    // Pango markup, and the label is API-controlled — escape it here, its only
    // markup insertion point. The default tooltip escapes the raw snapshot
    // itself, and or_balance_bar is markup we emit, so neither is touched.
    for key in ["plan", "or_label"] {
        if let Some(value) = values.get_mut(key) {
            *value = escape(value);
        }
    }

    let format_clean = format.replace("${", "{");
    let mut text = substitute(&format_clean, &values);
    if outcome.stale {
        text.push_str("");
    }
    let wrapper_color = severity_color(severity(snap), theme).to_string();
    let icon_prefix = match opts.icon.as_deref() {
        Some(ic) if !ic.is_empty() => format!("{ic} "),
        _ => String::new(),
    };
    let bar_text = color_span(&wrapper_color, &format!("{icon_prefix}{text}"));

    let tooltip = if let Some(fmt) = opts.tooltip_format.as_deref() {
        substitute(&fmt.replace("${", "{"), &values)
    } else {
        render_tooltip(outcome, snap, theme, now)
    };

    WaybarOutput {
        text: bar_text,
        tooltip,
        class,
    }
}

fn or_balance_bar(snap: &OpenRouterSnapshot, theme: &Theme) -> String {
    let color = severity_color(severity(snap), theme);
    pango::progress_bar(snap.consumed_pct(), color, theme, None)
}

/// OpenRouter severity is keyed on consumed-percentage (low credit = critical),
/// with one case the percentage cannot express: an account that owes money.
/// `consumed_pct` needs `total_credits` as a denominator and reports 0 without
/// one, so an account that never bought credits but ran up usage would
/// otherwise show a debt in reassuring green.
pub fn severity(snap: &OpenRouterSnapshot) -> PaceSeverity {
    if snap.balance() < 0.0 {
        return PaceSeverity::Critical;
    }
    severity_for(snap.consumed_pct())
}

fn render_tooltip(
    outcome: &VendorOutcome,
    snap: &OpenRouterSnapshot,
    theme: &Theme,
    now: DateTime<Utc>,
) -> String {
    let blue = &theme.blue;
    let dim = &theme.dim;
    let fg = &theme.fg;

    let color = severity_color(severity(snap), theme);
    let bar = or_balance_bar(snap, theme);

    let mut lines: Vec<TooltipLine> = Vec::new();
    lines.push(TooltipLine::Center(format!(
        "<span font_weight='bold' foreground='{blue}'>{label}</span>",
        label = escape(&snap.label)
    )));
    lines.push(TooltipLine::Sep);
    lines.push(TooltipLine::Body("".into()));

    lines.push(TooltipLine::Body(format!(
        " <span foreground='{fg}'>  󰢗  Balance</span>"
    )));
    lines.push(TooltipLine::Body(format!(
        "   {bar}  <span font_weight='bold' foreground='{color}'>{bal}</span>",
        bal = escape(&usd(snap.balance()))
    )));
    lines.push(TooltipLine::Body(format!(
        " <span foreground='{dim}'>  {used} of {total} used ({pct}%)</span>",
        used = escape(&usd(snap.total_usage)),
        total = escape(&usd(snap.total_credits)),
        pct = snap.consumed_pct()
    )));

    lines.push(TooltipLine::Body("".into()));
    lines.push(TooltipLine::Body(format!(
        " <span foreground='{fg}'>  󰸘  Usage</span>"
    )));
    lines.push(TooltipLine::Body(format!(
        " <span foreground='{dim}'>     today {today} · week {week} · month {month}</span>",
        today = escape(&usd(snap.usage_daily)),
        week = escape(&usd(snap.usage_weekly)),
        month = escape(&usd(snap.usage_monthly))
    )));

    if let Some(limit) = snap.limit {
        let rem = snap.limit_remaining.unwrap_or(0.0);
        lines.push(TooltipLine::Body("".into()));
        lines.push(TooltipLine::Body(format!(
            " <span foreground='{fg}'>  󱁻  Per-key limit</span>"
        )));
        lines.push(TooltipLine::Body(format!(
            " <span foreground='{dim}'>     {rem} of {tot} remaining</span>",
            rem = escape(&usd(rem)),
            tot = escape(&usd(limit))
        )));
    }

    let tier_label = if snap.is_free_tier {
        "free tier"
    } else {
        "paid tier"
    };
    lines.push(TooltipLine::Body("".into()));
    lines.push(TooltipLine::Body(format!(
        " <span foreground='{dim}'>  󰓹  {tier_label}</span>"
    )));

    if let Some((code, msg)) = outcome.last_error.as_ref()
        && *code != 0
    {
        let (icon, ecolor) = if *code >= 500 {
            ("󰅚", theme.red.as_str())
        } else {
            ("󰀪", theme.orange.as_str())
        };
        lines.push(TooltipLine::Body("".into()));
        lines.push(TooltipLine::Sep);
        lines.push(TooltipLine::Body(format!(
            " <span foreground='{ecolor}'>  {icon}  HTTP {code}</span>"
        )));
        lines.push(TooltipLine::Body(format!(
            "     <span foreground='{dim}'>{}</span>",
            escape(msg)
        )));
    }

    let updated = updated_at_hm(now, outcome.cache_age);
    lines.push(TooltipLine::Body("".into()));
    lines.push(TooltipLine::Sep);
    lines.push(TooltipLine::Body(format!(
        " <span foreground='{dim}'>  󰅐  Updated {updated}</span>"
    )));

    render_bordered(&lines, theme)
}

impl From<FetchOutcome> for VendorOutcome {
    fn from(o: FetchOutcome) -> Self {
        Self {
            snapshot: crate::usage::VendorSnapshot::Openrouter(o.snapshot),
            stale: o.stale,
            last_error: o.last_error,
            cache_age: o.cache_age,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::usage::OpenRouterSnapshot;

    fn sample_snap() -> OpenRouterSnapshot {
        OpenRouterSnapshot {
            label: "OpenRouter — prod".into(),
            total_credits: 100.0,
            total_usage: 25.5,
            usage_daily: 1.0,
            usage_weekly: 7.0,
            usage_monthly: 25.5,
            is_free_tier: false,
            limit: Some(50.0),
            limit_remaining: Some(24.5),
        }
    }

    fn sample_outcome(snap: OpenRouterSnapshot) -> VendorOutcome {
        VendorOutcome {
            snapshot: crate::usage::VendorSnapshot::Openrouter(snap),
            stale: false,
            last_error: None,
            cache_age: Some(std::time::Duration::from_secs(15)),
        }
    }

    fn opts() -> RenderOpts {
        RenderOpts {
            format: None,
            tooltip_format: None,
            icon: None,
            pace_tolerance: 5,
            format_pace_color: false,
            tooltip_pace_pts: false,
        }
    }

    #[test]
    fn api_controlled_label_is_pango_escaped_in_custom_formats() {
        // The label comes from the API and both sinks fed by the placeholder
        // map are Pango markup. Unescaped, a label like `a & b <span…>` either
        // breaks the markup or lets an attacker-shaped key name paint text the
        // widget never intended.
        let mut snap = sample_snap();
        snap.label = "A & B <b>spoof</b>".into();

        let mut o = opts();
        o.format = Some("{plan}|{or_label}".into());
        let out = render(
            &sample_outcome(snap.clone()),
            &snap,
            &Theme::default(),
            &o,
            Utc::now(),
        );
        assert!(
            out.text.contains("A &amp; B &lt;b&gt;spoof&lt;/b&gt;"),
            "label was not escaped: {}",
            out.text
        );
        assert!(!out.text.contains("<b>spoof</b>"));

        // ...and the same through the tooltip sink.
        let mut o2 = opts();
        o2.tooltip_format = Some("{or_label}".into());
        let out2 = render(
            &sample_outcome(snap.clone()),
            &snap,
            &Theme::default(),
            &o2,
            Utc::now(),
        );
        assert!(out2.tooltip.contains("A &amp; B"));
        assert!(!out2.tooltip.contains("<b>spoof</b>"));
    }

    #[test]
    fn default_render_contains_balance_and_today_usage() {
        let snap = sample_snap();
        let outcome = sample_outcome(snap.clone());
        let theme = Theme::default();
        let out = render(&outcome, &snap, &theme, &opts(), Utc::now());
        assert!(out.text.contains("$74.50"));
        assert!(out.text.contains("$1.00"));
    }

    #[test]
    fn tooltip_includes_balance_usage_tier() {
        let snap = sample_snap();
        let outcome = sample_outcome(snap.clone());
        let theme = Theme::default();
        let out = render(&outcome, &snap, &theme, &opts(), Utc::now());
        assert!(out.tooltip.contains("Balance"));
        assert!(out.tooltip.contains("$25.50 of $100.00 used"));
        assert!(out.tooltip.contains("paid tier"));
        assert!(out.tooltip.contains("Per-key limit"));
        assert!(out.tooltip.contains("$24.50 of $50.00"));
    }

    /// Reported as #118: an account that never bought credits but ran up usage
    /// showed a reassuring `$0.00` in green. Both halves were wrong — the
    /// number was clamped, and the severity came from a percentage that has no
    /// denominator to work with.
    #[test]
    fn a_debt_is_shown_as_a_debt_not_as_zero() {
        let mut snap = sample_snap();
        snap.total_credits = 0.0;
        snap.total_usage = 5.71;
        assert!((snap.balance() + 5.71).abs() < 1e-9);
        assert_eq!(snap.consumed_pct(), 0);
        assert_eq!(severity(&snap), PaceSeverity::Critical);

        let out = render(
            &sample_outcome(snap.clone()),
            &snap,
            &Theme::default(),
            &opts(),
            Utc::now(),
        );
        assert!(out.text.contains("-$5.71"), "{}", out.text);
        assert!(!out.text.contains("$0.00"), "{}", out.text);
        assert!(out.tooltip.contains("-$5.71"), "{}", out.tooltip);
    }

    /// The other way into debt: credits were bought, then overrun. Here the
    /// percentage already saturates at 100, so only the clamped number was
    /// wrong — but it must render identically.
    #[test]
    fn overrunning_purchased_credit_is_also_a_debt() {
        let mut snap = sample_snap();
        snap.total_credits = 10.0;
        snap.total_usage = 12.5;
        assert!((snap.balance() + 2.5).abs() < 1e-9);
        assert_eq!(snap.consumed_pct(), 100);
        assert_eq!(severity(&snap), PaceSeverity::Critical);

        let out = render(
            &sample_outcome(snap.clone()),
            &snap,
            &Theme::default(),
            &opts(),
            Utc::now(),
        );
        assert!(out.text.contains("-$2.50"), "{}", out.text);
    }

    /// A free-tier account that has spent nothing is not in debt, and must
    /// stay green — the fix keys on the balance, not on "credits are zero".
    #[test]
    fn a_zero_credit_account_with_no_usage_stays_low() {
        let mut snap = sample_snap();
        snap.total_credits = 0.0;
        snap.total_usage = 0.0;
        assert_eq!(snap.balance(), 0.0);
        assert_eq!(severity(&snap), PaceSeverity::Low);
    }

    #[test]
    fn free_tier_label() {
        let mut snap = sample_snap();
        snap.is_free_tier = true;
        let outcome = sample_outcome(snap.clone());
        let theme = Theme::default();
        let out = render(&outcome, &snap, &theme, &opts(), Utc::now());
        assert!(out.tooltip.contains("free tier"));
    }

    #[test]
    fn stale_appends_pause() {
        let snap = sample_snap();
        let mut outcome = sample_outcome(snap.clone());
        outcome.stale = true;
        let theme = Theme::default();
        let out = render(&outcome, &snap, &theme, &opts(), Utc::now());
        assert!(out.text.contains(""));
    }

    #[test]
    fn custom_tooltip_uses_placeholders() {
        let snap = sample_snap();
        let outcome = sample_outcome(snap.clone());
        let theme = Theme::default();
        let mut o = opts();
        o.tooltip_format = Some("bal: {or_balance} | mtd: {or_used_month}".into());
        let out = render(&outcome, &snap, &theme, &o, Utc::now());
        assert_eq!(out.tooltip, "bal: $74.50 | mtd: $25.50");
    }

    #[test]
    fn severity_keys_on_consumed_pct() {
        let mut snap = sample_snap();
        snap.total_usage = 92.0; // 92% consumed → critical
        assert_eq!(severity(&snap), PaceSeverity::Critical);
        snap.total_usage = 60.0; // mid
        assert_eq!(severity(&snap), PaceSeverity::Mid);
    }
}