:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): show the product empty state until an alert exists (#93038)
Rafael Audiberta6aab8e8d68e
diff --git a/docs/internal/product-empty-state-adoption.md b/docs/internal/product-empty-state-adoption.mdindex 066293805d92..d2c26d6fd4df 100644--- a/docs/internal/product-empty-state-adoption.md+++ b/docs/internal/product-empty-state-adoption.md@@ -67,6 +67,7 @@ Rows marked "in review" are not on `master` yet. See "Regenerating the lists" fo| Dashboards | `frontend/src/scenes/dashboard/dashboards/Dashboards.tsx` | on master || Product analytics | `frontend/src/scenes/saved-insights/SavedInsights.tsx` | on master || Notebooks | `frontend/src/scenes/notebooks/NotebooksScene.tsx` | on master |+| Alerts | `products/alerts/frontend/AlertsScene.tsx` | on master |Only four products resolve their status at app boot, via a `setupProbe` in their manifest:LLM analytics, error tracking, MCP analytics, web analytics.@@ -101,14 +102,13 @@ deeper, so the product is half-migrated.| Parent product | Sub-surface || ------------------ | ----------------------------------------------------------------------------------------------------------- || Workflows | `Channels/MessageChannels.tsx`, `OptOuts/OptOutCategories.tsx`, `TemplateLibrary/MessageTemplatesTable.tsx` |-| Logs | `components/LogsAlerting/LogsAlertList.tsx` || Replay vision | `replay_scanners/components/VisionActionsTab.tsx` || Customer analytics | `components/CustomerJourneys/CustomerJourneysEmptyState.tsx` |### Tier 4: everything else-Still on `ProductIntroduction`: alerts (`products/alerts/frontend/views/InsightAlerts.tsx`),-subscriptions, pulse, data catalog, engineering analytics, comments, ingestion warnings (v1 and v2),+Still on `ProductIntroduction`: subscriptions, pulse, data catalog, engineering analytics,+comments, ingestion warnings (v1 and v2),Max conversation history, and data pipelines destinations and transformations(`frontend/src/scenes/data-pipelines/DataPipelinesHogFunctions.tsx` covers the last two).diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 0d8eff021158..7367ea2ffb1b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1756,6 +1756,10 @@ snapshots:hash: v1.k794b7964.f10735d00b8b7484f071fdcaebec654ef0042bf7894e374cbe077acb88d1de1f.DVP2UF6lwJvd5PyN12NBZIhS9EOv5z-N0T-aYKrAONwcomponents-product-empty-state--ai-observability-needs-setup--light:hash: v1.k794b7964.356081f2e978bf91130ebf0aa39fdc921a169780d2c3b9e289191d40dc73f6f1.nOlwt03p_7y2o0g2xV7835qBylZDe7uIdPxowxXI8mA+ components-product-empty-state--alerts-needs-setup--dark:+ hash: v1.k794b7964.c32ae94661df7717f1eb3d34a588fb448656034cdf8c311c9d57d0a7b252e1bb.bsy-jXMCqyPPSTw5BnWFt0b_KAsSFhzOkZmZYGKh6NI+ components-product-empty-state--alerts-needs-setup--light:+ hash: v1.k794b7964.086690dbcdaadf39afe5fbccc09064b60772fc2773bbca51ff93dac49bb450b6.qT3UeCTW9_w2NIoSfASbExcPfCqJ4wRL1e3DkUajEQQcomponents-product-empty-state--annotations-needs-setup--dark:hash: v1.k794b7964.375eb5c484baae36185d43a8b1ae04a6ec0915405be7f4f4a05887816dfde456.L2szPOMNE0IT-m3Dxbt1SKmvgfc9bT1pvlF13-L4doIcomponents-product-empty-state--annotations-needs-setup--light:@@ -5049,13 +5053,13 @@ snapshots:products-alerts-alert-modal--missing-alert--light:hash: v1.k794b7964.84f6a3830bfb2104a4f6530814766ba5602c87feb8301bdc55f2a67c359b13ac.aEeOcFEuyf003aMGUgIK8Zldz1FzgRc492VXx63y4E8products-alerts-alerts-scene--empty-log-alerts--dark:- hash: v1.k794b7964.a9868dcf76f660a4b877ab75f7d250c5d9f88bb80c7569894ffd8b7dd47349eb.7b0VesDoG7DV59GvcHn7THcPrfCa6gx0H3IikajV1EA+ hash: v1.k794b7964.fd851b43900d431036bfe5ed95c60ac37e7d9d156636047cf8a46a50bc51e3ea.WaMiwwI8NpNv5Wvj4adbPTTlPLrFwxEUtZlbMiAXCEkproducts-alerts-alerts-scene--empty-log-alerts--light:- hash: v1.k794b7964.1caf4a25eab1c156cfe2fe0fdc28445f1312da38d9c3b21f2661ed7c1af9ad8d.ZfbubAvXZgUCHxZif8hN8LUQfZRlWV8nuVA36LOW2Pw+ hash: v1.k794b7964.738ae822e83096630168cbc5b89bf870d2ae98cecdcce0c71740f3bcc278b7d8.qWobifUt8Df9jS7q5ICqSSdXxImkwFD7sERz_8RhYfQproducts-alerts-alerts-scene--empty-state--dark:- hash: v1.k794b7964.b419d15fe1d77892d0bc6aa978baa0075f2b64e597b8b457b59daaf7d3268f1a.mxxfJ0VEg12SBSXNmlykTeIIj7jKxPkBHSB2399bnus+ hash: v1.k794b7964.3a30edbe5f7c83170e9431b0e90bbbec6e89c543d86d624872fee14b355927a3.2dG2KIvE1-wjloDHfxStse6wSY1iZRXsaFu1zkbT7qEproducts-alerts-alerts-scene--empty-state--light:- hash: v1.k794b7964.68282b46c2d253c95ece0fc855088e130c3866b9c96a857f3175656d4a2356e9.EhuHXcHe9cQbRatwuD5ervAmGm4omKeY2-UGMW4zAMQ+ hash: v1.k794b7964.853041aba5cd7e558b299495e6202a023c1e36b7cab3e18a842e4165ef8c3af4._tQ0N-2HWpiuGhj-KcBHqkPbWD0t4O6-UJRZhE3dRIwproducts-alerts-alerts-scene--insight-alerts--dark:hash: v1.k794b7964.5ae3b2c1ac763b47a52bfb9ec7ed536e2348e61a75e00b476ec5716cbccfa4f9.czQQpTNgAS1lFWe4cjHs5Ka_UDb8aFRk_DC1NkgwmX0products-alerts-alerts-scene--insight-alerts--light:diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsxindex 5f9eeb10298a..996d6afa24cd 100644--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx@@ -8,6 +8,7 @@ import { clustersEmptyState } from 'products/ai_observability/frontend/emptyStatimport { datasetsEmptyState } from 'products/ai_observability/frontend/emptyState/datasetsEmptyState'import { evaluationsEmptyState } from 'products/ai_observability/frontend/emptyState/evaluationsEmptyState'import { llmPromptsEmptyState } from 'products/ai_observability/frontend/emptyState/llmPromptsEmptyState'+import { alertsEmptyState } from 'products/alerts/frontend/emptyState/alertsEmptyState'import { annotationsEmptyState } from 'products/annotations/frontend/emptyState/annotationsEmptyState'import { businessKnowledgeEmptyState } from 'products/business_knowledge/frontend/emptyState/businessKnowledgeEmptyState'import { webScriptsEmptyState } from 'products/cdp/frontend/emptyState/webScriptsEmptyState'@@ -345,6 +346,16 @@ export const WebVitalsWaitingForData: ProductEmptyStateStory = productEmptyState{ mocks: webVitalsMocks })+// Alerts detection counts both alert kinds on mount - answer "none yet" to each.+export const AlertsNeedsSetup: ProductEmptyStateStory = productEmptyStateStory(alertsEmptyState, 'needs-setup', {+ mocks: {+ get: {+ '/api/projects/:team_id/alerts/': [200, emptyEntityList],+ '/api/projects/:team_id/logs/alerts/': [200, emptyEntityList],+ },+ },+})+// Notebooks detection counts notebooks on mount - answer "none yet".export const NotebooksNeedsSetup: ProductEmptyStateStory = productEmptyStateStory(notebooksEmptyState, 'needs-setup', {mocks: { get: { '/api/projects/:team_id/notebooks/': [200, { count: 0, results: [] }] } },diff --git a/frontend/src/styles/base.scss b/frontend/src/styles/base.scssindex 0ecbde01d57f..14a809166af4 100644--- a/frontend/src/styles/base.scss+++ b/frontend/src/styles/base.scss@@ -333,6 +333,8 @@--color-product-experiments-light: rgb(182 42 217);--color-product-error-tracking-light: rgb(211 148 24);--color-product-error-tracking-dark: rgb(247 165 1);+ --color-product-alerts-light: rgb(229 142 0);+ --color-product-alerts-dark: rgb(255 168 28);--color-product-surveys-light: rgb(243 84 84);--color-product-surveys-dark: rgb(248 121 121);--color-product-product-tours-light: rgb(243 84 84);diff --git a/products/alerts/frontend/AlertsScene.stories.tsx b/products/alerts/frontend/AlertsScene.stories.tsxindex 74a2ac126096..416b0c066ff0 100644--- a/products/alerts/frontend/AlertsScene.stories.tsx+++ b/products/alerts/frontend/AlertsScene.stories.tsx@@ -177,6 +177,9 @@ const meta: Meta = {mswDecorator({get: {'/api/environments/:team_id/alerts/': toPaginatedResponse(alerts),+ // The scene's setup gate counts both alert kinds over the project-scoped+ // API, so every story has to say whether the project has any alerts at all.+ '/api/projects/:team_id/alerts/': toPaginatedResponse(alerts),},}),],@@ -188,11 +191,18 @@ type Story = StoryObj<{}>export const InsightAlerts: Story = {}+// A project that alerts on logs but not on insights: the setup gate is satisfied, and+// the insights tab shows its own empty state.export const EmptyState: Story = {decorators: [mswDecorator({get: {'/api/environments/:team_id/alerts/': EMPTY_PAGINATED_RESPONSE,+ '/api/projects/:team_id/alerts/': EMPTY_PAGINATED_RESPONSE,+ '/api/projects/:team_id/logs/alerts/': [+ 200,+ { count: logAlerts.length, next: null, previous: null, results: logAlerts },+ ],},}),],diff --git a/products/alerts/frontend/AlertsScene.tsx b/products/alerts/frontend/AlertsScene.tsxindex 9d58ba8c7ae8..caa7235dba6a 100644--- a/products/alerts/frontend/AlertsScene.tsx+++ b/products/alerts/frontend/AlertsScene.tsx@@ -6,6 +6,7 @@ import { SceneExport } from 'scenes/sceneTypes'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { ProductKey } from '~/queries/schema/schema-general'+import { alertsEmptyState } from './emptyState/alertsEmptyState'import { Alerts } from './views/Alerts'export function AlertsScene(): JSX.Element {@@ -22,4 +23,5 @@ export function AlertsScene(): JSX.Element {export const scene: SceneExport = {component: AlertsScene,productKey: ProductKey.ALERTS,+ emptyState: alertsEmptyState,}diff --git a/products/alerts/frontend/emptyState/AlertsPreview.scss b/products/alerts/frontend/emptyState/AlertsPreview.scssnew file mode 100644index 000000000000..1c3854e73060--- /dev/null+++ b/products/alerts/frontend/emptyState/AlertsPreview.scss@@ -0,0 +1,248 @@+@import '../../../../frontend/src/lib/components/ProductEmptyState/previewMixins';++.AlertPreview {+ --alert-preview-accent: var(--empty-state-accent, var(--color-product-alerts-light));++ display: flex;+ flex-direction: column;+ gap: 0.75rem;++ // Hidden firing state. A direct child of .AlertPreview so `:checked ~` reaches all cards.+ &__checkbox {+ position: absolute;+ width: 0;+ height: 0;+ pointer-events: none;+ opacity: 0;+ }++ &__chart,+ &__panel {+ overflow: hidden;+ background: var(--color-bg-surface-primary);+ border: 1px solid var(--color-border-primary);+ border-radius: var(--radius);+ }++ // Before/after pairs are stacked on one grid cell and crossfaded, so lowering the+ // threshold never changes any element's size (no layout shift).+ &__swap {+ display: grid;+ }++ &__swap > * {+ grid-area: 1 / 1;+ min-width: 0;+ }++ &__when-after {+ @include preview-swap-hidden;+ }++ &__when-before {+ @include preview-swap-visible;+ }++ &__head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 0.5rem 0.75rem;+ border-bottom: 1px solid var(--color-border-primary);+ }++ &__title {+ font-size: 0.75rem;+ font-weight: 600;+ }++ // Chart card++ &__plot {+ padding: 0.75rem 0.75rem 0.25rem;+ }++ &__spark-area {+ fill: color-mix(in oklab, var(--alert-preview-accent) 13%, transparent);+ stroke: none;+ }++ &__spark-line {+ fill: none;+ stroke: color-mix(in oklab, var(--alert-preview-accent) 32%, transparent);+ stroke-width: 2;+ }++ // The moving bit: a short bright segment cycling along the line.+ &__spark-trace {+ fill: none;+ stroke: var(--alert-preview-accent);+ stroke-dasharray: 16 84;+ stroke-linecap: round;+ stroke-width: 2;+ animation: AlertPreview__trace 3.2s linear infinite;+ }++ // Threshold, drawn at the high value and moved down to the low one. The translation+ // is in user units, which the viewBox maps onto the plot's height.+ &__threshold-line {+ stroke: var(--color-text-tertiary);+ stroke-dasharray: 4 3;+ stroke-width: 1;+ transition: transform 300ms ease;+ }++ // The point where the series passes the lowered threshold.+ &__cross {+ opacity: 0;+ fill: var(--alert-preview-accent);+ transition: opacity 250ms ease;+ }++ &__threshold {+ display: flex;+ gap: 0.375rem;+ align-items: baseline;+ padding: 0.375rem 0.75rem 0.625rem;+ cursor: pointer;+ border-radius: var(--radius);+ }++ &__threshold-label {+ font-size: 0.625rem;+ color: var(--color-text-tertiary);+ }++ &__threshold-value {+ font-size: 0.75rem;+ font-weight: 600;+ font-variant-numeric: tabular-nums;++ @include preview-accent-text(var(--alert-preview-accent));+ }++ &__threshold-hint {+ margin-left: auto;+ font-size: 0.5625rem;+ color: var(--color-text-tertiary);+ text-align: right;+ }++ // Alerts list++ &__rows {+ display: flex;+ flex-direction: column;+ padding: 0.25rem 0.5rem;+ }++ &__row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto;+ gap: 0.5rem;+ align-items: center;+ padding: 0.375rem 0.5rem;+ border-radius: var(--radius);+ }++ &__row-main {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ min-width: 0;+ }++ &__row-title {+ overflow: hidden;+ font-size: 0.6875rem;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__row-meta {+ overflow: hidden;+ font-size: 0.5625rem;+ color: var(--color-text-tertiary);+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__pill {+ padding: 0.125rem 0.375rem;+ font-size: 0.5625rem;+ font-weight: 600;+ color: var(--color-text-tertiary);+ white-space: nowrap;+ background: var(--color-bg-fill-tertiary);+ border-radius: 999px;+ }++ &__pill--firing {+ background: color-mix(in oklab, var(--alert-preview-accent) 16%, var(--color-bg-surface-primary));++ @include preview-accent-text(var(--alert-preview-accent));+ }++ // Taller than the shared stat-card sparkline: the threshold moves within this box,+ // and the move has to be visible.+ &__spark-svg {+ height: 68px;+ }++ @include preview-sparkline;+}++// Firing state (user lowered the threshold)++.AlertPreview__checkbox:checked ~ * .AlertPreview__when-after {+ @include preview-swap-visible;+}++.AlertPreview__checkbox:checked ~ * .AlertPreview__when-before {+ @include preview-swap-hidden;+}++.AlertPreview__checkbox:checked ~ .AlertPreview__chart .AlertPreview__threshold-line {+ transform: translateY(12px);+}++.AlertPreview__checkbox:checked ~ .AlertPreview__chart .AlertPreview__cross {+ opacity: 1;+}++// The checkbox stays keyboard-focusable while visually hidden, so the threshold it+// labels needs a visible focus indicator (WCAG 2.4.7).+.AlertPreview__checkbox:focus-visible ~ .AlertPreview__chart .AlertPreview__threshold {+ outline: 2px solid var(--alert-preview-accent);+ outline-offset: -2px;+}++// Nudge attention at the threshold until it's moved.+.AlertPreview:not(.AlertPreview--static)+ .AlertPreview__checkbox:not(:checked)+ ~ .AlertPreview__chart+ .AlertPreview__threshold-value {+ animation: AlertPreview__pulse 2.4s ease-in-out infinite;+}++@keyframes AlertPreview__pulse {+ 0%,+ 100% {+ opacity: 1;+ }++ 50% {+ opacity: 0.45;+ }+}++// pathLength is normalized to 100, so the dash offset loops cleanly regardless of length.+@keyframes AlertPreview__trace {+ to {+ stroke-dashoffset: -100;+ }+}++// Storybook snapshots and reduced motion drop all ambient motion; lowering the+// threshold still fires the alert (transitions only).+@include preview-motion-guards('AlertPreview');diff --git a/products/alerts/frontend/emptyState/AlertsPreview.tsx b/products/alerts/frontend/emptyState/AlertsPreview.tsxnew file mode 100644index 000000000000..66d6762d00af--- /dev/null+++ b/products/alerts/frontend/emptyState/AlertsPreview.tsx@@ -0,0 +1,117 @@+import './AlertsPreview.scss'++import { LemonTag } from 'lib/lemon-ui/LemonTag'+import { cn } from 'lib/utils/css-classes'+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'++// Hand-authored weekly series climbing toward the threshold, so lowering the+// threshold puts the last two weeks above it.+const LINE = 'M 0 32 L 14 31 L 28 28 L 42 26 L 56 22 L 70 17 L 84 12 L 100 8'++function areaPath(line: string): string {+ return `${line} L 100 40 L 0 40 Z`+}++/**+ * Example-data preview for the alerts empty state: an insight being watched, and the+ * threshold that decides when it fires. Lowering the threshold puts the series above+ * it, so the alert fires and the notification it sent shows up in the list. One hidden+ * checkbox drives it via `:checked ~` styles - no timers or state, per the preview+ * rules in the `building-product-empty-states` skill. Before/after pairs share a+ * `__swap` grid cell and crossfade, so no row moves.+ */+export function AlertsPreview(): JSX.Element {+ const isStatic = inStorybook() || inStorybookTestRunner()++ return (+ <div className={cn('AlertPreview', isStatic && 'AlertPreview--static')}>+ {/* Firing state, before all cards so `:checked ~` can style them. */}+ <input type="checkbox" id="alert-preview-lower" className="AlertPreview__checkbox" />++ <div className="AlertPreview__chart">+ <div className="AlertPreview__head">+ <span className="AlertPreview__title">Weekly active users</span>+ <LemonTag size="small">example data</LemonTag>+ </div>++ <div className="AlertPreview__plot">+ <svg+ className="AlertPreview__spark-svg"+ viewBox="0 0 100 40"+ preserveAspectRatio="none"+ aria-hidden="true"+ >+ <path className="AlertPreview__spark-area" d={areaPath(LINE)} />+ <path className="AlertPreview__spark-line" d={LINE} vectorEffect="non-scaling-stroke" />+ <path+ className="AlertPreview__spark-trace"+ d={LINE}+ pathLength={100}+ vectorEffect="non-scaling-stroke"+ />+ <line+ className="AlertPreview__threshold-line"+ x1="0"+ x2="100"+ y1="6"+ y2="6"+ vectorEffect="non-scaling-stroke"+ />+ {/* Where the series passes the lowered threshold. The plot is scaled+ unevenly, so the marker is an ellipse that renders round. */}+ <ellipse className="AlertPreview__cross" cx="68" cy="18" rx="1.1" ry="2.5" />+ </svg>+ </div>++ <label htmlFor="alert-preview-lower" className="AlertPreview__threshold">+ <span className="AlertPreview__threshold-label">Notify me above</span>+ <span className="AlertPreview__threshold-value AlertPreview__swap">+ <span className="AlertPreview__when-before">12,000</span>+ <span className="AlertPreview__when-after">9,000</span>+ </span>+ <span className="AlertPreview__threshold-hint AlertPreview__swap">+ <span className="AlertPreview__when-before">Click to lower it</span>+ <span className="AlertPreview__when-after">Click to raise it back</span>+ </span>+ </label>+ </div>++ <div className="AlertPreview__panel">+ <div className="AlertPreview__head">+ <span className="AlertPreview__title">Alerts</span>+ </div>++ <div className="AlertPreview__rows">+ <div className="AlertPreview__row">+ <span className="AlertPreview__row-main">+ <span className="AlertPreview__row-title AlertPreview__swap">+ <span className="AlertPreview__when-before">Weekly active users above 12,000</span>+ <span className="AlertPreview__when-after">Weekly active users above 9,000</span>+ </span>+ <span className="AlertPreview__row-meta AlertPreview__swap">+ <span className="AlertPreview__when-before">Checked hourly</span>+ <span className="AlertPreview__when-after">Sent to #product-alerts, 2 minutes ago</span>+ </span>+ </span>+ <span className="AlertPreview__state AlertPreview__swap">+ <span className="AlertPreview__pill AlertPreview__when-before">Not firing</span>+ <span className="AlertPreview__pill AlertPreview__pill--firing AlertPreview__when-after">+ Firing+ </span>+ </span>+ </div>++ <div className="AlertPreview__row">+ <span className="AlertPreview__row-main">+ <span className="AlertPreview__row-title">Checkout errors above 20</span>+ <span className="AlertPreview__row-meta">Checked daily</span>+ </span>+ <span className="AlertPreview__state">+ <span className="AlertPreview__pill">Not firing</span>+ </span>+ </div>+ </div>+ </div>+ </div>+ )+}diff --git a/products/alerts/frontend/emptyState/AlertsPrimaryAction.tsx b/products/alerts/frontend/emptyState/AlertsPrimaryAction.tsxnew file mode 100644index 000000000000..70abb9b84ada--- /dev/null+++ b/products/alerts/frontend/emptyState/AlertsPrimaryAction.tsx@@ -0,0 +1,24 @@+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { urls } from 'scenes/urls'++import { AccessControlResourceType } from '~/types'++import { hasEffectiveResourceAccess } from '../utils'++/**+ * Create path for the alerts empty state. Insight alerts are created from an insight,+ * not from this scene, so the action sends the user to their insights. A user who+ * cannot read insights gets no button: their only alert kind is log alerts, which the+ * scene creates behind the setup screen.+ */+export function AlertsPrimaryAction(): JSX.Element | null {+ if (!hasEffectiveResourceAccess(AccessControlResourceType.Insight)) {+ return null+ }++ return (+ <LemonButton type="primary" to={urls.insights()} data-attr="alerts-browse-insights">+ Browse your insights+ </LemonButton>+ )+}diff --git a/products/alerts/frontend/emptyState/alertsEmptyState.tsx b/products/alerts/frontend/emptyState/alertsEmptyState.tsxnew file mode 100644index 000000000000..9f294013f4c1--- /dev/null+++ b/products/alerts/frontend/emptyState/alertsEmptyState.tsx@@ -0,0 +1,36 @@+import * as lifeguardPng from '@posthog/brand/hoggies/png/lifeguard'+import { IconBell } from '@posthog/icons'++import { pngHoggie } from 'lib/brand/hoggies'+import type { SceneProductEmptyState } from 'lib/components/ProductEmptyState/types'++import { ProductKey } from '~/queries/schema/schema-general'++import { AlertsPreview } from './AlertsPreview'+import { AlertsPrimaryAction } from './AlertsPrimaryAction'+import { alertsSetupLogic } from './alertsSetupLogic'++const HedgehogLifeguard = pngHoggie(lifeguardPng)++export const alertsEmptyState: SceneProductEmptyState = {+ statusLogic: alertsSetupLogic,+ config: {+ productKey: ProductKey.ALERTS,+ productName: 'Alerts',+ icon: <IconBell />,+ accentColor: 'var(--color-product-alerts-light)',+ accentColorDark: 'var(--color-product-alerts-dark)',+ hedgehog: HedgehogLifeguard,+ text: {+ 'needs-setup': {+ headline: 'Find out a metric moved without watching the dashboard',+ lead: 'An alert re-runs one insight or log search on a schedule and compares the result to a threshold you set. When the value crosses it, PostHog notifies you in Slack, Microsoft Teams, email, or a webhook, and keeps a record of every check it ran.',+ hint: 'Insight alerts start on the insight. Open one, then pick Alerts in its actions sidebar.',+ },+ },+ PrimaryAction: AlertsPrimaryAction,+ docsUrl: 'https://posthog.com/docs/alerts',+ previewLabel: 'An alert, once set',+ Preview: AlertsPreview,+ },+}diff --git a/products/alerts/frontend/emptyState/alertsSetupLogic.test.ts b/products/alerts/frontend/emptyState/alertsSetupLogic.test.tsnew file mode 100644index 000000000000..6d2897e0a95c--- /dev/null+++ b/products/alerts/frontend/emptyState/alertsSetupLogic.test.ts@@ -0,0 +1,78 @@+import { expectLogic } from 'kea-test-utils'++import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'+import * as appContext from 'lib/utils/getAppContext'++import { ProductKey } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType } from '~/types'++import * as logsApi from 'products/logs/frontend/generated/api'++import * as generatedApi from '../generated/api'+import { alertsSetupLogic } from './alertsSetupLogic'++// Guards the mapping into the app-wide setup-status layer: if it breaks, the scene+// empty-state gate strands on its spinner or shows the wrong surface.+describe('alertsSetupLogic', () => {+ let insightAlertsSpy: jest.SpyInstance+ let logAlertsSpy: jest.SpyInstance++ beforeEach(() => {+ insightAlertsSpy = jest.spyOn(generatedApi, 'alertsList')+ logAlertsSpy = jest.spyOn(logsApi, 'logsAlertsList')+ initKeaTests()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ async function mountAndReadStatus(): Promise<string> {+ const logic = alertsSetupLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ return productSetupStatusLogic({ productKey: ProductKey.ALERTS }).values.status+ }++ it.each([+ ['neither kind exists', 0, 0, 'needs-setup'],+ ['only insight alerts exist', 2, 0, 'has-data'],+ // The scene serves both kinds, so log alerts alone still count as set up.+ ['only log alerts exist', 0, 3, 'has-data'],+ ])('pushes %s as status %s', async (_name, insightAlerts, logAlerts, expected) => {+ insightAlertsSpy.mockResolvedValue({ count: insightAlerts, results: [] })+ logAlertsSpy.mockResolvedValue({ count: logAlerts, results: [] })+ expect(await mountAndReadStatus()).toBe(expected)+ })++ it('skips the kinds the user cannot read', async () => {+ jest.spyOn(appContext, 'getAppContext').mockReturnValue({+ effective_resource_access_control: {+ [AccessControlResourceType.Logs]: AccessControlLevel.None,+ },+ } as ReturnType<typeof appContext.getAppContext>)+ insightAlertsSpy.mockResolvedValue({ count: 0, results: [] })++ expect(await mountAndReadStatus()).toBe('needs-setup')+ expect(logAlertsSpy).not.toHaveBeenCalled()+ })++ it('leaves the scene to its access-denied screen when neither kind is readable', async () => {+ jest.spyOn(appContext, 'getAppContext').mockReturnValue({+ effective_resource_access_control: {+ [AccessControlResourceType.Insight]: AccessControlLevel.None,+ [AccessControlResourceType.Logs]: AccessControlLevel.None,+ },+ } as ReturnType<typeof appContext.getAppContext>)++ expect(await mountAndReadStatus()).toBe('unknown')+ expect(insightAlertsSpy).not.toHaveBeenCalled()+ })++ it('fails open to unknown when a count query fails before any answer', async () => {+ insightAlertsSpy.mockRejectedValue(new Error('network down'))+ logAlertsSpy.mockResolvedValue({ count: 0, results: [] })+ expect(await mountAndReadStatus()).toBe('unknown')+ })+})diff --git a/products/alerts/frontend/emptyState/alertsSetupLogic.ts b/products/alerts/frontend/emptyState/alertsSetupLogic.tsnew file mode 100644index 000000000000..56ee8d2c8bc2--- /dev/null+++ b/products/alerts/frontend/emptyState/alertsSetupLogic.ts@@ -0,0 +1,37 @@+import { createSetupDetectionLogic } from 'lib/components/ProductEmptyState/setupDetectionLogic'+import { projectLogic } from 'scenes/projectLogic'++import { ProductKey } from '~/queries/schema/schema-general'+import { AccessControlResourceType } from '~/types'++import { logsAlertsList } from 'products/logs/frontend/generated/api'++import { alertsList } from '../generated/api'+import { hasEffectiveResourceAccess } from '../utils'++/**+ * Setup detection for the alerts empty state. The scene serves both alert kinds, so+ * either one counts as set up - a project alerting only on logs must not be told it+ * has no alerts. Each kind is queried only when the user can see its tab, because a+ * kind they cannot read would answer 403 and fail the whole check.+ */+export const alertsSetupLogic = createSetupDetectionLogic({+ productKey: ProductKey.ALERTS,+ path: ['products', 'alerts', 'frontend', 'emptyState', 'alertsSetupLogic'],+ detect: async () => {+ const canViewInsightAlerts = hasEffectiveResourceAccess(AccessControlResourceType.Insight)+ const canViewLogAlerts = hasEffectiveResourceAccess(AccessControlResourceType.Logs)+ if (!canViewInsightAlerts && !canViewLogAlerts) {+ // The scene renders its own access-denied screen, which the setup screen must not hide.+ return 'unknown'+ }++ const projectId = String(projectLogic.findMounted()?.values.currentProjectId)+ const [insightAlerts, logAlerts] = await Promise.all([+ canViewInsightAlerts ? alertsList(projectId, { limit: 1 }) : null,+ canViewLogAlerts ? logsAlertsList(projectId, { limit: 1 }) : null,+ ])+ const count = (insightAlerts?.count ?? 0) + (logAlerts?.count ?? 0)+ return count > 0 ? 'has-data' : 'needs-setup'+ },+})diff --git a/products/alerts/frontend/utils.ts b/products/alerts/frontend/utils.tsindex 8319b3b41dc1..5b4660596b78 100644--- a/products/alerts/frontend/utils.ts+++ b/products/alerts/frontend/utils.ts@@ -1,6 +1,8 @@import { dayjs } from 'lib/dayjs'+import { getAppContext } from 'lib/utils/getAppContext'import { AlertState } from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType } from '~/types'import type { AlertCheck, AlertCheckDelivery } from './types'@@ -9,6 +11,10 @@ export enum AlertsTab {LOGS = 'logs',}+export function hasEffectiveResourceAccess(resourceType: AccessControlResourceType): boolean {+ return getAppContext()?.effective_resource_access_control?.[resourceType] !== AccessControlLevel.None+}+export function resolveSnoozeUntil(value: string): string {const relativeValue = value.match(/^\+(\d+)([mhdwMy])$/)if (!relativeValue) {diff --git a/products/alerts/frontend/views/Alerts.tsx b/products/alerts/frontend/views/Alerts.tsxindex 5cf3cd141c5e..c0939bf75b5b 100644--- a/products/alerts/frontend/views/Alerts.tsx+++ b/products/alerts/frontend/views/Alerts.tsx@@ -5,15 +5,14 @@ import { Suspense, useEffect } from 'react'import { LemonSkeleton, LemonTabs } from '@posthog/lemon-ui'import { AccessDenied } from 'lib/components/AccessDenied'-import { getAppContext } from 'lib/utils/getAppContext'import { lazyWithRetry } from 'lib/utils/retryImport'import { urls } from 'scenes/urls'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { AccessControlResourceType } from '~/types'import { AlertType } from '../types'-import { AlertsTab, getActiveAlertsTab, getAlertsTabs } from '../utils'+import { AlertsTab, getActiveAlertsTab, getAlertsTabs, hasEffectiveResourceAccess } from '../utils'const loadInsightAlerts = (): Promise<{ default: typeof import('./InsightAlerts').InsightAlerts }> =>import('./InsightAlerts').then((module) => ({ default: module.InsightAlerts }))@@ -36,10 +35,6 @@ const ALERTS_DESCRIPTION: Record<AlertsTab, string> = {[AlertsTab.LOGS]: 'Monitor matching logs and get notified when they cross a threshold.',}-function hasEffectiveResourceAccess(resourceType: AccessControlResourceType): boolean {- return getAppContext()?.effective_resource_access_control?.[resourceType] !== AccessControlLevel.None-}-function AlertsPanelSkeleton(): JSX.Element {return (<div className="space-y-4 p-4">diff --git a/products/alerts/frontend/views/InsightAlerts.tsx b/products/alerts/frontend/views/InsightAlerts.tsxindex 79d1f1ff4f43..10cd0cc177b5 100644--- a/products/alerts/frontend/views/InsightAlerts.tsx+++ b/products/alerts/frontend/views/InsightAlerts.tsx@@ -1,12 +1,9 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'import { IconEllipsis } from '@posthog/icons'import { LemonButton, LemonDialog, LemonMenu, LemonSwitch, Link, Tooltip } from '@posthog/lemon-ui'-import { pngHoggie } from 'lib/brand/hoggies'-import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'import { TZLabel } from 'lib/components/TZLabel'import type { LemonMenuItems } from 'lib/lemon-ui/LemonMenu'import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'@@ -14,7 +11,7 @@ import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'import { urls } from 'scenes/urls'-import { AlertState, ProductKey } from '~/queries/schema/schema-general'+import { AlertState } from '~/queries/schema/schema-general'import { AlertStateIndicator } from '../components/AlertDefinition'import { AlertsFiltersBar } from '../components/AlertsFiltersBar'@@ -26,8 +23,6 @@ import { AlertType } from '../types'import { EditAlertModal } from './EditAlertModal'import { AlertNotFoundModal } from './EditAlertModal/AlertNotFoundModal'-const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)-interface InsightAlertsProps {alertId: AlertType['id'] | null}@@ -82,7 +77,6 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {alertsResponseLoading,deletingAlertIds,pagination,- alertsCount,isFiltering,togglingAlertIds,alertDestinationCounts,@@ -224,28 +218,9 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {},]- const isEmpty = alertsCount === 0 && !alertsResponseLoading && !isFilteringconst alertForEditModal = alert ?? alertsSortedByState.find((candidate) => candidate.id === alertId)return (<>- {isEmpty && (- <ProductIntroduction- productName="Alerts"- productKey={ProductKey.ALERTS}- thingName="alert"- description="Alerts enable you to monitor your insight and notify you when certain conditions are met."- isEmpty- customHog={HedgehogMagnifyingGlass}- actionElementOverride={- <span className="italic">- To get started, open a <Link to={urls.insights()}>saved insight</Link>, then select Alerts- from the Actions sidebar.- </span>- }- mcpSurfaceKey="alerts.create"- />- )}-{alertForEditModal && (<EditAlertModalonClose={() => push(urls.alerts())}@@ -263,27 +238,28 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {<AlertNotFoundModal isOpen onClose={() => push(urls.alerts())} />)}- {isEmpty ? null : (- <>- <AlertsFiltersBar />- <LemonTable- loading={alertsResponseLoading}- columns={columns}- dataSource={alertsSortedByState}- noSortingCancellation- rowKey="id"- loadingSkeletonRows={5}- nouns={['alert', 'alerts']}- pagination={pagination}- rowClassName={(alert) => (alert.state === AlertState.NOT_FIRING ? null : 'highlighted')}- emptyState={- isFiltering ? (- <div className="py-8 text-center text-secondary">No alerts match your filters</div>- ) : undefined- }- />- </>- )}+ <AlertsFiltersBar />+ <LemonTable+ loading={alertsResponseLoading}+ columns={columns}+ dataSource={alertsSortedByState}+ noSortingCancellation+ rowKey="id"+ loadingSkeletonRows={5}+ nouns={['alert', 'alerts']}+ pagination={pagination}+ rowClassName={(alert) => (alert.state === AlertState.NOT_FIRING ? null : 'highlighted')}+ emptyState={+ isFiltering ? (+ <div className="py-8 text-center text-secondary">No alerts match your filters</div>+ ) : (+ <div className="py-8 text-center text-secondary">+ Insight alerts start on the insight. Open a <Link to={urls.insights()}>saved insight</Link>,+ then pick Alerts in its actions sidebar.+ </div>+ )+ }+ /></>)}diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsxindex 050135c30b74..088b5ac1ee29 100644--- a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx@@ -1,7 +1,6 @@import { useActions, useValues } from 'kea'-import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'-import { IconBell, IconEllipsis, IconPlus } from '@posthog/icons'+import { IconBell, IconEllipsis } from '@posthog/icons'import {LemonButton,LemonDialog,@@ -12,9 +11,7 @@ import {LemonTag,} from '@posthog/lemon-ui'-import { pngHoggie } from 'lib/brand/hoggies'import { MemberSelect } from 'lib/components/MemberSelect'-import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'import { TZLabel } from 'lib/components/TZLabel'import type { LemonMenuItems } from 'lib/lemon-ui/LemonMenu'import { LemonMenu } from 'lib/lemon-ui/LemonMenu'@@ -22,8 +19,6 @@ import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { urls } from 'scenes/urls'-import { ProductKey } from '~/queries/schema/schema-general'-import IconMicrosoftTeams from 'public/services/microsoft-teams.png'import IconSlack from 'public/services/slack.png'import IconWebhook from 'public/services/webhook.svg'@@ -46,8 +41,6 @@ const DESTINATION_TAGS = [{ type: NotificationDestinationTypeEnumApi.Teams, label: 'Teams', icon: IconMicrosoftTeams },] as const-const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)-function formatThreshold(alert: LogsAlertConfigurationApi): string {const operator = alert.threshold_operator === LogsAlertConfigurationThresholdOperatorEnumApi.Below ? '<' : '>'return `${operator} ${alert.threshold_count} in ${alert.window_minutes}m`@@ -269,30 +262,6 @@ export function LogsAlertList(): JSX.Element {},]- if (alerts.length === 0 && !createdByFilter && !alertsLoading) {- return (- <ProductIntroduction- productName="Logs alerts"- productKey={ProductKey.ALERTS}- thingName="logs alert"- description="Logs alerts notify you when matching logs cross a threshold."- isEmpty- customHog={HedgehogMagnifyingGlass}- actionElementOverride={- <LemonButton- type="primary"- icon={<IconPlus />}- onClick={openCreateAlertModal}- data-attr="logs-alerts-new"- >- Create alert- </LemonButton>- }- docsURL="https://posthog.com/docs/logs/alerts"- />- )- }-return (<div className="space-y-2"><div className="flex justify-end gap-2 flex-wrap">