Skip to content

Commit 50f517b

Browse files
committed
fix(web): keep usage controls working when storage fails
1 parent 4c0d6b0 commit 50f517b

4 files changed

Lines changed: 135 additions & 45 deletions

File tree

‎apps/web/src/components/usage/UsagePage.test.tsx‎

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,40 +7,38 @@ const testState = vi.hoisted(() => ({
77
useUsage: vi.fn(),
88
metric: "cost" as "cost" | "tokens" | "limits",
99
breakdown: "time" as "model" | "time",
10-
setPreferences: vi.fn(),
1110
}));
1211

1312
vi.mock("react", async (importOriginal) => {
1413
const actual = await importOriginal<typeof import("react")>();
1514
return {
1615
...actual,
1716
useState: vi.fn((initial: unknown) => [
18-
typeof initial === "function"
19-
? {
20-
days: 1,
21-
window: {
22-
sinceDay: "2026-08-10",
23-
untilDay: "2026-08-11",
24-
timeZone: "UTC",
25-
resolution: "hour",
26-
sinceTime: "2026-08-10T12:37:00.000Z",
27-
untilTime: "2026-08-11T12:37:00.000Z",
28-
},
29-
}
30-
: initial === "cost"
31-
? testState.metric
32-
: initial === "model"
33-
? testState.breakdown
34-
: initial,
17+
initial === readUsagePagePreferences
18+
? { metric: testState.metric, windowDays: 30 }
19+
: typeof initial === "function"
20+
? {
21+
days: 1,
22+
window: {
23+
sinceDay: "2026-08-10",
24+
untilDay: "2026-08-11",
25+
timeZone: "UTC",
26+
resolution: "hour",
27+
sinceTime: "2026-08-10T12:37:00.000Z",
28+
untilTime: "2026-08-11T12:37:00.000Z",
29+
},
30+
}
31+
: initial === "cost"
32+
? testState.metric
33+
: initial === "model"
34+
? testState.breakdown
35+
: initial,
3536
vi.fn(),
3637
]),
3738
};
3839
});
3940

4041
vi.mock("../../env", () => ({ isElectron: false }));
41-
vi.mock("../../hooks/useLocalStorage", () => ({
42-
useLocalStorage: () => [{ metric: testState.metric, windowDays: 30 }, testState.setPreferences],
43-
}));
4442
vi.mock("../../state/usage", () => ({ useUsage: testState.useUsage }));
4543
vi.mock("../ui/button", () => ({ Button: "button" }));
4644
vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
@@ -74,6 +72,7 @@ vi.mock("./usageProviders", async (importOriginal) => {
7472
});
7573

7674
import { UsagePage } from "./UsagePage";
75+
import { readUsagePagePreferences } from "./usagePagePreferences";
7776

