Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(alerts): redesign alert edit modal behind feature flag (#72437)

Matt Pua2808d8be1740
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 8ca6c0b5587e..054e679f0c76 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4690,50 +4690,46 @@ snapshots:
hash: v1.k794b7964.79aa55bc7ee50e205b299b2bde35388df13e0e2276e2266085b2e4afc3211f9d.wTwJM9Itu9VdDNnHqAGyxFvDgIf4HH6XUHwfUaFI38o
products-alerts-alert-history-chart--anomaly-probability-cutoff--light:
hash: v1.k794b7964.2e61e5b6c10e75ab7956910da63540cd59613cedd82cda41d27855350f1fbc79.qyZY692AuFYYlb0O5pP-6-NEzod1fZkG10CjZXEfY1U
- products-alerts-alert-history-chart--daily-evaluation-time-axis--dark:
- hash: v1.k794b7964.67c9f908439577db949b5b8ad39240f9951c23a79037e87f1b74306888ce61de.neh2fSbiMWRXykAhqiJbDODiOgAj-BAyQEqWQI4s-78
- products-alerts-alert-history-chart--daily-evaluation-time-axis--light:
- hash: v1.k794b7964.a7009268739c38eb44c519b0545f18a1a4edafa3fc1891f86d30eda3a0b3763c.nY2M-7wF1IGm4VGziP24xHTfsB_t9spxVA8mKyH9B5Y
products-alerts-alert-history-chart--default--dark:
hash: v1.k794b7964.506bc7fadd0b3360e3259626a9768352ccd4ce498b4df82d1225cea00ba15e88.0cs6ZhX2Ih--6CDOBuG12ZNyZjupj9ePoqMCW23GvcA
products-alerts-alert-history-chart--default--light:
hash: v1.k794b7964.3ae6d078b92dd2de10e90458c4b084cbe643a1843bf8456ea9cedb331fd2407e.YEPALzsZNyAn6dBDA0wVG5asI2MqqY0aMbtqUqICsjE
- products-alerts-alert-history-chart--mixed-threshold-change--dark:
- hash: v1.k794b7964.93bdb15a9050ddbb6f4d1e370610c6733d71172c6604585c4e7b703cfd47c482.XjoyauszRd57co7DPC89Cx9Je8LyJdhOzBZWWC_pxCo
- products-alerts-alert-history-chart--mixed-threshold-change--light:
- hash: v1.k794b7964.77d32c76ded75923403747e763b286f50914860f056c8696f92d9b089e688a5d.9bEDejgvXPmJUd3Jwo2gXEY0FEzIsnL7CyMg9ZJyRJ4
- products-alerts-alert-history-chart--monthly-evaluation-time-axis--dark:
- hash: v1.k794b7964.8721dd74e8d1ae4c07cb33589e60df105f409f7498f68e2273b7b1bbfe5d38fe.F56mukfQafN58mgMEKD60RAN9ZOzlo8WIIkdExjqgco
- products-alerts-alert-history-chart--monthly-evaluation-time-axis--light:
- hash: v1.k794b7964.59edee1cc41e2f3fa08908cc5d42abf841db1b4304e3478668f5267b259a1077.vNS7bCo0nwCxucUZfusbvIk_S_vZyL-NloeLMqGx3Ss
- products-alerts-alert-history-chart--more-checks-than-chart-window--dark:
- hash: v1.k794b7964.fc0bbe76de7a888aaac89fb7005b869d907866c3d58ed878111973eaf1b13b58.r0I-zFw_CfMWTAePQVHngs8j6_O585gnnPFGHjZzMig
- products-alerts-alert-history-chart--more-checks-than-chart-window--light:
- hash: v1.k794b7964.4c430430516c67b17d93456382ba5c78638d47c16b3d79536ff897067e1f9ebc.SadXjAHXIIvRoujMamHZP_7jcE_RRXadl30A5ngyxSU
products-alerts-alert-history-chart--percentage-thresholds--dark:
hash: v1.k794b7964.138483e490bdadb225663a058b6bebac6fdc0abf69a32a50b97723217224e9e9._tVpV44HZe6qDHZvZ5eCLaSGDSvXY09rEcKvN44f11U
products-alerts-alert-history-chart--percentage-thresholds--light:
hash: v1.k794b7964.1e61e68c1a67541f3c62db5fe55aa22fd0c9b3024e9bfe12b27655e5dbb388a6.lsLlLF6wu8nqCU1mBU5O1rfJFY_Ic44QU_KUv9avfCo
- products-alerts-alert-history-chart--quiet-hours-hourly--dark:
- hash: v1.k794b7964.a5f3b3a986af369bbfd25aad21d16683b38c82276121ff0baedabf1a67481684.j9wayZS9odsvQDjB4p-OOrnYC8k_R37ewM7c2dBvomk
- products-alerts-alert-history-chart--quiet-hours-hourly--light:
- hash: v1.k794b7964.bea0a8801c27d9f11c21fc1885aec15b5a220f460e1922c1e18b8bebf767d0d1.0UpBzFleU_dmkmS-vIEIOAxvFNqacE3bGW4IHxNnULc
- products-alerts-alert-history-chart--skip-weekends-and-quiet-hours-hourly--dark:
- hash: v1.k794b7964.0eeadb2913639941d8ed8525122ddd98b1d3744873f3bc792d24c9a414048a74.ughicTL8b7YmtastN1BhgzWvXxblgO2rdtDwbU3LZuk
- products-alerts-alert-history-chart--skip-weekends-and-quiet-hours-hourly--light:
- hash: v1.k794b7964.b12f6713d16adf2b118b07de83694dae7ba9d626a1ac26c77b3f4eed898678c4.mamDQQO2AiEwTKBCB72ikPSEL4bSCTiZICP9Vpha1fI
- products-alerts-alert-history-chart--skip-weekends-daily--dark:
- hash: v1.k794b7964.2d6cda0b3b7dd1a76ecbe412ffde3bc1939d30227d3881bd683809a4d2a685c6.Bm5JhA5T6nRQfNlrYt0FWsFo8FeU5MPJFMxu2zrSfxI
- products-alerts-alert-history-chart--skip-weekends-daily--light:
- hash: v1.k794b7964.fa6a55d35250b4ea451f382672464998d181b9446ebf95b7190cfed00c35b5e1.XpGNzzXn2QexWUeZsx9I7AG53w9A7va1kKXuooSpvek
- products-alerts-alert-history-chart--skip-weekends-hourly--dark:
- hash: v1.k794b7964.bce6bc9ea23ac158bbdc5582e6de649d8e2fa299ee8088be13d13235590d32fd.HgpROG2pudNRVPnjj5J0TIMg3vJq6kqAFaTGF4E9Dpw
- products-alerts-alert-history-chart--skip-weekends-hourly--light:
- hash: v1.k794b7964.5e3591cdbc4eee78b163a1aa8410fa65751bf23047acba4e048345ad3e4da682.iTpXWWJJ4v5ZmSpTyLC7anIF-F80OaQWuhOBXCgqeHQ
- products-alerts-alert-history-chart--weekly-evaluation-time-axis--dark:
- hash: v1.k794b7964.a499da46f133dea647381a38f323c0a99af30126221626420660f86226120a78.KyKzcKgo_lOwiZHSYVe5sTd0b9kmcMxQZSGRonrEQEw
- products-alerts-alert-history-chart--weekly-evaluation-time-axis--light:
- hash: v1.k794b7964.c2b3bd9c895a1a0cac092101517915d8d6706d2d284b47ebeeeecdd7ddbe35f7.oK9UeWi3IiEmGjxnoftQeq1e3mnOui_1M9XHlDuByOk
+ products-alerts-alert-history-chart--threshold-changed--dark:
+ hash: v1.k794b7964.93bdb15a9050ddbb6f4d1e370610c6733d71172c6604585c4e7b703cfd47c482.VL615VIicTduqKiolRa_CSYzf5qu-34WKbrSxE4IaQA
+ products-alerts-alert-history-chart--threshold-changed--light:
+ hash: v1.k794b7964.77d32c76ded75923403747e763b286f50914860f056c8696f92d9b089e688a5d.IzqZGt6MiYKjYUPtUCyaGTPvFyo6ZfZdyc4tyc-qISY
+ products-alerts-alert-history-chart--truncated-history--dark:
+ hash: v1.k794b7964.fc0bbe76de7a888aaac89fb7005b869d907866c3d58ed878111973eaf1b13b58.c5uaADCS2xUuOYu5cky5GCe4xJN3E9okpxmnlmSproA
+ products-alerts-alert-history-chart--truncated-history--light:
+ hash: v1.k794b7964.4c430430516c67b17d93456382ba5c78638d47c16b3d79536ff897067e1f9ebc.HZQrD0nZW8iu2VoLEoPxk8zKg05AOf9Dz9QdC4ncUqw
+ products-alerts-alert-modal--create-wizard--dark:
+ hash: v1.k794b7964.e3efb1235db76f2fe8b3ccff465df9b84263211b8648d57a725cfcf3a92c08c9.mTtZUY5-gkDVf9yjhBIR_Cx1_5arKEIEJh-2g-cLQBQ
+ products-alerts-alert-modal--create-wizard--light:
+ hash: v1.k794b7964.5d3e5771de5e54394886c7912e522f324add97132f71b60692b5d6efaeb8fdd3.mki0HDX74WZcOqtylWsX2ebTI-U1tVS9-5XcmKpY-bo
+ products-alerts-alert-modal--edit-alert--dark:
+ hash: v1.k794b7964.1b0b3ec51cc999c02f8442559b676a2e2f352998c0f3d4a9b10da7da8fc3aac1.ZktPS8oprYMZQ-rLsncCgMlyidqF97zUzqDfKjQGo1A
+ products-alerts-alert-modal--edit-alert--light:
+ hash: v1.k794b7964.38643f06f9a727b550dfcde1c46769c13a24bcc43877362c3d6feab29fd2f581.L1ItMn6mhr4o_vWqlI3lpil3yPPBgM0BgUa-yB6TzUQ
+ products-alerts-alerts-scene--empty-state--dark:
+ hash: v1.k794b7964.b419d15fe1d77892d0bc6aa978baa0075f2b64e597b8b457b59daaf7d3268f1a.mxxfJ0VEg12SBSXNmlykTeIIj7jKxPkBHSB2399bnus
+ products-alerts-alerts-scene--empty-state--light:
+ hash: v1.k794b7964.68282b46c2d253c95ece0fc855088e130c3866b9c96a857f3175656d4a2356e9.EhuHXcHe9cQbRatwuD5ervAmGm4omKeY2-UGMW4zAMQ
+ products-alerts-alerts-scene--insight-alerts--dark:
+ hash: v1.k794b7964.5ae3b2c1ac763b47a52bfb9ec7ed536e2348e61a75e00b476ec5716cbccfa4f9.czQQpTNgAS1lFWe4cjHs5Ka_UDb8aFRk_DC1NkgwmX0
+ products-alerts-alerts-scene--insight-alerts--light:
+ hash: v1.k794b7964.b351d0f1ddfbe12f4402335e19b5bf9611f8aa028e8c43d165f4bbfa98f32077.z4jf9YcaLIV85LqBKR-pzGdzL_7c2ycLVUTzkyVBRiU
+ products-alerts-alerts-scene--log-alerts--dark:
+ hash: v1.k794b7964.a40d931748bcafd0f7c04fc6c49b822be8354406f51a94a8dacf611bac3d2427.HPAk17TcKxsIPc0G2y4gKdrKfvDF-ZxS4UWiWi_RLSY
+ products-alerts-alerts-scene--log-alerts--light:
+ hash: v1.k794b7964.202760c4cc733d6ef4fee0ad7bee733d15f170e87ef01e64d481a954dcf5a0d3.8Wx10_cUTwP4fwGP183w2k8FTU7NsmgyvkPL_6_Eotg
+ products-alerts-insight-alerts-modal--with-alerts--dark:
+ hash: v1.k794b7964.71d299246cda9686b399251f872ee9603fa87c1bfc312559e99317107a16ab84.kQejra_LLghebT-mluFkAg4ukVJOgdt5yRonzhJGZpM
+ products-alerts-insight-alerts-modal--with-alerts--light:
+ hash: v1.k794b7964.e7d980de50b41878a13cbee137b56c8934d04fa4134cb42508031147061c4f58.oVmlPLncyOyUh6_4Yaz80d5t1350ESLPGFSpBux1iOQ
products-alerts-shared-components--advanced-options--dark:
hash: v1.k794b7964.3e55fa3a531d4b4f54ad6ea4679723bbac806e94a02edc0dd38e58b8bedf1285.avRzgZ_I6aR1-LlDLhiKIy4RgMi_UJZjHnXi94wcnwY
products-alerts-shared-components--advanced-options--light:
@@ -4743,9 +4739,13 @@ snapshots:
products-alerts-shared-components--definition--light:
hash: v1.k794b7964.90a8dd3ae31d38299907df369f0292820b96b9995c1208afdbb81b19fad55a73.WB_rZLWcLdb8-8vTIhUBc0PFmjrpFJwuKRmLpMaTYFU
products-alerts-shared-components--editor--dark:
- hash: v1.k794b7964.2842189cbb13cd78a201818689335762c86df3fa38a36ed86cf7620967e8237b.hO8K7Tepvpd1zTw_TrgEJabcpMq5RJj0qmaQvyU1Y7k
+ hash: v1.k794b7964.798a3c679795d90cfcf5f42db86e1a2cf7e93ba4a134712fb247b1c4526aa122.f20uEAd-je-70nFrOpSseL6qyucV2nEZnIDzrbVCQfw
products-alerts-shared-components--editor--light:
- hash: v1.k794b7964.bbc170e568523d203e413d0729dc756df98540fc6ea8a8d61e2685e1294580fe.eQXKeLusBVHchw_YgfEZkGqMCWvZCN9RyycW3yeFCng
+ hash: v1.k794b7964.11e63cdad38ae64326565607804d7794a640ce45cfbd9bba74802ab36752ac2c.aYLncpCo48hLPuP9BzZ8Jr2voDN9uSufxzQuZnafeDE
+ products-alerts-shared-components--editor-loading--dark:
+ hash: v1.k794b7964.06ae29718686868b16b6ed63656ac48f68e63965b8af99de8672324f346fed36.5mmecmMUjwwauSBmOgoqUtIIQWvuz1Cos-74vN_XTYg
+ products-alerts-shared-components--editor-loading--light:
+ hash: v1.k794b7964.5e3a2827ace05ced5a178649d4d511fde78fbd2efc102c1fd3d5cacc229b8395.GsnqMnxDeg6gkEjtWsWDcrdQRmw4OdCs2s4rfF0WdN4
products-alerts-shared-components--evaluation-history--dark:
hash: v1.k794b7964.453165acd1cbb101c12b290fe168d0fe04ae0f626fdae715e79f68fe69475caf.isZqjBZXk31Z7iMmwiTrmIFhJp6MdOLTWGJMtT6yUtQ
products-alerts-shared-components--evaluation-history--light:
@@ -5242,18 +5242,6 @@ snapshots:
hash: v1.k794b7964.a79751753cae893fcc58a4c977084260de54c1cedfbaf95e007c24e17b349bc0.EFZMJDQA59-TBfbw1hs6FJFClvazutyHRpNpyizIjjM
scenes-app-aigateway--page--light:
hash: v1.k794b7964.46e268c8c95189b2c120d6fafd639efb84a8700c5536e489c3f7e81f84ffb666.ZIHYAvfqLGq4DXFRUA5bvAayBpUSO6FmKj5R4OJpH4A
- scenes-app-alerts--empty-state--dark:
- hash: v1.k794b7964.b419d15fe1d77892d0bc6aa978baa0075f2b64e597b8b457b59daaf7d3268f1a.aIWM8EZJ8vEV7F2XucSkuXRwOe84IJEKVrSFrVSoyrM
- scenes-app-alerts--empty-state--light:
- hash: v1.k794b7964.68282b46c2d253c95ece0fc855088e130c3866b9c96a857f3175656d4a2356e9.XxMMtzs1kUZ0vOjdqOnjR-2f5JG8O-CyjJlV37dGjN4
- scenes-app-alerts--list-view--dark:
- hash: v1.k794b7964.4c020e0ebe744218e314df1ea31cd8de37bf7a02b3b809739c8f750b660666ed.YMrLxDq9FEQdAKC8xGXZC-oOT7jXWGUPF2TxasONlTo
- scenes-app-alerts--list-view--light:
- hash: v1.k794b7964.2725e031fe77d1eb8578762f3429cdc48bfcffe083a6864efa5c48cf77ff04b0.nblDx2dCBdOD9ws2ACxbDLVXCk0llg63ZLuDaV8eMmI
- scenes-app-alerts--log-alerts--dark:
- hash: v1.k794b7964.a40d931748bcafd0f7c04fc6c49b822be8354406f51a94a8dacf611bac3d2427.D3wB42FmYwzDpfwnYcqpL7RhNd1PlNBZU4LXJSaDf8s
- scenes-app-alerts--log-alerts--light:
- hash: v1.k794b7964.202760c4cc733d6ef4fee0ad7bee733d15f170e87ef01e64d481a954dcf5a0d3.iPzAqTj0a5NYLsyQjR4gZVE1hSbkWPJGXAD7oCjFCKQ
scenes-app-annotations--annotations--dark:
hash: v1.k794b7964.ee361eed99f04232ba32af0b7b7e38eb803860ee2faee52e094cf4fd126c30b1.ljX92vC8uyiUAdMxYyoQCDb2U9lqekhny9AhNrfVLpg
scenes-app-annotations--annotations--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 017d31e48b48..e15b7dc21e76 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -252,6 +252,7 @@ export const FEATURE_FLAGS = {
ALERTS_INLINE_NOTIFICATIONS: 'alerts-inline-notifications', // owner: @vdekrijger
ALERTS_INVESTIGATION_AGENT: 'alerts-investigation-agent', // owner: @andrewm4894, anomaly alerts — investigation agent on firing
ALERTS_REAL_TIME_INTERVAL: 'alerts-real-time-interval', // owner: #team-analytics-platform, gates real-time (2-minute) insight alert interval
+ ALERTS_REDESIGNED_EDIT_MODAL: 'alerts-redesigned-edit-modal', // owner: #team-analytics-platform, gates the redesigned alert edit/create modal (wizard for new, sections for edit)
AMPLITUDE_BATCH_IMPORT_OPTIONS: 'amplitude-batch-import-options', // owner: #team-ingestion
APPROVALS: 'approvals', // owner: @yasen-posthog #team-platform-features
AVERAGE_PAGE_VIEW_COLUMN: 'average-page-view-column', // owner: @jordanm-posthog #team-web-analytics
diff --git a/frontend/src/scenes/insights/InsightModals.tsx b/frontend/src/scenes/insights/InsightModals.tsx
index 759212cc03af..76f6defff467 100644
--- a/frontend/src/scenes/insights/InsightModals.tsx
+++ b/frontend/src/scenes/insights/InsightModals.tsx
@@ -115,6 +115,7 @@ function InsightAlertsModals({ insightLogicProps }: { insightLogicProps: Insight
alertId={alertId === null || alertId === 'new' ? undefined : alertId}
insightShortId={insight.short_id as InsightShortId}
insightId={insight.id}
+ insightName={insight.name}
onEditSuccess={() => push(urls.insightAlerts(insight.short_id as InsightShortId))}
insightLogicProps={insightLogicProps}
/>
diff --git a/products/alerts/frontend/AlertsScene.stories.tsx b/products/alerts/frontend/AlertsScene.stories.tsx
index 4048a1158c21..ee0e9a6ae062 100644
--- a/products/alerts/frontend/AlertsScene.stories.tsx
+++ b/products/alerts/frontend/AlertsScene.stories.tsx
@@ -166,7 +166,7 @@ const logAlerts = [
const meta: Meta = {
component: App,
- title: 'Scenes-App/Alerts',
+ title: 'Products/Alerts/Alerts scene',
parameters: {
layout: 'fullscreen',
viewMode: 'story',
@@ -188,7 +188,7 @@ export default meta
type Story = StoryObj<{}>
-export const ListView: Story = {}
+export const InsightAlerts: Story = {}
export const EmptyState: Story = {
decorators: [
diff --git a/products/alerts/frontend/components/AlertAdvancedOptions.tsx b/products/alerts/frontend/components/AlertAdvancedOptions.tsx
index 25f40817cf21..c0822927b443 100644
--- a/products/alerts/frontend/components/AlertAdvancedOptions.tsx
+++ b/products/alerts/frontend/components/AlertAdvancedOptions.tsx
@@ -5,13 +5,19 @@ import { LemonCollapse } from '@posthog/lemon-ui'
interface AlertAdvancedOptionsProps {
children: ReactNode
enabledCount?: number
+ defaultOpen?: boolean
}
-export function AlertAdvancedOptions({ children, enabledCount = 0 }: AlertAdvancedOptionsProps): JSX.Element {
+export function AlertAdvancedOptions({
+ children,
+ enabledCount = 0,
+ defaultOpen = false,
+}: AlertAdvancedOptionsProps): JSX.Element {
const countLabel = `${enabledCount} advanced option${enabledCount === 1 ? '' : 's'} on`
return (
<LemonCollapse
+ defaultActiveKey={defaultOpen ? 'advanced' : undefined}
panels={[
{
key: 'advanced',
diff --git a/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx b/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx
index d824c6409f95..0bdae5c059a0 100644
--- a/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx
+++ b/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx
@@ -18,6 +18,7 @@ export interface AlertAdvancedOptionsSectionProps {
canCheckOngoingInterval: boolean
projectTimezone: string
enabledAdvancedOptionsCount: number
+ defaultOpen?: boolean
onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
}
@@ -26,12 +27,13 @@ export function AlertAdvancedOptionsSection({
canCheckOngoingInterval,
projectTimezone,
enabledAdvancedOptionsCount,
+ defaultOpen,
onSetAlertFormValue,
}: AlertAdvancedOptionsSectionProps): JSX.Element {
const ongoing = ongoingIntervalField(alertForm.config, canCheckOngoingInterval)
return (
- <AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount}>
+ <AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount} defaultOpen={defaultOpen}>
{ongoing.show ? (
<Group name={['config']}>
<div className="flex gap-1">
@@ -45,7 +47,7 @@ export function AlertAdvancedOptionsSection({
/>
</LemonField>
<Tooltip title={ongoing.tooltip} placement="right" delayMs={0}>
- <IconInfo />
+ <IconInfo className="text-xl text-secondary shrink-0" />
</Tooltip>
</div>
</Group>
diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsx
index 019bfc0af151..e7030b1b82f2 100644
--- a/products/alerts/frontend/components/AlertComponents.stories.tsx
+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx
@@ -14,7 +14,7 @@ import type { ScheduleRestriction } from 'products/alerts/frontend/types'
import { AlertAdvancedOptions } from './AlertAdvancedOptions'
import { AlertDefinitionRow, AlertNextEvaluationStatus, AlertTimezoneNotice } from './AlertDefinition'
-import { AlertEditor, AlertEditorFormDetails, AlertEditorSection } from './AlertEditor'
+import { AlertEditor, AlertEditorFormDetails, AlertEditorLoading, AlertEditorSection } from './AlertEditor'
import {
AlertEvaluationHistoryChart,
AlertEvaluationHistoryPoint,
@@ -83,6 +83,14 @@ function EditorStory(): JSX.Element {
)
}
+function EditorLoadingStory(): JSX.Element {
+ return (
+ <div className="max-w-3xl overflow-hidden rounded border bg-surface-primary">
+ <AlertEditorLoading title="Edit alert" onBack={() => {}} />
+ </div>
+ )
+}
+
type DefinitionMode = 'above' | 'below'
const DEFINITION_MODE_OPTIONS: LemonSegmentedButtonOption<DefinitionMode>[] = [
@@ -281,6 +289,10 @@ export default meta
type Story = StoryObj<typeof meta>
export const Editor: Story = { render: () => <EditorStory /> }
+export const EditorLoading: Story = {
+ render: () => <EditorLoadingStory />,
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+}
export const Definition: Story = { render: () => <DefinitionStory /> }
export const AdvancedOptions: Story = { render: () => <AdvancedOptionsStory /> }
export const Notifications: Story = { render: () => <NotificationsStory /> }
diff --git a/products/alerts/frontend/components/AlertDefinition.tsx b/products/alerts/frontend/components/AlertDefinition.tsx
index b568d046881e..cd7e4ad03609 100644
--- a/products/alerts/frontend/components/AlertDefinition.tsx
+++ b/products/alerts/frontend/components/AlertDefinition.tsx
@@ -1,7 +1,11 @@
import { ReactNode } from 'react'
import { IconCalendar, IconClock } from '@posthog/icons'
-import { Link } from '@posthog/lemon-ui'
+import { LemonTag, Link } from '@posthog/lemon-ui'
+
+import { AlertState } from '~/queries/schema/schema-general'
+
+import { AlertType } from '../types'
interface AlertDefinitionRowProps {
label?: ReactNode
@@ -18,6 +22,23 @@ export function AlertDefinitionRow({ label, children, className }: AlertDefiniti
)
}
+export function AlertStateIndicator({ alert }: { alert: AlertType }): JSX.Element {
+ if (!alert.enabled) {
+ return <LemonTag type="muted">Disabled</LemonTag>
+ }
+
+ switch (alert.state) {
+ case AlertState.FIRING:
+ return <LemonTag type="danger">Firing</LemonTag>
+ case AlertState.ERRORED:
+ return <LemonTag type="danger">Errored</LemonTag>
+ case AlertState.SNOOZED:
+ return <LemonTag type="muted">Snoozed</LemonTag>
+ case AlertState.NOT_FIRING:
+ return <LemonTag type="success">Not firing</LemonTag>
+ }
+}
+
interface AlertNextEvaluationStatusProps {
children: ReactNode
loading?: boolean
diff --git a/products/alerts/frontend/components/AlertDefinitionFields.tsx b/products/alerts/frontend/components/AlertDefinitionFields.tsx
index bbc7adebf83e..df30b75b6689 100644
--- a/products/alerts/frontend/components/AlertDefinitionFields.tsx
+++ b/products/alerts/frontend/components/AlertDefinitionFields.tsx
@@ -17,7 +17,7 @@ import {
} from 'products/alerts/frontend/logic/funnelAlertOptions'
import { FunnelAlertPreview } from 'products/alerts/frontend/logic/funnelAlertPreview'
import { HogQLAlertPreview } from 'products/alerts/frontend/logic/hogqlAlertPreview'
-import { isFunnelsAlertConfig } from 'products/alerts/frontend/types'
+import { isFunnelsAlertConfig, isHogQLAlertConfig } from 'products/alerts/frontend/types'
import { HogQLAlertPreviewBanner, HogQLAlertPreviewRowsTable } from './HogQLAlertPreview'
@@ -70,8 +70,8 @@ export function TrendsDefinitionFields({
// banner string (mirrors the SQL preview's table cap); the rest collapse into "+N more".
const FUNNEL_BREACH_PREVIEW_CAP = 5
-/** Conversion-rate read-out + breach/ok status (mirrors the SQL alert's preview). */
-function FunnelAlertPreviewBanner({ preview }: { preview: FunnelAlertPreview | null }): JSX.Element | null {
+/** Conversion-rate read-out and whether the alert would fire. */
+export function FunnelAlertPreviewBanner({ preview }: { preview: FunnelAlertPreview | null }): JSX.Element | null {
if (preview === null) {
return (
<LemonBanner type="info" className="w-full">
@@ -90,10 +90,10 @@ function FunnelAlertPreviewBanner({ preview }: { preview: FunnelAlertPreview | n
const format = (rate: number): string => `${rate.toFixed(1)}%`
const breaching = preview.values.filter((value) => value.breaching)
const wouldFire = breaching.length > 0
- // Same at-a-glance breach/ok tag as the SQL alert preview; only meaningful once a threshold is set.
+ // The fire-state tag is only meaningful once a threshold is set.
const statusTag = preview.hasBounds ? (
- <LemonTag type={wouldFire ? 'warning' : 'success'} className="mr-2">
- {wouldFire ? 'breach' : 'ok'}
+ <LemonTag type={wouldFire ? 'danger' : 'success'} className="mr-2">
+ {wouldFire ? 'Would fire' : 'Would not fire'}
</LemonTag>
) : null
@@ -103,10 +103,10 @@ function FunnelAlertPreviewBanner({ preview }: { preview: FunnelAlertPreview | n
const first = preview.values[0]
const hasPrior = preview.values.some((value) => value.previousRate !== undefined)
return (
- <LemonBanner type={wouldFire ? 'warning' : 'info'} className="w-full">
+ <div className="w-full rounded border border-border bg-bg-light p-3 text-sm">
{statusTag}
{!hasPrior ? (
- <>Needs an earlier completed period to compare against — extend the date range.</>
+ <>Needs an earlier completed period to compare against. Extend the date range.</>
) : preview.isBreakdown ? (
<>
Across {preview.values.length} breakdown values, comparing each period against the one before it
@@ -119,23 +119,23 @@ function FunnelAlertPreviewBanner({ preview }: { preview: FunnelAlertPreview | n
</>
)}
{!preview.hasBounds ? <> Set a threshold to preview whether it would fire.</> : null}
- </LemonBanner>
+ </div>
)
}
if (preview.isBreakdown) {
const rates = preview.values.map((value) => value.rate)
return (
- <LemonBanner type={wouldFire ? 'warning' : 'info'} className="w-full">
+ <div className="w-full rounded border border-border bg-bg-light p-3 text-sm">
{statusTag}
Across {preview.values.length} breakdown values, currently{' '}
<strong>
{format(Math.min(...rates))}–{format(Math.max(...rates))}
</strong>
- {/* The tag + banner colour carry the breach/ok state; only add what they can't — which
+ {/* The tag and container color carry the fire state. Only add what they cannot: which
values breach, or (when no threshold is set yet) a prompt to set one. */}
{!preview.hasBounds ? (
- <> — fires if any value breaches. Set a threshold to preview.</>
+ <>. Fires if any value breaches. Set a threshold to preview.</>
) : wouldFire ? (
<>
{' '}
@@ -149,33 +149,35 @@ function FunnelAlertPreviewBanner({ preview }: { preview: FunnelAlertPreview | n
: ''}
</>
) : null}
- </LemonBanner>
+ </div>
)
}
return (
- <LemonBanner type={wouldFire ? 'warning' : 'info'} className="w-full">
+ <div className="w-full rounded border border-border bg-bg-light p-3 text-sm">
{statusTag}
- Currently converting at <strong>{format(preview.values[0].rate)}</strong>
- {!preview.hasBounds ? <> — set a threshold to preview whether it would fire.</> : null}
- </LemonBanner>
+ Current conversion is <strong>{format(preview.values[0].rate)}</strong>
+ {!preview.hasBounds ? <>. Set a threshold to preview whether it would fire.</> : null}
+ </div>
)
}
-/** Funnels: a single valid-conversion picker over the `{metric, funnel_step}` config — see funnelAlertOptions.
+/** Funnels: a single valid-conversion picker over the `{metric, funnel_step}` config. See funnelAlertOptions.
* A trends funnel charts the overall (whole-funnel) conversion rate over time, so there's no per-step
- * choice to make — it shows just the preview of the latest period's rate. */
+ * choice to make. It shows just the preview of the latest period's rate. */
export function FunnelsDefinitionFields({
alertForm,
stepLabels,
funnelPreview,
isTrendsFunnel,
+ showInlinePreview,
onSetAlertFormValue,
}: {
alertForm: AlertFormType
stepLabels: string[]
funnelPreview: FunnelAlertPreview | null
isTrendsFunnel: boolean
+ showInlinePreview: boolean
onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
}): JSX.Element {
const config = isFunnelsAlertConfig(alertForm.config) ? alertForm.config : null
@@ -183,32 +185,39 @@ export function FunnelsDefinitionFields({
// A trends funnel charts the overall conversion rate over time, so there's no per-step choice.
// The in-progress-period toggle lives in Advanced options, mirroring the trends-alert equivalent.
return (
- <div className="flex flex-wrap gap-3 items-center">
- <div>Alert on the overall conversion rate</div>
- <FunnelAlertPreviewBanner preview={funnelPreview} />
- </div>
+ <>
+ <AlertDefinitionRow label="When">
+ <span className="font-medium">Overall conversion rate</span>
+ </AlertDefinitionRow>
+ {showInlinePreview ? <FunnelAlertPreviewBanner preview={funnelPreview} /> : null}
+ </>
)
}
return (
- <div className="flex flex-wrap gap-3 items-center">
- <div>Alert on</div>
- <LemonSelect
- fullWidth
- className="flex-auto"
- data-attr="alertForm-funnel-conversion"
- placeholder="Select a conversion"
- // Wide funnels generate ~2 options per step; cap the menu so it scrolls instead of overflowing.
- menu={{ className: '!max-h-[400px]' }}
- value={config ? funnelConfigToOptionKey(config, stepLabels.length) : undefined}
- onChange={(key) =>
- // Each key fully determines the config, so build a fresh one rather than spreading
- // the previous config (whose type/metric/funnel_step would all be overwritten anyway).
- onSetAlertFormValue('config', { type: 'FunnelsAlertConfig', ...funnelConfigForOptionKey(key) })
- }
- options={funnelConversionOptions(stepLabels)}
- />
- <FunnelAlertPreviewBanner preview={funnelPreview} />
- </div>
+ <>
+ <AlertDefinitionRow label="When" className="flex-nowrap">
+ <div className="min-w-0 flex-1">
+ <LemonSelect
+ fullWidth
+ data-attr="alertForm-funnel-conversion"
+ placeholder="Select a conversion"
+ // Wide funnels generate ~2 options per step; cap the menu so it scrolls instead of overflowing.
+ menu={{ className: '!max-h-[400px]' }}
+ value={config ? funnelConfigToOptionKey(config, stepLabels.length) : undefined}
+ onChange={(key) =>
+ // Each key fully determines the config, so build a fresh one rather than spreading
+ // the previous config (whose type/metric/funnel_step would all be overwritten anyway).
+ onSetAlertFormValue('config', {
+ type: 'FunnelsAlertConfig',
+ ...funnelConfigForOptionKey(key),
+ })
+ }
+ options={funnelConversionOptions(stepLabels)}
+ />
+ </div>
+ </AlertDefinitionRow>
+ {showInlinePreview ? <FunnelAlertPreviewBanner preview={funnelPreview} /> : null}
+ </>
)
}
@@ -220,6 +229,7 @@ export function HogQLDefinitionFields({
hogqlColumns,
hogqlValueColumnOptions,
hogqlLabelColumnOptions,
+ showInlinePreview,
onSetAlertFormValue,
}: {
alertForm: AlertFormType
@@ -227,13 +237,31 @@ export function HogQLDefinitionFields({
hogqlColumns: string[] | null
hogqlValueColumnOptions: { label: string; value: string }[]
hogqlLabelColumnOptions: { label: string; value: string }[]
+ showInlinePreview: boolean
onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
}): JSX.Element {
const hasMultipleColumns = (hogqlColumns?.length ?? 0) > 1
+ const config = isHogQLAlertConfig(alertForm.config) ? alertForm.config : null
+ const showValueColumn = hasMultipleColumns || !!config?.column
+ const valueColumnOptions = [...hogqlValueColumnOptions]
+ if (config?.column && !valueColumnOptions.some((option) => option.value === config.column)) {
+ valueColumnOptions.unshift({ label: config.column, value: config.column })
+ }
return (
<>
<AlertDefinitionRow label="When">
<Group name={['config']}>
+ {showValueColumn && (
+ <LemonField name="column" className="flex-auto">
+ <LemonSelect
+ fullWidth
+ data-attr="alertForm-hogql-column"
+ placeholder="select column to evaluate"
+ options={valueColumnOptions}
+ />
+ </LemonField>
+ )}
+ {showValueColumn ? <span className="text-muted self-center">from</span> : null}
<LemonField name="evaluation" className="flex-auto">
{({ value, onChange }) => (
<LemonSelect
@@ -268,24 +296,12 @@ export function HogQLDefinitionFields({
label: 'any row',
value: 'any_row',
tooltip:
- 'Every row is checked and the alert fires if any value breaches the threshold — e.g. one row per country.',
+ 'Every row is checked and the alert fires if any value breaches the threshold, such as one row per country.',
},
]}
/>
)}
</LemonField>
- {hasMultipleColumns && (
- <LemonField name="column" className="flex-auto">
- {/* Prefilled with the last numeric column by alertFormLogic; the
- placeholder only shows when nothing numeric is detectable. */}
- <LemonSelect
- fullWidth
- data-attr="alertForm-hogql-column"
- placeholder="select column to evaluate"
- options={hogqlValueColumnOptions}
- />
- </LemonField>
- )}
</Group>
</AlertDefinitionRow>
{hasMultipleColumns && (
@@ -308,8 +324,12 @@ export function HogQLDefinitionFields({
</Group>
</div>
)}
- <HogQLAlertPreviewBanner preview={hogqlPreview} conditionType={alertForm.condition?.type} />
- {hogqlPreview?.status === 'ok' && <HogQLAlertPreviewRowsTable preview={hogqlPreview} />}
+ {showInlinePreview ? (
+ <>
+ <HogQLAlertPreviewBanner preview={hogqlPreview} conditionType={alertForm.condition?.type} />
+ {hogqlPreview?.status === 'ok' && <HogQLAlertPreviewRowsTable preview={hogqlPreview} />}
+ </>
+ ) : null}
</>
)
}
diff --git a/products/alerts/frontend/components/AlertDefinitionSection.tsx b/products/alerts/frontend/components/AlertDefinitionSection.tsx
index 9bdeb80f4ea4..3224d6be0197 100644
--- a/products/alerts/frontend/components/AlertDefinitionSection.tsx
+++ b/products/alerts/frontend/components/AlertDefinitionSection.tsx
@@ -1,39 +1,26 @@
-import { Group } from 'kea-forms'
+import { LemonBanner } from '@posthog/lemon-ui'
-import { IconInfo } from '@posthog/icons'
-import {
- LemonBanner,
- LemonButton,
- LemonCheckbox,
- LemonInput,
- LemonSegmentedButton,
- LemonSelect,
- Tooltip,
-} from '@posthog/lemon-ui'
-
-import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
-import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
-
-import { AlertDefinitionRow } from 'products/alerts/frontend/components/AlertDefinition'
import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
-import { getDefaultSimulationRange } from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { getDefaultAnomalyDetectorConfig } from 'products/alerts/frontend/logic/detectorConfigDefaults'
import { FunnelAlertPreview } from 'products/alerts/frontend/logic/funnelAlertPreview'
import { HogQLAlertPreview } from 'products/alerts/frontend/logic/hogqlAlertPreview'
-import { fractionToPercentInput, rescaleFunnelBound } from 'products/alerts/frontend/logic/thresholdPercent'
import {
AlertSimulationResult,
- isAnyRowHogQLConfig,
isFunnelsAlertConfig,
isHogQLAlertConfig,
isTrendsAlertConfig,
} from 'products/alerts/frontend/types'
import { DetectorSelector } from 'products/alerts/frontend/views/DetectorSelector'
-import { SimulationSummary } from 'products/alerts/frontend/views/SimulationSummary'
import { FunnelsDefinitionFields, HogQLDefinitionFields, TrendsDefinitionFields } from './AlertDefinitionFields'
-import { getSimulationRangeOptions } from './editAlertModalUtils'
+import { AlertSimulationSection } from './AlertSimulationSection'
+import { InvestigationAgentSettings } from './InvestigationAgentSettings'
+import { ThresholdDefinitionRow } from './ThresholdDefinitionRow'
+import type { ThresholdRowRenderProps } from './ThresholdDefinitionRow'
+
+export type { ThresholdRowRenderProps } from './ThresholdDefinitionRow'
export interface TrendsDefinitionProps {
/** Series in the alerted insight, for the series picker. */
@@ -74,22 +61,21 @@ export interface AlertDefinitionSectionProps {
funnel: FunnelDefinitionProps
hogql: HogQLDefinitionProps
supportsAnomalyDetection: boolean
+ twoColumnLayout?: boolean
investigationAgentEnabled: boolean
simulationResult: AlertSimulationResult | null
simulationResultLoading: boolean
simulationDateFrom: string | null
onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
+ /** Override the threshold row renderer. The legacy modal uses the inline wrapping row; the
+ * redesigned modal passes a stacked, labeled variant. Omit to keep the legacy row. */
+ thresholdRowRenderer?: (props: ThresholdRowRenderProps) => JSX.Element
onSimulateAlert: () => void
onSetSimulationDateFrom: (value: string) => void
onClearSimulation: () => void
onClearSimulationOverlay: () => void
}
-/** Whether the form's SQL alert config is in any-row mode (every row checked, not just the last). */
-function isHogQLAnyRow(alertForm: AlertFormType): boolean {
- return isAnyRowHogQLConfig(alertForm.config)
-}
-
export function AlertDefinitionSection({
alertForm,
alertMode,
@@ -99,11 +85,13 @@ export function AlertDefinitionSection({
funnel,
hogql,
supportsAnomalyDetection,
+ twoColumnLayout = false,
investigationAgentEnabled,
simulationResult,
simulationResultLoading,
simulationDateFrom,
onSetAlertFormValue,
+ thresholdRowRenderer,
onSimulateAlert,
onSetSimulationDateFrom,
onClearSimulation,
@@ -113,10 +101,41 @@ export function AlertDefinitionSection({
// value to compare against. A historical-trend funnel is a time series, so it does support them.
const isFunnelAlert = isFunnelsAlertConfig(alertForm.config)
const supportsRelativeConditions = !isFunnelAlert || funnel.isTrendsFunnel
- const relativeConditionDisabledReason =
- (isNonTimeSeriesDisplay && 'This condition is only supported for time series trends') ||
- (isHogQLAnyRow(alertForm) &&
- "Rows in any-row mode aren't a time series — switch to 'the latest value' for relative conditions")
+ let definitionFields: JSX.Element | null = null
+ if (isTrendsAlertConfig(alertForm.config)) {
+ definitionFields = (
+ <TrendsDefinitionFields
+ alertSeries={trends.alertSeries}
+ formulaNodes={trends.formulaNodes}
+ isBreakdownValid={trends.isBreakdownValid}
+ alertMode={alertMode}
+ />
+ )
+ } else if (isFunnelAlert) {
+ definitionFields = (
+ <FunnelsDefinitionFields
+ alertForm={alertForm}
+ stepLabels={funnel.stepLabels}
+ funnelPreview={funnel.preview}
+ isTrendsFunnel={funnel.isTrendsFunnel}
+ showInlinePreview={!twoColumnLayout}
+ onSetAlertFormValue={onSetAlertFormValue}
+ />
+ )
+ } else if (isHogQLAlertConfig(alertForm.config)) {
+ definitionFields = (
+ <HogQLDefinitionFields
+ alertForm={alertForm}
+ hogqlPreview={hogql.preview}
+ hogqlColumns={hogql.columns}
+ hogqlValueColumnOptions={hogql.valueColumnOptions}
+ hogqlLabelColumnOptions={hogql.labelColumnOptions}
+ showInlinePreview={!twoColumnLayout}
+ onSetAlertFormValue={onSetAlertFormValue}
+ />
+ )
+ }
+
return (
<>
{/* Trends-specific copy; funnels have their own breakdown messaging in the preview banner. */}
@@ -127,324 +146,92 @@ export function AlertDefinitionSection({
: 'For trends with breakdown, the alert will fire if any of the breakdown values breaches the threshold.'}
</LemonBanner>
)}
- {isTrendsAlertConfig(alertForm.config) ? (
- <TrendsDefinitionFields
- alertSeries={trends.alertSeries}
- formulaNodes={trends.formulaNodes}
- isBreakdownValid={trends.isBreakdownValid}
- alertMode={alertMode}
- />
- ) : isFunnelAlert ? (
- <FunnelsDefinitionFields
- alertForm={alertForm}
- stepLabels={funnel.stepLabels}
- funnelPreview={funnel.preview}
- isTrendsFunnel={funnel.isTrendsFunnel}
- onSetAlertFormValue={onSetAlertFormValue}
- />
- ) : isHogQLAlertConfig(alertForm.config) ? (
- <HogQLDefinitionFields
- alertForm={alertForm}
- hogqlPreview={hogql.preview}
- hogqlColumns={hogql.columns}
- hogqlValueColumnOptions={hogql.valueColumnOptions}
- hogqlLabelColumnOptions={hogql.labelColumnOptions}
- onSetAlertFormValue={onSetAlertFormValue}
- />
- ) : null}
-
- {supportsAnomalyDetection && (
- <LemonSegmentedButton
- fullWidth
- value={alertMode}
- onChange={(value) => {
- if (value === 'detector') {
- onSetAlertFormValue(
- 'detector_config',
- getDefaultAnomalyDetectorConfig(alertForm.calculation_interval)
- )
- } 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 statistical models. No fixed value threshold is required.',
- },
- ]}
- />
- )}
-
- {alertMode === 'threshold' ? (
- <div className="space-y-2">
- {thresholdBoundsFormError ? (
- <LemonBanner type="error">{thresholdBoundsFormError}</LemonBanner>
- ) : null}
- <AlertDefinitionRow>
- {supportsRelativeConditions && (
- <Group name={['condition']}>
- <LemonField name="type">
- {({ value, onChange }) => (
- <LemonSelect
- fullWidth
- className="w-40"
- data-attr="alertForm-condition"
- value={value}
- onChange={(newType) => {
- onChange(newType)
- if (!isFunnelAlert) {
- return
- }
- // Funnels have no #/% toggle: a relative condition uses a
- // PERCENTAGE threshold (0–1 fraction), "has value" an
- // ABSOLUTE one (raw percent). Keep the type in sync with the
- // condition and rescale the bounds so the on-screen number is
- // preserved across the switch instead of jumping ×100 / ÷100.
- const cfg = alertForm.threshold.configuration
- const targetType =
- newType === AlertConditionType.ABSOLUTE_VALUE
- ? InsightThresholdType.ABSOLUTE
- : InsightThresholdType.PERCENTAGE
- if (cfg.type === targetType) {
- return
- }
- onSetAlertFormValue('threshold', {
- configuration: {
- type: targetType,
- bounds: {
- lower: rescaleFunnelBound(cfg.bounds?.lower, targetType),
- upper: rescaleFunnelBound(cfg.bounds?.upper, targetType),
- },
- },
- })
- }}
- options={[
- { label: 'has value', value: AlertConditionType.ABSOLUTE_VALUE },
- {
- label: 'increases by',
- value: AlertConditionType.RELATIVE_INCREASE,
- disabledReason: relativeConditionDisabledReason,
- },
- {
- label: 'decreases by',
- value: AlertConditionType.RELATIVE_DECREASE,
- disabledReason: relativeConditionDisabledReason,
- },
- ]}
- />
- )}
- </LemonField>
- </Group>
- )}
- <div>less than</div>
- <LemonField name="lower">
- <LemonInput
- type="number"
- className="w-30"
- data-attr="alertForm-lower-threshold"
- suffix={isFunnelAlert ? <span aria-label="percent">%</span> : undefined}
- value={
- alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE
- ? fractionToPercentInput(alertForm.threshold.configuration.bounds?.lower)
- : 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"
- suffix={isFunnelAlert ? <span aria-label="percent">%</span> : undefined}
- value={
- alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE
- ? fractionToPercentInput(alertForm.threshold.configuration.bounds?.upper)
- : 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>
- {/* Funnels always compare as a percentage of the prior period, so the unit
- toggle is hidden for them (the threshold is pinned to PERCENTAGE). */}
- {!isFunnelAlert && 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>
- )}
- </AlertDefinitionRow>
- </div>
- ) : (
- <DetectorSelector
- value={alertForm.detector_config ?? null}
- onChange={(config) => {
- onSetAlertFormValue('detector_config', config)
- onClearSimulation()
- onClearSimulationOverlay()
- }}
- calculationInterval={alertForm.calculation_interval}
- />
- )}
+ <div
+ className={
+ twoColumnLayout ? 'grid items-start gap-6 md:grid-cols-[minmax(0,55%)_minmax(0,1fr)]' : 'space-y-3'
+ }
+ >
+ <div className="space-y-3">
+ {definitionFields}
- {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>
+ {supportsAnomalyDetection && (
+ <LemonRadio
+ radioPosition="top"
+ value={alertMode}
+ onChange={(value) =>
+ onSetAlertFormValue(
+ 'detector_config',
+ value === 'detector'
+ ? getDefaultAnomalyDetectorConfig(alertForm.calculation_interval)
+ : null
+ )
}
+ options={[
+ {
+ value: 'threshold',
+ label: 'Threshold',
+ description: 'Alert when a value goes above or below a fixed value you set.',
+ 'data-attr': 'alertForm-mode-threshold',
+ },
+ {
+ value: 'detector',
+ label: 'Anomaly detection',
+ description:
+ 'Automatically flag unusual changes using statistical models. No fixed value needed.',
+ 'data-attr': 'alertForm-mode-detector',
+ },
+ ]}
/>
- </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)}
+ <div className="space-y-3">
+ {alertMode === 'threshold' ? (
+ thresholdRowRenderer ? (
+ thresholdRowRenderer({
+ alertForm,
+ thresholdBoundsFormError,
+ isNonTimeSeriesDisplay,
+ supportsRelativeConditions,
+ onSetAlertFormValue,
+ })
+ ) : (
+ <ThresholdDefinitionRow
+ alertForm={alertForm}
+ thresholdBoundsFormError={thresholdBoundsFormError}
+ isNonTimeSeriesDisplay={isNonTimeSeriesDisplay}
+ supportsRelativeConditions={supportsRelativeConditions}
+ onSetAlertFormValue={onSetAlertFormValue}
+ />
+ )
+ ) : (
+ <DetectorSelector
+ value={alertForm.detector_config ?? null}
+ onChange={(config) => {
+ onSetAlertFormValue('detector_config', config)
+ onClearSimulation()
+ onClearSimulationOverlay()
+ }}
+ calculationInterval={alertForm.calculation_interval}
+ />
+ )}
+
+ {alertMode === 'detector' && alertForm.detector_config && investigationAgentEnabled && (
+ <InvestigationAgentSettings alertForm={alertForm} onSetAlertFormValue={onSetAlertFormValue} />
+ )}
+
+ {alertMode === 'detector' && alertForm.detector_config && (
+ <AlertSimulationSection
+ alertForm={alertForm}
+ simulationResult={simulationResult}
+ simulationResultLoading={simulationResultLoading}
+ simulationDateFrom={simulationDateFrom}
+ onSimulateAlert={onSimulateAlert}
+ onSetSimulationDateFrom={onSetSimulationDateFrom}
/>
- <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>
- )}
+ </div>
</>
)
}
diff --git a/products/alerts/frontend/components/AlertEditor.tsx b/products/alerts/frontend/components/AlertEditor.tsx
index ff918c5ebdad..9fac4dd05aab 100644
--- a/products/alerts/frontend/components/AlertEditor.tsx
+++ b/products/alerts/frontend/components/AlertEditor.tsx
@@ -1,7 +1,7 @@
import { ReactNode } from 'react'
import { IconChevronLeft } from '@posthog/icons'
-import { LemonCheckbox, LemonInput } from '@posthog/lemon-ui'
+import { LemonCheckbox, LemonInput, LemonSkeleton } from '@posthog/lemon-ui'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -33,6 +33,38 @@ export function AlertEditorHeader({ title, description, onBack }: AlertEditorHea
)
}
+export function AlertEditorLoading({ title, onBack }: Pick<AlertEditorHeaderProps, 'title' | 'onBack'>): JSX.Element {
+ return (
+ <div className="flex min-h-[600px] flex-col" aria-busy="true" aria-label={`Loading ${title.toLowerCase()}`}>
+ <header className="border-b p-4">
+ <AlertEditorHeader title={title} onBack={onBack} />
+ </header>
+ <div className="flex-1 space-y-4 p-4">
+ <LemonSkeleton className="h-20 w-full" />
+ <LemonSkeleton className="h-10 w-full" />
+ <LemonSkeleton className="h-4 w-48" />
+ <div className="grid grid-cols-2 gap-8">
+ <div className="space-y-3">
+ <LemonSkeleton className="h-10 w-full" />
+ <LemonSkeleton className="h-5 w-4/5" />
+ </div>
+ <div className="space-y-3">
+ <LemonSkeleton className="h-10 w-full" />
+ <LemonSkeleton className="h-10 w-3/4" />
+ </div>
+ </div>
+ </div>
+ <footer className="flex items-center justify-between border-t p-4">
+ <div className="flex gap-2">
+ <LemonSkeleton className="h-10 w-28" />
+ <LemonSkeleton className="h-10 w-32" />
+ </div>
+ <LemonSkeleton className="h-10 w-20" />
+ </footer>
+ </div>
+ )
+}
+
export interface AlertEditorActionsProps {
isEditing: boolean
isSubmitting: boolean
@@ -40,6 +72,7 @@ export interface AlertEditorActionsProps {
hasPendingChanges?: boolean
leadingActions?: ReactNode
onSubmitAttempted?: () => void
+ showNoChangesLabel?: boolean
}
export function AlertEditorActions({
@@ -49,8 +82,14 @@ export function AlertEditorActions({
hasPendingChanges = false,
leadingActions,
onSubmitAttempted,
+ showNoChangesLabel = false,
}: AlertEditorActionsProps): JSX.Element {
- const disabledReason = isEditing && !hasChanges && !hasPendingChanges ? 'No changes to save' : undefined
+ const hasUnsavedChanges = hasChanges || hasPendingChanges
+ const disabledReason = isEditing && !hasUnsavedChanges ? 'No changes to save' : undefined
+ let buttonLabel = 'Create alert'
+ if (isEditing) {
+ buttonLabel = showNoChangesLabel && !hasUnsavedChanges ? 'No changes' : 'Save'
+ }
return (
<>
@@ -62,7 +101,7 @@ export function AlertEditorActions({
disabledReason={disabledReason}
onClick={onSubmitAttempted}
>
- {isEditing ? 'Save' : 'Create alert'}
+ {buttonLabel}
</LemonButton>
</>
)
@@ -103,15 +142,17 @@ interface AlertEditorFormDetailsProps {
}
activity?: ReactNode
nameDataAttr?: string
+ nameError?: string
}
export function AlertEditorFormDetails({
enabled,
activity,
nameDataAttr = 'alertForm-name',
+ nameError,
}: AlertEditorFormDetailsProps): JSX.Element {
return (
- <div className="space-y-4">
+ <div className="space-y-2">
<div className="flex gap-4 items-center">
<LemonField className="flex-auto" name="name">
<LemonInput placeholder="Alert name" data-attr={nameDataAttr} />
@@ -127,6 +168,7 @@ export function AlertEditorFormDetails({
</LemonField>
) : null}
</div>
+ {nameError ? <LemonField.Error error={nameError} /> : null}
{activity}
</div>
)
@@ -134,15 +176,19 @@ export function AlertEditorFormDetails({
interface AlertEditorSectionProps {
title: string
+ icon?: ReactNode
description?: ReactNode
children: ReactNode
}
-export function AlertEditorSection({ title, description, children }: AlertEditorSectionProps): JSX.Element {
+export function AlertEditorSection({ title, icon, description, children }: AlertEditorSectionProps): JSX.Element {
return (
- <section className="space-y-5">
- <div className="space-y-1">
- <h3 className="text-base font-semibold m-0">{title}</h3>
+ <section className="space-y-2.5">
+ <div className="space-y-0.5">
+ <h3 className="text-sm font-semibold m-0 flex items-center gap-1.5">
+ {icon ? <span className="text-muted">{icon}</span> : null}
+ {title}
+ </h3>
{description ? <p className="text-xs text-secondary m-0">{description}</p> : null}
</div>
{children}
diff --git a/products/alerts/frontend/components/AlertPreviewCard.tsx b/products/alerts/frontend/components/AlertPreviewCard.tsx
new file mode 100644
index 000000000000..2ead4da4b31b
--- /dev/null
+++ b/products/alerts/frontend/components/AlertPreviewCard.tsx
@@ -0,0 +1,205 @@
+import { IconInfo } from '@posthog/icons'
+import { LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { Sparkline, SparklineReferenceLine } from 'lib/components/Sparkline'
+import type { AnyScaleOptions } from 'lib/components/Sparkline'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
+
+import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
+import { FunnelAlertPreview } from 'products/alerts/frontend/logic/funnelAlertPreview'
+import { HogQLAlertPreview } from 'products/alerts/frontend/logic/hogqlAlertPreview'
+import {
+ deriveTrendsAlertPreviewSeries,
+ TrendsAlertPreviewSeries,
+} from 'products/alerts/frontend/logic/trendsAlertPreview'
+import { isFunnelsAlertConfig, isHogQLAlertConfig, isTrendsAlertConfig } from 'products/alerts/frontend/types'
+
+import { FunnelAlertPreviewBanner } from './AlertDefinitionFields'
+import { fromLogScale, shouldUseLogScale, thresholdReferenceLines, toLogScale } from './AlertPreviewCard.utils'
+import { HogQLAlertPreviewBanner } from './HogQLAlertPreview'
+
+function allowNegativeYScale(scale: AnyScaleOptions): AnyScaleOptions {
+ return { ...scale, min: undefined }
+}
+
+function AlertPreviewSparkline({
+ values,
+ labels,
+ referenceLines,
+ relative,
+ renderTooltipValue,
+}: {
+ values: number[]
+ labels?: string[]
+ referenceLines: SparklineReferenceLine[]
+ relative: boolean
+ renderTooltipValue?: (value: number) => string
+}): JSX.Element {
+ return (
+ <Sparkline
+ type="line"
+ data={values}
+ labels={labels}
+ maximumIndicator={false}
+ referenceLines={referenceLines}
+ renderTooltipValue={renderTooltipValue}
+ withYScale={relative ? allowNegativeYScale : undefined}
+ className="w-full h-24 flex flex-col"
+ />
+ )
+}
+
+export interface AlertPreviewCardProps {
+ alertForm: AlertFormType
+ trendsValues: number[] | null
+ trendsLabels?: string[] | null
+ funnelPreview: FunnelAlertPreview | null
+ hogqlPreview: HogQLAlertPreview | null
+ checkPreview?: TrendsAlertPreviewSeries
+ // Keeps the card visible with a skeleton while data loads instead of popping in once it arrives.
+ loading?: boolean
+}
+
+export function AlertPreviewCard({
+ alertForm,
+ trendsValues,
+ trendsLabels,
+ funnelPreview,
+ hogqlPreview,
+ checkPreview,
+ loading,
+}: AlertPreviewCardProps): JSX.Element {
+ const config = alertForm.config
+ const trendsPreview = trendsValues
+ ? deriveTrendsAlertPreviewSeries(
+ trendsValues,
+ trendsLabels ?? undefined,
+ alertForm.condition?.type ?? AlertConditionType.ABSOLUTE_VALUE,
+ alertForm.threshold?.configuration?.type ?? InsightThresholdType.ABSOLUTE
+ )
+ : null
+ const referenceLines = thresholdReferenceLines(alertForm)
+ const useLogScale = Boolean(trendsPreview && shouldUseLogScale(trendsPreview.values, referenceLines))
+ const previewValues = useLogScale ? trendsPreview?.values.map(toLogScale) : trendsPreview?.values
+ const previewReferenceLines = useLogScale
+ ? referenceLines.map((line) => ({ ...line, value: toLogScale(line.value) }))
+ : referenceLines
+ const checkPreviewValues = checkPreview?.values
+ const isUnconfiguredAbsoluteThreshold =
+ !alertForm.detector_config &&
+ alertForm.condition?.type === AlertConditionType.ABSOLUTE_VALUE &&
+ alertForm.threshold?.configuration?.type === InsightThresholdType.ABSOLUTE &&
+ referenceLines.length === 0
+ const isAnomalyDetectionWithoutVisibleData =
+ !loading &&
+ !!alertForm.detector_config &&
+ isTrendsAlertConfig(config) &&
+ !trendsValues?.some((value) => value !== 0)
+
+ let body: JSX.Element | null = null
+ if (isUnconfiguredAbsoluteThreshold) {
+ body = (
+ <div className="flex h-24 items-center justify-center rounded border border-dashed border-border text-sm text-muted">
+ Set less than or more than to preview this alert.
+ </div>
+ )
+ } else if (checkPreviewValues && checkPreviewValues.length > 0) {
+ body = (
+ <AlertPreviewSparkline
+ values={checkPreviewValues}
+ labels={checkPreview.labels}
+ referenceLines={referenceLines}
+ relative={checkPreview.relative}
+ />
+ )
+ } else if (checkPreview !== undefined) {
+ body = (
+ <div className="flex h-24 items-center justify-center rounded border border-dashed border-border text-sm text-muted">
+ No evaluations available yet.
+ </div>
+ )
+ } else if (isAnomalyDetectionWithoutVisibleData) {
+ body = (
+ <div className="flex h-24 items-center justify-center rounded border border-dashed border-border text-sm text-muted">
+ No activity to preview for this series.
+ </div>
+ )
+ } else if (isTrendsAlertConfig(config) && previewValues && previewValues.length > 0) {
+ body = (
+ <AlertPreviewSparkline
+ values={previewValues}
+ labels={trendsPreview?.labels}
+ referenceLines={previewReferenceLines}
+ renderTooltipValue={useLogScale ? fromLogScale : undefined}
+ relative={!!trendsPreview?.relative}
+ />
+ )
+ } else if (isFunnelsAlertConfig(config) && funnelPreview) {
+ body = <FunnelAlertPreviewBanner preview={funnelPreview} />
+ } else if (isHogQLAlertConfig(config) && hogqlPreview) {
+ body = <HogQLAlertPreviewBanner preview={hogqlPreview} conditionType={alertForm.condition?.type} />
+ }
+
+ if (!body) {
+ if (loading) {
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-1.5 text-sm font-medium">
+ <span>Preview</span>
+ </div>
+ <LemonSkeleton className="h-16 w-full" />
+ </div>
+ )
+ }
+ body = (
+ <div className="flex h-24 items-center justify-center rounded border border-dashed border-border text-sm text-muted">
+ No insight data available to preview.
+ </div>
+ )
+ }
+
+ let lastValue: number | null = null
+ if (checkPreviewValues?.length) {
+ lastValue = checkPreviewValues[checkPreviewValues.length - 1]
+ } else if (isTrendsAlertConfig(config) && trendsPreview?.values.length) {
+ lastValue = trendsPreview.values[trendsPreview.values.length - 1]
+ }
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-1.5 text-sm font-medium">
+ <span>{checkPreview !== undefined ? 'Recent evaluations' : 'Preview'}</span>
+ <Tooltip
+ title={
+ checkPreview !== undefined
+ ? 'Values recorded by recent alert evaluations.'
+ : 'What this alert is watching right now. The dashed lines are your thresholds; points crossing them would fire.'
+ }
+ delayMs={0}
+ >
+ <IconInfo className="text-muted size-3.5" />
+ </Tooltip>
+ </div>
+ <div className="flex items-center gap-2">
+ {useLogScale ? (
+ <Tooltip title="A log scale keeps thresholds with very different values visually distinct.">
+ <LemonTag type="default" className="m-0">
+ Log scale
+ </LemonTag>
+ </Tooltip>
+ ) : null}
+ {lastValue != null ? (
+ <LemonTag type="default" className="m-0">
+ {checkPreview?.relative || trendsPreview?.relative ? 'Latest change:' : 'Latest:'}
+ <strong className="ml-1">{humanFriendlyNumber(lastValue)}</strong>
+ </LemonTag>
+ ) : null}
+ </div>
+ </div>
+ {body}
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/components/AlertPreviewCard.utils.ts b/products/alerts/frontend/components/AlertPreviewCard.utils.ts
new file mode 100644
index 000000000000..0362394aecf4
--- /dev/null
+++ b/products/alerts/frontend/components/AlertPreviewCard.utils.ts
@@ -0,0 +1,63 @@
+import type { SparklineReferenceLine } from 'lib/components/Sparkline'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
+
+import type { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
+
+export function thresholdReferenceLines(alertForm: AlertFormType): SparklineReferenceLine[] {
+ if (alertForm.detector_config) {
+ return []
+ }
+ const configuration = alertForm.threshold?.configuration
+ const bounds = configuration?.bounds
+ const relativePercentage =
+ alertForm.condition?.type !== AlertConditionType.ABSOLUTE_VALUE &&
+ configuration?.type === InsightThresholdType.PERCENTAGE
+ const displayValue = (value: number): number => (relativePercentage ? value * 100 : value)
+ const lines: SparklineReferenceLine[] = []
+ if (bounds?.upper != null && !Number.isNaN(bounds.upper)) {
+ const value = displayValue(bounds.upper)
+ lines.push({
+ value,
+ color: 'danger',
+ label: `above ${humanFriendlyNumber(value)}`,
+ labelPosition: 'end',
+ })
+ }
+ if (bounds?.lower != null && !Number.isNaN(bounds.lower)) {
+ const value = displayValue(bounds.lower)
+ lines.push({
+ value,
+ color: 'danger',
+ label: `below ${humanFriendlyNumber(value)}`,
+ labelPosition: 'start',
+ })
+ }
+ return lines
+}
+
+export function toLogScale(value: number): number {
+ return Math.log10(value + 1)
+}
+
+export function fromLogScale(value: number): string {
+ return humanFriendlyNumber(10 ** value - 1)
+}
+
+export function shouldUseLogScale(values: number[], referenceLines: SparklineReferenceLine[]): boolean {
+ if (
+ referenceLines.length === 0 ||
+ values.some((value) => value < 0 || !Number.isFinite(value)) ||
+ referenceLines.some((line) => line.value < 0)
+ ) {
+ return false
+ }
+ const positiveThresholds = referenceLines.map((line) => line.value).filter((value) => value > 0)
+ if (positiveThresholds.length === 0) {
+ return false
+ }
+ const largestValue = Math.max(...values, ...positiveThresholds)
+ const smallestThreshold = Math.min(...positiveThresholds)
+ return largestValue / smallestThreshold >= 1000
+}
diff --git a/products/alerts/frontend/components/AlertSimulationSection.tsx b/products/alerts/frontend/components/AlertSimulationSection.tsx
new file mode 100644
index 000000000000..655a4b9a327c
--- /dev/null
+++ b/products/alerts/frontend/components/AlertSimulationSection.tsx
@@ -0,0 +1,54 @@
+import { LemonButton, LemonSelect } from '@posthog/lemon-ui'
+
+import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
+import { getDefaultSimulationRange } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { AlertSimulationResult } from 'products/alerts/frontend/types'
+import { SimulationSummary } from 'products/alerts/frontend/views/SimulationSummary'
+
+import { getSimulationRangeOptions } from './editAlertModalUtils'
+
+interface AlertSimulationSectionProps {
+ alertForm: AlertFormType
+ simulationResult: AlertSimulationResult | null
+ simulationResultLoading: boolean
+ simulationDateFrom: string | null
+ onSimulateAlert: () => void
+ onSetSimulationDateFrom: (value: string) => void
+}
+
+export function AlertSimulationSection({
+ alertForm,
+ simulationResult,
+ simulationResultLoading,
+ simulationDateFrom,
+ onSimulateAlert,
+ onSetSimulationDateFrom,
+}: AlertSimulationSectionProps): JSX.Element {
+ return (
+ <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={onSetSimulationDateFrom}
+ 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 && alertForm.detector_config && (
+ <SimulationSummary result={simulationResult} detectorConfig={alertForm.detector_config} />
+ )}
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/components/AlertSummaryBanner.tsx b/products/alerts/frontend/components/AlertSummaryBanner.tsx
new file mode 100644
index 000000000000..f9a343ae5f04
--- /dev/null
+++ b/products/alerts/frontend/components/AlertSummaryBanner.tsx
@@ -0,0 +1,82 @@
+import { ReactNode } from 'react'
+
+import { AlertSummaryParts } from './alertSummary'
+
+export type AlertSummarySection = 'monitor' | 'schedule' | 'notify'
+
+export function AlertSummaryBanner({
+ summary,
+ header,
+ footer,
+ activeSection,
+}: {
+ summary: AlertSummaryParts
+ header?: ReactNode
+ footer?: ReactNode
+ activeSection?: AlertSummarySection
+}): JSX.Element {
+ const fires = summary.fires || 'a threshold'
+ const cadence = summary.cadence || 'unscheduled'
+ const notifies = summary.notifies || 'no one'
+
+ return (
+ <div className="w-full rounded border border-border bg-bg-light px-3 py-2 text-sm space-y-2">
+ {header}
+ <dl className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <SummarySection
+ active={activeSection === 'monitor'}
+ dataAttr="alert-summary-monitor"
+ label="Fires when"
+ value={fires}
+ />
+ <SummarySection
+ active={activeSection === 'schedule'}
+ dataAttr="alert-summary-schedule"
+ label="runs"
+ value={cadence}
+ separated
+ />
+ <SummarySection
+ active={activeSection === 'notify'}
+ dataAttr="alert-summary-notify"
+ label="notifies"
+ value={notifies}
+ separated
+ />
+ </dl>
+ {footer ? <div className="flex text-muted">{footer}</div> : null}
+ </div>
+ )
+}
+
+function SummarySection({
+ active,
+ dataAttr,
+ label,
+ value,
+ separated = false,
+}: {
+ active: boolean
+ dataAttr: string
+ label: string
+ value: string
+ separated?: boolean
+}): JSX.Element {
+ return (
+ <div
+ className={`flex items-center gap-3 ${separated ? "before:text-border before:content-['·']" : ''}`}
+ data-attr={dataAttr}
+ >
+ <dt className={active ? 'font-bold text-primary' : 'text-muted'}>{label}</dt>
+ <dd
+ className={
+ active
+ ? 'font-medium underline decoration-dotted decoration-border underline-offset-4'
+ : 'font-medium'
+ }
+ >
+ {value}
+ </dd>
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/components/AlertWizard.tsx b/products/alerts/frontend/components/AlertWizard.tsx
new file mode 100644
index 000000000000..b9bba8574ee2
--- /dev/null
+++ b/products/alerts/frontend/components/AlertWizard.tsx
@@ -0,0 +1,202 @@
+import posthog from 'posthog-js'
+import { useRef, useState } from 'react'
+
+import { IconChevronLeft } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { AlertEditorActions, AlertEditorHeader } from './AlertEditor'
+
+export interface AlertWizardStep {
+ key: string
+ title: string
+ description?: string
+ /** Whether the step is safe to advance from. Buttons are disabled otherwise. */
+ canAdvance?: boolean
+ /** Reason shown as a tooltip when the step can't advance. */
+ cannotAdvanceReason?: string
+ content: React.ReactNode
+}
+
+export interface AlertWizardProps {
+ title: string
+ steps: AlertWizardStep[]
+ isSubmitting: boolean
+ hasChanges: boolean
+ onBack: () => void
+ onSubmitAttempted: () => void
+ leadingActions?: React.ReactNode
+}
+
+/** Stepped layout for creating a new alert. Three steps (Monitor → Schedule & notify → Review)
+ * keep each screen's cognitive load low; the progress indicator shows where you are and the
+ * Review step surfaces a plain-English summary before committing. */
+export function AlertWizard({
+ title,
+ steps,
+ isSubmitting,
+ hasChanges,
+ onBack,
+ onSubmitAttempted,
+ leadingActions,
+}: AlertWizardProps): JSX.Element {
+ const [current, setCurrent] = useState(0)
+ const [blockedAdvanceAttempted, setBlockedAdvanceAttempted] = useState(false)
+ const capturedCompletedSteps = useRef(new Set<string>())
+ const step = steps[current]
+ const isFirst = current === 0
+ const isLast = current === steps.length - 1
+ const canAdvance = step?.canAdvance !== false
+
+ const captureCompletedSteps = (nextStepIndex: number): void => {
+ for (let index = current; index < nextStepIndex; index++) {
+ const completedStep = steps[index]
+ if (!completedStep || capturedCompletedSteps.current.has(completedStep.key)) {
+ continue
+ }
+ posthog.capture('alert wizard step completed', {
+ step_key: completedStep.key,
+ step_number: index + 1,
+ next_step_key: steps[index + 1]?.key,
+ total_steps: steps.length,
+ })
+ capturedCompletedSteps.current.add(completedStep.key)
+ }
+ }
+
+ const goNext = (): void => {
+ if (!canAdvance) {
+ setBlockedAdvanceAttempted(true)
+ onSubmitAttempted?.()
+ return
+ }
+ setBlockedAdvanceAttempted(false)
+ captureCompletedSteps(current + 1)
+ setCurrent((i) => Math.min(i + 1, steps.length - 1))
+ }
+ const goPrev = (): void => {
+ setBlockedAdvanceAttempted(false)
+ setCurrent((i) => Math.max(i - 1, 0))
+ }
+
+ return (
+ <div
+ className="flex flex-col min-h-0 flex-1 overflow-hidden"
+ onKeyDown={(event) => {
+ if (
+ event.key === 'Enter' &&
+ !event.nativeEvent.isComposing &&
+ !isLast &&
+ event.target instanceof HTMLInputElement
+ ) {
+ event.preventDefault()
+ goNext()
+ }
+ }}
+ >
+ <header className="border-b p-4">
+ <AlertEditorHeader title={title} onBack={onBack} />
+ <nav aria-label="Alert setup progress" className="mt-3">
+ <ol className="flex items-center gap-1">
+ {steps.map((s, i) => {
+ const isCurrent = i === current
+ const isComplete = i < current
+ const canAccess =
+ i <= current || steps.slice(current, i).every((st) => st.canAdvance !== false)
+ return (
+ <li key={s.key} className="flex items-center gap-1 min-w-0">
+ <button
+ type="button"
+ disabled={!canAccess}
+ onClick={() => {
+ if (canAccess) {
+ setBlockedAdvanceAttempted(false)
+ if (i > current) {
+ captureCompletedSteps(i)
+ }
+ setCurrent(i)
+ }
+ }}
+ className={cn(
+ 'flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-accent',
+ !canAccess && 'opacity-40 cursor-not-allowed',
+ isCurrent
+ ? 'bg-accent text-white font-semibold'
+ : isComplete
+ ? 'bg-success-highlight text-success'
+ : 'text-muted hover:bg-border'
+ )}
+ aria-current={isCurrent ? 'step' : undefined}
+ >
+ <span
+ className={cn(
+ 'inline-flex size-5 shrink-0 items-center justify-center rounded-full text-[11px] font-bold',
+ isCurrent
+ ? 'bg-white text-accent'
+ : isComplete
+ ? 'bg-success text-white'
+ : 'border border-border'
+ )}
+ >
+ {i + 1}
+ </span>
+ <span className="truncate">{s.title}</span>
+ </button>
+ {!isLastStep(i, steps) ? (
+ <span className="text-border" aria-hidden>
+ →
+ </span>
+ ) : null}
+ </li>
+ )
+ })}
+ </ol>
+ </nav>
+ </header>
+ <section className="p-4 min-h-0 flex-1 overflow-y-auto">
+ <div className="space-y-1 mb-3">
+ <h3 className="text-base font-semibold m-0">{step?.title}</h3>
+ {step?.description ? <p className="text-xs text-secondary m-0">{step.description}</p> : null}
+ </div>
+ {step?.content}
+ </section>
+ <footer className="flex flex-wrap items-center justify-between gap-2 border-t p-4">
+ <div className="flex-1">{leadingActions ? leadingActions : null}</div>
+ <div className="flex items-center gap-2">
+ {blockedAdvanceAttempted && !canAdvance && step?.cannotAdvanceReason ? (
+ <span className="text-sm text-danger" role="alert">
+ {step.cannotAdvanceReason}
+ </span>
+ ) : null}
+ {isFirst ? (
+ <LemonButton type="secondary" onClick={onBack}>
+ Close
+ </LemonButton>
+ ) : (
+ <LemonButton type="secondary" icon={<IconChevronLeft />} onClick={goPrev}>
+ Back
+ </LemonButton>
+ )}
+ {!isLast ? (
+ // Stays clickable when blocked so goNext can surface the step's validation errors.
+ <LemonButton type="primary" onClick={goNext}>
+ Continue
+ </LemonButton>
+ ) : (
+ <AlertEditorActions
+ isEditing={false}
+ isSubmitting={isSubmitting}
+ hasChanges={hasChanges}
+ onSubmitAttempted={onSubmitAttempted}
+ />
+ )}
+ </div>
+ </footer>
+ </div>
+ )
+}
+
+function isLastStep(index: number, steps: AlertWizardStep[]): boolean {
+ return index === steps.length - 1
+}
diff --git a/products/alerts/frontend/components/HogQLAlertPreview.tsx b/products/alerts/frontend/components/HogQLAlertPreview.tsx
index 7fe156f572a3..ca7e8f838c6e 100644
--- a/products/alerts/frontend/components/HogQLAlertPreview.tsx
+++ b/products/alerts/frontend/components/HogQLAlertPreview.tsx
@@ -1,3 +1,5 @@
+import type { ReactNode } from 'react'
+
import { LemonBanner, LemonTable, LemonTag } from '@posthog/lemon-ui'
import { humanFriendlyNumber } from 'lib/utils/numbers'
@@ -13,8 +15,21 @@ import {
const PREVIEW_TABLE_MAX_ROWS = 10
+function HogQLPreviewStatus({ wouldFire, children }: { wouldFire: boolean | null; children: ReactNode }): JSX.Element {
+ return (
+ <div className="rounded border border-border bg-bg-light p-3 text-sm">
+ {wouldFire !== null ? (
+ <LemonTag type={wouldFire ? 'danger' : 'success'} className="mr-2">
+ {wouldFire ? 'Would fire' : 'Would not fire'}
+ </LemonTag>
+ ) : null}
+ {children}
+ </div>
+ )
+}
+
/** Per-row view of what the alert would evaluate: breaching rows first (any-row) or the most
- * recent rows (last-row), capped to keep the modal compact. Shown even before a threshold is set —
+ * recent rows (last-row), capped to keep the modal compact. Shown even before a threshold is set.
* seeing the rows is how users orient on what to alert on; the breach column appears once bounds exist. */
export function HogQLAlertPreviewRowsTable({
preview,
@@ -33,7 +48,7 @@ export function HogQLAlertPreviewRowsTable({
// Only the evaluated row is tagged in single-row modes (the banner carries the rest); any-row
// tags them all. first_row evaluates the top row, last_row the bottom.
const evaluatedIndex = isAnyRow ? null : isFirstRow ? 0 : rows.length - 1
- // The trimmed rows are always the older ones — in last_row they sit before the visible window
+ // The trimmed rows are always the older ones. In last_row they sit before the visible window
// (note above), in first_row after it (note below); below would read as newer data otherwise.
const overflowNote =
hiddenCount > 0 ? (
@@ -54,7 +69,7 @@ export function HogQLAlertPreviewRowsTable({
{
title: preview.columnName ?? 'Value',
render: (_, row: HogQLAlertPreviewRow) =>
- row.value !== null ? humanFriendlyNumber(row.value) : '—',
+ row.value !== null ? humanFriendlyNumber(row.value) : 'N/A',
},
...(showStatus
? [
@@ -63,9 +78,9 @@ export function HogQLAlertPreviewRowsTable({
render: (_: unknown, row: HogQLAlertPreviewRow, index: number) =>
index === evaluatedIndex || isAnyRow ? (
row.breaching ? (
- <LemonTag type="warning">breach</LemonTag>
+ <LemonTag type="danger">Would fire</LemonTag>
) : (
- <LemonTag type="success">ok</LemonTag>
+ <LemonTag type="success">Would not fire</LemonTag>
)
) : null,
},
@@ -78,135 +93,105 @@ export function HogQLAlertPreviewRowsTable({
)
}
-/** Shows what the SQL alert would evaluate right now, surfacing shape problems before the first check. */
-export function HogQLAlertPreviewBanner({
- preview,
- conditionType,
-}: {
- preview: HogQLAlertPreview | null
- conditionType?: AlertConditionType
-}): JSX.Element {
- if (preview === null) {
- return (
- <LemonBanner type="info">
- This alert evaluates the SQL insight's result — load the insight to preview the value.
- </LemonBanner>
- )
- }
+function getHogQLPreviewBannerCopy(preview: Exclude<HogQLAlertPreview, { status: 'ok' }>): ReactNode {
switch (preview.status) {
case 'no-rows':
- return (
- <LemonBanner type="info">
- The query currently returns no rows — the alert evaluates this as 0, so a lower bound can still
- fire.
- </LemonBanner>
- )
+ return 'The query currently returns no rows. The alert evaluates this as 0, so a lower bound can still fire.'
case 'too-many-rows':
return (
- <LemonBanner type="warning">
+ <>
Any-row alerts evaluate at most {HOGQL_ANY_ROW_MAX_ROWS} rows, but the query returns{' '}
- {preview.rowCount} — add a LIMIT or aggregate the query, or the alert will fail to evaluate.
- </LemonBanner>
+ {preview.rowCount}. Add a LIMIT or aggregate the query, or the alert will fail to evaluate.
+ </>
)
case 'last-row-truncated':
return (
- <LemonBanner type="warning">
+ <>
The query returns {preview.rowCount.toLocaleString()} rows and may be truncated, so the last row
- isn't reliably the newest — add a LIMIT, aggregate the query, or switch to evaluating the first row
+ isn't reliably the newest. Add a LIMIT, aggregate the query, or switch to evaluating the first row
(newest-first ordering), or the alert will fail to evaluate.
- </LemonBanner>
+ </>
)
case 'bad-shape':
- return (
- <LemonBanner type="warning">
- The query result isn't plain rows of values — the alert requires a query returning rows with a
- numeric column.
- </LemonBanner>
- )
+ return "The query result isn't plain rows of values. The alert requires a query returning rows with a numeric column."
case 'ambiguous-columns':
return (
- <LemonBanner type="warning">
+ <>
The value column can't be inferred
- {preview.columnNames ? ` (columns: ${preview.columnNames.join(', ')})` : ''} — pick the column to
+ {preview.columnNames ? ` (columns: ${preview.columnNames.join(', ')})` : ''}. Pick the column to
evaluate above.
- </LemonBanner>
+ </>
)
case 'missing-column':
return (
- <LemonBanner type="warning">
+ <>
Column "{preview.column}" is no longer returned by the query
- {preview.columnNames ? ` (columns: ${preview.columnNames.join(', ')})` : ''} — pick another column
- to evaluate.
- </LemonBanner>
+ {preview.columnNames ? ` (columns: ${preview.columnNames.join(', ')})` : ''}. Pick another column to
+ evaluate.
+ </>
)
case 'not-numeric':
- return (
- <LemonBanner type="warning">
- The evaluated value ({preview.value}) isn't a number — pick a numeric column to evaluate.
- </LemonBanner>
- )
- case 'ok': {
- const isRelative =
- conditionType === AlertConditionType.RELATIVE_INCREASE ||
- conditionType === AlertConditionType.RELATIVE_DECREASE
- const columnLabel = preview.columnName ? (
+ return `The evaluated value (${preview.value}) isn't a number. Pick a numeric column to evaluate.`
+ }
+}
+
+/** Shows what the SQL alert would evaluate right now, surfacing shape problems before the first check. */
+export function HogQLAlertPreviewBanner({
+ preview,
+ conditionType,
+}: {
+ preview: HogQLAlertPreview | null
+ conditionType?: AlertConditionType
+}): JSX.Element {
+ if (preview === null) {
+ return (
+ <LemonBanner type="info">
+ This alert evaluates the SQL insight's result. Load the insight to preview the value.
+ </LemonBanner>
+ )
+ }
+ if (preview.status !== 'ok') {
+ return (
+ <LemonBanner type={preview.status === 'no-rows' ? 'info' : 'warning'}>
+ {getHogQLPreviewBannerCopy(preview)}
+ </LemonBanner>
+ )
+ }
+
+ const isRelative =
+ conditionType === AlertConditionType.RELATIVE_INCREASE || conditionType === AlertConditionType.RELATIVE_DECREASE
+ if (preview.mode === 'any_row') {
+ const breaching = preview.breachingRows
+ return (
+ <HogQLPreviewStatus wouldFire={breaching !== null ? breaching > 0 : null}>
+ {breaching !== null ? (
+ <>
+ <strong>{breaching}</strong> of {preview.rowCount} rows are outside the threshold.
+ </>
+ ) : (
+ <>{preview.rowCount} rows available. Set a threshold to see which would fire.</>
+ )}
+ </HogQLPreviewStatus>
+ )
+ }
+ if (isRelative && preview.rowCount < 2) {
+ return (
+ <LemonBanner type="warning">
+ Relative conditions compare the two most recent rows, but the query currently returns only one row.
+ </LemonBanner>
+ )
+ }
+ const isFirstRow = preview.mode === 'first_row'
+ const evaluatedRow = isFirstRow ? preview.rows[0] : preview.rows[preview.rows.length - 1]
+ const wouldFire = preview.breachingRows !== null ? evaluatedRow?.breaching === true : null
+ return (
+ <HogQLPreviewStatus wouldFire={wouldFire}>
+ Current value: <strong>{humanFriendlyNumber(preview.currentValue)}</strong>
+ {isRelative && preview.previousValue !== null ? (
<>
- the <strong>{preview.columnName}</strong> column
+ . Previous value: <strong>{humanFriendlyNumber(preview.previousValue)}</strong>
</>
- ) : (
- 'the result'
- )
- if (preview.mode === 'any_row') {
- const breaching = preview.breachingRows
- return (
- <LemonBanner type={breaching ? 'warning' : 'info'}>
- The alert checks every row of {columnLabel}
- {breaching !== null ? (
- <>
- {' '}
- — currently <strong>{breaching}</strong> of {preview.rowCount} rows breach the threshold
- {breaching > 0 ? ', so the alert would fire on its next check' : ''}.
- </>
- ) : (
- <>. Set a threshold to preview which rows would breach.</>
- )}
- </LemonBanner>
- )
- }
- if (isRelative && preview.rowCount < 2) {
- return (
- <LemonBanner type="warning">
- Relative conditions compare the two most recent rows, but the query currently returns only one
- row.
- </LemonBanner>
- )
- }
- const isFirstRow = preview.mode === 'first_row'
- const anchorRowLabel = isFirstRow ? 'first row' : 'last row'
- const orderingHint = isFirstRow
- ? 'Order the query newest→oldest (e.g. ORDER BY ... DESC) so the first row is the most recent value.'
- : 'Order the query oldest→newest so the last row is the most recent value.'
- return (
- <LemonBanner type="info">
- The alert evaluates the {anchorRowLabel} of {columnLabel} — currently{' '}
- <strong>{humanFriendlyNumber(preview.currentValue)}</strong>
- {isRelative && preview.previousValue !== null ? (
- <>
- {' '}
- vs <strong>{humanFriendlyNumber(preview.previousValue)}</strong> in the previous row
- </>
- ) : null}
- . {orderingHint}
- {!isRelative && preview.breachingRows !== null ? (
- <>
- {' '}
- Right now <strong>{preview.breachingRows}</strong> of its{' '}
- {pluralize(preview.rowCount, 'row')} {preview.breachingRows === 1 ? 'is' : 'are'} outside
- the threshold.
- </>
- ) : null}
- </LemonBanner>
- )
- }
- }
+ ) : null}
+ </HogQLPreviewStatus>
+ )
}
diff --git a/products/alerts/frontend/components/InvestigationAgentSettings.tsx b/products/alerts/frontend/components/InvestigationAgentSettings.tsx
new file mode 100644
index 000000000000..c95c1889679f
--- /dev/null
+++ b/products/alerts/frontend/components/InvestigationAgentSettings.tsx
@@ -0,0 +1,86 @@
+import { IconInfo } from '@posthog/icons'
+import { LemonCheckbox, LemonSegmentedButton, Tooltip } from '@posthog/lemon-ui'
+
+import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
+
+interface InvestigationAgentSettingsProps {
+ alertForm: AlertFormType
+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
+}
+
+export function InvestigationAgentSettings({
+ alertForm,
+ onSetAlertFormValue,
+}: InvestigationAgentSettingsProps): JSX.Element {
+ return (
+ <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 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 because an unsure agent is itself signal.',
+ },
+ { value: 'suppress', label: 'Suppress', tooltip: 'Only notify on true positives.' },
+ ]}
+ />
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/components/SnoozeButton.tsx b/products/alerts/frontend/components/SnoozeButton.tsx
index c969c12fdf66..6fbe4dbce2fc 100644
--- a/products/alerts/frontend/components/SnoozeButton.tsx
+++ b/products/alerts/frontend/components/SnoozeButton.tsx
@@ -1,3 +1,6 @@
+import { IconCalendar } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { dayjs } from 'lib/dayjs'
import { formatDate } from 'lib/utils/datetime'
@@ -7,14 +10,25 @@ const DATETIME_FORMAT = 'MMM D - HH:mm'
interface SnoozeButtonProps {
onChange: (snoonzeUntil: string) => void
value?: string
+ disabledReason?: string
}
-export function SnoozeButton({ onChange, value }: SnoozeButtonProps): JSX.Element {
+export function SnoozeButton({ onChange, value, disabledReason }: SnoozeButtonProps): JSX.Element {
+ if (disabledReason) {
+ return (
+ <LemonButton type="secondary" size="medium" icon={<IconCalendar />} disabledReason={disabledReason}>
+ Snooze until
+ </LemonButton>
+ )
+ }
+
return (
<DateFilter
dateFrom={value ?? null}
onChange={(snoozeUntil) => {
- snoozeUntil && onChange(snoozeUntil)
+ if (snoozeUntil) {
+ onChange(snoozeUntil)
+ }
}}
placeholder="Snooze until"
max={31}
diff --git a/products/alerts/frontend/components/ThresholdConditionRow.tsx b/products/alerts/frontend/components/ThresholdConditionRow.tsx
new file mode 100644
index 000000000000..37d1c56d235a
--- /dev/null
+++ b/products/alerts/frontend/components/ThresholdConditionRow.tsx
@@ -0,0 +1,198 @@
+import { Group } from 'kea-forms'
+
+import { LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
+
+import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
+import {
+ fractionToPercentInput,
+ inputToStoredBound,
+ thresholdForConditionChange,
+ thresholdForUnitChange,
+} from 'products/alerts/frontend/logic/thresholdPercent'
+import { isFunnelsAlertConfig } from 'products/alerts/frontend/types'
+
+export interface ThresholdConditionRowProps {
+ alertForm: AlertFormType
+ thresholdBoundsFormError?: string
+ isNonTimeSeriesDisplay: boolean
+ /** Whether relative conditions (increase/decrease by) are pickable. False for steps funnels;
+ * true for trends, HogQL last/first row, and trends funnels. */
+ supportsRelativeConditions: boolean
+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
+}
+
+/** Relative conditions (increase/decrease by) need a time series, so they're disabled for non-time-series
+ * trends and for HogQL any-row mode. Mirrors the gating in AlertDefinitionSection. */
+function relativeConditionDisabledReason(isNonTimeSeriesDisplay: boolean, isAnyRowHogQL: boolean): string | undefined {
+ if (isNonTimeSeriesDisplay) {
+ return 'This condition is only supported for time series trends'
+ }
+ if (isAnyRowHogQL) {
+ return "Rows in any-row mode aren't a time series — switch to 'the latest value' for relative conditions"
+ }
+ return undefined
+}
+
+interface ConditionOption {
+ label: string
+ value: AlertConditionType
+ disabledReason?: string
+}
+
+const CONDITION_OPTIONS = (disabledReason?: string): ConditionOption[] => [
+ { label: 'has value', value: AlertConditionType.ABSOLUTE_VALUE },
+ { label: 'increases by', value: AlertConditionType.RELATIVE_INCREASE, disabledReason },
+ { label: 'decreases by', value: AlertConditionType.RELATIVE_DECREASE, disabledReason },
+]
+
+const UNIT_OPTIONS = [
+ { value: InsightThresholdType.PERCENTAGE, label: '%', tooltip: 'Percent' },
+ { value: InsightThresholdType.ABSOLUTE, label: '#', tooltip: 'Absolute number' },
+]
+
+/** The threshold + condition config, laid out as separate labeled rows. */
+export function ThresholdConditionRow({
+ alertForm,
+ thresholdBoundsFormError,
+ isNonTimeSeriesDisplay,
+ supportsRelativeConditions,
+ onSetAlertFormValue,
+}: ThresholdConditionRowProps): JSX.Element {
+ const isFunnelAlert = isFunnelsAlertConfig(alertForm.config)
+ const isAnyRowHogQL =
+ !!alertForm.config && alertForm.config.type === 'HogQLAlertConfig' && alertForm.config.evaluation === 'any_row'
+ const disabledReason = relativeConditionDisabledReason(isNonTimeSeriesDisplay, isAnyRowHogQL)
+ const isRelative = alertForm.condition?.type !== AlertConditionType.ABSOLUTE_VALUE
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-muted shrink-0 w-20">Fire when</span>
+ <Group name={['condition']}>
+ <LemonField name="type">
+ {({ value, onChange }) => (
+ <LemonSelect
+ fullWidth
+ className="w-40 shrink-0"
+ data-attr="alertForm-condition"
+ value={value}
+ onChange={(newType) => {
+ onChange(newType)
+ const configuration = alertForm.threshold.configuration
+ const nextConfiguration = thresholdForConditionChange(
+ configuration,
+ newType,
+ isFunnelAlert
+ )
+ if (nextConfiguration === configuration) {
+ return
+ }
+ onSetAlertFormValue('threshold', {
+ configuration: nextConfiguration,
+ })
+ }}
+ options={
+ supportsRelativeConditions
+ ? CONDITION_OPTIONS(disabledReason)
+ : CONDITION_OPTIONS(undefined).filter(
+ (o) => o.value === AlertConditionType.ABSOLUTE_VALUE
+ )
+ }
+ />
+ )}
+ </LemonField>
+ </Group>
+ {!isFunnelAlert && isRelative && (
+ <LemonSegmentedButton
+ size="small"
+ value={alertForm.threshold.configuration.type}
+ options={UNIT_OPTIONS}
+ onChange={(newType) =>
+ onSetAlertFormValue('threshold', {
+ configuration: thresholdForUnitChange(alertForm.threshold.configuration, newType),
+ })
+ }
+ />
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <label className="text-sm text-muted shrink-0 w-20" htmlFor="alertForm-lower-threshold">
+ Less than
+ </label>
+ <LemonField name="lower">
+ <LemonInput
+ type="number"
+ min={isRelative ? 0 : undefined}
+ className="w-32"
+ status={thresholdBoundsFormError ? 'danger' : 'default'}
+ data-attr="alertForm-lower-threshold"
+ suffix={isFunnelAlert ? <span aria-label="percent">%</span> : undefined}
+ value={
+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE
+ ? fractionToPercentInput(alertForm.threshold.configuration.bounds?.lower)
+ : alertForm.threshold.configuration.bounds?.lower
+ }
+ onChange={(value) =>
+ onSetAlertFormValue('threshold', {
+ configuration: {
+ type: alertForm.threshold.configuration.type,
+ bounds: {
+ ...alertForm.threshold.configuration.bounds,
+ lower: inputToStoredBound(value, alertForm.threshold.configuration.type),
+ },
+ },
+ })
+ }
+ />
+ </LemonField>
+ </div>
+ <div className="flex items-center gap-2">
+ <label className="text-sm text-muted shrink-0 w-20" htmlFor="alertForm-upper-threshold">
+ More than
+ </label>
+ <LemonField name="upper">
+ <LemonInput
+ type="number"
+ min={isRelative ? 0 : undefined}
+ className="w-32"
+ status={thresholdBoundsFormError ? 'danger' : 'default'}
+ data-attr="alertForm-upper-threshold"
+ suffix={isFunnelAlert ? <span aria-label="percent">%</span> : undefined}
+ value={
+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE
+ ? fractionToPercentInput(alertForm.threshold.configuration.bounds?.upper)
+ : alertForm.threshold.configuration.bounds?.upper
+ }
+ onChange={(value) =>
+ onSetAlertFormValue('threshold', {
+ configuration: {
+ type: alertForm.threshold.configuration.type,
+ bounds: {
+ ...alertForm.threshold.configuration.bounds,
+ upper: inputToStoredBound(value, alertForm.threshold.configuration.type),
+ },
+ },
+ })
+ }
+ />
+ </LemonField>
+ </div>
+ <p
+ className={
+ thresholdBoundsFormError
+ ? 'm-0 min-h-10 pl-[5.5rem] text-xs text-danger'
+ : 'm-0 min-h-10 pl-[5.5rem] text-xs text-secondary'
+ }
+ >
+ {thresholdBoundsFormError ?? 'Enter a value in either field.'}
+ </p>
+ </div>
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/components/ThresholdDefinitionRow.tsx b/products/alerts/frontend/components/ThresholdDefinitionRow.tsx
new file mode 100644
index 000000000000..eefab8344f03
--- /dev/null
+++ b/products/alerts/frontend/components/ThresholdDefinitionRow.tsx
@@ -0,0 +1,151 @@
+import { Group } from 'kea-forms'
+
+import { LemonBanner, LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
+
+import { AlertDefinitionRow } from 'products/alerts/frontend/components/AlertDefinition'
+import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
+import {
+ fractionToPercentInput,
+ inputToStoredBound,
+ thresholdForConditionChange,
+} from 'products/alerts/frontend/logic/thresholdPercent'
+import { isAnyRowHogQLConfig, isFunnelsAlertConfig } from 'products/alerts/frontend/types'
+
+export interface ThresholdRowRenderProps {
+ alertForm: AlertFormType
+ thresholdBoundsFormError?: string
+ isNonTimeSeriesDisplay: boolean
+ supportsRelativeConditions: boolean
+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
+}
+
+export function ThresholdDefinitionRow({
+ alertForm,
+ thresholdBoundsFormError,
+ isNonTimeSeriesDisplay,
+ supportsRelativeConditions,
+ onSetAlertFormValue,
+}: ThresholdRowRenderProps): JSX.Element {
+ const isFunnelAlert = isFunnelsAlertConfig(alertForm.config)
+ const relativeConditionDisabledReason =
+ (isNonTimeSeriesDisplay && 'This condition is only supported for time series trends') ||
+ (isAnyRowHogQLConfig(alertForm.config) &&
+ "Rows in any-row mode aren't a time series. Switch to 'the latest value' for relative conditions")
+
+ return (
+ <div className="space-y-2">
+ {thresholdBoundsFormError ? <LemonBanner type="error">{thresholdBoundsFormError}</LemonBanner> : null}
+ <AlertDefinitionRow>
+ {supportsRelativeConditions && (
+ <Group name={['condition']}>
+ <LemonField name="type">
+ {({ value, onChange }) => (
+ <LemonSelect
+ fullWidth
+ className="w-40"
+ data-attr="alertForm-condition"
+ value={value}
+ onChange={(newType) => {
+ onChange(newType)
+ const configuration = alertForm.threshold.configuration
+ const nextConfiguration = thresholdForConditionChange(
+ configuration,
+ newType,
+ isFunnelAlert
+ )
+ if (nextConfiguration === configuration) {
+ return
+ }
+ onSetAlertFormValue('threshold', { configuration: nextConfiguration })
+ }}
+ options={[
+ { label: 'has value', value: AlertConditionType.ABSOLUTE_VALUE },
+ {
+ label: 'increases by',
+ value: AlertConditionType.RELATIVE_INCREASE,
+ disabledReason: relativeConditionDisabledReason,
+ },
+ {
+ label: 'decreases by',
+ value: AlertConditionType.RELATIVE_DECREASE,
+ disabledReason: relativeConditionDisabledReason,
+ },
+ ]}
+ />
+ )}
+ </LemonField>
+ </Group>
+ )}
+ <div>less than</div>
+ <LemonField name="lower">
+ <LemonInput
+ type="number"
+ min={alertForm.condition.type === AlertConditionType.ABSOLUTE_VALUE ? undefined : 0}
+ className="w-30"
+ data-attr="alertForm-lower-threshold"
+ suffix={isFunnelAlert ? <span aria-label="percent">%</span> : undefined}
+ value={
+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE
+ ? fractionToPercentInput(alertForm.threshold.configuration.bounds?.lower)
+ : alertForm.threshold.configuration.bounds?.lower
+ }
+ onChange={(value) =>
+ onSetAlertFormValue('threshold', {
+ configuration: {
+ type: alertForm.threshold.configuration.type,
+ bounds: {
+ ...alertForm.threshold.configuration.bounds,
+ lower: inputToStoredBound(value, alertForm.threshold.configuration.type),
+ },
+ },
+ })
+ }
+ />
+ </LemonField>
+ <div>or more than</div>
+ <LemonField name="upper">
+ <LemonInput
+ type="number"
+ min={alertForm.condition.type === AlertConditionType.ABSOLUTE_VALUE ? undefined : 0}
+ className="w-30"
+ data-attr="alertForm-upper-threshold"
+ suffix={isFunnelAlert ? <span aria-label="percent">%</span> : undefined}
+ value={
+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE
+ ? fractionToPercentInput(alertForm.threshold.configuration.bounds?.upper)
+ : alertForm.threshold.configuration.bounds?.upper
+ }
+ onChange={(value) =>
+ onSetAlertFormValue('threshold', {
+ configuration: {
+ type: alertForm.threshold.configuration.type,
+ bounds: {
+ ...alertForm.threshold.configuration.bounds,
+ upper: inputToStoredBound(value, alertForm.threshold.configuration.type),
+ },
+ },
+ })
+ }
+ />
+ </LemonField>
+ {/* Funnels always compare as a percentage of the prior period, so their unit is fixed. */}
+ {!isFunnelAlert && 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>
+ )}
+ </AlertDefinitionRow>
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/components/alertSummary.ts b/products/alerts/frontend/components/alertSummary.ts
new file mode 100644
index 000000000000..3ef8707bbb0c
--- /dev/null
+++ b/products/alerts/frontend/components/alertSummary.ts
@@ -0,0 +1,136 @@
+import { AlertCalculationInterval, AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
+
+import { intervalDropdownPhrase } from 'products/alerts/frontend/components/editAlertModalUtils'
+import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
+import { type AlertConfig, type AlertType } from 'products/alerts/frontend/types'
+
+export interface AlertSummaryParts {
+ /** What the alert watches — e.g. "value below 100" or "anomalies". Empty when unknown. */
+ fires: string
+ /** How often it runs — e.g. "every day". Empty when unknown. */
+ cadence: string
+ /** Who it notifies — e.g. "2 people" or "2 people + Slack". Empty when none configured. */
+ notifies: string
+}
+
+const ALERT_KIND_LABELS: Partial<Record<AlertConfig['type'], string>> = {
+ TrendsAlertConfig: 'Trends',
+ FunnelsAlertConfig: 'Funnels',
+ HogQLAlertConfig: 'SQL',
+}
+
+export function formatNotificationSummary(subscribedCount: number, destinationCount: number): string {
+ const parts: string[] = []
+ if (subscribedCount > 0) {
+ parts.push(`${subscribedCount} ${subscribedCount === 1 ? 'person' : 'people'}`)
+ }
+ if (destinationCount > 0) {
+ parts.push(`${destinationCount} ${destinationCount === 1 ? 'destination' : 'destinations'}`)
+ }
+ return parts.join(' + ')
+}
+
+function boundForDisplay(value: number | undefined, thresholdType: InsightThresholdType): number | null {
+ if (value == null || Number.isNaN(value)) {
+ return null
+ }
+ return thresholdType === InsightThresholdType.PERCENTAGE ? value * 100 : value
+}
+
+export function formatThresholdSummary(
+ conditionType: AlertConditionType,
+ thresholdType: InsightThresholdType,
+ lower: number | undefined,
+ upper: number | undefined
+): string {
+ const lo = boundForDisplay(lower, thresholdType)
+ const hi = boundForDisplay(upper, thresholdType)
+ const both = lo != null && hi != null
+ const unit = thresholdType === InsightThresholdType.PERCENTAGE ? '%' : ''
+ switch (conditionType) {
+ case AlertConditionType.RELATIVE_INCREASE:
+ if (both) {
+ return `increase outside ${lo}${unit} – ${hi}${unit}`
+ }
+ if (lo != null) {
+ return `increase below ${lo}${unit}`
+ }
+ if (hi != null) {
+ return `increase above ${hi}${unit}`
+ }
+ return 'increase breaches a threshold'
+ case AlertConditionType.RELATIVE_DECREASE:
+ if (both) {
+ return `decrease outside ${lo}${unit} – ${hi}${unit}`
+ }
+ if (lo != null) {
+ return `decrease below ${lo}${unit}`
+ }
+ if (hi != null) {
+ return `decrease above ${hi}${unit}`
+ }
+ return 'decrease breaches a threshold'
+ default:
+ if (both) {
+ return `value outside ${lo} – ${hi}`
+ }
+ if (lo != null) {
+ return `value below ${lo}`
+ }
+ if (hi != null) {
+ return `value above ${hi}`
+ }
+ return 'value breaches a threshold'
+ }
+}
+
+function detectorSummary(): string {
+ return 'an anomaly'
+}
+
+/** Build a one-line human summary of what an alert does. Pure (no React) so it can feed a header
+ * string, a wizard review step, or a tooltip. Returns empty parts when the form is too incomplete
+ * to summarize — the caller decides whether to render them at all. */
+export function buildAlertSummary(
+ alertForm: AlertFormType | AlertType,
+ subscribedCount: number,
+ destinationCount = 0
+): AlertSummaryParts {
+ const alertMode = alertForm.detector_config ? 'detector' : 'threshold'
+
+ let fires = ''
+ if (alertMode === 'detector') {
+ fires = detectorSummary()
+ } else {
+ const bounds = alertForm.threshold?.configuration?.bounds
+ fires = formatThresholdSummary(
+ alertForm.condition?.type ?? AlertConditionType.ABSOLUTE_VALUE,
+ alertForm.threshold?.configuration?.type ?? InsightThresholdType.ABSOLUTE,
+ bounds?.lower,
+ bounds?.upper
+ )
+ }
+
+ let cadence = ''
+ if (alertForm.calculation_interval) {
+ const phrase = intervalDropdownPhrase(alertForm.calculation_interval)
+ cadence =
+ alertForm.calculation_interval === AlertCalculationInterval.REAL_TIME ? `in real time` : `every ${phrase}`
+ }
+
+ const notifies = formatNotificationSummary(subscribedCount, destinationCount)
+
+ return { fires, cadence, notifies }
+}
+
+/** Short label for the alert kind — used by the header to hint what's being monitored. */
+export function alertKindLabel(alertForm: AlertFormType | AlertType | null | undefined): string | null {
+ if (!alertForm) {
+ return null
+ }
+ const config = alertForm.config
+ if (!config) {
+ return null
+ }
+ return ALERT_KIND_LABELS[config.type] ?? null
+}
diff --git a/products/alerts/frontend/logic/alertFormLogic.test.ts b/products/alerts/frontend/logic/alertFormLogic.test.ts
index 433de0e9e2ae..1193fe41d9d3 100644
--- a/products/alerts/frontend/logic/alertFormLogic.test.ts
+++ b/products/alerts/frontend/logic/alertFormLogic.test.ts
@@ -115,6 +115,7 @@ describe('alertFormLogic', () => {
let errorToastSpy: jest.SpyInstance
let successToastSpy: jest.SpyInstance
let captureExceptionSpy: jest.SpyInstance
+ let captureSpy: jest.SpyInstance
beforeEach(() => {
initKeaTests()
@@ -126,6 +127,7 @@ describe('alertFormLogic', () => {
errorToastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(jest.fn())
successToastSpy = jest.spyOn(lemonToast, 'success').mockImplementation(jest.fn())
captureExceptionSpy = jest.spyOn(posthog, 'captureException').mockImplementation(jest.fn())
+ captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(jest.fn())
insightLogic(insightLogicProps).mount()
insightDataLogic(insightLogicProps).mount()
@@ -149,6 +151,7 @@ describe('alertFormLogic', () => {
onEditSuccess,
insightVizDataLogicProps: insightLogicProps,
insightInterval: 'day',
+ uiVersion: 'redesigned',
})
logic.mount()
logic.actions.setAlertFormValues({ ...makeFormDefaults(), checks: undefined })
@@ -191,6 +194,24 @@ describe('alertFormLogic', () => {
}
)
+ it.each([
+ ['legacy', 'legacy' as const, '', {}],
+ ['redesigned', 'redesigned' as const, 'Weekly signups alert', { upper: 1 }],
+ ])('keeps %s creation defaults scoped to its UI', (_name, uiVersion, expectedName, expectedBounds) => {
+ const logic = alertFormLogic({
+ alert: null,
+ insightId: 42,
+ onEditSuccess: jest.fn(),
+ insightVizDataLogicProps: insightLogicProps,
+ insightName: 'Weekly signups',
+ uiVersion,
+ })
+ logic.mount()
+
+ expect(logic.values.alertForm.name).toBe(expectedName)
+ expect(logic.values.alertForm.threshold.configuration.bounds).toEqual(expectedBounds)
+ })
+
it('shows success toast and no error toast when create succeeds', async () => {
const logic = mountForm()
@@ -206,6 +227,9 @@ describe('alertFormLogic', () => {
action: expect.any(Function),
},
})
+ expect(captureSpy).toHaveBeenCalledWith('alert creation completed', {
+ ui_version: 'redesigned',
+ })
const toastOptions = successToastSpy.mock.calls[0][1] as { button: { action: () => void } }
toastOptions.button.action()
diff --git a/products/alerts/frontend/logic/alertFormLogic.ts b/products/alerts/frontend/logic/alertFormLogic.ts
index 9ea07c63053b..c1568506df55 100644
--- a/products/alerts/frontend/logic/alertFormLogic.ts
+++ b/products/alerts/frontend/logic/alertFormLogic.ts
@@ -154,6 +154,7 @@ export interface AlertFormLogicProps {
/** For funnel insights: whether it's a trends (historical) funnel, which alerts on the overall
* conversion rate over time rather than a single step snapshot. Drives the preview shape. */
insightIsTrendsFunnel?: boolean
+ uiVersion?: 'legacy' | 'redesigned'
}
const defaultConfigForInsight = (kind: AlertFormLogicProps['insightAlertKind']): AlertConfig => {
@@ -243,12 +244,18 @@ function defaultAlertName(props: AlertFormLogicProps, goalLines?: GoalLine[] | n
if (props.defaultToAnomalyDetection) {
return props.insightName ? `Anomaly in ${props.insightName}` : 'Anomaly alert'
}
+ if (props.uiVersion === 'redesigned' && props.insightName) {
+ return `${props.insightName} alert`
+ }
return goalLines && goalLines.length > 0 ? `Crossed ${goalLines[0].label}` : ''
}
-const getThresholdBounds = (goalLines?: GoalLine[] | null): InsightsThresholdBounds => {
+const getThresholdBounds = (
+ goalLines?: GoalLine[] | null,
+ uiVersion: AlertFormLogicProps['uiVersion'] = 'legacy'
+): InsightsThresholdBounds => {
if (goalLines == null || goalLines.length == 0) {
- return {}
+ return uiVersion === 'redesigned' ? { upper: 1 } : {}
}
// Simple assumption that the alert should be triggered when the first/smallest goal line is crossed
@@ -530,7 +537,7 @@ export const alertFormLogic = kea<alertFormLogicType>([
threshold: {
configuration: {
type: InsightThresholdType.ABSOLUTE,
- bounds: getThresholdBounds(values.goalLines),
+ bounds: getThresholdBounds(values.goalLines, props.uiVersion),
},
},
condition: {
@@ -647,6 +654,12 @@ export const alertFormLogic = kea<alertFormLogicType>([
throw error
}
+ if (isNewAlert) {
+ posthog.capture('alert creation completed', {
+ ui_version: props.uiVersion ?? 'legacy',
+ })
+ }
+
// The alert is already persisted — any error from the local side-effects below is a
// client-side bug, not a save failure. Capture it for investigation but don't surface it
// as "Error saving alert" since the API returned 2xx. Regression guarded by `alertFormLogic.test.ts`.
@@ -877,7 +890,6 @@ export const alertFormLogic = kea<alertFormLogicType>([
parent.actions.upsertAlert(updatedAlert)
parent.actions.loadAlerts()
}
- props.onEditSuccess(values.alertForm.id)
},
submitAlertForm: () => {
actions.setAlertFormSubmitAttempted()
diff --git a/products/alerts/frontend/logic/alertFormSchema.test.ts b/products/alerts/frontend/logic/alertFormSchema.test.ts
index 6a653559ae1e..4b5892da6a45 100644
--- a/products/alerts/frontend/logic/alertFormSchema.test.ts
+++ b/products/alerts/frontend/logic/alertFormSchema.test.ts
@@ -62,6 +62,35 @@ describe('alertFormSchema', () => {
).toBe(false)
})
+ it('requires the lower threshold to be below the upper threshold', () => {
+ const errors = getAlertFormValidationErrors({
+ ...baseAlert,
+ threshold: {
+ configuration: {
+ type: InsightThresholdType.ABSOLUTE,
+ bounds: { lower: 5, upper: 1 },
+ },
+ },
+ })
+
+ expect(errors.threshold).toBe('The “Less than” value must be lower than the “More than” value')
+ })
+
+ it('rejects negative thresholds for relative conditions', () => {
+ const errors = getAlertFormValidationErrors({
+ ...baseAlert,
+ condition: { type: AlertConditionType.RELATIVE_DECREASE },
+ threshold: {
+ configuration: {
+ type: InsightThresholdType.ABSOLUTE,
+ bounds: { upper: -1 },
+ },
+ },
+ })
+
+ expect(errors.threshold).toBe('Enter zero or a positive change value')
+ })
+
it('treats cleared threshold inputs as missing bounds', () => {
expect(
thresholdAlertHasBounds({
diff --git a/products/alerts/frontend/logic/alertFormSchema.ts b/products/alerts/frontend/logic/alertFormSchema.ts
index a709347f469d..48291b0e6faf 100644
--- a/products/alerts/frontend/logic/alertFormSchema.ts
+++ b/products/alerts/frontend/logic/alertFormSchema.ts
@@ -1,6 +1,8 @@
import type { DeepPartialMap, ValidationErrorType } from 'kea-forms'
import { z } from 'zod'
+import { AlertConditionType } from '~/queries/schema/schema-general'
+
import type { AlertType } from '../types'
import type { AlertFormType } from './alertFormLogic'
import { quietHoursFormError } from './scheduleRestrictionValidation'
@@ -9,11 +11,8 @@ export const THRESHOLD_BOUNDS_FORM_ERROR = 'Enter at least one threshold (less t
const NAME_REQUIRED_MESSAGE = 'You need to give your alert a name'
-function isFiniteThresholdBound(value: number | string | null | undefined): boolean {
- if (value == null || value === '') {
- return false
- }
- return !Number.isNaN(Number(value))
+function isFiniteThresholdBound(value: number | null | undefined): value is number {
+ return value != null && Number.isFinite(value)
}
export function thresholdAlertHasBounds(alert: AlertFormType | AlertType): boolean {
@@ -32,14 +31,15 @@ const alertFormSchema = z
.object({
name: z.string(),
detector_config: z.unknown().nullable(),
+ condition: z.object({ type: z.nativeEnum(AlertConditionType) }),
threshold: z
.object({
configuration: z
.object({
bounds: z
.object({
- lower: z.union([z.number(), z.string()]).nullish(),
- upper: z.union([z.number(), z.string()]).nullish(),
+ lower: z.number().finite().nullish(),
+ upper: z.number().finite().nullish(),
})
.optional(),
})
@@ -70,6 +70,31 @@ const alertFormSchema = z
message: THRESHOLD_BOUNDS_FORM_ERROR,
})
}
+
+ const bounds = alert.threshold?.configuration?.bounds
+ if (
+ !alert.detector_config &&
+ isFiniteThresholdBound(bounds?.lower) &&
+ isFiniteThresholdBound(bounds?.upper) &&
+ bounds.lower > bounds.upper
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['threshold'],
+ message: 'The “Less than” value must be lower than the “More than” value',
+ })
+ }
+
+ const hasNegativeRelativeBound =
+ alert.condition.type !== AlertConditionType.ABSOLUTE_VALUE &&
+ [bounds?.lower, bounds?.upper].some((value) => isFiniteThresholdBound(value) && value < 0)
+ if (hasNegativeRelativeBound) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['threshold'],
+ message: 'Enter zero or a positive change value',
+ })
+ }
})
export function getAlertFormValidationErrors(alert: AlertFormType): DeepPartialMap<AlertFormType, ValidationErrorType> {
diff --git a/products/alerts/frontend/logic/thresholdPercent.test.ts b/products/alerts/frontend/logic/thresholdPercent.test.ts
index 536bda8a5afc..336e7b44d1fa 100644
--- a/products/alerts/frontend/logic/thresholdPercent.test.ts
+++ b/products/alerts/frontend/logic/thresholdPercent.test.ts
@@ -1,6 +1,11 @@
-import { InsightThresholdType } from '~/queries/schema/schema-general'
+import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
-import { fractionToPercentInput, rescaleFunnelBound } from './thresholdPercent'
+import {
+ fractionToPercentInput,
+ rescaleThresholdBound,
+ thresholdForConditionChange,
+ thresholdForUnitChange,
+} from './thresholdPercent'
describe('thresholdPercent', () => {
// Stored 0–1 fractions render as percentage inputs without float noise — guards the ×100
@@ -22,13 +27,49 @@ describe('thresholdPercent', () => {
[0.99, InsightThresholdType.ABSOLUTE, 99],
[7, InsightThresholdType.PERCENTAGE, 0.07],
[undefined, InsightThresholdType.PERCENTAGE, undefined],
- ])('rescaleFunnelBound(%p, %s) === %p', (value, toType, expected) => {
- expect(rescaleFunnelBound(value as number | undefined, toType)).toBe(expected)
+ ])('rescaleThresholdBound(%p, %s) === %p', (value, toType, expected) => {
+ expect(rescaleThresholdBound(value as number | undefined, toType)).toBe(expected)
})
it('preserves the displayed number across a unit switch instead of ×100-ing it', () => {
// Entered as "99%" under a has-value (ABSOLUTE) condition, then switched to relative.
- const asFraction = rescaleFunnelBound(99, InsightThresholdType.PERCENTAGE)
+ const asFraction = rescaleThresholdBound(99, InsightThresholdType.PERCENTAGE)
expect(fractionToPercentInput(asFraction)).toBe(99) // was 9900 before the fix
})
+
+ it.each([
+ [
+ InsightThresholdType.PERCENTAGE,
+ { lower: 0.1, upper: 0.25 },
+ InsightThresholdType.ABSOLUTE,
+ { lower: 10, upper: 25 },
+ ],
+ [
+ InsightThresholdType.ABSOLUTE,
+ { lower: 10, upper: 25 },
+ InsightThresholdType.PERCENTAGE,
+ { lower: 0.1, upper: 0.25 },
+ ],
+ ])('preserves displayed bounds when switching from %s to %s', (fromType, bounds, toType, expectedBounds) => {
+ expect(thresholdForUnitChange({ type: fromType, bounds }, toType)).toEqual({
+ type: toType,
+ bounds: expectedBounds,
+ })
+ })
+
+ it('preserves displayed percentage values when switching to an absolute condition', () => {
+ expect(
+ thresholdForConditionChange(
+ {
+ type: InsightThresholdType.PERCENTAGE,
+ bounds: { lower: 0.2, upper: 3 },
+ },
+ AlertConditionType.ABSOLUTE_VALUE,
+ false
+ )
+ ).toEqual({
+ type: InsightThresholdType.ABSOLUTE,
+ bounds: { lower: 20, upper: 300 },
+ })
+ })
})
diff --git a/products/alerts/frontend/logic/thresholdPercent.ts b/products/alerts/frontend/logic/thresholdPercent.ts
index 23f8b6534283..cc89600a7292 100644
--- a/products/alerts/frontend/logic/thresholdPercent.ts
+++ b/products/alerts/frontend/logic/thresholdPercent.ts
@@ -1,4 +1,4 @@
-import { InsightThresholdType } from '~/queries/schema/schema-general'
+import { AlertConditionType, InsightThreshold, InsightThresholdType } from '~/queries/schema/schema-general'
// PERCENTAGE thresholds are stored as a 0–1 fraction and shown ×100; ABSOLUTE ones store the raw
// percent. These helpers keep the on-screen number stable across that boundary and round the
@@ -10,12 +10,53 @@ const roundPercent = (value: number): number => Math.round(value * 1e6) / 1e6
export const fractionToPercentInput = (fraction: number | undefined): number | undefined =>
typeof fraction === 'number' ? roundPercent(fraction * 100) : undefined
-/** Convert a bound between the relative (0–1 fraction, PERCENTAGE) and absolute (raw percent) units so
- * the displayed number is preserved when a funnel's condition flips the threshold type — rather than
- * jumping ×100 / ÷100. */
-export const rescaleFunnelBound = (value: number | undefined, toType: InsightThresholdType): number | undefined => {
+export const inputToStoredBound = (value: number | undefined, type: InsightThresholdType): number | undefined => {
+ if (value === undefined) {
+ return undefined
+ }
+ return type === InsightThresholdType.PERCENTAGE ? value / 100 : value
+}
+
+/** Convert a bound between the relative (0–1 fraction, PERCENTAGE) and absolute (raw) units. */
+export const rescaleThresholdBound = (value: number | undefined, toType: InsightThresholdType): number | undefined => {
if (typeof value !== 'number') {
return undefined
}
return toType === InsightThresholdType.PERCENTAGE ? roundPercent(value / 100) : roundPercent(value * 100)
}
+
+export function thresholdForUnitChange(
+ configuration: InsightThreshold,
+ targetType: InsightThresholdType
+): InsightThreshold {
+ if (configuration.type === targetType) {
+ return configuration
+ }
+
+ return {
+ type: targetType,
+ bounds: {
+ lower: rescaleThresholdBound(configuration.bounds?.lower, targetType),
+ upper: rescaleThresholdBound(configuration.bounds?.upper, targetType),
+ },
+ }
+}
+
+export function thresholdForConditionChange(
+ configuration: InsightThreshold,
+ conditionType: AlertConditionType,
+ forcePercentageForRelative: boolean
+): InsightThreshold {
+ let targetType = configuration.type
+ if (conditionType === AlertConditionType.ABSOLUTE_VALUE) {
+ targetType = InsightThresholdType.ABSOLUTE
+ } else if (forcePercentageForRelative) {
+ targetType = InsightThresholdType.PERCENTAGE
+ }
+
+ if (configuration.type === targetType) {
+ return configuration
+ }
+
+ return thresholdForUnitChange(configuration, targetType)
+}
diff --git a/products/alerts/frontend/logic/trendsAlertPreview.test.ts b/products/alerts/frontend/logic/trendsAlertPreview.test.ts
new file mode 100644
index 000000000000..96dd7f658e69
--- /dev/null
+++ b/products/alerts/frontend/logic/trendsAlertPreview.test.ts
@@ -0,0 +1,37 @@
+import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
+
+import { deriveAlertCheckPreviewSeries, deriveTrendsAlertPreviewSeries } from './trendsAlertPreview'
+
+describe('deriveTrendsAlertPreviewSeries', () => {
+ it.each([
+ [AlertConditionType.RELATIVE_INCREASE, InsightThresholdType.ABSOLUTE, [10, 15, 12], [5, -3], ['b', 'c']],
+ [AlertConditionType.RELATIVE_DECREASE, InsightThresholdType.ABSOLUTE, [10, 15, 12], [-5, 3], ['b', 'c']],
+ [AlertConditionType.RELATIVE_INCREASE, InsightThresholdType.PERCENTAGE, [100, 125, 100], [25, -20], ['b', 'c']],
+ [AlertConditionType.RELATIVE_DECREASE, InsightThresholdType.PERCENTAGE, [100, 125, 100], [-25, 20], ['b', 'c']],
+ [AlertConditionType.RELATIVE_INCREASE, InsightThresholdType.PERCENTAGE, [0, 1, 2], [100], ['c']],
+ ])('mirrors backend %s evaluation with %s thresholds', (conditionType, thresholdType, values, expected, labels) => {
+ expect(deriveTrendsAlertPreviewSeries(values, ['a', 'b', 'c'], conditionType, thresholdType)).toEqual({
+ values: expected,
+ labels,
+ relative: true,
+ })
+ })
+
+ it('builds a chronological percentage preview from completed alert checks', () => {
+ expect(
+ deriveAlertCheckPreviewSeries(
+ [
+ { created_at: '2026-07-21T12:00:00Z', calculated_value: 0.25 },
+ { created_at: '2026-07-21T10:00:00Z', calculated_value: null },
+ { created_at: '2026-07-21T11:00:00Z', calculated_value: 0.1 },
+ ],
+ AlertConditionType.RELATIVE_INCREASE,
+ InsightThresholdType.PERCENTAGE
+ )
+ ).toEqual({
+ values: [10, 25],
+ labels: ['2026-07-21T11:00:00Z', '2026-07-21T12:00:00Z'],
+ relative: true,
+ })
+ })
+})
diff --git a/products/alerts/frontend/logic/trendsAlertPreview.ts b/products/alerts/frontend/logic/trendsAlertPreview.ts
new file mode 100644
index 000000000000..b1860918fd23
--- /dev/null
+++ b/products/alerts/frontend/logic/trendsAlertPreview.ts
@@ -0,0 +1,66 @@
+import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
+
+export interface TrendsAlertPreviewSeries {
+ values: number[]
+ labels?: string[]
+ relative: boolean
+}
+
+interface AlertCheckPreviewInput {
+ calculated_value: number | null
+ created_at: string
+}
+
+export function deriveAlertCheckPreviewSeries(
+ checks: AlertCheckPreviewInput[],
+ conditionType: AlertConditionType,
+ thresholdType: InsightThresholdType
+): TrendsAlertPreviewSeries {
+ const percentageChange =
+ conditionType !== AlertConditionType.ABSOLUTE_VALUE && thresholdType === InsightThresholdType.PERCENTAGE
+ const points = checks
+ .filter(
+ (check): check is AlertCheckPreviewInput & { calculated_value: number } =>
+ check.calculated_value != null && Number.isFinite(check.calculated_value)
+ )
+ .sort((a, b) => a.created_at.localeCompare(b.created_at))
+
+ return {
+ values: points.map((check) => (percentageChange ? check.calculated_value * 100 : check.calculated_value)),
+ labels: points.map((check) => check.created_at),
+ relative: conditionType !== AlertConditionType.ABSOLUTE_VALUE,
+ }
+}
+
+export function deriveTrendsAlertPreviewSeries(
+ values: number[],
+ labels: string[] | undefined,
+ conditionType: AlertConditionType,
+ thresholdType: InsightThresholdType
+): TrendsAlertPreviewSeries {
+ if (conditionType === AlertConditionType.ABSOLUTE_VALUE) {
+ return { values, labels, relative: false }
+ }
+
+ const derivedPoints = values.slice(1).map((current, index) => {
+ const previous = values[index]
+ const numerator =
+ conditionType === AlertConditionType.RELATIVE_INCREASE ? current - previous : previous - current
+ if (thresholdType === InsightThresholdType.ABSOLUTE) {
+ return { value: numerator, index }
+ }
+ if (previous === 0) {
+ return { value: current === 0 ? 0 : null, index }
+ }
+ return { value: (numerator / previous) * 100, index }
+ })
+ const availablePoints = derivedPoints.filter(
+ (point): point is { value: number; index: number } => point.value !== null
+ )
+
+ return {
+ values: availablePoints.map((point) => point.value),
+ labels: labels ? availablePoints.map((point) => labels[point.index + 1]) : undefined,
+ relative: true,
+ }
+}
diff --git a/products/alerts/frontend/views/AlertHistoryChart.stories.tsx b/products/alerts/frontend/views/AlertHistoryChart.stories.tsx
index 8b0615152f4f..8a55127a4353 100644
--- a/products/alerts/frontend/views/AlertHistoryChart.stories.tsx
+++ b/products/alerts/frontend/views/AlertHistoryChart.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react'
-import { dayjs, type Dayjs } from 'lib/dayjs'
+import { dayjs } from 'lib/dayjs'
import {
AlertCalculationInterval,
@@ -55,123 +55,6 @@ function makePoints(count: number, seed = 0): AlertHistoryChartPoint[] {
}))
}
-/** X-axis labels that match how checks land for daily / weekly / monthly evaluation. */
-function makePointsForEvaluationInterval(
- count: number,
- unit: 'day' | 'week' | 'month',
- labelFormat: string,
- seed = 0
-): AlertHistoryChartPoint[] {
- return Array.from({ length: count }, (_, i) => ({
- value: 45 + Math.sin((i + seed) / 2.5) * 22 + (i % 5) * 4 + (i === Math.floor(count / 2) ? 35 : 0),
- label: dayjs()
- .subtract(count - 1 - i, unit)
- .format(labelFormat),
- }))
-}
-
-function minutesSinceMidnight(t: Dayjs): number {
- return t.hour() * 60 + t.minute()
-}
-
-function parseHHMMToMinutes(s: string): number {
- const [h, m] = s.split(':').map(Number)
- return h * 60 + m
-}
-
-/** Half-open [start, end) in project local time; supports overnight (e.g. 22:00–07:00). */
-function isInBlockedQuietWindow(t: Dayjs, start: string, end: string): boolean {
- const now = minutesSinceMidnight(t)
- const s = parseHHMMToMinutes(start)
- const e = parseHHMMToMinutes(end)
- if (s < e) {
- return now >= s && now < e
- }
- if (s > e) {
- return now >= s || now < e
- }
- return false
-}
-
-function synthValue(i: number, count: number, seed: number): number {
- return 45 + Math.sin((i + seed) / 2.5) * 22 + (i % 5) * 4 + (i === Math.floor(count / 2) ? 35 : 0)
-}
-
-/** Hourly checks only on weekdays (no Sat/Sun), newest on the right. */
-function makeHourlyPointsSkippingWeekends(pointCount: number, seed = 0): AlertHistoryChartPoint[] {
- const rev: { label: string }[] = []
- let t = dayjs().startOf('hour')
- while (rev.length < pointCount) {
- const dow = t.day()
- if (dow !== 0 && dow !== 6) {
- rev.push({ label: t.format('MMM D, HH:mm') })
- }
- t = t.subtract(1, 'hour')
- }
- return rev.reverse().map((p, i) => ({
- label: p.label,
- value: synthValue(i, pointCount, seed),
- }))
-}
-
-/** One check per weekday only (daily + skip weekends). */
-function makeDailyPointsSkippingWeekends(dayCount: number, seed = 0): AlertHistoryChartPoint[] {
- const rev: { label: string }[] = []
- let t = dayjs().startOf('day')
- while (rev.length < dayCount) {
- const dow = t.day()
- if (dow !== 0 && dow !== 6) {
- rev.push({ label: t.format('ddd, MMM D') })
- }
- t = t.subtract(1, 'day')
- }
- return rev.reverse().map((p, i) => ({
- label: p.label,
- value: synthValue(i, dayCount, seed),
- }))
-}
-
-/** Hourly checks outside quiet hours (e.g. overnight block defers runs → uneven spacing on the axis). */
-function makeHourlyPointsOutsideQuietHours(
- pointCount: number,
- blocked: { start: string; end: string },
- seed = 0
-): AlertHistoryChartPoint[] {
- const rev: { label: string }[] = []
- let t = dayjs().startOf('hour')
- while (rev.length < pointCount) {
- if (!isInBlockedQuietWindow(t, blocked.start, blocked.end)) {
- rev.push({ label: t.format('MMM D, HH:mm') })
- }
- t = t.subtract(1, 'hour')
- }
- return rev.reverse().map((p, i) => ({
- label: p.label,
- value: synthValue(i, pointCount, seed),
- }))
-}
-
-/** Hourly checks on weekdays only and outside quiet hours. */
-function makeHourlyPointsWeekdaysOutsideQuietHours(
- pointCount: number,
- blocked: { start: string; end: string },
- seed = 0
-): AlertHistoryChartPoint[] {
- const rev: { label: string }[] = []
- let t = dayjs().startOf('hour')
- while (rev.length < pointCount) {
- const dow = t.day()
- if (dow !== 0 && dow !== 6 && !isInBlockedQuietWindow(t, blocked.start, blocked.end)) {
- rev.push({ label: t.format('MMM D, HH:mm') })
- }
- t = t.subtract(1, 'hour')
- }
- return rev.reverse().map((p, i) => ({
- label: p.label,
- value: synthValue(i, pointCount, seed),
- }))
-}
-
/**
* Stamp each point with `firedAtTime` derived from the thresholds that were in effect at evaluation time.
* Use this for stories that demonstrate the real historical-firing signal (red dots), independent of
@@ -227,139 +110,13 @@ export const Default: Story = {
}
/** Caption when total checks exceed the chart window (see `historyLimit`). */
-export const MoreChecksThanChartWindow: Story = {
+export const TruncatedHistory: Story = {
args: {
...Default.args,
checksTotal: 240,
},
}
-/** One check per calendar day (daily evaluation). */
-export const DailyEvaluationTimeAxis: Story = {
- args: {
- ...Default.args,
- points: makePointsForEvaluationInterval(14, 'day', 'ddd, MMM D'),
- alert: buildStoryAlert({
- calculation_interval: AlertCalculationInterval.DAILY,
- threshold: {
- configuration: {
- type: InsightThresholdType.ABSOLUTE,
- bounds: { lower: 40, upper: 85 },
- },
- },
- }),
- },
-}
-
-/** One check per week (weekly evaluation). */
-export const WeeklyEvaluationTimeAxis: Story = {
- args: {
- ...Default.args,
- points: makePointsForEvaluationInterval(10, 'week', '[Week of] MMM D'),
- alert: buildStoryAlert({
- calculation_interval: AlertCalculationInterval.WEEKLY,
- threshold: {
- configuration: {
- type: InsightThresholdType.ABSOLUTE,
- bounds: { lower: 40, upper: 85 },
- },
- },
- }),
- },
-}
-
-/** One check per month (monthly evaluation). */
-export const MonthlyEvaluationTimeAxis: Story = {
- args: {
- ...Default.args,
- points: makePointsForEvaluationInterval(8, 'month', 'MMM YYYY'),
- alert: buildStoryAlert({
- calculation_interval: AlertCalculationInterval.MONTHLY,
- threshold: {
- configuration: {
- type: InsightThresholdType.ABSOLUTE,
- bounds: { lower: 40, upper: 85 },
- },
- },
- }),
- },
-}
-
-const DEFAULT_QUIET_HOURS = { start: '22:00', end: '07:00' }
-
-/** Hourly checks only land on weekdays when `skip_weekend` is set (gaps across Sat/Sun). */
-export const SkipWeekendsHourly: Story = {
- args: {
- ...Default.args,
- points: makeHourlyPointsSkippingWeekends(28, 1),
- alert: buildStoryAlert({
- calculation_interval: AlertCalculationInterval.HOURLY,
- skip_weekend: true,
- threshold: {
- configuration: {
- type: InsightThresholdType.ABSOLUTE,
- bounds: { lower: 40, upper: 85 },
- },
- },
- }),
- },
-}
-
-/** Daily checks only on weekdays (skip weekend). */
-export const SkipWeekendsDaily: Story = {
- args: {
- ...Default.args,
- points: makeDailyPointsSkippingWeekends(14, 2),
- alert: buildStoryAlert({
- calculation_interval: AlertCalculationInterval.DAILY,
- skip_weekend: true,
- threshold: {
- configuration: {
- type: InsightThresholdType.ABSOLUTE,
- bounds: { lower: 40, upper: 85 },
- },
- },
- }),
- },
-}
-
-/** Quiet hours defer checks — hourly timeline has uneven gaps (e.g. nothing overnight). */
-export const QuietHoursHourly: Story = {
- args: {
- ...Default.args,
- points: makeHourlyPointsOutsideQuietHours(32, DEFAULT_QUIET_HOURS, 3),
- alert: buildStoryAlert({
- calculation_interval: AlertCalculationInterval.HOURLY,
- schedule_restriction: { blocked_windows: [DEFAULT_QUIET_HOURS] },
- threshold: {
- configuration: {
- type: InsightThresholdType.ABSOLUTE,
- bounds: { lower: 40, upper: 85 },
- },
- },
- }),
- },
-}
-
-/** Both skip weekend and quiet hours (hourly). */
-export const SkipWeekendsAndQuietHoursHourly: Story = {
- args: {
- ...Default.args,
- points: makeHourlyPointsWeekdaysOutsideQuietHours(36, DEFAULT_QUIET_HOURS, 4),
- alert: buildStoryAlert({
- calculation_interval: AlertCalculationInterval.HOURLY,
- skip_weekend: true,
- schedule_restriction: { blocked_windows: [DEFAULT_QUIET_HOURS] },
- threshold: {
- configuration: {
- type: InsightThresholdType.ABSOLUTE,
- bounds: { lower: 40, upper: 85 },
- },
- },
- }),
- },
-}
-
export const PercentageThresholds: Story = {
args: {
points: makePoints(18, 2).map((p) => ({ ...p, value: (p.value - 40) / 100 })),
@@ -401,7 +158,7 @@ export const AnomalyProbabilityCutoff: Story = {
* Red dots below the lower line fired at the time but wouldn't under current config (widened).
* Orange dots between old and new upper bound would now fire but didn't then (tightened).
*/
-export const MixedThresholdChange: Story = {
+export const ThresholdChanged: Story = {
args: {
...Default.args,
points: withHistoricalFirings(makePoints(30, 11), { lower: 38, upper: 80 }),
diff --git a/products/alerts/frontend/views/AlertHistorySection.tsx b/products/alerts/frontend/views/AlertHistorySection.tsx
index 11d0eef6b98b..b93d59145315 100644
--- a/products/alerts/frontend/views/AlertHistorySection.tsx
+++ b/products/alerts/frontend/views/AlertHistorySection.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
-import { IconNotebook } from '@posthog/icons'
+import { IconGraph, IconNotebook } from '@posthog/icons'
import {
LemonSegmentedButton,
LemonSkeleton,
@@ -21,8 +21,8 @@ import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { formatDate } from 'lib/utils/datetime'
import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { AlertStateIndicator } from 'products/alerts/frontend/components/AlertDefinition'
import { AlertHistoryChart } from 'products/alerts/frontend/views/AlertHistoryChart'
-import { AlertStateIndicator } from 'products/alerts/frontend/views/ManageAlertsModal'
import { alertLogic, CHART_CHECKS_LIMIT, TABLE_CHECKS_PAGE_SIZE } from '../logic/alertLogic'
import { isAnyRowHogQLConfig } from '../types'
@@ -123,7 +123,13 @@ export function AlertHistorySectionSkeleton(): JSX.Element {
}
/** Check history in the alert modal: status, empty state, chart/table toggle, and paginated table. */
-export function AlertHistorySection({ alertId }: { alertId: AlertType['id'] }): JSX.Element | null {
+export function AlertHistorySection({
+ alertId,
+ showCurrentStatus = true,
+}: {
+ alertId: AlertType['id']
+ showCurrentStatus?: boolean
+}): JSX.Element | null {
const logic = alertLogic({ alertId })
const {
alert,
@@ -217,14 +223,19 @@ export function AlertHistorySection({ alertId }: { alertId: AlertType['id'] }):
const checksTotal = alert.checks_total
return (
- <div className="mt-10 space-y-2">
- <div className="flex flex-row gap-2 items-center">
- <h3 className="m-0">Current status: </h3>
- <AlertStateIndicator alert={alert} />
- <h3 className="m-0">
- {alert.snoozed_until && ` until ${formatDate(dayjs(alert?.snoozed_until), 'MMM D, HH:mm')}`}
- </h3>
- </div>
+ <div className="space-y-2">
+ {showCurrentStatus ? (
+ <div className="flex flex-row gap-2 items-center">
+ <h3 className="m-0 flex items-center gap-1.5">
+ <IconGraph className="size-4 text-muted" />
+ Current status:{' '}
+ </h3>
+ <AlertStateIndicator alert={alert} />
+ <h3 className="m-0">
+ {alert.snoozed_until && ` until ${formatDate(dayjs(alert?.snoozed_until), 'MMM D, HH:mm')}`}
+ </h3>
+ </div>
+ ) : null}
{!alertHistoryHasHistory ? (
<div
className="flex min-h-56 items-center justify-center bg-bg-surface-primary border border-primary rounded"
diff --git a/products/alerts/frontend/views/AlertModal.stories.tsx b/products/alerts/frontend/views/AlertModal.stories.tsx
new file mode 100644
index 000000000000..978bc17d4275
--- /dev/null
+++ b/products/alerts/frontend/views/AlertModal.stories.tsx
@@ -0,0 +1,311 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { BindLogic } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { mswDecorator } from '~/mocks/browser'
+import { EMPTY_PAGINATED_RESPONSE } from '~/mocks/handlers'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'
+import {
+ AlertCalculationInterval,
+ AlertConditionType,
+ AlertState,
+ InsightThresholdType,
+ NodeKind,
+} from '~/queries/schema/schema-general'
+import { isInsightVizNode } from '~/queries/utils'
+
+import type { AlertCheck, AlertType } from '../types'
+import { EditAlertModal } from './EditAlertModal'
+
+const createdBy = {
+ id: 1,
+ uuid: '018f59f3-4f2f-7c89-b389-73b99b91f442',
+ distinct_id: 'storybook-user',
+ first_name: 'Hedge Hog',
+ email: '[email protected]',
+ hedgehog_config: null,
+}
+
+function makeChecks(values: number[]): AlertCheck[] {
+ return values.map((calculatedValue, index) => ({
+ id: `check-${index}`,
+ created_at: `2026-07-16T${String(12 + index).padStart(2, '0')}:00:00Z`,
+ calculated_value: calculatedValue,
+ state: AlertState.NOT_FIRING,
+ targets_notified: false,
+ }))
+}
+
+const makeAlert = (overrides: Partial<AlertType>): AlertType =>
+ ({
+ id: 'alert-trends',
+ name: 'Large file uploads',
+ enabled: true,
+ state: AlertState.NOT_FIRING,
+ calculation_interval: AlertCalculationInterval.HOURLY,
+ last_checked_at: '2026-07-16T16:45:00Z',
+ last_notified_at: '2026-07-14T13:30:00Z',
+ created_at: '2026-06-01T09:00:00Z',
+ created_by: createdBy,
+ subscribed_users: [createdBy],
+ checks: makeChecks([4200000, 5100000, 4800000, 6700000, 7200000, 6100000, 8300000, 9400000]),
+ config: {
+ type: 'TrendsAlertConfig',
+ series_index: 0,
+ check_ongoing_interval: false,
+ },
+ threshold: {
+ configuration: {
+ type: InsightThresholdType.ABSOLUTE,
+ bounds: { lower: 1, upper: 10000000 },
+ },
+ },
+ condition: { type: AlertConditionType.ABSOLUTE_VALUE },
+ insight: {
+ id: 104,
+ short_id: 'large-file-uploads',
+ name: 'Large file uploads',
+ derived_name: 'Large file uploads',
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: 'file uploaded',
+ math: 'avg',
+ math_property: 'file_size_b',
+ },
+ ],
+ },
+ },
+ },
+ ...overrides,
+ }) as AlertType
+
+const trendsAlert = makeAlert({})
+
+const funnelAlert = makeAlert({
+ id: 'alert-funnel',
+ name: 'Checkout conversion below 40%',
+ checks: makeChecks([0.52, 0.49, 0.47, 0.44, 0.42, 0.39, 0.37, 0.35]),
+ config: {
+ type: 'FunnelsAlertConfig',
+ funnel_step: 1,
+ metric: 'conversion_from_start',
+ check_ongoing_interval: false,
+ },
+ insight: {
+ id: 105,
+ short_id: 'checkout-funnel',
+ name: 'Checkout funnel',
+ derived_name: 'Checkout funnel',
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.FunnelsQuery,
+ series: [
+ { kind: NodeKind.EventsNode, event: 'checkout started', name: 'Checkout started' },
+ { kind: NodeKind.EventsNode, event: 'order completed', name: 'Order completed' },
+ ],
+ },
+ },
+ } as unknown as AlertType['insight'],
+ threshold: {
+ configuration: {
+ type: InsightThresholdType.PERCENTAGE,
+ bounds: { lower: 0.4 },
+ },
+ },
+})
+
+const hogQLAlert = makeAlert({
+ id: 'alert-hogql',
+ name: 'Queue depth above 1,000',
+ checks: makeChecks([720, 810, 760, 880, 920, 1050, 980, 1200]),
+ config: {
+ type: 'HogQLAlertConfig',
+ column: 'queue_depth',
+ evaluation: 'last_row',
+ label_column: 'recorded_at',
+ },
+ insight: {
+ id: 106,
+ short_id: 'queue-depth',
+ name: 'Queue depth',
+ derived_name: 'Queue depth',
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: 'SELECT recorded_at, queue_depth FROM queue_metrics ORDER BY recorded_at',
+ },
+ },
+ } as unknown as AlertType['insight'],
+ threshold: {
+ configuration: {
+ type: InsightThresholdType.ABSOLUTE,
+ bounds: { upper: 1000 },
+ },
+ },
+})
+
+const meta: Meta<typeof EditAlertModal> = {
+ component: EditAlertModal,
+ title: 'Products/Alerts/Alert modal',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2026-07-16',
+ featureFlags: [FEATURE_FLAGS.ALERTS_REDESIGNED_EDIT_MODAL, FEATURE_FLAGS.ALERTS_INLINE_NOTIFICATIONS],
+ testOptions: { viewport: { width: 1300, height: 900 } },
+ },
+}
+
+export default meta
+
+type StoryInsightType = 'trends' | 'funnel' | 'hogql'
+
+interface AlertTypeStoryProps {
+ insightType: StoryInsightType
+}
+
+const storyAlerts: Record<StoryInsightType, AlertType> = {
+ trends: trendsAlert,
+ funnel: funnelAlert,
+ hogql: hogQLAlert,
+}
+
+const alertsById = Object.fromEntries(Object.values(storyAlerts).map((alert) => [alert.id, alert]))
+
+function EditAlertStory({ insightType }: AlertTypeStoryProps): JSX.Element {
+ const alert = storyAlerts[insightType]
+ return (
+ <EditAlertModal
+ isOpen
+ alertId={alert.id}
+ insightId={alert.insight.id}
+ insightShortId={alert.insight.short_id}
+ insightLogicProps={{
+ dashboardItemId: alert.insight.short_id,
+ cachedInsight: alert.insight,
+ }}
+ onEditSuccess={() => {}}
+ onClose={() => {}}
+ useAlertCheckPreview
+ />
+ )
+}
+
+type EditAlertVariant = StoryObj<AlertTypeStoryProps>
+
+export const EditAlert: EditAlertVariant = {
+ args: { insightType: 'trends' },
+ argTypes: {
+ insightType: {
+ control: 'select',
+ options: ['trends', 'funnel', 'hogql'],
+ },
+ },
+ render: ({ insightType }) => <EditAlertStory insightType={insightType} />,
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/alerts/:alert_id/': (request) => [
+ 200,
+ alertsById[request.params.alert_id as string],
+ ],
+ '/api/projects/:team_id/hog_functions/': EMPTY_PAGINATED_RESPONSE,
+ },
+ }),
+ ],
+}
+
+interface CreateWizardStoryProps {
+ insightType: StoryInsightType
+}
+
+const wizardCachedResults: Record<StoryInsightType, Record<string, unknown>> = {
+ trends: {
+ results: [
+ {
+ data: [4200000, 5100000, 4800000, 6700000, 7200000, 6100000, 8300000, 9400000],
+ labels: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00'],
+ },
+ ],
+ },
+ funnel: {
+ results: [
+ { name: 'Checkout started', count: 1000 },
+ { name: 'Order completed', count: 350 },
+ ],
+ },
+ hogql: {
+ results: [
+ ['2026-07-15 12:00:00', 850],
+ ['2026-07-16 12:00:00', 1200],
+ ],
+ columns: ['recorded_at', 'queue_depth'],
+ types: [
+ ['recorded_at', 'DateTime'],
+ ['queue_depth', 'UInt64'],
+ ],
+ },
+}
+
+function CreateWizardStory({ insightType }: CreateWizardStoryProps): JSX.Element {
+ const selectedAlert = storyAlerts[insightType]
+ const query = selectedAlert.insight.query
+ if (!isInsightVizNode(query)) {
+ throw new Error('Create wizard story requires an insight visualization query')
+ }
+ const insightLogicProps = {
+ dashboardItemId: selectedAlert.insight.short_id,
+ cachedInsight: selectedAlert.insight,
+ }
+
+ return (
+ <BindLogic
+ logic={dataNodeLogic}
+ props={{
+ key: insightVizDataNodeKey(insightLogicProps),
+ query: query.source,
+ cachedResults: wizardCachedResults[insightType],
+ doNotLoad: true,
+ }}
+ >
+ <EditAlertModal
+ isOpen
+ insightId={selectedAlert.insight.id}
+ insightShortId={selectedAlert.insight.short_id}
+ insightName={selectedAlert.insight.name}
+ insightLogicProps={insightLogicProps}
+ onEditSuccess={() => {}}
+ onClose={() => {}}
+ />
+ </BindLogic>
+ )
+}
+
+type CreateWizardVariant = StoryObj<CreateWizardStoryProps>
+
+export const CreateWizard: CreateWizardVariant = {
+ args: { insightType: 'trends' },
+ argTypes: {
+ insightType: {
+ control: 'select',
+ options: ['trends', 'funnel', 'hogql'],
+ },
+ },
+ render: ({ insightType }) => <CreateWizardStory insightType={insightType} />,
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/hog_functions/': EMPTY_PAGINATED_RESPONSE,
+ },
+ }),
+ ],
+}
diff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsx
index 5accebd79491..ec8bf2a4cdf4 100644
--- a/products/alerts/frontend/views/EditAlertModal.tsx
+++ b/products/alerts/frontend/views/EditAlertModal.tsx
@@ -2,12 +2,13 @@ import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { useCallback, useMemo } from 'react'
-import { SpinnerOverlay } from '@posthog/lemon-ui'
+import { LemonDialog, LemonSwitch } from '@posthog/lemon-ui'
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 { formatDate } from 'lib/utils/datetime'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
@@ -26,6 +27,7 @@ import { AlertDefinitionSection } from 'products/alerts/frontend/components/Aler
import {
AlertEditor,
AlertEditorFormDetails,
+ AlertEditorLoading,
AlertEditorSection,
} from 'products/alerts/frontend/components/AlertEditor'
import { AlertIntervalRow } from 'products/alerts/frontend/components/AlertIntervalRow'
@@ -41,20 +43,68 @@ import { insightAlertsLogic } from '../logic/insightAlertsLogic'
import { supportsAnomalyDetection, supportsOngoingInterval } from '../types'
import type { AlertType } from '../types'
import { AlertHistorySection } from './AlertHistorySection'
+import { EditAlertModalV2 } from './EditAlertModalV2'
-interface EditAlertModalProps {
+interface AlertModalCommonProps {
isOpen: boolean | undefined
- alertId?: AlertType['id']
- insightId: QueryBasedInsightModel['id']
- insightShortId: InsightShortId
onEditSuccess: (alertId?: AlertType['id'] | undefined) => void
onClose?: () => void
- insightLogicProps: InsightLogicProps
defaultToAnomalyDetection?: boolean
insightName?: string | null
+ useAlertCheckPreview?: boolean
}
-export function EditAlertModal({
+export type AlertModalProps = AlertModalCommonProps &
+ (
+ | {
+ alert: AlertType
+ alertId?: never
+ insightId?: never
+ insightShortId?: never
+ insightLogicProps?: never
+ }
+ | {
+ alert?: never
+ alertId?: AlertType['id']
+ insightId: QueryBasedInsightModel['id']
+ insightShortId: InsightShortId
+ insightLogicProps: InsightLogicProps
+ }
+ )
+
+export interface ResolvedAlertModalProps extends AlertModalCommonProps {
+ initialAlert?: AlertType
+ alertId?: AlertType['id']
+ insightId: QueryBasedInsightModel['id']
+ insightShortId: InsightShortId
+ insightLogicProps: InsightLogicProps
+}
+
+export function EditAlertModal(props: AlertModalProps): JSX.Element {
+ // Redesigned modal (wizard for new alerts, sectioned layout + live preview for edits). The flag
+ // is the single switch: off = legacy modal below, on = V2. Consumers don't change.
+ const redesigned = useFeatureFlag('ALERTS_REDESIGNED_EDIT_MODAL')
+ const resolvedProps: ResolvedAlertModalProps = props.alert
+ ? {
+ ...props,
+ initialAlert: props.alert,
+ alertId: props.alert.id,
+ insightId: props.alert.insight.id,
+ insightShortId: props.alert.insight.short_id,
+ insightLogicProps: {
+ dashboardItemId: props.alert.insight.short_id,
+ cachedInsight: props.alert.insight,
+ },
+ }
+ : props
+ if (redesigned) {
+ return <EditAlertModalV2 {...resolvedProps} />
+ }
+ return <LegacyEditAlertModal {...resolvedProps} />
+}
+
+function LegacyEditAlertModal({
+ initialAlert,
isOpen,
alertId,
insightId,
@@ -64,9 +114,10 @@ export function EditAlertModal({
insightLogicProps,
defaultToAnomalyDetection,
insightName,
-}: EditAlertModalProps): JSX.Element {
+}: ResolvedAlertModalProps): JSX.Element {
const _alertLogic = alertLogic({ alertId })
- const { alert, alertLoading } = useValues(_alertLogic)
+ const { alert: loadedAlert, alertLoading } = useValues(_alertLogic)
+ const alert = initialAlert ?? loadedAlert
/** Parent callback only (e.g. close modal). `alertLogic` is hydrated from the save response inside `alertFormLogic`. */
const _onEditSuccess = useCallback(
@@ -107,6 +158,7 @@ export function EditAlertModal({
defaultToAnomalyDetection: !alertId && !isNonTimeSeriesDisplay && defaultToAnomalyDetection,
insightName,
insightIsTrendsFunnel: isTrendsFunnel,
+ uiVersion: 'legacy' as const,
}
const formLogic = alertFormLogic(formLogicProps)
const {
@@ -221,14 +273,37 @@ export function EditAlertModal({
])
const leadingActions = (
- <div className="flex gap-2">
+ <div className="flex items-center gap-2">
{!creatingNewAlert ? (
- <LemonButton type="secondary" status="danger" onClick={deleteAlert}>
+ <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: deleteAlert,
+ 'data-attr': 'alert-delete-confirm',
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }}
+ >
Delete alert
</LemonButton>
) : null}
- {!creatingNewAlert && alert?.state === AlertState.FIRING ? (
- <SnoozeButton onChange={snoozeAlert} value={alert?.snoozed_until} />
+ {!creatingNewAlert ? (
+ <SnoozeButton
+ onChange={snoozeAlert}
+ value={alert?.snoozed_until}
+ disabledReason={
+ alert?.state === AlertState.FIRING ? undefined : 'Only firing alerts can be snoozed'
+ }
+ />
) : null}
{!creatingNewAlert && alert?.state === AlertState.SNOOZED ? (
<LemonButton
@@ -240,13 +315,18 @@ export function EditAlertModal({
Clear snooze
</LemonButton>
) : null}
+ <div className="ml-auto mr-2">
+ <LemonField name="enabled" className="m-0">
+ <LemonSwitch checked={alertForm.enabled} data-attr="alertForm-enabled" label="Enabled" />
+ </LemonField>
+ </div>
</div>
)
return (
<LemonModal onClose={handleClose} isOpen={isOpen} width={900} simple title="">
{alertLoading && !alert ? (
- <SpinnerOverlay />
+ <AlertEditorLoading title="Edit alert" onBack={handleClose} />
) : (
<Form
logic={alertFormLogic}
@@ -264,12 +344,12 @@ export function EditAlertModal({
isSubmitting={isAlertFormSubmitting}
hasChanges={alertFormChanged}
hasPendingChanges={hasPendingNotifications}
+ showNoChangesLabel
onSubmitAttempted={setAlertFormSubmitAttempted}
leadingActions={leadingActions}
>
<div className="deprecated-space-y-6">
<AlertEditorFormDetails
- enabled={{ checked: alertForm.enabled, dataAttr: 'alertForm-enabled' }}
activity={
alert?.created_by ? (
<UserActivityIndicator
@@ -347,7 +427,11 @@ export function EditAlertModal({
/>
</div>
- {alertId && alert ? <AlertHistorySection alertId={alert.id} /> : null}
+ {alertId && alert ? (
+ <div className="mt-6">
+ <AlertHistorySection alertId={alert.id} />
+ </div>
+ ) : null}
</AlertEditor>
</Form>
)}
diff --git a/products/alerts/frontend/views/EditAlertModalV2.tsx b/products/alerts/frontend/views/EditAlertModalV2.tsx
new file mode 100644
index 000000000000..b1991126e568
--- /dev/null
+++ b/products/alerts/frontend/views/EditAlertModalV2.tsx
@@ -0,0 +1,449 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+import { useCallback, useMemo } from 'react'
+
+import { UserActivityIndicator } from 'lib/components/UserActivityIndicator/UserActivityIndicator'
+import { dayjs } from 'lib/dayjs'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { formatDate } from 'lib/utils/datetime'
+import { insightLogic } from 'scenes/insights/insightLogic'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { getDisplayNameFromEntityNode } from 'scenes/insights/utils'
+import { teamLogic } from 'scenes/teamLogic'
+import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
+import { urls } from 'scenes/urls'
+
+import { AlertCalculationInterval, AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
+import { isFunnelsQuery, isInsightVizNode } from '~/queries/utils'
+import { FunnelVizType } from '~/types'
+
+import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/AlertAdvancedOptionsSection'
+import { AlertStateIndicator, AlertTimezoneNotice } from 'products/alerts/frontend/components/AlertDefinition'
+import { AlertDefinitionSection } from 'products/alerts/frontend/components/AlertDefinitionSection'
+import {
+ AlertEditor,
+ AlertEditorFormDetails,
+ AlertEditorLoading,
+} from 'products/alerts/frontend/components/AlertEditor'
+import { AlertIntervalRow } from 'products/alerts/frontend/components/AlertIntervalRow'
+import { AlertPreviewCard } from 'products/alerts/frontend/components/AlertPreviewCard'
+import { buildAlertSummary } from 'products/alerts/frontend/components/alertSummary'
+import { AlertWizard } from 'products/alerts/frontend/components/AlertWizard'
+import { ThresholdConditionRow } from 'products/alerts/frontend/components/ThresholdConditionRow'
+import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { quietHoursFormError } from 'products/alerts/frontend/logic/scheduleRestrictionValidation'
+import { deriveAlertCheckPreviewSeries } from 'products/alerts/frontend/logic/trendsAlertPreview'
+import { InsightAlertNotificationSection } from 'products/alerts/frontend/views/InsightAlertNotificationSection'
+
+import { alertFormLogic, canCheckOngoingInterval, insightAlertKindForQuery } from '../logic/alertFormLogic'
+import { alertLogic } from '../logic/alertLogic'
+import { alertNotificationLogic } from '../logic/alertNotificationLogic'
+import { isNextPlannedEvaluationStale } from '../logic/alertSchedulingStale'
+import { insightAlertsLogic } from '../logic/insightAlertsLogic'
+import { supportsAnomalyDetection, supportsOngoingInterval } from '../types'
+import type { AlertType } from '../types'
+import { AlertHistorySection } from './AlertHistorySection'
+import type { ResolvedAlertModalProps } from './EditAlertModal'
+import { AlertLeadingActions } from './EditAlertModalV2/AlertLeadingActions'
+import { buildWizardSteps } from './EditAlertModalV2/buildWizardSteps'
+import { EditAlertTabs } from './EditAlertModalV2/EditAlertTabs'
+
+/** Redesigned alert edit/create modal. New alerts use a 3-step wizard (Monitor → Schedule & notify
+ * → Review); editing an existing alert skips the wizard and uses a sectioned layout with a one-line
+ * summary and a live preview card. Gated behind the ALERTS_REDESIGNED_EDIT_MODAL feature flag. */
+export function EditAlertModalV2({
+ initialAlert,
+ isOpen,
+ alertId,
+ insightId,
+ insightShortId,
+ onClose,
+ onEditSuccess,
+ insightLogicProps,
+ defaultToAnomalyDetection,
+ insightName,
+ useAlertCheckPreview,
+}: ResolvedAlertModalProps): JSX.Element {
+ const _alertLogic = alertLogic({ alertId })
+ const { alert: loadedAlert, alertLoading } = useValues(_alertLogic)
+ const alert = initialAlert ?? loadedAlert
+ const { insightLoading } = useValues(insightLogic(insightLogicProps))
+
+ const _onEditSuccess = useCallback(
+ (alertId: AlertType['id'] | undefined) => {
+ onEditSuccess(alertId)
+ },
+ [onEditSuccess]
+ )
+
+ const trendsLogic = trendsDataLogic(insightLogicProps)
+ const {
+ alertSeries,
+ isNonTimeSeriesDisplay,
+ isBreakdownValid,
+ formulaNodes,
+ interval: trendInterval,
+ indexedResults,
+ insightDataLoading,
+ } = useValues(trendsLogic)
+
+ const { query } = useValues(insightVizDataLogic(insightLogicProps))
+
+ const funnelSource = !!query && isInsightVizNode(query) && isFunnelsQuery(query.source) ? query.source : null
+ const isTrendsFunnel = funnelSource?.funnelsFilter?.funnelVizType === FunnelVizType.Trends
+ const funnelStepLabels = (funnelSource?.series ?? []).map(
+ (node, index) => getDisplayNameFromEntityNode(node) ?? `Step ${index + 1}`
+ )
+ const insightAlertKind = insightAlertKindForQuery(query)
+
+ const formLogicProps = {
+ alert,
+ insightId,
+ onEditSuccess: _onEditSuccess,
+ insightVizDataLogicProps: insightLogicProps,
+ insightInterval: trendInterval ?? undefined,
+ insightAlertKind,
+ defaultToAnomalyDetection: !alertId && !isNonTimeSeriesDisplay && defaultToAnomalyDetection,
+ insightName,
+ insightIsTrendsFunnel: isTrendsFunnel,
+ uiVersion: 'redesigned' as const,
+ }
+ const formLogic = alertFormLogic(formLogicProps)
+ const {
+ alertForm,
+ isAlertFormSubmitting,
+ alertFormChanged,
+ alertFormHasErrors,
+ alertFormSubmitAttempted,
+ simulationResult,
+ simulationResultLoading,
+ simulationDateFrom,
+ thresholdBoundsFormError,
+ hogqlAlertPreview,
+ funnelAlertPreview,
+ hogqlResultColumns,
+ hogqlValueColumnOptions,
+ hogqlLabelColumnOptions,
+ } = useValues(formLogic)
+ const {
+ deleteAlert,
+ snoozeAlert,
+ clearSnooze,
+ simulateAlert,
+ clearSimulation,
+ setSimulationDateFrom,
+ setAlertFormSubmitAttempted,
+ } = useActions(formLogic)
+ const { setAlertFormValue } = useActions(formLogic)
+
+ const { currentTeam } = useValues(teamLogic)
+ const projectTimezone = currentTeam?.timezone ?? 'UTC'
+ const inlineNotificationsEnabled = useFeatureFlag('ALERTS_INLINE_NOTIFICATIONS')
+ const investigationAgentEnabled = useFeatureFlag('ALERTS_INVESTIGATION_AGENT')
+
+ const { existingHogFunctions, pendingNotifications } = useValues(alertNotificationLogic({ alertId: alertId }))
+ const hasPendingNotifications = inlineNotificationsEnabled && pendingNotifications.length > 0
+
+ const handleClose = useCallback(() => {
+ clearSimulation()
+ if (insightLogicProps && insightId) {
+ insightAlertsLogic({ insightId, insightLogicProps }).actions.clearSimulationAnomalyPoints()
+ }
+ onClose?.()
+ }, [clearSimulation, insightLogicProps, insightId, onClose])
+
+ const clearSimulationOverlay = useCallback(() => {
+ if (insightLogicProps && insightId) {
+ insightAlertsLogic({ insightId, insightLogicProps }).actions.clearSimulationAnomalyPoints()
+ }
+ }, [insightLogicProps, insightId])
+
+ const creatingNewAlert = alertId === undefined
+ const can_check_ongoing_interval = canCheckOngoingInterval(alertForm, { isTrendsFunnel })
+ const alertMode = alertForm.detector_config ? 'detector' : 'threshold'
+ const nextPlannedEvaluationStale = useMemo(
+ () =>
+ isNextPlannedEvaluationStale(
+ creatingNewAlert,
+ alert
+ ? {
+ calculation_interval: alert.calculation_interval,
+ schedule_restriction: alert.schedule_restriction,
+ skip_weekend: alert.skip_weekend,
+ config: supportsOngoingInterval(alert.config)
+ ? { check_ongoing_interval: alert.config.check_ongoing_interval }
+ : null,
+ }
+ : null,
+ {
+ calculation_interval: alertForm.calculation_interval,
+ schedule_restriction: alertForm.schedule_restriction,
+ skip_weekend: alertForm.skip_weekend,
+ config: supportsOngoingInterval(alertForm.config)
+ ? { check_ongoing_interval: alertForm.config.check_ongoing_interval }
+ : null,
+ }
+ ),
+ [
+ alert,
+ alertForm.calculation_interval,
+ alertForm.schedule_restriction,
+ alertForm.skip_weekend,
+ alertForm.config,
+ creatingNewAlert,
+ ]
+ )
+
+ const enabledAdvancedOptionsCount = useMemo(() => {
+ let n = 0
+ if (
+ supportsOngoingInterval(alertForm.config) &&
+ alertForm.config.check_ongoing_interval &&
+ can_check_ongoing_interval
+ ) {
+ n += 1
+ }
+ if (
+ (alertForm.calculation_interval === AlertCalculationInterval.DAILY ||
+ isSubDailyAlertInterval(alertForm.calculation_interval)) &&
+ alertForm.skip_weekend
+ ) {
+ n += 1
+ }
+ if ((alertForm.schedule_restriction?.blocked_windows?.length ?? 0) > 0) {
+ n += 1
+ }
+ return n
+ }, [
+ alertForm.calculation_interval,
+ alertForm.config,
+ alertForm.schedule_restriction?.blocked_windows?.length,
+ alertForm.skip_weekend,
+ can_check_ongoing_interval,
+ ])
+
+ const subscribedCount = alertForm.subscribed_users?.length ?? 0
+ const destinationCount = existingHogFunctions.length + pendingNotifications.length
+ const summary = useMemo(
+ () => buildAlertSummary(alertForm, subscribedCount, destinationCount),
+ [alertForm, destinationCount, subscribedCount]
+ )
+
+ // The monitored trends series' values, for the live preview sparkline. Picked by the alert's
+ // series_index so the preview matches what the alert actually evaluates.
+ const trendsPreviewValues = useMemo(() => {
+ if (!isTrendsFunnel && alertForm.config?.type === 'TrendsAlertConfig') {
+ const idx = alertForm.config.series_index ?? 0
+ const series = indexedResults?.[idx]
+ return series?.data ?? null
+ }
+ return null
+ }, [alertForm.config, indexedResults, isTrendsFunnel])
+
+ const checkPreview = useMemo(() => {
+ if (!useAlertCheckPreview || !alert) {
+ return undefined
+ }
+ const preview = deriveAlertCheckPreviewSeries(
+ alert.checks,
+ alertForm.condition?.type ?? AlertConditionType.ABSOLUTE_VALUE,
+ alertForm.threshold?.configuration?.type ?? InsightThresholdType.ABSOLUTE
+ )
+ return {
+ ...preview,
+ labels: preview.labels?.map((label) => formatDate(dayjs(label), 'MMM D, HH:mm')),
+ }
+ }, [alert, alertForm.condition?.type, alertForm.threshold?.configuration?.type, useAlertCheckPreview])
+
+ const leadingActions = (
+ <AlertLeadingActions
+ alertForm={alertForm}
+ alert={alert}
+ onDeleteAlert={deleteAlert}
+ onSnoozeAlert={snoozeAlert}
+ onClearSnooze={clearSnooze}
+ />
+ )
+
+ const definitionNode = (
+ <AlertDefinitionSection
+ alertForm={alertForm}
+ alertMode={alertMode}
+ thresholdBoundsFormError={thresholdBoundsFormError}
+ isNonTimeSeriesDisplay={isNonTimeSeriesDisplay}
+ trends={{ alertSeries, formulaNodes, isBreakdownValid }}
+ funnel={{
+ stepLabels: funnelStepLabels,
+ preview: funnelAlertPreview,
+ isTrendsFunnel,
+ }}
+ hogql={{
+ preview: hogqlAlertPreview,
+ columns: hogqlResultColumns,
+ valueColumnOptions: hogqlValueColumnOptions,
+ labelColumnOptions: hogqlLabelColumnOptions,
+ }}
+ supportsAnomalyDetection={!isNonTimeSeriesDisplay && supportsAnomalyDetection(alertForm.config)}
+ twoColumnLayout
+ investigationAgentEnabled={investigationAgentEnabled}
+ simulationResult={simulationResult}
+ simulationResultLoading={simulationResultLoading}
+ simulationDateFrom={simulationDateFrom}
+ onSetAlertFormValue={setAlertFormValue}
+ thresholdRowRenderer={(props) => <ThresholdConditionRow {...props} />}
+ onSimulateAlert={simulateAlert}
+ onSetSimulationDateFrom={setSimulationDateFrom}
+ onClearSimulation={clearSimulation}
+ onClearSimulationOverlay={clearSimulationOverlay}
+ />
+ )
+
+ const scheduleNode = (
+ <div className="space-y-2">
+ <AlertIntervalRow
+ alertForm={alertForm}
+ creatingNewAlert={creatingNewAlert}
+ alert={alert}
+ trendInterval={trendInterval}
+ nextPlannedEvaluationStale={nextPlannedEvaluationStale}
+ canCheckOngoingInterval={can_check_ongoing_interval}
+ onSetAlertFormValue={setAlertFormValue}
+ />
+ <AlertTimezoneNotice
+ timezone={projectTimezone}
+ settingsUrl={urls.settings('environment-customization', 'date-and-time')}
+ />
+ </div>
+ )
+
+ const notifyNode = (
+ <InsightAlertNotificationSection
+ alertForm={alertForm}
+ alertId={alertId}
+ insightShortId={insightShortId}
+ inlineNotificationsEnabled={inlineNotificationsEnabled}
+ showSectionTitle={false}
+ onSetAlertFormValue={setAlertFormValue}
+ />
+ )
+
+ const advancedNode = (
+ <AlertAdvancedOptionsSection
+ alertForm={alertForm}
+ canCheckOngoingInterval={can_check_ongoing_interval}
+ projectTimezone={projectTimezone}
+ enabledAdvancedOptionsCount={enabledAdvancedOptionsCount}
+ defaultOpen
+ onSetAlertFormValue={setAlertFormValue}
+ />
+ )
+
+ const previewNode = (
+ <AlertPreviewCard
+ alertForm={alertForm}
+ trendsValues={trendsPreviewValues}
+ trendsLabels={
+ indexedResults?.[
+ alertForm.config?.type === 'TrendsAlertConfig' ? (alertForm.config.series_index ?? 0) : 0
+ ]?.labels ?? null
+ }
+ funnelPreview={funnelAlertPreview}
+ hogqlPreview={hogqlAlertPreview}
+ checkPreview={checkPreview}
+ loading={!useAlertCheckPreview && (insightLoading || insightDataLoading)}
+ />
+ )
+ const nameError = alertFormSubmitAttempted && !alertForm.name ? 'Enter an alert name.' : undefined
+ const scheduleRestrictionFormError = quietHoursFormError(alertForm.schedule_restriction)
+
+ return (
+ <LemonModal onClose={handleClose} isOpen={isOpen} width={900} simple title="">
+ {alertLoading && !alert ? (
+ <AlertEditorLoading title="Edit alert" onBack={handleClose} />
+ ) : (
+ <Form
+ logic={alertFormLogic}
+ props={formLogicProps}
+ formKey="alertForm"
+ enableFormOnSubmit
+ className="LemonModal__layout"
+ >
+ {creatingNewAlert ? (
+ <AlertWizard
+ title="New alert"
+ isSubmitting={isAlertFormSubmitting}
+ hasChanges={alertFormChanged}
+ onBack={handleClose}
+ onSubmitAttempted={setAlertFormSubmitAttempted}
+ steps={buildWizardSteps({
+ nameNode: <AlertEditorFormDetails nameError={nameError} />,
+ definitionNode,
+ previewNode,
+ scheduleNode,
+ notifyNode,
+ advancedNode,
+ summary,
+ thresholdBoundsFormError,
+ scheduleRestrictionFormError,
+ alertFormHasErrors,
+ alertName: alertForm.name,
+ })}
+ />
+ ) : (
+ <AlertEditor
+ title="Edit alert"
+ className="min-h-0 flex-1 overflow-hidden"
+ contentClassName="min-h-0 flex-1 overflow-y-auto"
+ onBack={handleClose}
+ isEditing
+ isSubmitting={isAlertFormSubmitting}
+ hasChanges={alertFormChanged}
+ hasPendingChanges={hasPendingNotifications}
+ onSubmitAttempted={setAlertFormSubmitAttempted}
+ leadingActions={leadingActions}
+ >
+ <div className="space-y-3">
+ <EditAlertTabs
+ summary={summary}
+ summaryHeader={
+ alert ? (
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-medium">Current status</span>
+ <AlertStateIndicator alert={alert} />
+ </div>
+ ) : undefined
+ }
+ nameNode={
+ <AlertEditorFormDetails
+ nameError={nameError}
+ activity={
+ alert?.created_by ? (
+ <UserActivityIndicator
+ at={alert.created_at}
+ by={alert.created_by}
+ prefix="Created"
+ />
+ ) : undefined
+ }
+ />
+ }
+ previewNode={previewNode}
+ definitionNode={definitionNode}
+ scheduleNode={scheduleNode}
+ advancedNode={advancedNode}
+ notifyNode={notifyNode}
+ historyNode={
+ alertId && alert ? (
+ <AlertHistorySection alertId={alert.id} showCurrentStatus={false} />
+ ) : null
+ }
+ />
+ </div>
+ </AlertEditor>
+ )}
+ </Form>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/products/alerts/frontend/views/EditAlertModalV2/AlertLeadingActions.tsx b/products/alerts/frontend/views/EditAlertModalV2/AlertLeadingActions.tsx
new file mode 100644
index 000000000000..25382143b1ec
--- /dev/null
+++ b/products/alerts/frontend/views/EditAlertModalV2/AlertLeadingActions.tsx
@@ -0,0 +1,74 @@
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
+import { formatDate } from 'lib/utils/datetime'
+
+import { AlertState } from '~/queries/schema/schema-general'
+
+import { SnoozeButton } from 'products/alerts/frontend/components/SnoozeButton'
+import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
+import type { AlertType } from 'products/alerts/frontend/types'
+
+interface AlertLeadingActionsProps {
+ alertForm: AlertFormType
+ alert: AlertType | null
+ onDeleteAlert: () => void
+ onSnoozeAlert: (snoozeUntil: string) => void
+ onClearSnooze: () => void
+}
+
+export function AlertLeadingActions({
+ alertForm,
+ alert,
+ onDeleteAlert,
+ onSnoozeAlert,
+ onClearSnooze,
+}: AlertLeadingActionsProps): JSX.Element {
+ return (
+ <div className="flex 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>
+ <SnoozeButton
+ onChange={onSnoozeAlert}
+ value={alert?.snoozed_until}
+ disabledReason={alert?.state === AlertState.FIRING ? undefined : 'Only firing alerts can be snoozed'}
+ />
+ {alert?.state === AlertState.SNOOZED ? (
+ <LemonButton
+ type="secondary"
+ status="default"
+ onClick={onClearSnooze}
+ tooltip={`Currently snoozed until ${formatDate(dayjs(alert.snoozed_until), 'MMM D, HH:mm')}`}
+ >
+ Clear snooze
+ </LemonButton>
+ ) : null}
+ <div className="ml-auto">
+ <LemonField name="enabled" className="m-0">
+ <LemonSwitch checked={alertForm.enabled} data-attr="alertForm-enabled" label="Enabled" />
+ </LemonField>
+ </div>
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/views/EditAlertModalV2/EditAlertTabs.tsx b/products/alerts/frontend/views/EditAlertModalV2/EditAlertTabs.tsx
new file mode 100644
index 000000000000..547a71aea6b6
--- /dev/null
+++ b/products/alerts/frontend/views/EditAlertModalV2/EditAlertTabs.tsx
@@ -0,0 +1,101 @@
+import { useState } from 'react'
+
+import { IconBell, IconClock, IconGraph, IconPulse } from '@posthog/icons'
+import { LemonTabs } from '@posthog/lemon-ui'
+import type { LemonTab } from '@posthog/lemon-ui'
+
+import { AlertSummaryBanner, AlertSummarySection } from 'products/alerts/frontend/components/AlertSummaryBanner'
+
+interface EditAlertTabsProps {
+ summary: { fires: string; cadence: string; notifies: string }
+ summaryHeader?: React.ReactNode
+ nameNode: React.ReactNode
+ previewNode: React.ReactNode
+ definitionNode: React.ReactNode
+ scheduleNode: React.ReactNode
+ advancedNode: React.ReactNode
+ notifyNode: React.ReactNode
+ historyNode: React.ReactNode | null
+}
+
+export function EditAlertTabs({
+ summary,
+ summaryHeader,
+ nameNode,
+ previewNode,
+ definitionNode,
+ scheduleNode,
+ advancedNode,
+ notifyNode,
+ historyNode,
+}: EditAlertTabsProps): JSX.Element {
+ const [activeKey, setActiveKey] = useState<string>('monitor')
+
+ const tabs: (LemonTab<string> | null)[] = [
+ {
+ key: 'monitor',
+ label: (
+ <span className="flex items-center gap-1.5">
+ <IconPulse className="size-4" />
+ Monitor
+ </span>
+ ),
+ content: (
+ <div className="space-y-3 pt-3">
+ {nameNode}
+ {previewNode}
+ {definitionNode}
+ </div>
+ ),
+ },
+ {
+ key: 'schedule',
+ label: (
+ <span className="flex items-center gap-1.5">
+ <IconClock className="size-4" />
+ Schedule
+ </span>
+ ),
+ content: (
+ <div className="space-y-3 pt-3">
+ {scheduleNode}
+ {advancedNode}
+ </div>
+ ),
+ },
+ {
+ key: 'notify',
+ label: (
+ <span className="flex items-center gap-1.5">
+ <IconBell className="size-4" />
+ Notify
+ </span>
+ ),
+ content: <div className="pt-3">{notifyNode}</div>,
+ },
+ historyNode
+ ? {
+ key: 'history',
+ label: (
+ <span className="flex items-center gap-1.5">
+ <IconGraph className="size-4" />
+ History
+ </span>
+ ),
+ content: <div className="pt-3">{historyNode}</div>,
+ }
+ : null,
+ ]
+
+ let activeSummarySection: AlertSummarySection | undefined
+ if (['monitor', 'schedule', 'notify'].includes(activeKey)) {
+ activeSummarySection = activeKey as AlertSummarySection
+ }
+
+ return (
+ <div className="space-y-3">
+ <AlertSummaryBanner summary={summary} header={summaryHeader} activeSection={activeSummarySection} />
+ <LemonTabs tabs={tabs} activeKey={activeKey} onChange={setActiveKey} className="flex-1 min-h-0" />
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.test.tsx b/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.test.tsx
new file mode 100644
index 000000000000..cb3205f49e60
--- /dev/null
+++ b/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.test.tsx
@@ -0,0 +1,31 @@
+import { buildWizardSteps } from './buildWizardSteps'
+
+describe('buildWizardSteps', () => {
+ const baseInput = {
+ nameNode: null,
+ definitionNode: null,
+ previewNode: null,
+ scheduleNode: null,
+ notifyNode: null,
+ advancedNode: null,
+ summary: { fires: '', cadence: '', notifies: '' },
+ alertFormHasErrors: false,
+ alertName: 'My alert',
+ }
+
+ it.each([
+ ['missing name', { alertName: '' }, 'monitor', 'Enter an alert name.'],
+ ['invalid threshold', { thresholdBoundsFormError: 'Enter a threshold' }, 'monitor', 'Enter a threshold'],
+ [
+ 'invalid schedule',
+ { alertFormHasErrors: true, scheduleRestrictionFormError: 'Choose an end time' },
+ 'schedule',
+ 'Choose an end time',
+ ],
+ ])('blocks the step containing %s errors', (_name, overrides, stepKey, expectedReason) => {
+ const steps = buildWizardSteps({ ...baseInput, ...overrides })
+ const step = steps.find((step) => step.key === stepKey)
+
+ expect(step).toMatchObject({ canAdvance: false, cannotAdvanceReason: expectedReason })
+ })
+})
diff --git a/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.tsx b/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.tsx
new file mode 100644
index 000000000000..148f9d946829
--- /dev/null
+++ b/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.tsx
@@ -0,0 +1,92 @@
+import type { ReactNode } from 'react'
+
+import { AlertWizardStep } from 'products/alerts/frontend/components/AlertWizard'
+
+interface WizardStepInput {
+ nameNode: ReactNode
+ definitionNode: ReactNode
+ previewNode: ReactNode
+ scheduleNode: ReactNode
+ notifyNode: ReactNode
+ advancedNode: ReactNode
+ summary: { fires: string; cadence: string; notifies: string }
+ thresholdBoundsFormError?: string
+ scheduleRestrictionFormError?: string
+ alertFormHasErrors: boolean
+ alertName: string
+}
+
+export function buildWizardSteps(input: WizardStepInput): AlertWizardStep[] {
+ const { summary, alertFormHasErrors } = input
+ const reviewFires = summary.fires || 'a configured threshold'
+ const reviewCadence = summary.cadence || 'a cadence'
+ const reviewNotifies = summary.notifies || 'no one yet'
+ const monitorCannotAdvanceReason = !input.alertName ? 'Enter an alert name.' : input.thresholdBoundsFormError
+ const monitorCanAdvance = !monitorCannotAdvanceReason
+
+ return [
+ {
+ key: 'monitor',
+ title: 'Monitor',
+ description: 'Pick what this alert watches and when it should fire.',
+ canAdvance: monitorCanAdvance,
+ cannotAdvanceReason: monitorCannotAdvanceReason,
+ content: (
+ <div className="space-y-4">
+ {input.nameNode}
+ {input.previewNode}
+ {input.definitionNode}
+ </div>
+ ),
+ },
+ {
+ key: 'schedule',
+ title: 'Schedule',
+ description: 'How often this alert runs.',
+ canAdvance: !input.scheduleRestrictionFormError,
+ cannotAdvanceReason: input.scheduleRestrictionFormError,
+ content: (
+ <div className="space-y-3">
+ {input.scheduleNode}
+ {input.advancedNode}
+ </div>
+ ),
+ },
+ {
+ key: 'notify',
+ title: 'Notify',
+ description: 'Who gets told when this alert fires.',
+ canAdvance: true,
+ content: <div className="space-y-4">{input.notifyNode}</div>,
+ },
+ {
+ key: 'review',
+ title: 'Review',
+ description: 'Confirm what this alert will do, then create it.',
+ canAdvance: !alertFormHasErrors,
+ cannotAdvanceReason: alertFormHasErrors ? 'Fix the errors in previous steps before creating.' : undefined,
+ content: (
+ <div className="space-y-3">
+ <div className="rounded border border-border bg-bg-light p-3 space-y-1.5 text-sm">
+ <div className="flex gap-2">
+ <span className="text-muted w-20 shrink-0">Fires when</span>
+ <span className="font-medium">{reviewFires}</span>
+ </div>
+ <div className="flex gap-2">
+ <span className="text-muted w-20 shrink-0">Runs</span>
+ <span className="font-medium">{reviewCadence}</span>
+ </div>
+ <div className="flex gap-2">
+ <span className="text-muted w-20 shrink-0">Notifies</span>
+ <span className="font-medium">{reviewNotifies}</span>
+ </div>
+ </div>
+ <p className="text-xs text-muted">
+ You can adjust any of this later without stepping through the wizard. Editing an existing alert
+ opens straight to its sections.
+ </p>
+ </div>
+ ),
+ },
+ ]
+}
diff --git a/products/alerts/frontend/views/InsightAlertNotificationSection.tsx b/products/alerts/frontend/views/InsightAlertNotificationSection.tsx
index 9254812df699..b1723a5fb086 100644
--- a/products/alerts/frontend/views/InsightAlertNotificationSection.tsx
+++ b/products/alerts/frontend/views/InsightAlertNotificationSection.tsx
@@ -1,3 +1,5 @@
+import { IconBell } from '@posthog/icons'
+
import { MemberSelectMultiple } from 'lib/components/MemberSelectMultiple'
import { InsightShortId } from '~/types'
@@ -13,6 +15,7 @@ export interface InsightAlertNotificationSectionProps {
alertId: AlertType['id'] | undefined
insightShortId: InsightShortId
inlineNotificationsEnabled: boolean
+ showSectionTitle?: boolean
onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
}
@@ -21,6 +24,7 @@ export function InsightAlertNotificationSection({
alertId,
insightShortId,
inlineNotificationsEnabled,
+ showSectionTitle = true,
onSetAlertFormValue,
}: InsightAlertNotificationSectionProps): JSX.Element {
let destinations: JSX.Element
@@ -36,8 +40,8 @@ export function InsightAlertNotificationSection({
destinations = <div className="text-muted-alt">Save alert first to add destinations (e.g. Slack, Webhooks)</div>
}
- return (
- <AlertEditorSection title="Notification">
+ const content = (
+ <>
<div className="flex gap-4 items-center">
<div>E-mail</div>
<div className="flex-auto">
@@ -51,6 +55,16 @@ export function InsightAlertNotificationSection({
<h4 className="mt-4">Destinations</h4>
<div className="mt-4">{destinations}</div>
+ </>
+ )
+
+ if (!showSectionTitle) {
+ return content
+ }
+
+ return (
+ <AlertEditorSection title="Notification" icon={<IconBell className="size-4" />}>
+ {content}
</AlertEditorSection>
)
}
diff --git a/products/alerts/frontend/views/InsightAlerts.tsx b/products/alerts/frontend/views/InsightAlerts.tsx
index 314c2630fdfb..3211c84a10a5 100644
--- a/products/alerts/frontend/views/InsightAlerts.tsx
+++ b/products/alerts/frontend/views/InsightAlerts.tsx
@@ -16,13 +16,13 @@ import { urls } from 'scenes/urls'
import { AlertState, ProductKey } from '~/queries/schema/schema-general'
+import { AlertStateIndicator } from '../components/AlertDefinition'
import { AlertsFiltersBar } from '../components/AlertsFiltersBar'
import { alertIntervalDisplayLabel } from '../logic/alertIntervalHelpers'
import { alertLogic } from '../logic/alertLogic'
import { alertsLogic } from '../logic/alertsLogic'
import { AlertType } from '../types'
import { EditAlertModal } from './EditAlertModal'
-import { AlertStateIndicator } from './ManageAlertsModal'
const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
@@ -198,7 +198,7 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {
]
const isEmpty = alertsCount === 0 && !alertsResponseLoading && !isFiltering
- // TODO: add info here to sign up for alerts early access
+ const alertForEditModal = alert ?? alertsSortedByState.find((candidate) => candidate.id === alertId)
return (
<>
{isEmpty && (
@@ -219,14 +219,12 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {
/>
)}
- {alert && (
+ {alertForEditModal && (
<EditAlertModal
onClose={() => push(urls.alerts())}
isOpen
- alertId={alert.id}
- insightShortId={alert.insight.short_id}
- insightId={alert.insight.id}
- insightLogicProps={{ dashboardItemId: alert.insight.short_id }}
+ alert={alertForEditModal}
+ useAlertCheckPreview
onEditSuccess={() => {
loadAlerts()
push(urls.alerts())
diff --git a/products/alerts/frontend/views/ManageAlertsModal.stories.tsx b/products/alerts/frontend/views/ManageAlertsModal.stories.tsx
new file mode 100644
index 000000000000..aa1e88f0cf74
--- /dev/null
+++ b/products/alerts/frontend/views/ManageAlertsModal.stories.tsx
@@ -0,0 +1,130 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import {
+ AlertCalculationInterval,
+ AlertConditionType,
+ AlertState,
+ InsightThresholdType,
+ NodeKind,
+} from '~/queries/schema/schema-general'
+import type { InsightShortId } from '~/types'
+
+import type { AlertType } from '../types'
+import { ManageAlertsModal } from './ManageAlertsModal'
+
+const insightShortId = 'checkout-volume' as InsightShortId
+const createdBy = {
+ id: 1,
+ uuid: '018f59f3-4f2f-7c89-b389-73b99b91f442',
+ distinct_id: 'storybook-user',
+ first_name: 'Hedge Hog',
+ email: '[email protected]',
+ hedgehog_config: null,
+}
+
+const makeAlert = (overrides: Partial<AlertType>): AlertType =>
+ ({
+ id: 'alert-volume',
+ name: 'Upload volume above 10,000',
+ enabled: true,
+ state: AlertState.NOT_FIRING,
+ calculation_interval: AlertCalculationInterval.HOURLY,
+ last_checked_at: '2026-07-16T16:45:00Z',
+ last_notified_at: '2026-07-14T13:30:00Z',
+ created_at: '2026-06-01T09:00:00Z',
+ created_by: createdBy,
+ subscribed_users: [createdBy],
+ checks: [],
+ config: {
+ type: 'TrendsAlertConfig',
+ series_index: 0,
+ check_ongoing_interval: false,
+ },
+ threshold: {
+ configuration: {
+ type: InsightThresholdType.ABSOLUTE,
+ bounds: { upper: 10000 },
+ },
+ },
+ condition: { type: AlertConditionType.ABSOLUTE_VALUE },
+ insight: {
+ id: 101,
+ short_id: insightShortId,
+ name: 'Checkout volume',
+ derived_name: 'Checkout volume',
+ },
+ ...overrides,
+ }) as AlertType
+
+const alerts = [
+ makeAlert({}),
+ makeAlert({
+ id: 'alert-anomaly',
+ name: 'Unusual upload volume',
+ state: AlertState.FIRING,
+ detector_config: {
+ type: 'zscore',
+ threshold: 0.95,
+ window: 90,
+ },
+ }),
+ makeAlert({
+ id: 'alert-disabled',
+ name: 'Upload volume below 100',
+ enabled: false,
+ threshold: {
+ configuration: {
+ type: InsightThresholdType.ABSOLUTE,
+ bounds: { lower: 100 },
+ },
+ },
+ }),
+]
+
+const insightQuery = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: 'file uploaded' }],
+ },
+}
+
+const meta: Meta<typeof ManageAlertsModal> = {
+ component: ManageAlertsModal,
+ title: 'Products/Alerts/Insight alerts modal',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2026-07-16',
+ featureFlags: [FEATURE_FLAGS.ALERTS_REDESIGNED_EDIT_MODAL],
+ testOptions: { viewport: { width: 1000, height: 700 } },
+ },
+ args: {
+ isOpen: true,
+ insightId: 101,
+ insightShortId,
+ canCreateAlertForInsight: true,
+ insightQuery,
+ insightLogicProps: {
+ dashboardItemId: insightShortId,
+ cachedInsight: {
+ id: 101,
+ short_id: insightShortId,
+ name: 'Checkout volume',
+ query: insightQuery,
+ alerts,
+ },
+ },
+ onClose: () => {},
+ onCreateAlert: () => {},
+ onEditAlert: () => {},
+ },
+}
+
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const WithAlerts: Story = {}
diff --git a/products/alerts/frontend/views/ManageAlertsModal.tsx b/products/alerts/frontend/views/ManageAlertsModal.tsx
index 6d8c09b203cf..a73bfe417df6 100644
--- a/products/alerts/frontend/views/ManageAlertsModal.tsx
+++ b/products/alerts/frontend/views/ManageAlertsModal.tsx
@@ -3,36 +3,28 @@ import { router } from 'kea-router'
import { Link } from '@posthog/lemon-ui'
+import { UserActivityIndicator } from 'lib/components/UserActivityIndicator/UserActivityIndicator'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
-import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { ProfileBubbles } from 'lib/lemon-ui/ProfilePicture'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
-import { AlertState, InsightThresholdType } from '~/queries/schema/schema-general'
+import { InsightThresholdType } from '~/queries/schema/schema-general'
import { InsightShortId } from '~/types'
+import { AlertStateIndicator } from '../components/AlertDefinition'
+import { buildAlertSummary } from '../components/alertSummary'
+import { AlertSummaryBanner } from '../components/AlertSummaryBanner'
import { InsightAlertsLogicProps, alertsUnsupportedReason, insightAlertsLogic } from '../logic/insightAlertsLogic'
import { AlertType } from '../types'
-export function AlertStateIndicator({ alert }: { alert: AlertType }): JSX.Element {
- switch (alert.state) {
- case AlertState.FIRING:
- return <LemonTag type="danger">FIRING</LemonTag>
- case AlertState.ERRORED:
- return <LemonTag type="danger">ERRORED</LemonTag>
- case AlertState.SNOOZED:
- return <LemonTag type="muted">SNOOZED</LemonTag>
- case AlertState.NOT_FIRING:
- return <LemonTag type="success">NOT FIRING</LemonTag>
- }
-}
-
interface AlertListItemProps {
alert: AlertType
onClick: () => void
+ redesigned: boolean
}
function AlertSummary({ alert }: { alert: AlertType }): JSX.Element | null {
@@ -74,7 +66,26 @@ function AlertSummary({ alert }: { alert: AlertType }): JSX.Element | null {
)
}
-export function AlertListItem({ alert, onClick }: AlertListItemProps): JSX.Element {
+export function AlertListItem({ alert, onClick, redesigned }: AlertListItemProps): JSX.Element {
+ const summary = buildAlertSummary(alert, alert.subscribed_users?.length ?? 0)
+
+ if (redesigned) {
+ return (
+ <LemonButton onClick={onClick} data-attr="alert-list-item" fullWidth>
+ <AlertSummaryBanner
+ summary={summary}
+ header={
+ <div className="flex items-center justify-between gap-3">
+ <span className="min-w-0 truncate">{alert.name}</span>
+ <AlertStateIndicator alert={alert} />
+ </div>
+ }
+ footer={<UserActivityIndicator prefix="Created" at={alert.created_at} by={alert.created_by} />}
+ />
+ </LemonButton>
+ )
+ }
+
return (
<LemonButton type="secondary" onClick={onClick} data-attr="alert-list-item" fullWidth>
<div className="flex justify-between flex-auto items-center p-2">
@@ -106,6 +117,7 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
const logic = insightAlertsLogic(props)
const { alerts, alertsLoading } = useValues(logic)
+ const redesigned = useFeatureFlag('ALERTS_REDESIGNED_EDIT_MODAL')
const showDeferredListSpinner = props.deferInitialAlertsLoad && props.isOpen && alertsLoading
const openAlert = (alertId: AlertType['id']): void => {
@@ -153,7 +165,12 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
</div>
{alerts.map((alert) => (
- <AlertListItem key={alert.id} alert={alert} onClick={() => openAlert(alert.id)} />
+ <AlertListItem
+ key={alert.id}
+ alert={alert}
+ onClick={() => openAlert(alert.id)}
+ redesigned={redesigned}
+ />
))}
</div>
) : (
@@ -166,6 +183,9 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
</LemonModal.Content>
<LemonModal.Footer>
+ <LemonButton type="secondary" onClick={props.onClose}>
+ Close
+ </LemonButton>
<LemonButton
type="primary"
onClick={createAlert}
@@ -175,9 +195,6 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
>
New alert
</LemonButton>
- <LemonButton type="secondary" onClick={props.onClose}>
- Close
- </LemonButton>
</LemonModal.Footer>
</LemonModal>
)