: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(metrics): instrument metrics scene usage with tracked events and data-attrs (#69792)
Daniel Visca5992177618f9
diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsxindex 4353095e6d72..03b218dccddd 100644--- a/products/metrics/frontend/MetricsScene.tsx+++ b/products/metrics/frontend/MetricsScene.tsx@@ -1,4 +1,4 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { LemonBanner, LemonTabs } from '@posthog/lemon-ui'@@ -11,15 +11,16 @@ import { ProductKey } from '~/queries/schema/schema-general'import { MetricsSetupPrompt } from './components/MetricsSetupPrompt'import { MetricsSqlEditor } from './components/MetricsSqlEditor'+import { metricsUsageTrackingLogic } from './components/metricsUsageTrackingLogic'import { MetricsViewer } from './components/MetricsViewer'import { metricsIngestionLogic } from './metricsIngestionLogic'import { MetricsSceneActiveTab, metricsSceneLogic } from './metricsSceneLogic'export const METRICS_LOGIC_KEY = 'metrics'-const TABS: { key: MetricsSceneActiveTab; label: string }[] = [- { key: 'viewer', label: 'Viewer' },- { key: 'sql', label: 'SQL' },+const TABS: { key: MetricsSceneActiveTab; label: string; 'data-attr': string }[] = [+ { key: 'viewer', label: 'Viewer', 'data-attr': 'metrics-scene-tab-viewer' },+ { key: 'sql', label: 'SQL', 'data-attr': 'metrics-scene-tab-sql' },]export const scene: SceneExport = {@@ -40,6 +41,9 @@ const MetricsSceneContent = (): JSX.Element => {const { activeTab } = useValues(metricsSceneLogic)const { setActiveTab } = useActions(metricsSceneLogic)const { teamHasMetricsCheckFailed } = useValues(metricsIngestionLogic)+ // Scene-level so tab switches in both directions are captured; keeps the viewer+ // and samples logics (its connect targets) mounted across tab flips as a side effect.+ useMountedLogic(metricsUsageTrackingLogic)return (<>diff --git a/products/metrics/frontend/components/MetricsSamplesPanel.tsx b/products/metrics/frontend/components/MetricsSamplesPanel.tsxindex f89cfe24b2f5..10877e560148 100644--- a/products/metrics/frontend/components/MetricsSamplesPanel.tsx+++ b/products/metrics/frontend/components/MetricsSamplesPanel.tsx@@ -11,6 +11,7 @@ import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/import { traceUrl } from 'products/tracing/frontend/traceLinks'import { type MetricsAggregateRow, type MetricsPanelTab, metricsSamplesLogic } from './metricsSamplesLogic'+import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'import { metricsViewerLogic } from './metricsViewerLogic'function SampleAttributes({ sample }: { sample: _MetricEventSampleApi }): JSX.Element {@@ -34,6 +35,7 @@ function SampleAttributes({ sample }: { sample: _MetricEventSampleApi }): JSX.Elfunction SamplesTab(): JSX.Element {const { samples, samplesLoading } = useValues(metricsSamplesLogic)const { hasMetricName } = useValues(metricsViewerLogic)+ const { sampleRowExpanded, tracePivotClicked } = useActions(metricsUsageTrackingLogic)return (<LemonTable@@ -48,6 +50,7 @@ function SamplesTab(): JSX.Element {}expandable={{expandedRowRender: (sample) => <SampleAttributes sample={sample} />,+ onRowExpand: (sample) => sampleRowExpanded(sample),}}columns={[{@@ -84,8 +87,12 @@ function SamplesTab(): JSX.Element {ts: sample.timestamp,})}className="font-mono"+ onClick={() => tracePivotClicked(sample)}>- {sample.trace_id.slice(0, 8).toLowerCase()}+ {/* Link doesn't take data-attr; the span gives autocapture a named element. */}+ <span data-attr="metrics-trace-pivot">+ {sample.trace_id.slice(0, 8).toLowerCase()}+ </span></Link></Tooltip>) : (@@ -157,8 +164,18 @@ export function MetricsSamplesPanel(): JSX.Element {activeKey={activeTab}onChange={setActiveTab}tabs={[- { key: 'aggregates', label: 'Aggregates', content: <AggregatesTab /> },- { key: 'samples', label: 'Samples', content: <SamplesTab /> },+ {+ key: 'aggregates',+ label: 'Aggregates',+ content: <AggregatesTab />,+ 'data-attr': 'metrics-samples-panel-tab-aggregates',+ },+ {+ key: 'samples',+ label: 'Samples',+ content: <SamplesTab />,+ 'data-attr': 'metrics-samples-panel-tab-samples',+ },]}/></div>diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 6fe3a0659408..095355565a2f 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -40,9 +40,9 @@ import {RECOMMENDED_AGGREGATION_BY_TYPE,} from './metricsViewerLogic'-const VIEW_MODE_OPTIONS: { value: MetricsViewMode; label: string }[] = [- { value: 'chart', label: 'Chart' },- { value: 'stat', label: 'Stat' },+const VIEW_MODE_OPTIONS: { value: MetricsViewMode; label: string; 'data-attr': string }[] = [+ { value: 'chart', label: 'Chart', 'data-attr': 'metrics-viewer-view-mode-chart' },+ { value: 'stat', label: 'Stat', 'data-attr': 'metrics-viewer-view-mode-stat' },]// How the stat card summarizes the series into one headline value.@@ -222,6 +222,7 @@ export const MetricsViewer = (): JSX.Element => {value={aggregation}options={AGGREGATION_OPTIONS}onChange={(value) => setAggregation(value as MetricAggregation)}+ data-attr="metrics-viewer-aggregation"/><LemonInputSelectmode="multiple"@@ -232,6 +233,7 @@ export const MetricsViewer = (): JSX.Element => {options={[]}placeholder="Group by attribute…"className="min-w-[12rem]"+ data-attr="metrics-viewer-group-by"/><UniversalFiltersrootKey="metrics-viewer-filters"@@ -268,6 +270,7 @@ export const MetricsViewer = (): JSX.Element => {value={statSummary}options={SUMMARY_OPTIONS}onChange={(value) => setStatSummary(value)}+ data-attr="metrics-viewer-stat-summary"/>)}<LemonSwitch@@ -276,6 +279,7 @@ export const MetricsViewer = (): JSX.Element => {onChange={setLiveRefresh}tooltip={`Auto-refresh every ${LIVE_REFRESH_MS / 1000}s`}bordered+ data-attr="metrics-viewer-live-toggle"/><LemonButtonsize="small"diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.tsnew file mode 100644index 000000000000..9040d11b19fd--- /dev/null+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts@@ -0,0 +1,249 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { initKeaTests } from '~/test/init'++import {+ metricsQueryCreate,+ metricsSamplesCreate,+ metricsValuesRetrieve,+} from 'products/metrics/frontend/generated/api'+import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'++import { metricsSceneLogic } from '../metricsSceneLogic'+import { metricNamePickerLogic } from './metricNamePickerLogic'+import { metricsSamplesLogic } from './metricsSamplesLogic'+import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'+import { metricsViewerLogic, NEW_QUERY_STARTED_ERROR_MESSAGE } from './metricsViewerLogic'++jest.mock('posthog-js')++jest.mock('products/metrics/frontend/generated/api', () => ({+ ...jest.requireActual('products/metrics/frontend/generated/api'),+ metricsValuesRetrieve: jest.fn(),+ metricsQueryCreate: jest.fn(),+ metricsSamplesCreate: jest.fn(),+ metricsCharacterizeCreate: jest.fn(),+}))++// Sentinel strings that stand in for customer data — no capture call may ever contain them.+const SECRET_METRIC = 'customer_secret_metric'+const SECRET_LABEL = 'customer-secret-service'+const SECRET_ATTR_VALUE = 'customer-secret-endpoint'++const SAMPLE: _MetricEventSampleApi = {+ timestamp: '2026-07-09T05:46:28.132600+00:00',+ metric_name: SECRET_METRIC,+ metric_type: 'histogram',+ value: 970.97,+ count: 24,+ unit: 'ms',+ aggregation_temporality: 'cumulative',+ is_monotonic: false,+ service_name: SECRET_LABEL,+ trace_id: '4EE9645D1C55A19919C83FDD657C88A4',+ span_id: 'F068A584A45A5EDA',+ attributes: { endpoint: SECRET_ATTR_VALUE },+ resource_attributes: { 'service.name': SECRET_LABEL },+}++const TRACELESS_SAMPLE = { ...SAMPLE, trace_id: '', span_id: '', attributes: {}, resource_attributes: {} }++const captures = (event: string): any[][] =>+ (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name === event)++const allCapturedProperties = (): string => JSON.stringify((posthog.capture as jest.Mock).mock.calls)++describe('metricsUsageTrackingLogic', () => {+ let logic: ReturnType<typeof metricsUsageTrackingLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.mocked(posthog.capture).mockClear()+ jest.mocked(metricsValuesRetrieve).mockReset().mockResolvedValue({ results: [] })+ jest.mocked(metricsQueryCreate).mockReset().mockResolvedValue({ results: [] })+ jest.mocked(metricsSamplesCreate).mockReset().mockResolvedValue({ results: [] })+ logic = metricsUsageTrackingLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ // The whole point of this logic is the action -> event mapping; a renamed or disconnected+ // source action silently kills the dashboard tile that reads the event.+ it.each([+ ['metrics tab changed', () => metricsSceneLogic.actions.setActiveTab('sql'), { tab: 'sql' }],+ [+ 'metrics viewer aggregation changed',+ () => metricsViewerLogic.actions.setAggregation('p95'),+ { aggregation: 'p95' },+ ],+ [+ 'metrics viewer view mode changed',+ () => metricsViewerLogic.actions.setViewMode('stat'),+ { view_mode: 'stat' },+ ],+ [+ 'metrics viewer stat summary changed',+ () => metricsViewerLogic.actions.setStatSummary('total'),+ { stat_summary: 'total' },+ ],+ ['metrics viewer live toggled', () => metricsViewerLogic.actions.setLiveRefresh(true), { enabled: true }],+ [+ 'metrics viewer date range changed',+ () => metricsViewerLogic.actions.setDateFrom('-24h'),+ { date_from: '-24h' },+ ],+ [+ 'metrics viewer group by changed',+ () => metricsViewerLogic.actions.setGroupByKeys(['service.name', 'env']),+ { group_by_count: 2 },+ ],+ [+ 'metrics samples panel tab changed',+ () => metricsSamplesLogic.actions.setActiveTab('samples'),+ { tab: 'samples' },+ ],+ ])('%s fires with enum/count properties only', (event, dispatch, expectedProperties) => {+ dispatch()+ expect(captures(event)).toEqual([[event, expectedProperties]])+ })++ it('filter changes report the applied filter count, never keys or values', () => {+ metricsViewerLogic.actions.setFilterGroup({+ type: 'AND',+ values: [+ {+ type: 'AND',+ values: [+ { type: 'metric_attribute', key: 'endpoint', operator: 'exact', value: [SECRET_ATTR_VALUE] },+ ],+ },+ ],+ } as any)+ expect(captures('metrics viewer attribute filter changed')).toEqual([+ ['metrics viewer attribute filter changed', { filter_count: 1 }],+ ])+ expect(allCapturedProperties()).not.toContain(SECRET_ATTR_VALUE)+ })++ it('selecting a metric fires without the metric name; clearing it fires nothing', () => {+ metricsViewerLogic.actions.setMetricName(SECRET_METRIC)+ expect(captures('metrics viewer metric selected')).toHaveLength(1)+ expect(allCapturedProperties()).not.toContain(SECRET_METRIC)++ metricsViewerLogic.actions.setMetricName('')+ expect(captures('metrics viewer metric selected')).toHaveLength(1)+ })++ // Selecting a metric auto-applies its recommended aggregation; counting that dispatch as a+ // user action would inflate the feature-adoption tile on every metric switch.+ it('the auto-applied recommended aggregation is not an aggregation change', () => {+ metricNamePickerLogic.actions.loadItemsSuccess([{ name: SECRET_METRIC, metric_type: 'sum' }] as any)+ metricsViewerLogic.actions.setMetricName(SECRET_METRIC)+ expect(metricsViewerLogic.values.aggregation).toBe('increase')+ expect(captures('metrics viewer aggregation changed')).toHaveLength(0)+ })++ it('query completed reports shape counts and timing, never series labels', async () => {+ jest.mocked(metricsQueryCreate).mockResolvedValue({+ results: [+ {+ labels: { 'service.name': SECRET_LABEL },+ points: [+ { time: '2026-07-09T00:00:00Z', value: 1 },+ { time: '2026-07-09T00:01:00Z', value: 2 },+ ],+ },+ { labels: {}, points: [{ time: '2026-07-09T00:00:00Z', value: 3 }] },+ ],+ } as any)+ metricsViewerLogic.actions.setMetricName(SECRET_METRIC)+ metricsViewerLogic.actions.fetchQueryResults({})+ await expectLogic(metricsViewerLogic).toDispatchActions(['fetchQueryResultsSuccess'])++ expect(captures('metrics query completed')).toEqual([+ [+ 'metrics query completed',+ {+ series_count: 2,+ point_count: 3,+ load_ms: expect.any(Number),+ aggregation: 'sum',+ has_group_by: false,+ has_filters: false,+ },+ ],+ ])+ expect(allCapturedProperties()).not.toContain(SECRET_LABEL)+ })++ // The loader dispatches a success with [] before any metric is picked (initial mount) —+ // counting those would swamp the query-health tiles with empty no-op "queries".+ it('the empty-name initial query success is not a completed query', async () => {+ metricsViewerLogic.actions.fetchQueryResults({})+ await expectLogic(metricsViewerLogic).toDispatchActions(['fetchQueryResultsSuccess'])+ expect(captures('metrics query completed')).toHaveLength(0)+ })++ it('query failed captures a status class, never the error message', () => {+ metricsViewerLogic.actions.fetchQueryResultsFailure(`Invalid regex in ${SECRET_METRIC}{`, { status: 400 })+ expect(captures('metrics query failed')).toEqual([['metrics query failed', { error_type: 'http_400' }]])+ expect(allCapturedProperties()).not.toContain(SECRET_METRIC)+ })++ it('a superseded (aborted) query is not a failure', () => {+ metricsViewerLogic.actions.fetchQueryResultsFailure(+ NEW_QUERY_STARTED_ERROR_MESSAGE,+ new DOMException(NEW_QUERY_STARTED_ERROR_MESSAGE, 'AbortError')+ )+ expect(captures('metrics query failed')).toHaveLength(0)+ })++ it('samples loaded reports count and trace coverage, never attribute values', async () => {+ jest.mocked(metricsSamplesCreate).mockResolvedValue({+ results: [SAMPLE, SAMPLE, SAMPLE, TRACELESS_SAMPLE],+ } as any)+ metricsViewerLogic.actions.setMetricName(SECRET_METRIC)+ metricsSamplesLogic.actions.setActiveTab('samples')+ await expectLogic(metricsSamplesLogic).toDispatchActions(['loadSamplesSuccess'])++ expect(captures('metrics samples loaded')).toEqual([+ ['metrics samples loaded', { sample_count: 4, trace_coverage: 75 }],+ ])+ expect(allCapturedProperties()).not.toContain(SECRET_ATTR_VALUE)+ })++ it.each([+ [+ 'metrics sample row expanded',+ (sample: typeof SAMPLE) => logic.actions.sampleRowExpanded(sample),+ SAMPLE,+ { attribute_count: 2, has_trace: true },+ ],+ [+ 'metrics sample row expanded',+ (sample: typeof SAMPLE) => logic.actions.sampleRowExpanded(sample),+ TRACELESS_SAMPLE,+ { attribute_count: 0, has_trace: false },+ ],+ [+ 'metrics trace pivot clicked',+ (sample: typeof SAMPLE) => logic.actions.tracePivotClicked(sample),+ SAMPLE,+ { has_span_id: true },+ ],+ [+ 'metrics trace pivot clicked',+ (sample: typeof SAMPLE) => logic.actions.tracePivotClicked(sample),+ TRACELESS_SAMPLE,+ { has_span_id: false },+ ],+ ])('%s reports derived booleans/counts only', (event, dispatch, sample, expectedProperties) => {+ dispatch(sample)+ expect(captures(event)).toEqual([[event, expectedProperties]])+ expect(allCapturedProperties()).not.toContain(SECRET_ATTR_VALUE)+ })+})diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.tsnew file mode 100644index 000000000000..2011408374fb--- /dev/null+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts@@ -0,0 +1,133 @@+import { actions, connect, kea, listeners, path } from 'kea'+import posthog from 'posthog-js'++import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'++import { metricsSceneLogic } from '../metricsSceneLogic'+import { metricsSamplesLogic } from './metricsSamplesLogic'+import type { metricsUsageTrackingLogicType } from './metricsUsageTrackingLogicType'+import { isUserInitiatedError, metricsViewerLogic } from './metricsViewerLogic'++// Central usage tracking for the metrics scene, following the metricsSqlEditorTrackingLogic+// precedent: captures fire from listeners on the source logics' actions, not from onClick+// handlers scattered through components.+//+// Privacy rule: never capture customer metric names, series labels, attribute keys, or+// attribute values — only counts, booleans, durations, and our own enum values.+export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([+ path(['products', 'metrics', 'frontend', 'components', 'metricsUsageTrackingLogic']),+ connect(() => ({+ actions: [+ metricsSceneLogic,+ ['setActiveTab as sceneTabChanged'],+ metricsViewerLogic,+ [+ 'setMetricName',+ 'setAggregation',+ 'setDateFrom',+ 'setViewMode',+ 'setStatSummary',+ 'setLiveRefresh',+ 'setGroupByKeys',+ 'setFilterGroup',+ 'fetchQueryResults',+ 'fetchQueryResultsSuccess',+ 'fetchQueryResultsFailure',+ ],+ metricsSamplesLogic,+ ['setActiveTab as samplesPanelTabChanged', 'loadSamplesSuccess'],+ ],+ values: [metricsViewerLogic, ['hasMetricName', 'aggregation', 'groupByKeys', 'queryFilters']],+ })),+ actions({+ // Component-only interactions with no source-logic action to listen to.+ sampleRowExpanded: (sample: _MetricEventSampleApi) => ({ sample }),+ tracePivotClicked: (sample: _MetricEventSampleApi) => ({ sample }),+ }),+ listeners(({ values, cache }) => ({+ sceneTabChanged: ({ activeTab }) => {+ posthog.capture('metrics tab changed', { tab: activeTab })+ },+ setMetricName: ({ metricName }) => {+ if (metricName.trim()) {+ posthog.capture('metrics viewer metric selected')+ }+ },+ setAggregation: ({ aggregation }) => {+ posthog.capture('metrics viewer aggregation changed', { aggregation })+ },+ // The DateFilter dispatches setDateFrom and setDateTo together on every change,+ // so listening to setDateFrom alone captures each range change exactly once.+ setDateFrom: ({ dateFrom }) => {+ posthog.capture('metrics viewer date range changed', { date_from: dateFrom })+ },+ setViewMode: ({ viewMode }) => {+ posthog.capture('metrics viewer view mode changed', { view_mode: viewMode })+ },+ setStatSummary: ({ statSummary }) => {+ posthog.capture('metrics viewer stat summary changed', { stat_summary: statSummary })+ },+ setLiveRefresh: ({ liveRefresh }) => {+ posthog.capture('metrics viewer live toggled', { enabled: liveRefresh })+ },+ setGroupByKeys: ({ groupByKeys }) => {+ posthog.capture('metrics viewer group by changed', { group_by_count: groupByKeys.length })+ },+ setFilterGroup: () => {+ // queryFilters counts only complete, backend-valid chips (reducers ran before us).+ posthog.capture('metrics viewer attribute filter changed', { filter_count: values.queryFilters.length })+ },+ fetchQueryResults: () => {+ cache.queryStartedAt = performance.now()+ },+ fetchQueryResultsSuccess: ({ queryResults }) => {+ // The loader resolves [] without querying when no metric is picked yet — not a query.+ if (!values.hasMetricName) {+ return+ }+ // load_ms includes the loader's 300ms debounce breakpoint — consistent overhead,+ // fine for trend comparisons.+ const loadMs =+ cache.queryStartedAt !== undefined ? Math.round(performance.now() - cache.queryStartedAt) : null+ posthog.capture('metrics query completed', {+ series_count: queryResults.length,+ point_count: queryResults.reduce((sum: number, series) => sum + series.points.length, 0),+ load_ms: loadMs,+ aggregation: values.aggregation,+ has_group_by: values.groupByKeys.length > 0,+ has_filters: values.queryFilters.length > 0,+ })+ },+ fetchQueryResultsFailure: ({ error, errorObject }) => {+ // A superseded/unmounted query aborts — user-initiated, not a failure.+ if (isUserInitiatedError(error) || isUserInitiatedError(errorObject)) {+ return+ }+ // Only a coarse class — the message can embed the customer's metric name.+ const status = (errorObject as { status?: number } | undefined)?.status+ posthog.capture('metrics query failed', { error_type: status ? `http_${status}` : 'unknown' })+ },+ samplesPanelTabChanged: ({ activeTab }) => {+ posthog.capture('metrics samples panel tab changed', { tab: activeTab })+ },+ loadSamplesSuccess: ({ samples }) => {+ if (!values.hasMetricName) {+ return+ }+ const withTrace = samples.filter((sample) => !!sample.trace_id).length+ posthog.capture('metrics samples loaded', {+ sample_count: samples.length,+ trace_coverage: samples.length ? Math.round((100 * withTrace) / samples.length) : 0,+ })+ },+ sampleRowExpanded: ({ sample }) => {+ posthog.capture('metrics sample row expanded', {+ attribute_count: Object.keys(sample.attributes).length + Object.keys(sample.resource_attributes).length,+ has_trace: !!sample.trace_id,+ })+ },+ tracePivotClicked: ({ sample }) => {+ posthog.capture('metrics trace pivot clicked', { has_span_id: !!sample.span_id })+ },+ })),+])diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex d0e6337b3477..1ed537040a33 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -68,7 +68,7 @@ export const NEW_QUERY_STARTED_ERROR_MESSAGE = 'A new metrics query started, can// A superseded or unmounted request rejects with an abort, not a real failure — never surface it as an error.// The cancel path aborts with NEW_QUERY_STARTED_ERROR_MESSAGE, whose text doesn't contain "abort", so match it// explicitly alongside the generic abort check (mirrors logsViewerDataLogic's isUserInitiatedError).-const isUserInitiatedError = (error: unknown): boolean => {+export const isUserInitiatedError = (error: unknown): boolean => {const errorStr = String(error).toLowerCase()return error === NEW_QUERY_STARTED_ERROR_MESSAGE || errorStr.includes('abort')}@@ -146,6 +146,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([actions({setMetricName: (metricName: string) => ({ metricName }),setAggregation: (aggregation: MetricAggregation) => ({ aggregation }),+ // Auto-applied on metric switch — a separate action so usage tracking can+ // tell it apart from the user picking an aggregation themselves.+ setRecommendedAggregation: (aggregation: MetricAggregation) => ({ aggregation }),setDateFrom: (dateFrom: string | null) => ({ dateFrom }),setDateTo: (dateTo: string | null) => ({ dateTo }),setViewMode: (viewMode: MetricsViewMode) => ({ viewMode }),@@ -162,7 +165,10 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([metricName: ['' as string, { setMetricName: (_, { metricName }) => metricName }],aggregation: [DEFAULT_AGGREGATION as MetricAggregation,- { setAggregation: (_, { aggregation }) => aggregation },+ {+ setAggregation: (_, { aggregation }) => aggregation,+ setRecommendedAggregation: (_, { aggregation }) => aggregation,+ },],dateFrom: [DEFAULT_DATE_FROM as string | null, { setDateFrom: (_, { dateFrom }) => dateFrom }],dateTo: [null as string | null, { setDateTo: (_, { dateTo }) => dateTo }],@@ -198,7 +204,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([const metricType = values.items.find((item) => item.name === metricName)?.metric_typeconst recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefinedif (recommended && recommended !== values.aggregation) {- actions.setAggregation(recommended)+ actions.setRecommendedAggregation(recommended)}},saveAsInsightFailure: ({ error }) => {