Skip to main content

ai_usagebar/
format.rs

1//! `{placeholder}` substitution for `--format` and `--tooltip-format`.
2//!
3//! Same surface as claudebar (claudebar:625-667): placeholders are surrounded
4//! by `{}`, unknown placeholders are left untouched (matching bash parameter
5//! expansion's default behavior — claudebar uses `${text//\{x\}/$val}` which
6//! is a no-op for unknown keys).
7//!
8//! Built on a `Map<&str, String>` so each vendor can register its own
9//! placeholder set and the rendering code doesn't need to know what they are.
10
11use std::collections::HashMap;
12use std::time::Duration;
13
14use chrono::{DateTime, Local, Utc};
15
16use crate::countdown;
17use crate::pacing;
18use crate::usage::{ResetCredit, ResetCredits, UsageWindow};
19use crate::vendor::RenderOpts;
20
21/// The five per-window placeholder values every windowed renderer registers
22/// (`pct`, `reset`, `elapsed` and the two pace glyphs). A window the account
23/// does not report yields empty strings, the missing-placeholder convention.
24#[derive(Default)]
25pub struct WindowPlaceholders {
26    pub pct: String,
27    pub reset: String,
28    pub elapsed: String,
29    pub ratio_pace: String,
30    pub point_pace: String,
31}
32
33pub fn window_placeholders(
34    window: Option<&UsageWindow>,
35    opts: &RenderOpts,
36    now: DateTime<Utc>,
37) -> WindowPlaceholders {
38    let Some(window) = window else {
39        return WindowPlaceholders::default();
40    };
41    let pace = pacing::calc(
42        window.utilization_pct,
43        window.resets_at,
44        now,
45        window.window_duration,
46        opts.pace_tolerance,
47    );
48    WindowPlaceholders {
49        pct: window.utilization_pct.to_string(),
50        reset: countdown::format(window.resets_at, now),
51        elapsed: pace.elapsed_pct.to_string(),
52        ratio_pace: pace.ratio_pace.glyph().to_string(),
53        point_pace: pace.point_pace.glyph().to_string(),
54    }
55}
56
57/// A monetary amount, with the sign outside the symbol. `format!("${v:.2}")`
58/// puts it inside — `$-5.71` — which reads as a typo rather than as debt, and
59/// several providers let a balance go negative: OpenRouter overruns its
60/// credits, Moonshot carries an explicit `cash_balance` debt.
61///
62/// The sign is decided from the *rounded* magnitude, so neither a negative
63/// zero off the wire nor a sub-cent debt can produce the nonsense `-$0.00`.
64///
65/// This is the one place that decides what money looks like. Every renderer
66/// goes through it so a debt cannot be spelled two ways in two panels.
67pub fn money(v: f64, currency: &str) -> String {
68    let magnitude = format!("{:.2}", v.abs());
69    let sign = if v < 0.0 && magnitude != "0.00" {
70        "-"
71    } else {
72        ""
73    };
74    with_currency(sign, &magnitude, Some(currency))
75}
76
77/// Attach a currency to an already-formatted magnitude and sign.
78///
79/// The one table that decides which currencies get a symbol. [`money`] works in
80/// `f64` at two decimals and [`crate::usage::fmt_minor`] works in integer minor
81/// units at the currency's own scale — two different numbers, but they must not
82/// disagree about what a euro looks like. They did: `money` rendered EUR as
83/// `3.50 EUR` while `fmt_minor` rendered the same currency as `€3.50`.
84///
85/// `None` means a payload that predates any currency field; those were always
86/// USD. A code with no symbol here trails the code instead of guessing one,
87/// which is still truthful — rendering R$ 141.57 as "$141.57" is a claim about
88/// the wrong currency, the same class of defect as a fabricated number.
89pub fn with_currency(sign: &str, number: &str, currency: Option<&str>) -> String {
90    match currency {
91        None | Some("USD") => format!("{sign}${number}"),
92        Some("BRL") => format!("{sign}R${number}"),
93        Some("EUR") => format!("{sign}€{number}"),
94        Some("GBP") => format!("{sign}£{number}"),
95        Some("JPY") | Some("CNY") => format!("{sign}¥{number}"),
96        Some(other) => format!("{sign}{number} {other}"),
97    }
98}
99
100/// Upper-case the first character, leaving the rest alone.
101///
102/// Vendor plans arrive lower-cased (`"pro"`, `"max"`, `"glm coding pro"`) and
103/// every one of them wants the same title-ish label. `char::to_uppercase` can
104/// yield more than one char, so this is not `s[..1].to_uppercase() + &s[1..]`.
105pub fn capitalize(s: &str) -> String {
106    let mut chars = s.chars();
107    match chars.next() {
108        Some(first) => {
109            let mut out = String::with_capacity(s.len());
110            out.extend(first.to_uppercase());
111            out.push_str(chars.as_str());
112            out
113        }
114        None => String::new(),
115    }
116}
117
118/// [`money`] for the providers that only ever bill in dollars.
119pub fn usd(v: f64) -> String {
120    money(v, "USD")
121}
122
123/// A raw percentage as a whole number a meter can draw: rounded, held to
124/// 0–100, and NaN-safe.
125///
126/// A meter whose denominator came off the wire can be handed a NaN
127/// (`0.0 / 0.0`) or an out-of-range ratio, and each caller inventing its own
128/// guard is how two gauges end up disagreeing about what "100%" means.
129///
130/// **A shared helper, not a chokepoint.** Every float percentage that is
131/// rounded and held to 0–100 routes through here, and an `i32` caller widens
132/// the result with `i32::from`. Nothing enforces that. Some percentages follow
133/// a different rule on purpose and do not come here: a whole-number percent
134/// that a parser already rounded is clamped as an integer before it is cast
135/// into `Metric.pct`, and a few vendors round without clamping, or reject an
136/// out-of-range value instead of holding it. Prefer this for new callers.
137///
138/// # Examples
139///
140/// ```
141/// use ai_usagebar::format::clamp_pct;
142///
143/// assert_eq!(clamp_pct(24.5), 25);
144/// assert_eq!(clamp_pct(-3.0), 0);
145/// assert_eq!(clamp_pct(140.0), 100);
146/// assert_eq!(clamp_pct(f64::NAN), 0);
147/// ```
148pub fn clamp_pct(v: f64) -> u16 {
149    if v.is_nan() {
150        0
151    } else {
152        v.round().clamp(0.0, 100.0) as u16
153    }
154}
155
156pub fn local_time_hm(when: DateTime<Utc>) -> String {
157    when.with_timezone(&Local).format("%H:%M").to_string()
158}
159
160pub fn local_time_hms(when: DateTime<Utc>) -> String {
161    when.with_timezone(&Local).format("%H:%M:%S").to_string()
162}
163
164pub fn local_date_hm(when: DateTime<Utc>) -> String {
165    when.with_timezone(&Local)
166        .format("%b %-d %H:%M")
167        .to_string()
168}
169
170/// Compact count for placeholders and tooltips that have to stay on one line.
171pub fn reset_credits(credits: &ResetCredits) -> String {
172    let noun = if credits.available == 1 {
173        "reset"
174    } else {
175        "resets"
176    };
177    format!("{} {noun} available", credits.available)
178}
179
180/// One row per banked reset, soonest expiry first. This is what the panel,
181/// TUI, and tooltip list — a single "2 available · next expires Oct 4" line
182/// hides that two credits can lapse hours apart on the same day.
183pub fn reset_credit_lines(credits: &ResetCredits, now: DateTime<Utc>) -> Vec<String> {
184    let mut items = credits.credits.clone();
185    items.sort_by_key(|credit| credit.expires_at);
186    let mut lines: Vec<String> = items
187        .iter()
188        .map(|credit| reset_credit_line(credit, now))
189        .collect();
190    if lines.is_empty() {
191        // A stated zero still gets a row: an empty block reads as missing
192        // data rather than "you hold none".
193        lines.push(if credits.available > 0 {
194            reset_credits(credits)
195        } else {
196            "None available".to_string()
197        });
198    }
199    lines
200}
201
202fn reset_credit_line(credit: &ResetCredit, now: DateTime<Utc>) -> String {
203    let expiry = match credit.expires_at {
204        Some(expires) if expires <= now => format!("expired {}", local_date_hm(expires)),
205        Some(expires) => format!(
206            "expires {} ({})",
207            local_date_hm(expires),
208            crate::countdown::format(Some(expires), now)
209        ),
210        None => "no expiry reported".into(),
211    };
212    match credit
213        .title
214        .as_deref()
215        .map(str::trim)
216        .filter(|title| !title.is_empty())
217    {
218        Some(title) => format!("{title} · {expiry}"),
219        None => capitalize(&expiry),
220    }
221}
222
223/// The spending-page pair for one Cursor credit grant: `$21.00/$25.00
224/// remaining`, plus the expiry when the grant has one.
225///
226/// Money goes through [`crate::usage::fmt_minor`] so the sign and the dollar
227/// symbol match every other USD figure. The date is the local clock time, the
228/// same way a banked reset is written.
229pub fn cursor_credit_line(
230    remaining_cents: i64,
231    total_cents: i64,
232    expires_at: Option<DateTime<Utc>>,
233    now: DateTime<Utc>,
234) -> String {
235    let pair = format!(
236        "{}/{}",
237        crate::usage::fmt_minor(remaining_cents, 2, Some("USD")),
238        crate::usage::fmt_minor(total_cents, 2, Some("USD"))
239    );
240    let balance = format!("{pair} remaining");
241    match credit_expiry_clause(expires_at, now) {
242        Some(clause) => format!("{balance} · {clause}"),
243        None => balance,
244    }
245}
246
247/// The grant as the same meter On-Demand uses: remaining dollars beside a bar
248/// of how much of the grant is already spent, with that spend in the caption.
249///
250/// `(used percent, remaining dollars, caption)`. The percent is half-up, the
251/// same rounding as a usage bar, and it stays within 0–100 because a grant
252/// cannot be spent past its own total.
253pub fn cursor_credit_meter(
254    remaining_cents: i64,
255    total_cents: i64,
256    expires_at: Option<DateTime<Utc>>,
257    now: DateTime<Utc>,
258) -> (u16, String, String) {
259    let total = total_cents.max(0);
260    let remaining = remaining_cents.max(0).min(total);
261    let spent = total.saturating_sub(remaining);
262    let pct = if total <= 0 {
263        0
264    } else {
265        let rounded = (i128::from(spent) * 100 + i128::from(total) / 2) / i128::from(total);
266        u16::try_from(rounded).unwrap_or(100).min(100)
267    };
268    let mut caption = format!(
269        "{} of {} used ({pct}%)",
270        crate::usage::fmt_minor(spent, 2, Some("USD")),
271        crate::usage::fmt_minor(total, 2, Some("USD"))
272    );
273    if let Some(clause) = credit_expiry_clause(expires_at, now) {
274        caption.push_str(" · ");
275        caption.push_str(&clause);
276    }
277    (
278        pct,
279        crate::usage::fmt_minor(remaining, 2, Some("USD")),
280        caption,
281    )
282}
283
284fn credit_expiry_clause(expires_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> Option<String> {
285    match expires_at {
286        Some(expires) if expires <= now => Some(format!("expired {}", local_date_hm(expires))),
287        Some(expires) => Some(format!(
288            "expires {} ({})",
289            local_date_hm(expires),
290            crate::countdown::format(Some(expires), now)
291        )),
292        None => None,
293    }
294}
295
296/// The title Cursor puts on the grant.
297///
298/// The spending card is "Credits". The IDE banner says "Use your $N free
299/// credits", or names a scoped product ("Cursor Grok 4.6 Credit", "Cloud
300/// Agent Credits", "Bugbot Credit"). `display_name` is that product title
301/// when it says "credit". A server label that does not ("Power user grant")
302/// and a `grant_type` such as "promo" are not the words on those screens, so
303/// the row says "Credits".
304pub fn cursor_credit_label(display_name: &str) -> String {
305    let name = display_name.trim();
306    if name.to_lowercase().contains("credit") {
307        name.to_string()
308    } else {
309        "Credits".to_string()
310    }
311}
312
313pub fn updated_at_hm(now: DateTime<Utc>, cache_age: Option<Duration>) -> String {
314    match cache_age {
315        Some(age) => local_time_hm(now - chrono::Duration::from_std(age).unwrap_or_default()),
316        None => "—".to_string(),
317    }
318}
319
320/// Substitute every `{key}` in `template` with `values[key]`. Unknown keys
321/// are left as-is.
322///
323/// This is a single-pass scan; an O(N) implementation that does no
324/// re-substitution. (Avoids the bash pitfall where replacement text
325/// containing `{foo}` would get further substituted.)
326pub fn substitute(template: &str, values: &HashMap<&str, String>) -> String {
327    let mut out = String::with_capacity(template.len());
328    let mut rest = template;
329    while !rest.is_empty() {
330        match rest.find('{') {
331            None => {
332                out.push_str(rest);
333                break;
334            }
335            Some(open) => {
336                // Copy everything up to the '{'.
337                out.push_str(&rest[..open]);
338                let after_open = &rest[open + 1..];
339                if let Some(close) = after_open.find('}') {
340                    let key = &after_open[..close];
341                    if let Some(val) = values.get(key) {
342                        out.push_str(val);
343                        rest = &after_open[close + 1..];
344                        continue;
345                    }
346                }
347                // Unmatched or unknown — keep the '{' literal and continue.
348                out.push('{');
349                rest = after_open;
350            }
351        }
352    }
353    out
354}
355
356/// Convenience: build a placeholder map from `(&str, impl Into<String>)` pairs.
357pub fn placeholders<I, V>(pairs: I) -> HashMap<&'static str, String>
358where
359    I: IntoIterator<Item = (&'static str, V)>,
360    V: Into<String>,
361{
362    pairs.into_iter().map(|(k, v)| (k, v.into())).collect()
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368
369    fn pm(pairs: &[(&'static str, &str)]) -> HashMap<&'static str, String> {
370        placeholders(pairs.iter().map(|(k, v)| (*k, v.to_string())))
371    }
372
373    /// The doc example above is not a CI gate — `.github/workflows/ci.yml` runs
374    /// `cargo test --all-targets`, which skips doctests — so the rule every
375    /// gauge in the app clamps through is asserted here as well.
376    #[test]
377    fn a_grant_is_titled_the_way_cursor_titles_it() {
378        assert_eq!(cursor_credit_label(""), "Credits");
379        assert_eq!(cursor_credit_label("Power user grant"), "Credits");
380        assert_eq!(cursor_credit_label("promo"), "Credits");
381        assert_eq!(
382            cursor_credit_label("Cursor Grok 4.6 Credit"),
383            "Cursor Grok 4.6 Credit"
384        );
385        assert_eq!(
386            cursor_credit_label("Cloud Agent Credits"),
387            "Cloud Agent Credits"
388        );
389    }
390
391    #[test]
392    fn a_spent_grant_stays_a_full_meter() {
393        let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
394        let (pct, value, caption) = cursor_credit_meter(0, 2500, None, now);
395        assert_eq!(pct, 100);
396        assert_eq!(value, "$0.00");
397        assert_eq!(caption, "$25.00 of $25.00 used (100%)");
398    }
399
400    #[test]
401    fn a_percentage_is_rounded_held_to_the_meter_and_nan_safe() {
402        assert_eq!(clamp_pct(0.0), 0);
403        assert_eq!(clamp_pct(100.0), 100);
404        assert_eq!(clamp_pct(24.5), 25);
405        assert_eq!(clamp_pct(24.4), 24);
406        // Out of range in either direction stops at the end of the meter
407        // rather than drawing past it or wrapping.
408        assert_eq!(clamp_pct(-0.4), 0);
409        assert_eq!(clamp_pct(-9_999.0), 0);
410        assert_eq!(clamp_pct(140.0), 100);
411        assert_eq!(clamp_pct(f64::INFINITY), 100);
412        assert_eq!(clamp_pct(f64::NEG_INFINITY), 0);
413        // A denominator off the wire can be zero, and `0.0 / 0.0` is NaN. That
414        // is "nothing to draw", not a panic and not a cast to garbage.
415        assert_eq!(clamp_pct(f64::NAN), 0);
416    }
417
418    fn offer(title: Option<&str>, expires: &str) -> ResetCredit {
419        ResetCredit {
420            title: title.map(str::to_string),
421            expires_at: Some(expires.parse().unwrap()),
422        }
423    }
424
425    #[test]
426    fn a_reset_inventory_lists_each_credit_soonest_first() {
427        let now = "2026-07-04T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
428        let credits = ResetCredits {
429            available: 2,
430            credits: vec![
431                offer(Some("Full reset (Weekly + 5 hr)"), "2026-08-01T00:00:00Z"),
432                offer(Some("Full reset (Weekly + 5 hr)"), "2026-07-17T00:00:00Z"),
433            ],
434        };
435        assert_eq!(reset_credits(&credits), "2 resets available");
436        let lines = reset_credit_lines(&credits, now);
437        assert_eq!(lines.len(), 2, "{lines:?}");
438        assert!(lines[0].contains("Full reset (Weekly + 5 hr)"), "{lines:?}");
439        assert!(lines[0].contains("(13d 0h)"), "{lines:?}");
440        assert!(lines[1].contains("(28d 0h)"), "{lines:?}");
441    }
442
443    #[test]
444    fn a_lapsed_deadline_reads_as_expired_rather_than_now() {
445        let now = "2026-07-04T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
446        let lines = reset_credit_lines(
447            &ResetCredits {
448                available: 1,
449                credits: vec![offer(None, "2026-07-01T00:00:00Z")],
450            },
451            now,
452        );
453        assert_eq!(lines.len(), 1);
454        assert!(lines[0].starts_with("Expired "), "{lines:?}");
455        assert!(!lines[0].contains("(now)"), "{lines:?}");
456    }
457
458    #[test]
459    fn a_count_without_detail_still_renders_the_inventory() {
460        let now = "2026-07-04T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
461        assert_eq!(
462            reset_credit_lines(
463                &ResetCredits {
464                    available: 2,
465                    credits: vec![]
466                },
467                now
468            ),
469            vec!["2 resets available"]
470        );
471    }
472
473    #[test]
474    fn single_substitution() {
475        let v = pm(&[("session_pct", "42")]);
476        assert_eq!(substitute("{session_pct}%", &v), "42%");
477    }
478
479    #[test]
480    fn usd_keeps_the_sign_outside_the_symbol() {
481        assert_eq!(usd(74.5), "$74.50");
482        assert_eq!(usd(0.0), "$0.00");
483        assert_eq!(usd(-5.71), "-$5.71");
484        // A negative zero off the wire is not a debt, and must not print as
485        // one — `format!("{:.2}")` alone would render it "$-0.00".
486        assert_eq!(usd(-0.0), "$0.00");
487        // Neither is a debt too small to show a cent.
488        assert_eq!(usd(-0.001), "$0.00");
489        // One that does round to a cent keeps its sign.
490        assert_eq!(usd(-0.006), "-$0.01");
491    }
492
493    #[test]
494    fn money_places_the_sign_ahead_of_every_currency() {
495        assert_eq!(money(20.0, "CNY"), "¥20.00");
496        assert_eq!(money(-20.0, "CNY"), "-¥20.00");
497        // A currency trails its code only when this table has no symbol for
498        // it; the sign still leads either way.
499        assert_eq!(money(3.5, "SEK"), "3.50 SEK");
500        assert_eq!(money(-3.5, "SEK"), "-3.50 SEK");
501        // usd() is the same policy, not a second one.
502        assert_eq!(money(-5.71, "USD"), usd(-5.71));
503        assert_eq!(money(-0.0, "CNY"), "¥0.00");
504    }
505
506    /// `money` and `usage::fmt_minor` compute different numbers — f64 at two
507    /// decimals versus integer minor units at the currency's own scale — but a
508    /// euro must look like a euro in both. They disagreed once: `money` had no
509    /// EUR/GBP/BRL/JPY entry and trailed the code while `fmt_minor` printed the
510    /// symbol, so the same currency read two ways in two panels.
511    #[test]
512    fn the_two_money_formatters_agree_on_every_symbol() {
513        for (code, symbol) in [
514            ("USD", "$"),
515            ("BRL", "R$"),
516            ("EUR", "€"),
517            ("GBP", "£"),
518            ("JPY", "¥"),
519            ("CNY", "¥"),
520        ] {
521            assert_eq!(money(3.5, code), format!("{symbol}3.50"), "money {code}");
522            assert_eq!(
523                crate::usage::fmt_minor(350, 2, Some(code)),
524                format!("{symbol}3.50"),
525                "fmt_minor {code}"
526            );
527        }
528        // And they agree that an unlisted code trails instead of guessing.
529        assert_eq!(money(3.5, "SEK"), "3.50 SEK");
530        assert_eq!(crate::usage::fmt_minor(350, 2, Some("SEK")), "3.50 SEK");
531        // fmt_minor keeps its own scale: JPY has no minor unit.
532        assert_eq!(crate::usage::fmt_minor(350, 0, Some("JPY")), "¥350");
533    }
534
535    #[test]
536    fn multiple_substitutions() {
537        let v = pm(&[("a", "1"), ("b", "2")]);
538        assert_eq!(substitute("{a}-{b}-{a}", &v), "1-2-1");
539    }
540
541    #[test]
542    fn unknown_placeholder_passes_through() {
543        let v = pm(&[("a", "1")]);
544        assert_eq!(substitute("{a} {unknown}", &v), "1 {unknown}");
545    }
546
547    #[test]
548    fn no_re_substitution_in_replacement_text() {
549        // Replacement text containing {a} must NOT be re-expanded.
550        let v = pm(&[("a", "{a}"), ("b", "X")]);
551        assert_eq!(substitute("{b}{a}{b}", &v), "X{a}X");
552    }
553
554    #[test]
555    fn empty_template() {
556        let v = pm(&[("a", "1")]);
557        assert_eq!(substitute("", &v), "");
558    }
559
560    #[test]
561    fn template_without_braces() {
562        let v = pm(&[("a", "1")]);
563        assert_eq!(substitute("hello world", &v), "hello world");
564    }
565
566    #[test]
567    fn unmatched_open_brace_is_literal() {
568        let v = pm(&[("a", "1")]);
569        assert_eq!(substitute("{a {x", &v), "{a {x");
570    }
571
572    #[test]
573    fn placeholders_with_underscores_and_digits() {
574        let v = pm(&[("session_pct_2", "x")]);
575        assert_eq!(substitute("{session_pct_2}", &v), "x");
576    }
577
578    #[test]
579    fn utf8_around_braces() {
580        let v = pm(&[("x", "→")]);
581        assert_eq!(substitute("α{x}β", &v), "α→β");
582    }
583}