TypeScript
fix(web): Usage hourly labels follow the Time format setting (#15575)
Martin Bergo6cfd82fe1f34
diff --git a/apps/web/src/components/usage/UsageModelDialog.tsx b/apps/web/src/components/usage/UsageModelDialog.tsxindex 06408446c17..0fb6b89ce73 100644--- a/apps/web/src/components/usage/UsageModelDialog.tsx+++ b/apps/web/src/components/usage/UsageModelDialog.tsx@@ -30,6 +30,7 @@ export interface UsageChartWindow {readonly resolution: "day" | "hour";readonly timeZone: string;readonly referenceTime: string | undefined;+ readonly hour12: boolean;}export function UsageModelDialog({@@ -107,6 +108,7 @@ export function UsageModelDialog({referenceTime={chartWindow.referenceTime}resolution={chartWindow.resolution}timeZone={chartWindow.timeZone}+ hour12={chartWindow.hour12}/><div className="grid gap-x-10 gap-y-8 sm:grid-cols-2">diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsxindex b36c6fb697b..5728616edf8 100644--- a/apps/web/src/components/usage/UsagePage.tsx+++ b/apps/web/src/components/usage/UsagePage.tsx@@ -35,6 +35,8 @@ import {import { isElectron } from "../../env";import { cn } from "../../lib/utils";+import { usePrimarySettings } from "../../hooks/useSettings";+import { resolveHour12 } from "../../timestampFormat";import { appAtomRegistry } from "~/rpc/atomRegistry";import { environmentPresentations } from "../../state/presentation";import { primaryServerKeybindingsAtom, serverEnvironment } from "../../state/server";@@ -180,6 +182,7 @@ export function UsagePage() {const [preferences, setPreferences] = useState(readUsagePagePreferences);useEscapeToGoBack();const keybindings = useAtomValue(primaryServerKeybindingsAtom);+ const hour12 = usePrimarySettings((settings) => resolveHour12(settings.timestampFormat));const shortcutTitle = (option: (typeof METRIC_OPTIONS)[number] | (typeof WINDOW_OPTIONS)[number],) => {@@ -356,7 +359,7 @@ export function UsagePage() {const windowLabel =shownHourly && shownWindow.sinceTime !== undefined && shownWindow.untilTime !== undefined- ? `${formatDateTimeShort(shownWindow.sinceTime, shownWindow.timeZone)} to ${formatDateTimeShort(shownWindow.untilTime, shownWindow.timeZone)}`+ ? `${formatDateTimeShort(shownWindow.sinceTime, shownWindow.timeZone, hour12)} to ${formatDateTimeShort(shownWindow.untilTime, shownWindow.timeZone, hour12)}`: `${formatDayShort(shownWindow.sinceDay)} to ${formatDayShort(shownWindow.untilDay)}`;const topbarContent = (<div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 py-2 xl:flex">@@ -546,6 +549,7 @@ export function UsagePage() {<UsageOverviewmerged={merged}shownWindow={shownWindow}+ hour12={hour12}days={days}hours={hours}showingKept={showingKept}@@ -576,6 +580,7 @@ export function UsagePage() {resolution: shownHourly ? "hour" : "day",timeZone: shownWindow.timeZone,referenceTime: shownWindow.untilTime,+ hour12,}}onSetPrice={(model) => setPriceDialog({ model })}/>@@ -597,6 +602,7 @@ export function UsagePage() {function UsageOverview({merged,shownWindow,+ hour12,days,hours,showingKept,@@ -611,6 +617,7 @@ function UsageOverview({}: {readonly merged: MergedUsage;readonly shownWindow: UsageSummaryInput;+ readonly hour12: boolean;readonly days: readonly string[];readonly hours: readonly string[];readonly showingKept: boolean;@@ -826,6 +833,7 @@ function UsageOverview({referenceTime={shownWindow.untilTime}resolution={shownHourly ? "hour" : "day"}timeZone={shownWindow.timeZone}+ hour12={hour12}/></div></section>@@ -1027,7 +1035,7 @@ function UsageOverview({><td className="py-2 text-foreground">{"hourStart" in period- ? formatHourShort(period.hourStart, shownWindow.timeZone)+ ? formatHourShort(period.hourStart, shownWindow.timeZone, hour12): formatDayShort(period.day)}</td>{activeProviders.map((provider) => (diff --git a/apps/web/src/components/usage/UsageProviderChart.tsx b/apps/web/src/components/usage/UsageProviderChart.tsxindex 459312658c3..1df8377bbb0 100644--- a/apps/web/src/components/usage/UsageProviderChart.tsx+++ b/apps/web/src/components/usage/UsageProviderChart.tsx@@ -33,6 +33,7 @@ interface UsageProviderChartProps {readonly referenceTime: string | undefined;readonly resolution: "day" | "hour";readonly timeZone: string;+ readonly hour12: boolean;}export interface DayColumn {@@ -417,6 +418,7 @@ export function UsageProviderChart({referenceTime,resolution,timeZone,+ hour12,}: UsageProviderChartProps) {const periods = resolution === "hour" ? hours : days;const totals: readonly (DailyTotals | HourlyTotals)[] = resolution === "hour" ? hourly : daily;@@ -436,10 +438,10 @@ export function UsageProviderChart({cn("transition-opacity", loading && "opacity-40 delay-150");const format = metric === "tokens" ? formatTokens : formatUsd;const formatPeriod = (period: string) =>- resolution === "hour" ? formatHourShort(period, timeZone) : formatDayShort(period);+ resolution === "hour" ? formatHourShort(period, timeZone, hour12) : formatDayShort(period);const formatTooltipPeriod = (period: string) =>resolution === "hour" && referenceTime !== undefined- ? formatRelativeHourShort(period, referenceTime, timeZone)+ ? formatRelativeHourShort(period, referenceTime, timeZone, hour12): formatPeriod(period);return (diff --git a/apps/web/src/timestampFormat.test.ts b/apps/web/src/timestampFormat.test.tsindex 9d001ffc56e..7efc054c941 100644--- a/apps/web/src/timestampFormat.test.ts+++ b/apps/web/src/timestampFormat.test.ts@@ -1,3 +1,4 @@+import { formatHourShort } from "@t3tools/shared/usageFormat";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import {@@ -40,17 +41,20 @@ describe("formatShortTimestamp", () => {});it.each([- ["en-GB", "15:44"],- ["en-US", "3:44 PM"],- ])("honors %s and the explicit hour-cycle settings", async (locale, localTime) => {+ ["en-GB", "15:44", "15:00"],+ ["en-US", "3:44 PM", "3 PM"],+ ])("honors %s and the explicit hour-cycle settings", async (locale, localTime, localHour) => {vi.stubGlobal("window", { desktopBridge: { getSystemLocale: () => locale } });vi.resetModules();- const { formatShortTimestamp: format } = await import("./timestampFormat");+ const { formatShortTimestamp: format, resolveHour12 } = await import("./timestampFormat");const date = new Date(2026, 3, 7, 15, 44).toISOString();// ICU can separate the day period with a narrow no-break space.expect(format(date, "locale").replace(/[ ]/g, " ")).toBe(localTime);expect(format(date, "12-hour").replace(/[ ]/g, " ")).toMatch(/^3:44 [ap]m$/i);expect(format(date, "24-hour")).toBe("15:44");+ expect(formatHourShort(date, undefined, resolveHour12("locale"))).toBe(localHour);+ expect(formatHourShort(date, undefined, resolveHour12("12-hour"))).toBe("3 PM");+ expect(formatHourShort(date, undefined, resolveHour12("24-hour"))).toBe("15:00");});});diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.tsindex c6eae0ce6dd..7558a28f4fd 100644--- a/apps/web/src/timestampFormat.ts+++ b/apps/web/src/timestampFormat.ts@@ -93,6 +93,10 @@ function getTimestampFormatter(return formatter;}+export function resolveHour12(timestampFormat: TimestampFormat): boolean {+ return getTimestampFormatter(timestampFormat, false).resolvedOptions().hour12 ?? false;+}+export function parseTimestampDate(isoDate: string): Date | null {const date = new Date(isoDate);return Number.isNaN(date.getTime()) ? null : date;diff --git a/packages/shared/src/usageFormat.test.ts b/packages/shared/src/usageFormat.test.tsindex 3a47ede3bcc..de9eb8220ca 100644--- a/packages/shared/src/usageFormat.test.ts+++ b/packages/shared/src/usageFormat.test.ts@@ -63,6 +63,30 @@ describe("hourly usage formatting", () => {it("disambiguates repeated hours during a fall-back transition", () => {expect(formatHourShort("2026-11-01T05:37:00.000Z", "America/New_York")).toBe("1 AM EDT");expect(formatHourShort("2026-11-01T06:37:00.000Z", "America/New_York")).toBe("1 AM EST");+ expect(formatHourShort("2026-11-01T05:37:00.000Z", "America/New_York", false)).toBe(+ "01:00 EDT",+ );+ expect(formatHourShort("2026-11-01T06:37:00.000Z", "America/New_York", false)).toBe(+ "01:00 EST",+ );+ });++ it.each([+ [true, "2 PM", "12 AM"],+ [false, "14:00", "00:00"],+ ])("formats hourly usage labels with hour12=%s", (hour12, afternoon, midnight) => {+ const instant = "2026-08-11T14:37:00.000Z";++ expect(formatHourShort(instant, "UTC", hour12)).toBe(afternoon);+ expect(formatHourShort("2026-08-11T00:37:00.000Z", "UTC", hour12)).toBe(midnight);+ expect(formatDateTimeShort(instant, "UTC", hour12)).toBe(`Aug 11, ${afternoon}`);+ expect(formatRelativeHourShort(instant, instant, "UTC", hour12)).toBe(`${afternoon} today`);+ expect(formatRelativeHourShort(instant, "2026-08-12T15:37:00.000Z", "UTC", hour12)).toBe(+ `${afternoon} yesterday`,+ );+ expect(formatRelativeHourShort(instant, "2026-08-14T15:37:00.000Z", "UTC", hour12)).toBe(+ `Aug 11, ${afternoon}`,+ );});it("makes hourly tooltip dates relative to the window in its requested time zone", () => {diff --git a/packages/shared/src/usageFormat.ts b/packages/shared/src/usageFormat.tsindex 3b13d09e0a9..bcdc0edb950 100644--- a/packages/shared/src/usageFormat.ts+++ b/packages/shared/src/usageFormat.ts@@ -114,17 +114,30 @@ export function enumerateHourStarts(sinceTime: string, untilTime: string): readoreturn starts;}+function hourOptions(hour12: boolean): Intl.DateTimeFormatOptions {+ return hour12 ? { hour: "numeric" } : { hour: "2-digit", hourCycle: "h23" };+}++function formatHour(formatter: Intl.DateTimeFormat, date: Date, hour12: boolean): string {+ if (hour12) return formatter.format(date);+ // Rolling buckets can start between whole hours, but their labels always name the hour.+ return formatter+ .formatToParts(date)+ .map((part) => (part.type === "hour" ? `${part.value}:00` : part.value))+ .join("");+}+/*** Repeated wall-clock hours during a fall-back transition include their short zone name so the* two distinct buckets remain distinguishable.*/-export function formatHourShort(hourStart: string, timeZone?: string): string {+export function formatHourShort(hourStart: string, timeZone?: string, hour12 = true): string {const instant = new Date(hourStart);if (Number.isNaN(instant.getTime())) return hourStart;const options = timeZone === undefined ? {} : { timeZone };const hourFormat = dateTimeFormatter("en-US", {...options,- hour: "numeric",+ ...hourOptions(hour12),});const wallHourFormat = dateTimeFormatter("en-CA", {...options,@@ -139,34 +152,37 @@ export function formatHourShort(hourStart: string, timeZone?: string): string {(offset) => wallHourFormat.format(new Date(instant.getTime() + offset)) === wallHour,);- if (!isRepeatedHour) return hourFormat.format(instant);- return dateTimeFormatter("en-US", {- ...(timeZone === undefined ? {} : { timeZone }),- hour: "numeric",+ if (!isRepeatedHour) return formatHour(hourFormat, instant, hour12);+ const zonedHourFormat = dateTimeFormatter("en-US", {+ ...options,+ ...hourOptions(hour12),timeZoneName: "short",- }).format(instant);+ });+ return formatHour(zonedHourFormat, instant, hour12);}-export function formatDateTimeShort(instant: string, timeZone?: string): string {+export function formatDateTimeShort(instant: string, timeZone?: string, hour12 = true): string {const date = new Date(instant);if (Number.isNaN(date.getTime())) return instant;- return dateTimeFormatter("en-US", {+ const dateHourFormat = dateTimeFormatter("en-US", {...(timeZone === undefined ? {} : { timeZone }),month: "short",day: "numeric",- hour: "numeric",- }).format(date);+ ...hourOptions(hour12),+ });+ return formatHour(dateHourFormat, date, hour12);}export function formatRelativeHourShort(hourStart: string,relativeTo: string,timeZone?: string,+ hour12 = true,): string {const instant = new Date(hourStart);const reference = new Date(relativeTo);if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) {- return formatDateTimeShort(hourStart, timeZone);+ return formatDateTimeShort(hourStart, timeZone, hour12);}const dayFormat = dateTimeFormatter("en-CA", {@@ -178,11 +194,11 @@ export function formatRelativeHourShort(const instantDay = Date.parse(`${dayFormat.format(instant)}T00:00:00Z`);const referenceDay = Date.parse(`${dayFormat.format(reference)}T00:00:00Z`);const calendarDaysAgo = Math.round((referenceDay - instantDay) / (24 * HOUR_MS));- const hour = formatHourShort(hourStart, timeZone);+ const hour = formatHourShort(hourStart, timeZone, hour12);if (calendarDaysAgo === 0) return `${hour} today`;if (calendarDaysAgo === 1) return `${hour} yesterday`;- return formatDateTimeShort(hourStart, timeZone);+ return formatDateTimeShort(hourStart, timeZone, hour12);}export function makeWindow(