From a52a01fcabdf83e2970362cf7d9a082daf50f58b Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:23:54 -0500 Subject: [PATCH] fix(web): the token calendar never colors or counts a day after today Usage dated after today (from a paired computer whose clock runs ahead) was colored in Daily mode and counted in weekly totals and the color scale. The calendar also fixed its "today" when the page opened, so a page left open overnight could miss the new day. Today is now the later of the browser's UTC day and the day the data was checked, at most a day past the browser's, and it moves on at UTC midnight (useUtcDayStartMs, sharing the timer the sidebar's local-day hook uses). Days after it are blank in every mode and left out of week totals, running totals and the color scale. --- .../src/components/ProviderUsageDashboard.tsx | 37 ++++++---- .../settings/SettingsPanels.browser.tsx | 73 +++++++++++++++++++ apps/web/src/hooks/useLocalDayStartMs.ts | 19 +++-- apps/web/src/timestampFormat.ts | 6 ++ 4 files changed, 116 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/ProviderUsageDashboard.tsx b/apps/web/src/components/ProviderUsageDashboard.tsx index 62cff946e..dc40c23ef 100644 --- a/apps/web/src/components/ProviderUsageDashboard.tsx +++ b/apps/web/src/components/ProviderUsageDashboard.tsx @@ -17,6 +17,7 @@ import { SegmentedControl, SegmentedControlItem } from "./ui/segmented-control"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ProviderExternalResetsButton } from "./ProviderRateLimitResetCredit"; import { UsagePaceMark, usagePaceLabel } from "./usage/UsagePaceMark"; +import { useUtcDayStartMs } from "../hooks/useLocalDayStartMs"; type TokenActivityMode = "daily" | "weekly" | "cumulative"; type TokenActivityRange = "13-weeks" | "1-year"; @@ -65,6 +66,11 @@ function formatDateKey(ms: number): string { return new Date(ms).toISOString().slice(0, 10); } +function utcDayStartMs(ms: number): number { + const date = new Date(ms); + return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); +} + function startOfWeekUtc(ms: number): number { const date = new Date(ms); const day = date.getUTCDay(); @@ -175,15 +181,17 @@ function buildTokenActivityWeeks( ); if (datedBuckets.length === 0) return []; - const anchorDate = new Date(anchorMs); - const anchorDayMs = Date.UTC( - anchorDate.getUTCFullYear(), - anchorDate.getUTCMonth(), - anchorDate.getUTCDate(), - ); + // Today is the later of this browser's day and the day the data was + // checked, at most a day ahead: a server whose clock runs a little ahead, + // or a check after midnight while the page stays open, lands on today. + // Anything after today is the future and stays blank. + const checkedAtMs = Date.parse(tokenUsage.checkedAt); + const browserDayMs = utcDayStartMs(anchorMs); + const anchorDayMs = Number.isNaN(checkedAtMs) + ? browserDayMs + : Math.min(Math.max(browserDayMs, utcDayStartMs(checkedAtMs)), browserDayMs + DAY_MS); const endMs = endOfWeekUtc(anchorDayMs); const startMs = startOfWeekUtc(endMs) - 51 * 7 * DAY_MS; - const checkedAtMs = Date.parse(tokenUsage.checkedAt); const coverageStartMs = tokenUsage.coverageStartDate ? parseDateKey(tokenUsage.coverageStartDate) : null; @@ -207,6 +215,7 @@ function buildTokenActivityWeeks( let carriedCumulativeTokens = 0; for (const entry of datedBuckets) { + if (entry.ms > anchorDayMs) continue; if (entry.ms < startMs) { carriedCumulativeTokens += entry.bucket.tokens; } @@ -225,11 +234,12 @@ function buildTokenActivityWeeks( reportedStartMs > earliestBucketMs; for (let ms = startMs; ms <= endMs; ms += DAY_MS) { const dateKey = formatDateKey(ms); - const dailyTokens = tokenByDate.get(dateKey) ?? 0; + const dailyTokens = ms > anchorDayMs ? 0 : (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; + const reported = + ms <= anchorDayMs && ((ms >= reportedStartMs && ms <= reportedEndMs) || dailyTokens > 0); if (!reported && ms <= anchorDayMs) unknownDaySeen = true; days.push({ dateKey, @@ -522,14 +532,13 @@ export function ProviderUsageDashboard(props: { }) { const [activityMode, setActivityMode] = useState("daily"); const [activityRange, setActivityRange] = useState("13-weeks"); - const [activityAnchorMs] = useState(() => Date.now()); const tokenUsage = props.usage.tokenUsage ?? null; + // Moves on at UTC midnight, so a page left open overnight shows the new day. + const todayUtcMs = useUtcDayStartMs(); const activityWeeks = useMemo( () => - tokenUsage === null - ? [] - : buildTokenActivityWeeks(tokenUsage, activityMode, activityAnchorMs), - [activityAnchorMs, activityMode, tokenUsage], + tokenUsage === null ? [] : buildTokenActivityWeeks(tokenUsage, activityMode, todayUtcMs), + [activityMode, todayUtcMs, tokenUsage], ); const mobileActivityWeeks = activityRange === "13-weeks" ? activityWeeks.slice(-13) : activityWeeks; diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index f3f70f39b..e6cc573f7 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -3698,6 +3698,79 @@ describe("GeneralSettingsPanel observability", () => { expect(weekLabels.filter((label) => /^\d/.test(label))).toEqual([]); }); + it("leaves days after today blank in the token calendar", async () => { + // A Monday, so two days ahead falls inside the week the calendar shows. + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-11-23T12:00:00.000Z")); + onTestFinished(() => { + vi.useRealTimers(); + }); + const withBuckets = ( + dailyBuckets: ReadonlyArray<{ readonly startDate: string; readonly tokens: number }>, + ): ServerProvider => { + const provider = createClaudeProviderWithTokenHistory(); + const tokenUsage = provider.accountUsage?.tokenUsage; + if (!provider.accountUsage || !tokenUsage) throw new Error("fixture has no token history"); + return { + ...provider, + accountUsage: { ...provider.accountUsage, tokenUsage: { ...tokenUsage, dailyBuckets } }, + }; + }; + setServerConfigSnapshot({ + ...createBaseServerConfig(), + providers: [ + // Logged on a paired computer whose clock runs two days ahead. + withBuckets([ + { startDate: "2026-11-23", tokens: 1000 }, + { startDate: "2026-11-25", tokens: 5000 }, + ]), + ], + }); + + mounted = await renderWithTestRouter( + + + , + ); + + await openProviderDetails("Claude"); + await page.getByRole("button", { name: "Usage", exact: true }).click(); + const dailyGrid = page.getByLabelText("Local token activity daily token activity").last(); + await expect + .element( + dailyGrid.getByLabelText(`1k tokens on ${formatTokenActivityTestDate("2026-11-23")}`), + ) + .toBeVisible(); + expect(dailyGrid.getByLabelText(/^5k tokens/).elements()).toHaveLength(0); + + await page.getByRole("button", { name: "Weekly" }).last().click(); + await expect + .element( + page + .getByLabelText("Local token activity weekly token activity") + .last() + .getByLabelText(`1k tokens on week of ${formatTokenActivityTestDate("2026-11-22")}`), + ) + .toBeVisible(); + + // Left open until Sunday: the calendar moves on to the new week. + await page.getByRole("button", { name: "Daily" }).last().click(); + vi.setSystemTime(new Date("2026-11-29T01:00:00.000Z")); + window.dispatchEvent(new Event("focus")); + setServerConfigSnapshot({ + ...createBaseServerConfig(), + providers: [withBuckets([{ startDate: "2026-11-29", tokens: 2000 }])], + }); + await expect + .element( + page + .getByLabelText("Local token activity daily token activity") + .last() + .getByLabelText(`2k tokens on ${formatTokenActivityTestDate("2026-11-29")}`), + ) + .toBeVisible(); + }); + it("configures Claude fallback models from the provider models list", async () => { const updateSettings = vi .fn() diff --git a/apps/web/src/hooks/useLocalDayStartMs.ts b/apps/web/src/hooks/useLocalDayStartMs.ts index 140f1e4db..5d45428fa 100644 --- a/apps/web/src/hooks/useLocalDayStartMs.ts +++ b/apps/web/src/hooks/useLocalDayStartMs.ts @@ -1,13 +1,22 @@ import { useEffect, useState } from "react"; -import { startOfLocalDayMs } from "../timestampFormat"; +import { startOfLocalDayMs, startOfUtcDayMs } from "../timestampFormat"; /** * Local midnight of the current day. Re-renders only when the day turns, so * a "today" label moves on at midnight without a ticking clock. */ export function useLocalDayStartMs(): number { - const [dayStartMs, setDayStartMs] = useState(() => startOfLocalDayMs(Date.now())); + return useDayStartMs(startOfLocalDayMs); +} + +/** UTC midnight of the current day, for views that count days in UTC. */ +export function useUtcDayStartMs(): number { + return useDayStartMs(startOfUtcDayMs); +} + +function useDayStartMs(startOfDayMs: (nowMs: number, daysBack?: number) => number): number { + const [dayStartMs, setDayStartMs] = useState(() => startOfDayMs(Date.now())); useEffect(() => { let timer: ReturnType | undefined; // Checks the day, then waits until just past the next midnight. A timer's @@ -17,9 +26,9 @@ export function useLocalDayStartMs(): number { // One reading of the clock: two could fall either side of midnight, // and keep yesterday until the day after. const nowMs = Date.now(); - setDayStartMs(startOfLocalDayMs(nowMs)); + setDayStartMs(startOfDayMs(nowMs)); clearTimeout(timer); - timer = setTimeout(sync, startOfLocalDayMs(nowMs, -1) - nowMs + 1_000); + timer = setTimeout(sync, startOfDayMs(nowMs, -1) - nowMs + 1_000); }; sync(); window.addEventListener("focus", sync); @@ -29,6 +38,6 @@ export function useLocalDayStartMs(): number { window.removeEventListener("focus", sync); document.removeEventListener("visibilitychange", sync); }; - }, []); + }, [startOfDayMs]); return dayStartMs; } diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index edd4999fd..233f4ebea 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -270,3 +270,9 @@ export function startOfLocalDayMs(nowMs: number, daysBack = 0): number { const now = new Date(nowMs); return new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysBack).getTime(); } + +/** UTC midnight of the day `daysBack` days before `nowMs`'s day (negative: after). */ +export function startOfUtcDayMs(nowMs: number, daysBack = 0): number { + const now = new Date(nowMs); + return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - daysBack); +}