: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
fix(alerts): handle deleted alert state (#84884)
Matt Puaa2cc07ee85b1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 456240bea7d5..d334d3e57db4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4700,6 +4700,10 @@ snapshots:hash: v1.k794b7964.1b0b3ec51cc999c02f8442559b676a2e2f352998c0f3d4a9b10da7da8fc3aac1.ZktPS8oprYMZQ-rLsncCgMlyidqF97zUzqDfKjQGo1Aproducts-alerts-alert-modal--edit-alert--light:hash: v1.k794b7964.38643f06f9a727b550dfcde1c46769c13a24bcc43877362c3d6feab29fd2f581.L1ItMn6mhr4o_vWqlI3lpil3yPPBgM0BgUa-yB6TzUQ+ products-alerts-alert-modal--missing-alert--dark:+ hash: v1.k794b7964.9180de7bde4303208cc92881f51bfc618108d5e7204acef1114b80858661662d.gbwUGmvs26EJFVhIM-HqBuAIPreZL8pNqn2ZMVi992I+ products-alerts-alert-modal--missing-alert--light:+ hash: v1.k794b7964.84f6a3830bfb2104a4f6530814766ba5602c87feb8301bdc55f2a67c359b13ac.aEeOcFEuyf003aMGUgIK8Zldz1FzgRc492VXx63y4E8products-alerts-alerts-scene--empty-log-alerts--dark:hash: v1.k794b7964.a9868dcf76f660a4b877ab75f7d250c5d9f88bb80c7569894ffd8b7dd47349eb.7b0VesDoG7DV59GvcHn7THcPrfCa6gx0H3IikajV1EAproducts-alerts-alerts-scene--empty-log-alerts--light:diff --git a/products/alerts/frontend/logic/alertsLogic.test.ts b/products/alerts/frontend/logic/alertsLogic.test.tsindex fd5b361c5ab3..3f22e480f251 100644--- a/products/alerts/frontend/logic/alertsLogic.test.ts+++ b/products/alerts/frontend/logic/alertsLogic.test.ts@@ -41,8 +41,13 @@ describe('alertsLogic', () => {updateSpy?.mockRestore()})- it('deletes an alert and reloads the list', async () => {+ it('keeps a deleted alert out of a reloaded list', async () => {deleteSpy = jest.spyOn(api.alerts, 'delete').mockResolvedValue()+ const nextAlert = { ...alert, id: 'alert-2', name: 'Newer alert' }+ listSpy.mockReset()+ listSpy+ .mockResolvedValueOnce({ results: [alert], count: 1 })+ .mockResolvedValueOnce({ results: [alert, nextAlert], count: 2 })const logic = alertsLogic()logic.mount()@@ -52,6 +57,7 @@ describe('alertsLogic', () => {expect(deleteSpy).toHaveBeenCalledWith(alert.id)expect(listSpy).toHaveBeenCalledTimes(2)+ expect(logic.values.alertsResponse).toEqual({ results: [nextAlert], count: 1 })logic.unmount()})diff --git a/products/alerts/frontend/logic/alertsLogic.ts b/products/alerts/frontend/logic/alertsLogic.tsindex 33861388e736..c9ceca4308b2 100644--- a/products/alerts/frontend/logic/alertsLogic.ts+++ b/products/alerts/frontend/logic/alertsLogic.ts@@ -39,6 +39,7 @@ export interface alertsLogicValues {}alertsResponseLoading: booleanalertsSortedByState: AlertType[]+ deletedAlertIds: Set<string>deletingAlertIds: Set<string>filters: AlertsFiltersisFiltering: boolean@@ -88,6 +89,9 @@ export interface alertsLogicActions {}payload?: any}+ removeAlertFromList: (alertId: string) => {+ alertId: string+ }setAlertDeleting: (alertId: string,isDeleting: boolean@@ -137,6 +141,7 @@ export const alertsLogic = kea<alertsLogicType>([setAlertToggling: (alertId: string, isToggling: boolean) => ({ alertId, isToggling }),deleteAlert: (alert: AlertType) => ({ alert }),setAlertDeleting: (alertId: string, isDeleting: boolean) => ({ alertId, isDeleting }),+ removeAlertFromList: (alertId: string) => ({ alertId }),toggleAlertEnabled: (alert: AlertType) => ({ alert }),updateAlertInList: (alert: AlertType) => ({ alert }),}),@@ -149,6 +154,13 @@ export const alertsLogic = kea<alertsLogicType>([...state,results: state.results.map((currentAlert) => (currentAlert.id === alert.id ? alert : currentAlert)),}),+ removeAlertFromList: (state, { alertId }) => {+ const results = state.results.filter((alert) => alert.id !== alertId)+ if (results.length === state.results.length) {+ return state+ }+ return { results, count: Math.max(0, state.count - 1) }+ },},],page: [@@ -171,6 +183,12 @@ export const alertsLogic = kea<alertsLogicType>([},},],+ deletedAlertIds: [+ new Set<string>(),+ {+ removeAlertFromList: (state, { alertId }) => new Set(state).add(alertId),+ },+ ],togglingAlertIds: [new Set<string>(),{@@ -210,7 +228,14 @@ export const alertsLogic = kea<alertsLogicType>([...(search ? { search } : {}),...(values.filters.createdBy !== 'All users' ? { created_by: values.filters.createdBy } : {}),})- return { results: response.results, count: response.count ?? response.results.length }+ const results = response.results.filter((alert) => !values.deletedAlertIds.has(alert.id))+ return {+ results,+ count: Math.max(+ 0,+ (response.count ?? response.results.length) - (response.results.length - results.length)+ ),+ }},},],@@ -284,6 +309,7 @@ export const alertsLogic = kea<alertsLogicType>([actions.setAlertDeleting(alert.id, true)try {await api.alerts.delete(alert.id)+ actions.removeAlertFromList(alert.id)actions.loadAlerts()lemonToast.success(`${alert.name || 'Unnamed alert'} has been deleted`)} catch {diff --git a/products/alerts/frontend/views/AlertModal.stories.tsx b/products/alerts/frontend/views/AlertModal.stories.tsxindex 8bcb5451064a..076902193374 100644--- a/products/alerts/frontend/views/AlertModal.stories.tsx+++ b/products/alerts/frontend/views/AlertModal.stories.tsx@@ -246,6 +246,35 @@ export const EditAlert: EditAlertVariant = {],}+export const MissingAlert: EditAlertVariant = {+ args: { insightType: 'trends' },+ render: ({ insightType }) => {+ const alert = storyAlerts[insightType]+ return (+ <EditAlertModal+ isOpen+ alertId="missing-alert"+ insightId={alert.insight.id}+ insightShortId={alert.insight.short_id}+ insightLogicProps={{+ dashboardItemId: alert.insight.short_id,+ cachedInsight: alert.insight,+ }}+ onEditSuccess={() => {}}+ onClose={() => {}}+ />+ )+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/environments/:team_id/alerts/:alert_id/': [404, { detail: 'Not found.' }],+ '/api/projects/:team_id/hog_functions/': EMPTY_PAGINATED_RESPONSE,+ },+ }),+ ],+}+interface CreateWizardStoryProps {insightType: StoryInsightType}diff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsxindex acabab8e6b38..3b65c83bf659 100644--- a/products/alerts/frontend/views/EditAlertModal.tsx+++ b/products/alerts/frontend/views/EditAlertModal.tsx@@ -45,6 +45,7 @@ import { supportsAnomalyDetection, supportsOngoingInterval } from '../types'import type { AlertType } from '../types'import { AlertHistorySection } from './AlertHistorySection'import { AlertEnabledAction, AlertLeadingActions } from './EditAlertModal/AlertLeadingActions'+import { AlertNotFoundModal } from './EditAlertModal/AlertNotFoundModal'import { buildWizardSteps } from './EditAlertModal/buildWizardSteps'import { defaultAlertTabs, EditAlertTabs } from './EditAlertModal/EditAlertTabs'@@ -409,6 +410,10 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {const nameError = alertFormSubmitAttempted && !alertForm.name ? 'Enter an alert name.' : undefinedconst scheduleRestrictionFormError = quietHoursFormError(alertForm.schedule_restriction)+ if (alertId && !alertLoading && !alert) {+ return <AlertNotFoundModal isOpen={Boolean(isOpen)} onClose={handleClose} />+ }+return (<LemonModal onClose={handleClose} isOpen={isOpen} width={900} simple title="">{alertLoading && !alert ? (diff --git a/products/alerts/frontend/views/EditAlertModal/AlertLeadingActions.test.tsx b/products/alerts/frontend/views/EditAlertModal/AlertLeadingActions.test.tsxnew file mode 100644index 000000000000..9e08d0b22ca9--- /dev/null+++ b/products/alerts/frontend/views/EditAlertModal/AlertLeadingActions.test.tsx@@ -0,0 +1,44 @@+import { cleanup, render, screen } from '@testing-library/react'++import { AlertState } from '~/queries/schema/schema-general'++import type { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'+import type { AlertType } from 'products/alerts/frontend/types'++import { AlertLeadingActions } from './AlertLeadingActions'++const alert = {+ id: 'alert-1',+ state: AlertState.NOT_FIRING,+} as AlertType++const alertForm = { name: 'Checkout conversion dropped' } as AlertFormType++describe('AlertLeadingActions', () => {+ beforeEach(cleanup)++ it.each([+ ['loaded', alert, true],+ ['missing', null, false],+ ])('shows the delete action only when the alert is %s', (_, loadedAlert, showsDeleteAction) => {+ render(+ <AlertLeadingActions+ alertForm={alertForm}+ alert={loadedAlert}+ onDeleteAlert={() => {}}+ onSnoozeAlert={() => {}}+ onClearSnooze={() => {}}+ onSendTestDelivery={() => {}}+ testDeliveryLoading={false}+ showTestDelivery={false}+ />+ )++ const deleteAction = screen.queryByText('Delete alert')+ if (showsDeleteAction) {+ expect(deleteAction).not.toBeNull()+ return+ }+ expect(deleteAction).toBeNull()+ })+})diff --git a/products/alerts/frontend/views/EditAlertModal/AlertLeadingActions.tsx b/products/alerts/frontend/views/EditAlertModal/AlertLeadingActions.tsxindex c981b9ad7756..5be5df2e91f4 100644--- a/products/alerts/frontend/views/EditAlertModal/AlertLeadingActions.tsx+++ b/products/alerts/frontend/views/EditAlertModal/AlertLeadingActions.tsx@@ -37,26 +37,28 @@ export function AlertLeadingActions({}: AlertLeadingActionsProps): JSX.Element {return (<div className="flex flex-wrap items-center gap-2">- <LemonButton- type="secondary"- status="danger"- onClick={() => {- LemonDialog.open({- title: `Delete "${alertForm.name || 'this alert'}"?`,- description: 'This alert will be permanently deleted. This action cannot be undone.',- primaryButton: {- children: 'Delete',- type: 'primary',- status: 'danger',- onClick: onDeleteAlert,- 'data-attr': 'alert-delete-confirm',- },- secondaryButton: { children: 'Cancel' },- })- }}- >- Delete alert- </LemonButton>+ {alert ? (+ <LemonButton+ type="secondary"+ status="danger"+ onClick={() => {+ LemonDialog.open({+ title: `Delete "${alertForm.name || 'this alert'}"?`,+ description: 'This alert will be permanently deleted. This action cannot be undone.',+ primaryButton: {+ children: 'Delete',+ type: 'primary',+ status: 'danger',+ onClick: onDeleteAlert,+ 'data-attr': 'alert-delete-confirm',+ },+ secondaryButton: { children: 'Cancel' },+ })+ }}+ >+ Delete alert+ </LemonButton>+ ) : null}<SnoozeButtononChange={onSnoozeAlert}value={alert?.snoozed_until}diff --git a/products/alerts/frontend/views/EditAlertModal/AlertNotFoundModal.tsx b/products/alerts/frontend/views/EditAlertModal/AlertNotFoundModal.tsxnew file mode 100644index 000000000000..8f50fe593fe8--- /dev/null+++ b/products/alerts/frontend/views/EditAlertModal/AlertNotFoundModal.tsx@@ -0,0 +1,22 @@+import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'++import { pngHoggie } from 'lib/brand/hoggies'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonModal } from 'lib/lemon-ui/LemonModal'++const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)++export function AlertNotFoundModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }): JSX.Element {+ return (+ <LemonModal onClose={onClose} isOpen={isOpen} width={900} simple title="">+ <div className="flex min-h-[600px] flex-col items-center justify-center gap-3 p-6 text-center">+ <HedgehogMagnifyingGlass className="h-28 w-28" />+ <h2 className="m-0 text-lg font-semibold">Alert not found</h2>+ <p className="m-0 text-secondary">This alert may have been deleted.</p>+ <LemonButton type="secondary" onClick={onClose}>+ Back to alerts+ </LemonButton>+ </div>+ </LemonModal>+ )+}diff --git a/products/alerts/frontend/views/InsightAlerts.tsx b/products/alerts/frontend/views/InsightAlerts.tsxindex 6ec1cefe7fd4..3c9bda050852 100644--- a/products/alerts/frontend/views/InsightAlerts.tsx+++ b/products/alerts/frontend/views/InsightAlerts.tsx@@ -24,6 +24,7 @@ import { alertNotificationLogic } from '../logic/alertNotificationLogic'import { alertsLogic } from '../logic/alertsLogic'import { AlertType } from '../types'import { EditAlertModal } from './EditAlertModal'+import { AlertNotFoundModal } from './EditAlertModal/AlertNotFoundModal'const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)@@ -87,7 +88,7 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {alertDestinationCounts,} = useValues(logic)- const { alert } = useValues(alertLogic({ alertId }))+ const { alert, alertLoading } = useValues(alertLogic({ alertId }))const columns: LemonTableColumns<AlertType> = [{@@ -258,6 +259,10 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {/>)}+ {alertId && !alertForEditModal && !alertLoading && (+ <AlertNotFoundModal isOpen onClose={() => push(urls.alerts())} />+ )}+{isEmpty ? null : (<><AlertsFiltersBar />