Skip to content
TypeScript

test(web): cover usage model ordering without static markup (#13104)

oliverb954af60c402
diff --git a/apps/web/src/components/usage/UsagePage.test.tsx b/apps/web/src/components/usage/UsagePage.test.tsx
deleted file mode 100644
index 4a00317c7e8..00000000000
--- a/apps/web/src/components/usage/UsagePage.test.tsx
+++ /dev/null
@@ -1,231 +0,0 @@
-import { EnvironmentId, UsageDay, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
-import { mergeUsage } from "@t3tools/shared/usageMerge";
-import { renderToStaticMarkup } from "react-dom/server";
-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
-
-const testState = vi.hoisted(() => ({
- useUsage: vi.fn(),
- metric: "cost" as "cost" | "tokens" | "limits",
- breakdown: "time" as "model" | "time",
-}));
-
-vi.mock("react", async (importOriginal) => {
- const actual = await importOriginal<typeof import("react")>();
- return {
- ...actual,
- useState: vi.fn((initial: unknown) => [
- initial === readUsagePagePreferences
- ? { metric: testState.metric, windowDays: 30 }
- : typeof initial === "function"
- ? {
- days: 1,
- window: {
- sinceDay: "2026-08-10",
- untilDay: "2026-08-11",
- timeZone: "UTC",
- resolution: "hour",
- sinceTime: "2026-08-10T12:37:00.000Z",
- untilTime: "2026-08-11T12:37:00.000Z",
- },
- }
- : initial === "cost"
- ? testState.metric
- : initial === "model"
- ? testState.breakdown
- : initial,
- vi.fn(),
- ]),
- };
-});
-
-vi.mock("../../env", () => ({ isElectron: false }));
-vi.mock("../../state/usage", () => ({ useUsage: testState.useUsage }));
-vi.mock("../ui/button", () => ({ Button: "button", InlineButton: "button" }));
-vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
-vi.mock("../ui/select", () => ({
- Select: "div",
- SelectItem: "div",
- SelectPopup: "div",
- SelectTrigger: "div",
- SelectValue: "div",
-}));
-vi.mock("../ui/sidebar", () => ({ SidebarInset: "div" }));
-vi.mock("../ui/toggle-group", () => ({ Toggle: "button", ToggleGroup: "div" }));
-vi.mock("../WorkspaceBreadcrumb", () => ({
- WorkspaceBreadcrumb: "div",
- WorkspaceBreadcrumbItem: "div",
- WorkspaceBreadcrumbSeparator: "span",
-}));
-vi.mock("../WorkspacePageContainer", () => ({ WorkspacePageContainer: "main" }));
-vi.mock("../WorkspacePageHeader", () => ({ WorkspacePageHeader: "header" }));
-vi.mock("./UsageProviderChart", () => ({ UsageProviderChart: "div" }));
-vi.mock("./UsagePriceOverrides", () => ({ UsagePriceOverrides: () => null }));
-vi.mock("./usageProviders", async (importOriginal) => {
- const actual = await importOriginal<typeof import("./usageProviders")>();
- return {
- ...actual,
- PROVIDER_PRESENTATION: {
- codex: { color: "white", label: "Codex", mark: "span" },
- claude: { color: "orange", label: "Claude Code", mark: "span" },
- },
- };
-});
-
-import { UsagePage } from "./UsagePage";
-import { readUsagePagePreferences } from "./usagePagePreferences";
-
-const providerTotals = (codex: number, claude: number) =>
- new Map([
- ["codex", { costUsd: codex, totalTokens: codex * 1_000 }],
- ["claude", { costUsd: claude, totalTokens: claude * 1_000 }],
- ] as const);
-
-const modelTotals = Object.freeze([
- {
- model: "expensive-model",
- provider: "claude" as const,
- costUsd: 10,
- totalTokens: 100,
- records: 1,
- unpricedRecords: 0,
- costShare: 10 / 16,
- },
- {
- model: "token-heavy-model",
- provider: "codex" as const,
- costUsd: 5,
- totalTokens: 1_000,
- records: 1,
- unpricedRecords: 0,
- costShare: 5 / 16,
- },
- {
- model: "token-heavy-cheaper-model",
- provider: "codex" as const,
- costUsd: 1,
- totalTokens: 1_000,
- records: 1,
- unpricedRecords: 0,
- costShare: 1 / 16,
- },
- {
- model: "unpriced-model",
- provider: "codex" as const,
- costUsd: 0,
- totalTokens: 500,
- records: 2,
- unpricedRecords: 2,
- costShare: 0,
- },
-]);
-
-const environments = [
- {
- environmentId: EnvironmentId.make("test-environment"),
- label: "Test environment",
- isPending: false,
- error: null,
- summary: {
- contractVersion: USAGE_CONTRACT_VERSION,
- readAt: "2026-08-11T12:37:00.000Z",
- sinceDay: UsageDay.make("2026-08-10"),
- untilDay: UsageDay.make("2026-08-11"),
- timeZone: "UTC",
- buckets: [],
- sources: [],
- pricing: { status: "fresh", source: "test", fetchedAt: null, knownModels: 1 },
- scanDurationMs: 1,
- },
- },
-];
-
-beforeEach(() => {
- testState.metric = "cost";
- testState.breakdown = "time";
- testState.useUsage.mockReturnValue({
- merged: {
- ...mergeUsage([], USAGE_CONTRACT_VERSION),
- models: modelTotals,
- hourly: [
- {
- day: "2026-08-10",
- hourStart: "2026-08-10T13:37:00.000Z",
- costUsd: 13,
- totalTokens: 13_000,
- byProvider: providerTotals(7, 6),
- },
- {
- day: "2026-08-11",
- hourStart: "2026-08-11T11:37:00.000Z",
- costUsd: 11,
- totalTokens: 11_000,
- byProvider: providerTotals(6, 5),
- },
- ],
- },
- environments,
- selectedEnvironments: environments,
- isPending: false,
- isPartial: false,
- refresh: vi.fn(),
- });
-});
-
-describe("UsagePage hourly breakdown", () => {
- it("keeps recent activity visible first without empty hourly rows", () => {
- const markup = renderToStaticMarkup(<UsagePage />);
- const body = markup.match(/<tbody>(.*?)<\/tbody>/)?.[1] ?? "";
-
- expect(body.match(/<tr/g)).toHaveLength(2);
- expect(body).toContain("$11.00");
- expect(body).toContain("$13.00");
- expect(body.indexOf("$11.00")).toBeLessThan(body.indexOf("$13.00"));
- });
-
- it("keeps chronological ordering when the token metric is selected", () => {
- testState.metric = "tokens";
-
- const markup = renderToStaticMarkup(<UsagePage />);
- const body = markup.match(/<tbody>(.*?)<\/tbody>/)?.[1] ?? "";
-
- expect(body).toMatch(/\$11\.00.*\$13\.00/);
- });
-});
-
-describe("UsagePage model breakdown", () => {
- it("sorts models by cost when the cost metric is selected", () => {
- testState.breakdown = "model";
-
- const markup = renderToStaticMarkup(<UsagePage />);
- const body = markup.match(/<tbody>(.*?)<\/tbody>/)?.[1] ?? "";
-
- expect(body).toMatch(/expensive-model.*token-heavy-model.*token-heavy-cheaper-model/);
- });
-
- it("flags a model with no known rates instead of showing it as free", () => {
- testState.breakdown = "model";
-
- const markup = renderToStaticMarkup(<UsagePage />);
- const body = markup.match(/<tbody>(.*?)<\/tbody>/)?.[1] ?? "";
- const unpricedRow = body.split("<tr").find((row) => row.includes("unpriced-model")) ?? "";
-
- expect(unpricedRow).toContain("Unpriced");
- expect(unpricedRow).not.toContain("$0.00");
- });
-
- it("sorts models by token usage when the token metric is selected", () => {
- testState.metric = "tokens";
- testState.breakdown = "model";
-
- const markup = renderToStaticMarkup(<UsagePage />);
- const body = markup.match(/<tbody>(.*?)<\/tbody>/)?.[1] ?? "";
-
- expect(body).toMatch(/token-heavy-model.*token-heavy-cheaper-model.*expensive-model/);
- expect(modelTotals.map((model) => model.model)).toEqual([
- "expensive-model",
- "token-heavy-model",
- "token-heavy-cheaper-model",
- "unpriced-model",
- ]);
- });
-});
diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx
index c9177d17275..87c72f0bc8a 100644
--- a/apps/web/src/components/usage/UsagePage.tsx
+++ b/apps/web/src/components/usage/UsagePage.tsx
@@ -63,6 +63,7 @@ import { WorkspacePageHeader } from "../WorkspacePageHeader";
import { UsageLimitsSection } from "./UsageLimits";
import { UsagePriceOverrides } from "./UsagePriceOverrides";
import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
+import { sortModelsByTokens } from "./usageBreakdown";
import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";
import {
readUsagePagePreferences,
@@ -141,9 +142,7 @@ export function UsagePage() {
const breakdownModels = useMemo(
() =>
breakdown === "model" && metric === "tokens"
- ? merged.models.toSorted(
- (left, right) => right.totalTokens - left.totalTokens || right.costUsd - left.costUsd,
- )
+ ? sortModelsByTokens(merged.models)
: merged.models,
[breakdown, merged.models, metric],
);
diff --git a/apps/web/src/components/usage/usageBreakdown.test.ts b/apps/web/src/components/usage/usageBreakdown.test.ts
new file mode 100644
index 00000000000..db84528ce36
--- /dev/null
+++ b/apps/web/src/components/usage/usageBreakdown.test.ts
@@ -0,0 +1,31 @@
+import type { ModelTotals } from "@t3tools/shared/usageMerge";
+import { describe, expect, it } from "vite-plus/test";
+
+import { sortModelsByTokens } from "./usageBreakdown";
+
+const model = (name: string, totalTokens: number, costUsd: number): ModelTotals => ({
+ model: name,
+ provider: "codex",
+ costUsd,
+ totalTokens,
+ records: 1,
+ unpricedRecords: 0,
+ costShare: 0,
+});
+
+describe("sortModelsByTokens", () => {
+ it("sorts by tokens, breaks ties by cost, and leaves the input alone", () => {
+ const models = [
+ model("lower-cost", 100, 1),
+ model("more-tokens", 200, 2),
+ model("higher-cost", 100, 3),
+ ];
+
+ expect(sortModelsByTokens(models).map((item) => item.model)).toEqual([
+ "more-tokens",
+ "higher-cost",
+ "lower-cost",
+ ]);
+ expect(models.map((item) => item.model)).toEqual(["lower-cost", "more-tokens", "higher-cost"]);
+ });
+});
diff --git a/apps/web/src/components/usage/usageBreakdown.ts b/apps/web/src/components/usage/usageBreakdown.ts
new file mode 100644
index 00000000000..8245b593e9a
--- /dev/null
+++ b/apps/web/src/components/usage/usageBreakdown.ts
@@ -0,0 +1,7 @@
+import type { ModelTotals } from "@t3tools/shared/usageMerge";
+
+export function sortModelsByTokens(models: readonly ModelTotals[]) {
+ return models.toSorted(
+ (left, right) => right.totalTokens - left.totalTokens || right.costUsd - left.costUsd,
+ );
+}
diff --git a/packages/shared/src/usageMerge.test.ts b/packages/shared/src/usageMerge.test.ts
index 142d6922f0c..668d8bcc272 100644
--- a/packages/shared/src/usageMerge.test.ts
+++ b/packages/shared/src/usageMerge.test.ts
@@ -273,6 +273,29 @@ describe("mergeUsage", () => {
]);
});
+ it("orders models by cost descending", () => {
+ const merged = mergeUsage(
+ [
+ environment(
+ "env-a",
+ summary(
+ [
+ bucket({ provider: "claude", model: "lower-cost", costUsd: 4 }),
+ bucket({ provider: "codex", model: "higher-cost", costUsd: 9 }),
+ ],
+ [
+ { provider: "claude", hostId: "mac", homePath: "/a/.claude" },
+ { provider: "codex", hostId: "mac", homePath: "/a/.codex" },
+ ],
+ ),
+ ),
+ ],
+ USAGE_CONTRACT_VERSION,
+ );
+
+ expect(merged.models.map((model) => model.model)).toEqual(["higher-cost", "lower-cost"]);
+ });
+
it("keeps two machines apart when hostname and home path collide", () => {
// Every Mac resolves /Users/theo/.claude, so a hostname clash used to make
// one machine's usage vanish. Filesystem identity separates them.