feat(webui): show the full token-usage picture in settings (#6638)
This commit is contained in:
1 parent
b49218b6a3
commit
e6b23c7356
42 files changed
+1116
-342
No files matched your search
@@ -707,6 +707,34 @@ describe("webui API helpers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("shares only pending settings reads within the same client", async () => {
|
||||
const pending: ((response: Response) => void)[] = [];
|
||||
vi.mocked(fetch).mockImplementation(() => new Promise<Response>((resolve) => pending.push(resolve)));
|
||||
const first = fetchSettings("tok", "", mutationTransport);
|
||||
expect(fetchSettings("tok", "", mutationTransport)).toBe(first);
|
||||
const other = fetchSettings("tok", "", { requestMutation });
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
pending[0]({ ok: true, json: async () => ({ version: { current: "first" } }) } as Response);
|
||||
pending[1]({ ok: true, json: async () => ({ version: { current: "other" } }) } as Response);
|
||||
expect((await first).version?.current).toBe("first");
|
||||
expect((await other).version?.current).toBe("other");
|
||||
const refreshed = fetchSettings("tok", "", mutationTransport);
|
||||
expect(fetch).toHaveBeenCalledTimes(3);
|
||||
pending[2]({ ok: true, json: async () => ({ version: { current: "refreshed" } }) } as Response);
|
||||
expect((await refreshed).version?.current).toBe("refreshed");
|
||||
});
|
||||
|
||||
it("reuses unchanged usage and requests model details explicitly", async () => {
|
||||
const cached = { days: [], revision: "models" };
|
||||
const json = vi.fn();
|
||||
vi.mocked(fetch).mockResolvedValue({ status: 304, json } as unknown as Response);
|
||||
expect(await fetchSettingsUsage("tok", { details: true, cached })).toBe(cached);
|
||||
expect(fetch).toHaveBeenCalledWith("/api/settings/usage?details=true", expect.objectContaining({
|
||||
headers: { Authorization: "Bearer tok", "If-None-Match": 'W/"models"' },
|
||||
}));
|
||||
expect(json).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("serializes model configuration creation", async () => {
|
||||
await createModelConfiguration(mutationTransport, {
|
||||
name: "Fast writing",
|
||||
|
||||
@@ -662,6 +662,20 @@ describe("App layout", () => {
|
||||
expect(asideClassNames.some((cls) => cls.includes("lg:block"))).toBe(true);
|
||||
});
|
||||
|
||||
it("loads settings once when opening the overview directly", async () => {
|
||||
window.location.hash = "#/settings";
|
||||
mockFetchRoutes({ "/api/settings": baseSettingsPayload(), "/api/settings/usage": { days: [] } });
|
||||
render(<App />);
|
||||
await act(async () => { await import("@/components/settings/SettingsView"); });
|
||||
expect(await screen.findByRole("navigation", { name: "Settings sections" })).toBeInTheDocument();
|
||||
expect(await screen.findByText("Token usage")).toBeInTheDocument();
|
||||
const reads = () => vi.mocked(fetch).mock.calls.filter(([url]) => String(url) === "/api/settings");
|
||||
expect(reads()).toHaveLength(1);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Back to chat" }));
|
||||
await screen.findByRole("navigation", { name: "Sidebar navigation" });
|
||||
expect(reads()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("uses one main landmark and a page heading in desktop settings", async () => {
|
||||
mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
|
||||
const { container } = render(<App />);
|
||||
|
||||
@@ -569,13 +569,14 @@ describe("Settings capabilities", () => {
|
||||
requestMutationMock.mockResolvedValueOnce(saved);
|
||||
let refreshParent!: (snapshot: SettingsPayload) => void;
|
||||
let parentSnapshot: SettingsPayload = payload;
|
||||
const client = { requestMutation: requestMutationMock, status: "open",
|
||||
onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; },
|
||||
} as never;
|
||||
function Parent() {
|
||||
const [snapshot, setSnapshot] = useState<SettingsPayload>(payload);
|
||||
parentSnapshot = snapshot;
|
||||
refreshParent = setSnapshot;
|
||||
return <ClientProvider client={{ requestMutation: requestMutationMock, status: "open",
|
||||
onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; },
|
||||
} as never} token="tok">
|
||||
return <ClientProvider client={client} token="tok">
|
||||
<SettingsView themePreference="light" initialSection="voice" initialSettings={snapshot}
|
||||
onSettingsChange={setSnapshot} onNativeEngineRestart={restart}
|
||||
onChangeTheme={() => {}} onBackToChat={() => {}} onModelNameChange={() => {}} />
|
||||
|
||||
@@ -386,6 +386,7 @@ describe("Settings overview and appearance", () => {
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url === "/api/settings") return jsonResponse(payload);
|
||||
if (url === "/api/settings/usage") return jsonResponse(payload.usage);
|
||||
if (url === "/api/settings/cli-apps") {
|
||||
return jsonResponse({ apps: [], installed_count: 0 });
|
||||
}
|
||||
@@ -398,7 +399,7 @@ describe("Settings overview and appearance", () => {
|
||||
|
||||
renderSettingsView({ initialSection: "overview" });
|
||||
|
||||
expect(await screen.findByLabelText("1,500 tokens")).toBeInTheDocument();
|
||||
expect(await screen.findByLabelText("1,500 tokens in the last 30 days")).toBeInTheDocument();
|
||||
expect(screen.getByText("Token usage")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ function day(date: string, tokens: number): Usage["days"][number] {
|
||||
cache_write_observed_input_tokens: 0, requests: 1 };
|
||||
}
|
||||
function usage(days: Usage["days"]): Usage {
|
||||
return { days, total_tokens: 999999, total_tokens_30d: 999999, total_tokens_365d: 999999,
|
||||
return { days, total_tokens: 999999, total_tokens_30d: 999999, total_tokens_365d: 1_500_000,
|
||||
peak_day_tokens: 999999, current_streak_days: 0, longest_streak_days: 0,
|
||||
active_days_30d: 0, requests_30d: 0, updated_at: "2026-09-09T00:00:00Z" };
|
||||
}
|
||||
@@ -33,7 +33,7 @@ describe("Token usage card", () => {
|
||||
const baseline = container.querySelector<HTMLElement>('[data-model-usage-gridline="2"]')!;
|
||||
expect(plot).toContainElement(baseline);
|
||||
expect(baseline.parentElement).toHaveStyle({ top: "100%" });
|
||||
expect(plot).not.toContainElement(screen.getByText("09-01"));
|
||||
expect(plot).not.toContainElement(screen.getByText("Sep 1"));
|
||||
expect(bars[0].firstElementChild).toHaveStyle({ height: "100%" });
|
||||
expect(bars[0].firstElementChild?.children).toHaveLength(2);
|
||||
expect(bars[1].firstElementChild).toHaveStyle({ height: `${1 / 30_000_000 * 100}%` });
|
||||
@@ -46,17 +46,17 @@ describe("Token usage card", () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("uses one 30-day window for the total, chart and source percentages", () => {
|
||||
const today = { ...day("2026-09-09", 300), input_tokens: 240, output_tokens: 60, cache_read_tokens: 120, cache_read_observed_input_tokens: 180, estimated_tokens: 100,
|
||||
const today = { ...day("2026-09-09", 300), input_tokens: 240, output_tokens: 60, cache_read_tokens: 120, cache_read_observed_input_tokens: 180, cache_miss_tokens: 60, cache_unknown_tokens: 60, estimated_tokens: 100,
|
||||
sources: { user: day("2026-09-09", 200) } };
|
||||
render(<TokenUsageCard timeZone="UTC" usage={usage([
|
||||
day("2026-08-10", 9000), day("2026-08-11", 100), today, day("2026-09-10", 9000),
|
||||
])} />);
|
||||
expect(screen.getByLabelText("400 tokens")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("400 tokens in the last 30 days")).toBeInTheDocument();
|
||||
const bars = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img");
|
||||
expect(bars).toHaveLength(30);
|
||||
expect(bars.filter((bar) => bar.tabIndex === 0)).toEqual([bars[0], bars[29]]);
|
||||
expect(bars[0]).toHaveAccessibleName(/2026-08-11: 100 tokens, 1 requests/);
|
||||
expect(bars[29]).toHaveAccessibleName(/Cached input: 120, Cache miss: 60, Unknown status: 60, Output: 60/);
|
||||
expect(bars[29]).toHaveAccessibleName(/Cached input: 120, Cache write: 0, Cache miss: 60, Unknown status: 60, Output: 60/);
|
||||
const segments = bars[29].firstElementChild?.children;
|
||||
expect(segments).toHaveLength(4);
|
||||
expect(segments?.[0]).toHaveStyle({ height: "40%" });
|
||||
@@ -66,6 +66,43 @@ describe("Token usage card", () => {
|
||||
expect(bars[0]).toHaveAccessibleName(/Cache miss: 0, Unknown status: 100/);
|
||||
expect(screen.getAllByText("50%")).toHaveLength(2);
|
||||
expect(screen.getByText("Unclassified")).toBeInTheDocument();
|
||||
expect(screen.getByText("13.3")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Sep 9/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([0, 100])("partitions cache writes without overlap when cached input is %i", (read) => {
|
||||
const output = read === 0 ? 20 : 40;
|
||||
const total = read + 100 + output;
|
||||
const today = { ...day("2026-09-09", total), input_tokens: read + 100, output_tokens: output,
|
||||
cache_read_tokens: read, cache_write_tokens: 100,
|
||||
cache_read_observed_input_tokens: read, cache_write_observed_input_tokens: read + 100,
|
||||
cache_miss_tokens: 0, cache_unknown_tokens: 0 };
|
||||
render(<TokenUsageCard usage={usage([today])} />);
|
||||
const bar = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img")[29];
|
||||
expect(bar).toHaveAccessibleName(new RegExp(`Cached input: ${read}, Cache write: 100, Cache miss: 0, Unknown status: 0, Output: ${output}`));
|
||||
const segments = Array.from(bar.firstElementChild!.children);
|
||||
const values = [read, 100, output].filter(value => value > 0);
|
||||
expect(segments).toHaveLength(values.length);
|
||||
segments.forEach((segment, index) => expect(segment).toHaveStyle({ height: `${values[index] / total * 100}%` }));
|
||||
});
|
||||
|
||||
it("keeps the read-only breakdown for older backends without per-call partitions", () => {
|
||||
render(<TokenUsageCard usage={usage([{ ...day("2026-09-09", 240), input_tokens: 200, output_tokens: 40,
|
||||
cache_read_tokens: 100, cache_write_tokens: 100,
|
||||
cache_read_observed_input_tokens: 100, cache_write_observed_input_tokens: 200 }])} />);
|
||||
const bar = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img")[29];
|
||||
expect(bar).toHaveAccessibleName(/Cached input: 100, Cache write: 0, Cache miss: 0, Unknown status: 100, Output: 40/);
|
||||
expect(bar.firstElementChild?.children).toHaveLength(3);
|
||||
expect(bar.firstElementChild?.children[1]).toHaveStyle({ height: `${100 / 240 * 100}%` });
|
||||
});
|
||||
|
||||
it("hides a legend entry when that segment stays empty across the window", () => {
|
||||
const today = { ...day("2026-09-09", 1000), cache_read_tokens: 200, cache_read_observed_input_tokens: 400 };
|
||||
const { rerender } = render(<TokenUsageCard usage={usage([today])} />);
|
||||
expect(screen.getByText("Cached input")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Cache write")).not.toBeInTheDocument();
|
||||
rerender(<TokenUsageCard usage={usage([{ ...today, cache_write_tokens: 150, cache_write_observed_input_tokens: 400, cache_miss_tokens: 50, cache_unknown_tokens: 600 }])} />);
|
||||
expect(screen.getByText("Cache write")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an empty state for zero usage", () => {
|
||||
@@ -73,15 +110,11 @@ describe("Token usage card", () => {
|
||||
expect(screen.getByRole("status")).toHaveTextContent("No token usage in the last 30 days.");
|
||||
});
|
||||
|
||||
it("opens details and computes the weighted cache rate from observed input only", () => {
|
||||
render(<TokenUsageCard usage={usage([
|
||||
{ ...day("2026-09-08", 100), cache_read_tokens: 80, cache_read_observed_input_tokens: 100 },
|
||||
{ ...day("2026-09-09", 900), cache_read_tokens: 20, cache_read_observed_input_tokens: 300 },
|
||||
])} />);
|
||||
it("flags the share of tokens that were estimated locally", () => {
|
||||
render(<TokenUsageCard usage={usage([{ ...day("2026-09-09", 1000), estimated_tokens: 250 }])} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "View details" }));
|
||||
const details = screen.getByRole("dialog", { name: "Token usage" });
|
||||
expect(within(details).getByText("25%")).toBeInTheDocument();
|
||||
expect(within(details).getByTitle("Cache hit rate excludes input with unknown cache status.")).toBeInTheDocument();
|
||||
expect(within(details).getByText("25% of tokens are estimated")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not misrepresent unavailable usage as zero", () => {
|
||||
@@ -90,6 +123,49 @@ describe("Token usage card", () => {
|
||||
expect(screen.getByText("—")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("merges one model recorded under a provider prefix and a bare id", () => {
|
||||
const days = Array.from({ length: 30 }, (_, index) => {
|
||||
const date = new Date("2026-09-09T00:00:00Z");
|
||||
date.setUTCDate(date.getUTCDate() - 29 + index);
|
||||
const key = date.toISOString().slice(0, 10);
|
||||
return { date: key, usage: day(key, index === 29 ? 1000 : 0) };
|
||||
});
|
||||
render(<TokenUsageModelTrend days={days} models={[
|
||||
{ ...day("2026-09-09", 600), provider: "openai_codex", model: "openai-codex/gpt-6",
|
||||
cache_read_tokens: 100, cache_read_observed_input_tokens: 200,
|
||||
reported_tokens: 600, estimated_tokens: 0, successful_requests: 1, failed_requests: 0,
|
||||
reported_requests: 1, estimated_requests: 0, generation_ms: 0, measured_output_tokens: 0,
|
||||
ttft_ms: 0, timed_requests: 0, duration_ms: 0 },
|
||||
{ ...day("2026-09-09", 400), provider: "openai_codex", model: "gpt-6",
|
||||
cache_read_tokens: 50, cache_read_observed_input_tokens: 100,
|
||||
reported_tokens: 400, estimated_tokens: 0, successful_requests: 1, failed_requests: 0,
|
||||
reported_requests: 1, estimated_requests: 0, generation_ms: 0, measured_output_tokens: 0,
|
||||
ttft_ms: 0, timed_requests: 0, duration_ms: 0 },
|
||||
]} modelDays={[
|
||||
{ date: "2026-09-09", provider: "openai_codex", model: "openai-codex/gpt-6", total_tokens: 600 },
|
||||
{ date: "2026-09-09", provider: "openai_codex", model: "gpt-6", total_tokens: 400 },
|
||||
]} />);
|
||||
expect(screen.getAllByText("gpt-6")).toHaveLength(1);
|
||||
expect(screen.getByLabelText("gpt-6: Total tokens: 1,000 (100%), Cache hit rate: 50%")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reports per-model speed, first-token wait and cache hit rate where measured", () => {
|
||||
const days = Array.from({ length: 30 }, (_, index) => {
|
||||
const date = new Date("2026-09-09T00:00:00Z");
|
||||
date.setUTCDate(date.getUTCDate() - 29 + index);
|
||||
const key = date.toISOString().slice(0, 10);
|
||||
return { date: key, usage: day(key, index === 29 ? 1500 : 0) };
|
||||
});
|
||||
render(<TokenUsageModelTrend days={days} modelDays={[
|
||||
{ date: "2026-09-09", provider: "openai", model: "fast", total_tokens: 1000, measured_output_tokens: 400, generation_ms: 8000, ttft_ms: 3200, timed_requests: 1, cache_read_tokens: 700, cache_read_observed_input_tokens: 1000 },
|
||||
{ date: "2026-09-09", provider: "openai", model: "legacy", total_tokens: 500 },
|
||||
]} />);
|
||||
const column = screen.getAllByRole("img")[29];
|
||||
const label = column.getAttribute("aria-label") ?? "";
|
||||
expect(label).toContain("fast: 1,000, 50 tok/s, 3.2s to first token, 70% cache hit");
|
||||
expect(label).toContain("legacy: 500, Other models");
|
||||
});
|
||||
|
||||
it("keeps the five leading model series and reconciles the rest to the daily total", () => {
|
||||
const days = Array.from({ length: 30 }, (_, index) => {
|
||||
const date = new Date("2026-09-09T00:00:00Z");
|
||||
@@ -108,7 +184,7 @@ describe("Token usage card", () => {
|
||||
expect(screen.getAllByRole("img").filter((bar) => bar.tabIndex === 0)).toEqual([column]);
|
||||
expect(column).toHaveAccessibleName(/2026-09-09: 2,200 tokens/);
|
||||
expect(column).toHaveAccessibleName(/model-5: 600/);
|
||||
expect(column).toHaveAccessibleName(/Other \/ unattributed: 200/);
|
||||
expect(column).toHaveAccessibleName(/Other models: 200/);
|
||||
const legend = screen.getByLabelText("model-5: Total tokens: 600 (27.3%), Cache hit rate: 80%");
|
||||
expect(legend).toHaveAttribute("tabindex", "0");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TokenUsageOverview } from "@/components/settings/TokenUsageOverview";
|
||||
|
||||
const client = {};
|
||||
const getToken = () => "tok";
|
||||
vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client, getToken }) }));
|
||||
|
||||
const overview = { days: [], revision: "overview" };
|
||||
const models = { ...overview, revision: "models", providers_30d: [], model_days_30d: [] };
|
||||
const json = (value: unknown) => ({ ok: true, status: 200, json: async () => value }) as Response;
|
||||
|
||||
async function settle() {
|
||||
await act(async () => {});
|
||||
}
|
||||
|
||||
describe("Token usage loading", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-09-09T12:00:00Z"));
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("polls conditionally and loads models only while details are open", async () => {
|
||||
const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
if ((init?.headers as Record<string, string>)["If-None-Match"]) {
|
||||
return { status: 304 } as Response;
|
||||
}
|
||||
return json(String(_input).includes("details=true") ? models : overview);
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { unmount } = render(<TokenUsageOverview />);
|
||||
await settle();
|
||||
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(["/api/settings/usage"]);
|
||||
await act(async () => vi.advanceTimersByTimeAsync(5000));
|
||||
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage", expect.objectContaining({
|
||||
headers: { Authorization: "Bearer tok", "If-None-Match": 'W/"overview"' },
|
||||
}));
|
||||
fireEvent.click(screen.getByRole("button", { name: "View details" }));
|
||||
await settle();
|
||||
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage?details=true", expect.anything());
|
||||
await act(async () => vi.advanceTimersByTimeAsync(5000));
|
||||
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage?details=true", expect.objectContaining({
|
||||
headers: { Authorization: "Bearer tok", "If-None-Match": 'W/"models"' },
|
||||
}));
|
||||
const beforeClose = fetchMock.mock.calls.length;
|
||||
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
|
||||
await settle();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(beforeClose);
|
||||
await act(async () => vi.advanceTimersByTimeAsync(5000));
|
||||
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage", expect.anything());
|
||||
const beforeLeave = fetchMock.mock.calls.length;
|
||||
unmount();
|
||||
await act(async () => vi.advanceTimersByTimeAsync(10000));
|
||||
fireEvent(window, new Event("focus"));
|
||||
expect(fetchMock).toHaveBeenCalledTimes(beforeLeave);
|
||||
});
|
||||
|
||||
it("aborts a pending request when hidden and refreshes once when visible again", async () => {
|
||||
let visibility = "visible";
|
||||
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility as DocumentVisibilityState);
|
||||
const signals: AbortSignal[] = [];
|
||||
const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
|
||||
const signal = init!.signal!;
|
||||
signals.push(signal);
|
||||
signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
|
||||
}));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
render(<TokenUsageOverview />);
|
||||
await settle();
|
||||
fireEvent(window, new Event("focus"));
|
||||
await act(async () => vi.advanceTimersByTimeAsync(5000));
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
visibility = "hidden";
|
||||
fireEvent(document, new Event("visibilitychange"));
|
||||
await settle();
|
||||
expect(signals[0].aborted).toBe(true);
|
||||
await act(async () => vi.advanceTimersByTimeAsync(10000));
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
visibility = "visible";
|
||||
fireEvent(document, new Event("visibilitychange"));
|
||||
await settle();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { normalizeUsageModel } from "@/lib/usage-model";
|
||||
|
||||
describe("usage model names", () => {
|
||||
it("strips a prefix that repeats the provider", () => {
|
||||
expect(normalizeUsageModel("openai_codex", "openai-codex/gpt-6.1-sol")).toBe("gpt-6.1-sol");
|
||||
expect(normalizeUsageModel("openai_codex", "openai/gpt-6-astra")).toBe("gpt-6-astra");
|
||||
expect(normalizeUsageModel("custom-ffsa", "custom/model")).toBe("model");
|
||||
});
|
||||
|
||||
it("keeps prefixes that belong to the model name", () => {
|
||||
expect(normalizeUsageModel("custom-ffsa", "qwen/qwen3.8-27b")).toBe("qwen/qwen3.8-27b");
|
||||
expect(normalizeUsageModel("zhipu", "glm-5.3-flash")).toBe("glm-5.3-flash");
|
||||
expect(normalizeUsageModel("openai_codex", "gpt-6-astra")).toBe("gpt-6-astra");
|
||||
expect(normalizeUsageModel("acme", "/leading-slash")).toBe("/leading-slash");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { usageFormats } from "@/lib/usage-number";
|
||||
|
||||
describe("usage number formats", () => {
|
||||
it("switches to locale units once a count reaches five digits", () => {
|
||||
const en = usageFormats("en");
|
||||
const zh = usageFormats("zh-CN");
|
||||
expect(en.display(10_046_620_708)).toBe("10B");
|
||||
expect(en.display(69_134)).toBe("69.1K");
|
||||
expect(en.display(3039)).toBe("3,039");
|
||||
expect(zh.display(10_046_620_708)).toBe("100.5亿");
|
||||
expect(zh.display(10_324)).toBe("1万");
|
||||
expect(zh.display(3039)).toBe("3,039");
|
||||
});
|
||||
|
||||
it("keeps exact digits for titles and accessible labels", () => {
|
||||
const en = usageFormats("en");
|
||||
expect(en.exact(10_046_620_708)).toBe("10,046,620,708");
|
||||
expect(en.exact(0)).toBe("0");
|
||||
});
|
||||
|
||||
it("builds one formatter set per locale", () => {
|
||||
expect(usageFormats("en")).toBe(usageFormats("en"));
|
||||
expect(usageFormats("en")).not.toBe(usageFormats("zh-CN"));
|
||||
expect(usageFormats("en").percent(0.5)).toBe("50%");
|
||||
expect(usageFormats("en").date("2026-10-27")).toBe("Oct 27");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user