: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): surface insight alerts from the Metrics UI (#94325)
Daniel Visca9a11eb49718c
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex b5c5c6abb4d3..974fa4ee554a 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -123,6 +123,7 @@ export const MetricsViewer = (): JSX.Element => {clearAnomaly,saveAsInsight,addToDashboard,+ createAlert,closeAddToDashboardModal,setDisplayType,} = useActions(logic)@@ -310,6 +311,19 @@ export const MetricsViewer = (): JSX.Element => {>Save as insight</LemonButton>+ <LemonButton+ size="small"+ type="secondary"+ onClick={() => createAlert()}+ loading={savedInsightLoading}+ tooltip="Get notified when this metric crosses a threshold (uses insight alerts)"+ disabledReason={+ insightEditorDisabledReason ?? (!hasMetricName ? 'Pick a metric first' : undefined)+ }+ data-attr="metrics-viewer-create-alert"+ >+ Create alert+ </LemonButton><LemonButtonsize="small"type="primary"diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex 87230b4e9011..18a9780baeb7 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -1,3 +1,4 @@+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { NEW_QUERY_STARTED_ERROR_MESSAGE } from 'lib/utils/kea-logic-builders'@@ -415,6 +416,82 @@ describe('metricsViewerLogic', () => {expect(logic.values.isAddToDashboardModalOpen).toBe(false)})+ // "Create alert" surfaces the shared insight-alert flow for a metric: it saves the query as+ // an insight (reusing it while unchanged) and routes to that insight's alerts page, rather+ // than building a parallel metrics-specific alert model.+ it('create alert saves the insight and routes to its alerts page', async () => {+ const push = jest.spyOn(router.actions, 'push').mockImplementation(() => {})+ jest.mocked(insightsApi.create).mockImplementation(+ async (insight: any) => ({ id: 1, short_id: 'abc123', ...insight }) as any+ )+ logic.actions.setMetricName('queue_depth')++ logic.actions.createAlert()+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])+ expect(insightsApi.create).toHaveBeenCalledTimes(1)+ expect(push).toHaveBeenCalledWith('/insights/abc123/alerts')+ push.mockRestore()+ })++ it('create alert reuses the saved insight while the query is unchanged', async () => {+ const push = jest.spyOn(router.actions, 'push').mockImplementation(() => {})+ 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.createAlert()+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])+ expect(insightsApi.create).toHaveBeenCalledTimes(1)++ push.mockClear()+ // Unchanged query: route straight to the alerts page without a duplicate save.+ logic.actions.createAlert()+ await expectLogic(logic).toDispatchActions(['createAlert'])+ expect(insightsApi.create).toHaveBeenCalledTimes(1)+ expect(push).toHaveBeenCalledWith('/insights/abc123/alerts')+ push.mockRestore()+ })++ it('create alert saves a fresh insight after the query changes', async () => {+ const push = jest.spyOn(router.actions, 'push').mockImplementation(() => {})+ jest.mocked(insightsApi.create).mockImplementation(+ async (insight: any) => ({ id: 1, short_id: 'abc123', ...insight }) as any+ )+ logic.actions.setMetricName('queue_depth')+ logic.actions.createAlert()+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])++ logic.actions.setAggregation('rate')+ logic.actions.createAlert()+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])+ expect(insightsApi.create).toHaveBeenCalledTimes(2)+ push.mockRestore()+ })++ // The armed createAlert flag must clear after routing: if it stayed set, a later plain+ // "Save as insight" would be mis-routed to the alerts page (and its toast suppressed).+ it('a plain save after a create-alert save does not route to the alerts page', async () => {+ const push = jest.spyOn(router.actions, 'push').mockImplementation(() => {})+ jest.mocked(insightsApi.create).mockImplementation(+ async (insight: any) => ({ id: 1, short_id: 'abc123', ...insight }) as any+ )+ logic.actions.setMetricName('queue_depth')++ logic.actions.createAlert()+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])+ expect(push).toHaveBeenCalledWith('/insights/abc123/alerts')+ expect(logic.values.pendingAlert).toBe(false)++ push.mockClear()+ logic.actions.setAggregation('rate')+ logic.actions.saveAsInsight()+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])+ expect(push).not.toHaveBeenCalled()+ push.mockRestore()+ })+// 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 7740b91ef2b8..7728dcb48cf0 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -373,6 +373,7 @@ export interface metricsViewerLogicValues {metricsQueryNode: MetricsQuery | nullnamedClauses: MetricsViewerClause[]pendingAddToDashboard: boolean+ pendingAlert: booleanqueryAbortController: AbortController | nullqueryError: string | nullqueryFilters: _MetricFilterApi[]@@ -451,6 +452,9 @@ export interface metricsViewerLogicActions {closeAddToDashboardModal: () => {value: true}+ createAlert: () => {+ value: true+ }duplicateClause: (index: number) => {index: number}@@ -514,6 +518,9 @@ export interface metricsViewerLogicActions {removeGoalLine: (index: number) => {index: number}+ resetPendingAlert: () => {+ value: true+ }saveAsInsight: () => anysaveAsInsightFailure: (error: string,@@ -690,6 +697,16 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([openAddToDashboardModal: true,closeAddToDashboardModal: true,setLastSavedQueryNode: (query: MetricsQuery) => ({ query }),+ // Saves the current query as an insight (reusing the last save while the query is+ // unchanged) and routes to its alerts page, where the shared insight-alert form+ // builds a MetricsAlertConfig on it. Surfaces insight alerts for metrics instead of+ // a parallel metrics-specific alert model.+ createAlert: true,+ // Clears the armed createAlert flag after the success listener has routed to the alerts+ // page, so a later plain save isn't mis-routed. Resetting in the reducer on+ // saveAsInsightSuccess wouldn't work — reducers run before listeners, so the listener+ // would already read it cleared and never route.+ resetPendingAlert: true,// AbortController plumbing mirrors logsViewerDataLogic: a `cancelInProgress`// action aborts the previous controller before storing the new one.setQueryAbortController: (controller: AbortController | null) => ({ controller }),@@ -876,6 +893,18 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([saveAsInsightFailure: () => false,},],+ // Armed while a createAlert-initiated save is in flight, so the success listener routes to+ // the alerts page instead of showing the "View insight" toast. Reducers run before listeners,+ // so this can't reset on saveAsInsightSuccess (the listener needs to read it still armed);+ // the listener clears it via resetPendingAlert after routing. Cleared on failure.+ pendingAlert: [+ false,+ {+ createAlert: (state) => (canCreateMetricsInsight() ? true : state),+ resetPendingAlert: () => 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.@@ -1013,7 +1042,25 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([saveAsInsightSuccess: ({ savedInsight }) => {if (savedInsight && values.pendingAddToDashboard) {actions.openAddToDashboardModal()+ return}+ if (savedInsight && values.pendingAlert) {+ router.actions.push(urls.insightAlerts(savedInsight.short_id))+ // Clear the armed flag so a later plain save isn't mis-routed to the alerts page.+ actions.resetPendingAlert()+ }+ },+ createAlert: () => {+ if (!canCreateMetricsInsight() || !values.metricsQueryNode) {+ return+ }+ // Reuse the saved insight while the query is unchanged; route straight to its+ // alerts page since no save (and so no saveAsInsightSuccess) is coming.+ if (values.savedInsight && objectsEqual(values.lastSavedQueryNode, values.metricsQueryNode)) {+ router.actions.push(urls.insightAlerts(values.savedInsight.short_id))+ return+ }+ actions.saveAsInsight()},setGroupBySearch: () => {actions.loadAttributeKeyOptions({})@@ -1119,8 +1166,8 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([saved: true,})actions.setLastSavedQueryNode(query)- // The add-to-dashboard flow opens the dashboard picker instead of a toast.- if (!values.pendingAddToDashboard) {+ // The add-to-dashboard and create-alert flows route onward instead of a toast.+ if (!values.pendingAddToDashboard && !values.pendingAlert) {lemonToast.success('Insight saved', {button: {label: 'View insight',