: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): add to dashboard from the metrics scene (#70103)
Daniel Viscac3fc939a7484
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex bd64900690e2..363ee089e1af 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -11,6 +11,7 @@ import {SpinnerOverlay,} from '@posthog/lemon-ui'+import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboardModal'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'import { type MetricSummary } from 'lib/components/Metric/metricSummary'@@ -125,6 +126,8 @@ export const MetricsViewer = (): JSX.Element => {queryResultsLoading,queryError,savedInsightLoading,+ savedInsight,+ isAddToDashboardModalOpen,hasMetricName,} = useValues(logic)const {@@ -143,6 +146,8 @@ export const MetricsViewer = (): JSX.Element => {fetchAnomaly,clearAnomaly,saveAsInsight,+ addToDashboard,+ closeAddToDashboardModal,} = useActions(logic)const { items: pickerItems } = useValues(pickerLogic)@@ -297,7 +302,26 @@ export const MetricsViewer = (): JSX.Element => {>Save as insight</LemonButton>+ <LemonButton+ size="small"+ type="primary"+ onClick={() => addToDashboard()}+ loading={savedInsightLoading}+ disabledReason={!hasMetricName ? 'Pick a metric first' : undefined}+ data-attr="metrics-viewer-add-to-dashboard"+ >+ Add to dashboard+ </LemonButton></div>+ {savedInsight && (+ <AddToDashboardModal+ isOpen={isAddToDashboardModalOpen}+ closeModal={closeAddToDashboardModal}+ insightProps={{ dashboardItemId: savedInsight.short_id, cachedInsight: savedInsight }}+ canEditInsight+ data-attr="metrics-viewer-add-to-dashboard-modal"+ />+ )}<div className="flex flex-col xl:flex-row gap-3 items-stretch"><div className="flex-1 min-w-0"><div className="relative h-[360px] border rounded p-3">diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.tsindex 9040d11b19fd..8efe44c25262 100644--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts@@ -106,6 +106,22 @@ describe('metricsUsageTrackingLogic', () => {() => metricsSamplesLogic.actions.setActiveTab('samples'),{ tab: 'samples' },],+ ['metrics add to dashboard clicked', () => metricsViewerLogic.actions.addToDashboard(), { aggregation: 'sum' }],+ [+ // Reports the aggregation persisted on the insight, not the viewer's+ // current one — those diverge when the user changes the aggregation+ // while the save request is in flight (viewer state here is 'sum').+ 'metrics insight saved',+ () =>+ metricsViewerLogic.actions.saveAsInsightSuccess(+ {+ short_id: 'abc123',+ query: { kind: 'MetricsQuery', clauses: [{ name: 'a', aggregation: 'quantile' }] },+ } as any,+ {} as any+ ),+ { aggregation: 'p95' },+ ],])('%s fires with enum/count properties only', (event, dispatch, expectedProperties) => {dispatch()expect(captures(event)).toEqual([[event, expectedProperties]])diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.tsindex 2011408374fb..63d12b38d263 100644--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts@@ -1,6 +1,8 @@import { actions, connect, kea, listeners, path } from 'kea'import posthog from 'posthog-js'+import type { MetricsQuery } from '~/queries/schema/schema-general'+import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'import { metricsSceneLogic } from '../metricsSceneLogic'@@ -30,6 +32,8 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>(['setLiveRefresh','setGroupByKeys','setFilterGroup',+ 'addToDashboard',+ 'saveAsInsightSuccess','fetchQueryResults','fetchQueryResultsSuccess','fetchQueryResultsFailure',@@ -77,6 +81,21 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([// queryFilters counts only complete, backend-valid chips (reducers ran before us).posthog.capture('metrics viewer attribute filter changed', { filter_count: values.queryFilters.length })},+ addToDashboard: () => {+ posthog.capture('metrics add to dashboard clicked', { aggregation: values.aggregation })+ },+ saveAsInsightSuccess: ({ savedInsight }) => {+ if (!savedInsight) {+ return+ }+ // Read the aggregation off the insight itself — the viewer's current+ // value can already differ if it changed while the save was in flight.+ // The node's 'quantile' maps back to the viewer vocabulary's 'p95'.+ const nodeAggregation = (savedInsight.query as MetricsQuery | undefined)?.clauses?.[0]?.aggregation+ posthog.capture('metrics insight saved', {+ aggregation: nodeAggregation === 'quantile' ? 'p95' : (nodeAggregation ?? null),+ })+ },fetchQueryResults: () => {cache.queryStartedAt = performance.now()},diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex 76b242879c0f..b054fdc1aecb 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -1,5 +1,7 @@import { expectLogic } from 'kea-test-utils'+import { insightsApi } from 'scenes/insights/utils/api'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import {@@ -21,6 +23,11 @@ jest.mock('products/metrics/frontend/generated/api', () => ({metricsAttributesRetrieve: jest.fn(),}))+jest.mock('scenes/insights/utils/api', () => ({+ ...jest.requireActual('scenes/insights/utils/api'),+ insightsApi: { create: jest.fn() },+}))+const filterGroupWith = (filters: Record<string, any>[]): UniversalFiltersGroup => ({type: FilterLogicalOperator.And,values: [@@ -137,6 +144,61 @@ describe('metricsViewerLogic', () => {expect(logic.values.metricsQueryNode?.clauses[0].metricType).toBe('gauge')})+ // "Add to dashboard" must not create a fresh insight on every click — repeated+ // clicks for an unchanged query would litter saved insights with duplicates.+ // The mock normalizes the echoed query (like the API can: injected defaults,+ // version stamps), so reuse must not depend on the server round-tripping the+ // node byte-for-byte.+ it('add to dashboard saves the insight once, then reuses it while the query is unchanged', async () => {+ jest.mocked(insightsApi.create).mockImplementation(+ async (insight: any) =>+ ({ id: 1, short_id: 'abc123', ...insight, query: { ...insight.query, version: 1 } }) as any+ )+ logic.actions.setMetricName('queue_depth')++ logic.actions.addToDashboard()+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess', 'openAddToDashboardModal'])+ expect(logic.values.isAddToDashboardModalOpen).toBe(true)+ expect(insightsApi.create).toHaveBeenCalledTimes(1)++ logic.actions.closeAddToDashboardModal()+ logic.actions.addToDashboard()+ await expectLogic(logic).toDispatchActions(['openAddToDashboardModal'])+ expect(logic.values.isAddToDashboardModalOpen).toBe(true)+ expect(insightsApi.create).toHaveBeenCalledTimes(1)+ })++ it('add to dashboard saves a fresh insight after the query changes', async () => {+ jest.mocked(insightsApi.create).mockImplementation(+ async (insight: any) => ({ id: 1, short_id: 'abc123', ...insight }) as any+ )+ logic.actions.setMetricName('queue_depth')+ logic.actions.addToDashboard()+ await expectLogic(logic).toDispatchActions(['openAddToDashboardModal'])++ logic.actions.closeAddToDashboardModal()+ logic.actions.setAggregation('rate')+ logic.actions.addToDashboard()+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess', 'openAddToDashboardModal'])+ expect(insightsApi.create).toHaveBeenCalledTimes(2)+ })++ // A failed add-to-dashboard save must not leave the flow armed: a later plain+ // "Save as insight" success would unexpectedly pop the modal.+ it('a later plain save does not open the modal after a failed add-to-dashboard save', async () => {+ jest.mocked(insightsApi.create).mockRejectedValueOnce(new Error('boom'))+ logic.actions.setMetricName('queue_depth')+ logic.actions.addToDashboard()+ await expectLogic(logic).toDispatchActions(['saveAsInsightFailure'])++ jest.mocked(insightsApi.create).mockImplementation(+ async (insight: any) => ({ id: 1, short_id: 'abc123', ...insight }) as any+ )+ logic.actions.saveAsInsight()+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])+ expect(logic.values.isAddToDashboardModalOpen).toBe(false)+ })+// A failed query (bad regex, 500) used to render the same "No data" empty state as a genuinely// empty result. The failure records the message so the viewer can show a real error instead.// kea-loaders dispatches `<key>Failure(error.message, error)`, so the reducer reads the message.diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex e9805da106a0..6fdf15380e27 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -11,6 +11,7 @@ import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utilimport { dayjs } from 'lib/dayjs'import { escapeRegex } from 'lib/utils/actions'import { dateStringToDayJs } from 'lib/utils/dateFilters'+import { objectsEqual } from 'lib/utils/objects'import { insightsApi } from 'scenes/insights/utils/api'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -169,6 +170,12 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([setGroupByKeys: (groupByKeys: string[]) => ({ groupByKeys }),setGroupBySearch: (groupBySearch: string) => ({ groupBySearch }),setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),+ // Saves the current query as an insight (reusing the last save while the+ // query is unchanged) and opens the dashboard picker for it.+ addToDashboard: true,+ openAddToDashboardModal: true,+ closeAddToDashboardModal: true,+ setLastSavedQueryNode: (query: MetricsQuery) => ({ query }),// AbortController plumbing mirrors logsViewerDataLogic: a `cancelInProgress`// action aborts the previous controller before storing the new one.setQueryAbortController: (controller: AbortController | null) => ({ controller }),@@ -209,6 +216,30 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([null as AbortController | null,{ setQueryAbortController: (_, { controller }) => controller },],+ isAddToDashboardModalOpen: [+ false,+ {+ openAddToDashboardModal: () => true,+ closeAddToDashboardModal: () => false,+ },+ ],+ // The query node exactly as the last successful save sent it. The reuse+ // check compares against this, not the server-returned insight.query —+ // the API may normalize the stored node (injected defaults, version+ // stamps), and a comparison against that would never match and would+ // save a duplicate insight on every click.+ lastSavedQueryNode: [null as MetricsQuery | null, { setLastSavedQueryNode: (_, { query }) => query }],+ // Armed while an addToDashboard-initiated save is in flight, so the success+ // path opens the modal instead of the "View insight" toast. Not reset on+ // success by a reducer — the success listener must still read it as armed.+ pendingAddToDashboard: [+ false,+ {+ addToDashboard: () => true,+ openAddToDashboardModal: () => false,+ saveAsInsightFailure: () => false,+ },+ ],// A real query failure (bad regex, 500, timeout) — surfaced as a banner so it isn't mistaken// for the empty-result state. Cleared when a new query starts or one succeeds; an aborted// (superseded) query leaves the previous state untouched so refetches don't flash an error.@@ -248,6 +279,23 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([saveAsInsightFailure: ({ error }) => {lemonToast.error(`Failed to save insight: ${error}`)},+ addToDashboard: () => {+ if (!values.metricsQueryNode) {+ return+ }+ // Re-clicking with an unchanged query reuses the saved insight instead+ // of littering saved insights with duplicates.+ if (values.savedInsight && objectsEqual(values.lastSavedQueryNode, values.metricsQueryNode)) {+ actions.openAddToDashboardModal()+ return+ }+ actions.saveAsInsight()+ },+ saveAsInsightSuccess: ({ savedInsight }) => {+ if (savedInsight && values.pendingAddToDashboard) {+ actions.openAddToDashboardModal()+ }+ },setGroupBySearch: () => {actions.loadAttributeKeyOptions({})},@@ -350,12 +398,16 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([query,saved: true,})- lemonToast.success('Insight saved', {- button: {- label: 'View insight',- action: () => router.actions.push(urls.insightView(insight.short_id)),- },- })+ actions.setLastSavedQueryNode(query)+ // The add-to-dashboard flow opens the dashboard picker instead of a toast.+ if (!values.pendingAddToDashboard) {+ lemonToast.success('Insight saved', {+ button: {+ label: 'View insight',+ action: () => router.actions.push(urls.insightView(insight.short_id)),+ },+ })+ }return insight},},