Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 23 additions & 14 deletions apps/web/src/components/ProviderUsageDashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
Expand All @@ -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,
Expand Down Expand Up @@ -522,14 +532,13 @@ export function ProviderUsageDashboard(props: {
}) {
const [activityMode, setActivityMode] = useState<TokenActivityMode>("daily");
const [activityRange, setActivityRange] = useState<TokenActivityRange>("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;
Expand Down
73 changes: 73 additions & 0 deletions apps/web/src/components/settings/SettingsPanels.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3698,6 +3698,79 @@
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(
<TestAppProviders>
<ProviderSettingsPanel />
</TestAppProviders>,
);

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<LocalApi["server"]["updateSettings"]>()
Expand Down Expand Up @@ -7611,7 +7684,7 @@

let shown: ((id: SettingsPlaceSearchId) => boolean) | null = null;
function ReadShown() {
shown = useSettingsPlaceShown();

Check warning on line 7687 in apps/web/src/components/settings/SettingsPanels.browser.tsx

View workflow job for this annotation

GitHub Actions / Checks and Build

react(globals)

apps/web/src/components/settings/SettingsPanels.browser.tsx:7687:7: Cannot reassign variables declared outside of the component/hook
return null;
}
const liveRows = Object.entries(SETTINGS_ROWS).flatMap(([id, entry]) =>
Expand Down Expand Up @@ -7701,8 +7774,8 @@
let activeName: string | null = null;
let committedKind: string | null = null;
function ReadTheme() {
activeName = useActiveTheme().manifest?.name ?? null;

Check warning on line 7777 in apps/web/src/components/settings/SettingsPanels.browser.tsx

View workflow job for this annotation

GitHub Actions / Checks and Build

react(globals)

apps/web/src/components/settings/SettingsPanels.browser.tsx:7777:7: Cannot reassign variables declared outside of the component/hook
committedKind = useThemeChoice().kind;

Check warning on line 7778 in apps/web/src/components/settings/SettingsPanels.browser.tsx

View workflow job for this annotation

GitHub Actions / Checks and Build

react(globals)

apps/web/src/components/settings/SettingsPanels.browser.tsx:7778:7: Cannot reassign variables declared outside of the component/hook
return null;
}
await renderWithTestRouter(
Expand Down Expand Up @@ -7759,7 +7832,7 @@
setServerConfigSnapshot(createBaseServerConfig());
let activeName: string | null = null;
function ReadActive() {
activeName = useActiveTheme().manifest?.name ?? null;

Check warning on line 7835 in apps/web/src/components/settings/SettingsPanels.browser.tsx

View workflow job for this annotation

GitHub Actions / Checks and Build

react(globals)

apps/web/src/components/settings/SettingsPanels.browser.tsx:7835:7: Cannot reassign variables declared outside of the component/hook
return null;
}
await renderWithTestRouter(
Expand Down
19 changes: 14 additions & 5 deletions apps/web/src/hooks/useLocalDayStartMs.ts
Original file line number Diff line number Diff line change
@@ -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<typeof setTimeout> | undefined;
// Checks the day, then waits until just past the next midnight. A timer's
Expand All @@ -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);
Expand All @@ -29,6 +38,6 @@ export function useLocalDayStartMs(): number {
window.removeEventListener("focus", sync);
document.removeEventListener("visibilitychange", sync);
};
}, []);
}, [startOfDayMs]);
return dayStartMs;
}
6 changes: 6 additions & 0 deletions apps/web/src/timestampFormat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Loading