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(metrics): persist viewer query state in the URL (#89718)

Jimmy Zhu2d6b644696c2
diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
index cbd3552c9bf2..cd5e29a32c71 100644
--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
@@ -1,3 +1,4 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -156,6 +157,24 @@ describe('metricsUsageTrackingLogic', () => {
expect(captures('metrics viewer metric selected')).toHaveLength(1)
})
+ // Restoring a shared /metrics link replays the viewer setters; counting those dispatches
+ // as interactions would inflate the usage tiles on every link open or refresh.
+ it('a URL restore captures no viewer interactions', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', {
+ metricName: SECRET_METRIC,
+ aggregation: 'p95',
+ dateFrom: '-24h',
+ groupBy: '["env"]',
+ })
+ }).toFinishAllListeners()
+
+ expect(captures('metrics viewer metric selected')).toHaveLength(0)
+ expect(captures('metrics viewer aggregation changed')).toHaveLength(0)
+ expect(captures('metrics viewer date range changed')).toHaveLength(0)
+ expect(captures('metrics viewer group by changed')).toHaveLength(0)
+ })
+
// 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', () => {
diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
index 3094f472374f..c8e6e5bcb2a8 100644
--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
@@ -20,6 +20,7 @@ import type { MetricAggregation } from './metricsViewerLogic'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsUsageTrackingLogicValues {
+ isRestoringFromUrl: boolean // metricsSceneLogic
aggregation: MetricAggregation // metricsViewerLogic
groupByKeys: string[] // metricsViewerLogic
hasMetricName: boolean // metricsViewerLogic
@@ -132,7 +133,12 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
teamLogic,
['addProductIntent'],
],
- values: [metricsViewerLogic, ['hasMetricName', 'aggregation', 'groupByKeys', 'queryFilters']],
+ values: [
+ metricsViewerLogic,
+ ['hasMetricName', 'aggregation', 'groupByKeys', 'queryFilters'],
+ metricsSceneLogic,
+ ['isRestoringFromUrl'],
+ ],
})),
actions({
// Component-only interactions with no source-logic action to listen to.
@@ -144,26 +150,37 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
sceneTabChanged: ({ activeTab }) => {
posthog.capture('metrics tab changed', { tab: activeTab })
},
+ // The viewer setters also fire while the scene restores state from URL params —
+ // a restore is not a user interaction, so those dispatches are not captured.
setMetricName: ({ metricName }) => {
- if (metricName.trim()) {
+ if (metricName.trim() && !values.isRestoringFromUrl) {
posthog.capture('metrics viewer metric selected')
}
},
setAggregation: ({ aggregation }) => {
- posthog.capture('metrics viewer aggregation changed', { aggregation })
+ if (!values.isRestoringFromUrl) {
+ 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 })
+ if (!values.isRestoringFromUrl) {
+ posthog.capture('metrics viewer date range changed', { date_from: dateFrom })
+ }
},
setLiveRefresh: ({ liveRefresh }) => {
posthog.capture('metrics viewer live toggled', { enabled: liveRefresh })
},
setGroupByKeys: ({ groupByKeys }) => {
- posthog.capture('metrics viewer group by changed', { group_by_count: groupByKeys.length })
+ if (!values.isRestoringFromUrl) {
+ posthog.capture('metrics viewer group by changed', { group_by_count: groupByKeys.length })
+ }
},
setFilterGroup: () => {
+ if (values.isRestoringFromUrl) {
+ return
+ }
// queryFilters counts only complete, backend-valid chips (reducers ran before us).
posthog.capture('metrics viewer attribute filter changed', { filter_count: values.queryFilters.length })
},
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
index aa58cdb4f1e9..cb1ab10786e0 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -161,12 +161,23 @@ describe('metricsViewerLogic', () => {
expect(logic.values.metricsQueryNode?.clauses[0].metricType).toBe('gauge')
})
- it('backfills the metric type when the picker loads after the metric was set', () => {
+ it('backfills the metric type and recommended aggregation when the picker loads after the metric was set', () => {
metricNamePickerLogic.actions.loadItemsSuccess([])
logic.actions.setMetricName('queue_depth')
expect(logic.values.metricsQueryNode?.clauses[0]).not.toHaveProperty('metricType')
metricNamePickerLogic.actions.loadItemsSuccess(PICKER_ITEMS)
expect(logic.values.metricsQueryNode?.clauses[0].metricType).toBe('gauge')
+ // A cold URL restore sets the name before the list arrives, so without the late
+ // recommendation a gauge/counter link would silently chart as a raw sum.
+ expect(logic.values.aggregation).toBe('avg')
+ })
+
+ it('the late backfill leaves an explicitly chosen aggregation alone', () => {
+ metricNamePickerLogic.actions.loadItemsSuccess([])
+ logic.actions.setMetricName('queue_depth')
+ logic.actions.setAggregation('p95')
+ metricNamePickerLogic.actions.loadItemsSuccess(PICKER_ITEMS)
+ expect(logic.values.aggregation).toBe('p95')
})
// "Add to dashboard" must not create a fresh insight on every click — repeated
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 1c683f1dc356..efb7044dd1aa 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -38,7 +38,11 @@ import { metricNamePickerLogic } from './metricNamePickerLogic'
import type { MetricNameItem } from './metricNamePickerLogic'
import type { MetricsChartSeries } from './metricsSeries'
+// A derived type ((typeof METRIC_AGGREGATIONS)[number]) would keep these in sync, but
+// kea-typegen inlines derived unions into every consumer's generated block — keep the
+// named alias so those blocks stay stable.
export type MetricAggregation = 'sum' | 'avg' | 'count' | 'p95' | 'rate' | 'increase'
+export const METRIC_AGGREGATIONS: MetricAggregation[] = ['sum', 'avg', 'count', 'p95', 'rate', 'increase']
export type MetricsViewerSeries = _MetricSeriesApi
@@ -51,7 +55,7 @@ export interface MetricsAnomalyBadge {
onsetTime: string | null
}
-const DEFAULT_AGGREGATION: MetricAggregation = 'sum'
+export const DEFAULT_AGGREGATION: MetricAggregation = 'sum'
// Aggregation applied automatically when a metric of this type is selected.
// Cumulative counters (OTel type 'sum') summed raw give meaningless ever-growing
@@ -65,7 +69,7 @@ export const RECOMMENDED_AGGREGATION_BY_TYPE: Record<string, MetricAggregation>
summary: 'p95',
exponential_histogram: 'p95',
}
-const DEFAULT_DATE_FROM = '-1h'
+export const DEFAULT_DATE_FROM = '-1h'
export const NEW_QUERY_STARTED_ERROR_MESSAGE = 'A new metrics query started, canceling the previous one'
// A superseded or unmounted request rejects with an abort, not a real failure — never surface it as an error.
@@ -518,6 +522,13 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
if (known) {
actions.setSelectedMetricType(known)
}
+ // The name was set before the list arrived, so the pick-time recommendation
+ // never ran. Apply it late, but only over the untouched default — an
+ // aggregation restored from the URL or picked by the user stays.
+ const recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefined
+ if (recommended && values.aggregation === DEFAULT_AGGREGATION && recommended !== values.aggregation) {
+ actions.setRecommendedAggregation(recommended)
+ }
},
saveAsInsightFailure: ({ error }) => {
lemonToast.error(`Failed to save insight: ${error}`)
diff --git a/products/metrics/frontend/metricsSceneLogic.test.ts b/products/metrics/frontend/metricsSceneLogic.test.ts
new file mode 100644
index 000000000000..eb3685d06889
--- /dev/null
+++ b/products/metrics/frontend/metricsSceneLogic.test.ts
@@ -0,0 +1,196 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+import {
+ AccessControlLevel,
+ AccessControlResourceType,
+ AppContext,
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyOperator,
+ UniversalFiltersGroup,
+} from '~/types'
+
+import { metricsQueryCreate, metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'
+
+import { metricsSceneLogic } from './metricsSceneLogic'
+
+jest.mock('products/metrics/frontend/generated/api', () => ({
+ ...jest.requireActual('products/metrics/frontend/generated/api'),
+ metricsValuesRetrieve: jest.fn(),
+ metricsQueryCreate: jest.fn(),
+}))
+
+const PICKER_ITEMS = [
+ { name: 'requests_total', metric_type: 'sum' },
+ { name: 'queue_depth', metric_type: 'gauge' },
+]
+
+const FILTER_GROUP: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: PropertyFilterType.MetricAttribute,
+ key: 'service_name',
+ value: ['api'],
+ operator: PropertyOperator.Exact,
+ },
+ ],
+ },
+ ],
+}
+
+describe('metricsSceneLogic', () => {
+ let logic: ReturnType<typeof metricsSceneLogic.build>
+
+ beforeEach(async () => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ resource_access_control: {
+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
+ [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
+ },
+ } as AppContext
+ initKeaTests()
+ jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: PICKER_ITEMS })
+ jest.mocked(metricsQueryCreate).mockReset().mockResolvedValue({ results: [] })
+ logic = metricsSceneLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ describe('URL parameter parsing', () => {
+ it('restores the viewer query state from URL params', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', {
+ activeTab: 'viewer',
+ metricName: 'queue_depth',
+ metricType: 'gauge',
+ aggregation: 'p95',
+ dateFrom: '-24h',
+ dateTo: '2026-08-25T00:00:00.000Z',
+ groupBy: '["service_name","env"]',
+ filterGroup: JSON.stringify(FILTER_GROUP),
+ })
+ }).toFinishAllListeners()
+
+ expect(logic.values.activeTab).toEqual('viewer')
+ expect(logic.values.metricName).toEqual('queue_depth')
+ expect(logic.values.selectedMetricType).toEqual('gauge')
+ // The shared link's own aggregation survives the recommendation cascade that
+ // picking queue_depth (a gauge, recommending 'avg') triggers.
+ expect(logic.values.aggregation).toEqual('p95')
+ expect(logic.values.dateFrom).toEqual('-24h')
+ expect(logic.values.dateTo).toEqual('2026-08-25T00:00:00.000Z')
+ expect(logic.values.groupByKeys).toEqual(['service_name', 'env'])
+ expect(logic.values.filterGroup).toEqual(FILTER_GROUP)
+ // Applying the params dispatches setters whose own URL sync must not rewrite the
+ // URL from half-applied state — the params stay in the address bar for a refresh.
+ expect(router.values.searchParams).toMatchObject({ metricName: 'queue_depth', aggregation: 'p95' })
+ })
+
+ it('keeps the recommended aggregation for a link that has a metric but no aggregation param', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', { metricName: 'queue_depth' })
+ }).toFinishAllListeners()
+
+ expect(logic.values.aggregation).toEqual('avg')
+ })
+
+ it.each([
+ ['activeTab', 'nonsense', 'activeTab', 'overview'],
+ ['aggregation', 'not-an-aggregation', 'aggregation', 'sum'],
+ ['metricType', 'not-a-type', 'selectedMetricType', null],
+ ])('falls back to the default for an invalid %s param', async (param, urlValue, valueKey, expected) => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', { [param]: urlValue })
+ }).toFinishAllListeners()
+
+ expect(logic.values[valueKey as keyof typeof logic.values]).toEqual(expected)
+ })
+
+ it.each([
+ ['unparsable JSON', '{not valid json'],
+ // kea-router pre-parses JSON-looking params, so these arrive as real values
+ // and would crash the filter selectors without shape validation.
+ ['a JSON array', '[1,2]'],
+ ['a JSON object of the wrong shape', '{"a":1}'],
+ ['a group with junk inside values', '{"type":"AND","values":[1]}'],
+ // The viewer renders values[0] as a nested group, so a flat group (leaf chips
+ // at the top level) would crash the filter bar.
+ [
+ 'a flat group with a leaf at the top level',
+ '{"type":"AND","values":[{"type":"metric_attribute","key":"service_name","value":["api"],"operator":"exact"}]}',
+ ],
+ ])('ignores a malformed filterGroup in the URL (%s)', async (_, urlValue) => {
+ const before = logic.values.filterGroup
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', { filterGroup: urlValue })
+ }).toFinishAllListeners()
+
+ expect(logic.values.filterGroup).toEqual(before)
+ })
+ })
+
+ describe('URL writing', () => {
+ beforeEach(async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics')
+ }).toFinishAllListeners()
+ })
+
+ it('writes viewer state to the URL and drops params back at their defaults', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.setDateFrom('-7d')
+ }).toFinishAllListeners()
+
+ // aggregation is written even when recommended ('increase' for this counter), so
+ // restoring the link never has to re-derive it.
+ expect(router.values.searchParams).toMatchObject({
+ metricName: 'requests_total',
+ aggregation: 'increase',
+ dateFrom: '-7d',
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.setDateFrom('-1h')
+ }).toFinishAllListeners()
+
+ expect(router.values.searchParams).not.toHaveProperty('dateFrom')
+ expect(router.values.searchParams).toMatchObject({ metricName: 'requests_total' })
+ })
+
+ it('keeps viewer params in the URL when switching tabs', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.setActiveTab('sql')
+ }).toFinishAllListeners()
+
+ expect(router.values.searchParams).toMatchObject({ metricName: 'requests_total', activeTab: 'sql' })
+ })
+
+ it('does not write metrics params onto another scene URL', async () => {
+ // An async cascade (e.g. the picker's late metric-type backfill) can fire after
+ // the router already left /metrics while the scene logic is still mounted.
+ await expectLogic(logic, () => {
+ router.actions.push('/logs')
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setMetricName('requests_total')
+ }).toFinishAllListeners()
+
+ expect(router.values.location.pathname).toContain('/logs')
+ expect(router.values.searchParams).not.toHaveProperty('metricName')
+ })
+ })
+})
diff --git a/products/metrics/frontend/metricsSceneLogic.tsx b/products/metrics/frontend/metricsSceneLogic.tsx
index 3d7533631d5d..8c3419e2853b 100644
--- a/products/metrics/frontend/metricsSceneLogic.tsx
+++ b/products/metrics/frontend/metricsSceneLogic.tsx
@@ -1,12 +1,31 @@
-import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
import { router, urlToAction } from 'kea-router'
import { syncSearchParams, updateSearchParams } from '@posthog/products-error-tracking/frontend/utils'
+import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/constants'
+import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { objectsEqual } from 'lib/utils/objects'
+import { parseTagsFilter } from 'lib/utils/url'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
import { Params } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { UniversalFiltersGroup } from '~/types'
+
+import { OtelMetricTypeEnumApi } from 'products/metrics/frontend/generated/api.schemas'
+
+import {
+ DEFAULT_AGGREGATION,
+ DEFAULT_DATE_FROM,
+ METRIC_AGGREGATIONS,
+ MetricAggregation,
+ metricsViewerLogic,
+ toKnownMetricType,
+} from './components/metricsViewerLogic'
export const METRICS_SQL_EDITOR_TAB_ID = 'metrics-sql-editor'
@@ -14,53 +33,219 @@ export type MetricsSceneActiveTab = 'overview' | 'viewer' | 'sql' | 'fundamental
const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['overview', 'viewer', 'sql', 'fundamentals']
export const DEFAULT_ACTIVE_TAB: MetricsSceneActiveTab = 'overview'
+// kea-router pre-parses JSON-looking params, so anything a user types into the URL can reach
+// setFilterGroup — validate the whole tree or the filter selectors crash on `.values`/`in`.
+// The viewer renders values[0] as a nested group, so the top level must hold groups only.
+const isValidFilterValue = (value: any): boolean =>
+ typeof value === 'object' && value !== null && (!isUniversalGroupFilterLike(value) || isValidInnerGroup(value))
+const isValidInnerGroup = (group: any): boolean =>
+ isUniversalGroupFilterLike(group) && Array.isArray(group.values) && group.values.every(isValidFilterValue)
+const isValidFilterGroup = (group: any): group is UniversalFiltersGroup =>
+ isUniversalGroupFilterLike(group) &&
+ Array.isArray(group.values) &&
+ group.values.length > 0 &&
+ group.values.every(isValidInnerGroup)
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSceneLogicValues {
+ aggregation: MetricAggregation // metricsViewerLogic
+ dateFrom: string | null // metricsViewerLogic
+ dateTo: string | null // metricsViewerLogic
+ filterGroup: UniversalFiltersGroup // metricsViewerLogic
+ groupByKeys: string[] // metricsViewerLogic
+ metricName: string // metricsViewerLogic
+ selectedMetricType: OtelMetricTypeEnumApi | null // metricsViewerLogic
activeTab: MetricsSceneActiveTab
+ isRestoringFromUrl: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSceneLogicActions {
+ setAggregation: (aggregation: MetricAggregation) => {
+ aggregation: MetricAggregation
+ } // metricsViewerLogic
+ setDateFrom: (dateFrom: string | null) => {
+ dateFrom: string | null
+ } // metricsViewerLogic
+ setDateTo: (dateTo: string | null) => {
+ dateTo: string | null
+ } // metricsViewerLogic
+ setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
+ filterGroup: UniversalFiltersGroup
+ } // metricsViewerLogic
+ setGroupByKeys: (groupByKeys: string[]) => {
+ groupByKeys: string[]
+ } // metricsViewerLogic
+ setMetricName: (metricName: string) => {
+ metricName: string
+ } // metricsViewerLogic
+ setRecommendedAggregation: (aggregation: MetricAggregation) => {
+ aggregation: MetricAggregation
+ } // metricsViewerLogic
+ setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => {
+ metricType: OtelMetricTypeEnumApi | null
+ } // metricsViewerLogic
keepSqlEditorMounted: (editorTabId: string) => {
editorTabId: string
}
setActiveTab: (activeTab: MetricsSceneActiveTab) => {
activeTab: MetricsSceneActiveTab
}
+ setRestoringFromUrl: (restoring: boolean) => {
+ restoring: boolean
+ }
}
export type metricsSceneLogicType = MakeLogicType<metricsSceneLogicValues, metricsSceneLogicActions>
export const metricsSceneLogic = kea<metricsSceneLogicType>([
path(['products', 'metrics', 'frontend', 'metricsSceneLogic']),
+ // The scene owns ALL URL sync: metricsViewerLogic stays URL-free so it can be embedded
+ // anywhere, and this logic translates URL params into its actions and its actions back
+ // into URL writes. Mirrors the logsSceneLogic / tracingSceneLogic boundary.
+ connect(() => ({
+ values: [
+ metricsViewerLogic,
+ ['metricName', 'selectedMetricType', 'aggregation', 'dateFrom', 'dateTo', 'groupByKeys', 'filterGroup'],
+ ],
+ actions: [
+ metricsViewerLogic,
+ [
+ 'setMetricName',
+ 'setSelectedMetricType',
+ 'setAggregation',
+ 'setRecommendedAggregation',
+ 'setDateFrom',
+ 'setDateTo',
+ 'setGroupByKeys',
+ 'setFilterGroup',
+ ],
+ ],
+ })),
actions({
setActiveTab: (activeTab: MetricsSceneActiveTab) => ({ activeTab }),
+ setRestoringFromUrl: (restoring: boolean) => ({ restoring }),
keepSqlEditorMounted: (editorTabId: string) => ({ editorTabId }),
}),
reducers({
activeTab: [DEFAULT_ACTIVE_TAB as MetricsSceneActiveTab, { setActiveTab: (_, { activeTab }) => activeTab }],
+ // True while URL params are being applied, so URL writes pause and usage tracking
+ // can tell a restore from the user touching a control.
+ isRestoringFromUrl: [false, { setRestoringFromUrl: (_, { restoring }) => restoring }],
}),
+ listeners(({ cache }) => ({
+ keepSqlEditorMounted: ({ editorTabId }) => {
+ if (cache.sqlEditorTabId === editorTabId) {
+ return
+ }
+ cache.unmountSqlEditor?.()
+ cache.sqlEditorTabId = editorTabId
+ // Intentionally not cleaned up in beforeUnmount: keeps the embedded sqlEditorLogic
+ // alive across navigation so the user's query survives leaving and re-entering /metrics.
+ cache.unmountSqlEditor = sqlEditorLogic({ tabId: editorTabId, mode: SQLEditorMode.Embedded }).mount()
+ },
+ })),
urlToAction(({ actions, values, cache }) => {
- const urlToAction = (_: any, params: Params): void => {
+ const applyUrlParams = (_: any, params: Params): void => {
if (cache.isSyncingUrl) {
return
}
- const requested = params.activeTab
- if (
- typeof requested === 'string' &&
- VALID_ACTIVE_TABS.includes(requested as MetricsSceneActiveTab) &&
- requested !== values.activeTab
- ) {
- actions.setActiveTab(requested as MetricsSceneActiveTab)
+ // The setters below (and their viewer-listener cascades) each write the URL;
+ // syncUrl skips writes during the restore, or a mid-apply write built from
+ // half-applied state would strip the params this pass has not consumed yet.
+ actions.setRestoringFromUrl(true)
+ try {
+ const requested = params.activeTab
+ if (
+ typeof requested === 'string' &&
+ VALID_ACTIVE_TABS.includes(requested as MetricsSceneActiveTab) &&
+ requested !== values.activeTab
+ ) {
+ actions.setActiveTab(requested as MetricsSceneActiveTab)
+ }
+ // metricName first: its listener latches the metric type and a recommended
+ // aggregation, which the explicit URL params below then override.
+ const metricName = params.metricName != null ? String(params.metricName) : ''
+ if (metricName !== values.metricName) {
+ actions.setMetricName(metricName)
+ }
+ const metricType = toKnownMetricType(
+ typeof params.metricType === 'string' ? params.metricType : undefined
+ )
+ if (metricType && metricType !== values.selectedMetricType) {
+ actions.setSelectedMetricType(metricType)
+ }
+ const aggregation =
+ typeof params.aggregation === 'string' &&
+ METRIC_AGGREGATIONS.includes(params.aggregation as MetricAggregation)
+ ? (params.aggregation as MetricAggregation)
+ : null
+ if (aggregation && aggregation !== values.aggregation) {
+ actions.setAggregation(aggregation)
+ } else if (!aggregation && !metricName && values.aggregation !== DEFAULT_AGGREGATION) {
+ // A bare URL resets to the clean-slate default. With a metric but no
+ // aggregation param (a hand-written link), the recommended aggregation
+ // latched by setMetricName stays.
+ actions.setAggregation(DEFAULT_AGGREGATION)
+ }
+ const dateFrom =
+ typeof params.dateFrom === 'string' && params.dateFrom ? params.dateFrom : DEFAULT_DATE_FROM
+ if (dateFrom !== values.dateFrom) {
+ actions.setDateFrom(dateFrom)
+ }
+ const dateTo = typeof params.dateTo === 'string' && params.dateTo ? params.dateTo : null
+ if (dateTo !== values.dateTo) {
+ actions.setDateTo(dateTo)
+ }
+ const groupByKeys = parseTagsFilter(params.groupBy) ?? []
+ if (!objectsEqual(groupByKeys, values.groupByKeys)) {
+ actions.setGroupByKeys(groupByKeys)
+ }
+ if (params.filterGroup) {
+ try {
+ const filterGroup =
+ typeof params.filterGroup === 'string' ? JSON.parse(params.filterGroup) : params.filterGroup
+ if (isValidFilterGroup(filterGroup) && !objectsEqual(filterGroup, values.filterGroup)) {
+ actions.setFilterGroup(filterGroup)
+ }
+ } catch {
+ // Ignore malformed filterGroup JSON in the URL
+ }
+ } else if (!objectsEqual(DEFAULT_UNIVERSAL_GROUP_FILTER, values.filterGroup)) {
+ actions.setFilterGroup(DEFAULT_UNIVERSAL_GROUP_FILTER)
+ }
+ } finally {
+ actions.setRestoringFromUrl(false)
}
}
- return { '*': urlToAction }
+ return { [urls.metrics()]: applyUrlParams }
}),
trackedActionToUrl(({ values, cache }) => {
- const syncUrl = (): [string, Params, Record<string, any>, { replace: boolean }] => {
+ const syncUrl = (): [string, Params, Record<string, any>, { replace: boolean }] | undefined => {
+ // No writes during a restore (see applyUrlParams) or after navigating away —
+ // an async cascade (e.g. the picker's late metric-type backfill) must not
+ // splat metrics params onto another scene's URL.
+ const pathname = removeProjectIdIfPresent(router.values.location.pathname).replace(/\/+$/, '')
+ if (values.isRestoringFromUrl || pathname !== urls.metrics()) {
+ return undefined
+ }
cache.isSyncingUrl = true
const result = syncSearchParams(router, (params: Params) => {
updateSearchParams(params, 'activeTab', values.activeTab, DEFAULT_ACTIVE_TAB)
+ updateSearchParams(params, 'metricName', values.metricName, '')
+ updateSearchParams(params, 'metricType', values.selectedMetricType, null)
+ if (values.metricName) {
+ // Never dropped while a metric is picked: 'sum' is both the default and a
+ // valid explicit choice, so a link that omitted it would restore with the
+ // metric type's recommended aggregation instead of the one on screen.
+ params.aggregation = values.aggregation
+ } else {
+ delete params.aggregation
+ }
+ updateSearchParams(params, 'dateFrom', values.dateFrom, DEFAULT_DATE_FROM)
+ updateSearchParams(params, 'dateTo', values.dateTo, null)
+ updateSearchParams(params, 'groupBy', values.groupByKeys, [] as string[])
+ updateSearchParams(params, 'filterGroup', values.filterGroup, DEFAULT_UNIVERSAL_GROUP_FILTER)
return params
})
queueMicrotask(() => {
@@ -70,18 +255,14 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
}
return {
setActiveTab: () => syncUrl(),
+ setMetricName: () => syncUrl(),
+ setSelectedMetricType: () => syncUrl(),
+ setAggregation: () => syncUrl(),
+ setRecommendedAggregation: () => syncUrl(),
+ setDateFrom: () => syncUrl(),
+ setDateTo: () => syncUrl(),
+ setGroupByKeys: () => syncUrl(),
+ setFilterGroup: () => syncUrl(),
}
}),
- listeners(({ cache }) => ({
- keepSqlEditorMounted: ({ editorTabId }) => {
- if (cache.sqlEditorTabId === editorTabId) {
- return
- }
- cache.unmountSqlEditor?.()
- cache.sqlEditorTabId = editorTabId
- // Intentionally not cleaned up in beforeUnmount: keeps the embedded sqlEditorLogic
- // alive across navigation so the user's query survives leaving and re-entering /metrics.
- cache.unmountSqlEditor = sqlEditorLogic({ tabId: editorTabId, mode: SQLEditorMode.Embedded }).mount()
- },
- })),
])