Skip to content

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.

feat(web): redesign usage insights (#7147)

maria8c85b4933fb7
diff --git a/apps/web/src/components/WorkspaceBreadcrumb.tsx b/apps/web/src/components/WorkspaceBreadcrumb.tsx
index 3c67e4d32..f1c3d8b15 100644
--- a/apps/web/src/components/WorkspaceBreadcrumb.tsx
+++ b/apps/web/src/components/WorkspaceBreadcrumb.tsx
@@ -45,9 +45,9 @@ export function WorkspaceBreadcrumbItem({
);
}
-export function WorkspaceBreadcrumbSeparator() {
+export function WorkspaceBreadcrumbSeparator({ className }: { readonly className?: string }) {
return (
- <li aria-hidden="true" className="flex shrink-0 items-center text-icon-muted">
+ <li aria-hidden="true" className={cn("flex shrink-0 items-center text-icon-muted", className)}>
/
</li>
);
diff --git a/apps/web/src/components/WorkspacePageContainer.tsx b/apps/web/src/components/WorkspacePageContainer.tsx
new file mode 100644
index 000000000..dd876bdac
--- /dev/null
+++ b/apps/web/src/components/WorkspacePageContainer.tsx
@@ -0,0 +1,29 @@
+import type { ComponentPropsWithoutRef } from "react";
+
+import { cn } from "../lib/utils";
+
+export type WorkspacePageWidth = "readable" | "wide" | "expanded";
+
+const WIDTH_CLASS: Record<WorkspacePageWidth, string> = {
+ readable: "max-w-4xl",
+ wide: "max-w-5xl",
+ expanded: "max-w-6xl",
+};
+
+/** Shared content frame for workspace pages. */
+export function WorkspacePageContainer({
+ width = "readable",
+ className,
+ ...props
+}: ComponentPropsWithoutRef<"div"> & { readonly width?: WorkspacePageWidth }) {
+ return (
+ <div
+ className={cn(
+ "mx-auto flex w-full flex-col gap-6 px-5 pt-6 pb-12 sm:px-6",
+ WIDTH_CLASS[width],
+ className,
+ )}
+ {...props}
+ />
+ );
+}
diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx
index 11d572fd2..15540ff59 100644
--- a/apps/web/src/components/settings/settingsLayout.tsx
+++ b/apps/web/src/components/settings/settingsLayout.tsx
@@ -12,17 +12,10 @@ import {
} from "react";
import { cn } from "../../lib/utils";
+import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer";
import { Button } from "../ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
-type SettingsPageWidth = "readable" | "wide" | "expanded";
-
-const SETTINGS_PAGE_WIDTH_CLASS: Record<SettingsPageWidth, string> = {
- readable: "max-w-4xl",
- wide: "max-w-5xl",
- expanded: "max-w-6xl",
-};
-
interface SettingsSearchTargetContextValue {
readonly targetId: string | null;
readonly onTargetHandled: () => void;
@@ -245,7 +238,7 @@ export function SettingsPageContainer({
}: {
children: ReactNode;
className?: string;
- width?: SettingsPageWidth;
+ width?: WorkspacePageWidth;
}) {
const navigate = useNavigate();
const hash = useLocation({ select: (location) => location.hash });
@@ -260,15 +253,9 @@ export function SettingsPageContainer({
className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto [--topbar-scroll-fade-height:1.5rem] sm:[--topbar-scroll-fade-height:1.5rem]"
data-settings-page-scroll
>
- <div
- className={cn(
- "mx-auto flex w-full flex-col gap-12 px-5 pt-6 pb-12 sm:px-6",
- SETTINGS_PAGE_WIDTH_CLASS[width],
- className,
- )}
- >
+ <WorkspacePageContainer width={width} className={cn("gap-12", className)}>
{children}
- </div>
+ </WorkspacePageContainer>
</div>
</SettingsSearchTargetProvider>
);
diff --git a/apps/web/src/components/ui/toggle-group.test.tsx b/apps/web/src/components/ui/toggle-group.test.tsx
new file mode 100644
index 000000000..c2403c9f1
--- /dev/null
+++ b/apps/web/src/components/ui/toggle-group.test.tsx
@@ -0,0 +1,19 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vite-plus/test";
+
+import { Toggle, ToggleGroup } from "./toggle-group";
+
+describe("toggle group segmented defaults", () => {
+ it("derives the segmented item size from the variant", () => {
+ const html = renderToStaticMarkup(
+ <ToggleGroup variant="segmented" value={["a"]}>
+ <Toggle value="a">A</Toggle>
+ </ToggleGroup>,
+ );
+
+ expect(html.match(/data-size="segmented"/g)).toHaveLength(2);
+ expect(html).toContain("h-6");
+ expect(html).toContain("dark:hover:bg-input/32");
+ expect(html).toContain("dark:data-pressed:bg-input/72");
+ });
+});
diff --git a/apps/web/src/components/ui/toggle-group.tsx b/apps/web/src/components/ui/toggle-group.tsx
index 68cf007d7..ae10fe816 100644
--- a/apps/web/src/components/ui/toggle-group.tsx
+++ b/apps/web/src/components/ui/toggle-group.tsx
@@ -17,7 +17,7 @@ const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariant
function ToggleGroup({
className,
variant = "default",
- size = "default",
+ size = variant === "segmented" ? "segmented" : "default",
orientation = "horizontal",
children,
...props
@@ -30,11 +30,13 @@ function ToggleGroup({
orientation === "horizontal"
? "*:pointer-coarse:after:min-w-auto"
: "*:pointer-coarse:after:min-h-auto",
- variant === "default"
- ? "gap-0.5"
- : orientation === "horizontal"
- ? "*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none"
- : "*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block",
+ variant === "segmented"
+ ? "gap-0.5 rounded-lg bg-input/40 p-0.5"
+ : variant === "default"
+ ? "gap-0.5"
+ : orientation === "horizontal"
+ ? "*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none"
+ : "*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block",
className,
)}
data-size={size}
diff --git a/apps/web/src/components/ui/toggle.tsx b/apps/web/src/components/ui/toggle.tsx
index 5bf04adf4..9f74d4546 100644
--- a/apps/web/src/components/ui/toggle.tsx
+++ b/apps/web/src/components/ui/toggle.tsx
@@ -18,6 +18,8 @@ const toggleVariants = cva(
"h-7 min-w-7 rounded-md px-[calc(--spacing(1)-1px)] text-xs before:rounded-[calc(var(--radius-md)-1px)] [&_svg:not([class*='size-'])]:size-3.5",
default: "h-9 min-w-9 px-[calc(--spacing(2)-1px)] sm:h-8 sm:min-w-8",
lg: "h-10 min-w-10 px-[calc(--spacing(2.5)-1px)] sm:h-9 sm:min-w-9",
+ segmented:
+ "h-6 min-w-0 rounded-md px-2.5 text-xs before:rounded-[calc(var(--radius-md)-1px)]",
sm: "h-8 min-w-8 px-[calc(--spacing(1.5)-1px)] sm:h-7 sm:min-w-7",
xs: "h-7 min-w-7 px-[calc(--spacing(1)-1px)] sm:h-6 sm:min-w-6 rounded-md",
},
@@ -27,6 +29,8 @@ const toggleVariants = cva(
"border-transparent text-foreground shadow-none [:disabled,:active,[data-pressed]]:shadow-none before:shadow-none data-pressed:bg-accent data-pressed:text-accent-foreground disabled:opacity-100 disabled:text-muted-foreground disabled:[&_svg]:opacity-100",
outline:
"border-input bg-background not-dark:bg-clip-padding shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:data-pressed:bg-input dark:hover:bg-input/64 dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:not-disabled:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/2%)] [:disabled,:active,[data-pressed]]:shadow-none",
+ segmented:
+ "border-transparent text-muted-foreground shadow-none transition-colors before:shadow-none hover:bg-background/55 hover:text-foreground data-pressed:bg-background data-pressed:text-foreground data-pressed:shadow-xs/10 dark:hover:bg-input/32 dark:data-pressed:bg-input/72",
},
},
},
diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx
index 3f3b3e2c3..3c99271c1 100644
--- a/apps/web/src/components/usage/UsagePage.tsx
+++ b/apps/web/src/components/usage/UsagePage.tsx
@@ -19,12 +19,19 @@ import {
formatUsd,
makeWindow,
} from "@t3tools/shared/usageFormat";
-import { ScrollArea } from "../ui/scroll-area";
import { Button } from "../ui/button";
+import { ScrollArea } from "../ui/scroll-area";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { SidebarInset } from "../ui/sidebar";
-import { WorkspaceBreadcrumb, WorkspaceBreadcrumbItem } from "../WorkspaceBreadcrumb";
-import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "../../workspaceTitlebar";
-import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
+import { Toggle, ToggleGroup } from "../ui/toggle-group";
+import {
+ WorkspaceBreadcrumb,
+ WorkspaceBreadcrumbItem,
+ WorkspaceBreadcrumbSeparator,
+} from "../WorkspaceBreadcrumb";
+import { WorkspacePageContainer } from "../WorkspacePageContainer";
+import { WorkspacePageHeader } from "../WorkspacePageHeader";
+import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
import { PROVIDER_ORDER, PROVIDER_PRESENTATION } from "./usageProviders";
const WINDOW_OPTIONS = [
@@ -68,21 +75,6 @@ export function UsagePage() {
[isPast24Hours, merged.daily, merged.hourly],
);
- // Ranked by whatever the toggle is showing, so the bars always descend.
- const orderedProviders = useMemo(
- () =>
- merged.providers.toSorted((a, b) =>
- metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
- ),
- [merged.providers, metric],
- );
-
- 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,
@@ -102,78 +94,113 @@ export function UsagePage() {
setWindowSelection({ days: windowDays, window: nextWindow });
}
};
+ const windowLabel =
+ 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)}`;
+ const topbarContent = (
+ <div className="flex w-full min-w-0 items-center gap-3">
+ <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="min-w-0">
+ <WorkspaceBreadcrumbItem current>
+ <h1>Usage</h1>
+ </WorkspaceBreadcrumbItem>
+ <WorkspaceBreadcrumbSeparator className="hidden md:flex" />
+ <WorkspaceBreadcrumbItem className="hidden min-w-0 shrink md:flex">
+ <span className="truncate">{windowLabel}</span>
+ </WorkspaceBreadcrumbItem>
+ </WorkspaceBreadcrumb>
+ <div className="ms-auto hidden min-w-0 items-center justify-end gap-2 lg:flex">
+ <ToggleGroup
+ aria-label="Usage metric"
+ variant="segmented"
+ value={[metric]}
+ onValueChange={(next) => {
+ const value = next[0];
+ if (value === "cost" || value === "tokens") setMetric(value);
+ }}
+ >
+ {(["cost", "tokens"] as const).map((option) => (
+ <Toggle key={option} value={option}>
+ {option === "cost" ? "Cost" : "Tokens"}
+ </Toggle>
+ ))}
+ </ToggleGroup>
+ <ToggleGroup
+ aria-label="Usage period"
+ variant="segmented"
+ value={[String(windowDays)]}
+ onValueChange={(next) => {
+ const value = next[0];
+ if (value) selectWindow(Number(value));
+ }}
+ >
+ {WINDOW_OPTIONS.map((option) => (
+ <Toggle key={option.days} value={String(option.days)}>
+ {option.label}
+ </Toggle>
+ ))}
+ </ToggleGroup>
+ <Button onClick={refreshWindow} aria-label="Refresh usage" size="icon-sm" variant="ghost">
+ <RefreshCwIcon className="size-3.5" />
+ </Button>
+ </div>
+ <div className="ms-auto flex min-w-0 items-center justify-end gap-1 lg:hidden">
+ <Select
+ value={metric}
+ onValueChange={(value) => {
+ if (value === "cost" || value === "tokens") setMetric(value);
+ }}
+ >
+ <SelectTrigger
+ aria-label="Usage metric"
+ size="compact"
+ variant="ghost"
+ className="w-auto min-w-0"
+ >
+ <SelectValue>{metric === "cost" ? "Cost" : "Tokens"}</SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ <SelectItem value="cost">Cost</SelectItem>
+ <SelectItem value="tokens">Tokens</SelectItem>
+ </SelectPopup>
+ </Select>
+ <Select value={String(windowDays)} onValueChange={(value) => selectWindow(Number(value))}>
+ <SelectTrigger
+ aria-label="Usage period"
+ size="compact"
+ variant="ghost"
+ className="w-auto min-w-0"
+ >
+ <SelectValue>
+ {WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ {WINDOW_OPTIONS.map((option) => (
+ <SelectItem key={option.days} value={String(option.days)}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ <Button onClick={refreshWindow} aria-label="Refresh usage" size="icon-sm" variant="ghost">
+ <RefreshCwIcon className="size-3.5" />
+ </Button>
+ </div>
+ </div>
+ );
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
- {!isElectron && (
- <header
- className={cn(
- "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
- COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
- )}
- >
- <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb">
- <WorkspaceBreadcrumbItem current>Usage</WorkspaceBreadcrumbItem>
- </WorkspaceBreadcrumb>
- </header>
- )}
-
- {isElectron && (
- <div
- className={cn(
- "drag-region flex h-[52px] shrink-0 items-center px-5 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
- COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
- )}
- >
- <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb">
- <WorkspaceBreadcrumbItem current>Usage</WorkspaceBreadcrumbItem>
- </WorkspaceBreadcrumb>
- </div>
- )}
+ <WorkspacePageHeader electron={isElectron}>{topbarContent}</WorkspacePageHeader>
<ScrollArea className="min-h-0 flex-1">
- <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">
- {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 rounded-md border border-border">
- {WINDOW_OPTIONS.map((option) => (
- <button
- key={option.days}
- type="button"
- aria-pressed={option.days === windowDays}
- onClick={() => selectWindow(option.days)}
- className={cn(
- "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",
- )}
- >
- {option.label}
- </button>
- ))}
- </div>
- <Button
- size="icon"
- variant="outline"
- onClick={refreshWindow}
- aria-label="Refresh usage"
- >
- <RefreshCwIcon className="size-3.5" />
- </Button>
- </div>
- </div>
-
+ <WorkspacePageContainer width="wide">
{settling ? (
<>
{environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}
- <UsageSkeleton resolution={isPast24Hours ? "hour" : "day"} />
+ <UsageSkeleton />
</>
) : (
<>
@@ -183,88 +210,71 @@ export function UsagePage() {
staleEnvironments={merged.staleEnvironments}
/>
- {/* Cost first: the financial answer, then the provider split. */}
- <section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
- {/* The summary follows the chart toggle, so the headline and the
- series are always reading the same units. */}
- <div className="flex flex-col gap-5">
+ <section className="grid gap-6 lg:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]">
+ <div className="flex min-w-0 flex-col gap-5">
<div className="flex flex-col gap-1">
- <span className="text-xs tracking-wide text-muted-foreground uppercase">
- {metric === "cost" ? "Raw token cost" : "Processed tokens"}
- </span>
<span className="text-4xl font-semibold text-foreground tabular-nums">
{metric === "cost"
- ? `${formatUsd(merged.costUsd)}*`
+ ? formatUsd(merged.costUsd)
: formatTokens(merged.totalTokens)}
</span>
<span className="text-xs text-muted-foreground">
{metric === "cost"
- ? "* if billed at full API rate"
- : `Input, cache reads and output across ${formatCount(merged.sessions)} sessions.`}
+ ? `${formatCount(merged.sessions)} sessions · API estimate`
+ : `${formatCount(merged.sessions)} sessions`}
</span>
</div>
- {orderedProviders.map((provider) => {
- const share = metric === "cost" ? provider.costShare : provider.tokenShare;
+ {PROVIDER_ORDER.map((provider) => {
+ const totals = merged.providers.find((entry) => entry.provider === provider);
+ const share =
+ metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
+ const providerSessions = totals?.sessions ?? 0;
+ const sessionLabel = `${formatCount(providerSessions)} ${
+ providerSessions === 1 ? "session" : "sessions"
+ }`;
return (
- <div key={provider.provider} className="flex flex-col gap-1.5">
- <div className="flex items-baseline justify-between">
- <span className="flex items-center gap-2 text-sm text-foreground">
- <ProviderMark provider={provider.provider} className="size-4" />
- {PROVIDER_PRESENTATION[provider.provider].label}
+ <div key={provider} className="flex flex-col gap-1">
+ <div className="flex items-baseline justify-between gap-4">
+ <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
+ <span
+ aria-hidden
+ className="size-2 shrink-0 rounded-full"
+ style={{
+ backgroundColor: PROVIDER_PRESENTATION[provider].color,
+ }}
+ />
+ <ProviderMark provider={provider} className="size-4" />
+ <span className="flex min-w-0 items-baseline gap-1.5">
+ <span className="truncate">
+ {PROVIDER_PRESENTATION[provider].label}
+ </span>
+ <span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground tabular-nums">
+ {sessionLabel}
+ </span>
+ </span>
</span>
- <span className="text-sm text-foreground tabular-nums">
+ <span className="shrink-0 text-sm font-medium text-foreground tabular-nums">
{metric === "cost"
- ? formatUsd(provider.costUsd)
- : formatTokens(provider.totalTokens)}
+ ? formatUsd(totals?.costUsd ?? 0)
+ : formatTokens(totals?.totalTokens ?? 0)}
</span>
</div>
- <div className="h-1 w-full overflow-hidden rounded-full bg-muted">
- <div
- className="h-full"
- style={{
- width: `${(share * 100).toFixed(1)}%`,
- backgroundColor: PROVIDER_PRESENTATION[provider.provider].color,
- }}
- />
- </div>
<span className="text-xs text-muted-foreground">
{metric === "cost"
- ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
- : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
+ ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
+ : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
</span>
</div>
);
})}
</div>
- <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">
- {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">
- {(["cost", "tokens"] as const).map((option) => (
- <button
- key={option}
- type="button"
- onClick={() => setMetric(option)}
- className={cn(
- "cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",
- option === metric
- ? "bg-muted text-foreground"
- : "text-muted-foreground hover:text-foreground",
- )}
- >
- {option}
- </button>
- ))}
- </div>
- <UsageChartLegend />
- </div>
- </div>
+ <div className="flex min-w-0 flex-col gap-3">
+ <h2 className="text-sm font-medium text-foreground">
+ {isPast24Hours ? "Hourly" : "Daily"}{" "}
+ {metric === "tokens" ? "processed tokens" : "cost"}
+ </h2>
<UsageProviderChart
days={days}
daily={merged.daily}
@@ -278,63 +288,46 @@ export function UsagePage() {
</div>
</section>
- <section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5">
- <Metric
- label="Processed tokens"
- value={formatTokens(merged.totalTokens)}
- detail={`${formatTokens(periodAverage)} per active ${isPast24Hours ? "hour" : "day"}`}
- />
- <Metric
- label="Cached input"
- value={formatTokens(merged.cachedInputTokens)}
- detail={`${formatPercent(cachedShare)} of observed input`}
- />
- <Metric
- label="Uncached input"
- value={formatTokens(merged.uncachedInputTokens)}
- detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
- />
- <Metric
- label="Output"
- value={formatTokens(merged.outputTokens)}
- detail={`includes ${formatTokens(merged.reasoningTokens)} reasoning`}
- />
- <Metric
- label="Cache savings"
- value={formatUsd(merged.costQuality.cacheSavingsUsd)}
- detail={
- merged.costUsd > 0
- ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw token cost`
- : "vs full input rates"
- }
- />
+ <section className="flex flex-col gap-2">
+ <h2 className="text-sm font-medium text-foreground">Totals</h2>
+ <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
+ <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />
+ <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />
+ <Metric
+ label="Uncached input"
+ value={formatTokens(merged.uncachedInputTokens)}
+ />
+ <Metric label="Output" value={formatTokens(merged.outputTokens)} />
+ <Metric
+ label="Cache savings"
+ value={formatUsd(merged.costQuality.cacheSavingsUsd)}
+ />
+ </div>
</section>
<section className="flex flex-col gap-3">
<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">
+ <ToggleGroup
+ aria-label="Usage breakdown"
+ variant="segmented"
+ value={[breakdown]}
+ onValueChange={(next) => {
+ const value = next[0];
+ if (value === "model" || value === "time") setBreakdown(value);
+ }}
+ >
{(
[
- { value: "model", label: "model" },
- { value: "time", label: isPast24Hours ? "hour" : "day" },
+ { value: "model", label: "Model" },
+ { value: "time", label: isPast24Hours ? "Hour" : "Day" },
] as const
).map((option) => (
- <button
- key={option.value}
- type="button"
- onClick={() => setBreakdown(option.value)}
- className={cn(
- "cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",
- option.value === breakdown
- ? "bg-muted text-foreground"
- : "text-muted-foreground hover:text-foreground",
- )}
- >
+ <Toggle key={option.value} value={option.value}>
{option.label}
- </button>
+ </Toggle>
))}
- </div>
+ </ToggleGroup>
</div>
{breakdown === "model" ? (
@@ -358,7 +351,7 @@ export function UsagePage() {
merged.models.map((model) => (
<tr
key={`${model.provider}:${model.model}`}
- className="border-b border-border/50"
+ className="border-b border-border/50 transition-colors hover:bg-muted/50"
>
<td className="py-2 text-foreground">
<span className="flex items-center gap-2">
@@ -405,7 +398,7 @@ export function UsagePage() {
breakdownPeriods.map((period) => (
<tr
key={"hourStart" in period ? period.hourStart : period.day}
- className="border-b border-border/50"
+ className="border-b border-border/50 transition-colors hover:bg-muted/50"
>
<td className="py-2 text-foreground">
{"hourStart" in period
@@ -435,7 +428,7 @@ export function UsagePage() {
</section>
</>
)}
- </div>
+ </WorkspacePageContainer>
</ScrollArea>
</div>
</SidebarInset>
@@ -454,20 +447,11 @@ function ProviderMark({
return <Mark className={cn("shrink-0", className)} aria-hidden />;
}
-function Metric({
- label,
- value,
- detail,
-}: {
- readonly label: string;
- readonly value: string;
- readonly detail: string;
-}) {
+function Metric({ label, value }: { readonly label: string; readonly value: string }) {
return (
- <div className="flex flex-col gap-0.5 bg-background px-4 py-3">
+ <div className="flex min-w-0 flex-col gap-0.5">
<span className="text-xs text-muted-foreground">{label}</span>
- <span className="text-lg text-foreground tabular-nums">{value}</span>
- <span className="text-xs text-muted-foreground">{detail}</span>
+ <span className="text-base font-medium text-foreground tabular-nums">{value}</span>
</div>
);
}
@@ -571,70 +555,59 @@ function UsageDeviceStrip({
);
}
-/** Deterministic bar heights (each unique: they double as keys). */
-const SKELETON_BAR_HEIGHTS = [34, 58, 41, 72, 22, 12, 49, 63, 80, 38, 55, 26, 44, 67];
-
/**
- * Static stand-in with the loaded page's shape: headline, provider split,
- * chart and metrics strip. No shimmer; blocks fill in exactly once when the
- * last device answers.
+ * Static stand-in with the loaded page's shape. No shimmer; blocks fill in
+ * exactly once when the last device answers.
*/
-function UsageSkeleton({ resolution }: { readonly resolution: "day" | "hour" }) {
+function UsageSkeleton() {
return (
<>
- <section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
+ <section className="grid gap-6 lg:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]">
<div className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
- <span className="text-xs tracking-wide text-muted-foreground uppercase">
- Raw token cost
- </span>
- <div className="my-1.5 h-8 w-36 rounded-sm bg-muted" />
- <div className="h-3 w-28 rounded-sm bg-muted" />
+ <div className="h-10 w-36 rounded-sm bg-muted" />
+ <div className="h-4 w-32 rounded-sm bg-muted" />
</div>
-
{PROVIDER_ORDER.map((provider) => (
- <div key={provider} className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <span className="flex items-center gap-2 text-sm text-foreground">
+ <div key={provider} className="flex flex-col gap-1">
+ <div className="flex min-h-5 items-center justify-between gap-4">
+ <span className="flex items-center gap-2">
+ <span
+ aria-hidden
+ className="size-2 shrink-0 rounded-full"
+ style={{ backgroundColor: PROVIDER_PRESENTATION[provider].color }}
+ />
<ProviderMark provider={provider} className="size-4" />
- {PROVIDER_PRESENTATION[provider].label}
+ <div className="h-3.5 w-20 rounded-sm bg-muted" />
</span>
<div className="h-3.5 w-14 rounded-sm bg-muted" />
</div>
- <div className="h-1 w-full rounded-full bg-muted" />
- <div className="h-3 w-36 rounded-sm bg-muted" />
+ <div className="h-4 w-36 rounded-sm bg-muted" />
</div>
))}
</div>
<div className="flex flex-col gap-3">
- <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 a
- relayout when the real chart swaps in. */}
- <div className="flex h-56 items-end gap-1 pl-16">
- {SKELETON_BAR_HEIGHTS.map((height) => (
- <div
- key={height}
- className="flex-1 rounded-sm bg-muted"
- style={{ height: `${height}%` }}
- />
- ))}
+ <div className="h-5 w-24 rounded-sm bg-muted" />
+ <div className="flex flex-col gap-1">
+ <div className="ml-16 h-56 rounded-sm bg-muted/35" />
+ <div className="ml-16 h-3 rounded-sm bg-muted/35" />
</div>
</div>
</section>
- <section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5">
- {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
- (label) => (
- <div key={label} className="flex flex-col gap-0.5 bg-background px-4 py-3">
- <span className="text-xs text-muted-foreground">{label}</span>
- <div className="my-1 h-5 w-16 rounded-sm bg-muted" />
- <div className="h-3 w-24 rounded-sm bg-muted" />
- </div>
- ),
- )}
+ <section className="flex flex-col gap-2">
+ <h2 className="text-sm font-medium text-foreground">Totals</h2>
+ <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
+ {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
+ (label) => (
+ <div key={label} className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">{label}</span>
+ <div className="my-0.5 h-4 w-16 rounded-sm bg-muted" />
+ </div>
+ ),
+ )}
+ </div>
</section>
</>
);
diff --git a/apps/web/src/components/usage/UsageProviderChart.tsx b/apps/web/src/components/usage/UsageProviderChart.tsx
index d7582a0e4..8bc846483 100644
--- a/apps/web/src/components/usage/UsageProviderChart.tsx
+++ b/apps/web/src/components/usage/UsageProviderChart.tsx
@@ -1,5 +1,5 @@
import type { UsageProviderKind } from "@t3tools/contracts";
-import { useCallback, useMemo, useRef, useState } from "react";
+import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";
import {
@@ -68,13 +68,7 @@ function buildPeriodColumns(
});
}
-/**
- * Monotone cubic tangents (Fritsch-Carlson).
- *
- * Plain cubic smoothing overshoots on spiky daily data and would dip the area
- * below zero between points, which reads as negative spend. This variant is
- * shape-preserving, so a smoothed series never leaves the range of its samples.
- */
+/** Shape-preserving cubic tangents that cannot overshoot spiky usage data. */
function monotoneTangents(points: readonly Point[]): readonly number[] {
const count = points.length;
if (count < 2) return [0];
@@ -115,7 +109,6 @@ function monotoneTangents(points: readonly Point[]): readonly number[] {
return tangents;
}
-/** One cubic segment of a smoothed boundary. */
interface CurveSegment {
readonly from: Point;
readonly c1: Point;
@@ -123,7 +116,6 @@ interface CurveSegment {
readonly to: Point;
}
-/** Smoothed polyline through `points`, as explicit cubic control points. */
function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
if (points.length < 2) return [];
const tangents = monotoneTangents(points);
@@ -144,10 +136,10 @@ function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
return segments;
}
-function curvePath(segments: readonly CurveSegment[], startCommand: "M" | "L"): string {
+function curvePath(segments: readonly CurveSegment[]): string {
const first = segments[0];
if (first === undefined) return "";
- let path = `${startCommand}${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
+ let path = `M${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
for (const segment of segments) {
path += ` C${segment.c1.x.toFixed(2)},${segment.c1.y.toFixed(2)} ${segment.c2.x.toFixed(2)},${segment.c2.y.toFixed(2)} ${segment.to.x.toFixed(2)},${segment.to.y.toFixed(2)}`;
}
@@ -179,10 +171,8 @@ export function niceScale(peak: number, count: number): { max: number; ticks: re
/**
* Turns the merged daily totals into one column per day.
*
- * Values are absolute, not cumulative: the series are layered from a shared
- * zero baseline rather than stacked. A stacked chart puts whichever provider is
- * drawn last permanently above the other, which reads as "that one is bigger"
- * even on days where it is not.
+ * Values are absolute, not cumulative: each provider is drawn from the same
+ * zero baseline so the chart never implies that one provider is always larger.
*
* The chart paths and the hover readout both consume this, so the number under
* the cursor is by construction the number that was plotted rather than a
@@ -216,42 +206,44 @@ export function UsageProviderChart({
);
const [hoverIndex, setHoverIndex] = useState<number | null>(null);
const plotRef = useRef<HTMLDivElement | null>(null);
+ const tooltipRef = useRef<HTMLDivElement | null>(null);
+ const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);
- const { paths, ticks, stepX, toY, series } = useMemo(() => {
+ const { paths, series, stepX, ticks, toY } = useMemo(() => {
if (periods.length === 0) {
return {
paths: [],
- ticks: [0] as readonly number[],
+ series: [] as readonly DayColumn[],
stepX: 0,
+ ticks: [0] as readonly number[],
toY: () => VIEW_HEIGHT,
- series: [] as readonly DayColumn[],
};
}
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
- // leave the plot permanently half empty.
+ // The scale tops out at the largest single provider-period, not the sum:
+ // layered series each measure from zero, so a combined peak would leave
+ // the plot permanently half empty.
const peak = columns.reduce(
(max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
0,
);
const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT);
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.
+ // Leave room above the top gridline so the constant-width stroke is not
+ // clipped when a series reaches the peak.
const toY = (value: number) =>
max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
const built = PROVIDER_ORDER.map((provider, providerIndex) => {
- const curve = smoothCurve(
- columns.map((column, dayIndex) => ({
- x: dayIndex * step,
- y: toY(column.bands[providerIndex]?.value ?? 0),
- })),
+ const line = curvePath(
+ smoothCurve(
+ columns.map((column, periodIndex) => ({
+ x: periodIndex * step,
+ y: toY(column.bands[providerIndex]?.value ?? 0),
+ })),
+ ),
);
- const line = curvePath(curve, "M");
return {
provider,
total: columns.reduce((sum, column) => sum + (column.bands[providerIndex]?.value ?? 0), 0),
@@ -260,30 +252,76 @@ export function UsageProviderChart({
};
});
- // Paint the heavier series first so the lighter one is never buried under
- // it. The fills are faint enough that the order barely shows, but the
- // strokes are drawn in a second pass regardless, so neither can be hidden.
- const ordered = [...built].sort((a, b) => b.total - a.total);
-
- return { paths: ordered, ticks: tickValues, stepX: step, toY, series: columns };
+ // Paint the heavier series first so the lighter one is not buried.
+ return {
+ paths: built.toSorted((a, b) => b.total - a.total),
+ series: columns,
+ stepX: step,
+ ticks: tickValues,
+ toY,
+ };
}, [byPeriod, metric, periods]);
const format = metric === "tokens" ? formatTokens : formatUsd;
+ const positionTooltip = useCallback(() => {
+ const plot = plotRef.current;
+ const tooltip = tooltipRef.current;
+ const hoverPosition = hoverPositionRef.current;
+ if (plot === null || tooltip === null || hoverPosition === null) return;
+
+ const gap = 12;
+ const tooltipWidth = tooltip.offsetWidth;
+ const tooltipHeight = tooltip.offsetHeight;
+ const plotWidth = plot.clientWidth;
+ const plotHeight = plot.clientHeight;
+ const preferredLeft =
+ hoverPosition.x + gap + tooltipWidth <= plotWidth
+ ? hoverPosition.x + gap
+ : hoverPosition.x - gap - tooltipWidth;
+ const preferredTop =
+ hoverPosition.y + gap + tooltipHeight <= plotHeight
+ ? hoverPosition.y + gap
+ : hoverPosition.y - gap - tooltipHeight;
+ const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));
+ const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));
+ plot.style.setProperty("--usage-tooltip-left", `${left}px`);
+ plot.style.setProperty("--usage-tooltip-top", `${top}px`);
+ }, []);
+
+ useLayoutEffect(() => {
+ if (hoverIndex === null) return;
+ positionTooltip();
+
+ const plot = plotRef.current;
+ const tooltip = tooltipRef.current;
+ if (plot === null || tooltip === null || typeof ResizeObserver === "undefined") return;
+
+ const observer = new ResizeObserver(positionTooltip);
+ observer.observe(plot);
+ observer.observe(tooltip);
+ return () => observer.disconnect();
+ }, [hoverIndex, positionTooltip]);
+
const handleMove = useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
- const bounds = plotRef.current?.getBoundingClientRect();
- if (bounds === undefined || bounds.width === 0 || periods.length === 0) return;
- const fraction = (event.clientX - bounds.left) / bounds.width;
+ const plot = plotRef.current;
+ if (plot === null || periods.length === 0) return;
+ const bounds = plot.getBoundingClientRect();
+ if (bounds.width === 0) return;
+ const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));
+ const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));
+ const fraction = localX / bounds.width;
const index = Math.round(fraction * (periods.length - 1));
+ hoverPositionRef.current = { x: localX, y: localY };
+ positionTooltip();
setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));
},
- [periods.length],
+ [periods.length, positionTooltip],
);
const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];
const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex];
- 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) =>
@@ -311,7 +349,10 @@ export function UsageProviderChart({
ref={plotRef}
className="relative h-56 flex-1"
onMouseMove={handleMove}
- onMouseLeave={() => setHoverIndex(null)}
+ onMouseLeave={() => {
+ hoverPositionRef.current = null;
+ setHoverIndex(null);
+ }}
>
<svg
className="h-full w-full"
@@ -373,10 +414,11 @@ export function UsageProviderChart({
{hoveredPeriod === undefined ? null : (
<div
- className="pointer-events-none absolute top-0 z-10 min-w-36 border border-border bg-background/95 px-2 py-1.5 text-xs"
+ ref={tooltipRef}
+ className="surface-glass pointer-events-none absolute z-10 min-w-36 max-w-full rounded-xl border border-border/50 px-2.5 py-2 text-xs shadow-lg"
style={{
- left: `${hoverLeft}%`,
- transform: hoverLeft > 60 ? "translateX(-100%)" : "translateX(0)",
+ left: "var(--usage-tooltip-left, 0px)",
+ top: "var(--usage-tooltip-top, 0px)",
}}
>
<div className="mb-1 text-muted-foreground">{formatTooltipPeriod(hoveredPeriod)}</div>
@@ -423,21 +465,3 @@ export function UsageProviderChart({
</div>
);
}
-
-export function UsageChartLegend() {
- return (
- <div className="flex items-center gap-4">
- {PROVIDER_ORDER.map((provider) => {
- // Brand marks keep monochrome providers identifiable even when their
- // chart series use distinct colors.
- const { label, mark: Mark } = PROVIDER_PRESENTATION[provider];
- return (
- <span key={provider} className="flex items-center gap-1.5 text-xs text-muted-foreground">
- <Mark className="size-3.5 shrink-0" aria-hidden />
- {label}
- </span>
- );
- })}
- </div>
- );
-}
diff --git a/apps/web/src/components/usage/usageProviders.ts b/apps/web/src/components/usage/usageProviders.ts
index 00db67e28..615980cd4 100644
--- a/apps/web/src/components/usage/usageProviders.ts
+++ b/apps/web/src/components/usage/usageProviders.ts
@@ -26,5 +26,5 @@ export const PROVIDER_PRESENTATION = {
},
} satisfies Record<UsageProviderKind, UsageProviderPresentation>;
-/** The chart layers every series from zero, so order only controls how it is read. */
+/** Stable provider reading order across charts, summaries, tables, and hover rows. */
export const PROVIDER_ORDER = Object.keys(PROVIDER_PRESENTATION) as UsageProviderKind[];
diff --git a/packages/shared/src/usageMerge.test.ts b/packages/shared/src/usageMerge.test.ts
index c2fa9e2a8..3bee4a9bd 100644
--- a/packages/shared/src/usageMerge.test.ts
+++ b/packages/shared/src/usageMerge.test.ts
@@ -138,6 +138,12 @@ describe("mergeUsage", () => {
"claude",
"codex",
]);
+ expect(merged.sessions).toBe(2);
+ expect(
+ Object.fromEntries(
+ merged.providers.map((provider) => [provider.provider, provider.sessions]),
+ ),
+ ).toEqual({ claude: 1, codex: 1 });
});
it("excludes an environment reporting an older contract version", () => {
@@ -248,6 +254,7 @@ describe("mergeUsage", () => {
);
expect(merged.sessions).toBe(1);
+ expect(merged.providers[0]?.sessions).toBe(1);
});
it("returns empty totals with no environments", () => {
@@ -257,6 +264,30 @@ describe("mergeUsage", () => {
expect(merged.hourly).toHaveLength(0);
});
+ it("omits providers with no sessions or usage", () => {
+ const merged = mergeUsage(
+ [
+ environment(
+ "env-a",
+ summary(
+ [],
+ [
+ {
+ provider: "claude",
+ hostId: "mac",
+ homePath: "/a/.claude",
+ distinctSessions: 0,
+ },
+ ],
+ ),
+ ),
+ ],
+ USAGE_CONTRACT_VERSION,
+ );
+
+ expect(merged.providers).toEqual([]);
+ });
+
it("derives hourly totals without losing the daily rollup", () => {
const merged = mergeUsage(
[
diff --git a/packages/shared/src/usageMerge.ts b/packages/shared/src/usageMerge.ts
index 886b21418..954139b4e 100644
--- a/packages/shared/src/usageMerge.ts
+++ b/packages/shared/src/usageMerge.ts
@@ -25,6 +25,7 @@ export interface ProviderTotals {
readonly costUsd: number;
readonly totalTokens: number;
readonly records: number;
+ readonly sessions: number;
readonly costShare: number;
readonly tokenShare: number;
}
@@ -135,22 +136,29 @@ function claimSources(environments: readonly EnvironmentUsage[]): {
function ownedContribution(
environment: EnvironmentUsage,
ownerByFingerprint: ReadonlyMap<string, EnvironmentId>,
-): { readonly buckets: readonly UsageBucket[]; readonly sessions: number } {
+): {
+ readonly buckets: readonly UsageBucket[];
+ readonly sessionsByProvider: ReadonlyMap<UsageProviderKind, number>;
+} {
const ownedProviders = new Set<UsageProviderKind>();
- let sessions = 0;
+ const sessionsByProvider = new Map<UsageProviderKind, number>();
for (const source of environment.summary.sources) {
if (source.status === "missing") continue;
const key = fingerprintKey(source.fingerprint);
if (ownerByFingerprint.get(key) === environment.environmentId) {
- ownedProviders.add(source.fingerprint.provider);
+ const provider = source.fingerprint.provider;
+ ownedProviders.add(provider);
// Distinct within a directory. Summing per-bucket session counts instead
// would count a session once per day and model it spans.
- sessions += source.distinctSessions;
+ sessionsByProvider.set(
+ provider,
+ (sessionsByProvider.get(provider) ?? 0) + source.distinctSessions,
+ );
}
}
return {
buckets: environment.summary.buckets.filter((bucket) => ownedProviders.has(bucket.provider)),
- sessions,
+ sessionsByProvider,
};
}
@@ -228,7 +236,7 @@ export function mergeUsage(
const providerAccumulator = new Map<
UsageProviderKind,
- { costUsd: number; totalTokens: number; records: number }
+ { costUsd: number; totalTokens: number; records: number; sessions: number }
>();
const modelAccumulator = new Map<
string,
@@ -255,12 +263,21 @@ export function mergeUsage(
const contributingEnvironments: EnvironmentId[] = [];
for (const environment of current) {
- const { buckets, sessions: environmentSessions } = ownedContribution(
- environment,
- ownerByFingerprint,
- );
+ const { buckets, sessionsByProvider } = ownedContribution(environment, ownerByFingerprint);
if (buckets.length > 0) contributingEnvironments.push(environment.environmentId);
- sessions += environmentSessions;
+
+ for (const [providerKind, providerSessions] of sessionsByProvider) {
+ sessions += providerSessions;
+ if (providerSessions === 0) continue;
+ const provider = providerAccumulator.get(providerKind) ?? {
+ costUsd: 0,
+ totalTokens: 0,
+ records: 0,
+ sessions: 0,
+ };
+ provider.sessions += providerSessions;
+ providerAccumulator.set(providerKind, provider);
+ }
for (const bucket of buckets) {
const tokens = bucketTokens(bucket);
@@ -280,6 +297,7 @@ export function mergeUsage(
costUsd: 0,
totalTokens: 0,
records: 0,
+ sessions: 0,
};
provider.costUsd += bucket.costUsd;
provider.totalTokens += tokens;
@@ -341,6 +359,7 @@ export function mergeUsage(
costUsd: totals.costUsd,
totalTokens: totals.totalTokens,
records: totals.records,
+ sessions: totals.sessions,
costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
tokenShare: totalTokens === 0 ? 0 : totals.totalTokens / totalTokens,
}))