Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
Add hourly past-24-hour usage view (#6170)
Julius Marmingec842c6f5b901
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsxindex 54a9ac7bc..817e6d7f9 100644--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx@@ -1,9 +1,11 @@import { useNavigation } from "@react-navigation/native";-import type { MergedUsage } from "@t3tools/shared/usageMerge";+import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";import {enumerateDays,+ enumerateHourStarts,formatCount,formatDayShort,+ formatHourShort,formatPercent,formatTokens,formatUsd,@@ -23,6 +25,7 @@ import type { UsageChartMetric } from "./usageChartData";import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";const WINDOW_OPTIONS = [+ { days: 1, label: "Past 24h" },{ days: 7, label: "7 days" },{ days: 30, label: "30 days" },{ days: 90, label: "90 days" },@@ -33,23 +36,62 @@ const CHART_HEIGHT = 180;export function UsageRouteScreen() {const navigation = useNavigation();const insets = useSafeAreaInsets();- const [windowDays, setWindowDays] = useState<number>(30);+ const [windowSelection, setWindowSelection] = useState(() => ({+ days: 30,+ window: makeWindow(30),+ }));const [metric, setMetric] = useState<UsageChartMetric>("cost");-- // Recomputed only when the window length changes, so a re-render does not- // shift the range and refetch every environment.- const window = useMemo(() => makeWindow(windowDays), [windowDays]);+ const { days: windowDays, window } = windowSelection;+ const isPast24Hours = windowDays === 1;const { merged, environments, isPending, isPartial, refresh } = useUsage(window);const days = useMemo(() => enumerateDays(window.sinceDay, window.untilDay),[window.sinceDay, window.untilDay],);+ const chartDays = useMemo(+ () =>+ isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined+ ? enumerateHourStarts(window.sinceTime, window.untilTime)+ : days,+ [days, isPast24Hours, window.sinceTime, window.untilTime],+ );+ const chartTotals = useMemo(+ (): readonly DailyTotals[] =>+ isPast24Hours+ ? merged.hourly.map((hour) => ({+ day: hour.hourStart,+ costUsd: hour.costUsd,+ totalTokens: hour.totalTokens,+ byProvider: hour.byProvider,+ }))+ : merged.daily,+ [isPast24Hours, merged.daily, merged.hourly],+ );// The pull spinner tracks re-scans of environments that have answered// before. The initial scan renders its own placeholder, and an unreachable// environment stays pending forever — neither may pin the spinner on.const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);+ const selectWindow = (days: number) => {+ setWindowSelection({+ days,+ window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),+ });+ };+ const refreshWindow = () => {+ const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");+ if (+ nextWindow.sinceDay === window.sinceDay &&+ nextWindow.untilDay === window.untilDay &&+ nextWindow.sinceTime === window.sinceTime &&+ nextWindow.untilTime === window.untilTime+ ) {+ refresh();+ } else {+ setWindowSelection({ days: windowDays, window: nextWindow });+ }+ };return (<View collapsable={false} className="flex-1 bg-sheet">@@ -65,12 +107,12 @@ export function UsageRouteScreen() {className="flex-1"contentContainerClassName="gap-6 px-5 pt-4"contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}- refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refresh} />}+ refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}><SegmentedControloptions={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}selected={windowDays}- onSelect={setWindowDays}+ onSelect={selectWindow}/><UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />@@ -87,14 +129,17 @@ export function UsageRouteScreen() {<><ChartCardmerged={merged}- days={days}+ days={chartDays}+ daily={chartTotals}metric={metric}onMetricChange={setMetric}sinceDay={window.sinceDay}untilDay={window.untilDay}+ isPast24Hours={isPast24Hours}+ timeZone={window.timeZone}/><ProviderSection merged={merged} metric={metric} />- <TotalsSection merged={merged} />+ <TotalsSection merged={merged} isPast24Hours={isPast24Hours} /><ModelsSection merged={merged} /></>)}@@ -142,14 +187,17 @@ function SegmentedControl<Value extends number | string>(props: {function ChartCard(props: {readonly merged: MergedUsage;readonly days: readonly string[];+ readonly daily: readonly DailyTotals[];readonly metric: UsageChartMetric;readonly onMetricChange: (metric: UsageChartMetric) => void;readonly sinceDay: string;readonly untilDay: string;+ readonly isPast24Hours: boolean;+ readonly timeZone: string;}) {const { merged, metric } = props;const colors = useProviderColors();- const hasActivity = merged.daily.some((day) => day.totalTokens > 0);+ const hasActivity = props.daily.some((period) => period.totalTokens > 0);return (<View className="gap-4 rounded-[24px] border-continuous bg-card p-4">@@ -173,7 +221,7 @@ function ChartCard(props: {{hasActivity ? (<UsageDailyChartdays={props.days}- daily={merged.daily}+ daily={props.daily}metric={metric}height={CHART_HEIGHT}/>@@ -184,7 +232,11 @@ function ChartCard(props: {)}<View className="flex-row items-center justify-between">- <Text className="text-xs text-foreground-tertiary">{formatDayShort(props.sinceDay)}</Text>+ <Text className="text-xs text-foreground-tertiary">+ {props.isPast24Hours+ ? formatHourShort(props.days[0] ?? "", props.timeZone)+ : formatDayShort(props.sinceDay)}+ </Text><View className="flex-row items-center gap-4">{merged.providers.map((provider) => (<View key={provider.provider} className="flex-row items-center gap-1.5">@@ -198,7 +250,11 @@ function ChartCard(props: {</View>))}</View>- <Text className="text-xs text-foreground-tertiary">{formatDayShort(props.untilDay)}</Text>+ <Text className="text-xs text-foreground-tertiary">+ {props.isPast24Hours+ ? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)+ : formatDayShort(props.untilDay)}+ </Text></View></View>);@@ -292,10 +348,12 @@ function ProviderSection(props: {);}-function TotalsSection(props: { readonly merged: MergedUsage }) {+function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {const { merged } = props;- const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;- const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;+ const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(+ (period) => period.totalTokens > 0,+ ).length;+ const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;@@ -305,7 +363,7 @@ function TotalsSection(props: { readonly merged: MergedUsage }) {<MetricCelllabel="Processed tokens"value={formatTokens(merged.totalTokens)}- detail={`${formatTokens(dailyAverage)} per active day`}+ detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}/><MetricCelllabel="Cache savings"diff --git a/apps/mobile/src/state/usage.ts b/apps/mobile/src/state/usage.tsindex 91cefda07..cce91b65a 100644--- a/apps/mobile/src/state/usage.ts+++ b/apps/mobile/src/state/usage.ts@@ -81,8 +81,18 @@ export function useUsage(input: UsageSummaryInput): UsageView {sinceDay: input.sinceDay,untilDay: input.untilDay,timeZone: input.timeZone,+ resolution: input.resolution,+ sinceTime: input.sinceTime,+ untilTime: input.untilTime,}),- [input.sinceDay, input.untilDay, input.timeZone],+ [+ input.sinceDay,+ input.untilDay,+ input.timeZone,+ input.resolution,+ input.sinceTime,+ input.untilTime,+ ],);const atom = usageByWindowAtom(windowKey);const environments = useAtomValue(atom);diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.tsindex 2ad2a729e..0bf131ac9 100644--- a/apps/server/src/usage/UsageService.ts+++ b/apps/server/src/usage/UsageService.ts@@ -1,5 +1,5 @@/**- * UsageService - scans provider transcripts and returns priced daily usage.+ * UsageService - scans provider transcripts and returns priced usage buckets.** The scan reads the provider CLIs' own session files rather than T3 Code's* orchestration projections, so usage covers turns driven outside T3 Code too.@@ -64,6 +64,7 @@ const RATES_TTL_MS = 24 * 60 * 60 * 1000;* last write lands just before local midnight on the window's first day.*/const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;+const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;/** Longest window the UI offers, plus slack. Older entries are pruned. */const CACHE_RETENTION_DAYS = 90;@@ -297,6 +298,30 @@ export const make = Effect.gen(function* () {});}+ let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;+ if (input.resolution === "hour") {+ const sinceTime =+ input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);+ const untilTime =+ input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);+ if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {+ return yield* new UsageReadError({+ reason: "invalidWindow",+ detail: "Hourly usage requires valid sinceTime and untilTime instants",+ });+ }+ const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);+ const untilTimeMs = DateTime.toEpochMillis(untilTime.value);+ const durationMs = untilTimeMs - sinceTimeMs;+ if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {+ return yield* new UsageReadError({+ reason: "invalidWindow",+ detail: "Hourly usage window must be greater than zero and at most 24 hours",+ });+ }+ hourlyWindow = { sinceTimeMs, untilTimeMs };+ }+const startedAtMs = yield* Clock.currentTimeMillis;yield* ensureRates();yield* ensureScanCacheLoaded;@@ -312,12 +337,15 @@ export const make = Effect.gen(function* () {detail: `sinceDay '${input.sinceDay}' is not a valid date`,});}- const windowStartMs = DateTime.toEpochMillis(windowStart.value) - MTIME_SLACK_MS;+ const windowStartMs =+ (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;const aggregator = new UsageAggregator({timeZone: input.timeZone,sinceDay: input.sinceDay,untilDay: input.untilDay,+ resolution: input.resolution ?? "day",+ ...hourlyWindow,rates,});diff --git a/apps/server/src/usage/usageAggregation.test.ts b/apps/server/src/usage/usageAggregation.test.tsindex 9117e216f..8da4e920a 100644--- a/apps/server/src/usage/usageAggregation.test.ts+++ b/apps/server/src/usage/usageAggregation.test.ts@@ -36,11 +36,24 @@ function record(overrides: Partial<UsageRecord> = {}): UsageRecord {};}-function aggregate(records: readonly UsageRecord[], timeZone = "UTC") {+function aggregate(+ records: readonly UsageRecord[],+ timeZone = "UTC",+ resolution: "day" | "hour" = "day",+) {+ const hourlyBounds =+ resolution === "hour"+ ? {+ sinceTimeMs: Date.parse("2026-08-06T04:37:00.000Z"),+ untilTimeMs: Date.parse("2026-08-07T04:37:00.000Z"),+ }+ : {};const aggregator = new UsageAggregator({timeZone,sinceDay: "2026-08-01",untilDay: "2026-08-31",+ resolution,+ ...hourlyBounds,rates,});for (const item of records) aggregator.add(item);@@ -48,6 +61,19 @@ function aggregate(records: readonly UsageRecord[], timeZone = "UTC") {}describe("UsageAggregator", () => {+ it("requires exact bounds for hourly aggregation", () => {+ expect(+ () =>+ new UsageAggregator({+ timeZone: "UTC",+ sinceDay: "2026-08-01",+ untilDay: "2026-08-31",+ resolution: "hour",+ rates,+ }),+ ).toThrow("requires exact time bounds");+ });+it("keeps only the first record for a repeated dedupe key", () => {const result = aggregate([record({ dedupeKey: "msg_1:" }),@@ -76,6 +102,52 @@ describe("UsageAggregator", () => {expect(losAngeles.buckets[0]?.day).toBe("2026-08-06");});+ it("splits an hourly request into fixed buckets anchored to its exact start", () => {+ const result = aggregate(+ [+ record({ timestampMs: Date.parse("2026-08-07T02:40:13.944Z") }),+ record({ timestampMs: Date.parse("2026-08-07T03:40:13.944Z") }),+ ],+ "America/Los_Angeles",+ "hour",+ );++ expect(result.buckets.map((bucket) => [bucket.day, bucket.hourStart])).toEqual([+ ["2026-08-06", "2026-08-07T02:37:00.000Z"],+ ["2026-08-06", "2026-08-07T03:37:00.000Z"],+ ]);+ });++ it("uses an inclusive start and exclusive end for rolling windows", () => {+ const result = aggregate(+ [+ record({ timestampMs: Date.parse("2026-08-06T04:36:59.999Z") }),+ record({ timestampMs: Date.parse("2026-08-06T04:37:00.000Z") }),+ record({ timestampMs: Date.parse("2026-08-07T04:36:59.999Z") }),+ record({ timestampMs: Date.parse("2026-08-07T04:37:00.000Z") }),+ ],+ "UTC",+ "hour",+ );++ expect(result.outOfWindow).toBe(2);+ expect(result.buckets.map((bucket) => bucket.hourStart)).toEqual([+ "2026-08-06T04:37:00.000Z",+ "2026-08-07T03:37:00.000Z",+ ]);+ });++ it("keeps daily payloads collapsed when hourly resolution is not requested", () => {+ const result = aggregate([+ record({ timestampMs: Date.parse("2026-08-07T04:05:13.944Z") }),+ record({ timestampMs: Date.parse("2026-08-07T05:05:13.944Z") }),+ ]);++ expect(result.buckets).toHaveLength(1);+ expect(result.buckets[0]?.hourStart).toBeUndefined();+ expect(result.buckets[0]?.records).toBe(2);+ });+it("prices against the rate table", () => {const result = aggregate([record()]);diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.tsindex 4f04a318c..e100be76e 100644Binary files a/apps/server/src/usage/usageAggregation.ts and b/apps/server/src/usage/usageAggregation.ts differdiff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsxindex b550d673f..5e9034bb2 100644--- a/apps/web/src/components/usage/UsagePage.tsx+++ b/apps/web/src/components/usage/UsagePage.tsx@@ -2,13 +2,18 @@ import type { UsageProviderKind } from "@t3tools/contracts";import { CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";import { useMemo, useState } from "react";+import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";+import { isElectron } from "../../env";import { cn } from "../../lib/utils";import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";import {enumerateDays,+ enumerateHourStarts,formatCount,+ formatDateTimeShort,formatDayShort,+ formatHourShort,formatPercent,formatTokens,formatUsd,@@ -22,19 +27,21 @@ import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./Uimport { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";const WINDOW_OPTIONS = [+ { days: 1, label: "Past 24h" },{ days: 7, label: "7 days" },{ days: 30, label: "30 days" },{ days: 90, label: "90 days" },] as const;export function UsagePage() {- const [windowDays, setWindowDays] = useState<number>(30);+ const [windowSelection, setWindowSelection] = useState(() => ({+ days: 30,+ window: makeWindow(30),+ }));const [metric, setMetric] = useState<UsageChartMetric>("cost");- const [breakdown, setBreakdown] = useState<"model" | "day">("model");-- // Recomputed only when the window length changes, so a re-render does not- // shift the range and refetch every environment.- const window = useMemo(() => makeWindow(windowDays), [windowDays]);+ const [breakdown, setBreakdown] = useState<"model" | "time">("model");+ const { days: windowDays, window } = windowSelection;+ const isPast24Hours = windowDays === 1;const { merged, environments, isPending, isPartial, refresh } = useUsage(window);// Hold the content until every environment is terminal. Rendering merged@@ -46,7 +53,17 @@ export function UsagePage() {() => enumerateDays(window.sinceDay, window.untilDay),[window.sinceDay, window.untilDay],);- const recentDays = useMemo(() => merged.daily.toReversed().slice(0, 8), [merged.daily]);+ const hours = useMemo(+ () =>+ window.sinceTime === undefined || window.untilTime === undefined+ ? []+ : enumerateHourStarts(window.sinceTime, window.untilTime),+ [window.sinceTime, window.untilTime],+ );+ const recentPeriods = useMemo<readonly (DailyTotals | HourlyTotals)[]>(+ () => (isPast24Hours ? merged.hourly : merged.daily).toReversed().slice(0, 8),+ [isPast24Hours, merged.daily, merged.hourly],+ );// Ranked by whatever the toggle is showing, so the bars always descend.const orderedProviders = useMemo(@@ -57,10 +74,31 @@ export function UsagePage() {[merged.providers, metric],);- const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;- const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;+ const activePeriods = (isPast24Hours ? merged.hourly : merged.daily).filter(+ (period) => period.totalTokens > 0,+ ).length;+ const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;+ const selectWindow = (days: number) => {+ setWindowSelection({+ days,+ window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),+ });+ };+ const refreshWindow = () => {+ const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");+ if (+ nextWindow.sinceDay === window.sinceDay &&+ nextWindow.untilDay === window.untilDay &&+ nextWindow.sinceTime === window.sinceTime &&+ nextWindow.untilTime === window.untilTime+ ) {+ refresh();+ } else {+ setWindowSelection({ days: windowDays, window: nextWindow });+ }+ };return (<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">@@ -95,17 +133,20 @@ export function UsagePage() {<div className="mx-auto flex w-full max-w-6xl flex-col gap-8 px-6 py-6"><div className="flex flex-wrap items-center justify-between gap-4"><p className="text-sm text-muted-foreground">- {formatDayShort(window.sinceDay)} to {formatDayShort(window.untilDay)}+ {isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined+ ? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`+ : `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`}</p><div className="flex items-center gap-2">- <div className="flex overflow-hidden rounded-md border border-border">+ <div className="flex rounded-md border border-border">{WINDOW_OPTIONS.map((option) => (<buttonkey={option.days}type="button"- onClick={() => setWindowDays(option.days)}+ aria-pressed={option.days === windowDays}+ onClick={() => selectWindow(option.days)}className={cn(- "cursor-pointer px-3 py-1.5 text-xs",+ "relative cursor-pointer px-3 py-1.5 text-xs outline-none first:rounded-s-[calc(var(--radius-md)-1px)] last:rounded-e-[calc(var(--radius-md)-1px)] focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",option.days === windowDays? "bg-muted text-foreground": "text-muted-foreground hover:text-foreground",@@ -117,7 +158,7 @@ export function UsagePage() {</div><buttontype="button"- onClick={refresh}+ onClick={refreshWindow}aria-label="Refresh usage"className="cursor-pointer rounded-md border border-border p-2 text-muted-foreground hover:text-foreground">@@ -129,7 +170,7 @@ export function UsagePage() {{settling ? (<>{environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}- <UsageSkeleton />+ <UsageSkeleton resolution={isPast24Hours ? "hour" : "day"} /></>) : (<>@@ -197,7 +238,8 @@ export function UsagePage() {<div className="flex flex-col gap-3"><div className="flex flex-wrap items-center justify-between gap-3"><h2 className="text-sm font-medium text-foreground">- Daily {metric === "tokens" ? "processed tokens" : "cost"}+ {isPast24Hours ? "Hourly" : "Daily"}{" "}+ {metric === "tokens" ? "processed tokens" : "cost"}</h2><div className="flex items-center gap-4"><div className="flex overflow-hidden rounded-md border border-border">@@ -220,7 +262,16 @@ export function UsagePage() {<UsageChartLegend /></div></div>- <UsageProviderChart days={days} daily={merged.daily} metric={metric} />+ <UsageProviderChart+ days={days}+ daily={merged.daily}+ hours={hours}+ hourly={merged.hourly}+ metric={metric}+ referenceTime={window.untilTime}+ resolution={isPast24Hours ? "hour" : "day"}+ timeZone={window.timeZone}+ /></div></section>@@ -228,7 +279,7 @@ export function UsagePage() {<Metriclabel="Processed tokens"value={formatTokens(merged.totalTokens)}- detail={`${formatTokens(dailyAverage)} per active day`}+ detail={`${formatTokens(periodAverage)} per active ${isPast24Hours ? "hour" : "day"}`}/><Metriclabel="Cached input"@@ -260,19 +311,24 @@ export function UsagePage() {<div className="flex items-center justify-between gap-3"><h2 className="text-sm font-medium text-foreground">Breakdown</h2><div className="flex overflow-hidden rounded-md border border-border">- {(["model", "day"] as const).map((option) => (+ {(+ [+ { value: "model", label: "model" },+ { value: "time", label: isPast24Hours ? "hour" : "day" },+ ] as const+ ).map((option) => (<button- key={option}+ key={option.value}type="button"- onClick={() => setBreakdown(option)}+ onClick={() => setBreakdown(option.value)}className={cn("cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",- option === breakdown+ option.value === breakdown? "bg-muted text-foreground": "text-muted-foreground hover:text-foreground",)}>- {option}+ {option.label}</button>))}</div>@@ -325,7 +381,7 @@ export function UsagePage() {<table className="w-full text-sm"><thead><tr className="border-b border-border text-left text-xs text-muted-foreground">- <th className="py-2 font-normal">Day</th>+ <th className="py-2 font-normal">{isPast24Hours ? "Hour" : "Day"}</th>{PROVIDER_ORDER.map((provider) => (<th key={provider} className="py-2 text-right font-normal">{PROVIDER_LABEL[provider]}@@ -336,29 +392,36 @@ export function UsagePage() {</tr></thead><tbody>- {recentDays.length === 0 ? (+ {recentPeriods.length === 0 ? (<tr><td colSpan={5} className="py-6 text-center text-muted-foreground">No activity in this window.</td></tr>) : (- recentDays.map((day) => (- <tr key={day.day} className="border-b border-border/50">- <td className="py-2 text-foreground">{formatDayShort(day.day)}</td>+ recentPeriods.map((period) => (+ <tr+ key={"hourStart" in period ? period.hourStart : period.day}+ className="border-b border-border/50"+ >+ <td className="py-2 text-foreground">+ {"hourStart" in period+ ? formatHourShort(period.hourStart, window.timeZone)+ : formatDayShort(period.day)}+ </td>{PROVIDER_ORDER.map((provider) => (<tdkey={provider}className="py-2 text-right text-muted-foreground tabular-nums">- {formatUsd(day.byProvider.get(provider)?.costUsd ?? 0)}+ {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}</td>))}<td className="py-2 text-right text-foreground tabular-nums">- {formatUsd(day.costUsd)}+ {formatUsd(period.costUsd)}</td><td className="py-2 text-right text-muted-foreground tabular-nums">- {formatTokens(day.totalTokens)}+ {formatTokens(period.totalTokens)}</td></tr>))@@ -513,7 +576,7 @@ const SKELETON_BAR_HEIGHTS = [34, 58, 41, 72, 22, 12, 49, 63, 80, 38, 55, 26, 44* chart and metrics strip. No shimmer; blocks fill in exactly once when the* last device answers.*/-function UsageSkeleton() {+function UsageSkeleton({ resolution }: { readonly resolution: "day" | "hour" }) {return (<><section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">@@ -542,7 +605,9 @@ function UsageSkeleton() {</div><div className="flex flex-col gap-3">- <h2 className="py-1 text-sm font-medium text-foreground">Daily cost</h2>+ <h2 className="py-1 text-sm font-medium text-foreground">+ {resolution === "hour" ? "Hourly" : "Daily"} cost+ </h2>{/* Mirrors the chart's h-56 body and w-14 axis gutter to avoid arelayout when the real chart swaps in. */}<div className="flex h-56 items-end gap-1 pl-16">diff --git a/apps/web/src/components/usage/UsageProviderChart.test.ts b/apps/web/src/components/usage/UsageProviderChart.test.tsindex a36cd1e88..1c91ab1b4 100644--- a/apps/web/src/components/usage/UsageProviderChart.test.ts+++ b/apps/web/src/components/usage/UsageProviderChart.test.ts@@ -95,3 +95,28 @@ describe("buildDayColumns", () => {}});});++describe("hourly chart columns", () => {+ it("zero-fills inactive hours and preserves hourly provider values", () => {+ const byHour = new Map([+ [+ "2026-08-11T09:37:00.000Z",+ {+ day: "2026-08-11",+ hourStart: "2026-08-11T09:37:00.000Z",+ costUsd: 4,+ totalTokens: 40,+ byProvider: new Map([["codex" as const, { costUsd: 4, totalTokens: 40 }]]),+ },+ ],+ ]);++ expect(+ buildDayColumns(+ ["2026-08-11T08:37:00.000Z", "2026-08-11T09:37:00.000Z", "2026-08-11T10:37:00.000Z"],+ byHour,+ "cost",+ ).map((column) => column.total),+ ).toEqual([0, 4, 0]);+ });+});diff --git a/apps/web/src/components/usage/UsageProviderChart.tsx b/apps/web/src/components/usage/UsageProviderChart.tsxindex 8f31d348e..f41945bfe 100644--- a/apps/web/src/components/usage/UsageProviderChart.tsx+++ b/apps/web/src/components/usage/UsageProviderChart.tsx@@ -1,8 +1,14 @@import type { UsageProviderKind } from "@t3tools/contracts";import { useCallback, useMemo, useRef, useState } from "react";-import type { DailyTotals } from "@t3tools/shared/usageMerge";-import { formatDayShort, formatTokens, formatUsd } from "@t3tools/shared/usageFormat";+import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";+import {+ formatDayShort,+ formatHourShort,+ formatRelativeHourShort,+ formatTokens,+ formatUsd,+} from "@t3tools/shared/usageFormat";import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders";const VIEW_WIDTH = 960;@@ -15,7 +21,12 @@ export type UsageChartMetric = "tokens" | "cost";interface UsageProviderChartProps {readonly days: readonly string[];readonly daily: readonly DailyTotals[];+ readonly hours: readonly string[];+ readonly hourly: readonly HourlyTotals[];readonly metric: UsageChartMetric;+ readonly referenceTime: string | undefined;+ readonly resolution: "day" | "hour";+ readonly timeZone: string;}/** One day's per-provider values, shared by the paths and the hover readout. */@@ -33,15 +44,30 @@ interface Point {}function valueFor(- daily: DailyTotals | undefined,+ totals: DailyTotals | HourlyTotals | undefined,provider: UsageProviderKind,metric: UsageChartMetric,): number {- const entry = daily?.byProvider.get(provider);+ const entry = totals?.byProvider.get(provider);if (entry === undefined) return 0;return metric === "tokens" ? entry.totalTokens : entry.costUsd;}+function buildPeriodColumns(+ periods: readonly string[],+ byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,+ metric: UsageChartMetric,+): readonly DayColumn[] {+ return periods.map((period) => {+ const entry = byPeriod.get(period);+ const bands = PROVIDER_ORDER.map((provider) => ({+ provider,+ value: valueFor(entry, provider, metric),+ }));+ return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) };+ });+}+/*** Monotone cubic tangents (Fritsch-Carlson).*@@ -167,23 +193,32 @@ export function buildDayColumns(byDay: ReadonlyMap<string, DailyTotals>,metric: UsageChartMetric,): readonly DayColumn[] {- return days.map((day) => {- const entry = byDay.get(day);- const bands = PROVIDER_ORDER.map((provider) => ({- provider,- value: valueFor(entry, provider, metric),- }));- return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) };- });+ return buildPeriodColumns(days, byDay, metric);}-export function UsageProviderChart({ days, daily, metric }: UsageProviderChartProps) {- const byDay = useMemo(() => new Map(daily.map((entry) => [entry.day, entry])), [daily]);+export function UsageProviderChart({+ days,+ daily,+ hours,+ hourly,+ metric,+ referenceTime,+ resolution,+ timeZone,+}: UsageProviderChartProps) {+ const periods = resolution === "hour" ? hours : days;+ const byPeriod = useMemo(+ () =>+ resolution === "hour"+ ? new Map(hourly.map((entry) => [entry.hourStart, entry]))+ : new Map(daily.map((entry) => [entry.day, entry])),+ [daily, hourly, resolution],+ );const [hoverIndex, setHoverIndex] = useState<number | null>(null);const plotRef = useRef<HTMLDivElement | null>(null);const { paths, ticks, stepX, toY, series } = useMemo(() => {- if (days.length === 0) {+ if (periods.length === 0) {return {paths: [],ticks: [0] as readonly number[],@@ -193,7 +228,7 @@ export function UsageProviderChart({ days, daily, metric }: UsageProviderChartPr};}- const columns = buildDayColumns(days, byDay, metric);+ const columns = buildPeriodColumns(periods, byPeriod, metric);// The scale tops out at the largest single provider-day, not the largest// sum: layered series each measure from zero, so a combined peak would@@ -203,7 +238,7 @@ export function UsageProviderChart({ days, daily, metric }: UsageProviderChartPr0,);const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT);- const step = days.length === 1 ? 0 : VIEW_WIDTH / (days.length - 1);+ const step = periods.length === 1 ? 0 : VIEW_WIDTH / (periods.length - 1);// Reserve a sliver above the top gridline so the series stroke, which is// drawn at constant screen width, is not shaved off at a peak.const toY = (value: number) =>@@ -231,24 +266,30 @@ export function UsageProviderChart({ days, daily, metric }: UsageProviderChartPrconst ordered = [...built].sort((a, b) => b.total - a.total);return { paths: ordered, ticks: tickValues, stepX: step, toY, series: columns };- }, [byDay, days, metric]);+ }, [byPeriod, metric, periods]);const format = metric === "tokens" ? formatTokens : formatUsd;const handleMove = useCallback((event: React.MouseEvent<HTMLDivElement>) => {const bounds = plotRef.current?.getBoundingClientRect();- if (bounds === undefined || bounds.width === 0 || days.length === 0) return;+ if (bounds === undefined || bounds.width === 0 || periods.length === 0) return;const fraction = (event.clientX - bounds.left) / bounds.width;- const index = Math.round(fraction * (days.length - 1));- setHoverIndex(Math.min(days.length - 1, Math.max(0, index)));+ const index = Math.round(fraction * (periods.length - 1));+ setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));},- [days.length],+ [periods.length],);- const hoveredDay = hoverIndex === null ? undefined : days[hoverIndex];+ const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex];- const hoverLeft = days.length <= 1 ? 0 : ((hoverIndex ?? 0) / (days.length - 1)) * 100;+ const hoverLeft = periods.length <= 1 ? 0 : ((hoverIndex ?? 0) / (periods.length - 1)) * 100;+ const formatPeriod = (period: string) =>+ resolution === "hour" ? formatHourShort(period, timeZone) : formatDayShort(period);+ const formatTooltipPeriod = (period: string) =>+ resolution === "hour" && referenceTime !== undefined+ ? formatRelativeHourShort(period, referenceTime, timeZone)+ : formatPeriod(period);return (<div className="flex flex-col gap-1">@@ -277,7 +318,7 @@ export function UsageProviderChart({ days, daily, metric }: UsageProviderChartPrviewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}preserveAspectRatio="none"role="img"- aria-label={`Daily ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}+ aria-label={`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}>{ticks.map((tick) => {const y = toY(tick);@@ -325,7 +366,7 @@ export function UsageProviderChart({ days, daily, metric }: UsageProviderChartPr)}</svg>- {hoveredDay === undefined ? null : (+ {hoveredPeriod === undefined ? null : (<divclassName="pointer-events-none absolute top-0 z-10 min-w-36 border border-border bg-background/95 px-2 py-1.5 text-xs"style={{@@ -333,7 +374,7 @@ export function UsageProviderChart({ days, daily, metric }: UsageProviderChartPrtransform: hoverLeft > 60 ? "translateX(-100%)" : "translateX(0)",}}>- <div className="mb-1 text-muted-foreground">{formatDayShort(hoveredDay)}</div>+ <div className="mb-1 text-muted-foreground">{formatTooltipPeriod(hoveredPeriod)}</div>{PROVIDER_ORDER.map((provider) => {const Mark = PROVIDER_MARK[provider];return (@@ -362,14 +403,16 @@ export function UsageProviderChart({ days, daily, metric }: UsageProviderChartPr</div><div className="flex justify-between pl-16 text-[10px] text-muted-foreground uppercase">- <span>{days[0] === undefined ? "" : formatDayShort(days[0])}</span>+ <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span><span>- {days[Math.floor(days.length / 2)] === undefined+ {periods[Math.floor(periods.length / 2)] === undefined? ""- : formatDayShort(days[Math.floor(days.length / 2)] ?? "")}+ : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}</span><span>- {days[days.length - 1] === undefined ? "" : formatDayShort(days[days.length - 1] ?? "")}+ {periods[periods.length - 1] === undefined+ ? ""+ : formatPeriod(periods[periods.length - 1] ?? "")}</span></div></div>diff --git a/apps/web/src/state/usage.ts b/apps/web/src/state/usage.tsindex 9d65b6ad6..ba78a61d8 100644--- a/apps/web/src/state/usage.ts+++ b/apps/web/src/state/usage.ts@@ -78,8 +78,18 @@ export function useUsage(input: UsageSummaryInput): UsageView {sinceDay: input.sinceDay,untilDay: input.untilDay,timeZone: input.timeZone,+ resolution: input.resolution,+ sinceTime: input.sinceTime,+ untilTime: input.untilTime,}),- [input.sinceDay, input.untilDay, input.timeZone],+ [+ input.sinceDay,+ input.untilDay,+ input.timeZone,+ input.resolution,+ input.sinceTime,+ input.untilTime,+ ],);const atom = usageByWindowAtom(windowKey);const environments = useAtomValue(atom);diff --git a/docs/README.md b/docs/README.mdindex 51277fd73..30653e7d5 100644--- a/docs/README.md+++ b/docs/README.md@@ -6,6 +6,7 @@- [Permission modes](./user/permission-modes.md)- [Keyboard shortcuts](./user/keybindings.md)- [Organizing threads](./user/thread-sidebar.md)+- [Review usage](./user/usage.md)- [Customize a project icon](./user/project-settings.md)- [Remote access](./user/remote-access.md)- [Keeping app and server in sync](./user/updating.md)diff --git a/docs/user/usage.md b/docs/user/usage.mdnew file mode 100644index 000000000..72d19ba77--- /dev/null+++ b/docs/user/usage.md@@ -0,0 +1,10 @@+# Review usage++The Usage page combines Codex and Claude Code activity from your connected environments. It reads+the providers' local session history and shows API-equivalent token cost, processed tokens, cache+savings, provider shares, and model breakdowns. Subscription billing is separate from the raw token+cost shown here.++Use **Past 24h** for an hourly chart covering the exact rolling 24-hour period. The **7 days**,+**30 days**, and **90 days** ranges use daily resolution. Cost and token toggles update both the+headline and chart, and refreshing rescans every connected environment.diff --git a/packages/contracts/src/usage.ts b/packages/contracts/src/usage.tsindex 1aa639fe4..cde888a61 100644--- a/packages/contracts/src/usage.ts+++ b/packages/contracts/src/usage.ts@@ -7,8 +7,8 @@* even for turns that were never driven through T3 Code. This mirrors the* approach `ccusage` takes.*- * Environments return pre-aggregated `(day, provider, model)` buckets. Raw- * transcript records never cross the wire.+ * Environments return pre-aggregated `(day, hourStart?, provider, model)`+ * buckets. Raw transcript records never cross the wire.** @module usage*/@@ -21,7 +21,7 @@ import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";* client renders partial coverage when an environment reports an older version* rather than failing the whole page.*/-export const USAGE_CONTRACT_VERSION = 3 as const;+export const USAGE_CONTRACT_VERSION = 4 as const;export const UsageProviderKind = Schema.Literals(["claude", "codex"]);export type UsageProviderKind = typeof UsageProviderKind.Type;@@ -39,6 +39,9 @@ export const UsageDay = TrimmedNonEmptyString.check(Schema.isPattern(USAGE_DAY_P);export type UsageDay = typeof UsageDay.Type;+export const UsageResolution = Schema.Literals(["day", "hour"]);+export type UsageResolution = typeof UsageResolution.Type;+/*** Why a bucket's cost is what it is.*@@ -68,7 +71,8 @@ export const UsageTokenTotals = Schema.Struct({export type UsageTokenTotals = typeof UsageTokenTotals.Type;/**- * One `(day, provider, model)` cell.+ * One `(day, hourStart?, provider, model)` cell. `hourStart` is the UTC start+ * instant of a rolling bucket and is present only for hourly requests.** `costUsd` is the raw API-equivalent cost of these tokens. It is not money* spent: subscription plans bill separately. `unpricedRecords` counts records@@ -77,6 +81,7 @@ export type UsageTokenTotals = typeof UsageTokenTotals.Type;*/export const UsageBucket = Schema.Struct({day: UsageDay,+ hourStart: Schema.optional(TrimmedNonEmptyString),provider: UsageProviderKind,model: TrimmedNonEmptyString,totals: UsageTokenTotals,@@ -165,6 +170,12 @@ export const UsageSummaryInput = Schema.Struct({* any window that crosses a DST boundary.*/timeZone: TrimmedNonEmptyString,+ /** Defaults to daily for older clients. */+ resolution: Schema.optional(UsageResolution),+ /** Inclusive UTC instant for an hourly rolling window. */+ sinceTime: Schema.optional(TrimmedNonEmptyString),+ /** Exclusive UTC instant for an hourly rolling window. */+ untilTime: Schema.optional(TrimmedNonEmptyString),});export type UsageSummaryInput = typeof UsageSummaryInput.Type;diff --git a/packages/shared/src/usageFormat.test.ts b/packages/shared/src/usageFormat.test.tsnew file mode 100644index 000000000..cecc07c6e--- /dev/null+++ b/packages/shared/src/usageFormat.test.ts@@ -0,0 +1,57 @@+// @effect-diagnostics globalDate:off -- A fixed instant keeps calendar-window assertions deterministic.+import { describe, expect, it } from "vite-plus/test";++import {+ enumerateHourStarts,+ formatDateTimeShort,+ formatHourShort,+ formatRelativeHourShort,+ makeWindow,+} from "./usageFormat.ts";++describe("hourly usage formatting", () => {+ it("enumerates 24 fixed buckets across a rolling window", () => {+ const hours = enumerateHourStarts("2026-08-10T12:37:00.000Z", "2026-08-11T12:37:00.000Z");++ expect(hours).toHaveLength(24);+ expect(hours[0]).toBe("2026-08-10T12:37:00.000Z");+ expect(hours[23]).toBe("2026-08-11T11:37:00.000Z");+ });++ it("formats rolling instants in the requested time zone", () => {+ expect(formatHourShort("2026-08-11T00:37:00.000Z", "UTC")).toBe("12 AM");+ expect(formatHourShort("2026-08-11T12:37:00.000Z", "UTC")).toBe("12 PM");+ expect(formatDateTimeShort("2026-08-11T17:37:00.000Z", "UTC")).toBe("Aug 11, 5 PM");+ });++ 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");+ });++ it("makes hourly tooltip dates relative to the window in its requested time zone", () => {+ const windowEnd = "2026-08-11T14:37:00.000Z";++ expect(formatRelativeHourShort("2026-08-10T17:37:00.000Z", windowEnd, "UTC")).toBe(+ "5 PM yesterday",+ );+ expect(formatRelativeHourShort("2026-08-11T14:37:00.000Z", windowEnd, "UTC")).toBe(+ "2 PM today",+ );+ expect(+ formatRelativeHourShort(+ "2026-08-11T01:37:00.000Z",+ "2026-08-11T10:37:00.000Z",+ "America/Los_Angeles",+ ),+ ).toBe("6 PM yesterday");+ });++ it("builds an exact minute-aligned 24-hour request", () => {+ const window = makeWindow(1, new Date("2026-08-11T12:37:42.123Z"), "hour");++ expect(window.resolution).toBe("hour");+ expect(window.sinceTime).toBe("2026-08-10T12:37:00.000Z");+ expect(window.untilTime).toBe("2026-08-11T12:37:00.000Z");+ });+});diff --git a/packages/shared/src/usageFormat.ts b/packages/shared/src/usageFormat.tsindex 21e11fee7..ef2b2bcf2 100644--- a/packages/shared/src/usageFormat.ts+++ b/packages/shared/src/usageFormat.ts@@ -4,7 +4,7 @@** @module usageFormat*/-import { UsageDay, type UsageSummaryInput } from "@t3tools/contracts";+import { UsageDay, type UsageResolution, type UsageSummaryInput } from "@t3tools/contracts";const CURRENCY = new Intl.NumberFormat("en-US", {style: "currency",@@ -80,11 +80,105 @@ export function enumerateDays(sinceDay: string, untilDay: string): readonly strireturn days;}+const HOUR_MS = 60 * 60 * 1000;++/** Every fixed-duration bucket start in an hourly rolling window. */+export function enumerateHourStarts(sinceTime: string, untilTime: string): readonly string[] {+ const starts: string[] = [];+ const start = Date.parse(sinceTime);+ const end = Date.parse(untilTime);+ if (Number.isNaN(start) || Number.isNaN(end) || end <= start) return starts;++ for (let cursor = start; cursor < end; cursor += HOUR_MS) {+ starts.push(new Date(cursor).toISOString());+ }+ return starts;+}++/**+ * A rolling bucket start rendered in the viewer's requested time zone.+ *+ * 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 {+ const instant = new Date(hourStart);+ if (Number.isNaN(instant.getTime())) return hourStart;+ const options = timeZone === undefined ? {} : { timeZone };+ const hourFormat = new Intl.DateTimeFormat("en-US", {+ ...options,+ hour: "numeric",+ });+ const wallHourFormat = new Intl.DateTimeFormat("en-CA", {+ ...options,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ hourCycle: "h23",+ });+ const wallHour = wallHourFormat.format(instant);+ const isRepeatedHour = [-HOUR_MS, HOUR_MS].some(+ (offset) => wallHourFormat.format(new Date(instant.getTime() + offset)) === wallHour,+ );++ if (!isRepeatedHour) return hourFormat.format(instant);+ return new Intl.DateTimeFormat("en-US", {+ ...(timeZone === undefined ? {} : { timeZone }),+ hour: "numeric",+ timeZoneName: "short",+ }).format(instant);+}++/** `2026-08-11T14:37:00Z` to `Aug 11, 2 PM` in the requested zone. */+export function formatDateTimeShort(instant: string, timeZone?: string): string {+ const date = new Date(instant);+ if (Number.isNaN(date.getTime())) return instant;+ return new Intl.DateTimeFormat("en-US", {+ ...(timeZone === undefined ? {} : { timeZone }),+ month: "short",+ day: "numeric",+ hour: "numeric",+ }).format(date);+}++/** An hourly tooltip label relative to the rolling window's end date. */+export function formatRelativeHourShort(+ hourStart: string,+ relativeTo: string,+ timeZone?: string,+): string {+ const instant = new Date(hourStart);+ const reference = new Date(relativeTo);+ if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) {+ return formatDateTimeShort(hourStart, timeZone);+ }++ const dayFormat = new Intl.DateTimeFormat("en-CA", {+ ...(timeZone === undefined ? {} : { timeZone }),+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ 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);++ if (calendarDaysAgo === 0) return `${hour} today`;+ if (calendarDaysAgo === 1) return `${hour} yesterday`;+ return formatDateTimeShort(hourStart, timeZone);+}+/*** The window the page requests, expressed in the viewer's own time zone so days* line up with what they actually experienced.*/-export function makeWindow(days: number, now = new Date()): UsageSummaryInput {+export function makeWindow(+ days: number,+ now = new Date(),+ resolution: UsageResolution = "day",+): UsageSummaryInput {const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";const format = new Intl.DateTimeFormat("en-CA", {timeZone,@@ -93,9 +187,26 @@ export function makeWindow(days: number, now = new Date()): UsageSummaryInput {day: "2-digit",});const untilDay = format.format(now);+ if (resolution === "hour") {+ // Minute-aligned bounds keep labels readable while still representing an+ // exact rolling 24-hour duration. Fixed-duration buckets remain correct+ // across offset changes and daylight-saving transitions.+ const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000;+ const sinceTimeMs = untilTimeMs - 24 * HOUR_MS;+ const sinceTime = new Date(sinceTimeMs);+ const untilTime = new Date(untilTimeMs);+ return {+ sinceDay: UsageDay.make(format.format(sinceTime)),+ untilDay: UsageDay.make(format.format(untilTime)),+ timeZone,+ resolution,+ sinceTime: sinceTime.toISOString(),+ untilTime: untilTime.toISOString(),+ };+ }// Subtracting fixed milliseconds from `now` lands on the wrong calendar day- // around a DST transition. Only "today" needs the zone; the window start is- // pure calendar arithmetic on that day, done in UTC where days are uniform.+ // around a DST transition. The window start is pure calendar arithmetic on+ // the local end day, done in UTC where days are uniform.const [year = 0, month = 1, dayOfMonth = 1] = untilDay.split("-").map((part) => Number.parseInt(part, 10));@@ -104,5 +215,6 @@ export function makeWindow(days: number, now = new Date()): UsageSummaryInput {sinceDay: UsageDay.make(start.toISOString().slice(0, 10)),untilDay: UsageDay.make(untilDay),timeZone,+ resolution,};}diff --git a/packages/shared/src/usageMerge.test.ts b/packages/shared/src/usageMerge.test.tsindex 3c377a33f..c2fa9e2a8 100644--- a/packages/shared/src/usageMerge.test.ts+++ b/packages/shared/src/usageMerge.test.ts@@ -254,5 +254,31 @@ describe("mergeUsage", () => {const merged = mergeUsage([], USAGE_CONTRACT_VERSION);expect(merged.costUsd).toBe(0);expect(merged.daily).toHaveLength(0);+ expect(merged.hourly).toHaveLength(0);+ });++ it("derives hourly totals without losing the daily rollup", () => {+ const merged = mergeUsage(+ [+ environment(+ "env-a",+ summary(+ [+ bucket({ hourStart: "2026-08-07T09:37:00.000Z", costUsd: 3 }),+ bucket({ hourStart: "2026-08-07T10:37:00.000Z", costUsd: 7 }),+ ],+ [{ provider: "claude", hostId: "mac", homePath: "/a/.claude" }],+ ),+ ),+ ],+ USAGE_CONTRACT_VERSION,+ );++ expect(merged.hourly.map((hour) => [hour.hourStart, hour.costUsd])).toEqual([+ ["2026-08-07T09:37:00.000Z", 3],+ ["2026-08-07T10:37:00.000Z", 7],+ ]);+ expect(merged.daily).toHaveLength(1);+ expect(merged.daily[0]?.costUsd).toBe(10);});});diff --git a/packages/shared/src/usageMerge.ts b/packages/shared/src/usageMerge.tsindex fd73c0a31..886b21418 100644--- a/packages/shared/src/usageMerge.ts+++ b/packages/shared/src/usageMerge.ts@@ -45,6 +45,14 @@ export interface DailyTotals {readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>;}+export interface HourlyTotals {+ readonly day: string;+ readonly hourStart: string;+ readonly costUsd: number;+ readonly totalTokens: number;+ readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>;+}+export interface CostQuality {readonly providerReportedShare: number;readonly modelPricedShare: number;@@ -65,6 +73,7 @@ export interface MergedUsage {readonly providers: readonly ProviderTotals[];readonly models: readonly ModelTotals[];readonly daily: readonly DailyTotals[];+ readonly hourly: readonly HourlyTotals[];readonly costQuality: CostQuality;/** Environments whose data was dropped as a duplicate of another's. */readonly duplicateSources: readonly string[];@@ -168,6 +177,7 @@ const EMPTY_MERGED: MergedUsage = {providers: [],models: [],daily: [],+ hourly: [],costQuality: {providerReportedShare: 0,modelPricedShare: 0,@@ -232,6 +242,16 @@ export function mergeUsage(byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;}>();+ const hourlyAccumulator = new Map<+ string,+ {+ day: string;+ hourStart: string;+ costUsd: number;+ totalTokens: number;+ byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;+ }+ >();const contributingEnvironments: EnvironmentId[] = [];for (const environment of current) {@@ -290,6 +310,26 @@ export function mergeUsage(dayProvider.totalTokens += tokens;day.byProvider.set(bucket.provider, dayProvider);dailyAccumulator.set(bucket.day, day);++ if (bucket.hourStart !== undefined) {+ const hour = hourlyAccumulator.get(bucket.hourStart) ?? {+ day: bucket.day,+ hourStart: bucket.hourStart,+ costUsd: 0,+ totalTokens: 0,+ byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),+ };+ hour.costUsd += bucket.costUsd;+ hour.totalTokens += tokens;+ const hourProvider = hour.byProvider.get(bucket.provider) ?? {+ costUsd: 0,+ totalTokens: 0,+ };+ hourProvider.costUsd += bucket.costUsd;+ hourProvider.totalTokens += tokens;+ hour.byProvider.set(bucket.provider, hourProvider);+ hourlyAccumulator.set(bucket.hourStart, hour);+ }}}@@ -326,6 +366,10 @@ export function mergeUsage(})).sort((a, b) => a.day.localeCompare(b.day));+ const hourly: HourlyTotals[] = [...hourlyAccumulator.values()].sort((a, b) =>+ a.hourStart.localeCompare(b.hourStart),+ );+return {costUsd,uncachedInputTokens,@@ -339,6 +383,7 @@ export function mergeUsage(providers,models,daily,+ hourly,costQuality: {providerReportedShare: records === 0 ? 0 : providerReportedRecords / records,unpricedShare: records === 0 ? 0 : unpricedRecords / records,