From 55df2e79e4665e9c663a76fba7b9b99d0caf18a6 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:51:24 -0500 Subject: [PATCH] fix(web): cumulative calendar totals with unknown days read "At least" In Cumulative mode a running total read as exact even when days before it are unknown (outside the known range, their files possibly deleted), and weeks after real usage showed "unavailable" instead of the total so far. Each day now records whether an unknown day comes at or before it, including usage carried in from before the grid. Such a total shows as a floor: the tooltip says "At least" and the number rounds down, so it never claims more than was counted. It keeps showing in every week after the first known usage, and shows as unavailable only when it is still zero. A weekly total with an unknown day also reads "At least", and a known quiet day in such a week keeps its zero color. --- .../src/components/ProviderUsageDashboard.tsx | 77 +++++++++++++------ .../settings/SettingsPanels.browser.tsx | 24 ++++++ apps/web/src/lib/providerUsage.test.ts | 6 ++ apps/web/src/lib/providerUsage.ts | 23 +++++- 4 files changed, 106 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/ProviderUsageDashboard.tsx b/apps/web/src/components/ProviderUsageDashboard.tsx index 0539993b7..62cff946e 100644 --- a/apps/web/src/components/ProviderUsageDashboard.tsx +++ b/apps/web/src/components/ProviderUsageDashboard.tsx @@ -50,6 +50,8 @@ interface TokenActivityDay { readonly dailyTokens: number; readonly weeklyTokens: number; readonly cumulativeTokens: number; + /** A day up to this one has an unknown total, so the running total is only a floor. */ + readonly cumulativeIsFloor: boolean; } function parseDateKey(dateKey: string): number | null { @@ -109,16 +111,23 @@ function formatTokenActivityTooltip( return `${tokenLabel} tokens on ${formatLongDate(ms)}`; } +/** + * `isFloor` marks a total with unknown days in it: the usage it counts + * happened, and maybe more. + */ function formatTokenActivityWeekTooltip( mode: TokenActivityMode, weekStartMs: number, weekEndMs: number, value: number | null, + isFloor = false, ): string { if (value === null) { return `Usage unavailable for week of ${formatLongDate(weekStartMs)}`; } - const tokenLabel = formatProviderTokenCount(value) ?? "0"; + const tokenLabel = isFloor + ? `At least ${formatProviderTokenCount(value, { roundDown: true }) ?? "0"}` + : (formatProviderTokenCount(value) ?? "0"); if (mode === "weekly") { return `${tokenLabel} tokens on week of ${formatLongDate(weekStartMs)}`; } @@ -207,26 +216,42 @@ function buildTokenActivityWeeks( const days: TokenActivityDay[] = []; let cumulativeTokens = carriedCumulativeTokens; + // Usage carried in from before the grid is a floor too when unknown days + // lie among it: the known range starts after the first of those days. + const earliestBucketMs = Math.min(...datedBuckets.map((entry) => entry.ms)); + let unknownDaySeen = + !tokenUsage.completeLifetimeHistory && + carriedCumulativeTokens > 0 && + reportedStartMs > earliestBucketMs; for (let ms = startMs; ms <= endMs; ms += DAY_MS) { const dateKey = formatDateKey(ms); const dailyTokens = tokenByDate.get(dateKey) ?? 0; cumulativeTokens += dailyTokens; + // A day outside the known range still shows usage it does have: only + // its zero is unknown, since its files may be gone. + const reported = (ms >= reportedStartMs && ms <= reportedEndMs) || dailyTokens > 0; + if (!reported && ms <= anchorDayMs) unknownDaySeen = true; days.push({ dateKey, ms, - // A day outside the known range still shows usage it does have: only - // its zero is unknown, since its files may be gone. - reported: (ms >= reportedStartMs && ms <= reportedEndMs) || dailyTokens > 0, + reported, dailyTokens, weeklyTokens: weeklyTotals.get(formatDateKey(startOfWeekUtc(ms))) ?? 0, cumulativeTokens, + cumulativeIsFloor: unknownDaySeen, }); } + // A running total stays meaningful past an unknown day, as a floor: it + // shows on every day so far unless it is a zero that might not be one. + const cumulativeValue = (day: TokenActivityDay): number | null => + day.ms > anchorDayMs || (day.cumulativeTokens === 0 && day.cumulativeIsFloor) + ? null + : day.cumulativeTokens; const maxValue = Math.max( 0, ...days - .filter((day) => day.reported) + .filter((day) => (mode === "cumulative" ? cumulativeValue(day) !== null : day.reported)) .map((day) => mode === "daily" ? day.dailyTokens @@ -245,19 +270,26 @@ function buildTokenActivityWeeks( // have still shows. const weekPartlyUnknown = weekDays.some((day) => !day.reported && day.ms <= anchorDayMs); const weekQuiet = reportedWeekDays.every((day) => day.dailyTokens === 0); + // The week's running total is its last day so far. + const lastPastDay = weekDays.findLast((day) => day.ms <= anchorDayMs); const weekValue = - reportedWeekDays.length === 0 || (weekPartlyUnknown && weekQuiet && mode !== "cumulative") - ? null - : mode === "weekly" - ? (reportedWeekDays[0]?.weeklyTokens ?? 0) - : mode === "cumulative" - ? (reportedWeekDays[reportedWeekDays.length - 1]?.cumulativeTokens ?? 0) + mode === "cumulative" + ? lastPastDay + ? cumulativeValue(lastPastDay) + : null + : reportedWeekDays.length === 0 || (weekPartlyUnknown && weekQuiet) + ? null + : mode === "weekly" + ? (reportedWeekDays[0]?.weeklyTokens ?? 0) : reportedWeekDays.reduce((sum, day) => sum + day.dailyTokens, 0); + const weekIsFloor = + mode === "cumulative" ? lastPastDay?.cumulativeIsFloor === true : weekPartlyUnknown; const weekTooltip = formatTokenActivityWeekTooltip( mode, weekDays[0]?.ms ?? weekStartMs, weekDays[weekDays.length - 1]?.ms ?? weekStartMs, weekValue, + weekIsFloor, ); let monthLabel: string | null = null; for (const [offset, day] of weekDays.entries()) { @@ -267,19 +299,20 @@ function buildTokenActivityWeeks( monthLabel = formatMonthLabel(day.ms); previousMonth = month; } - const value = !day.reported - ? null - : mode === "daily" - ? day.dailyTokens - : mode === "weekly" - ? day.dailyTokens > 0 - ? day.weeklyTokens - : weekPartlyUnknown - ? null - : 0 + const value = + mode === "cumulative" + ? cumulativeValue(day) === null + ? null : day.cumulativeTokens > 0 ? weekValue - : 0; + : 0 + : !day.reported + ? null + : mode === "daily" + ? day.dailyTokens + : day.dailyTokens > 0 + ? day.weeklyTokens + : 0; cells.push({ dateKey: day.dateKey, value, diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index c2b6a6c07..f3f70f39b 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -3672,6 +3672,30 @@ describe("GeneralSettingsPanel observability", () => { await expect .element(visibleActivityGrid.getByLabelText(`Usage unavailable on ${earlyQuietDate}`)) .toBeVisible(); + + // With unknown days behind it, a running total is a floor, never an exact sum. + await page.getByRole("button", { name: "Cumulative" }).last().click(); + const cumulativeGrid = page + .getByLabelText("Local token activity cumulative token activity") + .last(); + // A week after the first usage and before the known range still shows the floor. + const unknownDayMs = Date.parse(`${utcDateKeyAtOffset(-34)}T00:00:00.000Z`); + const unknownWeekStart = new Date( + unknownDayMs - new Date(unknownDayMs).getUTCDay() * 86_400_000, + ) + .toISOString() + .slice(0, 10); + await expect + .element( + cumulativeGrid.getByLabelText( + `At least 4k tokens through week of ${formatTokenActivityTestDate(unknownWeekStart)}`, + ), + ) + .toBeVisible(); + const weekLabels = [ + ...cumulativeGrid.element().querySelectorAll('[role="img"]'), + ].map((week) => week.getAttribute("aria-label") ?? ""); + expect(weekLabels.filter((label) => /^\d/.test(label))).toEqual([]); }); it("configures Claude fallback models from the provider models list", async () => { diff --git a/apps/web/src/lib/providerUsage.test.ts b/apps/web/src/lib/providerUsage.test.ts index 4dd9de68f..c68387229 100644 --- a/apps/web/src/lib/providerUsage.test.ts +++ b/apps/web/src/lib/providerUsage.test.ts @@ -27,6 +27,12 @@ describe("deriveProviderAccountUsagePresentation", () => { expect(formatProviderTokenCount(279_500_000)).toBe("279.5m"); }); + it("rounds a floor down so it never claims more than was counted", () => { + expect(formatProviderTokenCount(10_600)).toBe("11k"); + expect(formatProviderTokenCount(10_600, { roundDown: true })).toBe("10k"); + expect(formatProviderTokenCount(6_229_999_999, { roundDown: true })).toBe("6.22B"); + }); + it("formats Codex rate limit usage with used percent and reset time", () => { const usage: ServerProviderAccountUsage = { source: "codex-rate-limits", diff --git a/apps/web/src/lib/providerUsage.ts b/apps/web/src/lib/providerUsage.ts index a263e9d44..98bf04174 100644 --- a/apps/web/src/lib/providerUsage.ts +++ b/apps/web/src/lib/providerUsage.ts @@ -591,8 +591,27 @@ function formatResetCreditsPresentation( }; } -export function formatProviderTokenCount(value: number | undefined): string | null { - if (value === undefined || !Number.isFinite(value) || value < 0) return null; +/** The smallest change each size of token count shows, matching the format below. */ +function tokenCountDisplayStep(value: number): number { + if (value < 1_000) return 1; + if (value < 10_000) return 100; + if (value < 1_000_000) return 1_000; + if (value < 1_000_000_000) return 100_000; + return value < 10_000_000_000 ? 10_000_000 : 100_000_000; +} + +/** + * A token count for display. `roundDown` is for a floor ("at least"): the + * shown number must not exceed what was counted. + */ +export function formatProviderTokenCount( + rawValue: number | undefined, + options?: { readonly roundDown?: boolean }, +): string | null { + if (rawValue === undefined || !Number.isFinite(rawValue) || rawValue < 0) return null; + const value = options?.roundDown + ? Math.floor(rawValue / tokenCountDisplayStep(rawValue)) * tokenCountDisplayStep(rawValue) + : rawValue; if (value < 1_000) return `${Math.round(value)}`; if (value < 10_000) return `${(value / 1_000).toFixed(1).replace(/\.0$/, "")}k`; if (value < 1_000_000) return `${Math.round(value / 1_000)}k`;