Skip to content
TypeScript

fix(web): remember usage page selection (#10189)

Exoticadd8c3a55ac8
diff --git a/apps/web/src/components/usage/UsagePage.test.tsx b/apps/web/src/components/usage/UsagePage.test.tsx
index 944987388b0..e41843e6d9c 100644
--- a/apps/web/src/components/usage/UsagePage.test.tsx
+++ b/apps/web/src/components/usage/UsagePage.test.tsx
@@ -5,7 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const testState = vi.hoisted(() => ({
useUsage: vi.fn(),
- metric: "cost" as "cost" | "tokens",
+ metric: "cost" as "cost" | "tokens" | "limits",
breakdown: "time" as "model" | "time",
}));
@@ -14,23 +14,25 @@ vi.mock("react", async (importOriginal) => {
return {
...actual,
useState: vi.fn((initial: unknown) => [
- 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,
+ 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(),
]),
};
@@ -70,6 +72,7 @@ vi.mock("./usageProviders", async (importOriginal) => {
});
import { UsagePage } from "./UsagePage";
+import { readUsagePagePreferences } from "./usagePagePreferences";
const providerTotals = (codex: number, claude: number) =>
new Map([
diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx
index f0dcec49ad9..deb05f266b9 100644
--- a/apps/web/src/components/usage/UsagePage.tsx
+++ b/apps/web/src/components/usage/UsagePage.tsx
@@ -62,6 +62,11 @@ import { UsageLimitsSection } from "./UsageLimits";
import { UsagePriceOverrides } from "./UsagePriceOverrides";
import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";
+import {
+ readUsagePagePreferences,
+ saveUsagePagePreferences,
+ type UsagePagePreferences,
+} from "./usagePagePreferences";
type UsageMetric = UsageChartMetric | "limits";
const METRIC_OPTIONS = [
@@ -81,12 +86,21 @@ const WINDOW_OPTIONS = [
{ days: 90, label: "90 days" },
] as const;
+function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] {
+ return WINDOW_OPTIONS.some((option) => option.days === value);
+}
+
export function UsagePage() {
+ const [preferences, setPreferences] = useState(readUsagePagePreferences);
const [windowSelection, setWindowSelection] = useState(() => ({
- days: 30,
- window: makeWindow(30),
+ days: preferences.windowDays,
+ window: makeWindow(
+ preferences.windowDays,
+ undefined,
+ preferences.windowDays === 1 ? "hour" : "day",
+ ),
}));
- const [metric, setMetric] = useState<UsageMetric>("cost");
+ const metric = preferences.metric;
const showingLimits = metric === "limits";
const [isRefreshing, setIsRefreshing] = useState(false);
const refreshingRef = useRef(false);
@@ -134,11 +148,20 @@ export function UsagePage() {
const timeValueColumnWidth = `${60 / (activeProviders.length + 2)}%`;
const selectWindow = (days: number) => {
+ if (!isUsageWindowDays(days)) return;
+ const nextPreferences = { metric, windowDays: days };
+ setPreferences(nextPreferences);
+ saveUsagePagePreferences(nextPreferences);
setWindowSelection({
days,
window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
});
};
+ const selectMetric = (nextMetric: UsageMetric) => {
+ const nextPreferences = { metric: nextMetric, windowDays };
+ setPreferences(nextPreferences);
+ saveUsagePagePreferences(nextPreferences);
+ };
const refreshWindow = () => {
if (refreshingRef.current) return;
@@ -210,7 +233,7 @@ export function UsagePage() {
value={[metric]}
onValueChange={(next) => {
const value = next[0];
- if (isUsageMetric(value)) setMetric(value);
+ if (isUsageMetric(value)) selectMetric(value);
}}
>
{METRIC_OPTIONS.map((option) => (
@@ -252,7 +275,7 @@ export function UsagePage() {
<Select
value={metric}
onValueChange={(value) => {
- if (isUsageMetric(value)) setMetric(value);
+ if (isUsageMetric(value)) selectMetric(value);
}}
>
<SelectTrigger
diff --git a/apps/web/src/components/usage/usagePagePreferences.test.ts b/apps/web/src/components/usage/usagePagePreferences.test.ts
new file mode 100644
index 00000000000..dcdde98fa24
--- /dev/null
+++ b/apps/web/src/components/usage/usagePagePreferences.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { readUsagePagePreferences, saveUsagePagePreferences } from "./usagePagePreferences";
+
+const key = "t3code:usage-page-preferences:v1";
+let values: Map<string, string>;
+let storage: Pick<Storage, "getItem" | "setItem">;
+
+beforeEach(() => {
+ values = new Map();
+ storage = {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => {
+ values.set(key, value);
+ },
+ };
+ vi.stubGlobal("window", { localStorage: storage });
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe("Usage page preferences", () => {
+ it("uses defaults when no preference has been saved", () => {
+ expect(readUsagePagePreferences()).toEqual({ metric: "cost", windowDays: 30 });
+ });
+
+ it.each([1, 7, 30, 90] as const)("round-trips every metric with a %i-day range", (windowDays) => {
+ for (const metric of ["cost", "tokens", "limits"] as const) {
+ saveUsagePagePreferences({ metric, windowDays });
+ expect(readUsagePagePreferences()).toEqual({ metric, windowDays });
+ }
+ });
+
+ it.each([
+ "not-json",
+ '{"metric":"unknown","windowDays":7}',
+ '{"metric":"cost","windowDays":365}',
+ ])("replaces invalid preferences on the next save: %s", (value) => {
+ values.set(key, value);
+ expect(readUsagePagePreferences()).toEqual({ metric: "cost", windowDays: 30 });
+ saveUsagePagePreferences({ metric: "tokens", windowDays: 7 });
+ expect(readUsagePagePreferences()).toEqual({ metric: "tokens", windowDays: 7 });
+ });
+
+ it("contains write failures and can save again after storage recovers", () => {
+ saveUsagePagePreferences({ metric: "cost", windowDays: 30 });
+ const write = vi.spyOn(storage, "setItem").mockImplementation(() => {
+ throw new Error("QuotaExceededError");
+ });
+ expect(() => saveUsagePagePreferences({ metric: "tokens", windowDays: 7 })).not.toThrow();
+ expect(readUsagePagePreferences()).toEqual({ metric: "cost", windowDays: 30 });
+ write.mockRestore();
+ saveUsagePagePreferences({ metric: "limits", windowDays: 7 });
+ expect(readUsagePagePreferences()).toEqual({ metric: "limits", windowDays: 7 });
+ });
+
+ it("contains failures when the browser blocks storage access", () => {
+ vi.stubGlobal("window", {
+ get localStorage() {
+ throw new Error("SecurityError");
+ },
+ });
+ expect(readUsagePagePreferences()).toEqual({ metric: "cost", windowDays: 30 });
+ expect(() => saveUsagePagePreferences({ metric: "tokens", windowDays: 7 })).not.toThrow();
+ });
+});
diff --git a/apps/web/src/components/usage/usagePagePreferences.ts b/apps/web/src/components/usage/usagePagePreferences.ts
new file mode 100644
index 00000000000..ddd6d5341cc
--- /dev/null
+++ b/apps/web/src/components/usage/usagePagePreferences.ts
@@ -0,0 +1,32 @@
+import * as Schema from "effect/Schema";
+
+import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalStorage";
+
+const STORAGE_KEY = "t3code:usage-page-preferences:v1";
+const UsagePagePreferencesSchema = Schema.Struct({
+ metric: Schema.Literals(["cost", "tokens", "limits"]),
+ windowDays: Schema.Literals([1, 7, 30, 90]),
+});
+export type UsagePagePreferences = typeof UsagePagePreferencesSchema.Type;
+
+export function readUsagePagePreferences(): UsagePagePreferences {
+ try {
+ return (
+ getLocalStorageItem(STORAGE_KEY, UsagePagePreferencesSchema) ?? {
+ metric: "cost",
+ windowDays: 30,
+ }
+ );
+ } catch (error) {
+ console.error("Could not read Usage page preferences.", error);
+ return { metric: "cost", windowDays: 30 };
+ }
+}
+
+export function saveUsagePagePreferences(preferences: UsagePagePreferences): void {
+ try {
+ setLocalStorageItem(STORAGE_KEY, preferences, UsagePagePreferencesSchema);
+ } catch (error) {
+ console.error("Could not save Usage page preferences.", error);
+ }
+}