From 61eb5fbca524a2384d65578111ba4dfbef3519f9 Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Wed, 1 Jul 2026 16:53:44 +0300 Subject: [PATCH] fix: scope cache read/write to the selected period (web + devices CLI) (#583) (#586) The dashboard Cache read/write cards and the `codeburn devices` summarizer summed the full 365-day history.daily backfill instead of the selected period, so shorter windows over-counted (today ~197x on real data). Every other metric already reads the period-scoped `current` block. buildMenubarPayload now emits period-scoped cacheReadTokens/cacheWriteTokens on `current` (from PeriodData, alongside inputTokens/outputTokens); the web cards (single + combined views) and summarizeOneDevice read those instead of reducing history.daily. The trend chart still uses history.daily. Older peers that omit the fields fall back to 0 (web) or the windowed daily sum (CLI). Adds regression tests for both surfaces. --- dash/src/App.tsx | 17 ++++++++++------- dash/src/lib/api.ts | 4 ++++ src/menubar-json.ts | 7 +++++++ src/sharing/host.ts | 13 +++++++++---- tests/menubar-json.test.ts | 29 +++++++++++++++++++++++++++++ tests/sharing/host.test.ts | 25 +++++++++++++++++++++++++ 6 files changed, 84 insertions(+), 11 deletions(-) diff --git a/dash/src/App.tsx b/dash/src/App.tsx index 4b5a610a..8dfc1a7d 100644 --- a/dash/src/App.tsx +++ b/dash/src/App.tsx @@ -74,9 +74,11 @@ function Stat({ label: lbl, value }: { label: string; value: string }) { // project and session detail is intentionally absent. function DeviceView({ payload, isRemote, unit }: { payload?: Payload; isRemote: boolean; unit: Unit }) { const c = payload?.current - const daily = payload?.history.daily ?? [] - const cacheWrite = daily.reduce((s, d) => s + d.cacheWriteTokens, 0) - const cacheRead = daily.reduce((s, d) => s + d.cacheReadTokens, 0) + // Cache cards read the period-scoped `current` totals, matching Cost/Calls/ + // Tokens. `history.daily` is the 365-day backfill that feeds the trend chart + // only; summing it here over-counted the cards for shorter periods (#583). + const cacheWrite = c?.cacheWriteTokens ?? 0 + const cacheRead = c?.cacheReadTokens ?? 0 const toolBars: BarItem[] = c ? Object.entries(c.providers).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]).map(([k, v]) => ({ name: k, value: v, display: usd(v) })) : [] @@ -256,10 +258,11 @@ function CombinedView({ devices, unit }: { devices: DeviceUsage[]; unit: Unit }) if (!c) continue inTok += c.inputTokens outTok += c.outputTokens - for (const e of d.payload?.history.daily ?? []) { - cacheWrite += e.cacheWriteTokens - cacheRead += e.cacheReadTokens - } + // Period-scoped per device (was summing each device's 365-day backfill, #583). + // `?? 0` mirrors DeviceView and guards the un-normalized bootstrap payload, + // where an older peer may not carry these fields yet (avoids NaN). + cacheWrite += c.cacheWriteTokens ?? 0 + cacheRead += c.cacheReadTokens ?? 0 for (const [k, v] of Object.entries(c.providers)) providers.set(k, (providers.get(k) ?? 0) + v) for (const m of c.topModels) models.set(m.name, (models.get(m.name) ?? 0) + m.cost) for (const a of c.topActivities) activities.set(a.name, (activities.get(a.name) ?? 0) + a.cost) diff --git a/dash/src/lib/api.ts b/dash/src/lib/api.ts index f0d0bc45..0a1e6a4a 100644 --- a/dash/src/lib/api.ts +++ b/dash/src/lib/api.ts @@ -27,6 +27,8 @@ export type Current = { oneShotRate: number | null inputTokens: number outputTokens: number + cacheReadTokens: number + cacheWriteTokens: number cacheHitPercent: number codexCredits: number topActivities: Array<{ name: string; cost: number; turns: number; oneShotRate: number | null }> @@ -86,6 +88,8 @@ function normalizePayload(p?: Payload): Payload | undefined { oneShotRate: c.oneShotRate ?? null, inputTokens: c.inputTokens ?? 0, outputTokens: c.outputTokens ?? 0, + cacheReadTokens: c.cacheReadTokens ?? 0, + cacheWriteTokens: c.cacheWriteTokens ?? 0, cacheHitPercent: c.cacheHitPercent ?? 0, codexCredits: c.codexCredits ?? 0, topActivities: c.topActivities ?? [], diff --git a/src/menubar-json.ts b/src/menubar-json.ts index ef72538f..f337f9c9 100644 --- a/src/menubar-json.ts +++ b/src/menubar-json.ts @@ -118,6 +118,11 @@ export type MenubarPayload = { oneShotRate: number | null inputTokens: number outputTokens: number + /// Period-scoped cache token totals. Kept separate from `history.daily` + /// (which is a 365-day backfill for the trend chart) so the web cache + /// cards read the same range as Cost/Calls/Tokens (issue #583). + cacheReadTokens: number + cacheWriteTokens: number cacheHitPercent: number /// Codex credits consumed in the period; 0 when there is no Codex usage. codexCredits: number @@ -357,6 +362,8 @@ export function buildMenubarPayload( oneShotRate: aggregateOneShotRate(current.categories), inputTokens: current.inputTokens, outputTokens: current.outputTokens, + cacheReadTokens: current.cacheReadTokens, + cacheWriteTokens: current.cacheWriteTokens, cacheHitPercent: cacheHitPercent(current.inputTokens, current.cacheReadTokens), codexCredits: current.codexCredits ?? 0, topActivities: buildTopActivities(current.categories), diff --git a/src/sharing/host.ts b/src/sharing/host.ts index a372161e..f5aaf3e3 100644 --- a/src/sharing/host.ts +++ b/src/sharing/host.ts @@ -13,9 +13,11 @@ import { Chalk } from 'chalk' export type { CombinedUsage, DeviceSummary } from '../menubar-json.js' // Minimal shape we read from a device's usage payload (the menubar payload). -// Cache create/read are only in the daily history, so we sum those. +// Cache read/write come from the period-scoped `current` (like input/output) +// when the peer sends them; older peers only carry cache in the daily history, +// so we fall back to summing that (scoped by `window` when provided). type DevicePayload = { - current?: { cost?: number; calls?: number; sessions?: number; inputTokens?: number; outputTokens?: number } + current?: { cost?: number; calls?: number; sessions?: number; inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number } history?: { daily?: Array<{ date?: string; cacheReadTokens?: number; cacheWriteTokens?: number }> } } @@ -66,8 +68,11 @@ function summarizeOneDevice(d: DeviceUsage, window?: SummaryWindow): DeviceSumma }) const inputTokens = num(cur?.inputTokens) const outputTokens = num(cur?.outputTokens) - const cacheCreateTokens = daily.reduce((s, e) => s + num(e.cacheWriteTokens), 0) - const cacheReadTokens = daily.reduce((s, e) => s + num(e.cacheReadTokens), 0) + // Prefer the period-scoped `current` counts (issue #583); fall back to the + // windowed daily history for older peers that don't send them. `??` keeps a + // genuine 0 and only falls back when the field is absent. + const cacheCreateTokens = cur?.cacheWriteTokens ?? daily.reduce((s, e) => s + num(e.cacheWriteTokens), 0) + const cacheReadTokens = cur?.cacheReadTokens ?? daily.reduce((s, e) => s + num(e.cacheReadTokens), 0) return { id: d.id, name: d.name, diff --git a/tests/menubar-json.test.ts b/tests/menubar-json.test.ts index ad2f5822..11f4ce0e 100644 --- a/tests/menubar-json.test.ts +++ b/tests/menubar-json.test.ts @@ -43,6 +43,35 @@ describe('buildMenubarPayload', () => { expect(payload.current.outputTokens).toBe(675600) }) + it('exposes period-scoped cache tokens on current, decoupled from the 365-day history backfill (#583)', () => { + const period: PeriodData = { + label: '30 Days', + cost: 5, calls: 10, sessions: 2, + inputTokens: 1000, outputTokens: 2000, + // What `report -p 30days` shows in the terminal for the same window. + cacheReadTokens: 1_391_100_000, + cacheWriteTokens: 42_000_000, + categories: [], models: [], + } + // history.daily is the full BACKFILL_DAYS (365) trend, whose cache totals are + // far larger than the selected period. The web cards used to sum these, which + // is the bug in #583. current must mirror the period, not the backfill. + const dailyHistory = [ + { date: '2025-07-15', cost: 0, savingsUSD: 0, calls: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 1_800_000_000, cacheWriteTokens: 60_000_000, topModels: [] }, + { date: '2026-06-30', cost: 0, savingsUSD: 0, calls: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 270_000_000, cacheWriteTokens: 12_000_000, topModels: [] }, + ] + const payload = buildMenubarPayload(period, [], null, dailyHistory) + + // current carries the period totals verbatim ... + expect(payload.current.cacheReadTokens).toBe(1_391_100_000) + expect(payload.current.cacheWriteTokens).toBe(42_000_000) + // ... and is independent of the larger history-backfill sum the cards used before. + const historyReadSum = dailyHistory.reduce((s, d) => s + d.cacheReadTokens, 0) + const historyWriteSum = dailyHistory.reduce((s, d) => s + d.cacheWriteTokens, 0) + expect(historyReadSum).toBeGreaterThan(payload.current.cacheReadTokens) + expect(historyWriteSum).toBeGreaterThan(payload.current.cacheWriteTokens) + }) + it('computes per-category oneShotRate from editTurns and skips categories without edits', () => { const period: PeriodData = { label: 'Today', diff --git a/tests/sharing/host.test.ts b/tests/sharing/host.test.ts index 09a377d4..39db6883 100644 --- a/tests/sharing/host.test.ts +++ b/tests/sharing/host.test.ts @@ -230,4 +230,29 @@ describe('host device flow', () => { reachableCount: 2, }) }) + + it('prefers period-scoped current cache tokens over the 365-day daily history (#583)', () => { + const results: DeviceUsage[] = [ + { + id: 'local', + name: 'Mac', + local: true, + payload: { + current: { cost: 1, calls: 1, sessions: 1, inputTokens: 100, outputTokens: 50, cacheReadTokens: 42, cacheWriteTokens: 7 }, + history: { + daily: [ + // A full 365-day backfill whose cache dwarfs the selected period. + { date: '2025-08-01', cacheWriteTokens: 900, cacheReadTokens: 5000 }, + { date: '2026-04-10', cacheWriteTokens: 3, cacheReadTokens: 8 }, + ], + }, + }, + }, + ] + + const summary = summarizeDeviceUsage(results) + // Reads current (7 / 42), not the inflated daily-history sum (903 / 5008). + expect(summary.perDevice[0]).toMatchObject({ cacheCreateTokens: 7, cacheReadTokens: 42 }) + expect(summary.combined).toMatchObject({ cacheCreateTokens: 7, cacheReadTokens: 42 }) + }) })