Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): state the window the usage figure covers (#105175)

posthog[bot]8e33a4dace76
diff --git a/products/desktop/packages/core/src/billing/usageDisplay.test.ts b/products/desktop/packages/core/src/billing/usageDisplay.test.ts
index 8764cf6304d2..31da099a9750 100644
--- a/products/desktop/packages/core/src/billing/usageDisplay.test.ts
+++ b/products/desktop/packages/core/src/billing/usageDisplay.test.ts
@@ -3,6 +3,8 @@ import type { UsageOutput } from "../usage/schemas";
import {
codeOrgSpendLimitUsd,
codeUsageMeter,
+ codeUsageResetLabel,
+ codeUsageWindowLabel,
desktopUsageComponents,
formatResetTime,
formatUsageBreakdown,
@@ -93,7 +95,7 @@ describe("codeUsageMeter", () => {
limitUsd: 50,
percent: 25,
exceeded: false,
- resetAt: "2026-06-01T00:00:00.000Z",
+ periodEndsAt: "2026-06-01T00:00:00.000Z",
breakdown: { includedUsd: 20, spendLimitUsd: 30 },
});
});
@@ -120,7 +122,7 @@ describe("codeUsageMeter", () => {
expect(meter).toMatchObject({ kind: "dollars", breakdown: null });
});
- it("marks the dollars meter exceeded from the org bucket and falls back to the sustained reset", () => {
+ it("marks the dollars meter exceeded from the org bucket, and never borrows the valve reset as a period end", () => {
const meter = codeUsageMeter({
...makeUsage(),
code_usage_subscribed: false,
@@ -130,7 +132,7 @@ describe("codeUsageMeter", () => {
kind: "dollars",
percent: 100,
exceeded: true,
- resetAt: "2026-05-01T13:00:00.000Z",
+ periodEndsAt: null,
});
});
@@ -159,6 +161,62 @@ describe("codeUsageMeter", () => {
});
});
+describe("codeUsageWindowLabel", () => {
+ const dollars = codeUsageMeter({
+ ...makeUsage(),
+ code_usage_subscribed: true,
+ ai_credits: { exhausted: false, used_usd: 12.4, limit_usd: 50 },
+ billing_period_end: "2026-06-01T00:00:00.000Z",
+ });
+ const bucket = codeUsageMeter({
+ ...makeUsage(),
+ code_usage_subscribed: false,
+ });
+
+ it.each([
+ [dollars, false, "Usage this billing period"],
+ [dollars, true, "Free usage this billing period"],
+ [bucket, true, "Free usage this 30-day window"],
+ ])("names the window the number covers", (meter, freeTier, expected) => {
+ expect(codeUsageWindowLabel(meter, freeTier)).toBe(expected);
+ });
+});
+
+describe("codeUsageResetLabel", () => {
+ const now = Date.parse("2026-05-01T12:00:00.000Z");
+
+ it("counts down to billing's own period end", () => {
+ const meter = codeUsageMeter({
+ ...makeUsage(),
+ code_usage_subscribed: true,
+ ai_credits: { exhausted: false, used_usd: 12.4, limit_usd: 50 },
+ billing_period_end: "2026-05-01T18:00:00.000Z",
+ });
+ expect(codeUsageResetLabel(meter, { now })).toBe(
+ "Billing period ends in 6h",
+ );
+ });
+
+ it("claims no period end when billing reported none", () => {
+ const meter = codeUsageMeter({
+ ...makeUsage(),
+ code_usage_subscribed: true,
+ ai_credits: { exhausted: false, used_usd: 12.4, limit_usd: 50 },
+ });
+ expect(codeUsageResetLabel(meter, { now })).toBe(
+ "Resets when your billing period ends",
+ );
+ });
+
+ it("counts down to the valve bucket's own reset", () => {
+ const meter = codeUsageMeter({
+ ...makeUsage(),
+ code_usage_subscribed: false,
+ });
+ expect(codeUsageResetLabel(meter, { now })).toBe("Resets in 1h");
+ });
+});
+
describe("codeOrgSpendLimitUsd", () => {
const subscribedWithLimit = (limitUsd: number | null) => ({
code_usage_subscribed: true,
diff --git a/products/desktop/packages/core/src/billing/usageDisplay.ts b/products/desktop/packages/core/src/billing/usageDisplay.ts
index d544bff92939..2b2304ffbade 100644
--- a/products/desktop/packages/core/src/billing/usageDisplay.ts
+++ b/products/desktop/packages/core/src/billing/usageDisplay.ts
@@ -33,7 +33,12 @@ export type CodeUsageMeter =
limitUsd: number;
percent: number;
exceeded: boolean;
- resetAt: string;
+ /**
+ * End of the billing period the dollars cover, or null when billing has
+ * not reported one. The valve bucket's reset is a different window, so it
+ * is not a stand-in here.
+ */
+ periodEndsAt: string | null;
breakdown: CodeUsageBreakdown | null;
}
| { kind: "bucket"; bucket: UsageBucket }
@@ -59,7 +64,7 @@ export function codeUsageMeter(
limitUsd,
percent: Math.min(100, Math.round((usedUsd / limitUsd) * 100)),
exceeded: usage.ai_credits?.exhausted === true,
- resetAt: usage.billing_period_end ?? usage.sustained.reset_at,
+ periodEndsAt: usage.billing_period_end ?? null,
breakdown:
spendLimitUsd != null
? { includedUsd: CODE_INCLUDED_USAGE_USD, spendLimitUsd }
@@ -72,6 +77,39 @@ export function codeUsageMeter(
return { kind: "hidden" };
}
+/**
+ * The window the meter's number covers. Org dollars are a billing-period total,
+ * while the valve bucket counts a fixed 30 days, and the two rarely line up.
+ */
+export function codeUsageWindowSuffix(meter: CodeUsageMeter): string {
+ return meter.kind === "bucket" ? "this 30-day window" : "this billing period";
+}
+
+/** The meter's heading: what the number is, over the window it covers. */
+export function codeUsageWindowLabel(
+ meter: CodeUsageMeter,
+ freeTier: boolean,
+): string {
+ return `${freeTier ? "Free usage" : "Usage"} ${codeUsageWindowSuffix(meter)}`;
+}
+
+/** When the meter's window restarts, phrased for the window it belongs to. */
+export function codeUsageResetLabel(
+ meter: CodeUsageMeter,
+ options: { now?: number } = {},
+): string {
+ if (meter.kind === "bucket") {
+ return formatResetTime(meter.bucket.reset_at, options);
+ }
+ if (meter.kind === "dollars" && meter.periodEndsAt) {
+ return formatResetTime(meter.periodEndsAt, {
+ ...options,
+ label: "Billing period ends",
+ });
+ }
+ return "Resets when your billing period ends";
+}
+
export function formatUsdAmount(amount: number): string {
return Number.isInteger(amount) ? `$${amount}` : `$${amount.toFixed(2)}`;
}
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 35f6d00444e4..ba0a7ac679bf 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -914,6 +914,17 @@ export interface UsageViewedProperties {
sustained_used_percent: number | null;
/** Daily bucket percent (0-100), null when usage is unavailable. */
burst_used_percent: number | null;
+ /** Which meter the page rendered: org dollars, the valve bucket, or nothing. */
+ meter_kind: "dollars" | "bucket" | "hidden";
+ /** The dollar figure the meter rendered, null when it rendered no dollars. */
+ org_used_usd: number | null;
+ /** The org limit the figure is measured against, null when no dollars render. */
+ org_limit_usd: number | null;
+ /**
+ * The viewer's own 30-day spend, null when it has not loaded. Read against
+ * `org_used_usd` to see the two figures disagree.
+ */
+ personal_spend_30d_usd: number | null;
}
export interface SpendAnalysisTaskOpenedProperties {
diff --git a/products/desktop/packages/ui/src/features/billing/UsageButton.tsx b/products/desktop/packages/ui/src/features/billing/UsageButton.tsx
index 425566e1b056..b22222968e37 100644
--- a/products/desktop/packages/ui/src/features/billing/UsageButton.tsx
+++ b/products/desktop/packages/ui/src/features/billing/UsageButton.tsx
@@ -1,6 +1,7 @@
import { Circle } from "@phosphor-icons/react";
import {
- formatResetTime,
+ codeUsageResetLabel,
+ codeUsageWindowSuffix,
formatUsageBreakdown,
formatUsdAmount,
} from "@posthog/core/billing/usageDisplay";
@@ -65,14 +66,14 @@ export function UsageButton() {
: meter.kind === "dollars"
? `Usage: ${formatUsdAmount(meter.usedUsd)}`
: `Usage: ${percent}%`;
- const amountLabel =
+ const usedLabel =
meter.kind === "dollars"
? `${formatUsdAmount(meter.usedUsd)} of ${formatUsdAmount(meter.limitUsd)} used`
: `${percent}% used`;
- const resetLabel =
- meter.kind === "dollars"
- ? formatResetTime(meter.resetAt, { label: "Billing period ends" })
- : formatResetTime(meter.bucket.reset_at);
+ // The window belongs next to the amount: on its own the figure reads as
+ // today's spend.
+ const amountLabel = `${usedLabel} ${codeUsageWindowSuffix(meter)}`;
+ const resetLabel = codeUsageResetLabel(meter);
const breakdownLabel =
meter.kind === "dollars" && meter.breakdown
? formatUsageBreakdown(meter.breakdown)
diff --git a/products/desktop/packages/ui/src/features/billing/useSpendTotals.ts b/products/desktop/packages/ui/src/features/billing/useSpendTotals.ts
index d04561d1ac2a..a2ad613b2bf8 100644
--- a/products/desktop/packages/ui/src/features/billing/useSpendTotals.ts
+++ b/products/desktop/packages/ui/src/features/billing/useSpendTotals.ts
@@ -50,11 +50,22 @@ function fetchSpendWindow(
});
}
+export interface SpendTotalsState {
+ totals: SpendSnapshot | null;
+ /** True while the first read is in flight, so a surface can tell waiting from unavailable. */
+ isLoading: boolean;
+}
+
/**
* Today's and this month's personal spend in this app, or null while the
* data hasn't loaded (or the endpoint is unavailable).
*/
export function useSpendTotals(): SpendSnapshot | null {
+ return useSpendTotalsState().totals;
+}
+
+/** The same totals, with the loading flag a rendering surface needs. */
+export function useSpendTotalsState(): SpendTotalsState {
const client = useOptionalAuthenticatedClient();
const query = useQuery({
queryKey: SPEND_TOTALS_QUERY_KEY,
@@ -71,11 +82,14 @@ export function useSpendTotals(): SpendSnapshot | null {
meta: AUTH_SCOPED_QUERY_META,
});
const days = query.data?.by_day?.items;
- return useMemo(() => {
+ const totals = useMemo(() => {
if (!days) return null;
return {
...spendTotalsFromDays(days, utcDayIso()),
avgDailyUsd: averageDailySpend(days, WINDOW_DAYS),
};
}, [days]);
+ // A query disabled before auth is not idle, it is waiting: react-query
+ // reports isLoading false there, which would read as "unavailable".
+ return { totals, isLoading: client === null || query.isLoading };
}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.stories.tsx b/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.stories.tsx
index ee7980ccb216..9981b354dc36 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.stories.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.stories.tsx
@@ -47,6 +47,8 @@ const meta: Meta<typeof PlanUsageContent> = {
billingUrl: "https://app.posthog.com/organization/billing",
usage,
usageLoading: false,
+ spendTotals: { todayUsd: 3.42, monthUsd: 41.18, avgDailyUsd: 1.37 },
+ spendTotalsLoading: false,
},
};
@@ -97,5 +99,26 @@ export const OrganizationLimitReached: Story = {
};
export const Loading: Story = {
- args: { usage: null, usageLoading: true },
+ args: {
+ usage: null,
+ usageLoading: true,
+ spendTotals: null,
+ spendTotalsLoading: true,
+ },
+};
+
+export const BillingPeriodEndUnknown: Story = {
+ args: {
+ usage: { ...usage, billing_period_end: null },
+ },
+};
+
+export const FreeTierValveBucket: Story = {
+ args: {
+ usage: {
+ ...usage,
+ code_usage_subscribed: false,
+ ai_credits: { exhausted: false, used_usd: null, limit_usd: null },
+ },
+ },
};
diff --git a/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.tsx
index 8ce7179aa4d0..ec44ba9f5933 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.tsx
@@ -6,8 +6,9 @@ import {
} from "@phosphor-icons/react";
import {
codeUsageMeter,
+ codeUsageResetLabel,
+ codeUsageWindowLabel,
desktopUsageComponents,
- formatResetTime,
formatUsageQuantity,
formatUsdAmount,
isCodeUsageFreeTier,
@@ -17,9 +18,14 @@ import { BILLING_FLAG, CLOUD_COMPUTE_BILLING_FLAG } from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
import { UsageMeter } from "@posthog/ui/features/billing/UsageMeter";
+import {
+ type SpendSnapshot,
+ useSpendTotalsState,
+} from "@posthog/ui/features/billing/useSpendTotals";
import { useUsage } from "@posthog/ui/features/billing/useUsage";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { SettingsSubsection } from "@posthog/ui/features/settings/components/SettingsSubsection";
+import { PersonalSpendTotals } from "@posthog/ui/features/usage/components/PersonalSpendTotals";
import { SpendAnalysisSection } from "@posthog/ui/features/usage/components/SpendAnalysisSection";
import { useTrackUsageViewed } from "@posthog/ui/features/usage/useTrackUsageViewed";
import { LoadingState } from "@posthog/ui/primitives/LoadingState";
@@ -39,6 +45,8 @@ export function PlanUsageSettings() {
isLoading: usageLoading,
refetch: refetchUsage,
} = useUsage({ enabled: billingEnabled });
+ const { totals: spendTotals, isLoading: spendTotalsLoading } =
+ useSpendTotalsState();
useEffect(() => {
// refetchUsage is a refresh mutation, so it bypasses useUsage's `enabled`
@@ -46,10 +54,16 @@ export function PlanUsageSettings() {
if (billingEnabled) void refetchUsage();
}, [refetchUsage, billingEnabled]);
+ const meter = codeUsageMeter(usage);
useTrackUsageViewed({
isLoading: billingEnabled && usageLoading,
+ spendTotalsLoading,
sustainedUsedPercent: usage?.sustained.used_percent ?? null,
burstUsedPercent: usage?.burst.used_percent ?? null,
+ meterKind: meter.kind,
+ orgUsedUsd: meter.kind === "dollars" ? meter.usedUsd : null,
+ orgLimitUsd: meter.kind === "dollars" ? meter.limitUsd : null,
+ personalSpend30dUsd: spendTotals?.monthUsd ?? null,
});
return (
@@ -59,6 +73,8 @@ export function PlanUsageSettings() {
billingUrl={billingUrl}
usage={usage}
usageLoading={usageLoading}
+ spendTotals={spendTotals}
+ spendTotalsLoading={spendTotalsLoading}
personalSpendAnalysis={<SpendAnalysisSection />}
/>
);
@@ -70,6 +86,8 @@ interface PlanUsageContentProps {
billingUrl: string | null | undefined;
usage: UsageOutput | null | undefined;
usageLoading: boolean;
+ spendTotals: SpendSnapshot | null;
+ spendTotalsLoading: boolean;
personalSpendAnalysis?: ReactNode;
}
@@ -79,6 +97,8 @@ export function PlanUsageContent({
billingUrl,
usage,
usageLoading,
+ spendTotals,
+ spendTotalsLoading,
personalSpendAnalysis,
}: PlanUsageContentProps) {
const freeTier = isCodeUsageFreeTier(usage);
@@ -148,10 +168,10 @@ export function PlanUsageContent({
<LoadingState className="rounded-(--radius-3) border border-border bg-card p-4" />
) : meter.kind === "dollars" ? (
<UsageMeter
- label={freeTier ? "Monthly free usage" : "Usage this period"}
+ label={codeUsageWindowLabel(meter, freeTier)}
percent={meter.percent}
valueLabel={`${formatUsdAmount(meter.usedUsd)} of ${formatUsdAmount(meter.limitUsd)}${freeTier ? " included" : ""}`}
- detail={`${meter.exceeded ? "Limit exceeded. " : ""}${formatResetTime(meter.resetAt, { label: "Billing period ends" })}`}
+ detail={`${meter.exceeded ? "Limit exceeded. " : ""}${codeUsageResetLabel(meter)}`}
breakdown={
meter.breakdown
? { ...meter.breakdown, usedUsd: meter.usedUsd }
@@ -161,10 +181,10 @@ export function PlanUsageContent({
/>
) : meter.kind === "bucket" ? (
<UsageMeter
- label="Monthly free usage"
+ label={codeUsageWindowLabel(meter, freeTier)}
percent={meter.bucket.used_percent}
valueLabel={`${meter.bucket.used_percent.toFixed(2)}%`}
- detail={`${meter.bucket.exceeded ? "Limit exceeded. " : ""}${formatResetTime(meter.bucket.reset_at)}`}
+ detail={`${meter.bucket.exceeded ? "Limit exceeded. " : ""}${codeUsageResetLabel(meter)}`}
color={meter.bucket.exceeded ? "red" : undefined}
/>
) : (
@@ -199,14 +219,22 @@ export function PlanUsageContent({
<UsageMix components={components} />
)}
<Text className="text-[12px] text-muted-foreground">
- Usage reporting may be delayed by 15–20 minutes.
+ {meter.kind === "dollars"
+ ? "This total comes from billing, so it can lag by 15 to 20 minutes. "
+ : ""}
+ Your own spend below is near real time.
</Text>
</Flex>
)}
</SettingsSubsection>
)}
- <PersonalSpendDisclosure>{personalSpendAnalysis}</PersonalSpendDisclosure>
+ <PersonalSpendDisclosure
+ totals={spendTotals}
+ totalsLoading={spendTotalsLoading}
+ >
+ {personalSpendAnalysis}
+ </PersonalSpendDisclosure>
</Flex>
);
}
@@ -274,8 +302,17 @@ function UsageMix({
);
}
-function PersonalSpendDisclosure({ children }: { children: ReactNode }) {
- // Collapsed by default so opening the page doesn't fire the spend query.
+function PersonalSpendDisclosure({
+ totals,
+ totalsLoading,
+ children,
+}: {
+ totals: SpendSnapshot | null;
+ totalsLoading: boolean;
+ children: ReactNode;
+}) {
+ // The totals above read the window the guardrails already poll, so only the
+ // charts and breakdowns wait for the disclosure.
const [expanded, setExpanded] = useState(false);
return (
@@ -289,11 +326,12 @@ function PersonalSpendDisclosure({ children }: { children: ReactNode }) {
aria-expanded={expanded}
onClick={() => setExpanded((value) => !value)}
>
- {expanded ? "Hide" : "Show"}
+ {expanded ? "Hide details" : "Show details"}
{expanded ? <CaretUp size={12} /> : <CaretDown size={12} />}
</Button>
}
>
+ <PersonalSpendTotals totals={totals} isLoading={totalsLoading} />
{expanded ? children : null}
</SettingsSubsection>
);
diff --git a/products/desktop/packages/ui/src/features/usage/components/PersonalSpendTotals.tsx b/products/desktop/packages/ui/src/features/usage/components/PersonalSpendTotals.tsx
new file mode 100644
index 000000000000..60254f8fd023
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/usage/components/PersonalSpendTotals.tsx
@@ -0,0 +1,61 @@
+import { formatUsd } from "@posthog/core/billing/spendAnalysisFormat";
+import { Text } from "@posthog/quill";
+import { MetricCard, useChartTheme } from "@posthog/quill-charts";
+import type { SpendSnapshot } from "@posthog/ui/features/billing/useSpendTotals";
+import { LoadingState } from "@posthog/ui/primitives/LoadingState";
+
+interface PersonalSpendTotalsProps {
+ totals: SpendSnapshot | null;
+ isLoading: boolean;
+}
+
+/**
+ * Your own spend, on the page without opening the detail section, so the
+ * organization meter above always has a near-real-time figure beside it.
+ */
+export function PersonalSpendTotals({
+ totals,
+ isLoading,
+}: PersonalSpendTotalsProps) {
+ const theme = useChartTheme();
+
+ if (isLoading) {
+ return (
+ <LoadingState className="rounded-(--radius-3) border border-border bg-card p-4" />
+ );
+ }
+
+ if (!totals) {
+ return (
+ <div className="rounded-(--radius-3) border border-border bg-card p-4">
+ <Text className="text-muted-foreground text-xs">
+ Couldn't load your spend. In the details below, select 30 days, then
+ Refresh to try again.
+ </Text>
+ </div>
+ );
+ }
+
+ return (
+ <div className="grid grid-cols-2 gap-px overflow-hidden rounded-(--radius-3) border border-(--gray-5) bg-(--gray-5)">
+ <div className="min-w-0 bg-(--color-panel-solid) px-4 py-3">
+ <MetricCard
+ title={<span className="text-[12px] text-gray-11">Today</span>}
+ value={Math.max(0, totals.todayUsd)}
+ theme={theme}
+ formatValue={formatUsd}
+ change={null}
+ />
+ </div>
+ <div className="min-w-0 bg-(--color-panel-solid) px-4 py-3">
+ <MetricCard
+ title={<span className="text-[12px] text-gray-11">Last 30 days</span>}
+ value={Math.max(0, totals.monthUsd)}
+ theme={theme}
+ formatValue={formatUsd}
+ change={null}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/usage/useTrackUsageViewed.test.tsx b/products/desktop/packages/ui/src/features/usage/useTrackUsageViewed.test.tsx
new file mode 100644
index 000000000000..d1e4ef6d91e6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/usage/useTrackUsageViewed.test.tsx
@@ -0,0 +1,76 @@
+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import { renderHook } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+const trackMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@posthog/ui/shell/analytics", () => ({ track: trackMock }));
+
+import {
+ type TrackUsageViewedInput,
+ useTrackUsageViewed,
+} from "./useTrackUsageViewed";
+
+const input = (
+ overrides: Partial<TrackUsageViewedInput> = {},
+): TrackUsageViewedInput => ({
+ isLoading: false,
+ spendTotalsLoading: false,
+ sustainedUsedPercent: 0,
+ burstUsedPercent: 0,
+ meterKind: "dollars",
+ orgUsedUsd: 12.4,
+ orgLimitUsd: 70,
+ personalSpend30dUsd: 41.18,
+ ...overrides,
+});
+
+describe("useTrackUsageViewed", () => {
+ it("carries the rendered dollars, so a figure that disagrees with personal spend is measurable", () => {
+ trackMock.mockClear();
+ renderHook(() => useTrackUsageViewed(input()));
+
+ expect(trackMock).toHaveBeenCalledWith(
+ ANALYTICS_EVENTS.USAGE_VIEWED,
+ expect.objectContaining({
+ meter_kind: "dollars",
+ org_used_usd: 12.4,
+ org_limit_usd: 70,
+ personal_spend_30d_usd: 41.18,
+ }),
+ );
+ });
+
+ it.each([41.18, 0, null])(
+ "waits for usage and personal spend to settle at %s, then fires once",
+ (personalSpend30dUsd) => {
+ trackMock.mockClear();
+ const { rerender } = renderHook(
+ (props: TrackUsageViewedInput) => useTrackUsageViewed(props),
+ {
+ initialProps: input({
+ isLoading: true,
+ spendTotalsLoading: true,
+ orgUsedUsd: null,
+ personalSpend30dUsd: null,
+ }),
+ },
+ );
+ expect(trackMock).not.toHaveBeenCalled();
+
+ rerender(input({ spendTotalsLoading: true, personalSpend30dUsd: null }));
+ expect(trackMock).not.toHaveBeenCalled();
+
+ rerender(input({ personalSpend30dUsd }));
+ rerender(input({ orgUsedUsd: 13.9 }));
+ expect(trackMock).toHaveBeenCalledTimes(1);
+ expect(trackMock).toHaveBeenCalledWith(
+ ANALYTICS_EVENTS.USAGE_VIEWED,
+ expect.objectContaining({
+ org_used_usd: 12.4,
+ personal_spend_30d_usd: personalSpend30dUsd,
+ }),
+ );
+ },
+ );
+});
diff --git a/products/desktop/packages/ui/src/features/usage/useTrackUsageViewed.ts b/products/desktop/packages/ui/src/features/usage/useTrackUsageViewed.ts
index b299cd5c974d..6c492aa758e5 100644
--- a/products/desktop/packages/ui/src/features/usage/useTrackUsageViewed.ts
+++ b/products/desktop/packages/ui/src/features/usage/useTrackUsageViewed.ts
@@ -1,25 +1,55 @@
-import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import {
+ ANALYTICS_EVENTS,
+ type UsageViewedProperties,
+} from "@posthog/shared/analytics-events";
import { track } from "@posthog/ui/shell/analytics";
import { useEffect, useRef } from "react";
export interface TrackUsageViewedInput {
isLoading: boolean;
+ spendTotalsLoading: boolean;
sustainedUsedPercent: number | null;
burstUsedPercent: number | null;
+ meterKind: UsageViewedProperties["meter_kind"];
+ orgUsedUsd: number | null;
+ orgLimitUsd: number | null;
+ personalSpend30dUsd: number | null;
}
export function useTrackUsageViewed(input: TrackUsageViewedInput): void {
- const { isLoading, sustainedUsedPercent, burstUsedPercent } = input;
+ const {
+ isLoading,
+ spendTotalsLoading,
+ sustainedUsedPercent,
+ burstUsedPercent,
+ meterKind,
+ orgUsedUsd,
+ orgLimitUsd,
+ personalSpend30dUsd,
+ } = input;
const firedRef = useRef(false);
useEffect(() => {
if (firedRef.current) return;
// Wait for data to settle so the once-only event doesn't lock in defaults.
- if (isLoading) return;
+ if (isLoading || spendTotalsLoading) return;
firedRef.current = true;
track(ANALYTICS_EVENTS.USAGE_VIEWED, {
sustained_used_percent: sustainedUsedPercent,
burst_used_percent: burstUsedPercent,
+ meter_kind: meterKind,
+ org_used_usd: orgUsedUsd,
+ org_limit_usd: orgLimitUsd,
+ personal_spend_30d_usd: personalSpend30dUsd,
});
- }, [isLoading, sustainedUsedPercent, burstUsedPercent]);
+ }, [
+ isLoading,
+ spendTotalsLoading,
+ sustainedUsedPercent,
+ burstUsedPercent,
+ meterKind,
+ orgUsedUsd,
+ orgLimitUsd,
+ personalSpend30dUsd,
+ ]);
}