: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(mcp-analytics): migrate metric tiles to the composable quill Metric (#70142)
Sam Pennington2c7223895b88
diff --git a/frontend/jest.config.ts b/frontend/jest.config.tsindex 5ccbdff06f80..925be69c3053 100644--- a/frontend/jest.config.ts+++ b/frontend/jest.config.ts@@ -216,6 +216,7 @@ const config: Config = {'^@posthog/quill-charts/testing$': '<rootDir>/../packages/quill/packages/charts/src/testing/index.ts','^@posthog/quill-charts/story-helpers$': '<rootDir>/../packages/quill/packages/charts/src/story-helpers.tsx','^@posthog/quill-components$': '<rootDir>/../packages/quill/packages/components/src/index.ts',+ '^@posthog/quill-components/metric$': '<rootDir>/../packages/quill/packages/components/src/metric.tsx','^@posthog/quill-primitives$': '<rootDir>/../packages/quill/packages/primitives/src/index.ts','^@posthog/quill-tokens$': '<rootDir>/../packages/quill/packages/tokens/src/index.ts','^@posthog/shared-onboarding/(.*)$': '<rootDir>/../docs/onboarding/$1',diff --git a/frontend/package.json b/frontend/package.jsonindex 87db1a506a51..be5ad9f4c4bf 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -133,6 +133,7 @@"@posthog/products-workflows": "workspace:*","@posthog/quill": "workspace:*","@posthog/quill-charts": "workspace:*",+ "@posthog/quill-components": "workspace:*","@posthog/react": "catalog:","@posthog/replay-shared": "workspace:*","@posthog/tailwind": "workspace:*",diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex fe05e76c2196..a676757903ba 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6167,9 +6167,9 @@ snapshots:scenes-app-mcp-analytics--dashboard--light:hash: v1.k794b7964.49f850b518aa783296b3d178c4335a14048651a65980d230e22f2d140176b149.GdW1N70CXyKtRCe88ML3fwlrrHTXrIJ58dXsp7VIN6gscenes-app-mcp-analytics--dashboard-with-menu-bar--dark:- hash: v1.k794b7964.e2c33e0d83a374dcb482a4f87ab282b6970f07b6a2f02d3b401c949d809655a2.pxgapCvTjPi-25Dyd4Jy72NRuWPIjPO_-8Gi6Mxp_zY+ hash: v1.k794b7964.ec3c0249491cc08c6b3e36e6a6f8a237e16a0742a26bec7bf5ec94cc658071e7.ttVOYlABA3PeTBJKCxXvYWlrLij8JlGo50fy0kJSC1Ascenes-app-mcp-analytics--dashboard-with-menu-bar--light:- hash: v1.k794b7964.36ff58ccd3dfdbb5dcf9d4629c4d2f68ab9c2b8fb1ac42d190eaa328d8006df7.N8A44kWdcSNbtQ6AqRwi3fnIEQyGJ1bvVIqzDFi7MG0+ hash: v1.k794b7964.64aa035890ac3ad11d7c4d7a7edcd9fd677462780b05db60c1777ced89c90371.M9V8SQPjfYBEjJfl54ow7GhayKAiOaPoGE-j1ZU3ouIscenes-app-mcp-analytics--intent-clustering--dark:hash: v1.k794b7964.93cb428637db03234a4d0d09b51ef886d95ab801bb3e4dc6ca0f1ba3824b9fe3.JeUzojRsSPumu87KUEx7WXtojxL5GEF98Ps9CVS7WAYscenes-app-mcp-analytics--intent-clustering--light:@@ -6199,9 +6199,9 @@ snapshots:scenes-app-mcp-analytics-dashboard-cards--flagged-sessions--light:hash: v1.k794b7964.594333649b8b6be4e2af262bb606f164e5ed9b72271f7226668af76653013150.BYJ6q_JJ2ZGGSCxOs4SoGDb1E9BNWRk9Yo5lrIFdzW8scenes-app-mcp-analytics-dashboard-cards--key-metrics--dark:- hash: v1.k794b7964.539a2481d273c0043468cca5c575d2b1b597b6a7ebdb985da1692f8a02c9bb43.bFQjFUi7S6EomB8-kxn_lUjRaN4pfI6uzsu4_HnReYg+ hash: v1.k794b7964.c43bf4fc139c60f91e2bbe9f160077ebe7678b23bfbb86cc23ffb7e610cf510a.cYi4muc-vdYm66DM_ooUC9daJDJ7FJlH9dgETasyR68scenes-app-mcp-analytics-dashboard-cards--key-metrics--light:- hash: v1.k794b7964.244789b4b44125b7c6eb278c728ec71a6c14abb7848ed3ef93b594804fc46cdd.LpSM8CA_ZM-w4j5hPzdNf-gWxnPzoKDtvI94CwtEgns+ hash: v1.k794b7964.e44175ae2c238669a74dd8aec65a9a30e46a9bb1f7f75065d9f5a6c95e4d226b.PMsDqcVriwdb3Q7xvz70gU_edbqDUiMp-o5p_vdn7SIscenes-app-mcp-analytics-dashboard-cards--share-by-harness--dark:hash: v1.k794b7964.a4f65ae92d92d3600674689dc61f5ba834aac470154fb26b82821cb17b12cada.vAYLkto1-GBp1WeHETUeB5R0Pljn-RwHDW9h3bib1KQscenes-app-mcp-analytics-dashboard-cards--share-by-harness--light:diff --git a/packages/quill/packages/components/AGENTS.md b/packages/quill/packages/components/AGENTS.mdindex 6e7f77fbb54e..02283b379707 100644--- a/packages/quill/packages/components/AGENTS.md+++ b/packages/quill/packages/components/AGENTS.md@@ -132,10 +132,11 @@ const theme = useChartTheme()Rules:- Wrap `Metric` in `<Card flush>` — `Metric` is just the layout/content (it owns its inline padding like `CardContent`, so the sparkline can bleed out with `-mx-4`); the card owns the border, block padding, and bottom edge. `flush` drops the card's bottom padding so `MetricSparkline` reaches the bottom; a number-only tile can use a plain `<Card>`.+- `MetricSparkline` owns the bottom-edge alignment (a built-in 6px shift that pushes the canvas's hover-ring margin past the card edge so the line rests on it) — a custom `className` only manages margins (`-mx-*`/`-mb-*`/`mt-*`), never re-adds the offset.- Give the card a height (`className="h-40"`, or `h-full` in a sized box) when using `sparklineFill` or when you want a fixed-height sparkline pinned to the bottom; otherwise it sizes to content (`Metric` is `h-full` so it fills whatever card it's in).- The root owns the data/hover behavior and feeds the parts via context — a part used outside `<Metric>` throws. Pass `value` for a number-only tile; pass `data`+`labels`+`theme` for a sparkline.-- `MetricDelta` renders a `Badge`; `goodDirection` (default `up`) decides success vs destructive. `changeTooltip` needs a `TooltipProvider` at the app root.-- Reproduces `MetricCard`'s behavior (`restingSubtitle`, `hoverChangeFromPreviousPoint`, `changeTooltip`) but drops its color/size props in favor of `Badge` variants.+- `MetricDelta` renders a `Badge`; `goodDirection` (default `up`) decides success vs destructive. It carries its own `TooltipProvider`, so `changeTooltip` needs no app-root setup. resize via `className` (the metric insight passes its own larger-pill classes and puts it inline next to the headline via `MetricHeader`; there is no `changeInline` or size prop, compose and style at the call site).+- Reproduces `MetricCard`'s behavior (`restingSubtitle`, `hoverChangeFromPreviousPoint`, `changeTooltip`, `positiveColor`/`negativeColor` for user-configured pill colors); omit the color props to keep the semantic `Badge` variants.## Maintenancediff --git a/packages/quill/packages/components/src/metric.tsx b/packages/quill/packages/components/src/metric.tsxindex 4128eaa6d675..369cb1a7e38e 100644--- a/packages/quill/packages/components/src/metric.tsx+++ b/packages/quill/packages/components/src/metric.tsx@@ -2,6 +2,7 @@ import { ChevronDown, ChevronUp } from 'lucide-react'import * as React from 'react'import {+ type ChangeColor,ChartErrorBoundary,computeFallbackChangePercent,type MetricChange,@@ -13,9 +14,9 @@ import {useHoverIntent,} from '@posthog/quill-charts'import type { ChartTheme } from '@posthog/quill-charts'-import { Badge, cn, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill-primitives'+import { Badge, cn, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@posthog/quill-primitives'-export type { MetricChange }+export type { ChangeColor, MetricChange }// What the root computes once and every part reads. Parts stay dumb: they render a slice of this.interface MetricContextValue {@@ -30,6 +31,7 @@ interface MetricContextValue {positive: boolean/** Change is in the desired direction — drives the Badge color (success vs destructive). */good: boolean+ colors?: ChangeColortooltip?: string} | null/** Sparkline wiring, or null when no series was supplied. */@@ -88,7 +90,11 @@ export interface MetricProps {change?: MetricChange | null/** Which direction is "good" — drives the pill color. Defaults to `up`. */goodDirection?: 'up' | 'down'- /** Tooltip shown on hover over the change pill (requires a `TooltipProvider` at the app root). */+ /** Custom pill colors for a change in the good direction; overrides the Badge `success` variant. */+ positiveColor?: ChangeColor+ /** Custom pill colors for a change in the bad direction; overrides the Badge `destructive` variant. */+ negativeColor?: ChangeColor+ /** Tooltip shown on hover over the change pill. */changeTooltip?: string/** Caption shown at rest and on hover. Always wins over `restingSubtitle` and hovered labels. */subtitle?: React.ReactNode@@ -150,6 +156,8 @@ function MetricInner({showChange = true,change,goodDirection = 'up',+ positiveColor,+ negativeColor,changeTooltip,subtitle,restingSubtitle,@@ -212,6 +220,7 @@ function MetricInner({delta,positive,good,+ colors: good ? positiveColor : negativeColor,// The tooltip describes the resting comparison, so hide it on the per-point delta.tooltip: usePrevPointHover ? undefined : changeTooltip,}@@ -242,6 +251,8 @@ function MetricInner({formatChange,changeTooltip,goodDirection,+ positiveColor,+ negativeColor,formatValue,animatedValue,subtitle,@@ -291,8 +302,9 @@ export function MetricValue({ className, children, ...props }: React.ComponentPr)}-/** Change pill — a `Badge` (success/destructive by `goodDirection`) with a directional chevron.- * Renders nothing when there is no resolved delta. */+/** Change pill — a `Badge` (success/destructive by `goodDirection`, or the root's custom+ * `positiveColor`/`negativeColor`) with a directional chevron. Renders nothing when there is no+ * resolved delta. */export function MetricDelta({ className }: { className?: string }): React.ReactElement | null {const { change } = useMetric('MetricDelta')if (change == null) {@@ -301,8 +313,14 @@ export function MetricDelta({ className }: { className?: string }): React.ReactEconst Chevron = change.positive ? ChevronUp : ChevronDownconst badge = (<Badge- variant={change.good ? 'success' : 'destructive'}+ variant={change.colors != null ? 'default' : change.good ? 'success' : 'destructive'}className={cn('gap-0.5 rounded-full tabular-nums', className)}+ // Dynamic user-configured colors can't be Tailwind classes; inline style wins over the variant.+ style={+ change.colors != null+ ? { background: change.colors.background, color: change.colors.foreground }+ : undefined+ }data-attr="metric-change-pill"><Chevron className="size-3" />@@ -312,11 +330,14 @@ export function MetricDelta({ className }: { className?: string }): React.ReactEif (change.tooltip == null) {return badge}+ // Badge isn't a forwardRef component, so it can't be the `render` target — anchor on a span.return (- <Tooltip>- <TooltipTrigger render={badge} />- <TooltipContent>{change.tooltip}</TooltipContent>- </Tooltip>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger render={<span className="inline-flex" />}>{badge}</TooltipTrigger>+ <TooltipContent>{change.tooltip}</TooltipContent>+ </Tooltip>+ </TooltipProvider>)}@@ -340,7 +361,7 @@ export function MetricSubtitle({/** Sparkline, bled out to the card edges. Renders nothing when no series was supplied to the root. */export function MetricSparkline({- className = '-mx-4 -mb-4 mt-4 relative top-[6px] flex-1',+ className = '-mx-4 -mb-4 mt-4 flex-1',}: {className?: string}): React.ReactElement | null {@@ -350,7 +371,8 @@ export function MetricSparkline({}// A fixed-height sparkline drops to the bottom of a taller card via `mt-auto`; a filling sparkline// grows into the free space itself, so it must not also claim that space with a margin. `-mx-4`/`-mb-4`- // cancel the card's content padding so the chart reaches the left/right/bottom edges.+ // cancel the card's content padding so the chart reaches the left/right/bottom edges. The 6px shift+ // eats the canvas's bottom hover-ring margin so the line rests on the card edge.const pinBottom = sparkline.fill ? '' : 'mt-auto'return (<Sparkline@@ -363,7 +385,7 @@ export function MetricSparkline({fillOpacity={sparkline.fillOpacity}dashedFromIndex={sparkline.dashedFromIndex}onHoverIndexChange={sparkline.setHoverIndex}- className={cn(pinBottom, className)}+ className={cn('relative top-[6px]', pinBottom, className)}dataAttr="metric-sparkline"/>)diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4c083cb7a87b..fd1ddf0d52e1 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -790,6 +790,9 @@ importers:'@posthog/quill-charts':specifier: workspace:*version: link:../packages/quill/packages/charts+ '@posthog/quill-components':+ specifier: workspace:*+ version: link:../packages/quill/packages/components'@posthog/react':specifier: 'catalog:'diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsxindex 35f88e803db1..9a88c0868072 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx@@ -5,14 +5,12 @@ import { IconArrowLeft, IconArrowRight } from '@posthog/icons'import { LemonDivider, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'import {type ChartTheme,- MetricCard,type Series,TimeSeriesLineChart,type TimeSeriesLineChartConfig,} from '@posthog/quill-charts'import {Card,- CardContent,CardDescription,CardHeader,CardTitle,@@ -39,8 +37,9 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { SceneExport } from '~/scenes/sceneTypes'-import { formatMs, formatMsAsSeconds } from './dashboard/formatters'+import { formatBucketLabel, formatMs, formatMsAsSeconds } from './dashboard/formatters'import { HarnessLogo, HarnessPill } from './dashboard/harness'+import { MetricTile } from './dashboard/MetricTile'import { mcpAnalyticsFeaturePreviewGate } from './featurePreviewGate'import {type DailyChartData,@@ -59,52 +58,6 @@ export const scene: SceneExport<MCPAnalyticsToolDetailLogicProps> = {}),}-function StatTile({- label,- value,- formatValue,- data,- theme,- color,- goodDirection,- loading,-}: {- label: string- value: number- formatValue: (n: number) => string- data?: number[]- theme: ChartTheme- color?: string- goodDirection?: 'up' | 'down'- loading: boolean-}): JSX.Element {- return (- <Card size="sm" className="flex-1">- {loading ? (- <CardContent className="flex flex-col gap-2">- <Skeleton className="h-3 w-16" />- <Skeleton className="h-7 w-20" />- </CardContent>- ) : (- <CardContent>- <MetricCard- className="text-primary"- title={label}- value={value}- data={data}- theme={theme}- color={color}- formatValue={formatValue}- goodDirection={goodDirection}- sparklineHeight={40}- sparklineClassName="mt-2 -mx-3 -mb-3"- />- </CardContent>- )}- </Card>- )-}-// Renderer for the "person" column in the Top users table. The loader maps each row's// person into a [distinct_id, _, person_properties] array. Wrap it back into the shape// PersonDisplay expects.@@ -260,69 +213,79 @@ function StatTiles({const errors = summary?.errors ?? 0const errorRate = calls ? (errors / calls) * 100 : 0const errorRateDaily = daily.calls.map((c, i) => (c ? (daily.errors[i] / c) * 100 : 0))+ const sparkLabels = daily.labels.slice(-SPARKLINE_DAYS).map(formatBucketLabel)++ const tiles: {+ label: string+ value: number+ formatValue: (n: number) => string+ data: number[]+ color: string+ goodDirection: 'up' | 'down'+ }[] = [+ {+ label: 'Calls',+ value: calls,+ formatValue: humanFriendlyNumber,+ data: spark(daily.calls),+ color: theme.colors[0],+ goodDirection: 'up',+ },+ {+ label: 'Error rate',+ value: errorRate,+ formatValue: (n) => `${n.toFixed(1)}%`,+ data: spark(errorRateDaily),+ color: theme.colors[4],+ goodDirection: 'down',+ },+ {+ label: 'p50 latency',+ value: summary?.p50_ms ?? 0,+ formatValue: formatMs,+ data: spark(daily.p50),+ color: theme.colors[0],+ goodDirection: 'down',+ },+ {+ label: 'p95 latency',+ value: summary?.p95_ms ?? 0,+ formatValue: formatMs,+ data: spark(daily.p95),+ color: theme.colors[0],+ goodDirection: 'down',+ },+ {+ label: 'Users',+ value: summary?.users ?? 0,+ formatValue: humanFriendlyNumber,+ data: spark(daily.users),+ color: theme.colors[0],+ goodDirection: 'up',+ },+ {+ label: 'Sessions',+ value: summary?.conversations ?? 0,+ formatValue: humanFriendlyNumber,+ data: spark(daily.sessions),+ color: theme.colors[6],+ goodDirection: 'up',+ },+ ]return (<div className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-6" data-quill>- <StatTile- label="Calls"- loading={loading}- value={calls}- formatValue={humanFriendlyNumber}- data={spark(daily.calls)}- theme={theme}- color={theme.colors[0]}- goodDirection="up"- />- <StatTile- label="Error rate"- loading={loading}- value={errorRate}- formatValue={(n) => `${n.toFixed(1)}%`}- data={spark(errorRateDaily)}- theme={theme}- color={theme.colors[4]}- goodDirection="down"- />- <StatTile- label="p50 latency"- loading={loading}- value={summary?.p50_ms ?? 0}- formatValue={formatMs}- data={spark(daily.p50)}- theme={theme}- color={theme.colors[0]}- goodDirection="down"- />- <StatTile- label="p95 latency"- loading={loading}- value={summary?.p95_ms ?? 0}- formatValue={formatMs}- data={spark(daily.p95)}- theme={theme}- color={theme.colors[0]}- goodDirection="down"- />- <StatTile- label="Users"- loading={loading}- value={summary?.users ?? 0}- formatValue={humanFriendlyNumber}- data={spark(daily.users)}- theme={theme}- color={theme.colors[0]}- goodDirection="up"- />- <StatTile- label="Sessions"- loading={loading}- value={summary?.conversations ?? 0}- formatValue={humanFriendlyNumber}- data={spark(daily.sessions)}- theme={theme}- color={theme.colors[6]}- goodDirection="up"- />+ {tiles.map((tile) => (+ <MetricTile+ key={tile.label}+ {...tile}+ loading={loading}+ labels={sparkLabels}+ theme={theme}+ restingSubtitle="Last 7 days"+ sparklineHeight={40}+ />+ ))}</div>)}diff --git a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsxindex bf726f1590b1..7c8a6116828c 100644--- a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx+++ b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx@@ -103,6 +103,7 @@ function metric(value: number, previousValue: number, sparkline: number[], goodDpreviousValue,deltaPct: previousValue ? ((value - previousValue) / previousValue) * 100 : null,sparkline,+ sparklineLabels: sparkline.map((_, i) => `2026-06-${String(10 + i).padStart(2, '0')} 00:00:00`),goodDirection,}}diff --git a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsxindex c22799a62b86..0e41c7ae651d 100644--- a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx+++ b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx@@ -1,12 +1,12 @@import { Link } from '@posthog/lemon-ui'-import { type ChartTheme, MetricCard } from '@posthog/quill-charts'-import { Card, CardContent, Skeleton } from '@posthog/quill-primitives'+import { type ChartTheme } from '@posthog/quill-charts'import { formatPercentage } from 'lib/utils/numbers'import { urls } from 'scenes/urls'import { type KPIData, KPIMetric } from '../mcpDashboardOverviewLogic'-import { formatMs, formatNumber } from './formatters'+import { formatBucketLabel, formatMs, formatNumber } from './formatters'+import { MetricTile } from './MetricTile'interface TileSpec {label: string@@ -15,45 +15,38 @@ interface TileSpec {format: (n: number) => stringcolor: stringloading: boolean- // Overrides the default "vs. prior" comparison line — used to flag a tile- // whose value isn't scoped by the dashboard filters.+ summaryLabel: string+ // Overrides the summary caption — used to flag a tile whose value isn't+ // scoped by the dashboard filters.subtitle?: string}function KPITile({ tile, theme }: { tile: TileSpec; theme: ChartTheme }): JSX.Element {const { metric } = tile- const hasSparkline = metric.sparkline.length > 0- const hasComparison = metric.deltaPct !== nullreturn (<Link to={tile.href} subtle className="group/tile flex h-full">- <Card size="sm" className="flex-1 transition-transform group-hover/tile:-translate-y-0.5">- {tile.loading ? (- <CardContent className="flex flex-col gap-2">- <Skeleton className="h-3 w-16" />- <Skeleton className="h-7 w-20" />- </CardContent>- ) : (- <CardContent>- <MetricCard- className="text-primary"- title={tile.label}- value={metric.value}- data={hasSparkline ? metric.sparkline : undefined}- theme={theme}- color={tile.color}- goodDirection={metric.goodDirection}- formatValue={tile.format}- subtitle={- tile.subtitle ??- (hasComparison ? `vs. ${tile.format(metric.previousValue)} prior` : undefined)- }- sparklineHeight={50}- sparklineClassName="mt-3 -mx-3 -mb-3"- />- </CardContent>- )}- </Card>+ <MetricTile+ className="transition-transform group-hover/tile:-translate-y-0.5"+ label={tile.label}+ loading={tile.loading}+ value={metric.value}+ data={metric.sparkline}+ labels={metric.sparklineLabels.map(formatBucketLabel)}+ theme={theme}+ color={tile.color}+ goodDirection={metric.goodDirection}+ formatValue={tile.format}+ change={metric.deltaPct !== null ? { value: metric.deltaPct } : null}+ changeTooltip={+ metric.deltaPct !== null+ ? `vs. ${tile.format(metric.previousValue)} in the previous period`+ : undefined+ }+ hoverChangeFromPreviousPoint+ restingSubtitle={tile.subtitle ?? tile.summaryLabel}+ sparklineHeight={50}+ /></Link>)}@@ -82,6 +75,7 @@ export function KpiTiles({format: formatNumber,color: theme.colors[2],loading: usersLoading,+ summaryLabel: 'Total',},{label: 'Sessions',@@ -90,6 +84,7 @@ export function KpiTiles({format: formatNumber,color: theme.colors[0],loading: kpisLoading,+ summaryLabel: 'Total',},{label: 'Tool calls',@@ -98,6 +93,7 @@ export function KpiTiles({format: formatNumber,color: theme.colors[0],loading: kpisLoading,+ summaryLabel: 'Total',},{label: 'Error rate',@@ -106,6 +102,7 @@ export function KpiTiles({format: (n) => formatPercentage(n, { compact: true }),color: theme.colors[4],loading: kpisLoading,+ summaryLabel: 'Latest',},{label: 'p95 latency',@@ -114,6 +111,7 @@ export function KpiTiles({format: formatMs,color: theme.colors[0],loading: kpisLoading,+ summaryLabel: 'Latest',},{label: 'Intent clusters',@@ -122,6 +120,7 @@ export function KpiTiles({format: formatNumber,color: theme.colors[6],loading: false,+ summaryLabel: 'Total',// Clusters come from the latest clustering snapshot across all sessions, so// unlike the other tiles this count isn't scoped by the date or test-account// filters. Label it so the grid doesn't read as a single consistent scope.diff --git a/products/mcp_analytics/frontend/dashboard/MetricTile.tsx b/products/mcp_analytics/frontend/dashboard/MetricTile.tsxnew file mode 100644index 000000000000..75cda9b06505--- /dev/null+++ b/products/mcp_analytics/frontend/dashboard/MetricTile.tsx@@ -0,0 +1,84 @@+import { type ChartTheme } from '@posthog/quill-charts'+import {+ Metric,+ type MetricChange,+ MetricDelta,+ MetricHeader,+ MetricSparkline,+ MetricSubtitle,+ MetricTitle,+ MetricValue,+} from '@posthog/quill-components/metric'+import { Card, CardContent, cn, Skeleton } from '@posthog/quill-primitives'++export interface MetricTileProps {+ label: string+ value: number+ formatValue: (n: number) => string+ theme: ChartTheme+ loading: boolean+ data?: number[]+ labels?: string[]+ color?: string+ goodDirection?: 'up' | 'down'+ restingSubtitle: string+ change?: MetricChange | null+ changeTooltip?: string+ hoverChangeFromPreviousPoint?: boolean+ sparklineHeight?: number+ className?: string+}++export function MetricTile({+ label,+ value,+ formatValue,+ theme,+ loading,+ data,+ labels,+ color,+ goodDirection,+ restingSubtitle,+ change = null,+ changeTooltip,+ hoverChangeFromPreviousPoint = false,+ sparklineHeight,+ className,+}: MetricTileProps): JSX.Element {+ const hasSparkline = data != null && data.length > 0+ return (+ <Card size="sm" flush={hasSparkline} className={cn('flex-1', className)}>+ {loading ? (+ <CardContent className="flex flex-col gap-2">+ <Skeleton className="h-3 w-16" />+ <Skeleton className="h-7 w-20" />+ </CardContent>+ ) : (+ <Metric+ className="px-3 text-primary"+ value={value}+ data={hasSparkline ? data : undefined}+ labels={hasSparkline ? labels : undefined}+ theme={theme}+ color={color}+ goodDirection={goodDirection}+ formatValue={formatValue}+ change={change}+ changeTooltip={changeTooltip}+ hoverChangeFromPreviousPoint={hoverChangeFromPreviousPoint}+ restingSubtitle={restingSubtitle}+ sparklineHeight={sparklineHeight}+ >+ <MetricHeader>+ <MetricTitle>{label}</MetricTitle>+ <MetricDelta />+ </MetricHeader>+ <MetricValue className="mt-2" />+ <MetricSubtitle className="mt-1" />+ <MetricSparkline className="mt-3 -mx-3" />+ </Metric>+ )}+ </Card>+ )+}diff --git a/products/mcp_analytics/frontend/dashboard/formatters.ts b/products/mcp_analytics/frontend/dashboard/formatters.tsindex 154010b21105..3978e936e5c6 100644--- a/products/mcp_analytics/frontend/dashboard/formatters.ts+++ b/products/mcp_analytics/frontend/dashboard/formatters.ts@@ -1,8 +1,14 @@+import { dayjs } from 'lib/dayjs'import { humanFriendlyDuration } from 'lib/utils/durations'import { humanFriendlyLargeNumber } from 'lib/utils/numbers'const EMPTY = '—'+export function formatBucketLabel(bucket: string): string {+ const d = dayjs(bucket)+ return d.isValid() ? d.format('MMM D') : bucket+}+export function formatNumber(n: number): string {if (!isFinite(n)) {return EMPTYdiff --git a/products/mcp_analytics/frontend/firstLook/firstLookCopy.test.ts b/products/mcp_analytics/frontend/firstLook/firstLookCopy.test.tsindex af22c0afd879..622809fe00e7 100644--- a/products/mcp_analytics/frontend/firstLook/firstLookCopy.test.ts+++ b/products/mcp_analytics/frontend/firstLook/firstLookCopy.test.ts@@ -6,6 +6,7 @@ const metric = (value: number): KPIData['sessions'] => ({previousValue: 0,deltaPct: null,sparkline: [],+ sparklineLabels: [],goodDirection: 'up',})diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.tsindex 6c2644c55b45..cc324010045f 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts@@ -348,6 +348,7 @@ describe('mcpDashboardOverviewLogic', () => {previousValue: 5,deltaPct: 500,sparkline: [10, 20], // current sorted by bucket+ sparklineLabels: ['2024-01-08', '2024-01-09'],goodDirection: 'up',})expect(kpis.toolCalls).toMatchObject({@@ -362,9 +363,12 @@ describe('mcpDashboardOverviewLogic', () => {deltaPct: 100,goodDirection: 'down',})- expect(kpis.errorRatePct.value).toBeCloseTo(6.667, 2)- expect(kpis.errorRatePct.previousValue).toBeCloseTo(10, 5)- expect(kpis.errorRatePct.goodDirection).toBe('down')+ expect(kpis.errorRatePct).toMatchObject({+ value: 7.5,+ previousValue: 10,+ deltaPct: -25,+ goodDirection: 'down',+ })})it('returns null deltas when there is no prior-period data', () => {@@ -470,6 +474,7 @@ describe('mcpDashboardOverviewLogic', () => {previousValue: 30,deltaPct: 40,sparkline: [],+ sparklineLabels: [],goodDirection: 'up',})})diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.tsindex af5a65f20ff3..d48072fa0b08 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts@@ -153,6 +153,7 @@ export interface KPIMetric {previousValue: numberdeltaPct: number | nullsparkline: number[]+ sparklineLabels: string[]goodDirection: 'up' | 'down'}@@ -223,7 +224,14 @@ export interface NotableSession {session: SessionRow}-const EMPTY_METRIC: KPIMetric = { value: 0, previousValue: 0, deltaPct: null, sparkline: [], goodDirection: 'up' }+const EMPTY_METRIC: KPIMetric = {+ value: 0,+ previousValue: 0,+ deltaPct: null,+ sparkline: [],+ sparklineLabels: [],+ goodDirection: 'up',+}const EMPTY_KPIS: KPIData = {sessions: { ...EMPTY_METRIC, goodDirection: 'up' },toolCalls: { ...EMPTY_METRIC, goodDirection: 'up' },@@ -397,18 +405,27 @@ export function buildKPIs(rows: BucketRow[], currentStartBucket: string): KPIDatconst current = rows.filter((r) => r.bucket >= currentStartBucket).sort((a, b) => a.bucket.localeCompare(b.bucket))const previous = rows.filter((r) => r.bucket < currentStartBucket)+ // Newest bucket with latency data — p95 === 0 marks a bucket without any.+ const latestP95 = (rows_: BucketRow[]): number =>+ [...rows_].sort((a, b) => b.bucket.localeCompare(a.bucket)).find((r) => r.p95 > 0)?.p95 ?? 0++ // Newest bucket with any calls — a 0% rate from an empty bucket would be meaningless.+ const latestErrorRate = (rows_: BucketRow[]): number => {+ const row = [...rows_].sort((a, b) => b.bucket.localeCompare(a.bucket)).find((r) => r.tool_calls > 0)+ return row ? (row.errors / row.tool_calls) * 100 : 0+ }+const curSessions = current.reduce((acc, r) => acc + r.sessions, 0)const curCalls = current.reduce((acc, r) => acc + r.tool_calls, 0)- const curErrors = current.reduce((acc, r) => acc + r.errors, 0)- const curP95 = current.length ? Math.max(...current.map((r) => r.p95)) : 0+ const curP95 = latestP95(current)const prevSessions = previous.reduce((acc, r) => acc + r.sessions, 0)const prevCalls = previous.reduce((acc, r) => acc + r.tool_calls, 0)- const prevErrors = previous.reduce((acc, r) => acc + r.errors, 0)- const prevP95 = previous.length ? Math.max(...previous.map((r) => r.p95)) : 0+ const prevP95 = latestP95(previous)- const curErrorRate = curCalls ? (curErrors / curCalls) * 100 : 0- const prevErrorRate = prevCalls ? (prevErrors / prevCalls) * 100 : 0+ const curErrorRate = latestErrorRate(current)+ const prevErrorRate = latestErrorRate(previous)+ const sparklineLabels = current.map((r) => r.bucket)return {sessions: {@@ -416,6 +433,7 @@ export function buildKPIs(rows: BucketRow[], currentStartBucket: string): KPIDatpreviousValue: prevSessions,deltaPct: deltaPct(curSessions, prevSessions),sparkline: current.map((r) => r.sessions),+ sparklineLabels,goodDirection: 'up',},toolCalls: {@@ -423,6 +441,7 @@ export function buildKPIs(rows: BucketRow[], currentStartBucket: string): KPIDatpreviousValue: prevCalls,deltaPct: deltaPct(curCalls, prevCalls),sparkline: current.map((r) => r.tool_calls),+ sparklineLabels,goodDirection: 'up',},errorRatePct: {@@ -430,6 +449,7 @@ export function buildKPIs(rows: BucketRow[], currentStartBucket: string): KPIDatpreviousValue: prevErrorRate,deltaPct: deltaPct(curErrorRate, prevErrorRate),sparkline: current.map((r) => (r.tool_calls ? (r.errors / r.tool_calls) * 100 : 0)),+ sparklineLabels,goodDirection: 'down',},p95LatencyMs: {@@ -437,6 +457,7 @@ export function buildKPIs(rows: BucketRow[], currentStartBucket: string): KPIDatpreviousValue: prevP95,deltaPct: deltaPct(curP95, prevP95),sparkline: current.map((r) => r.p95),+ sparklineLabels,goodDirection: 'down',},}@@ -522,6 +543,7 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([deltaPct: deltaPct(value, previousValue),// No sparkline: the headline is a window-level distinct count, not a per-bucket series.sparkline: [],+ sparklineLabels: [],goodDirection: 'up',}},@@ -687,6 +709,7 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([previousValue: 0,deltaPct: null,sparkline: [],+ sparklineLabels: [],goodDirection: 'up',}),],