7877
const providerTotals = (codex: number, claude: number) =>
7978
new Map([

‎apps/web/src/components/usage/UsagePage.tsx‎

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { useAtomValue } from "@effect/atom-react";
2-
import * as Schema from "effect/Schema";
32
import {
43
USAGE_CONTRACT_VERSION,
54
type EnvironmentId,
@@ -21,7 +20,6 @@ import {
2120
} from "@t3tools/shared/usageMerge";
2221

2322
import { isElectron } from "../../env";
24-
import { useLocalStorage } from "../../hooks/useLocalStorage";
2523
import { cn } from "../../lib/utils";
2624
import { environmentPresentations } from "../../state/presentation";
2725
import { serverEnvironment } from "../../state/server";
@@ -64,6 +62,11 @@ import { UsageLimitsSection } from "./UsageLimits";
6462
import { UsagePriceOverrides } from "./UsagePriceOverrides";
6563
import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
6664
import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";
65+
import {
66+
readUsagePagePreferences,
67+
saveUsagePagePreferences,
68+
type UsagePagePreferences,
69+
} from "./usagePagePreferences";
6770

6871
type UsageMetric = UsageChartMetric | "limits";
6972
const METRIC_OPTIONS = [
@@ -72,20 +75,6 @@ const METRIC_OPTIONS = [
7275
{ value: "limits", label: "Limits" },
7376
] as const satisfies readonly { value: UsageMetric; label: string }[];
7477

75-
const USAGE_PAGE_PREFERENCES_STORAGE_KEY = "t3code:usage-page-preferences:v1";
76-
const UsageMetricSchema = Schema.Literals(["cost", "tokens", "limits"]);
77-
const UsageWindowDaysSchema = Schema.Literals([1, 7, 30, 90]);
78-
type UsageWindowDays = typeof UsageWindowDaysSchema.Type;
79-
const UsagePagePreferencesSchema = Schema.Struct({
80-
metric: UsageMetricSchema,
81-
windowDays: UsageWindowDaysSchema,
82-
});
83-
type UsagePagePreferences = typeof UsagePagePreferencesSchema.Type;
84-
const DEFAULT_USAGE_PAGE_PREFERENCES: UsagePagePreferences = {
85-
metric: "cost",
86-
windowDays: 30,
87-
};
88-
8978
function isUsageMetric(value: string | null | undefined): value is UsageMetric {
9079
return METRIC_OPTIONS.some((option) => option.value === value);
9180
}
@@ -97,16 +86,12 @@ const WINDOW_OPTIONS = [
9786
{ days: 90, label: "90 days" },
9887
] as const;
9988

100-
function isUsageWindowDays(value: number): value is UsageWindowDays {
89+
function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] {
10190
return WINDOW_OPTIONS.some((option) => option.days === value);
10291
}
10392

10493
export function UsagePage() {
105-
const [preferences, setPreferences] = useLocalStorage(
106-
USAGE_PAGE_PREFERENCES_STORAGE_KEY,
107-
DEFAULT_USAGE_PAGE_PREFERENCES,
108-
UsagePagePreferencesSchema,
109-
);
94+
const [preferences, setPreferences] = useState(readUsagePagePreferences);
11095
const [windowSelection, setWindowSelection] = useState(() => ({
11196
days: preferences.windowDays,
11297
window: makeWindow(
@@ -162,14 +147,18 @@ export function UsagePage() {
162147

163148
const selectWindow = (days: number) => {
164149
if (!isUsageWindowDays(days)) return;
165-
setPreferences((current) => ({ ...current, windowDays: days }));
150+
const nextPreferences = { metric, windowDays: days };
151+
setPreferences(nextPreferences);
152+
saveUsagePagePreferences(nextPreferences);
166153
setWindowSelection({
167154
days,
168155
window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
169156
});
170157
};
171158
const selectMetric = (nextMetric: UsageMetric) => {
172-
setPreferences((current) => ({ ...current, metric: nextMetric }));
159+
const nextPreferences = { metric: nextMetric, windowDays };
160+
setPreferences(nextPreferences);
161+
saveUsagePagePreferences(nextPreferences);
173162
};
174163
const refreshWindow = () => {
175164
if (showingLimits) {
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2+
3+
import { readUsagePagePreferences, saveUsagePagePreferences } from "./usagePagePreferences";
4+
5+
const key = "t3code:usage-page-preferences:v1";
6+
let values: Map<string, string>;
7+
let storage: Pick<Storage, "getItem" | "setItem">;
8+
9+
beforeEach(() => {
10+
values = new Map();
11+
storage = {
12+
getItem: (key) => values.get(key) ?? null,
13+
setItem: (key, value) => {
14+
values.set(key, value);
15+
},
16+
};
17+
vi.stubGlobal("window", { localStorage: storage });
18+
vi.spyOn(console, "error").mockImplementation(() => {});
19+
});
20+
21+
afterEach(() => {
22+
vi.restoreAllMocks();
23+
vi.unstubAllGlobals();
24+
});
25+
26+
describe("Usage page preferences", () => {
27+
it("uses defaults when no preference has been saved", () => {
28+
expect(readUsagePagePreferences()).toEqual({ metric: "cost", windowDays: 30 });
29+
});
30+
31+
it.each([1, 7, 30, 90] as const)("round-trips every metric with a %i-day range", (windowDays) => {
32+
for (const metric of ["cost", "tokens", "limits"] as const) {
33+
saveUsagePagePreferences({ metric, windowDays });
34+
expect(readUsagePagePreferences()).toEqual({ metric, windowDays });
35+
}
36+
});
37+
38+
it.each([
39+
"not-json",
40+
'{"metric":"unknown","windowDays":7}',
41+
'{"metric":"cost","windowDays":365}',
42+
])("replaces invalid preferences on the next save: %s", (value) => {
43+
values.set(key, value);
44+
expect(readUsagePagePreferences()).toEqual({ metric: "cost", windowDays: 30 });
45+
saveUsagePagePreferences({ metric: "tokens", windowDays: 7 });
46+
expect(readUsagePagePreferences()).toEqual({ metric: "tokens", windowDays: 7 });
47+
});
48+
49+
it("contains write failures and can save again after storage recovers", () => {
50+
saveUsagePagePreferences({ metric: "cost", windowDays: 30 });
51+
const write = vi.spyOn(storage, "setItem").mockImplementation(() => {
52+
throw new Error("QuotaExceededError");
53+
});
54+
expect(() => saveUsagePagePreferences({ metric: "tokens", windowDays: 7 })).not.toThrow();
55+
expect(readUsagePagePreferences()).toEqual({ metric: "cost", windowDays: 30 });
56+
write.mockRestore();
57+
saveUsagePagePreferences({ metric: "limits", windowDays: 7 });
58+
expect(readUsagePagePreferences()).toEqual({ metric: "limits", windowDays: 7 });
59+
});
60+
61+
it("contains failures when the browser blocks storage access", () => {
62+
vi.stubGlobal("window", {
63+
get localStorage() {
64+
throw new Error("SecurityError");
65+
},
66+
});
67+
expect(readUsagePagePreferences()).toEqual({ metric: "cost", windowDays: 30 });
68+
expect(() => saveUsagePagePreferences({ metric: "tokens", windowDays: 7 })).not.toThrow();
69+
});
70+
});
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import * as Schema from "effect/Schema";
2+
3+
import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalStorage";
4+
5+
const STORAGE_KEY = "t3code:usage-page-preferences:v1";
6+
const UsagePagePreferencesSchema = Schema.Struct({
7+
metric: Schema.Literals(["cost", "tokens", "limits"]),
8+
windowDays: Schema.Literals([1, 7, 30, 90]),
9+
});
10+
export type UsagePagePreferences = typeof UsagePagePreferencesSchema.Type;
11+
12+
export function readUsagePagePreferences(): UsagePagePreferences {
13+
try {
14+
return (
15+
getLocalStorageItem(STORAGE_KEY, UsagePagePreferencesSchema) ?? {
16+
metric: "cost",
17+
windowDays: 30,
18+
}
19+
);
20+
} catch (error) {
21+
console.error("Could not read Usage page preferences.", error);
22+
return { metric: "cost", windowDays: 30 };
23+
}
24+
}
25+
26+
export function saveUsagePagePreferences(preferences: UsagePagePreferences): void {
27+
try {
28+
setLocalStorageItem(STORAGE_KEY, preferences, UsagePagePreferencesSchema);
29+
} catch (error) {
30+
console.error("Could not save Usage page preferences.", error);
31+
}
32+
}

0 commit comments

Comments
 (0)