: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(alerts): add 15-minute interval ui and split edit alert modal (#59104)
Matt Puac61e2ffcf3ef
diff --git a/frontend/package.json b/frontend/package.jsonindex 4b25328ad0bd..e1398247ff0e 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -70,6 +70,7 @@"@posthog/icons": "^0.36.6","@posthog/products-access-control": "workspace:*","@posthog/products-actions": "workspace:*",+ "@posthog/products-alerts": "workspace:*","@posthog/products-business-knowledge": "workspace:*","@posthog/products-cohorts": "workspace:*","@posthog/products-conversations": "workspace:*",diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2b701501dc81..d7131647c01e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -97,9 +97,9 @@ snapshots:components-alerts-alert-history-chart--weekly-evaluation-time-axis--light:hash: v1.k794b7964.c95195c8c099622ee1c1d0525be01290609fb202f9be6ab18a1f8ca6051c80a3.WY8HvYGu-6QCFZxhH2zq5zlWNOG__WnH_88GWRVax30components-alerts-quiet-hours-fields--default--dark:- hash: v1.k794b7964.b1d9dcf611e6103856c1e579471fcc8d15e5ede8d778f58119af30defd021088.yuhFcITo9oT9yqz-ilwd1uzRK-Q9jRg3C9olYPw_hu4+ hash: v1.k794b7964.58bdea6c05aa465d03d1c3f4cb148db45683e75fc6c68e4cb742378223d555f3.wBQ30YLJxWg4haG-HxQciM8qUYaYx5Tls_nzDZKt9AIcomponents-alerts-quiet-hours-fields--default--light:- hash: v1.k794b7964.a2293bde4bb0b7ca27dfd7ee41226407780d9848000a22b9ccd5903674163749.AY5DM6ohNxpR3I4WEpxtTkkrtEij5AAL_VJOYjJXkko+ hash: v1.k794b7964.cb68e6420d435c8c09102712f2acbabe529d26d432c274cc5cf4dc56156d7946.gaeEA-JTXRoLDquSzNjikcSZfDZGmvD6N_19jNkwGVgcomponents-bulkupdatetagsbutton--add-mode--dark:hash: v1.k794b7964.ba66e3fd796ded95414954112b8e8ad07474b5be373cb4e98ecf3e56d8f61aab.jgsY9nY4c4c5rgf0ML5534zPOMlCIbIubJMaH2hRaigcomponents-bulkupdatetagsbutton--add-mode--light:@@ -888,6 +888,10 @@ snapshots:hash: v1.k794b7964.16497ffba42652fff4fac6a013ae2fc2a1288fa48a0fec12d320efba5cfb947b.fOszZPdI1FYuR807Uz2MhIYgyGadShFZS4zfWPtRngscomponents-pay-gate-mini--pay-gate-mini-grandfathered--light:hash: v1.k794b7964.257bf2813b5210f17fdd46f5b871a5c460e58eacee07fe8c33e4e1a0ae8a6679.gh6MmdaCBdVHreM0fW3iKetiV2-2VeDnDQNWslH58KA+ components-pay-gate-mini--pay-gate-mini-high-frequency-alerts--dark:+ hash: v1.k794b7964.94f1860843c98848eab0b8ff9eb7f4ff2134e75af952d4959928269955b31fd1.g1EIWDa_OGJGgJSYWdtwPhHp0G2OGRJcTFjIMVX0WZE+ components-pay-gate-mini--pay-gate-mini-high-frequency-alerts--light:+ hash: v1.k794b7964.9a91ae9560e83d468f08202ceb06b9f757484052a47880e7bfc4ca32828af746.sR0CdB_MywB3V5uYpNGg64r6pkKQ6VeB6eSmdi0ugdkcomponents-pay-gate-mini--pay-gate-mini-limit-feature-other--dark:hash: v1.k794b7964.5114bd6770b3f496dd3fdfa1537a3d00a05703d08afc2c16259015d402762346.sddINQTbkhCG4p1sNut8KRkZy7ccwpe4S3B2XWdYNZ0components-pay-gate-mini--pay-gate-mini-limit-feature-other--light:diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts b/frontend/src/lib/components/Alerts/alertFormLogic.test.tsindex 78916777542b..873a7ca30780 100644--- a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts+++ b/frontend/src/lib/components/Alerts/alertFormLogic.test.ts@@ -4,10 +4,12 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'import api, { ApiError } from 'lib/api'+import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { createEmptyInsight, insightLogic } from 'scenes/insights/insightLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'+import { userLogic } from 'scenes/userLogic'import {AlertCalculationInterval,@@ -228,4 +230,26 @@ describe('alertFormLogic', () => {expect(errorToastSpy).not.toHaveBeenCalled()expect(successToastSpy).toHaveBeenCalledWith('Alert saved.')})++ it('blocks save with error toast for 15-minute interval without entitlement', async () => {+ userLogic.mount()+ upgradeModalLogic.mount()+ const logic = mountForm()+ logic.actions.setAlertFormValues({+ ...makeFormDefaults(),+ calculation_interval: AlertCalculationInterval.EVERY_15_MINUTES,+ checks: undefined,+ })++ await expectLogic(logic, () => {+ logic.actions.submitAlertForm()+ }).toFinishAllListeners()++ expect(createSpy).not.toHaveBeenCalled()+ expect(upgradeModalLogic.values.upgradeModalFeatureKey).toBeNull()+ expect(errorToastSpy).toHaveBeenCalledWith(+ '15-minute alert intervals require a Boost, Scale, or Enterprise platform add-on.'+ )+ expect(successToastSpy).not.toHaveBeenCalled()+ })})diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.ts b/frontend/src/lib/components/Alerts/alertFormLogic.tsindex 8df48b10f025..5c325fe88ffe 100644--- a/frontend/src/lib/components/Alerts/alertFormLogic.ts+++ b/frontend/src/lib/components/Alerts/alertFormLogic.ts@@ -7,6 +7,7 @@ import api, { ApiError } from 'lib/api'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'+import { userLogic } from 'scenes/userLogic'import {AlertCalculationInterval,@@ -15,7 +16,14 @@ import {InsightThresholdType,InsightsThresholdBounds,} from '~/queries/schema/schema-general'-import { InsightLogicProps, IntervalType, QueryBasedInsightModel } from '~/types'+import { AvailableFeature, InsightLogicProps, IntervalType, QueryBasedInsightModel } from '~/types'++import {+ blockSubmitWithoutHighFrequencyAlertsEntitlement,+ getDefaultSimulationRange,+ HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE,+ isHighFrequencyAlertInterval,+} from 'products/alerts/frontend/logic/alertIntervalHelpers'import type { alertFormLogicType } from './alertFormLogicType'import { alertLogic } from './alertLogic'@@ -57,20 +65,6 @@ export function canCheckOngoingInterval(alert?: AlertType | AlertFormType): bool)}-export function getDefaultSimulationRange(interval: AlertCalculationInterval): string {- switch (interval) {- case AlertCalculationInterval.EVERY_15_MINUTES:- case AlertCalculationInterval.HOURLY:- return '-48h'- case AlertCalculationInterval.DAILY:- return '-30d'- case AlertCalculationInterval.WEEKLY:- return '-12w'- case AlertCalculationInterval.MONTHLY:- return '-12m'- }-}-export interface AlertFormLogicProps {alert: AlertType | nullinsightId: QueryBasedInsightModel['id']@@ -137,6 +131,13 @@ function insightIntervalToAlertInterval(interval?: IntervalType | null): AlertCa}}+function alertToFormType(alert: AlertType, insightId: QueryBasedInsightModel['id']): AlertFormType {+ return {+ ...alert,+ insight: insightId,+ }+}+const getThresholdBounds = (goalLines?: GoalLine[] | null): InsightsThresholdBounds => {if (goalLines == null || goalLines.length == 0) {return {}@@ -199,54 +200,64 @@ export const alertFormLogic = kea<alertFormLogicType>([forms(({ props, values }) => ({alertForm: {- defaults:- props.alert ??- ({- id: undefined,- name: values.goalLines && values.goalLines.length > 0 ? `Crossed ${values.goalLines[0].label}` : '',- created_by: null,- created_at: '',- enabled: true,- config: {- type: 'TrendsAlertConfig',- series_index: 0,- check_ongoing_interval: false,- },- threshold: {- configuration: {- type: InsightThresholdType.ABSOLUTE,- bounds: getThresholdBounds(values.goalLines),- },- },- condition: {- type: AlertConditionType.ABSOLUTE_VALUE,- },- subscribed_users: [],- checks: [],- calculation_interval: insightIntervalToAlertInterval(props.insightInterval),- skip_weekend: false,- schedule_restriction: null,- detector_config: null,- investigation_agent_enabled: false,- investigation_gates_notifications: false,- investigation_inconclusive_action: 'notify',- insight: props.insightId,- } as AlertFormType),- errors: (alert: AlertType | AlertFormType) =>+ defaults: props.alert+ ? alertToFormType(props.alert, props.insightId)+ : ({+ id: undefined,+ name:+ values.goalLines && values.goalLines.length > 0 ? `Crossed ${values.goalLines[0].label}` : '',+ created_by: null,+ created_at: '',+ enabled: true,+ config: {+ type: 'TrendsAlertConfig',+ series_index: 0,+ check_ongoing_interval: false,+ },+ threshold: {+ configuration: {+ type: InsightThresholdType.ABSOLUTE,+ bounds: getThresholdBounds(values.goalLines),+ },+ },+ condition: {+ type: AlertConditionType.ABSOLUTE_VALUE,+ },+ subscribed_users: [],+ checks: [],+ calculation_interval: insightIntervalToAlertInterval(props.insightInterval),+ skip_weekend: false,+ schedule_restriction: null,+ detector_config: null,+ investigation_agent_enabled: false,+ investigation_gates_notifications: false,+ investigation_inconclusive_action: 'notify',+ insight: props.insightId,+ } as AlertFormType),+ errors: (alert: AlertFormType) =>({name: !alert.name ? 'You need to give your alert a name' : undefined,schedule_restriction: quietHoursFormError(alert.schedule_restriction),- }) as DeepPartialMap<AlertType | AlertFormType, ValidationErrorType>,+ }) as DeepPartialMap<AlertFormType, ValidationErrorType>,submit: async (alert) => {+ if (+ blockSubmitWithoutHighFrequencyAlertsEntitlement(+ alert.calculation_interval,+ userLogic.values.hasAvailableFeature(AvailableFeature.HIGH_FREQUENCY_ALERTS)+ )+ ) {+ lemonToast.error(HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE)+ throw new Error(HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE)+ }+const payload: AlertTypeWrite = {...alert,subscribed_users: alert.subscribed_users?.map(({ id }) => id),insight: props.insightId,// can only skip weekends for sub-daily alertsskip_weekend:- (alert.calculation_interval === AlertCalculationInterval.EVERY_15_MINUTES ||- alert.calculation_interval === AlertCalculationInterval.DAILY ||- alert.calculation_interval === AlertCalculationInterval.HOURLY) &&+ (alert.calculation_interval === AlertCalculationInterval.DAILY ||+ isHighFrequencyAlertInterval(alert.calculation_interval)) &&alert.skip_weekend,// can only check ongoing interval for absolute value/increase alerts with upper thresholdconfig: {@@ -325,7 +336,7 @@ export const alertFormLogic = kea<alertFormLogicType>([tryShowMCPHint('alerts.create')}- return updatedAlert+ return alertToFormType(updatedAlert, props.insightId)},},})),diff --git a/frontend/src/lib/components/Alerts/alertLogic.ts b/frontend/src/lib/components/Alerts/alertLogic.tsindex 246b2826517e..b1a0be126c8e 100644--- a/frontend/src/lib/components/Alerts/alertLogic.ts+++ b/frontend/src/lib/components/Alerts/alertLogic.ts@@ -53,10 +53,7 @@ function getCheckPlotValue(check: AlertCheck, isAnomalyDetection: boolean): numb}}const v = check.calculated_value- if (v != null && typeof v === 'number' && !Number.isNaN(v)) {- return v- }- return null+ return v != null && !Number.isNaN(v) ? v : null}export const alertLogic = kea<alertLogicType>([@@ -179,10 +176,6 @@ export const alertLogic = kea<alertLogicType>([return (alert?.checks?.length ?? 0) > 0},],- alertHistoryHasChartableHistory: [- (s) => [s.alertHistoryChartSeries],- (series: AlertHistoryChartPoint[]) => series.length > 0,- ],alertHistoryTablePageCount: [(s) => [s.alert],(alert: AlertType | null): number => {@@ -234,9 +227,13 @@ export const alertLogic = kea<alertLogicType>([},})),- events(({ actions }) => ({+ events(({ actions, props }) => ({afterMount() {- actions.loadAlert()+ if (props.alertId) {+ actions.selectAlertHistoryView('chart')+ } else {+ actions.loadAlert()+ }},})),])diff --git a/frontend/src/lib/components/Alerts/types.ts b/frontend/src/lib/components/Alerts/types.tsindex 80e1e5e24bc7..615875a1e1fb 100644--- a/frontend/src/lib/components/Alerts/types.ts+++ b/frontend/src/lib/components/Alerts/types.ts@@ -84,7 +84,7 @@ export type InvestigationVerdict = 'true_positive' | 'false_positive' | 'inconclexport interface AlertCheck {id: stringcreated_at: string- calculated_value: number+ calculated_value: number | nullstate: AlertStatetargets_notified: booleananomaly_scores?: (number | null)[] | nulldiff --git a/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx b/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsxindex ce03a86ae000..19bec00cc9be 100644--- a/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx+++ b/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx@@ -131,7 +131,6 @@ export function AlertHistorySection({ alertId }: { alertId: AlertType['id'] }):alertHistoryChartSeriesName,alertHistoryUsesAnomalyScores,alertHistoryHasHistory,- alertHistoryHasChartableHistory,alertHistoryChecksSortedDesc,alertHistoryTableEntryCount,alertHistoryIsAnomalyDetection,@@ -213,18 +212,16 @@ export function AlertHistorySection({ alertId }: { alertId: AlertType['id'] }):</div>) : (<>- {alertHistoryHasChartableHistory ? (- <LemonSegmentedButton- size="small"- value={alertHistoryView}- onChange={(v) => selectAlertHistoryView(v)}- options={[- { value: 'chart', label: 'Chart' },- { value: 'table', label: 'Table' },- ]}- />- ) : null}- {alertHistoryView === 'chart' && alertHistoryHasChartableHistory ? (+ <LemonSegmentedButton+ size="small"+ value={alertHistoryView}+ onChange={(v) => selectAlertHistoryView(v)}+ options={[+ { value: 'chart', label: 'Chart' },+ { value: 'table', label: 'Table' },+ ]}+ />+ {alertHistoryView === 'chart' ? (<div className="relative">{alertLoading ? <SpinnerOverlay /> : null}<AlertHistoryChartdiff --git a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsxindex cad26db3c68b..e21b403b301c 100644--- a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx+++ b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx@@ -1,102 +1,40 @@import { useActions, useValues } from 'kea'-import { Form, Group } from 'kea-forms'+import { Form } from 'kea-forms'import { useCallback, useMemo } from 'react'-import { IconCalendar, IconChevronLeft, IconClock, IconInfo } from '@posthog/icons'-import {- LemonBanner,- LemonCheckbox,- LemonCollapse,- LemonInput,- LemonSegmentedButton,- LemonSelect,- Link,- SpinnerOverlay,- Tooltip,-} from '@posthog/lemon-ui'+import { IconCalendar, IconChevronLeft } from '@posthog/icons'+import { LemonCheckbox, LemonInput, Link, SpinnerOverlay } from '@posthog/lemon-ui'-import { MemberSelectMultiple } from 'lib/components/MemberSelectMultiple'-import { TZLabel } from 'lib/components/TZLabel'+import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'import { UserActivityIndicator } from 'lib/components/UserActivityIndicator/UserActivityIndicator'import { dayjs } from 'lib/dayjs'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonModal } from 'lib/lemon-ui/LemonModal'-import { alphabet, formatDate } from 'lib/utils'+import { formatDate } from 'lib/utils'import { teamLogic } from 'scenes/teamLogic'import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'-import {- AlertCalculationInterval,- AlertConditionType,- AlertState,- InsightThresholdType,-} from '~/queries/schema/schema-general'-import { InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'+import { AlertCalculationInterval, AlertState } from '~/queries/schema/schema-general'+import { AvailableFeature, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'-import { alertFormLogic, canCheckOngoingInterval, getDefaultSimulationRange } from '../alertFormLogic'+import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection'+import { AlertDefinitionSection } from 'products/alerts/frontend/components/editAlertModal/AlertDefinitionSection'+import { AlertIntervalRow } from 'products/alerts/frontend/components/editAlertModal/AlertIntervalRow'+import { AlertNotificationSection } from 'products/alerts/frontend/components/editAlertModal/AlertNotificationSection'+import { isHighFrequencyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'++import { alertFormLogic, canCheckOngoingInterval } from '../alertFormLogic'import { alertLogic } from '../alertLogic'import { alertNotificationLogic } from '../alertNotificationLogic'import { isNextPlannedEvaluationStale } from '../alertSchedulingStale'import { insightAlertsLogic } from '../insightAlertsLogic'import { SnoozeButton } from '../SnoozeButton'import type { AlertType } from '../types'-import { AlertDestinationSelector } from './AlertDestinationSelector'import { AlertHistorySection, AlertHistorySectionSkeleton } from './AlertHistorySection'-import { DetectorSelector, getDefaultWindow } from './DetectorSelector'-import { InlineAlertNotifications } from './InlineAlertNotifications'-import { QuietHoursFields } from './QuietHoursFields'-import { SimulationSummary } from './SimulationSummary'--function getSimulationRangeOptions(interval: AlertCalculationInterval): { label: string; value: string }[] {- switch (interval) {- case AlertCalculationInterval.EVERY_15_MINUTES:- case AlertCalculationInterval.HOURLY:- return [- { label: 'Last 24h', value: '-24h' },- { label: 'Last 48h', value: '-48h' },- { label: 'Last 72h', value: '-72h' },- { label: 'Last 7d', value: '-168h' },- ]- case AlertCalculationInterval.DAILY:- return [- { label: 'Last 14d', value: '-14d' },- { label: 'Last 30d', value: '-30d' },- { label: 'Last 60d', value: '-60d' },- { label: 'Last 90d', value: '-90d' },- ]- case AlertCalculationInterval.WEEKLY:- return [- { label: 'Last 8w', value: '-8w' },- { label: 'Last 12w', value: '-12w' },- { label: 'Last 26w', value: '-26w' },- { label: 'Last 52w', value: '-52w' },- ]- case AlertCalculationInterval.MONTHLY:- return [- { label: 'Last 6m', value: '-6m' },- { label: 'Last 12m', value: '-12m' },- { label: 'Last 24m', value: '-24m' },- ]- }-}--function alertCalculationIntervalToLabel(interval: AlertCalculationInterval): string {- switch (interval) {- case AlertCalculationInterval.EVERY_15_MINUTES:- return '15 minutes'- case AlertCalculationInterval.HOURLY:- return 'hour'- case AlertCalculationInterval.DAILY:- return 'day'- case AlertCalculationInterval.WEEKLY:- return 'week'- case AlertCalculationInterval.MONTHLY:- return 'month'- }-}interface EditAlertModalProps {isOpen: boolean | undefined@@ -117,8 +55,6 @@ export function EditAlertModal({onEditSuccess,insightLogicProps,}: EditAlertModalProps): JSX.Element {- const alerts15MinuteIntervalEnabled = useFeatureFlag('ALERTS_15_MINUTE_INTERVAL')-const _alertLogic = alertLogic({ alertId })const { alert, alertLoading } = useValues(_alertLogic)@@ -164,6 +100,11 @@ export function EditAlertModal({const anomalyDetectionEnabled = useFeatureFlag('ALERTS_ANOMALY_DETECTION')const inlineNotificationsEnabled = useFeatureFlag('ALERTS_INLINE_NOTIFICATIONS')const investigationAgentEnabled = useFeatureFlag('ALERTS_INVESTIGATION_AGENT')+ const alerts15MinuteIntervalEnabled = useFeatureFlag('ALERTS_15_MINUTE_INTERVAL')++ const { hasAvailableFeature } = useValues(userLogic)+ const { guardAvailableFeature } = useValues(upgradeModalLogic)+ const hasHighFrequencyAlertsEntitlement = hasAvailableFeature(AvailableFeature.HIGH_FREQUENCY_ALERTS)const { pendingNotifications } = useValues(alertNotificationLogic({ alertId: alertId }))const hasPendingNotifications = inlineNotificationsEnabled && pendingNotifications.length > 0@@ -183,7 +124,6 @@ export function EditAlertModal({}, [insightLogicProps, insightId])const creatingNewAlert = alertForm.id === undefined- // can only check ongoing interval for absolute value/increase alerts with upper thresholdconst can_check_ongoing_interval = canCheckOngoingInterval(alertForm)const alertMode = alertForm.detector_config ? 'detector' : 'threshold'const nextPlannedEvaluationStale = useMemo(@@ -210,9 +150,8 @@ export function EditAlertModal({n += 1}if (- (alertForm.calculation_interval === AlertCalculationInterval.EVERY_15_MINUTES ||- alertForm.calculation_interval === AlertCalculationInterval.DAILY ||- alertForm.calculation_interval === AlertCalculationInterval.HOURLY) &&+ (alertForm.calculation_interval === AlertCalculationInterval.DAILY ||+ isHighFrequencyAlertInterval(alertForm.calculation_interval)) &&alertForm.skip_weekend) {n += 1@@ -277,398 +216,34 @@ export function EditAlertModal({<div className="deprecated-space-y-3"><h3 className="mb-0">Definition</h3><div className="deprecated-space-y-3">- {isBreakdownValid && (- <LemonBanner type="warning">- {alertMode === 'detector'- ? 'For trends with breakdown, the detector will independently monitor each breakdown value (up to 25) and fire if any is anomalous.'- : 'For trends with breakdown, the alert will fire if any of the breakdown values breaches the threshold.'}- </LemonBanner>- )}- <div className="flex gap-3 items-center">- <div>When</div>- <Group name={['config']}>- <LemonField name="series_index" className="flex-auto">- <LemonSelect- fullWidth- data-attr="alertForm-series-index"- options={- formulaNodes?.length > 0- ? formulaNodes.map(({ formula, custom_name }, index) => ({- label: `${- custom_name ? custom_name : 'Formula'- } (${formula})`,- value: index,- }))- : (alertSeries?.map(- ({ custom_name, name, event }, index) => ({- label: isBreakdownValid- ? 'any breakdown value'- : `${alphabet[index]} - ${- custom_name ?? name ?? event- }`,- value: isBreakdownValid ? 0 : index,- })- ) ?? [])- }- disabledReason={- isBreakdownValid &&- (alertMode === 'detector'- ? 'For trends with breakdown, the detector will independently monitor each breakdown value (up to 25) and fire if any is anomalous.'- : 'For trends with breakdown, the alert will fire if any of the breakdown values breaches the threshold.')- }- />- </LemonField>- </Group>- </div>-- {anomalyDetectionEnabled && (- <LemonSegmentedButton- fullWidth- value={alertMode}- onChange={(value) => {- if (value === 'detector') {- setAlertFormValue('detector_config', {- type: 'zscore',- threshold: 0.95,- window: getDefaultWindow(alertForm.calculation_interval),- preprocessing: { diffs_n: 1 },- })- } else {- setAlertFormValue('detector_config', null)- }- }}- options={[- {- value: 'threshold',- label: 'Threshold',- tooltip:- 'Alert when a value goes above or below a fixed threshold you define.',- },- {- value: 'detector',- label: 'Anomaly detection',- tooltip:- 'Automatically detect unusual changes using AI (ohhh fancy, jk its just good old stats and ml stuff). No manual thresholds needed.',- },- ]}- />- )}-- {alertMode === 'threshold' ? (- <div className="flex flex-wrap gap-x-3 gap-y-2 items-center">- <Group name={['condition']}>- <LemonField name="type">- <LemonSelect- fullWidth- className="w-40"- data-attr="alertForm-condition"- options={[- {- label: 'has value',- value: AlertConditionType.ABSOLUTE_VALUE,- },- {- label: 'increases by',- value: AlertConditionType.RELATIVE_INCREASE,- disabledReason:- isNonTimeSeriesDisplay &&- 'This condition is only supported for time series trends',- },- {- label: 'decreases by',- value: AlertConditionType.RELATIVE_DECREASE,- disabledReason:- isNonTimeSeriesDisplay &&- 'This condition is only supported for time series trends',- },- ]}- />- </LemonField>- </Group>- <div>less than</div>- <LemonField name="lower">- <LemonInput- type="number"- className="w-30"- data-attr="alertForm-lower-threshold"- value={- alertForm.threshold.configuration.type ===- InsightThresholdType.PERCENTAGE &&- alertForm.threshold.configuration.bounds?.lower- ? alertForm.threshold.configuration.bounds?.lower * 100- : alertForm.threshold.configuration.bounds?.lower- }- onChange={(value) =>- setAlertFormValue('threshold', {- configuration: {- type: alertForm.threshold.configuration.type,- bounds: {- ...alertForm.threshold.configuration.bounds,- lower:- value &&- alertForm.threshold.configuration.type ===- InsightThresholdType.PERCENTAGE- ? value / 100- : value,- },- },- })- }- />- </LemonField>- <div>or more than</div>- <LemonField name="upper">- <LemonInput- type="number"- className="w-30"- data-attr="alertForm-upper-threshold"- value={- alertForm.threshold.configuration.type ===- InsightThresholdType.PERCENTAGE &&- alertForm.threshold.configuration.bounds?.upper- ? alertForm.threshold.configuration.bounds?.upper * 100- : alertForm.threshold.configuration.bounds?.upper- }- onChange={(value) =>- setAlertFormValue('threshold', {- configuration: {- type: alertForm.threshold.configuration.type,- bounds: {- ...alertForm.threshold.configuration.bounds,- upper:- value &&- alertForm.threshold.configuration.type ===- InsightThresholdType.PERCENTAGE- ? value / 100- : value,- },- },- })- }- />- </LemonField>- {alertForm.condition.type !== AlertConditionType.ABSOLUTE_VALUE && (- <Group name={['threshold', 'configuration']}>- <LemonField name="type">- <LemonSegmentedButton- options={[- {- value: InsightThresholdType.PERCENTAGE,- label: '%',- tooltip: 'Percent',- },- {- value: InsightThresholdType.ABSOLUTE,- label: '#',- tooltip: 'Absolute number',- },- ]}- />- </LemonField>- </Group>- )}- </div>- ) : (- <DetectorSelector- value={alertForm.detector_config ?? null}- onChange={(config) => {- setAlertFormValue('detector_config', config)- clearSimulation()- clearSimulationOverlay()- }}- calculationInterval={alertForm.calculation_interval}- />- )}-- {alertMode === 'detector' &&- alertForm.detector_config &&- investigationAgentEnabled && (- <div className="deprecated-space-y-2">- <div className="flex items-center gap-1">- <h4 className="m-0">Investigation agent</h4>- <Tooltip- title="An optional AI agent that investigates anomaly fires against this insight's own data. It runs read-only HogQL queries, looks at the metric chart, and writes its findings — verdict, hypotheses, recommendations — to a notebook linked from the alert history. You can also have it gate notifications so false positives don't page you."- placement="right"- delayMs={0}- >- <IconInfo />- </Tooltip>- </div>- <div className="flex flex-wrap items-center gap-x-6 gap-y-2">- <LemonCheckbox- data-attr="alertForm-investigation-agent-enabled"- checked={!!alertForm.investigation_agent_enabled}- onChange={(checked) =>- setAlertFormValue('investigation_agent_enabled', checked)- }- label={- <span className="flex items-center gap-1">- Run investigation agent when this alert fires- <Tooltip- title="On the transition to firing, an agent validates the anomaly with read-only queries, writes a notebook with its findings, and links it from the alert check history. Runs once per transition."- placement="right"- delayMs={0}- >- <IconInfo />- </Tooltip>- </span>- }- />- <LemonCheckbox- data-attr="alertForm-investigation-gates-notifications"- checked={!!alertForm.investigation_gates_notifications}- onChange={(checked) =>- setAlertFormValue(- 'investigation_gates_notifications',- checked- )- }- disabledReason={- !alertForm.investigation_agent_enabled- ? 'Enable the investigation agent first'- : undefined- }- label={- <span className="flex items-center gap-1">- Wait for the verdict before notifying- <Tooltip- title="Notifications are delayed ~30–90s while the agent investigates. False-positive verdicts are suppressed. A safety-net task force-fires after a few minutes if the investigation stalls, so real fires can't be silently missed."- placement="right"- delayMs={0}- >- <IconInfo />- </Tooltip>- </span>- }- />- </div>- {alertForm.investigation_agent_enabled &&- alertForm.investigation_gates_notifications && (- <div className="flex flex-wrap items-center gap-2 text-sm text-secondary">- <span>On inconclusive verdict</span>- <LemonSegmentedButton- size="xsmall"- value={- alertForm.investigation_inconclusive_action ??- 'notify'- }- onChange={(value) =>- setAlertFormValue(- 'investigation_inconclusive_action',- value- )- }- options={[- {- value: 'notify',- label: 'Notify',- tooltip:- 'Safe default — an unsure agent is itself signal.',- },- {- value: 'suppress',- label: 'Suppress',- tooltip: 'Only notify on true positives.',- },- ]}- />- </div>- )}- </div>- )}-- {alertMode === 'detector' && alertForm.detector_config && (- <div className="deprecated-space-y-2">- <div className="flex gap-2 items-center">- <h4 className="m-0">Simulation</h4>- <LemonSelect- size="small"- data-attr="alertForm-simulate-range"- value={- simulationDateFrom ??- getDefaultSimulationRange(alertForm.calculation_interval)- }- onChange={(value) => setSimulationDateFrom(value)}- options={getSimulationRangeOptions(alertForm.calculation_interval)}- />- <LemonButton- type="secondary"- size="small"- data-attr="alertForm-simulate"- onClick={simulateAlert}- loading={simulationResultLoading}- tooltip="Run the detector on historical data to preview which points would be flagged as anomalies"- >- Simulate- </LemonButton>- </div>- {simulationResult && (- <SimulationSummary- result={simulationResult}- detectorConfig={alertForm.detector_config}- />- )}- </div>- )}-- <div className="flex flex-wrap gap-x-3 gap-y-2 items-center">- <div>Run alert every</div>- <LemonField name="calculation_interval">- <LemonSelect- fullWidth- className="w-28"- data-attr="alertForm-calculation-interval"- options={Object.values(AlertCalculationInterval).map((interval) => ({- label: alertCalculationIntervalToLabel(interval),- value: interval,- hidden:- interval === AlertCalculationInterval.EVERY_15_MINUTES &&- !alerts15MinuteIntervalEnabled,- }))}- />- </LemonField>- <div>- and check {alertForm?.config.check_ongoing_interval ? 'current' : 'last'}- </div>- <LemonSelect- fullWidth- className="w-28"- data-attr="alertForm-trend-interval"- disabledReason={- <>- To change the interval being checked, edit and <b>save</b> the- interval which the insight is 'grouped by'- </>- }- value={trendInterval ?? 'day'}- options={[- {- label: trendInterval ?? 'day',- value: trendInterval ?? 'day',- },- ]}- />- </div>- {!creatingNewAlert && alert ? (- <div className="text-sm text-muted flex flex-wrap items-center gap-x-2 gap-y-0">- <IconClock- className={`size-4 shrink-0 text-muted motion-reduce:animate-none${- !nextPlannedEvaluationStale && !alert.next_check_at- ? ' animate-spin'- : ''- }`}- aria-hidden- />- <span className="shrink-0">Next planned evaluation:</span>- {nextPlannedEvaluationStale ? (- <span>We'll recalculate this after you save.</span>- ) : alert.next_check_at ? (- <TZLabel time={alert.next_check_at} />- ) : (- <span>We're calculating this. This can take a few minutes.</span>- )}- </div>- ) : null}+ <AlertDefinitionSection+ alertForm={alertForm}+ alertMode={alertMode}+ isBreakdownValid={isBreakdownValid}+ isNonTimeSeriesDisplay={isNonTimeSeriesDisplay}+ alertSeries={alertSeries}+ formulaNodes={formulaNodes}+ anomalyDetectionEnabled={anomalyDetectionEnabled}+ investigationAgentEnabled={investigationAgentEnabled}+ simulationResult={simulationResult}+ simulationResultLoading={simulationResultLoading}+ simulationDateFrom={simulationDateFrom}+ onSetAlertFormValue={setAlertFormValue}+ onSimulateAlert={simulateAlert}+ onSetSimulationDateFrom={setSimulationDateFrom}+ onClearSimulation={clearSimulation}+ onClearSimulationOverlay={clearSimulationOverlay}+ />+ <AlertIntervalRow+ alertForm={alertForm}+ creatingNewAlert={creatingNewAlert}+ alert={alert}+ trendInterval={trendInterval}+ alerts15MinuteIntervalEnabled={alerts15MinuteIntervalEnabled}+ hasHighFrequencyAlertsEntitlement={hasHighFrequencyAlertsEntitlement}+ guardAvailableFeature={guardAvailableFeature}+ nextPlannedEvaluationStale={nextPlannedEvaluationStale}+ /></div></div>@@ -686,131 +261,24 @@ export function EditAlertModal({</span></div>- <div>- <h3>Notification</h3>- <div className="flex gap-4 items-center mt-2">- <div>E-mail</div>- <div className="flex-auto">- <MemberSelectMultiple- value={alertForm.subscribed_users?.map((u) => u.id) ?? []}- idKey="id"- onChange={(value) => setAlertFormValue('subscribed_users', value)}- />- </div>- </div>-- <h4 className="mt-4">Destinations</h4>- <div className="mt-4">- {inlineNotificationsEnabled ? (- <InlineAlertNotifications alertId={alertId} />- ) : alertId ? (- <div className="flex flex-col">- <AlertDestinationSelector- alertId={alertId}- insightShortId={insightShortId}- />- </div>- ) : (- <div className="text-muted-alt">- Save alert first to add destinations (e.g. Slack, Webhooks)- </div>- )}- </div>- </div>-- <div className="deprecated-space-y-2">- <LemonCollapse- panels={[- {- key: 'advanced',- header: {- type: enabledAdvancedOptionsCount > 0 ? 'primary' : 'tertiary',- children: (- <span className="flex w-full min-w-0 items-center justify-between gap-2">- <span className="min-w-0">Advanced options</span>- {enabledAdvancedOptionsCount > 0 ? (- <span- className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-current/20 bg-current/10 text-xs font-semibold tabular-nums leading-none"- aria-label={`${enabledAdvancedOptionsCount} advanced option${- enabledAdvancedOptionsCount === 1 ? '' : 's'- } on`}- >- {enabledAdvancedOptionsCount}- </span>- ) : null}- </span>- ),- },- content: (- <div className="space-y-2">- <Group name={['config']}>- <div className="flex gap-1">- <LemonField name="check_ongoing_interval">- <LemonCheckbox- checked={- can_check_ongoing_interval &&- alertForm?.config.check_ongoing_interval- }- data-attr="alertForm-check-ongoing-interval"- fullWidth- label="Check ongoing period"- disabledReason={- !can_check_ongoing_interval &&- 'Can only alert for ongoing period when checking for absolute value/increase above a set upper threshold.'- }- />- </LemonField>- <Tooltip- title="Checks the insight value for the ongoing period (current week/month) that hasn't yet completed. Use this if you want to be alerted right away when the insight value rises/increases above threshold"- placement="right"- delayMs={0}- >- <IconInfo />- </Tooltip>- </div>- </Group>- <LemonField name="skip_weekend">- <LemonCheckbox- checked={- (alertForm?.calculation_interval ===- AlertCalculationInterval.EVERY_15_MINUTES ||- alertForm?.calculation_interval ===- AlertCalculationInterval.DAILY ||- alertForm?.calculation_interval ===- AlertCalculationInterval.HOURLY) &&- alertForm?.skip_weekend- }- data-attr="alertForm-skip-weekend"- fullWidth- label="Skip checking on weekends"- disabledReason={- alertForm?.calculation_interval !==- AlertCalculationInterval.EVERY_15_MINUTES &&- alertForm?.calculation_interval !==- AlertCalculationInterval.DAILY &&- alertForm?.calculation_interval !==- AlertCalculationInterval.HOURLY &&- 'Can only skip weekend checking for 15-minute, hourly, or daily alerts'- }- />- </LemonField>- <QuietHoursFields- scheduleRestriction={alertForm.schedule_restriction}- calculationInterval={alertForm.calculation_interval}- teamTimezone={projectTimezone}- onChange={(next) =>- setAlertFormValue('schedule_restriction', next)- }- />- </div>- ),- },- ]}- />- </div>+ <AlertNotificationSection+ alertForm={alertForm}+ alertId={alertId}+ insightShortId={insightShortId}+ inlineNotificationsEnabled={inlineNotificationsEnabled}+ onSetAlertFormValue={setAlertFormValue}+ />++ <AlertAdvancedOptionsSection+ alertForm={alertForm}+ canCheckOngoingInterval={can_check_ongoing_interval}+ projectTimezone={projectTimezone}+ enabledAdvancedOptionsCount={enabledAdvancedOptionsCount}+ onSetAlertFormValue={setAlertFormValue}+ /></div>- {!creatingNewAlert && alertId ? (+ {alertId ? (alert ? (<AlertHistorySection alertId={alert.id} />) : alertLoading ? (diff --git a/frontend/src/lib/components/PayGateMini/PayGateMini.stories.tsx b/frontend/src/lib/components/PayGateMini/PayGateMini.stories.tsxindex 9226c04386e4..e69858d3f303 100644--- a/frontend/src/lib/components/PayGateMini/PayGateMini.stories.tsx+++ b/frontend/src/lib/components/PayGateMini/PayGateMini.stories.tsx@@ -71,6 +71,10 @@ export const PayGateMiniGrandfathered: Story = {args: { feature: AvailableFeature.SUBSCRIPTIONS, isGrandfathered: true },}+export const PayGateMiniHighFrequencyAlerts: Story = {+ args: { feature: AvailableFeature.HIGH_FREQUENCY_ALERTS },+}+export const PayGateMiniAddon: Story = {args: { feature: AvailableFeature.GROUP_ANALYTICS },}diff --git a/frontend/src/scenes/insights/InsightModals.tsx b/frontend/src/scenes/insights/InsightModals.tsxindex 4bac86b2d9c3..7843e7ef95fb 100644--- a/frontend/src/scenes/insights/InsightModals.tsx+++ b/frontend/src/scenes/insights/InsightModals.tsx@@ -94,7 +94,7 @@ function InsightAlertsModals({ insightLogicProps }: { insightLogicProps: Insightreturn (<>- {insightMode === ItemMode.Alerts && (+ {insightMode === ItemMode.Alerts && !alertId && (<ManageAlertsModalonClose={() => push(urls.insightView(insight.short_id as InsightShortId))}isOpen={insightMode === ItemMode.Alerts}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8262e5a622cd..a7ada2203826 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -339,7 +339,7 @@ importers:version: 0.25.10jest:specifier: ^29.7.0- version: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ version: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))puppeteer:specifier: 19.0.0version: 19.0.0([email protected])@@ -609,6 +609,9 @@ importers:'@posthog/products-actions':specifier: workspace:*version: link:../products/actions+ '@posthog/products-alerts':+ specifier: workspace:*+ version: link:../products/alerts'@posthog/products-business-knowledge':specifier: workspace:*version: link:../products/business_knowledge@@ -2079,7 +2082,36 @@ importers:specifier: 'catalog:'version: 0.2.4([email protected]([email protected]))- products/alerts: {}+ products/alerts:+ dependencies:+ '@posthog/icons':+ specifier: '*'+ '@posthog/lemon-ui':+ specifier: '*'+ version: 0.0.0([email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected]([email protected]))([email protected])+ '@types/react':+ specifier: 18.3.27+ version: 18.3.27+ kea-forms:+ specifier: '*'+ version: 3.2.0([email protected]([email protected]))+ posthog-js:+ specifier: 'catalog:'+ version: 1.376.0+ react:+ specifier: 18.3.1+ version: 18.3.1+ typescript:+ specifier: 6.0.3+ version: 6.0.3+ devDependencies:+ '@storybook/react':+ specifier: 'catalog:'+ version: 7.6.24([email protected])([email protected]([email protected]))([email protected])([email protected])+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected]([email protected]))products/analytics_platform: {}@@ -35152,7 +35184,7 @@ snapshots:commander: 9.4.1expect-playwright: 0.8.0glob: 10.4.5- jest: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-circus: 29.7.0jest-environment-node: 29.7.0jest-junit: 16.0.0@@ -43447,7 +43479,7 @@ snapshots:dependencies:expect-playwright: 0.8.0- jest: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-circus: 29.7.0jest-environment-node: 29.7.0jest-process-manager: 0.4.0@@ -43882,7 +43914,7 @@ snapshots:dependencies:ansi-escapes: 6.0.0chalk: 5.6.2- jest: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-regex-util: 29.6.3jest-watcher: 29.7.0slash: 5.1.0diff --git a/frontend/src/lib/components/Alerts/views/QuietHoursDayTimeline.tsx b/products/alerts/frontend/components/QuietHoursDayTimeline.tsxsimilarity index 94%rename from frontend/src/lib/components/Alerts/views/QuietHoursDayTimeline.tsxrename to products/alerts/frontend/components/QuietHoursDayTimeline.tsxindex 69474dbda9af..fc8fcfaf0cf2 100644--- a/frontend/src/lib/components/Alerts/views/QuietHoursDayTimeline.tsx+++ b/products/alerts/frontend/components/QuietHoursDayTimeline.tsx@@ -1,5 +1,8 @@-import { blockedAndAllowedMinuteIntervalsForQuietHours, MINUTES_PER_DAY } from '../scheduleRestrictionValidation'-import type { BlockedWindow } from '../types'+import {+ blockedAndAllowedMinuteIntervalsForQuietHours,+ MINUTES_PER_DAY,+} from 'lib/components/Alerts/scheduleRestrictionValidation'+import type { BlockedWindow } from 'lib/components/Alerts/types'type TimelineSegment = { kind: 'blocked' | 'allowed'; from: number; to: number }diff --git a/frontend/src/lib/components/Alerts/views/QuietHoursFields.stories.tsx b/products/alerts/frontend/components/QuietHoursFields.stories.tsxsimilarity index 96%rename from frontend/src/lib/components/Alerts/views/QuietHoursFields.stories.tsxrename to products/alerts/frontend/components/QuietHoursFields.stories.tsxindex bb48504ef05b..b8a6b2bcd252 100644--- a/frontend/src/lib/components/Alerts/views/QuietHoursFields.stories.tsx+++ b/products/alerts/frontend/components/QuietHoursFields.stories.tsx@@ -1,9 +1,10 @@import type { Meta, StoryObj } from '@storybook/react'import { useState } from 'react'+import type { ScheduleRestriction } from 'lib/components/Alerts/types'+import { AlertCalculationInterval } from '~/queries/schema/schema-general'-import type { ScheduleRestriction } from '../types'import type { QuietHoursFieldsProps } from './QuietHoursFields'import { QuietHoursFields } from './QuietHoursFields'diff --git a/frontend/src/lib/components/Alerts/views/QuietHoursFields.tsx b/products/alerts/frontend/components/QuietHoursFields.tsxsimilarity index 79%rename from frontend/src/lib/components/Alerts/views/QuietHoursFields.tsxrename to products/alerts/frontend/components/QuietHoursFields.tsxindex d14f12fc364e..f8871f057f30 100644--- a/frontend/src/lib/components/Alerts/views/QuietHoursFields.tsx+++ b/products/alerts/frontend/components/QuietHoursFields.tsx@@ -3,11 +3,14 @@ import { useMemo, type FocusEvent } from 'react'import { IconTrash } from '@posthog/icons'import { LemonBanner, LemonButton, LemonCheckbox, LemonInput } from '@posthog/lemon-ui'+import { findQuietHoursIssues, MAX_BLOCKED_WINDOWS } from 'lib/components/Alerts/scheduleRestrictionValidation'+import type { BlockedWindow, ScheduleRestriction } from 'lib/components/Alerts/types'+import { AlertCalculationInterval } from '~/queries/schema/schema-general'-import { estimateHourlyCheckSlotsNext24h } from '../scheduleRestrictionPreview'-import { findQuietHoursIssues, MAX_BLOCKED_WINDOWS } from '../scheduleRestrictionValidation'-import type { BlockedWindow, ScheduleRestriction } from '../types'+import { isHighFrequencyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'+import { estimateCheckSlotsNext24h } from 'products/alerts/frontend/logic/scheduleRestrictionPreview'+import { QuietHoursDayTimeline } from './QuietHoursDayTimeline'const DEFAULT_OVERNIGHT: BlockedWindow = { start: '22:00', end: '07:00' }@@ -76,24 +79,41 @@ export function QuietHoursFields({setWindows([{ ...DEFAULT_OVERNIGHT }])}- const hourlyApprox = enabled- ? estimateHourlyCheckSlotsNext24h(scheduleRestriction?.blocked_windows, teamTimezone)- : null+ const highFrequencySlotPreview = useMemo(() => {+ const cadenceMinutes =+ calculationInterval === AlertCalculationInterval.EVERY_15_MINUTES+ ? 15+ : calculationInterval === AlertCalculationInterval.HOURLY+ ? 60+ : null+ if (!enabled || cadenceMinutes == null) {+ return null+ }+ const slotApprox = estimateCheckSlotsNext24h(scheduleRestriction?.blocked_windows, teamTimezone, cadenceMinutes)+ const totalSlots = (24 * 60) / cadenceMinutes+ if (slotApprox >= totalSlots) {+ return null+ }+ return {+ slotApprox,+ totalSlots,+ cadenceLabel: cadenceMinutes === 15 ? '15-minute' : 'hourly',+ intervalLabel: cadenceMinutes === 15 ? '15 minutes' : 'clock hour',+ }+ }, [enabled, calculationInterval, scheduleRestriction?.blocked_windows, teamTimezone])const quietIssue = useMemo(() => (enabled && windows.length > 0 ? findQuietHoursIssues(windows) : null),[enabled, windows])- const nonHourlyInterval =- calculationInterval === AlertCalculationInterval.EVERY_15_MINUTES ||- calculationInterval === AlertCalculationInterval.HOURLY- ? null- : calculationInterval === AlertCalculationInterval.DAILY- ? 'day'- : calculationInterval === AlertCalculationInterval.WEEKLY- ? 'week'- : 'month'+ const nonHighFrequencyInterval = !isHighFrequencyAlertInterval(calculationInterval)+ ? calculationInterval === AlertCalculationInterval.DAILY+ ? 'day'+ : calculationInterval === AlertCalculationInterval.WEEKLY+ ? 'week'+ : 'month'+ : nullconst atWindowLimit = windows.length >= MAX_BLOCKED_WINDOWSconst addWindowButtonLabel = atWindowLimit ? `Maximum of ${MAX_BLOCKED_WINDOWS} time windows` : 'Add time window'@@ -110,10 +130,10 @@ export function QuietHoursFields({/>{enabled ? (<>- {nonHourlyInterval ? (+ {nonHighFrequencyInterval ? (<LemonBanner type="info">If a scheduled run would fall during quiet hours, it runs at the next allowed time in that- same day or cycle instead of waiting until the next {nonHourlyInterval}.+ same day or cycle instead of waiting until the next {nonHighFrequencyInterval}.</LemonBanner>) : null}<div className="flex flex-wrap gap-2">@@ -121,13 +141,11 @@ export function QuietHoursFields({Preset: overnight (10pm–7am)</LemonButton></div>- {(calculationInterval === AlertCalculationInterval.EVERY_15_MINUTES ||- calculationInterval === AlertCalculationInterval.HOURLY) &&- hourlyApprox != null &&- hourlyApprox < 24 ? (+ {highFrequencySlotPreview ? (<div className="text-muted text-sm">- For hourly alerts we schedule about one check per clock hour. Roughly {hourlyApprox} of the- next 24 hours would still run outside quiet hours.+ For {highFrequencySlotPreview.cadenceLabel} alerts we schedule about one check every{' '}+ {highFrequencySlotPreview.intervalLabel}. Roughly {highFrequencySlotPreview.slotApprox} of+ the next {highFrequencySlotPreview.totalSlots} slots would still run outside quiet hours.</div>) : null}{quietIssue ? <LemonBanner type="error">{quietIssue.message}</LemonBanner> : null}diff --git a/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsxnew file mode 100644index 000000000000..6fe52c3a37b3--- /dev/null+++ b/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx@@ -0,0 +1,116 @@+import { Group } from 'kea-forms'++import { IconInfo } from '@posthog/icons'+import { LemonCheckbox, LemonCollapse, Tooltip } from '@posthog/lemon-ui'++import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'+import { LemonField } from 'lib/lemon-ui/LemonField'++import { AlertCalculationInterval } from '~/queries/schema/schema-general'++import { isHighFrequencyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'++import { QuietHoursFields } from '../QuietHoursFields'++export interface AlertAdvancedOptionsSectionProps {+ alertForm: AlertFormType+ canCheckOngoingInterval: boolean+ projectTimezone: string+ enabledAdvancedOptionsCount: number+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void+}++export function AlertAdvancedOptionsSection({+ alertForm,+ canCheckOngoingInterval: can_check_ongoing_interval,+ projectTimezone,+ enabledAdvancedOptionsCount,+ onSetAlertFormValue,+}: AlertAdvancedOptionsSectionProps): JSX.Element {+ return (+ <div className="deprecated-space-y-2">+ <LemonCollapse+ panels={[+ {+ key: 'advanced',+ header: {+ type: enabledAdvancedOptionsCount > 0 ? 'primary' : 'tertiary',+ children: (+ <span className="flex w-full min-w-0 items-center justify-between gap-2">+ <span className="min-w-0">Advanced options</span>+ {enabledAdvancedOptionsCount > 0 ? (+ <span+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-current/20 bg-current/10 text-xs font-semibold tabular-nums leading-none"+ aria-label={`${enabledAdvancedOptionsCount} advanced option${+ enabledAdvancedOptionsCount === 1 ? '' : 's'+ } on`}+ >+ {enabledAdvancedOptionsCount}+ </span>+ ) : null}+ </span>+ ),+ },+ content: (+ <div className="space-y-2">+ <Group name={['config']}>+ <div className="flex gap-1">+ <LemonField name="check_ongoing_interval">+ <LemonCheckbox+ checked={+ can_check_ongoing_interval &&+ alertForm?.config.check_ongoing_interval+ }+ data-attr="alertForm-check-ongoing-interval"+ fullWidth+ label="Check ongoing period"+ disabledReason={+ !can_check_ongoing_interval &&+ 'Can only alert for ongoing period when checking for absolute value/increase above a set upper threshold.'+ }+ />+ </LemonField>+ <Tooltip+ title="Checks the insight value for the ongoing period (current week/month) that hasn't yet completed. Use this if you want to be alerted right away when the insight value rises/increases above threshold"+ placement="right"+ delayMs={0}+ >+ <IconInfo />+ </Tooltip>+ </div>+ </Group>+ <LemonField name="skip_weekend">+ <LemonCheckbox+ checked={+ (alertForm?.calculation_interval === AlertCalculationInterval.DAILY ||+ isHighFrequencyAlertInterval(+ alertForm?.calculation_interval ?? AlertCalculationInterval.DAILY+ )) &&+ alertForm?.skip_weekend+ }+ data-attr="alertForm-skip-weekend"+ fullWidth+ label="Skip checking on weekends"+ disabledReason={+ alertForm?.calculation_interval !== AlertCalculationInterval.DAILY &&+ !isHighFrequencyAlertInterval(+ alertForm?.calculation_interval ?? AlertCalculationInterval.DAILY+ ) &&+ 'Can only skip weekend checking for 15-minute, hourly, or daily alerts'+ }+ />+ </LemonField>+ <QuietHoursFields+ scheduleRestriction={alertForm.schedule_restriction}+ calculationInterval={alertForm.calculation_interval}+ teamTimezone={projectTimezone}+ onChange={(next) => onSetAlertFormValue('schedule_restriction', next)}+ />+ </div>+ ),+ },+ ]}+ />+ </div>+ )+}diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsxnew file mode 100644index 000000000000..66d58301c057--- /dev/null+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx@@ -0,0 +1,367 @@+import { Group } from 'kea-forms'++import { IconInfo } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonCheckbox,+ LemonInput,+ LemonSegmentedButton,+ LemonSelect,+ Tooltip,+} from '@posthog/lemon-ui'++import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'+import { AlertSimulationResult } from 'lib/components/Alerts/types'+import { DetectorSelector, getDefaultWindow } from 'lib/components/Alerts/views/DetectorSelector'+import { SimulationSummary } from 'lib/components/Alerts/views/SimulationSummary'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { alphabet } from 'lib/utils'++import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'++import { getDefaultSimulationRange } from 'products/alerts/frontend/logic/alertIntervalHelpers'++import { getSimulationRangeOptions } from './editAlertModalUtils'++export interface AlertDefinitionSectionProps {+ alertForm: AlertFormType+ alertMode: 'detector' | 'threshold'+ isBreakdownValid: boolean+ isNonTimeSeriesDisplay: boolean+ alertSeries: Array<{ custom_name?: string | null; name?: string | null; event?: string | null }> | null+ formulaNodes: Array<{ formula: string; custom_name?: string | null }> | undefined+ anomalyDetectionEnabled: boolean+ investigationAgentEnabled: boolean+ simulationResult: AlertSimulationResult | null+ simulationResultLoading: boolean+ simulationDateFrom: string | null+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void+ onSimulateAlert: () => void+ onSetSimulationDateFrom: (value: string) => void+ onClearSimulation: () => void+ onClearSimulationOverlay: () => void+}++export function AlertDefinitionSection({+ alertForm,+ alertMode,+ isBreakdownValid,+ isNonTimeSeriesDisplay,+ alertSeries,+ formulaNodes,+ anomalyDetectionEnabled,+ investigationAgentEnabled,+ simulationResult,+ simulationResultLoading,+ simulationDateFrom,+ onSetAlertFormValue,+ onSimulateAlert,+ onSetSimulationDateFrom,+ onClearSimulation,+ onClearSimulationOverlay,+}: AlertDefinitionSectionProps): JSX.Element {+ return (+ <>+ {isBreakdownValid && (+ <LemonBanner type="warning">+ {alertMode === 'detector'+ ? 'For trends with breakdown, the detector will independently monitor each breakdown value (up to 25) and fire if any is anomalous.'+ : 'For trends with breakdown, the alert will fire if any of the breakdown values breaches the threshold.'}+ </LemonBanner>+ )}+ <div className="flex gap-3 items-center">+ <div>When</div>+ <Group name={['config']}>+ <LemonField name="series_index" className="flex-auto">+ <LemonSelect+ fullWidth+ data-attr="alertForm-series-index"+ options={+ (formulaNodes?.length ?? 0) > 0+ ? (formulaNodes ?? []).map(({ formula, custom_name }, index) => ({+ label: `${custom_name ? custom_name : 'Formula'} (${formula})`,+ value: index,+ }))+ : (alertSeries?.map(({ custom_name, name, event }, index) => ({+ label: isBreakdownValid+ ? 'any breakdown value'+ : `${alphabet[index]} - ${custom_name ?? name ?? event}`,+ value: isBreakdownValid ? 0 : index,+ })) ?? [])+ }+ disabledReason={+ isBreakdownValid &&+ (alertMode === 'detector'+ ? 'For trends with breakdown, the detector will independently monitor each breakdown value (up to 25) and fire if any is anomalous.'+ : 'For trends with breakdown, the alert will fire if any of the breakdown values breaches the threshold.')+ }+ />+ </LemonField>+ </Group>+ </div>++ {anomalyDetectionEnabled && (+ <LemonSegmentedButton+ fullWidth+ value={alertMode}+ onChange={(value) => {+ if (value === 'detector') {+ onSetAlertFormValue('detector_config', {+ type: 'zscore',+ threshold: 0.95,+ window: getDefaultWindow(alertForm.calculation_interval),+ preprocessing: { diffs_n: 1 },+ })+ } else {+ onSetAlertFormValue('detector_config', null)+ }+ }}+ options={[+ {+ value: 'threshold',+ label: 'Threshold',+ tooltip: 'Alert when a value goes above or below a fixed threshold you define.',+ },+ {+ value: 'detector',+ label: 'Anomaly detection',+ tooltip:+ 'Automatically detect unusual changes using AI (ohhh fancy, jk its just good old stats and ml stuff). No manual thresholds needed.',+ },+ ]}+ />+ )}++ {alertMode === 'threshold' ? (+ <div className="flex flex-wrap gap-x-3 gap-y-2 items-center">+ <Group name={['condition']}>+ <LemonField name="type">+ <LemonSelect+ fullWidth+ className="w-40"+ data-attr="alertForm-condition"+ options={[+ {+ label: 'has value',+ value: AlertConditionType.ABSOLUTE_VALUE,+ },+ {+ label: 'increases by',+ value: AlertConditionType.RELATIVE_INCREASE,+ disabledReason:+ isNonTimeSeriesDisplay &&+ 'This condition is only supported for time series trends',+ },+ {+ label: 'decreases by',+ value: AlertConditionType.RELATIVE_DECREASE,+ disabledReason:+ isNonTimeSeriesDisplay &&+ 'This condition is only supported for time series trends',+ },+ ]}+ />+ </LemonField>+ </Group>+ <div>less than</div>+ <LemonField name="lower">+ <LemonInput+ type="number"+ className="w-30"+ data-attr="alertForm-lower-threshold"+ value={+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE &&+ alertForm.threshold.configuration.bounds?.lower+ ? alertForm.threshold.configuration.bounds?.lower * 100+ : alertForm.threshold.configuration.bounds?.lower+ }+ onChange={(value) =>+ onSetAlertFormValue('threshold', {+ configuration: {+ type: alertForm.threshold.configuration.type,+ bounds: {+ ...alertForm.threshold.configuration.bounds,+ lower:+ value &&+ alertForm.threshold.configuration.type ===+ InsightThresholdType.PERCENTAGE+ ? value / 100+ : value,+ },+ },+ })+ }+ />+ </LemonField>+ <div>or more than</div>+ <LemonField name="upper">+ <LemonInput+ type="number"+ className="w-30"+ data-attr="alertForm-upper-threshold"+ value={+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE &&+ alertForm.threshold.configuration.bounds?.upper+ ? alertForm.threshold.configuration.bounds?.upper * 100+ : alertForm.threshold.configuration.bounds?.upper+ }+ onChange={(value) =>+ onSetAlertFormValue('threshold', {+ configuration: {+ type: alertForm.threshold.configuration.type,+ bounds: {+ ...alertForm.threshold.configuration.bounds,+ upper:+ value &&+ alertForm.threshold.configuration.type ===+ InsightThresholdType.PERCENTAGE+ ? value / 100+ : value,+ },+ },+ })+ }+ />+ </LemonField>+ {alertForm.condition.type !== AlertConditionType.ABSOLUTE_VALUE && (+ <Group name={['threshold', 'configuration']}>+ <LemonField name="type">+ <LemonSegmentedButton+ options={[+ {+ value: InsightThresholdType.PERCENTAGE,+ label: '%',+ tooltip: 'Percent',+ },+ {+ value: InsightThresholdType.ABSOLUTE,+ label: '#',+ tooltip: 'Absolute number',+ },+ ]}+ />+ </LemonField>+ </Group>+ )}+ </div>+ ) : (+ <DetectorSelector+ value={alertForm.detector_config ?? null}+ onChange={(config) => {+ onSetAlertFormValue('detector_config', config)+ onClearSimulation()+ onClearSimulationOverlay()+ }}+ calculationInterval={alertForm.calculation_interval}+ />+ )}++ {alertMode === 'detector' && alertForm.detector_config && investigationAgentEnabled && (+ <div className="deprecated-space-y-2">+ <div className="flex items-center gap-1">+ <h4 className="m-0">Investigation agent</h4>+ <Tooltip+ title="An optional AI agent that investigates anomaly fires against this insight's own data. It runs read-only HogQL queries, looks at the metric chart, and writes its findings — verdict, hypotheses, recommendations — to a notebook linked from the alert history. You can also have it gate notifications so false positives don't page you."+ placement="right"+ delayMs={0}+ >+ <IconInfo />+ </Tooltip>+ </div>+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2">+ <LemonCheckbox+ data-attr="alertForm-investigation-agent-enabled"+ checked={!!alertForm.investigation_agent_enabled}+ onChange={(checked) => onSetAlertFormValue('investigation_agent_enabled', checked)}+ label={+ <span className="flex items-center gap-1">+ Run investigation agent when this alert fires+ <Tooltip+ title="On the transition to firing, an agent validates the anomaly with read-only queries, writes a notebook with its findings, and links it from the alert check history. Runs once per transition."+ placement="right"+ delayMs={0}+ >+ <IconInfo />+ </Tooltip>+ </span>+ }+ />+ <LemonCheckbox+ data-attr="alertForm-investigation-gates-notifications"+ checked={!!alertForm.investigation_gates_notifications}+ onChange={(checked) => onSetAlertFormValue('investigation_gates_notifications', checked)}+ disabledReason={+ !alertForm.investigation_agent_enabled+ ? 'Enable the investigation agent first'+ : undefined+ }+ label={+ <span className="flex items-center gap-1">+ Wait for the verdict before notifying+ <Tooltip+ title="Notifications are delayed ~30–90s while the agent investigates. False-positive verdicts are suppressed. A safety-net task force-fires after a few minutes if the investigation stalls, so real fires can't be silently missed."+ placement="right"+ delayMs={0}+ >+ <IconInfo />+ </Tooltip>+ </span>+ }+ />+ </div>+ {alertForm.investigation_agent_enabled && alertForm.investigation_gates_notifications && (+ <div className="flex flex-wrap items-center gap-2 text-sm text-secondary">+ <span>On inconclusive verdict</span>+ <LemonSegmentedButton+ size="xsmall"+ value={alertForm.investigation_inconclusive_action ?? 'notify'}+ onChange={(value) => onSetAlertFormValue('investigation_inconclusive_action', value)}+ options={[+ {+ value: 'notify',+ label: 'Notify',+ tooltip: 'Safe default — an unsure agent is itself signal.',+ },+ {+ value: 'suppress',+ label: 'Suppress',+ tooltip: 'Only notify on true positives.',+ },+ ]}+ />+ </div>+ )}+ </div>+ )}++ {alertMode === 'detector' && alertForm.detector_config && (+ <div className="deprecated-space-y-2">+ <div className="flex gap-2 items-center">+ <h4 className="m-0">Simulation</h4>+ <LemonSelect+ size="small"+ data-attr="alertForm-simulate-range"+ value={simulationDateFrom ?? getDefaultSimulationRange(alertForm.calculation_interval)}+ onChange={(value) => onSetSimulationDateFrom(value)}+ options={getSimulationRangeOptions(alertForm.calculation_interval)}+ />+ <LemonButton+ type="secondary"+ size="small"+ data-attr="alertForm-simulate"+ onClick={onSimulateAlert}+ loading={simulationResultLoading}+ tooltip="Run the detector on historical data to preview which points would be flagged as anomalies"+ >+ Simulate+ </LemonButton>+ </div>+ {simulationResult && (+ <SimulationSummary result={simulationResult} detectorConfig={alertForm.detector_config} />+ )}+ </div>+ )}+ </>+ )+}diff --git a/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx b/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsxnew file mode 100644index 000000000000..e63c2c04054d--- /dev/null+++ b/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx@@ -0,0 +1,100 @@+import { IconClock } from '@posthog/icons'+import { LemonSelect } from '@posthog/lemon-ui'++import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'+import { AlertType } from 'lib/components/Alerts/types'+import { TZLabel } from 'lib/components/TZLabel'+import type { GuardAvailableFeatureFn } from 'lib/components/UpgradeModal/upgradeModalLogic'+import { LemonField } from 'lib/lemon-ui/LemonField'++import { selectAlertCalculationInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'++import { getAlertIntervalOptions } from './editAlertModalUtils'++export interface AlertIntervalRowProps {+ alertForm: AlertFormType+ creatingNewAlert: boolean+ alert: AlertType | null | undefined+ trendInterval: string | null | undefined+ alerts15MinuteIntervalEnabled: boolean+ hasHighFrequencyAlertsEntitlement: boolean+ guardAvailableFeature: GuardAvailableFeatureFn+ nextPlannedEvaluationStale: boolean+}++export function AlertIntervalRow({+ alertForm,+ creatingNewAlert,+ alert,+ trendInterval,+ alerts15MinuteIntervalEnabled,+ hasHighFrequencyAlertsEntitlement,+ guardAvailableFeature,+ nextPlannedEvaluationStale,+}: AlertIntervalRowProps): JSX.Element {+ return (+ <>+ <div className="flex flex-wrap gap-x-3 gap-y-2 items-center">+ <div>Run alert every</div>+ <LemonField name="calculation_interval">+ {({ value, onChange }) => (+ <LemonSelect+ fullWidth+ className="w-36 shrink-0 whitespace-nowrap"+ data-attr="alertForm-calculation-interval"+ value={value}+ options={getAlertIntervalOptions(+ alerts15MinuteIntervalEnabled,+ hasHighFrequencyAlertsEntitlement+ )}+ onChange={(interval) => {+ selectAlertCalculationInterval(interval, {+ guardAvailableFeature,+ onSelect: onChange,+ hasHighFrequencyAlertsEntitlement,+ })+ }}+ />+ )}+ </LemonField>+ <div>and check {alertForm?.config.check_ongoing_interval ? 'current' : 'last'}</div>+ <LemonSelect+ fullWidth+ className="w-28"+ data-attr="alertForm-trend-interval"+ disabledReason={+ <>+ To change the interval being checked, edit and <b>save</b> the interval which the insight is+ 'grouped by'+ </>+ }+ value={trendInterval ?? 'day'}+ options={[+ {+ label: trendInterval ?? 'day',+ value: trendInterval ?? 'day',+ },+ ]}+ />+ </div>+ {!creatingNewAlert && alert ? (+ <div className="text-sm text-muted flex flex-wrap items-center gap-x-2 gap-y-0">+ <IconClock+ className={`size-4 shrink-0 text-muted motion-reduce:animate-none${+ !nextPlannedEvaluationStale && !alert.next_check_at ? ' animate-spin' : ''+ }`}+ aria-hidden+ />+ <span className="shrink-0">Next planned evaluation:</span>+ {nextPlannedEvaluationStale ? (+ <span>We'll recalculate this after you save.</span>+ ) : alert.next_check_at ? (+ <TZLabel time={alert.next_check_at} />+ ) : (+ <span>We're calculating this. This can take a few minutes.</span>+ )}+ </div>+ ) : null}+ </>+ )+}diff --git a/products/alerts/frontend/components/editAlertModal/AlertNotificationSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertNotificationSection.tsxnew file mode 100644index 000000000000..580dfa9fdaaf--- /dev/null+++ b/products/alerts/frontend/components/editAlertModal/AlertNotificationSection.tsx@@ -0,0 +1,52 @@+import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'+import { AlertType } from 'lib/components/Alerts/types'+import { AlertDestinationSelector } from 'lib/components/Alerts/views/AlertDestinationSelector'+import { InlineAlertNotifications } from 'lib/components/Alerts/views/InlineAlertNotifications'+import { MemberSelectMultiple } from 'lib/components/MemberSelectMultiple'++import { InsightShortId } from '~/types'++export interface AlertNotificationSectionProps {+ alertForm: AlertFormType+ alertId: AlertType['id'] | undefined+ insightShortId: InsightShortId+ inlineNotificationsEnabled: boolean+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void+}++export function AlertNotificationSection({+ alertForm,+ alertId,+ insightShortId,+ inlineNotificationsEnabled,+ onSetAlertFormValue,+}: AlertNotificationSectionProps): JSX.Element {+ return (+ <div>+ <h3>Notification</h3>+ <div className="flex gap-4 items-center mt-2">+ <div>E-mail</div>+ <div className="flex-auto">+ <MemberSelectMultiple+ value={alertForm.subscribed_users?.map((u) => u.id) ?? []}+ idKey="id"+ onChange={(value) => onSetAlertFormValue('subscribed_users', value)}+ />+ </div>+ </div>++ <h4 className="mt-4">Destinations</h4>+ <div className="mt-4">+ {inlineNotificationsEnabled ? (+ <InlineAlertNotifications alertId={alertId} />+ ) : alertId ? (+ <div className="flex flex-col">+ <AlertDestinationSelector alertId={alertId} insightShortId={insightShortId} />+ </div>+ ) : (+ <div className="text-muted-alt">Save alert first to add destinations (e.g. Slack, Webhooks)</div>+ )}+ </div>+ </div>+ )+}diff --git a/products/alerts/frontend/components/editAlertModal/editAlertModalUtils.tsx b/products/alerts/frontend/components/editAlertModal/editAlertModalUtils.tsxnew file mode 100644index 000000000000..5628e50de604--- /dev/null+++ b/products/alerts/frontend/components/editAlertModal/editAlertModalUtils.tsx@@ -0,0 +1,89 @@+import { IconLock } from '@posthog/icons'++import { AlertCalculationInterval } from '~/queries/schema/schema-general'++export function getSimulationRangeOptions(interval: AlertCalculationInterval): { label: string; value: string }[] {+ switch (interval) {+ case AlertCalculationInterval.EVERY_15_MINUTES:+ return [+ { label: 'Last 12h', value: '-12h' },+ { label: 'Last 24h', value: '-24h' },+ { label: 'Last 48h', value: '-48h' },+ { label: 'Last 72h', value: '-72h' },+ { label: 'Last 7d', value: '-168h' },+ ]+ case AlertCalculationInterval.HOURLY:+ return [+ { label: 'Last 24h', value: '-24h' },+ { label: 'Last 48h', value: '-48h' },+ { label: 'Last 72h', value: '-72h' },+ { label: 'Last 7d', value: '-168h' },+ ]+ case AlertCalculationInterval.DAILY:+ return [+ { label: 'Last 14d', value: '-14d' },+ { label: 'Last 30d', value: '-30d' },+ { label: 'Last 60d', value: '-60d' },+ { label: 'Last 90d', value: '-90d' },+ ]+ case AlertCalculationInterval.WEEKLY:+ return [+ { label: 'Last 8w', value: '-8w' },+ { label: 'Last 12w', value: '-12w' },+ { label: 'Last 26w', value: '-26w' },+ { label: 'Last 52w', value: '-52w' },+ ]+ case AlertCalculationInterval.MONTHLY:+ return [+ { label: 'Last 6m', value: '-6m' },+ { label: 'Last 12m', value: '-12m' },+ { label: 'Last 24m', value: '-24m' },+ ]+ }+}++export function alertCalculationIntervalToLabel(interval: AlertCalculationInterval): string {+ switch (interval) {+ case AlertCalculationInterval.EVERY_15_MINUTES:+ return '15 minutes'+ case AlertCalculationInterval.HOURLY:+ return 'hour'+ case AlertCalculationInterval.DAILY:+ return 'day'+ case AlertCalculationInterval.WEEKLY:+ return 'week'+ case AlertCalculationInterval.MONTHLY:+ return 'month'+ }+}++export const ALERT_INTERVAL_OPTIONS: AlertCalculationInterval[] = [+ AlertCalculationInterval.HOURLY,+ AlertCalculationInterval.DAILY,+ AlertCalculationInterval.WEEKLY,+ AlertCalculationInterval.MONTHLY,+]++export function getAlertIntervalOptions(+ alerts15MinuteIntervalEnabled: boolean,+ hasHighFrequencyAlertsEntitlement: boolean+): Array<{ label: string | JSX.Element; value: AlertCalculationInterval }> {+ const intervals = alerts15MinuteIntervalEnabled+ ? [AlertCalculationInterval.EVERY_15_MINUTES, ...ALERT_INTERVAL_OPTIONS]+ : ALERT_INTERVAL_OPTIONS+ return intervals.map((interval) => {+ const labelText = alertCalculationIntervalToLabel(interval)+ const showLock = interval === AlertCalculationInterval.EVERY_15_MINUTES && !hasHighFrequencyAlertsEntitlement+ return {+ label: showLock ? (+ <span className="flex items-center gap-1.5">+ {labelText}+ <IconLock className="text-muted text-base shrink-0" />+ </span>+ ) : (+ labelText+ ),+ value: interval,+ }+ })+}diff --git a/products/alerts/frontend/logic/alertIntervalHelpers.test.ts b/products/alerts/frontend/logic/alertIntervalHelpers.test.tsnew file mode 100644index 000000000000..e71468373fac--- /dev/null+++ b/products/alerts/frontend/logic/alertIntervalHelpers.test.ts@@ -0,0 +1,98 @@+import type { GuardAvailableFeatureFn } from 'lib/components/UpgradeModal/upgradeModalLogic'+import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'+import { userLogic } from 'scenes/userLogic'++import { AlertCalculationInterval } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { AvailableFeature } from '~/types'++import {+ getDefaultSimulationRange,+ isHighFrequencyAlertInterval,+ selectAlertCalculationInterval,+} from './alertIntervalHelpers'++describe('alertIntervalHelpers', () => {+ beforeEach(() => {+ initKeaTests()+ })++ describe('getDefaultSimulationRange', () => {+ it.each([+ [AlertCalculationInterval.EVERY_15_MINUTES, '-12h'],+ [AlertCalculationInterval.HOURLY, '-48h'],+ [AlertCalculationInterval.DAILY, '-30d'],+ [AlertCalculationInterval.WEEKLY, '-12w'],+ [AlertCalculationInterval.MONTHLY, '-12m'],+ ])('%s returns %s', (interval, expected) => {+ expect(getDefaultSimulationRange(interval)).toBe(expected)+ })+ })++ describe('selectAlertCalculationInterval', () => {+ beforeEach(() => {+ userLogic.mount()+ upgradeModalLogic.mount()+ })++ it('opens upgrade modal and does not update interval when 15-minute is selected without entitlement', () => {+ const onSelect = jest.fn()++ const applied = selectAlertCalculationInterval(AlertCalculationInterval.EVERY_15_MINUTES, {+ guardAvailableFeature: upgradeModalLogic.values.guardAvailableFeature,+ onSelect,+ hasHighFrequencyAlertsEntitlement: false,+ })++ expect(applied).toBe(false)+ expect(onSelect).not.toHaveBeenCalled()+ expect(upgradeModalLogic.values.upgradeModalFeatureKey).toBe(AvailableFeature.HIGH_FREQUENCY_ALERTS)+ })++ it('updates interval when 15-minute is selected with entitlement', () => {+ const onSelect = jest.fn()+ const guardAvailableFeature: GuardAvailableFeatureFn = (_feature, callback) => {+ callback?.()+ return true+ }++ const applied = selectAlertCalculationInterval(AlertCalculationInterval.EVERY_15_MINUTES, {+ guardAvailableFeature,+ onSelect,+ hasHighFrequencyAlertsEntitlement: true,+ })++ expect(applied).toBe(true)+ expect(onSelect).toHaveBeenCalledWith(AlertCalculationInterval.EVERY_15_MINUTES)+ })++ it('updates interval for non-15-minute options without calling the guard', () => {+ const onSelect = jest.fn()+ const guardAvailableFeature = jest.fn<+ ReturnType<GuardAvailableFeatureFn>,+ Parameters<GuardAvailableFeatureFn>+ >(() => true)++ selectAlertCalculationInterval(AlertCalculationInterval.HOURLY, {+ guardAvailableFeature,+ onSelect,+ hasHighFrequencyAlertsEntitlement: false,+ })++ expect(onSelect).toHaveBeenCalledWith(AlertCalculationInterval.HOURLY)+ expect(guardAvailableFeature).not.toHaveBeenCalled()+ })+ })++ describe('isHighFrequencyAlertInterval', () => {+ it.each([+ [AlertCalculationInterval.EVERY_15_MINUTES, true],+ [AlertCalculationInterval.HOURLY, true],+ [AlertCalculationInterval.DAILY, false],+ [AlertCalculationInterval.WEEKLY, false],+ [AlertCalculationInterval.MONTHLY, false],+ ])('%s → %s', (interval, expected) => {+ expect(isHighFrequencyAlertInterval(interval)).toBe(expected)+ })+ })+})diff --git a/products/alerts/frontend/logic/alertIntervalHelpers.ts b/products/alerts/frontend/logic/alertIntervalHelpers.tsnew file mode 100644index 000000000000..e16a601d56f9--- /dev/null+++ b/products/alerts/frontend/logic/alertIntervalHelpers.ts@@ -0,0 +1,59 @@+import posthog from 'posthog-js'++import type { GuardAvailableFeatureFn } from 'lib/components/UpgradeModal/upgradeModalLogic'++import { AlertCalculationInterval } from '~/queries/schema/schema-general'+import { AvailableFeature } from '~/types'++export function getDefaultSimulationRange(interval: AlertCalculationInterval): string {+ switch (interval) {+ case AlertCalculationInterval.EVERY_15_MINUTES:+ return '-12h'+ case AlertCalculationInterval.HOURLY:+ return '-48h'+ case AlertCalculationInterval.DAILY:+ return '-30d'+ case AlertCalculationInterval.WEEKLY:+ return '-12w'+ case AlertCalculationInterval.MONTHLY:+ return '-12m'+ }+}++export function isHighFrequencyAlertInterval(interval: AlertCalculationInterval): boolean {+ return interval === AlertCalculationInterval.HOURLY || interval === AlertCalculationInterval.EVERY_15_MINUTES+}++export const HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE =+ '15-minute alert intervals require a Boost, Scale, or Enterprise platform add-on.'++export function blockSubmitWithoutHighFrequencyAlertsEntitlement(+ interval: AlertCalculationInterval,+ hasHighFrequencyAlertsEntitlement: boolean+): boolean {+ return interval === AlertCalculationInterval.EVERY_15_MINUTES && !hasHighFrequencyAlertsEntitlement+}++export function selectAlertCalculationInterval(+ value: AlertCalculationInterval,+ {+ guardAvailableFeature,+ onSelect,+ hasHighFrequencyAlertsEntitlement,+ }: {+ guardAvailableFeature: GuardAvailableFeatureFn+ onSelect: (interval: AlertCalculationInterval) => void+ hasHighFrequencyAlertsEntitlement: boolean+ }+): boolean {+ if (value === AlertCalculationInterval.EVERY_15_MINUTES) {+ posthog.capture('alert 15 min interval selected', {+ has_entitlement: hasHighFrequencyAlertsEntitlement,+ })+ return guardAvailableFeature(AvailableFeature.HIGH_FREQUENCY_ALERTS, () => {+ onSelect(value)+ })+ }+ onSelect(value)+ return true+}diff --git a/products/alerts/frontend/logic/scheduleRestrictionPreview.test.ts b/products/alerts/frontend/logic/scheduleRestrictionPreview.test.tsnew file mode 100644index 000000000000..388c657502ea--- /dev/null+++ b/products/alerts/frontend/logic/scheduleRestrictionPreview.test.ts@@ -0,0 +1,22 @@+import { estimateCheckSlotsNext24h } from './scheduleRestrictionPreview'++describe('scheduleRestrictionPreview', () => {+ const overnight = [{ start: '22:00', end: '07:00' }]++ it('returns full slot count when no quiet hours are configured', () => {+ expect(estimateCheckSlotsNext24h(null, 'UTC', 60)).toBe(24)+ expect(estimateCheckSlotsNext24h(undefined, 'UTC', 15)).toBe(96)+ })++ it('counts fewer hourly slots when overnight quiet hours block most of the day', () => {+ const count = estimateCheckSlotsNext24h(overnight, 'UTC', 60)+ expect(count).toBeGreaterThan(0)+ expect(count).toBeLessThan(24)+ })++ it('counts fewer 15-minute slots than 96 when quiet hours apply', () => {+ const count = estimateCheckSlotsNext24h(overnight, 'UTC', 15)+ expect(count).toBeGreaterThan(0)+ expect(count).toBeLessThan(96)+ })+})diff --git a/frontend/src/lib/components/Alerts/scheduleRestrictionPreview.ts b/products/alerts/frontend/logic/scheduleRestrictionPreview.tssimilarity index 75%rename from frontend/src/lib/components/Alerts/scheduleRestrictionPreview.tsrename to products/alerts/frontend/logic/scheduleRestrictionPreview.tsindex 4a8676f2b8c2..89758ff20914 100644--- a/frontend/src/lib/components/Alerts/scheduleRestrictionPreview.ts+++ b/products/alerts/frontend/logic/scheduleRestrictionPreview.ts@@ -1,7 +1,6 @@+import type { BlockedWindow } from 'lib/components/Alerts/types'import { dayjs } from 'lib/dayjs'-import type { BlockedWindow } from './types'-type ParsedWindow = { start: number; end: number; overnight: boolean }function parseHHMM(value: string): number {@@ -48,24 +47,27 @@ export function isLocalMinuteBlocked(minute: number, windows: ParsedWindow[]): breturn false}-/** Rough count of hourly evaluation slots in the next 24h that are not fully blocked at the hour start (team TZ). */-export function estimateHourlyCheckSlotsNext24h(+/** Rough count of evaluation slots in the next 24h that are not blocked at slot start (team TZ). */+export function estimateCheckSlotsNext24h(blockedWindows: BlockedWindow[] | null | undefined,- teamTimezone: string+ teamTimezone: string,+ cadenceMinutes: 15 | 60): number {+ const totalSlots = (24 * 60) / cadenceMinutesif (!blockedWindows?.length) {- return 24+ return totalSlots}let parsed: ParsedWindow[]try {parsed = parseBlockedWindowsForPreview(blockedWindows)} catch {- return 24+ return totalSlots}- const start = dayjs().tz(teamTimezone).startOf('hour')+ const start =+ cadenceMinutes === 60 ? dayjs().tz(teamTimezone).startOf('hour') : dayjs().tz(teamTimezone).startOf('minute')let count = 0- for (let i = 0; i < 24; i++) {- const t = start.add(i, 'hour')+ for (let i = 0; i < totalSlots; i++) {+ const t = start.add(i * cadenceMinutes, 'minute')const minute = t.hour() * 60 + t.minute()if (!isLocalMinuteBlocked(minute, parsed)) {count++diff --git a/products/alerts/package.json b/products/alerts/package.jsonindex 7d738f04d75c..b2f6deef0037 100644--- a/products/alerts/package.json+++ b/products/alerts/package.json@@ -2,5 +2,20 @@"name": "@posthog/products-alerts","scripts": {"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/test_max_tools.py -v --tb=short"+ },+ "dependencies": {+ "posthog-js": "catalog:"+ },+ "devDependencies": {+ "@storybook/react": "catalog:",+ "kea-test-utils": "catalog:"+ },+ "peerDependencies": {+ "@posthog/icons": "*",+ "@posthog/lemon-ui": "*",+ "@types/react": "*",+ "kea-forms": "*",+ "react": "*",+ "typescript": "catalog:*"}}