Skip to content

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

feat(mcp-analytics): add a grouping interval picker to Tool quality (#81367)

Radu Raiceac20c88e816a2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index bc57de430e62..397fe9969035 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6675,7 +6675,7 @@ snapshots:
scenes-app-mcp-analytics--sessions--light:
hash: v1.k794b7964.8a6b42b3e994bb9f035951d84f071f2d7c20756f9745281f61e3383133bd5bb5.GxtTX98b-FQFH6zFqQLhs-oEq7qO_vVqKjJS-CBN77U
scenes-app-mcp-analytics--tool-quality--dark:
- hash: v1.k794b7964.d4227f0ef61e4a1f092fde543c1a8dc62f0f05e0488f2b15fc9f3c3f902954e8.DsFDnzZRkS66upVNo75VlLqrgFFhXOXF8aJVLUtBZ1s
+ hash: v1.k794b7964.1a048a30aaedf592d08fb4a1a84d74d722e0afcdb9c72c1a001890f28530b50b.05NkieX3K7vPDZ5lVm_K5o7azAn1_9755fgJk77I9oo
scenes-app-mcp-analytics--tool-quality--light:
hash: v1.k794b7964.04a9b39c28f16ad4b5a1b2625115e68768273cc7b66548fcbc5754a8f48aaac6.varhLyKH9GufBWEUlArceEOjryAzqMHvXgGzy-6VecY
scenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--dark:
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
index 0288442637c2..3ab53d1c8093 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
@@ -504,6 +504,7 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.
dateRangeLabel,
dateFilter,
interval,
+ pinnedInterval,
incompleteTail,
} = useValues(mcpAnalyticsToolDetailLogic({ toolName }))
const { selectFailure } = useActions(mcpAnalyticsToolDetailLogic({ toolName }))
@@ -532,7 +533,7 @@ function MCPAnalyticsToolDetailContent({ toolName }: { toolName: string }): JSX.
resourceType={{ type: 'mcp_analytics' }}
forceBackTo={{
name: 'Tool quality',
- path: mcpToolQualityUrlWithDates(dateFilter),
+ path: mcpToolQualityUrlWithDates(dateFilter, pinnedInterval),
key: 'mcp-analytics-tool-quality',
}}
/>
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx
index b9f375ff2526..902bc27e94d7 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolQuality.tsx
@@ -10,14 +10,22 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { teamLogic } from 'scenes/teamLogic'
import { McpDateFilter } from './components/McpDateFilter'
+import { McpIntervalFilter } from './components/McpIntervalFilter'
import { mcpAnalyticsToolQualityLogic, mcpToolReportUrl } from './mcpAnalyticsToolQualityLogic'
import { ToolQualityCharts } from './tool-quality/ToolQualityCharts'
import { ToolQualityTable } from './tool-quality/ToolQualityTable'
function FilterBar(): JSX.Element {
- const { availableCategories, selectedCategories, scopeShare, dateFilter, dateRangeLabel } =
- useValues(mcpAnalyticsToolQualityLogic)
- const { setSelectedCategories, setDateFilter } = useActions(mcpAnalyticsToolQualityLogic)
+ const {
+ availableCategories,
+ selectedCategories,
+ scopeShare,
+ dateFilter,
+ dateRangeLabel,
+ interval,
+ intervalOptions,
+ } = useValues(mcpAnalyticsToolQualityLogic)
+ const { setSelectedCategories, setDateFilter, setPinnedInterval } = useActions(mcpAnalyticsToolQualityLogic)
const hasScope = selectedCategories.length > 0
const sharePct = scopeShare.pct === null ? null : Math.round(scopeShare.pct * 10) / 10
@@ -40,6 +48,12 @@ function FilterBar(): JSX.Element {
onChange={(dateFrom, dateTo) => setDateFilter(dateFrom, dateTo)}
dataAttr="mcp-tool-quality-date-filter"
/>
+ <McpIntervalFilter
+ interval={interval}
+ options={intervalOptions}
+ onChange={setPinnedInterval}
+ dataAttr="mcp-tool-quality-interval-filter"
+ />
{hasScope && sharePct !== null ? (
<Tooltip
title={`${scopeShare.inScope.toLocaleString()} of ${scopeShare.total.toLocaleString()} MCP tool calls were in the selected categories (${dateRangeLabel})`}
@@ -54,7 +68,7 @@ function FilterBar(): JSX.Element {
}
function ChartsScopeHeader(): JSX.Element {
- const { selectedTool, dateFilter } = useValues(mcpAnalyticsToolQualityLogic)
+ const { selectedTool, dateFilter, pinnedInterval } = useValues(mcpAnalyticsToolQualityLogic)
const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)
if (!selectedTool) {
@@ -74,7 +88,7 @@ function ChartsScopeHeader(): JSX.Element {
<Button
variant="outline"
size="sm"
- render={<LinkPrimitive to={mcpToolReportUrl(selectedTool, dateFilter)} />}
+ render={<LinkPrimitive to={mcpToolReportUrl(selectedTool, dateFilter, pinnedInterval)} />}
data-attr="mcp-tool-quality-full-report"
>
Full tool report
diff --git a/products/mcp_analytics/frontend/components/McpIntervalFilter.tsx b/products/mcp_analytics/frontend/components/McpIntervalFilter.tsx
new file mode 100644
index 000000000000..cd4272a23dc8
--- /dev/null
+++ b/products/mcp_analytics/frontend/components/McpIntervalFilter.tsx
@@ -0,0 +1,37 @@
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@posthog/quill-primitives'
+
+import { IntervalType } from '~/types'
+
+import { type IntervalOption } from '../timeBuckets'
+
+interface McpIntervalFilterProps {
+ interval: IntervalType
+ options: IntervalOption[]
+ onChange: (interval: IntervalType) => void
+ dataAttr: string
+}
+
+export function McpIntervalFilter({ interval, options, onChange, dataAttr }: McpIntervalFilterProps): JSX.Element {
+ return (
+ <div className="flex items-center gap-2" data-quill>
+ <span className="text-sm text-secondary">Grouped by</span>
+ <Select value={interval} onValueChange={(value) => onChange(value as IntervalType)}>
+ <SelectTrigger data-attr={dataAttr}>
+ <SelectValue>
+ {(value: IntervalType) => options.find((option) => option.value === value)?.label ?? value}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value} disabled={!!option.disabledReason}>
+ <span className="flex-1">{option.label}</span>
+ {option.disabledReason ? (
+ <span className="text-xs text-secondary">{option.disabledReason}</span>
+ ) : null}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )
+}
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
index 31b26708bfc1..e0db4a44a02b 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
@@ -4,7 +4,7 @@ import { urlToAction } from 'kea-router'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { dateFilterToText, dateStringToDayJs, getDefaultInterval } from 'lib/utils/dateFilters'
+import { dateFilterToText, dateStringToDayJs } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -23,7 +23,13 @@ import {
} from '~/queries/schema/schema-general'
import { IntervalType } from '~/types'
-import { buildBucketKeys, lastBucketIsInProgress, normalizeBucket } from './timeBuckets'
+import {
+ buildBucketKeys,
+ lastBucketIsInProgress,
+ normalizeBucket,
+ parseIntervalParam,
+ resolveInterval,
+} from './timeBuckets'
export interface ToolSummary {
calls: number
errors: number
@@ -151,6 +157,7 @@ export interface mcpAnalyticsToolDetailLogicValues {
neighborsAfterRowsLoading: boolean
neighborsBeforeRows: ResultRows
neighborsBeforeRowsLoading: boolean
+ pinnedInterval: IntervalType | null
sampleIntentRows: ResultRows
sampleIntentRowsLoading: boolean
selectedFailure: MCPToolFailureItem | null
@@ -341,6 +348,9 @@ export interface mcpAnalyticsToolDetailLogicActions {
dateFrom: string | null
dateTo: string | null
}
+ setPinnedInterval: (interval: IntervalType | null) => {
+ interval: IntervalType | null
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -355,7 +365,7 @@ export interface mcpAnalyticsToolDetailLogicMeta {
timezone: string
) => DailyChartData
incompleteTail: (dailyChartData: DailyChartData, interval: IntervalType, timezone: string) => boolean
- interval: (dateFilter: DateFilter) => IntervalType
+ interval: (dateFilter: DateFilter, pinnedInterval: IntervalType | null, timezone: string) => IntervalType
dateRange: (dateFilter: DateFilter, timezone: string) => DateRange
dateRangeLabel: (dateFilter: DateFilter) => string
}
@@ -375,6 +385,7 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
actions({
setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
+ setPinnedInterval: (interval: IntervalType | null) => ({ interval }),
loadAllSections: true,
selectFailure: (bucket: MCPToolFailureItem | null) => ({ bucket }),
}),
@@ -386,6 +397,14 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
setDateFilter: (_, { dateFrom, dateTo }): DateFilter => ({ dateFrom, dateTo }),
},
],
+ // Grouping picked on the Tool quality tab and carried here in the URL; null follows the
+ // auto-choice for the window. This page has no picker of its own.
+ pinnedInterval: [
+ null as IntervalType | null,
+ {
+ setPinnedInterval: (_, { interval }): IntervalType | null => interval,
+ },
+ ],
}),
loaders(({ props, values }) => ({
@@ -626,11 +645,13 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
lastBucketIsInProgress(dailyChartData.labels, timezone, interval),
],
- // Grouping interval for the daily series — PostHog's standard auto-choice, matching the query's
- // dateTrunc so a sub-day window buckets by hour/minute instead of collapsing to one day point.
+ // Grouping interval for the daily series, matching the query's dateTrunc: the interval pinned on
+ // the Tool quality tab, else the auto-choice so a sub-day window buckets by hour/minute instead
+ // of collapsing to one day point.
interval: [
- (s) => [s.dateFilter],
- (dateFilter: DateFilter): IntervalType => getDefaultInterval(dateFilter.dateFrom, dateFilter.dateTo),
+ (s) => [s.dateFilter, s.pinnedInterval, teamLogic.selectors.timezone],
+ (dateFilter: DateFilter, pinnedInterval: IntervalType | null, timezone: string): IntervalType =>
+ resolveInterval(dateFilter.dateFrom, dateFilter.dateTo, timezone, pinnedInterval),
],
// Resolve the `dateFilter` state (camelCase, nullable, may be relative like '-30d') into the
@@ -668,9 +689,10 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
},
})),
- // The window rides along in the URL from the Tool quality tab. Reading it here (rather than once
- // in afterMount) keeps the page in sync when only date_from / date_to change for the same tool —
- // e.g. browser back/forward — since the logic is keyed by toolName and wouldn't remount.
+ // The window and grouping ride along in the URL from the Tool quality tab. Reading them here
+ // (rather than once in afterMount) keeps the page in sync when only date_from / date_to / interval
+ // change for the same tool — e.g. browser back/forward — since the logic is keyed by toolName and
+ // wouldn't remount.
urlToAction(({ actions, values, cache }) => ({
[`${urls.mcpAnalyticsToolQuality()}/:toolName`]: (_, searchParams) => {
const dateFrom =
@@ -680,8 +702,17 @@ export const mcpAnalyticsToolDetailLogic = kea<mcpAnalyticsToolDetailLogicType>(
if (dateChanged) {
actions.setDateFilter(dateFrom, dateTo)
}
+ const interval = parseIntervalParam(searchParams.interval)
+ const intervalChanged = interval !== values.pinnedInterval
+ if (intervalChanged) {
+ actions.setPinnedInterval(interval)
+ }
if (dateChanged || !cache.hasLoaded) {
actions.loadAllSections()
+ } else if (intervalChanged) {
+ // Only the trend series buckets by interval; every other section is a single-window
+ // aggregate that a grouping change cannot move.
+ actions.loadDailyStats()
}
cache.hasLoaded = true
},
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts
index f46050ca6054..636890e5a285 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.test.ts
@@ -188,5 +188,35 @@ describe('mcpAnalyticsToolQualityLogic', () => {
expect(logic.values.selectedTool).toBe('tool_a')
})
+
+ it('refetches the charts at the picked grouping, leaving the table alone', async () => {
+ const logic = mcpAnalyticsToolQualityLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const callsBefore = mockApi.query.mock.calls.length
+
+ await expectLogic(logic, () => {
+ logic.actions.setPinnedInterval('hour')
+ }).toFinishAllListeners()
+
+ const newCalls = queryCallsSince(callsBefore)
+ expect(newCalls.length).toBe(1) // daily stats only — the table is a single-window aggregate
+ expect(newCalls[0].interval).toBe('hour')
+ })
+
+ // The two filters are independent: changing the window must not silently undo the grouping.
+ it('keeps the picked grouping when the date range changes', async () => {
+ const logic = mcpAnalyticsToolQualityLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setPinnedInterval('hour')
+ await expectLogic(logic, () => {
+ logic.actions.setDateFilter('-14d', null)
+ }).toFinishAllListeners()
+
+ // Two weeks would auto-group by day.
+ expect(logic.values.interval).toBe('hour')
+ })
})
})
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
index 8a05ae60a912..55e238b05e41 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
-import { dateFilterToText, getDefaultInterval } from 'lib/utils/dateFilters'
+import { dateFilterToText } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -16,7 +16,15 @@ import {
} from '~/queries/schema/schema-general'
import { IntervalType } from '~/types'
-import { buildBucketKeys, lastBucketIsInProgress, normalizeBucket } from './timeBuckets'
+import {
+ type IntervalOption,
+ buildBucketKeys,
+ intervalOptionsForWindow,
+ lastBucketIsInProgress,
+ normalizeBucket,
+ parseIntervalParam,
+ resolveInterval,
+} from './timeBuckets'
export interface CategoryCount {
category: string
@@ -41,9 +49,10 @@ export interface DateFilter {
dateTo: string | null
}
-// Carry the selected window across navigation as date_from / date_to, mirroring the tab's
-// actionToUrl. Only set them when present so a cleared range stays out of the URL.
-export function mcpDateSearchParams(dateFilter: DateFilter): Record<string, string> {
+// Carry the selected window across navigation as date_from / date_to, plus the grouping interval
+// when one is pinned, mirroring the tab's actionToUrl. Only set them when present so a cleared range
+// and an auto interval stay out of the URL.
+export function mcpDateSearchParams(dateFilter: DateFilter, interval?: IntervalType | null): Record<string, string> {
const params: Record<string, string> = {}
if (dateFilter.dateFrom) {
params.date_from = dateFilter.dateFrom
@@ -51,18 +60,21 @@ export function mcpDateSearchParams(dateFilter: DateFilter): Record<string, stri
if (dateFilter.dateTo) {
params.date_to = dateFilter.dateTo
}
+ if (interval) {
+ params.interval = interval
+ }
return params
}
-// Link from the Tool quality tab to an individual tool's report, keeping the date filter so
-// the tool page opens on the same window.
-export function mcpToolReportUrl(tool: string, dateFilter: DateFilter): string {
- return combineUrl(urls.mcpAnalyticsTool(tool), mcpDateSearchParams(dateFilter)).url
+// Link from the Tool quality tab to an individual tool's report, keeping the date filter and pinned
+// interval so the tool page opens on the same window and granularity.
+export function mcpToolReportUrl(tool: string, dateFilter: DateFilter, interval?: IntervalType | null): string {
+ return combineUrl(urls.mcpAnalyticsTool(tool), mcpDateSearchParams(dateFilter, interval)).url
}
-// Link back from a tool report to the Tool quality tab, restoring the date filter.
-export function mcpToolQualityUrlWithDates(dateFilter: DateFilter): string {
- return combineUrl(urls.mcpAnalyticsToolQuality(), mcpDateSearchParams(dateFilter)).url
+// Link back from a tool report to the Tool quality tab, restoring the date filter and interval.
+export function mcpToolQualityUrlWithDates(dateFilter: DateFilter, interval?: IntervalType | null): string {
+ return combineUrl(urls.mcpAnalyticsToolQuality(), mcpDateSearchParams(dateFilter, interval)).url
}
export interface ToolQualityRow {
@@ -148,6 +160,8 @@ export interface mcpAnalyticsToolQualityLogicValues {
filteredRows: ToolQualityRow[]
incompleteTail: boolean
interval: IntervalType
+ intervalOptions: IntervalOption[]
+ pinnedInterval: IntervalType | null
scopeShare: ScopeShare
searchTerm: string
selectedCategories: string[]
@@ -229,6 +243,9 @@ export interface mcpAnalyticsToolQualityLogicActions {
dateFrom: string | null
dateTo: string | null
}
+ setPinnedInterval: (interval: IntervalType | null) => {
+ interval: IntervalType | null
+ }
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
@@ -251,7 +268,8 @@ export interface mcpAnalyticsToolQualityLogicActions {
export interface mcpAnalyticsToolQualityLogicMeta {
__keaTypeGenInternalSelectorTypes: {
dateRangeLabel: (dateFilter: DateFilter) => string
- interval: (dateFilter: DateFilter) => IntervalType
+ intervalOptions: (dateFilter: DateFilter, timezone: string) => IntervalOption[]
+ interval: (dateFilter: DateFilter, pinnedInterval: IntervalType | null, timezone: string) => IntervalType
scopeShare: (categoryCounts: CategoryCount[], selectedCategories: string[]) => ScopeShare
filteredRows: (toolRows: ToolQualityRow[], toolQualitySort: SortState, searchTerm: string) => ToolQualityRow[]
dailyChartData: (
@@ -277,6 +295,7 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType
actions({
setToolQualitySort: (column: string, direction: SortDirection) => ({ column, direction }),
setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
+ setPinnedInterval: (interval: IntervalType | null) => ({ interval }),
setSelectedCategories: (categories: string[]) => ({ categories }),
setSelectedTool: (tool: string | null) => ({ tool }),
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
@@ -296,6 +315,15 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType
setDateFilter: (_, { dateFrom, dateTo }): DateFilter => ({ dateFrom, dateTo }),
},
],
+ // The grouping the user picked, kept independent of the window: null means follow the
+ // auto-choice for the range. It survives date changes so switching windows doesn't quietly
+ // undo the pin — `interval` drops back to auto only when the pin no longer fits.
+ pinnedInterval: [
+ null as IntervalType | null,
+ {
+ setPinnedInterval: (_, { interval }): IntervalType | null => interval,
+ },
+ ],
selectedCategories: [
[] as string[],
{
@@ -404,11 +432,18 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType
(dateFilter: DateFilter): string =>
dateFilterToText(dateFilter.dateFrom, dateFilter.dateTo, 'the selected range') ?? 'the selected range',
],
- // Grouping interval for the daily chart — PostHog's standard auto-choice, so a sub-day window
- // (e.g. last 12 hours) buckets hourly instead of collapsing to a single day point.
+ intervalOptions: [
+ (s) => [s.dateFilter, teamLogic.selectors.timezone],
+ (dateFilter: DateFilter, timezone: string): IntervalOption[] =>
+ intervalOptionsForWindow(dateFilter.dateFrom, dateFilter.dateTo, timezone),
+ ],
+ // Grouping interval for the charts: the pinned choice, or PostHog's standard auto-choice when
+ // none is pinned, so a sub-day window (e.g. last 12 hours) still buckets hourly by default
+ // instead of collapsing to a single day point.
interval: [
- (s) => [s.dateFilter],
- (dateFilter: DateFilter): IntervalType => getDefaultInterval(dateFilter.dateFrom, dateFilter.dateTo),
+ (s) => [s.dateFilter, s.pinnedInterval, teamLogic.selectors.timezone],
+ (dateFilter: DateFilter, pinnedInterval: IntervalType | null, timezone: string): IntervalType =>
+ resolveInterval(dateFilter.dateFrom, dateFilter.dateTo, timezone, pinnedInterval),
],
scopeShare: [
(s) => [s.categoryCounts, s.selectedCategories],
@@ -461,6 +496,10 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType
setSelectedCategories: () => {
actions.reloadAll()
},
+ // Only the charts bucket by interval; the table is a single-window aggregate.
+ setPinnedInterval: () => {
+ actions.loadDailyStats()
+ },
reloadAll: () => {
actions.loadToolRows()
actions.loadDailyStats()
@@ -501,11 +540,17 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType
} else {
delete searchParams.date_to
}
+ if (values.pinnedInterval) {
+ searchParams.interval = values.pinnedInterval
+ } else {
+ delete searchParams.interval
+ }
return [currentLocation.pathname, searchParams, currentLocation.hashParams, { replace: true }]
}
return {
setSelectedTool: syncUrl,
setDateFilter: syncUrl,
+ setPinnedInterval: syncUrl,
setSelectedCategories: syncUrl,
}
}),
@@ -530,6 +575,10 @@ export const mcpAnalyticsToolQualityLogic = kea<mcpAnalyticsToolQualityLogicType
if (dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo) {
actions.setDateFilter(dateFrom, dateTo)
}
+ const interval = parseIntervalParam(searchParams.interval)
+ if (interval !== values.pinnedInterval) {
+ actions.setPinnedInterval(interval)
+ }
},
})),
diff --git a/products/mcp_analytics/frontend/timeBuckets.test.ts b/products/mcp_analytics/frontend/timeBuckets.test.ts
index 23b95f1a9081..9b95310a07f7 100644
--- a/products/mcp_analytics/frontend/timeBuckets.test.ts
+++ b/products/mcp_analytics/frontend/timeBuckets.test.ts
@@ -1,6 +1,15 @@
import { dayjs } from 'lib/dayjs'
-import { buildBucketKeys, formatBucketLabel, lastBucketIsInProgress, normalizeBucket } from './timeBuckets'
+import { IntervalType } from '~/types'
+
+import {
+ buildBucketKeys,
+ formatBucketLabel,
+ intervalOptionsForWindow,
+ lastBucketIsInProgress,
+ normalizeBucket,
+ resolveInterval,
+} from './timeBuckets'
describe('timeBuckets', () => {
describe('normalizeBucket', () => {
@@ -133,4 +142,36 @@ describe('timeBuckets', () => {
expect(lastBucketIsInProgress(keys, 'Europe/Athens', 'day', now)).toBe(false)
})
})
+
+ describe('resolveInterval', () => {
+ // A pin outlives the window it was set on, so it has to give way once the window outgrows it:
+ // charting a year hour by hour also runs past the query's row limit, which drops the newest
+ // buckets. A pin that still fits has to beat the auto-choice — that's the point of pinning.
+ it.each([
+ ['-14d', 'hour', 'hour'], // 337 hourly buckets: fits
+ ['-1y', 'hour', 'month'], // 8761 hourly buckets: back to the auto-choice
+ ['-7d', 'month', 'day'], // shorter than one month: back to the auto-choice
+ ['-1y', 'day', 'day'], // 367 daily buckets: fits, and beats the auto-choice
+ ['-1y', null, 'month'], // nothing pinned: the auto-choice
+ ])('groups a %s window pinned to %s by %s', (dateFrom, pinned, expected) => {
+ expect(resolveInterval(dateFrom, null, 'UTC', pinned as IntervalType | null)).toBe(expected)
+ })
+ })
+
+ describe('intervalOptionsForWindow', () => {
+ it('disables the intervals that would smear or collapse the window', () => {
+ expect(intervalOptionsForWindow('-1y', null, 'UTC')).toEqual([
+ { value: 'hour', label: 'Hour', disabledReason: 'Range too long' },
+ { value: 'day', label: 'Day', disabledReason: null },
+ { value: 'week', label: 'Week', disabledReason: null },
+ { value: 'month', label: 'Month', disabledReason: null },
+ ])
+ expect(intervalOptionsForWindow('-7d', null, 'UTC')).toEqual([
+ { value: 'hour', label: 'Hour', disabledReason: null },
+ { value: 'day', label: 'Day', disabledReason: null },
+ { value: 'week', label: 'Week', disabledReason: null },
+ { value: 'month', label: 'Month', disabledReason: 'Range too short' },
+ ])
+ })
+ })
})
diff --git a/products/mcp_analytics/frontend/timeBuckets.ts b/products/mcp_analytics/frontend/timeBuckets.ts
index 9889a0d38ccb..8ad78fddc76d 100644
--- a/products/mcp_analytics/frontend/timeBuckets.ts
+++ b/products/mcp_analytics/frontend/timeBuckets.ts
@@ -1,5 +1,5 @@
import { dayjs } from 'lib/dayjs'
-import { dateStringToComponents, dateStringToDayJs } from 'lib/utils/dateFilters'
+import { dateStringToComponents, dateStringToDayJs, getDefaultInterval } from 'lib/utils/dateFilters'
import { IntervalType } from '~/types'
@@ -68,6 +68,77 @@ export function buildBucketKeys(
return keys
}
+// Grouping intervals offered in the picker. Sub-hour intervals are left out: the date filter has no
+// minute-level quick range, and a window short enough to need one is rare enough to skip.
+export const SELECTABLE_INTERVALS: IntervalType[] = ['hour', 'day', 'week', 'month']
+
+const INTERVAL_LABELS: Record<string, string> = { hour: 'Hour', day: 'Day', week: 'Week', month: 'Month' }
+
+// A line this dense is already a smear, and MCPToolQualityDailyStatsQuery's row limit starts dropping
+// the newest buckets not far above it, so intervals past this many points are offered disabled.
+const MAX_BUCKETS = 1000
+
+export interface IntervalOption {
+ value: IntervalType
+ label: string
+ // Set when the interval doesn't suit the selected window — the picker offers it disabled with
+ // this as the reason.
+ disabledReason: string | null
+}
+
+// Read a pinned grouping interval off a URL param, ignoring anything the picker can't offer.
+export function parseIntervalParam(raw: unknown): IntervalType | null {
+ return SELECTABLE_INTERVALS.find((interval) => interval === raw) ?? null
+}
+
+// How many buckets a window spans at an interval, without materializing every key. Approximate by
+// design: month lengths and DST shifts move the count by one, which never changes the judgement it
+// feeds.
+export function approximateBucketCount(
+ dateFrom: string | null,
+ dateTo: string | null,
+ timezone: string,
+ interval: IntervalType
+): number {
+ const { start, end } = resolveWindow(dateFrom, dateTo, timezone)
+ return Math.max(1, Math.floor(end.diff(startOfBucket(start, interval), interval, true)) + 1)
+}
+
+// The picker's options for a window, with the intervals that would draw an unreadable line or
+// collapse the range to a single point marked disabled.
+export function intervalOptionsForWindow(
+ dateFrom: string | null,
+ dateTo: string | null,
+ timezone: string
+): IntervalOption[] {
+ return SELECTABLE_INTERVALS.map((value) => {
+ const buckets = approximateBucketCount(dateFrom, dateTo, timezone, value)
+ return {
+ value,
+ label: INTERVAL_LABELS[value] ?? value,
+ disabledReason: buckets > MAX_BUCKETS ? 'Range too long' : buckets < 2 ? 'Range too short' : null,
+ }
+ })
+}
+
+// The interval to group by: the pinned choice when it still suits the window, else PostHog's
+// auto-choice for the range. A pin survives date changes, so it has to give way when the window
+// outgrows it — hourly kept from a 12-hour window would otherwise chart a year hour by hour.
+export function resolveInterval(
+ dateFrom: string | null,
+ dateTo: string | null,
+ timezone: string,
+ pinned: IntervalType | null
+): IntervalType {
+ if (pinned) {
+ const option = intervalOptionsForWindow(dateFrom, dateTo, timezone).find((o) => o.value === pinned)
+ if (option && !option.disabledReason) {
+ return pinned
+ }
+ }
+ return getDefaultInterval(dateFrom, dateTo)
+}
+
// True when the final bucket is the current, still-running interval (open-ended window), so a chart
// can dash that segment as "in progress" rather than letting the partial period read as a drop.
// Needs ≥2 buckets to have a segment to dash; `now` is injectable so the logic stays testable.
diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx
index 21d9819d7e40..5de842b524fb 100644
--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx
+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx
@@ -117,7 +117,8 @@ function SortableHead({
}
function ToolRows(): JSX.Element {
- const { filteredRows, toolRowsLoading, selectedTool, dateFilter } = useValues(mcpAnalyticsToolQualityLogic)
+ const { filteredRows, toolRowsLoading, selectedTool, dateFilter, pinnedInterval } =
+ useValues(mcpAnalyticsToolQualityLogic)
const { setSelectedTool } = useActions(mcpAnalyticsToolQualityLogic)
if (toolRowsLoading && filteredRows.length === 0) {
@@ -167,7 +168,7 @@ function ToolRows(): JSX.Element {
<Button
variant="outline"
size="sm"
- render={<LinkPrimitive to={mcpToolReportUrl(row.tool, dateFilter)} />}
+ render={<LinkPrimitive to={mcpToolReportUrl(row.tool, dateFilter, pinnedInterval)} />}
onClick={(e) => e.stopPropagation()}
data-attr="mcp-tool-quality-full-report"
>