Skip to main content

cmd_usage/ocuse/
window.rs

1// Aggregation: rows -> per-model totals -> the documented windows.
2//
3// Go's limits are per model and per period: 5-hour = 20% of the monthly limit,
4// weekly = 50%, monthly = 100%. The monthly *period* is a subscription
5// anniversary that nothing local records, so we infer it from the earliest Go
6// row we have ever seen (its day-of-month) and fall back to the calendar month
7// when there is no evidence. The inference is reported, never silent.
8use crate::ocuse::db::Row;
9use crate::ocuse::zen::Catalog;
10
11pub const FIVE_HOUR_SECS: i64 = 5 * 3600;
12pub const WEEKLY_SECS: i64 = 7 * 86_400;
13/// How far back to read when inferring the anniversary.
14pub const LOOKBACK_SECS: i64 = 120 * 86_400;
15
16#[derive(Debug, Clone, Default)]
17pub struct Totals {
18    pub cost: f64,
19    pub requests: u64,
20    pub input: u64,
21    pub output: u64,
22    pub cache_read: u64,
23}
24
25impl Totals {
26    /// Add one turn at `cost` — priced by the caller, which is the whole point:
27    /// `row.cost_usd` is opencode's figure, always the off-peak sheet, so the
28    /// dashboard prices each turn on the documented schedule instead and falls
29    /// back to the recorded cost when the model carries no rates.
30    pub fn add(&mut self, row: &Row, cost: f64) {
31        self.cost += cost;
32        self.requests += 1;
33        self.input += row.input;
34        self.output += row.output + row.reasoning;
35        self.cache_read += row.cache_read;
36    }
37
38    pub fn tokens(&self) -> u64 {
39        self.input + self.output + self.cache_read
40    }
41}
42
43#[derive(Debug, Clone)]
44pub struct ModelUsage {
45    pub id: String,
46    pub provider: String,
47    pub limit: Option<f64>,
48    pub month: Totals,
49    pub five_hour: Totals,
50    pub weekly: Totals,
51}
52
53impl ModelUsage {
54    /// Fraction of the monthly limit used, when the docs give one.
55    pub fn month_use(&self) -> Option<f64> {
56        self.limit.filter(|l| *l > 0.0).map(|l| self.month.cost / l)
57    }
58}
59
60/// Which of this model's windows is over its share of the monthly limit, if
61/// any — the verdict the sidebar's flag, the watch frame and the cap
62/// notification all read from. Go meters per model AND per window (5-hour =
63/// 20%, weekly = 50%, monthly = 100%), so any one of them counts; the shortest
64/// window wins, being the most actionable. `None` for a free/unlimited model.
65pub fn over_window(model: &ModelUsage) -> Option<&'static str> {
66    let limit = model.limit.filter(|l| *l > 0.0)?;
67    let shares = &crate::ocuse::zen::catalog().go.window_share;
68    if model.five_hour.cost > limit * shares.five_hour {
69        Some("5-hour")
70    } else if model.weekly.cost > limit * shares.weekly {
71        Some("weekly")
72    } else if model.month.cost > limit * shares.monthly {
73        Some("monthly")
74    } else {
75        None
76    }
77}
78
79#[derive(Debug, Clone)]
80pub struct Report {
81    /// What the caller called this period ("calendar month", "all", "30d") for display.
82    pub period_label: String,
83    pub now_ms: i64,
84    pub since_ms: i64,
85    /// End of the period (epoch ms), resolved by the caller from its own start
86    /// — see `next_month`. `None` when the period has no boundary (`--window
87    /// all`); the rolling 5h/weekly windows never carry one.
88    pub period_end_ms: Option<i64>,
89    pub month_inferred: bool,
90    /// The account's own three meters, when OpenCode Go's usage endpoint
91    /// answered (`ocuse::api`). The dashboard's window rows read from here
92    /// rather than from [`Self::five_hour`]/[`Self::weekly`]/[`Self::month`],
93    /// because only the server's numbers agree with the console; the store's are
94    /// the fallback. `None` also keeps every existing caller working.
95    pub account: Option<crate::ocuse::api::Usage>,
96    /// Why the account's meters are absent, when that is worth saying — a refused
97    /// key, a missing one, a dead network. `None` when the endpoint answered, and
98    /// also for `--no-api` (a deliberate choice is not a fault). Without it the
99    /// dashboard's "estimated locally" says nothing about which it was, and only
100    /// one of those is something to act on.
101    pub account_error: Option<String>,
102    pub five_hour: Totals,
103    pub weekly: Totals,
104    pub month: Totals,
105    /// Sorted by month cost, descending.
106    pub models: Vec<ModelUsage>,
107}
108
109/// Civil date from a Unix day number (Howard Hinnant's algorithm) — avoids a
110/// date dependency for the one thing we need: a day-of-month.
111fn day_of_month(epoch_secs: i64) -> u32 {
112    civil(epoch_secs).2 as u32
113}
114
115pub fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
116    let y = if m <= 2 { y - 1 } else { y };
117    let era = y.div_euclid(400);
118    let yoe = y - era * 400;
119    let mp = if m > 2 { m - 3 } else { m + 9 };
120    let doy = (153 * mp + 2) / 5 + d - 1;
121    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
122    era * 146_097 + doe - 719_468
123}
124
125fn civil(epoch_secs: i64) -> (i64, i64, i64) {
126    let days = epoch_secs.div_euclid(86_400);
127    let z = days + 719_468;
128    let era = z.div_euclid(146_097);
129    let doe = z.rem_euclid(146_097);
130    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
131    let y = yoe + era * 400;
132    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
133    let mp = (5 * doy + 2) / 153;
134    let d = doy - (153 * mp + 2) / 5 + 1;
135    let m = if mp < 10 { mp + 3 } else { mp - 9 };
136    (if m <= 2 { y + 1 } else { y }, m, d)
137}
138
139/// Wall-clock now in epoch ms.
140pub fn now_ms() -> i64 {
141    std::time::SystemTime::now()
142        .duration_since(std::time::UNIX_EPOCH)
143        .map(|d| d.as_millis() as i64)
144        .unwrap_or(0)
145}
146
147/// Start of the calendar month, 00:00 UTC — the predictable default, since
148/// nothing local records a subscription anniversary (the console holds it).
149pub fn calendar_month_start(now_ms: i64) -> i64 {
150    let (year, month, _) = civil(now_ms / 1000);
151    days_from_civil(year, month, 1) * 86_400_000
152}
153
154/// The same day-of-month one month later, 00:00 UTC, in epoch ms; the year
155/// wraps. The day is clamped to 28 so an anniversary on the 29th–31st cannot
156/// skip a month into the wrong one — the same clamp `month_start` applies, so a
157/// period start it produced always has a matching end.
158pub fn next_month(ms: i64) -> i64 {
159    let (year, month, day) = civil(ms / 1000);
160    let (ny, nm) = if month == 12 {
161        (year + 1, 1)
162    } else {
163        (year, month + 1)
164    };
165    days_from_civil(ny, nm, day.min(28)) * 86_400_000
166}
167
168/// The same day-of-month one month *earlier*, keeping the time of day — the
169/// inverse of [`next_month`] for the instants it can produce. The account API's
170/// monthly `resetsAt` is an anniversary time (09:14:35, not midnight), so its
171/// period start has to carry that time of day back to the previous month.
172pub fn prev_month(ms: i64) -> i64 {
173    let (year, month, day) = civil(ms / 1000);
174    let (py, pm) = if month == 1 {
175        (year - 1, 12)
176    } else {
177        (year, month - 1)
178    };
179    days_from_civil(py, pm, day.min(28)) * 86_400_000 + ms.rem_euclid(86_400_000)
180}
181
182/// Start of the billing month: the most recent occurrence of the inferred
183/// anniversary day, else the first of the calendar month. Returns (start, inferred).
184pub fn month_start(rows: &[Row], now_ms: i64) -> (i64, bool) {
185    let now_secs = now_ms / 1000;
186    // Anniversary evidence: the oldest Go row we know about (its day-of-month),
187    // else the oldest row of any kind.
188    let (year, month, _day) = civil(now_secs);
189    let earliest_go = rows
190        .iter()
191        .filter(|r| r.provider == "opencode-go")
192        .map(|r| r.at_ms)
193        .min();
194    let anniversary = earliest_go
195        .or_else(|| rows.iter().map(|r| r.at_ms).min())
196        .map(|ms| day_of_month(ms / 1000));
197    if let Some(day_wanted) = anniversary {
198        let candidate = days_from_civil(year, month, day_wanted.min(28) as i64) * 86_400;
199        if candidate <= now_secs {
200            return (candidate * 1000, true);
201        }
202        let (py, pm) = if month == 1 {
203            (year - 1, 12)
204        } else {
205            (year, month - 1)
206        };
207        return (
208            days_from_civil(py, pm, day_wanted.min(28) as i64) * 86_400 * 1000,
209            true,
210        );
211    }
212    // No evidence at all: calendar month.
213    let current = civil(now_secs);
214    let days = days_from_civil(current.0, current.1, 1);
215    (days * 86_400 * 1000, false)
216}
217
218/// Build the report: window totals plus a per-model breakdown for the period.
219///
220/// `plan_id` selects which Go plan's per-model allowances the figures are
221/// measured against (the store records no subscription, so the caller chooses);
222/// `since_override` pins the period start (from `--period-start`); otherwise the
223/// anniversary heuristic in [`month_start`] applies. Rows before the period are
224/// anniversary evidence only — never listed — so the table and the totals agree.
225pub fn build(
226    rows: &[Row],
227    catalog: &Catalog,
228    plan_id: &str,
229    now_ms: i64,
230    since_override: Option<i64>,
231    account: Option<&crate::ocuse::api::Usage>,
232) -> Report {
233    let (inferred_start, month_inferred) = month_start(rows, now_ms);
234    let since_ms = since_override.unwrap_or(inferred_start);
235    // The windows are cut at the *account's* bounds when it answered. Go meters a
236    // 5-hour block with its own reset, a week anchored to Monday 00:00 UTC, and
237    // the billing anniversary — none of which a rolling `now - length` cut
238    // reproduces. Cutting locally and pairing those dollars with the server's
239    // percentage put two different windows on one row: on real data the weekly
240    // row read `$20.45 (0.0% of limit)`, because the store's rolling week still
241    // held the previous week's spend while the server's week had just started.
242    // Without an answer the rolling cuts stay — the only ones this machine knows.
243    let (five_start, five_end) = match account.and_then(|a| a.rolling.reset_ms()) {
244        Some(reset) => (reset - FIVE_HOUR_SECS * 1000, reset),
245        None => (now_ms - FIVE_HOUR_SECS * 1000, i64::MAX),
246    };
247    let (week_start, week_end) = match account.and_then(|a| a.weekly.reset_ms()) {
248        Some(reset) => (reset - WEEKLY_SECS * 1000, reset),
249        None => (now_ms - WEEKLY_SECS * 1000, i64::MAX),
250    };
251
252    let mut report = Report {
253        period_label: "calendar month".into(),
254        now_ms,
255        since_ms,
256        period_end_ms: None,
257        month_inferred: since_override.is_none() && month_inferred,
258        account: None,
259        account_error: None,
260        five_hour: Totals::default(),
261        weekly: Totals::default(),
262        month: Totals::default(),
263        models: Vec::new(),
264    };
265    let mut by_model: std::collections::BTreeMap<String, ModelUsage> = Default::default();
266
267    for row in rows {
268        // The month cut applies to the month, not to the loop: the account's week
269        // is anchored to Monday, which can start before a mid-week billing
270        // anniversary, and dropping those rows would undercount the very window
271        // the server's percentage describes.
272        let in_month = row.at_ms >= since_ms;
273        let in_week = row.at_ms >= week_start && row.at_ms < week_end;
274        let in_five = row.at_ms >= five_start && row.at_ms < five_end;
275        if !in_month && !in_week && !in_five {
276            continue;
277        }
278        // Priced on the documented schedule, not by opencode's recorded `cost`
279        // (always the off-peak sheet). Falls back to the recorded figure for a
280        // model with no rate rows, so a free or unknown model still counts zero
281        // and an unpriced one still counts its own cost.
282        let cost = catalog
283            .price(
284                &row.model,
285                row.at_ms,
286                row.input,
287                row.output,
288                row.reasoning,
289                row.cache_read,
290                row.cache_write,
291            )
292            .unwrap_or(row.cost_usd);
293        if in_month {
294            report.month.add(row, cost);
295        }
296        if in_week {
297            report.weekly.add(row, cost);
298        }
299        if in_five {
300            report.five_hour.add(row, cost);
301        }
302        let entry = by_model
303            .entry(row.model.clone())
304            .or_insert_with(|| ModelUsage {
305                id: row.model.clone(),
306                provider: row.provider.clone(),
307                limit: catalog.go_limit(plan_id, &row.model),
308                month: Totals::default(),
309                five_hour: Totals::default(),
310                weekly: Totals::default(),
311            });
312        if in_month {
313            entry.month.add(row, cost);
314        }
315        if in_week {
316            entry.weekly.add(row, cost);
317        }
318        if in_five {
319            entry.five_hour.add(row, cost);
320        }
321    }
322
323    report.models = by_model.into_values().collect();
324    report.models.sort_by(|a, b| {
325        b.month
326            .cost
327            .partial_cmp(&a.month.cost)
328            .unwrap_or(std::cmp::Ordering::Equal)
329            .then_with(|| a.id.cmp(&b.id))
330    });
331    report
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337    use crate::ocuse::db::Row;
338
339    fn row(at_s: i64, model: &str, cost: f64) -> Row {
340        Row {
341            at_ms: at_s * 1000,
342            provider: "opencode-go".into(),
343            model: model.into(),
344            cost_usd: cost,
345            ..Default::default()
346        }
347    }
348
349    /// An account meter with a reset instant, for the window-bound tests.
350    fn meter(status: &str, percent: f64, resets_at: &str) -> crate::ocuse::api::Meter {
351        crate::ocuse::api::Meter {
352            status: status.into(),
353            percent,
354            resets_at: Some(resets_at.into()),
355        }
356    }
357
358    /// ISO-8601 UTC for an epoch-seconds instant, so the meter's wire shape
359    /// (`resetsAt`) is exercised rather than a pre-parsed value.
360    fn iso(secs: i64) -> String {
361        let rem = secs.rem_euclid(86_400);
362        let (y, m, d) = civil(secs - rem);
363        format!(
364            "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.000Z",
365            rem / 3600,
366            (rem % 3600) / 60,
367            rem % 60
368        )
369    }
370
371    #[test]
372    fn civil_helpers_round_trip() {
373        // 2026-09-27T00:00:00Z
374        let secs = days_from_civil(2026, 9, 27) * 86_400;
375        assert_eq!(civil(secs), (2026, 9, 27));
376        assert_eq!(day_of_month(secs), 27);
377    }
378
379    #[test]
380    fn next_month_keeps_the_day_and_wraps_the_year() {
381        // Same day-of-month, one month later, across a year boundary.
382        let dec15 = days_from_civil(2026, 12, 15) * 86_400_000;
383        assert_eq!(civil(next_month(dec15) / 1000), (2027, 1, 15));
384        // A calendar-month start (day 1) lands on day 1 of the next month.
385        let jan1 = days_from_civil(2026, 1, 1) * 86_400_000;
386        assert_eq!(civil(next_month(jan1) / 1000), (2026, 2, 1));
387        // A 31st start is clamped to 28, so it cannot skip a short month.
388        let jan31 = days_from_civil(2026, 1, 31) * 86_400_000;
389        assert_eq!(civil(next_month(jan31) / 1000), (2026, 2, 28));
390    }
391
392    #[test]
393    fn prev_month_inverts_next_month_and_keeps_the_clock() {
394        // The account API's monthly reset for this subscription.
395        let reset = 1_794_604_475_000; // 2026-11-13T09:14:35Z
396        let start = prev_month(reset);
397        assert_eq!(civil(start / 1000), (2026, 10, 13));
398        assert_eq!(start % 86_400_000, reset % 86_400_000, "time of day kept");
399        // One month on from the derived start is the reset's date again.
400        assert_eq!(civil(next_month(start) / 1000), (2026, 11, 13));
401        // Year wrap, and the day clamp that keeps a 31st from skipping a month.
402        let dec13 = days_from_civil(2026, 12, 13) * 86_400_000;
403        assert_eq!(civil(prev_month(dec13) / 1000), (2026, 11, 13));
404        let mar31 = days_from_civil(2026, 3, 31) * 86_400_000;
405        assert_eq!(civil(prev_month(mar31) / 1000), (2026, 2, 28));
406    }
407
408    #[test]
409    fn windows_are_rolling_and_the_month_is_inferred() {
410        let now = days_from_civil(2026, 9, 27) * 86_400 + 12 * 3600;
411        let rows = vec![
412            row(now - 60, "glm-5.3-flash", 1.0),          // inside 5h
413            row(now - 2 * 3600, "glm-5.3-flash", 2.0),    // inside 5h + week
414            row(now - 3 * 86_400, "kimi-k3", 4.0),        // inside week only
415            row(now - 40 * 86_400, "glm-5.3-flash", 8.0), // previous cycle: anniversary evidence
416        ];
417        let catalog = crate::ocuse::zen::catalog();
418        let report = build(
419            &rows,
420            &catalog,
421            crate::ocuse::zen::DEFAULT_PLAN,
422            now * 1000,
423            None,
424            None,
425        );
426        assert!(
427            report.month_inferred,
428            "anniversary inferred from the earliest row"
429        );
430        assert!((report.five_hour.cost - 3.0).abs() < 1e-9);
431        assert!((report.weekly.cost - 7.0).abs() < 1e-9);
432        // anniversary day = 18 (40 days before the 27th), so this cycle starts Sep 18
433        assert!(
434            (report.month.cost - 7.0).abs() < 1e-9,
435            "month cost {}",
436            report.month.cost
437        );
438        let flash = report
439            .models
440            .iter()
441            .find(|m| m.id == "glm-5.3-flash")
442            .unwrap();
443        assert_eq!(flash.limit, Some(60.0));
444        assert!((flash.five_hour.cost - 3.0).abs() < 1e-9);
445    }
446
447    /// The account's own bounds decide the windows when it answered. Go's 5-hour
448    /// window is a *block* with its own reset and its week starts Monday 00:00
449    /// UTC, so a rolling `now - length` cut describes a different span — the bug
450    /// that printed `$20.45 (0.0% of limit)` on a row whose console share had
451    /// just started counting.
452    #[test]
453    fn the_accounts_bounds_cut_the_windows_when_it_answered() {
454        let now = days_from_civil(2026, 10, 19) * 86_400 + 12 * 3600; // Mon noon UTC
455        let week_reset = now + 6 * 86_400 + 12 * 3600; // next Monday 00:00
456        let five_reset = now + 3 * 3600;
457        let five_start = five_reset - FIVE_HOUR_SECS;
458        let rows = vec![
459            // Before the server's week (so outside it) but inside a rolling 7d.
460            row(now - 6 * 86_400, "glm-5.3-flash", 9.0),
461            // Inside the server's week but outside its 5-hour block (which
462            // starts two hours back), so the two cuts are distinguishable.
463            row(now - 3 * 3600, "glm-5.3-flash", 2.0),
464            // Inside the server's 5-hour block.
465            row(five_start + 60, "glm-5.3-flash", 1.0),
466        ];
467        let account = crate::ocuse::api::Usage {
468            rolling: meter("ok", 6.0, &iso(five_reset)),
469            weekly: meter("ok", 3.0, &iso(week_reset)),
470            monthly: meter("ok", 51.0, &iso(now + 20 * 86_400)),
471        };
472        let report = build(
473            &rows,
474            &crate::ocuse::zen::catalog(),
475            crate::ocuse::zen::DEFAULT_PLAN,
476            now * 1000,
477            None,
478            Some(&account),
479        );
480        // The rolling 7d cut would have counted the 6-day-old row ($9, so 12.0
481        // here); the server's Monday week starts 12h ago and must not.
482        assert!(
483            (report.weekly.cost - 3.0).abs() < 1e-9,
484            "weekly {}",
485            report.weekly.cost
486        );
487        assert!(
488            (report.five_hour.cost - 1.0).abs() < 1e-9,
489            "5h {}",
490            report.five_hour.cost
491        );
492        // …and the same cut applies to the per-model rows the panel pairs with.
493        let flash = report
494            .models
495            .iter()
496            .find(|m| m.id == "glm-5.3-flash")
497            .unwrap();
498        assert!((flash.weekly.cost - 3.0).abs() < 1e-9);
499        assert!((flash.five_hour.cost - 1.0).abs() < 1e-9);
500        // The month is untouched by the window cuts: it still sees every row in
501        // the period, including the one the server's week excluded.
502        assert!((report.month.cost - 12.0).abs() < 1e-9);
503    }
504
505    #[test]
506    fn models_sort_by_month_spend() {
507        let now = days_from_civil(2026, 9, 27) * 86_400;
508        let rows = vec![row(now - 60, "cheap", 0.1), row(now - 60, "pricey", 5.0)];
509        let report = build(
510            &rows,
511            &crate::ocuse::zen::catalog(),
512            crate::ocuse::zen::DEFAULT_PLAN,
513            now * 1000,
514            None,
515            None,
516        );
517        assert_eq!(report.models[0].id, "pricey");
518    }
519}