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
77 changes: 55 additions & 22 deletions apps/web/src/components/ProviderUsageDashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)}`;
}
Expand Down Expand Up @@ -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
Expand All @@ -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()) {
Expand All @@ -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,
Expand Down
24 changes: 24 additions & 0 deletions apps/web/src/components/settings/SettingsPanels.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>('[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 () => {
Expand Down
6 changes: 6 additions & 0 deletions apps/web/src/lib/providerUsage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
23 changes: 21 additions & 2 deletions apps/web/src/lib/providerUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
Expand Down
Loading