: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): add distinct-users tile to dashboard overview (#68240)
posthog[bot]84f4ea80c403
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b24c6aa88a09..40230a69bb6d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6165,9 +6165,9 @@ snapshots:scenes-app-marketing-analytics-cell-actions--source-cell-action-unmapped--light:hash: v1.k794b7964.c15b997111d34fb17ad2dd192b97c01d0a7ab3a320c5edf9a3e20b0b63a4ff9b.UHxcXJdZkFGXRnzIMFWO99QMD_gZm0V47g8f1j4OFS0scenes-app-mcp-analytics--dashboard--dark:- hash: v1.k794b7964.b808f4aa884cd8841113e007d72e6eda60f523efb574cb49ce240fc997e34786.PwJQj0mMYEYRECT3GMPWfu8ZDviUUiO78jXxO0ThK2E+ hash: v1.k794b7964.5c68a5b1960c19bde11204b144353e5a655322d258d05273505c35cbb7e255dc.PcnSu5cRQDDanvMnxMUOUsJkBSDHUjgPIGW_f-rOPYUscenes-app-mcp-analytics--dashboard--light:- hash: v1.k794b7964.8a54f39fa61e29de60a8f182dcd18b1f0009797449d34d562b9544db08b4fd44.hPsGJnRmLWXT9gbM8Tgn_9reho5TcafpOON2b9wwoso+ hash: v1.k794b7964.f4acf23317352214813d98ee488b9d1eaaaf86321fa81e4b999b0df10d528e55.4F7cFSFc-wE2ns4rWSaEQY_aiUJn877CTJe7LiGlX40scenes-app-mcp-analytics--dashboard-with-menu-bar--dark:hash: v1.k794b7964.20d53706369819a7b2c0362e19d0b2294f97b5eed1028fea44df50ae9872fc54.yNsqojVK97Tn9tBxdYCT3JlcjkDB4xkrJhY7EOfG4xcscenes-app-mcp-analytics--dashboard-with-menu-bar--light:@@ -6201,9 +6201,9 @@ snapshots:scenes-app-mcp-analytics-dashboard-cards--flagged-sessions--light:hash: v1.k794b7964.3564655474c6001d48e81c691e1339dc5413f96073ca97ab730d45c1f098a9d9.nHOM1CoYHMaZRiMpFANM8CPeuiPQp4Lysxq6m1uCs-wscenes-app-mcp-analytics-dashboard-cards--key-metrics--dark:- hash: v1.k794b7964.481cecf19de81a8f3e995f66377e05f5ea64f6c1eaaf921537524d9e09fe5029.H5FpcTcE4_0O_5IIPHk6Xooy1bypCNWjBp3CrDigCUM+ hash: v1.k794b7964.539a2481d273c0043468cca5c575d2b1b597b6a7ebdb985da1692f8a02c9bb43.bFQjFUi7S6EomB8-kxn_lUjRaN4pfI6uzsu4_HnReYgscenes-app-mcp-analytics-dashboard-cards--key-metrics--light:- hash: v1.k794b7964.84de31830adee4516636778b26edce0714e6e72b5a6396eac048cdd4feb69a6c.4TA16oV-WAv-1ahpK7Yld3Tjb8OCh9lcdB5CC08-hzo+ hash: v1.k794b7964.244789b4b44125b7c6eb278c728ec71a6c14abb7848ed3ef93b594804fc46cdd.LpSM8CA_ZM-w4j5hPzdNf-gWxnPzoKDtvI94CwtEgnsscenes-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/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsxindex 7b94712b6df9..a3a028d72dea 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx@@ -21,6 +21,8 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {const {kpis,kpisLoading,+ users,+ usersLoading,intentClusterCount,notableSessions,sessionRowsLoading,@@ -79,7 +81,14 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {<MCPAnalyticsFirstLook /><section data-quill><h2 className="mb-4 text-xl font-semibold text-primary">Key metrics</h2>- <KpiTiles kpis={kpis} intentClusterCount={intentClusterCount} kpisLoading={kpisLoading} theme={theme} />+ <KpiTiles+ kpis={kpis}+ users={users}+ intentClusterCount={intentClusterCount}+ kpisLoading={kpisLoading}+ usersLoading={usersLoading}+ theme={theme}+ /></section><section data-quill><h2 className="mb-4 text-xl font-semibold text-primary">Usage</h2>diff --git a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsxindex 3ef69e389ef8..bf726f1590b1 100644--- a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx+++ b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx@@ -141,8 +141,10 @@ export const KeyMetrics: Story = {<div className="w-[960px]"><KpiTileskpis={KPIS}+ users={metric(1840, 1655, [], 'up')}intentClusterCount={metric(6, 0, [], 'up')}kpisLoading={false}+ usersLoading={false}theme={buildTheme()}/></div>diff --git a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsxindex b1706cbdc4d3..c22799a62b86 100644--- a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx+++ b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx@@ -60,16 +60,29 @@ function KPITile({ tile, theme }: { tile: TileSpec; theme: ChartTheme }): JSX.Elexport function KpiTiles({kpis,+ users,intentClusterCount,kpisLoading,+ usersLoading,theme,}: {kpis: KPIData+ users: KPIMetricintentClusterCount: KPIMetrickpisLoading: boolean+ usersLoading: booleantheme: ChartTheme}): JSX.Element {const tiles: TileSpec[] = [+ {+ label: 'Users',+ metric: users,+ // Person identity (email/name) is resolved on the Sessions tab, so that's the drill-down for "who".+ href: urls.mcpAnalyticsSessions(),+ format: formatNumber,+ color: theme.colors[2],+ loading: usersLoading,+ },{label: 'Sessions',metric: kpis.sessions,@@ -116,11 +129,16 @@ export function KpiTiles({},]+ // Wrap the six tiles only into rows that divide evenly (6 → 3+3 → 2+2+2), never a lone+ // trailing card. Container queries key off the card area's own width, so the sidebar can't+ // push it to an awkward 5+1 the way viewport breakpoints or plain auto-fit would.return (- <div className="grid grid-cols-[repeat(auto-fit,minmax(175px,1fr))] gap-3">- {tiles.map((tile) => (- <KPITile key={tile.label} tile={tile} theme={theme} />- ))}+ <div className="@container">+ <div className="grid grid-cols-2 gap-3 @xl:grid-cols-3 @6xl:grid-cols-6">+ {tiles.map((tile) => (+ <KPITile key={tile.label} tile={tile} theme={theme} />+ ))}+ </div></div>)}diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.tsindex 6894611f6d27..3d520617ad72 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts@@ -450,6 +450,29 @@ describe('mcpDashboardOverviewLogic', () => {// at the top level. This reads whichever shape a reload used.const filtersOf = (call: any): Record<string, any> => call.filters ?? call+ // The users query returns a single [current_users, prior_users] row; loadUsers maps+ // column 0 → value, column 1 → previousValue, and derives the delta. Pins that column+ // mapping and the deltaPct wiring — a swap or a dropped delta would slip past the other+ // tests, which only ever see empty results.+ it('maps the users query columns to the current/prior metric', async () => {+ mockApi.query.mockImplementation(async (node: any) =>+ typeof node?.query === 'string' && node.query.includes('current_users')+ ? ({ results: [[42, 30]] } as any)+ : ({ results: [] } as any)+ )+ const logic = mcpDashboardOverviewLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.users).toEqual({+ value: 42,+ previousValue: 30,+ deltaPct: 40,+ sparkline: [],+ goodDirection: 'up',+ })+ })+it('reloads every tile when the date filter changes', async () => {const logic = mcpDashboardOverviewLogic()logic.mount()@@ -461,15 +484,18 @@ describe('mcpDashboardOverviewLogic', () => {}).toFinishAllListeners()const reloads = reloadCallsSince(callsBefore)- // Six tiles: KPI + the five breakdown queries.- expect(reloads.length).toBe(6)+ // Seven tiles: KPI + users + the five breakdown queries.+ expect(reloads.length).toBe(7)// The five breakdowns pass the raw selected range straight through.const breakdowns = reloads.filter((call) => filtersOf(call).dateRange?.date_from === '-30d')expect(breakdowns).toHaveLength(5)- // The KPI tile widens to an absolute doubled window so it can compare against the prior period.+ // The KPI and users tiles widen to an absolute doubled window so they can compare against the prior period.const kpi = reloads.find((call) => call.query?.includes('AS bucket'))expect(kpi?.filters.dateRange.date_from).not.toBe('-30d')expect(dayjs(kpi?.filters.dateRange.date_from).isValid()).toBe(true)+ const usersTile = reloads.find((call) => call.query?.includes('current_users'))+ expect(usersTile?.filters.dateRange.date_from).not.toBe('-30d')+ expect(dayjs(usersTile?.filters.dateRange.date_from).isValid()).toBe(true)})it.each([[false], [true]])('passes filterTestAccounts=%s to every tile', async (enabled) => {@@ -486,7 +512,7 @@ describe('mcpDashboardOverviewLogic', () => {}const reloads = reloadCallsSince(callsBefore)- expect(reloads.length).toBe(6)+ expect(reloads.length).toBe(7)expect(reloads.every((call) => filtersOf(call).filterTestAccounts === enabled)).toBe(true)})@@ -499,7 +525,7 @@ describe('mcpDashboardOverviewLogic', () => {// No explicit toggle, yet every tile filters internal users because the team default is on.const reloads = mockApi.query.mock.calls.map((call) => call[0] as any)- expect(reloads.length).toBeGreaterThanOrEqual(6)+ expect(reloads.length).toBeGreaterThanOrEqual(7)expect(reloads.every((call) => filtersOf(call).filterTestAccounts === true)).toBe(true)})@@ -531,7 +557,7 @@ describe('mcpDashboardOverviewLogic', () => {}).toFinishAllListeners()const reloads = reloadCallsSince(callsBefore)- expect(reloads.length).toBe(6)+ expect(reloads.length).toBe(7)expect(reloads.every((call) => JSON.stringify(filtersOf(call).properties) === JSON.stringify([filter]))).toBe(true)diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.tsindex 5535a62e8b5f..af5a65f20ff3 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts@@ -45,6 +45,23 @@ GROUP BY bucketORDER BY bucket`+// Distinct MCP users for the "Users" tile — how many distinct people made tool calls.+// Counted over the doubled window like the KPI query, then split into the selected period+// and its equal-length predecessor with a single conditional uniq so the comparison is a+// true distinct-person count (summing per-bucket distinct users would over-count anyone+// active on more than one day). `__CUR_START__` is the selected-period boundary, injected+// as a timezone-aware toDateTime at call time.+const USERS_QUERY = `+SELECT+ uniqIf(person_id, timestamp >= __CUR_START__) AS current_users,+ uniqIf(person_id, timestamp < __CUR_START__) AS prior_users+FROM events+WHERE event = '$mcp_tool_call'+ AND properties.$mcp_tool_name IS NOT NULL+ AND properties.$mcp_tool_name != ''+ AND {filters}+`+// Per-session rollup powering the Notable sessions block. The selector// applies fixed rules over this set; no per-rule SQL.const SESSION_ROWS_QUERY = `@@ -356,6 +373,14 @@ export function buildKpiWindow(dateFilter: DateFilter, timezone: string, interva}}+// Merge the dashboard's active filters with a doubled comparison window's date range.+// Shared by the KPI and Users loaders so both tiles are scoped to the exact same window —+// the tile-parity the reload test asserts. Keep the two loaders reading from here so the+// window/filter plumbing can't drift between them.+function kpiWindowFilters(queryFilters: HogQLFilters, kpiWindow: KpiWindow): HogQLFilters {+ return { ...queryFilters, dateRange: { date_from: kpiWindow.dateFrom, date_to: kpiWindow.dateTo } }+}+function parseRows(rawRows: unknown[][]): BucketRow[] {return rawRows.map((r) => ({bucket: String(r[0]),@@ -460,10 +485,7 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([const response = (await api.query({kind: NodeKind.HogQLQuery,query: KPI_QUERY.replace('__BUCKET__', `dateTrunc('${interval}', timestamp)`),- filters: {- ...values.queryFilters,- dateRange: { date_from: kpiWindow.dateFrom, date_to: kpiWindow.dateTo },- },+ filters: kpiWindowFilters(values.queryFilters, kpiWindow),})) as HogQLQueryResponsebreakpoint()const rows = parseRows((response?.results as unknown[][]) ?? [])@@ -471,6 +493,40 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([},},],+ users: [+ EMPTY_METRIC,+ {+ loadUsers: async (_: void, breakpoint): Promise<KPIMetric> => {+ const { interval, timezone } = values+ const kpiWindow = buildKpiWindow(values.dateFilter, timezone, interval)+ // Split the doubled window at the selected period's start. currentStartBucket is+ // interval-aligned (buildKpiWindow → start.startOf(interval)), so comparing the raw+ // `timestamp` against toDateTime(bucket, tz) lands on the same instant as the KPI+ // tiles' dateTrunc bucket-string split — keeping this count consistent with them.+ // (For rolling sub-day ranges the two halves can differ by up to one interval, the+ // same bounded skew the KPI tiles already carry; splitting on the raw start instead+ // would equalize the halves but desync Users from the other tiles, so don't.)+ const curStart = `toDateTime('${kpiWindow.currentStartBucket}', '${timezone}')`+ const response = (await api.query({+ kind: NodeKind.HogQLQuery,+ query: USERS_QUERY.replace(/__CUR_START__/g, curStart),+ filters: kpiWindowFilters(values.queryFilters, kpiWindow),+ })) as HogQLQueryResponse+ breakpoint()+ const row = (response?.results as unknown[][])?.[0] ?? []+ const value = Number(row[0] ?? 0)+ const previousValue = Number(row[1] ?? 0)+ return {+ value,+ previousValue,+ deltaPct: deltaPct(value, previousValue),+ // No sparkline: the headline is a window-level distinct count, not a per-bucket series.+ sparkline: [],+ goodDirection: 'up',+ }+ },+ },+ ],toolRows: [[] as ToolRow[],{@@ -647,6 +703,7 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([},reloadAll: () => {actions.loadKPIs()+ actions.loadUsers()actions.loadToolRows()actions.loadSessionRows()actions.loadHarnessRows()