: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 dashboard-wide time filter (#64434)
Paul D'Ambraa72a3d826822
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b642aab28ca3..485e8b64047c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5641,21 +5641,21 @@ snapshots:scenes-app-marketing-analytics-cell-actions--source-cell-action-unmapped--light:hash: v1.k794b7964.4ebf2f848b10c8b2859630215a9be1ff91fb825fc334005207556310261d3a5c.UcqJY3dqyJNbi3x7oYaZ2rEu95LAEdbGmMyEpI-Wlgcscenes-app-mcp-analytics--dashboard--dark:- hash: v1.k794b7964.83c70580c95196511976b284e12102c4fc4b60bfe0c4b5b84ede14177c0f0fc1.ghImisZOBWjSVAnytJWdTHks5jIe2jn032_4NF_-g-c+ hash: v1.k794b7964.ce73116b61c51cdf515f7c449614e819605543194fc8194e3777cdd3fe37e847.V5cyDORCjiV-nUz1h65KpHKbywxm0u-TRuq7W3vJSrYscenes-app-mcp-analytics--dashboard--light:- hash: v1.k794b7964.c64d5d43c4eaa79d3008e9dd40857d9bee879832e68a8f8e9464657ff670773f.yKxStICPwIMCMEnf_zQhK0BuXu5BIxaUKmgPYHAEzYo+ hash: v1.k794b7964.ca0753eb512b0d9ccef0d4c4ff92aadcea3b6df1be5651501038556443e5e914.yj6GSJwiP_mA_Eq426rKSfymYSgYCQVBqsnB5hLWwKQscenes-app-mcp-analytics--sessions--dark:hash: v1.k794b7964.277463ad445565d14f2549a063a4f8c0c23a81af419bfafc9eefc65577fb0834.woelvjefGWPDW4Acae_sP2fA7YidrA7tkhfvC8u_AQ4scenes-app-mcp-analytics--sessions--light:hash: v1.k794b7964.bbe32ae76ef1ed9053d24d860933bc0bf1cca54ed3f601effaf515b8d9a6cd21.saYknnP-f1-BwcwRczq_p6CgUmnH8cmE8YJ_9XpN2Pkscenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--dark:- hash: v1.k794b7964.695d298349258e60b3b8f0c8775e1554ffd9ad3a3b9d4d750df124550bf65c51.cpBNQ-OwnkymJacZsj27ScYkVTr_36Yb8Z27xINlTN8+ hash: v1.k794b7964.921f819d1e55f6b1df74b8d4990bba635aa6f7db8ab7a75a232009bbac5f2e43.qy4SEtXqEIFBeEw5gzgTLCCbKUL61bV7pvuMq_cdTzAscenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--light:- hash: v1.k794b7964.3dfc5ce2265a673956f3eab4e61f354d521843fa67e204a55b00d9a477059dff.5usCphh504ZrBw5hriydx544vV8-RLHdGmrR-lJipNU+ hash: v1.k794b7964.5d9dd4393c052649a915d9fc01f0f07234778e6f07f876a2fb912692b967788e.xDH1R5rcnjKd-BMTqKjYRI3ILq3GIZKLCfvQCkBA6gEscenes-app-mcp-analytics-dashboard-cards--daily-tool-breakdown--dark:- hash: v1.k794b7964.830c208da94ba09d6c4ebbf829d48e8d8647ac7e6f10005d0ece25d8b1452826.H6z3crTfy2qeI7IGNmP1sVidoSC2oOUayUHiftQFGK4+ hash: v1.k794b7964.236335937faad628b44dd754d4ce16dd3420dfc7a6d490441aadd4d4c7617477.MSc20kR_NgLKYepX3fzKiFeTN7RWZBJrLsiUG6gXePIscenes-app-mcp-analytics-dashboard-cards--daily-tool-breakdown--light:- hash: v1.k794b7964.08616349eeae04cabd327dde6ab1cf6bd40a19a609f175554044ac2c0bceb271.qccwqFpHII7zSOEe3-1rqQpODEHCZ4B5uOyojP6oO9Y+ hash: v1.k794b7964.2310b7364e5f258ea2a43fa99bb9de186017c80b5ab3861419426edbc128acb9.yt5bPk2SSqYNpVVzhYToDVQfoOq_hkz7Ee1dZbk5pQoscenes-app-mcp-analytics-dashboard-cards--error-rate-by-tool--dark:hash: v1.k794b7964.6d0c0cd5cbb382903fee3b31192a515c1aeaf19d17ef3626f300815b1d0ce3aa.czfgUIwTwO7B3tJ874cZj9pvjWCdKI9wQLAkIl5LIhUscenes-app-mcp-analytics-dashboard-cards--error-rate-by-tool--light:diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsxindex 6d66ed335cfb..70db4b17b30c 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboardOverview.tsx@@ -1,4 +1,4 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { useMemo } from 'react'import { type ChartTheme } from '@posthog/quill-charts'@@ -8,6 +8,7 @@ import { teamLogic } from 'scenes/teamLogic'import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { McpDateFilter } from './components/McpDateFilter'import { ActivityChart } from './dashboard/ActivityChart'import { HarnessDonut } from './dashboard/HarnessDonut'import { KpiTiles } from './dashboard/KpiTiles'@@ -31,7 +32,10 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {toolDailyRowsLoading,toolRows,toolRowsLoading,+ dateFilter,+ interval,} = useValues(mcpDashboardOverviewLogic)+ const { setDateFilter } = useActions(mcpDashboardOverviewLogic)const { isDarkModeOn } = useValues(themeLogic)const { timezone } = useValues(teamLogic)@@ -40,13 +44,21 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {const theme = useMemo<ChartTheme>(() => buildTheme(), [isDarkModeOn])return (- <div className="flex flex-col gap-10" data-quill>+ <div className="flex flex-col gap-4" data-quill>+ <div className="flex flex-wrap items-center gap-3">+ <McpDateFilter+ dateFrom={dateFilter.dateFrom}+ dateTo={dateFilter.dateTo}+ onChange={(dateFrom, dateTo) => setDateFilter(dateFrom, dateTo)}+ dataAttr="mcp-dashboard-date-filter"+ />+ </div><section>- <h2 className="mb-4 text-xl font-semibold text-primary">This week's key metrics</h2>+ <h2 className="mb-4 text-xl font-semibold text-primary">Key metrics</h2><KpiTiles kpis={kpis} intentClusterCount={intentClusterCount} kpisLoading={kpisLoading} theme={theme} /></section><section>- <h2 className="mb-4 text-xl font-semibold text-primary">Last month's usage</h2>+ <h2 className="mb-4 text-xl font-semibold text-primary">Usage</h2><div className="flex flex-col gap-[22px]"><div className="grid grid-cols-1 gap-[22px] lg:grid-cols-3"><div className="flex lg:col-span-2">@@ -55,6 +67,7 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {loading={activityRowsLoading}theme={theme}timezone={timezone}+ interval={interval}/></div><HarnessDonut rows={harnessRows} loading={harnessRawRowsLoading} theme={theme} />@@ -68,6 +81,7 @@ export function MCPAnalyticsDashboardOverview(): JSX.Element {loading={toolDailyRowsLoading}theme={theme}timezone={timezone}+ interval={interval}/></div></section>diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsxindex 000bf1abaf9b..ae51d6bb42e4 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx@@ -14,9 +14,9 @@ import { urls } from 'scenes/urls'import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { McpDateFilter } from './components/McpDateFilter'import { mcpAnalyticsToolQualityLogic } from './mcpAnalyticsToolQualityLogic'import { ToolQualityCharts } from './tool-quality/ToolQualityCharts'-import { ToolQualityDateFilter } from './tool-quality/ToolQualityDateFilter'import { ToolQualityTable } from './tool-quality/ToolQualityTable'function FilterBar(): JSX.Element {@@ -38,10 +38,11 @@ function FilterBar(): JSX.Element {dataAttr="mcp-tool-quality-category-scope"/></div>- <ToolQualityDateFilter+ <McpDateFilterdateFrom={dateFilter.dateFrom}dateTo={dateFilter.dateTo}onChange={(dateFrom, dateTo) => setDateFilter(dateFrom, dateTo)}+ dataAttr="mcp-tool-quality-date-filter"/>{hasScope && sharePct !== null ? (<Tooltipdiff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityDateFilter.tsx b/products/mcp_analytics/frontend/components/McpDateFilter.tsxsimilarity index 92%rename from products/mcp_analytics/frontend/tool-quality/ToolQualityDateFilter.tsxrename to products/mcp_analytics/frontend/components/McpDateFilter.tsxindex e866993ca3c1..aec80425e5c6 100644--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityDateFilter.tsx+++ b/products/mcp_analytics/frontend/components/McpDateFilter.tsx@@ -56,13 +56,14 @@ function formatTriggerLabel(value: DateTimeValue): string {return `${dayjs(value.start).format('MMM D, HH:mm')} – ${dayjs(value.end).format('MMM D, HH:mm')}`}-interface ToolQualityDateFilterProps {+interface McpDateFilterProps {dateFrom: string | nulldateTo: string | nullonChange: (dateFrom: string | null, dateTo: string | null) => void+ dataAttr: string}-export function ToolQualityDateFilter({ dateFrom, dateTo, onChange }: ToolQualityDateFilterProps): JSX.Element {+export function McpDateFilter({ dateFrom, dateTo, onChange, dataAttr }: McpDateFilterProps): JSX.Element {const [open, setOpen] = useState(false)const value = toPickerValue(dateFrom, dateTo)@@ -80,7 +81,7 @@ export function ToolQualityDateFilter({ dateFrom, dateTo, onChange }: ToolQualit<Popover open={open} onOpenChange={setOpen}><PopoverTriggerrender={- <Button variant="outline" data-attr="mcp-tool-quality-date-filter">+ <Button variant="outline" data-attr={dataAttr}><IconCalendar />{formatTriggerLabel(value)}</Button>diff --git a/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx b/products/mcp_analytics/frontend/dashboard/ActivityChart.tsxindex c82c4d57f106..f7534f364369 100644--- a/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx+++ b/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx@@ -3,6 +3,7 @@ import { useMemo } from 'react'import {type ChartTheme,type Series,+ type TimeInterval,TimeSeriesLineChart,type TimeSeriesLineChartConfig,} from '@posthog/quill-charts'@@ -16,11 +17,13 @@ export function ActivityChart({loading,theme,timezone,+ interval,}: {daily: DailyActivityloading: booleantheme: ChartThemetimezone: string+ interval: TimeInterval}): JSX.Element {const series = useMemo<Series[]>(() => {const totals = daily.successes.map((s, i) => s + (daily.errors[i] ?? 0))@@ -34,15 +37,15 @@ export function ActivityChart({() => ({yAxis: { showGrid: false },showAxisLines: true,- xAxis: { interval: 'day', timezone },+ xAxis: { interval, timezone },showCrosshair: true,tooltip: { placement: 'cursor' },}),- [timezone]+ [timezone, interval])return (- <Card className="flex flex-1 flex-col" title="Daily tool calls and errors">+ <Card className="flex flex-1 flex-col" title="Tool calls and errors"><CardStateloading={loading}isEmpty={daily.labels.length === 0}diff --git a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsxindex 07700d375935..6463f9265dd7 100644--- a/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx+++ b/products/mcp_analytics/frontend/dashboard/DashboardCards.stories.tsx@@ -150,7 +150,9 @@ export const KeyMetrics: Story = {}export const DailyCallsAndErrors: Story = {- render: withTheme((theme) => <ActivityChart daily={DAILY_ACTIVITY} loading={false} theme={theme} timezone="UTC" />),+ render: withTheme((theme) => (+ <ActivityChart daily={DAILY_ACTIVITY} loading={false} theme={theme} timezone="UTC" interval="day" />+ )),}export const ShareByHarness: Story = {@@ -162,7 +164,9 @@ export const ErrorRateByTool: Story = {}export const DailyToolBreakdown: Story = {- render: withTheme((theme) => <ToolUsageChart data={TOOL_DAILY} loading={false} theme={theme} timezone="UTC" />),+ render: withTheme((theme) => (+ <ToolUsageChart data={TOOL_DAILY} loading={false} theme={theme} timezone="UTC" interval="day" />+ )),}export const FlaggedSessions: Story = {diff --git a/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx b/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsxindex 00009ce84def..46c6f971b351 100644--- a/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx+++ b/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx@@ -1,6 +1,12 @@import { useMemo } from 'react'-import { type ChartTheme, type Series, TimeSeriesBarChart, type TimeSeriesBarChartConfig } from '@posthog/quill-charts'+import {+ type ChartTheme,+ type Series,+ type TimeInterval,+ TimeSeriesBarChart,+ type TimeSeriesBarChartConfig,+} from '@posthog/quill-charts'import { Skeleton } from '@posthog/quill-primitives'import { type ToolDailySeries } from '../mcpDashboardOverviewLogic'@@ -11,11 +17,13 @@ export function ToolUsageChart({loading,theme,timezone,+ interval,}: {data: ToolDailySeriesloading: booleantheme: ChartThemetimezone: string+ interval: TimeInterval}): JSX.Element {const series = useMemo<Series[]>(() =>@@ -33,14 +41,14 @@ export function ToolUsageChart({barCornerRadius: 2,yAxis: { showGrid: false },showAxisLines: true,- xAxis: { interval: 'day', timezone },+ xAxis: { interval, timezone },tooltip: { placement: 'cursor' },}),- [timezone]+ [timezone, interval])return (- <Card title="Daily breakdown of tool calls">+ <Card title="Tool call breakdown"><CardStateloading={loading}isEmpty={data.labels.length === 0}diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.tsindex 9153ddf2619f..63467cfb795c 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts@@ -397,8 +397,8 @@ ORDER BY day},})),- actionToUrl(({ values }) => ({- setSelectedTool: () => {+ actionToUrl(({ values }) => {+ const syncUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {const { currentLocation } = router.valuesconst searchParams = { ...currentLocation.searchParams }if (values.selectedTool) {@@ -406,9 +406,23 @@ ORDER BY day} else {delete searchParams.tool}+ if (values.dateFilter.dateFrom) {+ searchParams.date_from = values.dateFilter.dateFrom+ } else {+ delete searchParams.date_from+ }+ if (values.dateFilter.dateTo) {+ searchParams.date_to = values.dateFilter.dateTo+ } else {+ delete searchParams.date_to+ }return [currentLocation.pathname, searchParams, currentLocation.hashParams, { replace: true }]- },- })),+ }+ return {+ setSelectedTool: syncUrl,+ setDateFilter: syncUrl,+ }+ }),urlToAction(({ actions, values }) => ({[urls.mcpAnalyticsToolQuality()]: (_, searchParams) => {@@ -416,6 +430,12 @@ ORDER BY dayif (tool !== values.selectedTool) {actions.setSelectedTool(tool)}+ const dateFrom =+ typeof searchParams.date_from === 'string' ? searchParams.date_from : values.dateFilter.dateFrom+ const dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : null+ if (dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo) {+ actions.setDateFilter(dateFrom, dateTo)+ }},})),diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.tsindex 1f967bc538bb..2e6cdc202b9b 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts@@ -1,16 +1,33 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+import { dayjs } from 'lib/dayjs'++import { initKeaTests } from '~/test/init'+import {aggregateHarnessRows,type BucketRow,buildKPIs,+ buildKpiWindow,buildToolDailySeries,categorizeHarness,deltaPct,type HarnessRawRow,+ mcpDashboardOverviewLogic,pickNotableSessions,type SessionRow,type ToolDailyRow,} from './mcpDashboardOverviewLogic'+jest.mock('lib/api')+jest.mock('./generated/api', () => ({+ mcpAnalyticsIntentClustersRetrieve: jest.fn().mockResolvedValue({ status: 'idle', clusters: [] }),+ mcpAnalyticsIntentClustersRecompute: jest.fn(),+}))++const mockApi = api as jest.Mocked<typeof api>+function session(overrides: Partial<SessionRow> & { session_id: string }): SessionRow {return {tool_calls: 0,@@ -23,7 +40,7 @@ function session(overrides: Partial<SessionRow> & { session_id: string }): Sessi}}-describe('mcpDashboardOverviewLogic helpers', () => {+describe('mcpDashboardOverviewLogic', () => {describe('categorizeHarness', () => {it.each([['claude-code/1.0.0', 'Claude Code'],@@ -115,14 +132,52 @@ describe('mcpDashboardOverviewLogic helpers', () => {})})+ describe('buildKpiWindow', () => {+ it.each([+ ['2024-01-08', '2024-01-15', 'day', '2024-01-08 00:00:00', '2023-12-31'],+ ['2024-01-01', '2024-01-31', 'day', '2024-01-01 00:00:00', '2023-12-01'],+ ])(+ 'extends [%s, %s] back to an equal-length prior window with cutoff at the selected start',+ (dateFrom, dateTo, interval, expectedCutoff, expectedPriorStart) => {+ const window = buildKpiWindow({ dateFrom, dateTo }, 'UTC', interval as 'day')+ expect(window.currentStartBucket).toBe(expectedCutoff)+ expect(dayjs(window.dateFrom).format('YYYY-MM-DD')).toBe(expectedPriorStart)+ }+ )++ it('rolls an hour-level range from now and steps the prior window back equally', () => {+ jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:30:00Z'))+ try {+ // "-1h" resolves to the trailing hour; prior window is the hour before that.+ const window = buildKpiWindow({ dateFrom: '-1h', dateTo: null }, 'UTC', 'minute')+ expect(window.currentStartBucket).toBe('2026-06-18 11:30:00')+ expect(dayjs(window.dateFrom).toISOString()).toBe('2026-06-18T10:29:00.000Z')+ } finally {+ jest.useRealTimers()+ }+ })++ it('resolves the relative -7d default against now', () => {+ jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:00:00Z'))+ try {+ const window = buildKpiWindow({ dateFrom: '-7d', dateTo: null }, 'UTC', 'day')+ expect(window.currentStartBucket).toBe('2026-06-11 00:00:00')+ // doubled window: prior 8 day-buckets before the cutoff+ expect(dayjs(window.dateFrom).format('YYYY-MM-DD')).toBe('2026-06-03')+ } finally {+ jest.useRealTimers()+ }+ })+ })+describe('buildKPIs', () => {it('splits current vs prior buckets and computes values, deltas, and sparklines', () => {const rows: BucketRow[] = [- { bucket: '2024-01-09', sessions: 20, tool_calls: 200, errors: 15, p95: 300, in_current: true },- { bucket: '2024-01-08', sessions: 10, tool_calls: 100, errors: 5, p95: 200, in_current: true },- { bucket: '2024-01-01', sessions: 5, tool_calls: 50, errors: 5, p95: 150, in_current: false },+ { bucket: '2024-01-09', sessions: 20, tool_calls: 200, errors: 15, p95: 300 },+ { bucket: '2024-01-08', sessions: 10, tool_calls: 100, errors: 5, p95: 200 },+ { bucket: '2024-01-01', sessions: 5, tool_calls: 50, errors: 5, p95: 150 },]- const kpis = buildKPIs(rows)+ const kpis = buildKPIs(rows, '2024-01-08')expect(kpis.sessions).toEqual({value: 30,@@ -149,10 +204,8 @@ describe('mcpDashboardOverviewLogic helpers', () => {})it('returns null deltas when there is no prior-period data', () => {- const rows: BucketRow[] = [- { bucket: '2024-01-08', sessions: 10, tool_calls: 100, errors: 0, p95: 200, in_current: true },- ]- expect(buildKPIs(rows).sessions.deltaPct).toBeNull()+ const rows: BucketRow[] = [{ bucket: '2024-01-08', sessions: 10, tool_calls: 100, errors: 0, p95: 200 }]+ expect(buildKPIs(rows, '2024-01-08').sessions.deltaPct).toBeNull()})})@@ -217,4 +270,38 @@ describe('mcpDashboardOverviewLogic helpers', () => {expect(new Set(picked.map((p) => p.session.session_id)).size).toBe(5)})})++ describe('date filter wiring', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ initKeaTests()+ jest.spyOn(mockApi, 'query').mockResolvedValue({ results: [] } as any)+ })++ function reloadCallsSince(callIndex: number): { query: string; filters: Record<string, any> }[] {+ return mockApi.query.mock.calls.slice(callIndex).map((call) => call[0] as any)+ }++ it('reloads every tile when the date filter changes', async () => {+ const logic = mcpDashboardOverviewLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const callsBefore = mockApi.query.mock.calls.length++ await expectLogic(logic, () => {+ logic.actions.setDateFilter('-30d', null)+ }).toFinishAllListeners()++ const reloads = reloadCallsSince(callsBefore)+ // Six tiles: KPI + the five breakdown queries.+ expect(reloads.length).toBe(6)+ // The five breakdowns pass the raw selected range straight through.+ const breakdowns = reloads.filter((call) => call.filters.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.+ 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)+ })+ })})diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.tsindex 280cd87391da..573e59e9b94b 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts@@ -1,38 +1,50 @@-import { afterMount, connect, kea, path, selectors } from 'kea'+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { actionToUrl, router, urlToAction } from 'kea-router'-import { hogqlQuery } from '~/queries/query'-import { hogql } from '~/queries/utils'+import api from 'lib/api'+import { dayjs } from 'lib/dayjs'+import { dateStringToComponents, dateStringToDayJs, getDefaultInterval } from 'lib/utils/dateFilters'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { HogQLFilters, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'+import { IntervalType } from '~/types'import { mcpClusteringLogic } from './clustering/mcpClusteringLogic'import type { MCPIntentClusterApi } from './generated/api.schemas'import type { mcpDashboardOverviewLogicType } from './mcpDashboardOverviewLogicType'-// KPI tiles compare this week against the prior week.-const LOOKBACK_DAYS = 7-// Breakdowns and trends (activity, tools, harnesses, notable sessions) use a longer 30-day window.-const BREAKDOWN_DAYS = 30+export interface DateFilter {+ dateFrom: string | null+ dateTo: string | null+}++const DEFAULT_DATE_FILTER: DateFilter = { dateFrom: '-7d', dateTo: null }-const KPI_QUERY = hogql`+// KPI tiles compare the selected window against the immediately preceding window+// of equal length. The current/previous split is applied in `buildKPIs` against+// the time buckets, so the query only needs the doubled date range. `__BUCKET__`+// is replaced with a dateTrunc at the active interval at call time.+const KPI_QUERY = `SELECT- toDate(timestamp) AS bucket,+ __BUCKET__ AS bucket,countDistinctIf(toString(properties.$mcp_session_id), toString(properties.$mcp_session_id) != '') AS sessions,count() AS tool_calls,countIf(toBool(properties.$mcp_is_error)) AS errors,- round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95,- timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS))} DAY AS in_current+ round(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95FROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL ${hogql.raw(String(LOOKBACK_DAYS * 2))} DAYAND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''-GROUP BY bucket, in_current+ AND {filters}+GROUP BY bucketORDER BY bucket`// Per-session rollup powering the Notable sessions block. The selector// applies fixed rules over this set; no per-rule SQL.-const SESSION_ROWS_QUERY = hogql`+const SESSION_ROWS_QUERY = `SELECTtoString(properties.$mcp_session_id) AS session_id,count() AS tool_calls,@@ -43,11 +55,11 @@ SELECTmax(timestamp) AS last_seenFROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAYAND properties.$mcp_session_id IS NOT NULLAND properties.$mcp_session_id != ''AND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''+ AND {filters}GROUP BY session_idHAVING tool_calls >= 1ORDER BY tool_calls DESC@@ -56,7 +68,7 @@ LIMIT 500// Mirrors products/mcp_analytics/backend/templates/tool_quality.sql for the// compact reliability matrix on the overview. Limited columns + 50 rows.-const TOOL_ROWS_QUERY = hogql`+const TOOL_ROWS_QUERY = `SELECTtoString(properties.$mcp_tool_name) AS tool,count() AS total_calls,@@ -65,15 +77,15 @@ SELECTround(quantile(0.95)(toFloat(properties.$mcp_duration_ms))) AS p95_duration_msFROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAYAND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''+ AND {filters}GROUP BY toolORDER BY total_calls DESCLIMIT 50`-const HARNESS_ROWS_QUERY = hogql`+const HARNESS_ROWS_QUERY = `SELECTtoString(properties.$mcp_client_name) AS client,count() AS total_calls,@@ -81,40 +93,40 @@ SELECTcountDistinctIf(toString(properties.$mcp_session_id), toString(properties.$mcp_session_id) != '') AS sessionsFROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAYAND properties.$mcp_client_name IS NOT NULLAND properties.$mcp_client_name != ''+ AND {filters}GROUP BY clientORDER BY total_calls DESCLIMIT 200`// Daily success/error split powering the activity time-series bar chart.-const ACTIVITY_QUERY = hogql`+const ACTIVITY_QUERY = `SELECT- toDate(timestamp) AS day,+ __BUCKET__ AS day,countIf(NOT toBool(properties.$mcp_is_error)) AS successes,countIf(toBool(properties.$mcp_is_error)) AS errorsFROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAYAND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''+ AND {filters}GROUP BY dayORDER BY day`// Daily call counts per tool, powering the tool-usage stacked bar (one segment per tool).-const TOOL_DAILY_QUERY = hogql`+const TOOL_DAILY_QUERY = `SELECT- toDate(timestamp) AS day,+ __BUCKET__ AS day,toString(properties.$mcp_tool_name) AS tool,count() AS callsFROM eventsWHERE event = 'mcp_tool_call'- AND timestamp >= now() - INTERVAL ${hogql.raw(String(BREAKDOWN_DAYS))} DAYAND properties.$mcp_tool_name IS NOT NULLAND properties.$mcp_tool_name != ''+ AND {filters}GROUP BY day, toolORDER BY dayLIMIT 10000@@ -126,7 +138,6 @@ export interface BucketRow {tool_calls: numbererrors: numberp95: number- in_current: boolean}export interface KPIMetric {@@ -330,6 +341,46 @@ export function deltaPct(current: number, previous: number): number | null {return ((current - previous) / previous) * 100}+// Resolve the filter to absolute bounds. Hour-level relative ranges ("-1h") are+// rolling from now; dateStringToDayJs anchors relative dates to the start of the+// day, which would inflate a "last hour" window to half a day. Day+ ranges keep+// that start-of-day anchoring (the established behaviour).+function resolveWindow(dateFilter: DateFilter, timezone: string): { start: dayjs.Dayjs; end: dayjs.Dayjs } {+ const now = dayjs().tz(timezone)+ const end = (dateFilter.dateTo ? dateStringToDayJs(dateFilter.dateTo, timezone) : now) ?? now+ const components = dateStringToComponents(dateFilter.dateFrom)+ if (components && components.unit === 'hour' && !dateFilter.dateTo) {+ // components.amount is signed (negative for the past), so add() walks backwards.+ return { start: now.add(components.amount, 'hour'), end: now }+ }+ const start = dateStringToDayJs(dateFilter.dateFrom, timezone) ?? now.subtract(7, 'day')+ return { start, end }+}++export interface KpiWindow {+ dateFrom: string+ dateTo: string+ currentStartBucket: string+}++// Extend the resolved window back by an equal number of `interval` buckets so a+// single query returns both the selected period and its prior period.+// `currentStartBucket` is the cutoff `buildKPIs` splits on — formatted to match+// dateTrunc's DateTime output.+export function buildKpiWindow(dateFilter: DateFilter, timezone: string, interval: IntervalType): KpiWindow {+ const { start, end } = resolveWindow(dateFilter, timezone)+ // The selected period covers the inclusive buckets [start, end] — one more than+ // end.diff(start). Step the prior window back by that same count so the two+ // halves of the comparison span an equal number of buckets.+ const selectedBuckets = Math.max(1, end.diff(start, interval) + 1)+ const priorStart = start.subtract(selectedBuckets, interval)+ return {+ dateFrom: priorStart.toISOString(),+ dateTo: end.toISOString(),+ currentStartBucket: start.startOf(interval).format('YYYY-MM-DD HH:mm:ss'),+ }+}+function parseRows(rawRows: unknown[][]): BucketRow[] {return rawRows.map((r) => ({bucket: String(r[0]),@@ -337,13 +388,14 @@ function parseRows(rawRows: unknown[][]): BucketRow[] {tool_calls: Number(r[2] ?? 0),errors: Number(r[3] ?? 0),p95: Number(r[4] ?? 0),- in_current: Boolean(r[5]),}))}-export function buildKPIs(rows: BucketRow[]): KPIData {- const current = rows.filter((r) => r.in_current).sort((a, b) => a.bucket.localeCompare(b.bucket))- const previous = rows.filter((r) => !r.in_current)+// Buckets at or after `currentStartBucket` belong to the selected window; the+// rest are the equal-length window immediately before it.+export function buildKPIs(rows: BucketRow[], currentStartBucket: string): KPIData {+ const current = rows.filter((r) => r.bucket >= currentStartBucket).sort((a, b) => a.bucket.localeCompare(b.bucket))+ const previous = rows.filter((r) => r.bucket < currentStartBucket)const curSessions = current.reduce((acc, r) => acc + r.sessions, 0)const curCalls = current.reduce((acc, r) => acc + r.tool_calls, 0)@@ -393,24 +445,51 @@ export function buildKPIs(rows: BucketRow[]): KPIData {export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([path(['products', 'mcp_analytics', 'frontend', 'mcpDashboardOverviewLogic']),connect(() => ({- values: [mcpClusteringLogic, ['clusters', 'hasSnapshot']],+ values: [mcpClusteringLogic, ['clusters', 'hasSnapshot'], teamLogic, ['timezone']],})),- loaders({+ actions({+ setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),+ reloadAll: true,+ }),+ reducers({+ dateFilter: [+ DEFAULT_DATE_FILTER,+ {+ setDateFilter: (_, { dateFrom, dateTo }): DateFilter => ({ dateFrom, dateTo }),+ },+ ],+ }),+ loaders(({ values }) => ({kpis: [EMPTY_KPIS,{- loadKPIs: async () => {- const response = await hogqlQuery(KPI_QUERY)+ loadKPIs: async (_: void, breakpoint) => {+ const { interval } = values+ const kpiWindow = buildKpiWindow(values.dateFilter, values.timezone, interval)+ 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 },+ },+ })) as HogQLQueryResponse+ breakpoint()const rows = parseRows((response?.results as unknown[][]) ?? [])- return buildKPIs(rows)+ return buildKPIs(rows, kpiWindow.currentStartBucket)},},],toolRows: [[] as ToolRow[],{- loadToolRows: async () => {- const response = await hogqlQuery(TOOL_ROWS_QUERY)+ loadToolRows: async (_: void, breakpoint) => {+ const response = (await api.query({+ kind: NodeKind.HogQLQuery,+ query: TOOL_ROWS_QUERY,+ filters: values.queryFilters,+ })) as HogQLQueryResponse+ breakpoint()const raw = (response?.results as unknown[][]) ?? []return raw.map((r) => ({tool: String(r[0] ?? ''),@@ -425,8 +504,13 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([sessionRows: [[] as SessionRow[],{- loadSessionRows: async () => {- const response = await hogqlQuery(SESSION_ROWS_QUERY)+ loadSessionRows: async (_: void, breakpoint) => {+ const response = (await api.query({+ kind: NodeKind.HogQLQuery,+ query: SESSION_ROWS_QUERY,+ filters: values.queryFilters,+ })) as HogQLQueryResponse+ breakpoint()const raw = (response?.results as unknown[][]) ?? []return raw.map((r) => ({session_id: String(r[0] ?? ''),@@ -443,8 +527,13 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([harnessRawRows: [[] as HarnessRawRow[],{- loadHarnessRows: async () => {- const response = await hogqlQuery(HARNESS_ROWS_QUERY)+ loadHarnessRows: async (_: void, breakpoint) => {+ const response = (await api.query({+ kind: NodeKind.HogQLQuery,+ query: HARNESS_ROWS_QUERY,+ filters: values.queryFilters,+ })) as HogQLQueryResponse+ breakpoint()const raw = (response?.results as unknown[][]) ?? []return raw.map((r) => ({client: String(r[0] ?? ''),@@ -458,8 +547,13 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([activityRows: [[] as ActivityRow[],{- loadActivityRows: async (): Promise<ActivityRow[]> => {- const response = await hogqlQuery(ACTIVITY_QUERY)+ loadActivityRows: async (_: void, breakpoint): Promise<ActivityRow[]> => {+ const response = (await api.query({+ kind: NodeKind.HogQLQuery,+ query: ACTIVITY_QUERY.replace('__BUCKET__', `dateTrunc('${values.interval}', timestamp)`),+ filters: values.queryFilters,+ })) as HogQLQueryResponse+ breakpoint()const raw = (response?.results as unknown[][]) ?? []return raw.map((r) => ({day: String(r[0] ?? ''),@@ -472,8 +566,13 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([toolDailyRows: [[] as ToolDailyRow[],{- loadToolDailyRows: async (): Promise<ToolDailyRow[]> => {- const response = await hogqlQuery(TOOL_DAILY_QUERY)+ loadToolDailyRows: async (_: void, breakpoint): Promise<ToolDailyRow[]> => {+ const response = (await api.query({+ kind: NodeKind.HogQLQuery,+ query: TOOL_DAILY_QUERY.replace('__BUCKET__', `dateTrunc('${values.interval}', timestamp)`),+ filters: values.queryFilters,+ })) as HogQLQueryResponse+ breakpoint()const raw = (response?.results as unknown[][]) ?? []return raw.map((r) => ({day: String(r[0] ?? ''),@@ -483,8 +582,18 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([},},],- }),+ })),selectors({+ queryFilters: [+ (s) => [s.dateFilter],+ (dateFilter: DateFilter): HogQLFilters => ({+ dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },+ }),+ ],+ interval: [+ (s) => [s.dateFilter],+ (dateFilter: DateFilter): IntervalType => getDefaultInterval(dateFilter.dateFrom, dateFilter.dateTo),+ ],harnessRows: [(s) => [s.harnessRawRows], (raw: HarnessRawRow[]): HarnessRow[] => aggregateHarnessRows(raw)],dailyActivity: [(s) => [s.activityRows],@@ -513,13 +622,62 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([}),],}),- afterMount(({ actions }) => {- actions.loadKPIs()- actions.loadToolRows()- actions.loadSessionRows()- actions.loadHarnessRows()- actions.loadActivityRows()- actions.loadToolDailyRows()+ listeners(({ actions }) => ({+ setDateFilter: () => {+ actions.reloadAll()+ },+ reloadAll: () => {+ actions.loadKPIs()+ actions.loadToolRows()+ actions.loadSessionRows()+ actions.loadHarnessRows()+ actions.loadActivityRows()+ actions.loadToolDailyRows()+ },+ })),+ actionToUrl(({ values }) => ({+ setDateFilter: () => {+ const { currentLocation } = router.values+ const searchParams = { ...currentLocation.searchParams }+ if (values.dateFilter.dateFrom) {+ searchParams.date_from = values.dateFilter.dateFrom+ } else {+ delete searchParams.date_from+ }+ if (values.dateFilter.dateTo) {+ searchParams.date_to = values.dateFilter.dateTo+ } else {+ delete searchParams.date_to+ }+ return [currentLocation.pathname, searchParams, currentLocation.hashParams, { replace: true }]+ },+ })),+ urlToAction(({ actions, values, cache }) => ({+ [urls.mcpAnalyticsDashboard()]: (_, searchParams) => {+ const dateFrom =+ typeof searchParams.date_from === 'string' ? searchParams.date_from : DEFAULT_DATE_FILTER.dateFrom+ const dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : null+ if (dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo) {+ // setDateFilter's listener reloads everything.+ actions.setDateFilter(dateFrom, dateTo)+ } else if (!cache.hasLoaded) {+ // URL already matches state (e.g. default window) and afterMount deferred — load once here.+ actions.reloadAll()+ }+ cache.hasLoaded = true+ },+ })),+ afterMount(({ actions, cache }) => {+ // urlToAction owns the initial load whenever the dashboard URL carries filter+ // params; this is the fallback for a param-less mount (and off-route mounts in+ // tests, where urlToAction never fires). The cache.hasLoaded guard keeps a+ // deep-linked load from firing twice.+ const { searchParams } = router.values+ const hasUrlFilters = typeof searchParams.date_from === 'string' || typeof searchParams.date_to === 'string'+ if (!hasUrlFilters && !cache.hasLoaded) {+ cache.hasLoaded = true+ actions.reloadAll()+ }}),])