: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): improve plan and usage insights (#79172)
Matt Puaf6a04f66fc36
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsxindex c0cc5547e1a3..2fea19e94008 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx@@ -64,6 +64,7 @@ import { Text } from "@radix-ui/themes";import { Link } from "@tanstack/react-router";import {memo,+ type ReactElement,type ReactNode,useCallback,useEffect,@@ -758,7 +759,7 @@ export function ChannelFeedView({/** Rendered pinned above the first entry — the Slack-style channel intro* (name, creation line, onboarding card). When set, the feed renders even* with no entries instead of falling back to `emptyState`. */- intro?: ReactNode;+ intro?: ReactElement;onOpenTask: (task: Task) => void;onOpenThread: (task: Task) => void;}) {@@ -826,7 +827,7 @@ export function ChannelFeedView({bottom padding clears the composer's floating workspace-modeselector, which hangs over the end of the feed. */}<ChatMessageScrollerContent className="mx-auto w-full gap-0 pt-4 pb-10">- {intro}+ {intro as never}{entries.map((entry) =>entry.kind === "task" ? (<FeedRowdiff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsxindex 877d062fc4bf..0552dff4b863 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx@@ -992,7 +992,7 @@ function ThreadScrollBody({rows: TurnRow[];renderItem: (item: ConversationItem) => ReactNode;/** Status row (duration / diff stats) pinned as the last item in the thread. */- footer?: ReactNode;+ footer?: ReactElement;keyboardFocusedMessageId?: string | null;/** Clears keyboard-focused message state on any pointer interaction with the thread. */onUserInteract?: () => void;diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsxindex ec0ad4500a1a..a994ae4961f5 100644--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx@@ -47,7 +47,11 @@ function defineSettingsPage(const SETTINGS_PAGES: Record<SettingsCategory, SettingsPageDefinition> = {general: defineSettingsPage("General", GeneralSettings),notifications: defineSettingsPage("Notifications", NotificationsSettings),- "plan-usage": defineSettingsPage("Plan & usage", PlanUsageSettings),+ "plan-usage": defineSettingsPage(+ "Plan & usage",+ PlanUsageSettings,+ SETTINGS_PAGE_LAYOUT.FULL_BLEED,+ ),workspaces: defineSettingsPage("Workspaces", WorkspacesSettings),worktrees: defineSettingsPage("Worktrees", WorktreesSettings),environments: defineSettingsPage("Environments", EnvironmentsSettings),diff --git a/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.tsxindex d7d74d22dd30..25cd0211dfed 100644--- a/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/PlanUsageSettings.tsx@@ -27,7 +27,16 @@ import { useSpendAnalysisEnabled } from "@posthog/ui/features/usage/useSpendAnalimport { useTrackUsageViewed } from "@posthog/ui/features/usage/useTrackUsageViewed";import { track } from "@posthog/ui/shell/analytics";import { getBillingUrl } from "@posthog/ui/utils/urls";-import { Badge, Button, Callout, Flex, Spinner, Text } from "@radix-ui/themes";+import {+ Badge,+ Box,+ Button,+ Callout,+ Flex,+ ScrollArea,+ Spinner,+ Text,+} from "@radix-ui/themes";import { useEffect } from "react";export function PlanUsageSettings() {@@ -82,144 +91,150 @@ export function PlanUsageSettings() {}return (- <Flex direction="column" gap="5">- {billingEnabled && (- <>- {orgLimitReached && (- <Callout.Root color="red" size="1">- <Callout.Icon>- <WarningCircle size={16} />- </Callout.Icon>- <Callout.Text>- <Flex direction="column" gap="2">- <Text className="text-sm">- Your organization has reached its usage limit for this- billing period.- </Text>- <Button- size="1"- variant="outline"- color="red"- disabled={!billingUrl}- onClick={openBilling}- className="self-start"- >- Manage billing- <ArrowSquareOut size={12} />- </Button>- </Flex>- </Callout.Text>- </Callout.Root>- )}-- <Flex- direction="column"- gap="3"- p="4"- className="rounded-(--radius-3) border border-(--gray-5)"- >- <Flex align="center" justify="between">- <Flex direction="column" gap="1">- <Text className="font-bold text-base">- {freeTier ? "Free tier" : "Usage-based billing"}- </Text>- <Text className="text-(--gray-11) text-sm">- {freeTier- ? "Your organization's first $20 of usage each month is included, with access to open models. Add a payment method to unlock premium models — you only pay for what you use."- : "Your organization pays for usage at cost — no seats, no subscriptions. The first $20 each month is included."}- </Text>- </Flex>- {subscribed && (- <Badge variant="soft" color="green" radius="full">- Active- </Badge>+ <ScrollArea className="h-full w-full">+ <Box p="6" className="relative z-[1]">+ <Flex direction="column" gap="5">+ {billingEnabled && (+ <>+ {orgLimitReached && (+ <Callout.Root color="red" size="1">+ <Callout.Icon>+ <WarningCircle size={16} />+ </Callout.Icon>+ <Callout.Text>+ <Flex direction="column" gap="2">+ <Text className="text-sm">+ Your organization has reached its usage limit for this+ billing period.+ </Text>+ <Button+ size="1"+ variant="outline"+ color="red"+ disabled={!billingUrl}+ onClick={openBilling}+ className="self-start"+ >+ Manage billing+ <ArrowSquareOut size={12} />+ </Button>+ </Flex>+ </Callout.Text>+ </Callout.Root>)}- </Flex>- <Button- size="1"- variant={freeTier ? "solid" : "outline"}- disabled={!billingUrl}- onClick={() => {- if (freeTier) {- track(ANALYTICS_EVENTS.UPGRADE_PROMPT_CLICKED, {- surface: "plan_page_card",- });- }- openBilling();- }}- className="self-start"- >- {freeTier- ? "Add payment method"- : "Manage billing and spend limits"}- <ArrowSquareOut size={12} />- </Button>- </Flex>- <Flex direction="column" gap="3">- <Text className="font-medium text-(--gray-9) text-sm">- Organization usage- </Text>- {usageLoading ? (<Flex- align="center"- justify="center"+ direction="column"+ gap="3"p="4"className="rounded-(--radius-3) border border-(--gray-5)">- <Spinner size="2" />+ <Flex align="center" justify="between">+ <Flex direction="column" gap="1">+ <Text className="font-bold text-base">+ {freeTier ? "Free tier" : "Usage-based billing"}+ </Text>+ <Text className="text-(--gray-11) text-sm">+ {freeTier+ ? "Your organization's first $20 of usage each month is included, with access to open models. Add a payment method to unlock premium models — you only pay for what you use."+ : "Your organization pays for usage at cost — no seats, no subscriptions. The first $20 each month is included."}+ </Text>+ </Flex>+ {subscribed && (+ <Badge variant="soft" color="green" radius="full">+ Active+ </Badge>+ )}+ </Flex>+ <Button+ size="1"+ variant={freeTier ? "solid" : "outline"}+ disabled={!billingUrl}+ onClick={() => {+ if (freeTier) {+ track(ANALYTICS_EVENTS.UPGRADE_PROMPT_CLICKED, {+ surface: "plan_page_card",+ });+ }+ openBilling();+ }}+ className="self-start"+ >+ {freeTier+ ? "Add payment method"+ : "Manage billing and spend limits"}+ <ArrowSquareOut size={12} />+ </Button></Flex>- ) : meter.kind === "dollars" ? (- <UsageMeter- label={freeTier ? "Monthly free usage" : "Usage this period"}- 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" })}`}- breakdown={- meter.breakdown- ? { ...meter.breakdown, usedUsd: meter.usedUsd }- : undefined- }- color={meter.exceeded ? "red" : undefined}- />- ) : meter.kind === "bucket" ? (- <UsageMeter- label="Monthly free usage"- percent={meter.bucket.used_percent}- valueLabel={`${meter.bucket.used_percent.toFixed(2)}%`}- detail={`${meter.bucket.exceeded ? "Limit exceeded. " : ""}${formatResetTime(meter.bucket.reset_at)}`}- color={meter.bucket.exceeded ? "red" : undefined}- />- ) : (- <Flex- align="center"- justify="between"- p="4"- className="rounded-(--radius-3) border border-(--gray-5)"- >- <Text color="gray" className="text-sm">- {usage- ? "Usage is billed to your organization. View detailed usage and spend in PostHog."- : "Unable to load usage data"}++ <Flex direction="column" gap="3">+ <Text className="font-medium text-(--gray-9) text-sm">+ Organization usage</Text>- {usage && (- <Button- size="1"- variant="outline"- disabled={!billingUrl}- onClick={openBilling}+ {usageLoading ? (+ <Flex+ align="center"+ justify="center"+ p="4"+ className="rounded-(--radius-3) border border-(--gray-5)">- View usage- <ArrowSquareOut size={12} />- </Button>+ <Spinner size="2" />+ </Flex>+ ) : meter.kind === "dollars" ? (+ <UsageMeter+ label={+ freeTier ? "Monthly free usage" : "Usage this period"+ }+ 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" })}`}+ breakdown={+ meter.breakdown+ ? { ...meter.breakdown, usedUsd: meter.usedUsd }+ : undefined+ }+ color={meter.exceeded ? "red" : undefined}+ />+ ) : meter.kind === "bucket" ? (+ <UsageMeter+ label="Monthly free usage"+ percent={meter.bucket.used_percent}+ valueLabel={`${meter.bucket.used_percent.toFixed(2)}%`}+ detail={`${meter.bucket.exceeded ? "Limit exceeded. " : ""}${formatResetTime(meter.bucket.reset_at)}`}+ color={meter.bucket.exceeded ? "red" : undefined}+ />+ ) : (+ <Flex+ align="center"+ justify="between"+ p="4"+ className="rounded-(--radius-3) border border-(--gray-5)"+ >+ <Text color="gray" className="text-sm">+ {usage+ ? "Usage is billed to your organization. View detailed usage and spend in PostHog."+ : "Unable to load usage data"}+ </Text>+ {usage && (+ <Button+ size="1"+ variant="outline"+ disabled={!billingUrl}+ onClick={openBilling}+ >+ View usage+ <ArrowSquareOut size={12} />+ </Button>+ )}+ </Flex>)}</Flex>- )}- </Flex>- </>- )}+ </>+ )}- {spendAnalysisEnabled && <SpendAnalysisSection />}- </Flex>+ {spendAnalysisEnabled && <SpendAnalysisSection />}+ </Flex>+ </Box>+ </ScrollArea>);}diff --git a/products/desktop/packages/ui/src/features/usage/components/ModelBreakdownCards.tsx b/products/desktop/packages/ui/src/features/usage/components/ModelBreakdownCards.tsxindex 9b03a9906ff3..023bb17808c2 100644--- a/products/desktop/packages/ui/src/features/usage/components/ModelBreakdownCards.tsx+++ b/products/desktop/packages/ui/src/features/usage/components/ModelBreakdownCards.tsx@@ -4,15 +4,56 @@ import {formatUsd,} from "@posthog/core/billing/spendAnalysisFormat";import type { SpendAnalysisModelRow } from "@posthog/core/billing/spendAnalysisTypes";-import { Flex, Text } from "@radix-ui/themes";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Text,+} from "@posthog/quill";+import type { ReactElement } from "react";+import { useState } from "react";import { UsageCard } from "./UsageCard";-function ModelStat({ label, value }: { label: string; value: string }) {+export type ModelBreakdownSort = "cost" | "tokens";++export function sortModelBreakdownRows(+ rows: SpendAnalysisModelRow[],+ sortBy: ModelBreakdownSort,+): SpendAnalysisModelRow[] {+ return [...rows].sort((first, second) => {+ const firstValue =+ sortBy === "cost"+ ? first.cost_usd+ : first.input_tokens + first.output_tokens;+ const secondValue =+ sortBy === "cost"+ ? second.cost_usd+ : second.input_tokens + second.output_tokens;++ if (firstValue !== secondValue) return secondValue - firstValue;+ if (first.cost_usd !== second.cost_usd)+ return second.cost_usd - first.cost_usd;++ return (first.model ?? "").localeCompare(second.model ?? "");+ });+}++function ModelStat({+ label,+ value,+}: {+ label: string;+ value: string;+}): ReactElement {return (- <Flex align="center" justify="between">- <Text className="text-(--gray-9) text-[12px]">{label}</Text>- <Text className="text-[12px]">{value}</Text>- </Flex>+ <div className="flex items-center justify-between">+ <Text size="xs" variant="muted">+ {label}+ </Text>+ <Text size="xs">{value}</Text>+ </div>);}@@ -24,37 +65,70 @@ interface ModelBreakdownCardsProps {export function ModelBreakdownCards({rows,scopedCostUsd,-}: ModelBreakdownCardsProps) {+}: ModelBreakdownCardsProps): ReactElement | null {+ const [sortBy, setSortBy] = useState<ModelBreakdownSort>("cost");+if (rows.length === 0) return null;++ const sortedRows = sortModelBreakdownRows(rows, sortBy);+return (<UsageCardicon={<Robot size={14} className="text-(--gray-9)" />}title="Cost by model"+ actions={+ <div className="flex items-center gap-2">+ <Text size="xs" variant="muted">+ Sort by+ </Text>+ <Select+ value={sortBy}+ onValueChange={(value: ModelBreakdownSort | null) => {+ if (value) setSortBy(value);+ }}+ >+ <SelectTrigger size="sm" aria-label="Sort models">+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end" side="bottom" sideOffset={6}>+ <SelectItem value="cost">Cost</SelectItem>+ <SelectItem value="tokens">Total tokens</SelectItem>+ </SelectContent>+ </Select>+ </div>+ }>- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">- {rows.map((row) => {+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">+ {sortedRows.map((row) => {const share =scopedCostUsd > 0? Math.round((row.cost_usd / scopedCostUsd) * 100): 0;return (- <Flex+ <divkey={row.model ?? "(unknown)"}- direction="column"- gap="2"- p="3"- className="rounded-(--radius-2) border border-(--gray-5) bg-(--gray-2)"+ className="flex flex-col gap-2 rounded-(--radius-2) border border-(--gray-5) bg-(--gray-2) p-3">- <Flex align="center" gap="2">- <Text className="truncate font-medium text-sm">+ <div className="flex items-center gap-2">+ <Text size="sm" weight="medium" className="truncate">{row.model ?? "(unknown)"}</Text>- <Flex flexGrow="1" />- <Text className="font-semibold text-(--accent-11) text-sm">+ <div className="flex-1" />+ <Text+ size="sm"+ weight="semibold"+ className="text-(--accent-11)"+ >{formatUsd(row.cost_usd)}</Text>- </Flex>+ </div><div className="grid grid-cols-2 gap-x-4 gap-y-1">+ <div className="col-span-2">+ <ModelStat+ label="Total tokens"+ value={formatTokens(row.input_tokens + row.output_tokens)}+ />+ </div><ModelStatlabel="Input"value={formatTokens(row.input_tokens)}@@ -69,7 +143,7 @@ export function ModelBreakdownCards({/><ModelStat label="Share" value={`${share}%`} /></div>- </Flex>+ </div>);})}</div>diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.ts b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.tsnew file mode 100644index 000000000000..e553bb69fb2a--- /dev/null+++ b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.ts@@ -0,0 +1,25 @@+import type { SpendAnalysisFilledDay } from "@posthog/core/billing/spendAnalysisFormat";+import { describe, expect, it, vi } from "vitest";++vi.mock("@posthog/quill-charts", () => ({+ DefaultTooltip: () => null,+ TimeSeriesComboChart: () => null,+ useChartTheme: () => ({}),+}));++import { spendSeriesForDays } from "./SpendOverTimeCard";++describe("spendSeriesForDays", () => {+ it("keeps daily spend separate from the cumulative total", () => {+ const days: SpendAnalysisFilledDay[] = [+ { day: "2026-08-01", cost_usd: 1.25, event_count: 1 },+ { day: "2026-08-02", cost_usd: -0.5, event_count: 2 },+ { day: "2026-08-03", cost_usd: 2.75, event_count: 3 },+ ];++ expect(spendSeriesForDays(days)).toMatchObject([+ { key: "daily-spend", type: "bar", data: [1.25, 0, 2.75] },+ { key: "cumulative-spend", type: "line", data: [1.25, 1.25, 4] },+ ]);+ });+});diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsxindex 8354c41efd1d..9098252cf3a8 100644--- a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx+++ b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx@@ -4,49 +4,78 @@ import {type SpendAnalysisFilledDay,} from "@posthog/core/billing/spendAnalysisFormat";import {+ DefaultTooltip,type Series,- TimeSeriesBarChart,+ TimeSeriesComboChart,+ type TimeSeriesComboChartConfig,useChartTheme,} from "@posthog/quill-charts";import { UsageCard } from "./UsageCard";-const VALUE_LABEL_MAX_BARS = 31;-interface SpendOverTimeCardProps {filledDays: SpendAnalysisFilledDay[];}-export function SpendOverTimeCard({ filledDays }: SpendOverTimeCardProps) {- const theme = useChartTheme();- const series: Series[] = [+export function spendSeriesForDays(+ filledDays: SpendAnalysisFilledDay[],+): Series[] {+ let cumulativeSpend = 0;+ const dailySpend = filledDays.map((day) => Math.max(0, day.cost_usd));++ return [+ {+ key: "daily-spend",+ label: "Daily spend",+ data: dailySpend,+ type: "bar",+ yAxisId: "daily",+ },{- key: "cost",- label: "Cost (USD)",- data: filledDays.map((d) => Math.max(0, d.cost_usd)),+ key: "cumulative-spend",+ label: "Cumulative spend",+ data: dailySpend.map((cost) => {+ cumulativeSpend += cost;+ return cumulativeSpend;+ }),+ type: "line",+ yAxisId: "cumulative",+ points: { radius: 3 },},];- const showValueLabels = filledDays.length <= VALUE_LABEL_MAX_BARS;+}++export function SpendOverTimeCard({ filledDays }: SpendOverTimeCardProps) {+ const theme = useChartTheme();+ const series = spendSeriesForDays(filledDays);+return (<UsageCardicon={<ChartBar size={14} className="text-(--accent-9)" />}- title="Cost over time"+ title="Daily spend and total">- {/* flex-col + fixed height: the quill chart sizes its canvas by filling- a flex-column parent; a plain block collapses it to 0. */}<div className="flex h-56 w-full flex-col">- <TimeSeriesBarChart+ <TimeSeriesComboChartseries={series}labels={filledDays.map((d) => d.day)}config={{xAxis: { timezone: "UTC", interval: "day" },- yAxis: { tickFormatter: formatUsd },- valueLabels: showValueLabels- ? { formatter: (value) => (value > 0 ? formatUsd(value) : "") }- : false,+ yAxis: [+ { id: "daily", position: "left", tickFormatter: formatUsd },+ {+ id: "cumulative",+ position: "right",+ tickFormatter: formatUsd,+ },+ ] as unknown as TimeSeriesComboChartConfig["yAxis"],+ barLayout: "grouped",barCornerRadius: 2,showCrosshair: true,+ tooltip: { placement: "cursor", showTotal: false },}}theme={theme}+ tooltip={(context) => (+ <DefaultTooltip {...context} valueFormatter={formatUsd} />+ )}/></div></UsageCard>diff --git a/products/desktop/packages/ui/src/features/usage/components/modelBreakdownSort.test.ts b/products/desktop/packages/ui/src/features/usage/components/modelBreakdownSort.test.tsnew file mode 100644index 000000000000..4c96436d2eec--- /dev/null+++ b/products/desktop/packages/ui/src/features/usage/components/modelBreakdownSort.test.ts@@ -0,0 +1,35 @@+import type { SpendAnalysisModelRow } from "@posthog/core/billing/spendAnalysisTypes";+import { describe, expect, it } from "vitest";+import { sortModelBreakdownRows } from "./ModelBreakdownCards";++describe("sortModelBreakdownRows", () => {+ const rows: SpendAnalysisModelRow[] = [+ {+ model: "highest-cost",+ cost_usd: 10,+ input_tokens: 100,+ output_tokens: 50,+ generation_count: 1,+ },+ {+ model: "most-tokens",+ cost_usd: 2,+ input_tokens: 900,+ output_tokens: 100,+ generation_count: 1,+ },+ ];++ it("orders models by the selected metric without changing the input rows", () => {+ expect(+ sortModelBreakdownRows(rows, "cost").map((row) => row.model),+ ).toEqual(["highest-cost", "most-tokens"]);+ expect(+ sortModelBreakdownRows(rows, "tokens").map((row) => row.model),+ ).toEqual(["most-tokens", "highest-cost"]);+ expect(rows.map((row) => row.model)).toEqual([+ "highest-cost",+ "most-tokens",+ ]);+ });+});