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.

refactor(alerts): add reusable alert editor components (#72008)

Matt Puaf6123fb56d24
diff --git a/.agents/skills/adding-product-alerting/SKILL.md b/.agents/skills/adding-product-alerting/SKILL.md
index 4d1fa7c449ae..76ebae3b4536 100644
--- a/.agents/skills/adding-product-alerting/SKILL.md
+++ b/.agents/skills/adding-product-alerting/SKILL.md
@@ -4,7 +4,7 @@ description: >
Recommended repo-engineering guide when adding alerting to a PostHog product or
extending the shared alerts platform. Routes lifecycle state machines,
AlertPolicy, destinations, HogFunction dispatch, email, fixed-cadence and calendar
- scheduling, insight evaluation, and the AlertWizard. Use for product alert implementations,
+ scheduling, insight evaluation, the AlertWizard, and shared alert editor components. Use for product alert implementations,
shared destination types, lifecycle or scheduling options, advanced alert settings,
and platform alert infrastructure. Not for configuring alerts in an existing product.
---
@@ -24,6 +24,7 @@ This skill covers two jobs:
| Request | Path | Read |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------ |
| Add alerting to a product | Adopt | [adopting-platform-alerting.md](references/adopting-platform-alerting.md) |
+| Build or extend a product alert editor, destination UI, advanced options, or evaluation history | Frontend | [frontend-alerting.md](references/frontend-alerting.md) |
| Add a lifecycle rule, destination type, delivery behavior, schedule primitive, email capability, wizard option, or shared evaluation feature | Extend | [extending-platform-alerting.md](references/extending-platform-alerting.md) |
| Change behavior for one existing product | Adopt first | Keep it product-owned unless the behavior is reusable and backed by a real second use case |
| Understand ownership or choose the correct layer | Architecture | [architecture.md](references/architecture.md) |
@@ -41,7 +42,8 @@ Both paths must preserve these rules:
5. **Destinations are allowlisted.** Shared support does not automatically expose a destination in every product.
6. **Scheduling math is shared, eligibility is product-owned.** Reuse fixed-cadence, calendar-anchor, timezone, and schedule-restriction helpers from `products/alerts/backend/scheduling.py`. Keep model-specific due predicates and persistence with the adopter.
7. **Shared code has no product branches.** `common/alerting/` stays pure Python. Reusable Django behavior belongs in `products/alerts/backend/`.
-8. **Defaults remain backward compatible.** New platform options must preserve existing adopters until they explicitly opt in.
+8. **Frontend data is normalized at the product boundary.** Shared editor components render normalized definitions, destinations, advanced options, schedules, and history. Product API calls, payloads, and evaluation-specific fields stay in the product adapter.
+9. **Defaults remain backward compatible.** New platform options must preserve existing adopters until they explicitly opt in.
## Current limits
@@ -54,3 +56,4 @@ There is no generic alert base model, product registry, push-mode `submit_check(
| Layer ownership, public contracts, and reference adopters | [architecture.md](references/architecture.md) |
| Add alerting to a product | [adopting-platform-alerting.md](references/adopting-platform-alerting.md) |
| Extend shared alert infrastructure | [extending-platform-alerting.md](references/extending-platform-alerting.md) |
+| Build the product alert frontend | [frontend-alerting.md](references/frontend-alerting.md) |
diff --git a/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md b/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md
index e3cdacb2f329..0d67b4c1770c 100644
--- a/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md
+++ b/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md
@@ -110,15 +110,24 @@ Avoid large Temporal payloads. Pass alert IDs and references, then load data ins
## 8. Add the frontend
-Use the shared `AlertWizard` when the product creates HogFunction-backed alerts.
+Read [frontend-alerting.md](frontend-alerting.md), then choose the appropriate shared path.
+
+Use `AlertWizard` when the product creates HogFunction-backed alerts from trigger and destination templates.
- Configure a unique `logicKey`.
- Supply supported sub-template IDs, triggers, and destinations.
- Add product-specific configuration outside the shared wizard when it is not a reusable HogFunction input.
- Keep the traditional HogFunction editor as the advanced fallback when the product already supports it.
-- Ensure every network-backed action has loading and double-submit protection.
-A product may skip `AlertWizard` if it has no HogFunction destinations.
+Use the shared product alert components in `products/alerts/frontend/components/` when the product owns an alert configuration, evaluation rules, lifecycle state, destinations, and history.
+
+- Compose the form with `AlertEditor`, `AlertEditorFormDetails`, and `AlertEditorSection`.
+- Use the shared definition, schedule, next-evaluation, timezone, and advanced-options components for presentation.
+- Normalize destinations into `AlertNotificationDestinationEditor` view models while keeping supported types, payloads, grouping, and persistence product-owned.
+- Normalize numeric evaluations and current bounds into `AlertEvaluationHistoryChart`; keep the product history table or event timeline beside it.
+- Keep container sizing in the product modal, scene, or embedded section.
+
+A product may use either path or both. Ensure every network-backed action has loading and double-submit protection.
## 9. Verify the boundaries
diff --git a/.agents/skills/adding-product-alerting/references/architecture.md b/.agents/skills/adding-product-alerting/references/architecture.md
index 30370376ae12..98b49506025a 100644
--- a/.agents/skills/adding-product-alerting/references/architecture.md
+++ b/.agents/skills/adding-product-alerting/references/architecture.md
@@ -10,12 +10,29 @@ Use this reference to decide where code belongs before editing it.
| Shared alert infrastructure | `products/alerts/backend/` | Scheduling math, destination configuration and persistence, internal-event delivery, email transport, insight alert models/API, and insight evaluation |
| Product adapter | `products/<name>/backend/` | Domain evaluation, model snapshots, the single mutator, event payloads, allowed destinations, due queries, history, and orchestration |
| Shared alert creation UI | `frontend/src/lib/components/Alerting/AlertWizard/` | Reusable HogFunction destination, trigger, and configuration flow |
-| Product UI | `products/<name>/frontend/` or `frontend/src/scenes/<name>/` | Alert settings, product-specific fields, entry points, detail pages, and wizard configuration |
+| Shared product alert UI | `products/alerts/frontend/components/` | Container-agnostic editor layout, definition primitives, advanced options, destination editor, schedule presentation, and evaluation chart |
+| Product UI | `products/<name>/frontend/` or `frontend/src/scenes/<name>/` | Form logic, API calls, product fields, normalized adapters, entry points, detail tables, and wizard configuration |
-`products/logs` is the reference adopter for the shared lifecycle, fixed-cadence scheduling, HogFunction destinations, delivery rollback, and product-owned Temporal orchestration.
+`products/logs` is the reference adopter for the shared lifecycle, fixed-cadence scheduling, HogFunction destinations, delivery rollback, product-owned Temporal orchestration, and the shared product alert editor components.
Insight alerts are the reference adopter for shared calendar anchors, schedule restrictions, weekend skipping, and email delivery. Their model, API, query evaluation, and Django scheduling adapters live in `products/alerts/backend/` and `posthog/tasks/alerts/`. The evaluation package is shared across insight query kinds, but it is not a generic evaluator for unrelated products.
+## Frontend contract
+
+Shared product alert UI lives in `products/alerts/frontend/components/`. It is presentation infrastructure, not a frontend product registry.
+
+- `AlertEditor`, `AlertEditorFormDetails`, and `AlertEditorSection` provide the container-agnostic form shell.
+- `AlertDefinition*` components provide composable definition, schedule, next-evaluation, and timezone presentation.
+- `AlertAdvancedOptions` owns shared collapse and enabled-count behavior.
+- `AlertNotificationDestinationEditor` renders normalized saved and pending destinations.
+- `AlertEvaluationHistoryChart` renders normalized evaluation points and current thresholds.
+
+Products own keyed kea logic, API calls, form schemas, source/filter controls, supported destination types, HogFunction payloads, threshold conversion, enabled-count calculation, and history tables. Keep modals, scene widths, and embedded-section sizing in the product surface.
+
+`AlertWizard` remains the shared HogFunction creation flow. Adopters provide keyed `alertWizardLogic` props with supported sub-template IDs, `WizardTrigger[]`, `WizardDestination[]`, and optional URL or preset behavior. Backend destination support alone does not make an option available in the wizard.
+
+Read [frontend-alerting.md](frontend-alerting.md) before adding or extending a product alert frontend. Follow `frontend/src/AGENTS.md`, use generated API types, and guard network submissions from double clicks.
+
## Lifecycle contract
`common/alerting/state_machine.py` is pure Python.
@@ -79,11 +96,3 @@ Email callers use `send_alert_email(...)` through the facade. The caller owns re
Use the scheduler's real interval when computing shards. Use the same shard function when creating, updating, and advancing an alert.
Products translate their enums and stored payloads into the shared contract. Due eligibility, schedule persistence, retry behavior, and orchestration stay product-specific because model fields, states, snooze behavior, and tenant constraints differ.
-
-## Frontend contract
-
-`AlertWizard` is a shared HogFunction creation flow, not a lifecycle engine.
-
-Adopters provide keyed `alertWizardLogic` props with supported sub-template IDs, `WizardTrigger[]`, `WizardDestination[]`, and optional URL/preset behavior. Compatibility comes from HogFunction sub-templates. Backend destination support alone does not make an option available in the wizard.
-
-Keep product business logic in kea. Follow `frontend/src/AGENTS.md`, use generated API types, and guard network submissions from double clicks.
diff --git a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md
index 7b29a8412eee..8930669b57b4 100644
--- a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md
+++ b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md
@@ -80,6 +80,19 @@ For an advanced option on an existing destination, decide whether it is transpor
Do not route unrelated product evaluators through this package solely because it is named `evaluation`.
+### Shared product alert frontend
+
+Extend `products/alerts/frontend/components/` only when a second adopter has the same presentation contract.
+
+- Keep shared components container-agnostic and free of product-name branches.
+- Accept normalized definition rows, destination view models, evaluation points, thresholds, scheduling state, and enabled counts.
+- Keep API calls, form schemas, kea logic, payload construction, product filters, detector configuration, simulations, and history tables in product adapters.
+- Prefer small composable definition primitives over one component with optional props for every alert product.
+- Preserve pending destination retry behavior, loading states, and submit guards.
+- Add or update shared component stories and verify at least one insight and one logs path when changing a shared contract.
+
+Read [frontend-alerting.md](frontend-alerting.md) for the current component map and adoption workflow.
+
### AlertWizard
- Put business logic in keyed kea logic, not React hooks.
@@ -107,7 +120,8 @@ Verify both the shared layer and reference adopters:
- Destination, delivery, email, or evaluation tests for the changed contract.
- Logs tests for lifecycle, scheduling, HogFunction delivery, and rollback changes.
- Insight alert tests for model/API, evaluation, email, or calendar scheduling changes.
-- `AlertWizard` logic tests and at least one adopter path for frontend changes.
+- Shared alert component stories and at least one insight and one logs adopter path for frontend changes.
+- `AlertWizard` logic tests and at least one adopter path when the wizard contract changes.
- OpenAPI generation and frontend typecheck for API contract changes.
- The alert-state semgrep rule when lifecycle mutation paths change.
diff --git a/.agents/skills/adding-product-alerting/references/frontend-alerting.md b/.agents/skills/adding-product-alerting/references/frontend-alerting.md
new file mode 100644
index 000000000000..f749c64dafb0
--- /dev/null
+++ b/.agents/skills/adding-product-alerting/references/frontend-alerting.md
@@ -0,0 +1,96 @@
+# Build a product alert frontend
+
+Use this reference when adding or extending the alert editor, destinations, advanced settings, or evaluation history for a product.
+
+Read `frontend/src/AGENTS.md` before changing frontend code. Keep business logic in keyed kea logic and use `kea-forms` for persisted alert forms. Network-backed actions need loading and double-submit protection.
+
+## Choose the frontend path
+
+Use `AlertWizard` from `frontend/src/lib/components/Alerting/AlertWizard/` when the product is creating HogFunction-backed alerts from trigger and destination templates.
+
+Use the shared product alert editor components in `products/alerts/frontend/components/` when the product owns an alert configuration model, evaluation rules, lifecycle state, and history. Logs and insight alerts are the reference adopters.
+
+A product can use both paths when it has a simple HogFunction creation flow and a richer product-owned alert configuration surface.
+
+## Compose the shared editor
+
+Build the product form around these components:
+
+| Component | Purpose | Product responsibility |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
+| `AlertEditor` | Header, content, submit footer, loading, and changed-state behavior | Form logic, title, back/delete actions, and submit listener |
+| `AlertEditorFormDetails` | Shared name, enabled state, and activity row | Form field names and product activity content |
+| `AlertEditorSection` | Consistent section title, description, and spacing | Section content |
+| `AlertDefinitionRow` | Definition row layout | Source/filter pickers, mode controls, validation, normalized condition values, and product-specific previews |
+| `AlertNextEvaluationStatus`, `AlertTimezoneNotice` | Next-run state and timezone presentation | Cadence controls, evaluated window, scheduling state, and settings URL |
+| `AlertAdvancedOptions` | Collapsible advanced-options shell and enabled-count badge | Product-specific fields and enabled-count calculation |
+| `AlertNotificationDestinationEditor` | Existing and pending destination rows, Slack picker, URL input, and add/remove actions | Destination view models, supported destination types, payload construction, and persistence |
+| `AlertEvaluationHistoryChart` | Generic evaluation plot, current thresholds, historical firing state, and truncation copy | Normalized points, threshold adapters, totals, and the product history table |
+
+Do not add product branches to these components. Normalize product data before rendering and keep product API calls, payloads, and state in the product adapter.
+
+## Definition adapters
+
+Keep definition primitives small and composable. Products should normalize common concepts without forcing unrelated evaluators into one schema:
+
+- Render product source selectors or filters inside shared definition rows.
+- Render threshold modes directly with `LemonSegmentedButton` while keeping options and validation in product logic.
+- Map upper and lower bounds to product form fields. A product with a single comparator can expose one bound.
+- Keep anomaly detector configuration, insight series/funnel/SQL fields, logs filters, and simulation results product-owned.
+- Render cadence controls directly with existing Lemon components. Use `AlertNextEvaluationStatus` and `AlertTimezoneNotice` for shared presentation, while keeping cadence eligibility, entitlements, and due-time calculation product-owned.
+
+Avoid a giant generic definition component with optional props for every product. Prefer shared layout primitives plus typed product adapters. Do not create pass-through wrappers around Lemon components or layout-only `div` elements.
+
+## Destination adapters
+
+`AlertNotificationDestinationEditor` renders normalized view models. The product still owns:
+
+- Which destination types are allowed.
+- How a pending destination becomes HogFunction input.
+- How saved HogFunctions are grouped. Logs groups firing, resolved, and broken functions into one destination row.
+- Detail URLs, labels, enabled state, deletion, and loading state.
+- Email recipients or other product-specific notification controls outside the destination editor.
+
+Reuse shared destination constants and backend builders where applicable, but do not assume every product supports every shared destination type.
+
+## Evaluation history adapters
+
+Map product history into `AlertEvaluationHistoryPoint`:
+
+- `label`: formatted evaluation timestamp.
+- `value`: evaluated numeric value, count, score, or probability.
+- `firedAtTime`: whether that evaluation had the alert in a firing state at the time.
+
+Map current product rules into `AlertEvaluationThreshold` with a direction, value, and display label. Keep the product table or event timeline beside the chart because history detail columns and pagination remain domain-specific.
+
+Do not infer historical firing solely from the current threshold when persisted state exists. The chart distinguishes evaluations that fired at the time from evaluations that would fire under the current configuration.
+
+## Advanced options
+
+Use `AlertAdvancedOptions` for the shared collapse behavior. Calculate `enabledCount` from non-default product options.
+
+Keep the fields product-owned. Insight alerts use ongoing-period checks, weekend skipping, and quiet hours. Logs alerts use N-of-M noise reduction and notification cooldown. Share a field only after a second adopter has the same input contract and semantics.
+
+## Form and state rules
+
+- Put listeners, reducers, selectors, loaders, and API calls in keyed kea logic.
+- Bind product logic with `BindLogic` when multiple alerts can render simultaneously.
+- Use `Form` and `LemonField` for persisted fields.
+- Pass `isSubmitting`, `hasChanges`, and product pending changes into `AlertEditor`.
+- Flush pending destinations only after the alert exists, and preserve failed pending destinations for retry.
+- Keep container sizing in the product surface. Shared editor components must remain modal, scene, and embedded-section agnostic.
+
+## Storybook and verification
+
+Add or update stories for reusable shared components and product adapters.
+
+- Use real background tokens such as `bg-bg-primary` or `bg-surface-primary`; `bg-default` is a legacy text-color alias and paints a dark background in light mode.
+- Keep modal dimensions and borders in modal stories, not shared editor components.
+- Cover loading, disabled submit, pending destinations, existing destinations, threshold modes, and history points where they represent realistic regressions.
+
+Before finishing:
+
+1. Run targeted Oxfmt and Oxlint on changed files.
+2. Run `pnpm --filter=@posthog/frontend typescript:check` and separate changed-file failures from unrelated repository failures.
+3. Run the lowest-level relevant Jest or Storybook tests when behavior changed.
+4. Invoke `/writing-tests` before adding or substantially changing tests and `/writing-kea-logics` before changing product alert logic.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ad483dd5f18f..7260758f4a58 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -80,58 +80,6 @@ snapshots:
hash: v1.k794b7964.9f33b09ff241fc19c39fd800175395619537ea36383d1e53bfd3e28396521bcd.FxESBpXaR3nB54oSTRPMVCecF9ZLRokj3hwgzqj23CM
components-agentpromptbutton--size-variants--light:
hash: v1.k794b7964.a4689efd898e649cd3af89945355236bc837f4da4161933009509e6b1dd0351e.uJ14IIK2CgtcaD5jBRWDIJzC6hPogw9aVHjMJ7R0PTs
- components-alerts-alert-history-chart--anomaly-probability-cutoff--dark:
- hash: v1.k794b7964.d721f74acc814f7863950dd80f746a9db060206f7731fc3f0b82099122c0a222.o814bvlKu0MDHKOir97vr_kVFwZc3NorIr9y0agFMAY
- components-alerts-alert-history-chart--anomaly-probability-cutoff--light:
- hash: v1.k794b7964.c3a0573032b737df3f6c6aa6732b97224f63c9692bd9dc6ee6820afbcd15294e.aJNzfO5GFObISuXfjvoICPdP_dtC7iW_oiWJrH3Chm8
- components-alerts-alert-history-chart--daily-evaluation-time-axis--dark:
- hash: v1.k794b7964.4a7621325b0e6e0572a1e022df4d3c9fe1b4e2c8aca8c8c56db34e23e4183d18.FoBkLUKWWkyY-aoCiIR3IAIz7_05E3winnpYtT8V4so
- components-alerts-alert-history-chart--daily-evaluation-time-axis--light:
- hash: v1.k794b7964.4c4e4f4c3a5b0ac2b4560dd2758d033f08e5bab1ef8c06e7ad0ee6fde8721ee5.ojXt_ab--F2oSkWz7RJF597AIqr19iitifDqKvSPpvs
- components-alerts-alert-history-chart--default--dark:
- hash: v1.k794b7964.5495728d66c7d6058d5c2cb95109c35e9ade944e7671e44cb282fd8e427925f6.-D0FGYUxoxv6VvYH2o1_JW1pXdLB_yZcV8W77EyNotM
- components-alerts-alert-history-chart--default--light:
- hash: v1.k794b7964.08ff2b08126b1a76ad26ac2c808408eddde0f581efcee19e5d98a33be5307ed3.xRmz6MbT5-AEpvSMsmf8aqmGHJeNPDVh62DNiOfrCuI
- components-alerts-alert-history-chart--mixed-threshold-change--dark:
- hash: v1.k794b7964.8300d762473ef218f936506d76170d45ba044b7f347e7f2a16b67c53d870673a.hKVDH0Cg_iqlfFNquHZxNfb9nS_zpfyIOL0dO1M9WcE
- components-alerts-alert-history-chart--mixed-threshold-change--light:
- hash: v1.k794b7964.888efcd8d0ccb0315c7844f92bca4415a424667c13732b5f14af04d5b255edb9.ta52p8oUcf-p3VG0tV0x3CLFI7IoPaKMYFvPtPpiy-g
- components-alerts-alert-history-chart--monthly-evaluation-time-axis--dark:
- hash: v1.k794b7964.503a950ac6c86a0bc07977ceb4c23378540af08e56b2bf785b5536c82ff320dc.ZofvAjybHTUzYAknYnAxnogFYPEpnl_t1rZBHmM2o4k
- components-alerts-alert-history-chart--monthly-evaluation-time-axis--light:
- hash: v1.k794b7964.c1349dcc51c3ee553574def8974d1119a40dfb728bed7556968cf1d16950f66b.5H0Yu282wQJbQmhJmPiv1wa_-2ZFvYuZz1MRq4aKySo
- components-alerts-alert-history-chart--more-checks-than-chart-window--dark:
- hash: v1.k794b7964.fc5761ef47afd3806056a4c7de1f456b8a12b735441cf536d5f3e018633ea2ea.DwHMNdTJe75NabPCzELV_oRGMVSokyA1f-5Yz2ft2uA
- components-alerts-alert-history-chart--more-checks-than-chart-window--light:
- hash: v1.k794b7964.f2a112a1ef89cad67545e0729fb88cef81e0b813bc08d1069ef455c4abc46a59.SRI98D6k1eDo0efVUdLLcI6ZYvGlaEaTX9OpGC7CuVM
- components-alerts-alert-history-chart--percentage-thresholds--dark:
- hash: v1.k794b7964.55e07b218730e3ffb51fd5bccc580df1c1dd909a3768986298cf2e6e692aed82.eLw7bRog2ObAar3AhN-xH1YgmmK8nZI4AOc8AR6okiQ
- components-alerts-alert-history-chart--percentage-thresholds--light:
- hash: v1.k794b7964.a45dc230f8772563ba43154649728f1003e28a72dc8f629cf14c63e096f48177.bBNC4L-gDtmEQ40b0_KOQnxaRsGW5JmDbWMVpPGFh7E
- components-alerts-alert-history-chart--quiet-hours-hourly--dark:
- hash: v1.k794b7964.dd43162d7d7e6491e445b984f5c21ec8d7d5974ade65f17e914846b408e9d5a2.NuBNhmFfwBP48-4YyKRgdDjMCPcsxN3hnwhhkZX2uEk
- components-alerts-alert-history-chart--quiet-hours-hourly--light:
- hash: v1.k794b7964.cc7e6556b05e8b0360d48fcdf9551bb23e9fa006f506e7eb90ddb51851c9da68.ciTpTMt6y_s0v73UskDL2mq7hQdu_x92AJ3F8QBabX8
- components-alerts-alert-history-chart--skip-weekends-and-quiet-hours-hourly--dark:
- hash: v1.k794b7964.dff4d57901ad1af94b615d8a3528f31cbe48e87f503a22e7b853e1eccd103970.V2Co6QPp-4wq6yarmSEN8DfAO49XzY77w4zwnDQX9F0
- components-alerts-alert-history-chart--skip-weekends-and-quiet-hours-hourly--light:
- hash: v1.k794b7964.3ca19b353e4193fde84b3888db1a8786639022b88188acc8ce8fb25196e82aec.T0emSS-mIqJbbG1DX9sKvNZbMTXIAE_jn8kVy3xdGGA
- components-alerts-alert-history-chart--skip-weekends-daily--dark:
- hash: v1.k794b7964.090e180e325ac85ab9e835f4452e494bdfaf9c396ffa18cfaa393c356b191cf6.Sa1PvUeeVayDI-HD7Zhdaf7KD-cDG-DH8abOt-Suaao
- components-alerts-alert-history-chart--skip-weekends-daily--light:
- hash: v1.k794b7964.9e5377b16800d87e5a0a46cb24804b94e2ebfec00e8834e46db24684f6e35a35.7F36QYEjmEQFJEdGX4L_7amD1lISdlkfL9s2NW5lWUk
- components-alerts-alert-history-chart--skip-weekends-hourly--dark:
- hash: v1.k794b7964.d50d9885e11f36c679888d083854d55a95dc63ac19757d1b741c2747b680060a.9Mr8cFbCuNOv1_l-5DazyMFhg8W6Z7P1dPXozMOA0ik
- components-alerts-alert-history-chart--skip-weekends-hourly--light:
- hash: v1.k794b7964.bd92013bf2fd9b167d20fa30e1814f2ca6a376f692840b28cde7ecb3ec589e03.KVuhsmmnBbZbd86mMq41OYE1jyNqSXbfwU81LsSaiO0
- components-alerts-alert-history-chart--weekly-evaluation-time-axis--dark:
- hash: v1.k794b7964.bdb29bef0dbae358dd90db7571d1c8a855945cf33b0b7beb23cac9523dc1a8d5.UkbaVmXiZQYxWgk8qgGKyVDwp-ULgPGk8eqeiaEG40M
- components-alerts-alert-history-chart--weekly-evaluation-time-axis--light:
- hash: v1.k794b7964.2854d0413a885b33092968c9ab3c1238cef271f8f937f14fe428730f7ff967ba.WkUmRtsGw7rym9dsG4fZUHFLgWICVyTFa1uIVaIZwrg
- components-alerts-quiet-hours-fields--default--dark:
- hash: v1.k794b7964.aed02b7d152d7ac3360707fe6d6681d026e3bbd3d194d069d18927bf35618393.TbHCSBVg_dz4UL95FuefjNyGcbpNQ4bOg70IJsinWfU
- components-alerts-quiet-hours-fields--default--light:
- hash: v1.k794b7964.bc6c6320c27a2bd53fd67db6a6b4562bb2c1e8a0b39e760ce36a0c75c86f128c.fOLXgNlFvMhu536IkZoP75bSWwYw2fdWmfDr-1mxwcQ
components-bulkupdatetagsbutton--add-mode--dark:
hash: v1.k794b7964.ba66e3fd796ded95414954112b8e8ad07474b5be373cb4e98ecf3e56d8f61aab.jgsY9nY4c4c5rgf0ML5534zPOMlCIbIubJMaH2hRaig
components-bulkupdatetagsbutton--add-mode--light:
@@ -4694,6 +4642,78 @@ snapshots:
hash: v1.k794b7964.260c60a4a1510acae8062ebd7564bf8c3ea344b580b3c85a772605de98ad8397.AV2iNSkxr-Wh-w4qn5N6_OBQOWYf0bW8YKvlPnsBAfw
posthog-3000-keyboard-shortcut--within-tooltip--light:
hash: v1.k794b7964.aa2d9701c9134d5c374b6517f2fa542eb24c7e15ebf0d65f64efbc0ec2a99efa.BL1mMRm5CNDAmAMk-2pf-lp8EI6t65oBqoy990BdgyQ
+ products-alerts-alert-history-chart--anomaly-probability-cutoff--dark:
+ 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-shared-components--advanced-options--dark:
+ hash: v1.k794b7964.3e55fa3a531d4b4f54ad6ea4679723bbac806e94a02edc0dd38e58b8bedf1285.avRzgZ_I6aR1-LlDLhiKIy4RgMi_UJZjHnXi94wcnwY
+ products-alerts-shared-components--advanced-options--light:
+ hash: v1.k794b7964.c46dbad365b56790b429c0cce7c878c4cc354692272be6542b3ab4ae3df2a87e.pm2l849MobJC1-WUg10fqEsVVozy_mUZBIaB0DnK09Q
+ products-alerts-shared-components--definition--dark:
+ hash: v1.k794b7964.a786ddc6639b55018ea288780e70eb2cefacabfb93f35e8c15fe02f4fd4fbe0c.cYEymzCb4qyN2N9w3HPEf0W7DfGJhmFsmCSQi2PQVb8
+ 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
+ products-alerts-shared-components--editor--light:
+ hash: v1.k794b7964.bbc170e568523d203e413d0729dc756df98540fc6ea8a8d61e2685e1294580fe.eQXKeLusBVHchw_YgfEZkGqMCWvZCN9RyycW3yeFCng
+ products-alerts-shared-components--evaluation-history--dark:
+ hash: v1.k794b7964.453165acd1cbb101c12b290fe168d0fe04ae0f626fdae715e79f68fe69475caf.isZqjBZXk31Z7iMmwiTrmIFhJp6MdOLTWGJMtT6yUtQ
+ products-alerts-shared-components--evaluation-history--light:
+ hash: v1.k794b7964.4d156162bbf222b25d0bcea9f4be1c23c8c787a360b4b0bef507de7f361e8025.25EdkHo5WY5JPgsCWiwy4a_UjKJ594t0qnizfl_KW8A
+ products-alerts-shared-components--notifications--dark:
+ hash: v1.k794b7964.3f137bbf7a90843202ca75d89d5dec7f102945cf55f2c4532ccac3b4e8073c9b.phN1IPBCANIC0EsrGxopacxr96qniH5DnAm-ZnKVUz0
+ products-alerts-shared-components--notifications--light:
+ hash: v1.k794b7964.240b6085693c57e601cf978fe479a2cb6124c80c7cd743f44ff61744e94c90bb.v4D0nGdwscIlnUoeTqwHQsyEggk4eOm3GBGvgvFkXII
+ products-alerts-shared-components--quiet-hours--dark:
+ hash: v1.k794b7964.3a4e054512c5b607cf75f1cc3e6dd2212333d05e4fb89274b580b47f01e5aeaf.nPp2_jJIgcpjkQgHQA63v-eqzVox-oIfDi3SQKPdRis
+ products-alerts-shared-components--quiet-hours--light:
+ hash: v1.k794b7964.d562af4f5d4b2eb1566f5f378227e08f8743c6fab8ceb709d19c7bde3f80d8be.SFC4RHmaGUHYuisvesHu5mP7lE-6I5qKkIGFJCxlRwo
products-data-modeling-lineage-graph--canvas--dark:
hash: v1.k794b7964.cb415b8a2cb9697e353db5cd11808642c38d589431a0cb95cb1ddf632160eed8.ND20cRcJ3o2QK0K6DSbHBN66H2HwvcsKMd8tgfSITaY
products-data-modeling-lineage-graph--canvas--light:
diff --git a/products/alerts/frontend/components/AlertAdvancedOptions.tsx b/products/alerts/frontend/components/AlertAdvancedOptions.tsx
new file mode 100644
index 000000000000..25f40817cf21
--- /dev/null
+++ b/products/alerts/frontend/components/AlertAdvancedOptions.tsx
@@ -0,0 +1,39 @@
+import { ReactNode } from 'react'
+
+import { LemonCollapse } from '@posthog/lemon-ui'
+
+interface AlertAdvancedOptionsProps {
+ children: ReactNode
+ enabledCount?: number
+}
+
+export function AlertAdvancedOptions({ children, enabledCount = 0 }: AlertAdvancedOptionsProps): JSX.Element {
+ const countLabel = `${enabledCount} advanced option${enabledCount === 1 ? '' : 's'} on`
+
+ return (
+ <LemonCollapse
+ panels={[
+ {
+ key: 'advanced',
+ header: {
+ type: enabledCount > 0 ? 'primary' : 'tertiary',
+ children: (
+ <span className="flex w-full min-w-0 items-center justify-between gap-2">
+ <span className="min-w-0">Advanced options</span>
+ {enabledCount > 0 ? (
+ <span
+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-current/20 bg-current/10 text-xs font-semibold tabular-nums leading-none"
+ aria-label={countLabel}
+ >
+ {enabledCount}
+ </span>
+ ) : null}
+ </span>
+ ),
+ },
+ content: <div className="space-y-2">{children}</div>,
+ },
+ ]}
+ />
+ )
+}
diff --git a/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx b/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx
new file mode 100644
index 000000000000..d824c6409f95
--- /dev/null
+++ b/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx
@@ -0,0 +1,79 @@
+import { Group } from 'kea-forms'
+
+import { IconInfo } from '@posthog/icons'
+import { LemonCheckbox, Tooltip } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { AlertCalculationInterval } from '~/queries/schema/schema-general'
+
+import { AlertAdvancedOptions } from 'products/alerts/frontend/components/AlertAdvancedOptions'
+import { AlertFormType, ongoingIntervalField } from 'products/alerts/frontend/logic/alertFormLogic'
+import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+
+import { QuietHoursFields } from './QuietHoursFields'
+
+export interface AlertAdvancedOptionsSectionProps {
+ alertForm: AlertFormType
+ canCheckOngoingInterval: boolean
+ projectTimezone: string
+ enabledAdvancedOptionsCount: number
+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
+}
+
+export function AlertAdvancedOptionsSection({
+ alertForm,
+ canCheckOngoingInterval,
+ projectTimezone,
+ enabledAdvancedOptionsCount,
+ onSetAlertFormValue,
+}: AlertAdvancedOptionsSectionProps): JSX.Element {
+ const ongoing = ongoingIntervalField(alertForm.config, canCheckOngoingInterval)
+
+ return (
+ <AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount}>
+ {ongoing.show ? (
+ <Group name={['config']}>
+ <div className="flex gap-1">
+ <LemonField name="check_ongoing_interval">
+ <LemonCheckbox
+ checked={ongoing.checked}
+ data-attr="alertForm-check-ongoing-interval"
+ fullWidth
+ label="Check ongoing period"
+ disabledReason={ongoing.disabledReason}
+ />
+ </LemonField>
+ <Tooltip title={ongoing.tooltip} placement="right" delayMs={0}>
+ <IconInfo />
+ </Tooltip>
+ </div>
+ </Group>
+ ) : null}
+ <LemonField name="skip_weekend">
+ <LemonCheckbox
+ checked={
+ (alertForm.calculation_interval === AlertCalculationInterval.DAILY ||
+ isSubDailyAlertInterval(alertForm.calculation_interval)) &&
+ alertForm.skip_weekend
+ }
+ data-attr="alertForm-skip-weekend"
+ fullWidth
+ label="Skip checking on weekends"
+ disabledReason={
+ alertForm.calculation_interval !== AlertCalculationInterval.DAILY &&
+ !isSubDailyAlertInterval(alertForm.calculation_interval)
+ ? 'Can only skip weekend checking for 15-minute, hourly, or daily alerts'
+ : undefined
+ }
+ />
+ </LemonField>
+ <QuietHoursFields
+ scheduleRestriction={alertForm.schedule_restriction}
+ calculationInterval={alertForm.calculation_interval}
+ teamTimezone={projectTimezone}
+ onChange={(next) => onSetAlertFormValue('schedule_restriction', next)}
+ />
+ </AlertAdvancedOptions>
+ )
+}
diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsx
new file mode 100644
index 000000000000..019bfc0af151
--- /dev/null
+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx
@@ -0,0 +1,288 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { kea, path, useValues } from 'kea'
+import { Form, forms } from 'kea-forms'
+import { useState } from 'react'
+
+import type { LemonSegmentedButtonOption, LemonSelectOptions } from '@posthog/lemon-ui'
+import { LemonCheckbox, LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+
+import { AlertCalculationInterval } from '~/queries/schema/schema-general'
+
+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 {
+ AlertEvaluationHistoryChart,
+ AlertEvaluationHistoryPoint,
+ AlertEvaluationThreshold,
+} from './AlertEvaluationHistoryChart'
+import {
+ AlertNotificationDestinationEditor,
+ AlertNotificationDestinationView,
+ PendingAlertNotificationDestinationView,
+} from './AlertNotificationDestinationEditor'
+import { QuietHoursFields } from './QuietHoursFields'
+
+const alertEditorStoryLogic = kea([
+ path(['products', 'alerts', 'components', 'AlertComponents', 'story']),
+ forms({
+ alertForm: {
+ defaults: {
+ name: 'Error rate alert',
+ enabled: true,
+ },
+ submit: () => Promise.resolve(),
+ },
+ }),
+])
+
+function EditorStory(): JSX.Element {
+ const { alertForm } = useValues(alertEditorStoryLogic)
+ const [lastAction, setLastAction] = useState('No action selected')
+
+ return (
+ <div className="max-w-3xl border rounded bg-surface-primary">
+ <Form logic={alertEditorStoryLogic} formKey="alertForm" enableFormOnSubmit>
+ <AlertEditor
+ title="Edit alert"
+ description="Get notified when a condition is met."
+ onBack={() => setLastAction('Selected back')}
+ isEditing
+ isSubmitting={false}
+ hasChanges
+ onSubmitAttempted={() => setLastAction('Saved alert')}
+ leadingActions={
+ <LemonButton type="secondary" onClick={() => setLastAction('Selected delete')}>
+ Delete alert
+ </LemonButton>
+ }
+ >
+ <div className="space-y-6">
+ <AlertEditorFormDetails
+ enabled={{ checked: alertForm.enabled }}
+ activity={<p className="text-muted text-sm m-0">Created by Story User</p>}
+ />
+ <AlertEditorSection
+ title="Definition"
+ description="Product-specific alert conditions render inside shared sections."
+ >
+ <div className="border rounded p-3 text-sm">Alert when the error rate exceeds 5%.</div>
+ </AlertEditorSection>
+ <AlertEditorSection title="Notifications">
+ <div className="border rounded p-3 text-sm">Send a notification to #alerts.</div>
+ </AlertEditorSection>
+ <p className="text-muted m-0">{lastAction}</p>
+ </div>
+ </AlertEditor>
+ </Form>
+ </div>
+ )
+}
+
+type DefinitionMode = 'above' | 'below'
+
+const DEFINITION_MODE_OPTIONS: LemonSegmentedButtonOption<DefinitionMode>[] = [
+ { label: 'Above', value: 'above' },
+ { label: 'Below', value: 'below' },
+]
+
+function DefinitionStory(): JSX.Element {
+ const [mode, setMode] = useState<DefinitionMode>('above')
+ const [threshold, setThreshold] = useState('100')
+
+ return (
+ <div className="max-w-2xl space-y-5 border rounded bg-surface-primary p-4">
+ <AlertDefinitionRow label="Alert if event count is">
+ <LemonSegmentedButton value={mode} options={DEFINITION_MODE_OPTIONS} onChange={setMode} size="small" />
+ <LemonInput value={threshold} onChange={setThreshold} className="w-24" />
+ </AlertDefinitionRow>
+ <div className="space-y-2">
+ <AlertDefinitionRow label="Evaluate every">
+ <span className="font-semibold">15 minutes</span>
+ </AlertDefinitionRow>
+ <AlertNextEvaluationStatus>July 17, 2026 at 12:15 PM</AlertNextEvaluationStatus>
+ <AlertTimezoneNotice timezone="America/Toronto" settingsUrl="#project-settings" />
+ </div>
+ </div>
+ )
+}
+
+function AdvancedOptionsStory(): JSX.Element {
+ const [skipWeekends, setSkipWeekends] = useState(true)
+ const [quietHours, setQuietHours] = useState(true)
+ const enabledCount = Number(skipWeekends) + Number(quietHours)
+
+ return (
+ <div className="max-w-2xl border rounded bg-surface-primary p-4">
+ <AlertAdvancedOptions enabledCount={enabledCount}>
+ <LemonCheckbox checked={skipWeekends} onChange={setSkipWeekends} label="Skip weekend evaluations" />
+ <LemonCheckbox
+ checked={quietHours}
+ onChange={setQuietHours}
+ label="Pause notifications during quiet hours"
+ />
+ </AlertAdvancedOptions>
+ </div>
+ )
+}
+
+type StoryNotificationType = 'slack' | 'webhook'
+
+const NOTIFICATION_TYPE_OPTIONS: LemonSelectOptions<StoryNotificationType> = [
+ { label: 'Slack', value: 'slack' },
+ { label: 'Webhook', value: 'webhook' },
+]
+
+function NotificationsStory(): JSX.Element {
+ const [selectedType, setSelectedType] = useState<StoryNotificationType>('webhook')
+ const [urlValue, setUrlValue] = useState('https://example.com/alerts')
+ const [slackChannelValue, setSlackChannelValue] = useState<string | null>(null)
+ const [existingDestinations, setExistingDestinations] = useState<AlertNotificationDestinationView[]>([
+ {
+ key: 'existing-slack',
+ title: 'Slack: #product-alerts',
+ tags: [{ label: 'Active', type: 'success' }],
+ viewAction: { kind: 'button', label: 'View', url: '#destination' },
+ onDelete: () => setExistingDestinations([]),
+ },
+ ])
+ const [pendingDestinations, setPendingDestinations] = useState<PendingAlertNotificationDestinationView[]>([
+ {
+ key: 'pending-webhook',
+ label: 'Webhook: https://example.com/pending',
+ status: '(pending, save alert to apply)',
+ onRemove: () => setPendingDestinations([]),
+ },
+ ])
+
+ const addDestination = (): void => {
+ if (selectedType !== 'webhook' || !urlValue) {
+ return
+ }
+ setPendingDestinations((destinations) => [
+ ...destinations,
+ {
+ key: `pending-${destinations.length}`,
+ label: `Webhook: ${urlValue}`,
+ status: '(pending, save alert to apply)',
+ onRemove: () => setPendingDestinations([]),
+ },
+ ])
+ setUrlValue('')
+ }
+
+ let addDisabledReason: string | undefined
+ if (selectedType === 'slack') {
+ addDisabledReason = 'Connect Slack first'
+ } else if (!urlValue) {
+ addDisabledReason = 'Enter a webhook URL'
+ }
+
+ return (
+ <div className="max-w-2xl border rounded bg-surface-primary p-4">
+ <AlertNotificationDestinationEditor
+ description="Each destination receives alert state changes."
+ destinations={{
+ showExisting: true,
+ existingLoading: false,
+ existing: existingDestinations,
+ pending: pendingDestinations,
+ }}
+ notificationType={{
+ options: NOTIFICATION_TYPE_OPTIONS,
+ value: selectedType,
+ onChange: setSelectedType,
+ }}
+ slack={{
+ notificationType: 'slack',
+ channelValue: slackChannelValue,
+ onChannelValueChange: setSlackChannelValue,
+ }}
+ url={
+ selectedType === 'webhook'
+ ? {
+ input: { placeholder: 'https://example.com/webhook' },
+ value: urlValue,
+ onChange: setUrlValue,
+ }
+ : undefined
+ }
+ add={{ onClick: addDestination, disabledReason: addDisabledReason }}
+ />
+ </div>
+ )
+}
+
+function QuietHoursStory(): JSX.Element {
+ const [scheduleRestriction, setScheduleRestriction] = useState<ScheduleRestriction | null>({
+ blocked_windows: [{ start: '22:00', end: '07:00' }],
+ })
+
+ return (
+ <div className="max-w-2xl border rounded bg-surface-primary p-4">
+ <QuietHoursFields
+ scheduleRestriction={scheduleRestriction}
+ onChange={setScheduleRestriction}
+ teamTimezone="America/Toronto"
+ calculationInterval={AlertCalculationInterval.HOURLY}
+ />
+ </div>
+ )
+}
+
+const HISTORY_POINTS: AlertEvaluationHistoryPoint[] = [
+ { label: '11:00', value: 42 },
+ { label: '11:15', value: 48 },
+ { label: '11:30', value: 71, firedAtTime: true },
+ { label: '11:45', value: 64, firedAtTime: true },
+ { label: '12:00', value: 53, firedAtTime: false },
+ { label: '12:15', value: 38, firedAtTime: false },
+ { label: '12:30', value: 76, firedAtTime: true },
+]
+
+const HISTORY_THRESHOLDS: AlertEvaluationThreshold[] = [{ direction: 'upper', value: 60, label: 'Alert above 60' }]
+
+function EvaluationHistoryStory(): JSX.Element {
+ return (
+ <div className="max-w-3xl border rounded bg-surface-primary p-4">
+ <AlertEvaluationHistoryChart
+ points={HISTORY_POINTS}
+ valueLabel="Events"
+ thresholds={HISTORY_THRESHOLDS}
+ historyLimit={20}
+ evaluationsTotal={47}
+ evaluationNoun="evaluation"
+ tableAvailable
+ />
+ </div>
+ )
+}
+
+const meta: Meta = {
+ title: 'Products/Alerts/Shared components',
+ parameters: {
+ layout: 'fullscreen',
+ },
+ decorators: [
+ (Story): JSX.Element => (
+ <div className="min-h-screen bg-bg-primary p-4">
+ <Story />
+ </div>
+ ),
+ ],
+}
+
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const Editor: Story = { render: () => <EditorStory /> }
+export const Definition: Story = { render: () => <DefinitionStory /> }
+export const AdvancedOptions: Story = { render: () => <AdvancedOptionsStory /> }
+export const Notifications: Story = { render: () => <NotificationsStory /> }
+export const QuietHours: Story = { render: () => <QuietHoursStory /> }
+export const EvaluationHistory: Story = { render: () => <EvaluationHistoryStory /> }
diff --git a/products/alerts/frontend/components/AlertDefinition.tsx b/products/alerts/frontend/components/AlertDefinition.tsx
new file mode 100644
index 000000000000..b568d046881e
--- /dev/null
+++ b/products/alerts/frontend/components/AlertDefinition.tsx
@@ -0,0 +1,56 @@
+import { ReactNode } from 'react'
+
+import { IconCalendar, IconClock } from '@posthog/icons'
+import { Link } from '@posthog/lemon-ui'
+
+interface AlertDefinitionRowProps {
+ label?: ReactNode
+ children: ReactNode
+ className?: string
+}
+
+export function AlertDefinitionRow({ label, children, className }: AlertDefinitionRowProps): JSX.Element {
+ return (
+ <div className={`flex flex-wrap gap-x-3 gap-y-2 items-center${className ? ` ${className}` : ''}`}>
+ {label ? <div>{label}</div> : null}
+ {children}
+ </div>
+ )
+}
+
+interface AlertNextEvaluationStatusProps {
+ children: ReactNode
+ loading?: boolean
+}
+
+export function AlertNextEvaluationStatus({ children, loading = false }: AlertNextEvaluationStatusProps): JSX.Element {
+ return (
+ <div className="text-sm text-muted flex flex-wrap items-center gap-x-2 gap-y-0">
+ <IconClock
+ className={`size-4 shrink-0 text-muted motion-reduce:animate-none${loading ? ' animate-spin' : ''}`}
+ aria-hidden
+ />
+ <span className="shrink-0">Next planned evaluation:</span>
+ {children}
+ </div>
+ )
+}
+
+interface AlertTimezoneNoticeProps {
+ timezone: string
+ settingsUrl: string
+}
+
+export function AlertTimezoneNotice({ timezone, settingsUrl }: AlertTimezoneNoticeProps): JSX.Element {
+ return (
+ <div className="text-muted text-sm flex flex-wrap items-start gap-2">
+ <IconCalendar className="size-4 shrink-0 text-muted mt-0.5" aria-hidden />
+ <span className="min-w-0">
+ Times use your project timezone ({timezone}).{' '}
+ <Link to={settingsUrl} target="_blank" targetBlankIcon={false}>
+ Change in settings
+ </Link>
+ </span>
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx b/products/alerts/frontend/components/AlertDefinitionFields.tsx
similarity index 98%
rename from products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
rename to products/alerts/frontend/components/AlertDefinitionFields.tsx
index b84d758dfc44..bbc7adebf83e 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
+++ b/products/alerts/frontend/components/AlertDefinitionFields.tsx
@@ -8,6 +8,7 @@ import { alphabet } from 'lib/utils/strings'
import { AlertConditionType } from '~/queries/schema/schema-general'
+import { AlertDefinitionRow } from 'products/alerts/frontend/components/AlertDefinition'
import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
import {
funnelConfigForOptionKey,
@@ -38,8 +39,7 @@ export function TrendsDefinitionFields({
alertMode: 'detector' | 'threshold'
}): JSX.Element {
return (
- <div className="flex gap-3 items-center">
- <div>When</div>
+ <AlertDefinitionRow label="When">
<Group name={['config']}>
<LemonField name="series_index" className="flex-auto">
<LemonSelect
@@ -62,7 +62,7 @@ export function TrendsDefinitionFields({
/>
</LemonField>
</Group>
- </div>
+ </AlertDefinitionRow>
)
}
@@ -232,8 +232,7 @@ export function HogQLDefinitionFields({
const hasMultipleColumns = (hogqlColumns?.length ?? 0) > 1
return (
<>
- <div className="flex gap-3 items-center">
- <div>When</div>
+ <AlertDefinitionRow label="When">
<Group name={['config']}>
<LemonField name="evaluation" className="flex-auto">
{({ value, onChange }) => (
@@ -288,7 +287,7 @@ export function HogQLDefinitionFields({
</LemonField>
)}
</Group>
- </div>
+ </AlertDefinitionRow>
{hasMultipleColumns && (
<div className="flex gap-3 items-center">
<Tooltip title="Names the evaluated row in notifications and the check history.">
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx b/products/alerts/frontend/components/AlertDefinitionSection.tsx
similarity index 99%
rename from products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
rename to products/alerts/frontend/components/AlertDefinitionSection.tsx
index cd6d2ae828d7..9bdeb80f4ea4 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
+++ b/products/alerts/frontend/components/AlertDefinitionSection.tsx
@@ -15,6 +15,7 @@ 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 { getDefaultSimulationRange } from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { getDefaultAnomalyDetectorConfig } from 'products/alerts/frontend/logic/detectorConfigDefaults'
@@ -183,11 +184,11 @@ export function AlertDefinitionSection({
)}
{alertMode === 'threshold' ? (
- <div className="deprecated-space-y-2">
+ <div className="space-y-2">
{thresholdBoundsFormError ? (
<LemonBanner type="error">{thresholdBoundsFormError}</LemonBanner>
) : null}
- <div className="flex flex-wrap gap-x-3 gap-y-2 items-center">
+ <AlertDefinitionRow>
{supportsRelativeConditions && (
<Group name={['condition']}>
<LemonField name="type">
@@ -325,7 +326,7 @@ export function AlertDefinitionSection({
</LemonField>
</Group>
)}
- </div>
+ </AlertDefinitionRow>
</div>
) : (
<DetectorSelector
diff --git a/products/alerts/frontend/components/AlertEditor.tsx b/products/alerts/frontend/components/AlertEditor.tsx
new file mode 100644
index 000000000000..ff918c5ebdad
--- /dev/null
+++ b/products/alerts/frontend/components/AlertEditor.tsx
@@ -0,0 +1,151 @@
+import { ReactNode } from 'react'
+
+import { IconChevronLeft } from '@posthog/icons'
+import { LemonCheckbox, LemonInput } from '@posthog/lemon-ui'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { cn } from 'lib/utils/css-classes'
+
+export interface AlertEditorHeaderProps {
+ title: string
+ description?: string
+ onBack?: () => void
+}
+
+export function AlertEditorHeader({ title, description, onBack }: AlertEditorHeaderProps): JSX.Element {
+ return (
+ <div className="flex items-center gap-2">
+ {onBack ? (
+ <LemonButton
+ icon={<IconChevronLeft />}
+ onClick={onBack}
+ size="xsmall"
+ tooltip="Go back"
+ aria-label="Go back"
+ />
+ ) : null}
+ <div>
+ <h3 className="text-lg font-bold m-0">{title}</h3>
+ {description ? <p className="text-muted text-sm mt-2 mb-0">{description}</p> : null}
+ </div>
+ </div>
+ )
+}
+
+export interface AlertEditorActionsProps {
+ isEditing: boolean
+ isSubmitting: boolean
+ hasChanges: boolean
+ hasPendingChanges?: boolean
+ leadingActions?: ReactNode
+ onSubmitAttempted?: () => void
+}
+
+export function AlertEditorActions({
+ isEditing,
+ isSubmitting,
+ hasChanges,
+ hasPendingChanges = false,
+ leadingActions,
+ onSubmitAttempted,
+}: AlertEditorActionsProps): JSX.Element {
+ const disabledReason = isEditing && !hasChanges && !hasPendingChanges ? 'No changes to save' : undefined
+
+ return (
+ <>
+ {leadingActions ? <div className="flex-1">{leadingActions}</div> : null}
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ loading={isSubmitting}
+ disabledReason={disabledReason}
+ onClick={onSubmitAttempted}
+ >
+ {isEditing ? 'Save' : 'Create alert'}
+ </LemonButton>
+ </>
+ )
+}
+
+export interface AlertEditorProps extends AlertEditorHeaderProps, AlertEditorActionsProps {
+ children: ReactNode
+ className?: string
+ contentClassName?: string
+}
+
+export function AlertEditor({
+ title,
+ description,
+ onBack,
+ children,
+ className,
+ contentClassName,
+ ...actionsProps
+}: AlertEditorProps): JSX.Element {
+ return (
+ <div className={cn('flex flex-col', className)}>
+ <header className="border-b p-4">
+ <AlertEditorHeader title={title} description={description} onBack={onBack} />
+ </header>
+ <section className={cn('p-4', contentClassName)}>{children}</section>
+ <footer className="flex flex-wrap items-center justify-end gap-2 border-t p-4">
+ <AlertEditorActions {...actionsProps} />
+ </footer>
+ </div>
+ )
+}
+
+interface AlertEditorFormDetailsProps {
+ enabled?: {
+ checked: boolean
+ dataAttr?: string
+ }
+ activity?: ReactNode
+ nameDataAttr?: string
+}
+
+export function AlertEditorFormDetails({
+ enabled,
+ activity,
+ nameDataAttr = 'alertForm-name',
+}: AlertEditorFormDetailsProps): JSX.Element {
+ return (
+ <div className="space-y-4">
+ <div className="flex gap-4 items-center">
+ <LemonField className="flex-auto" name="name">
+ <LemonInput placeholder="Alert name" data-attr={nameDataAttr} />
+ </LemonField>
+ {enabled ? (
+ <LemonField name="enabled">
+ <LemonCheckbox
+ checked={enabled.checked}
+ data-attr={enabled.dataAttr}
+ fullWidth
+ label="Enabled"
+ />
+ </LemonField>
+ ) : null}
+ </div>
+ {activity}
+ </div>
+ )
+}
+
+interface AlertEditorSectionProps {
+ title: string
+ description?: ReactNode
+ children: ReactNode
+}
+
+export function AlertEditorSection({ title, 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>
+ {description ? <p className="text-xs text-secondary m-0">{description}</p> : null}
+ </div>
+ {children}
+ </section>
+ )
+}
diff --git a/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx b/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx
new file mode 100644
index 000000000000..a7a424967ad8
--- /dev/null
+++ b/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx
@@ -0,0 +1,327 @@
+import annotationPlugin from 'chartjs-plugin-annotation'
+import { useMemo } from 'react'
+
+import { Chart } from 'lib/Chart'
+import { useChart } from 'lib/hooks/useChart'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
+
+Chart.register(annotationPlugin)
+
+const ROLLING_WINDOW = 5
+
+type PointClassification = 'historical' | 'currentOnly' | 'none'
+
+export interface AlertEvaluationHistoryPoint {
+ label: string
+ value: number
+ firedAtTime?: boolean
+}
+
+export interface AlertEvaluationThreshold {
+ direction: 'upper' | 'lower'
+ value: number
+ label: string
+}
+
+interface AlertEvaluationHistoryChartProps {
+ points: AlertEvaluationHistoryPoint[]
+ valueLabel: string
+ thresholds: AlertEvaluationThreshold[]
+ historyLimit: number
+ evaluationsTotal?: number | null
+ evaluationNoun?: string
+ tableAvailable?: boolean
+ classifyUnusualWithoutThresholds?: boolean
+}
+
+function rollingMean(values: number[], window: number): number[] {
+ const boundedWindow = Math.max(1, Math.min(window, values.length))
+ const means: number[] = []
+ for (let index = 0; index < values.length; index++) {
+ const start = Math.max(0, index - boundedWindow + 1)
+ const slice = values.slice(start, index + 1)
+ means.push(slice.reduce((sum, value) => sum + value, 0) / slice.length)
+ }
+ return means
+}
+
+function detectSpikesAboveTrend(values: number[], trailingMean: number[]): boolean[] {
+ if (values.length === 0) {
+ return []
+ }
+ const minimum = Math.min(...values)
+ const maximum = Math.max(...values)
+ const range = maximum - minimum || Math.max(Math.abs(maximum), 1)
+ const globalMean = values.reduce((sum, value) => sum + value, 0) / values.length
+ const variance = values.reduce((sum, value) => sum + (value - globalMean) ** 2, 0) / values.length
+ const standardDeviation = Math.sqrt(variance) || range * 0.05
+
+ return values.map((value, index) => {
+ const baseline = trailingMean[index] ?? value
+ const margin = Math.max(0.12 * range, 0.85 * standardDeviation)
+ return value > baseline + margin
+ })
+}
+
+function matchesThreshold(value: number, thresholds: AlertEvaluationThreshold[]): boolean {
+ return thresholds.some((threshold) => {
+ if (threshold.direction === 'upper') {
+ return value > threshold.value
+ }
+ return value < threshold.value
+ })
+}
+
+function buildHistoryCaption(
+ displayedCount: number,
+ historyLimit: number,
+ evaluationsTotal: number | null | undefined,
+ evaluationNoun: string,
+ tableAvailable: boolean
+): string {
+ const recentEvaluations = (count: number): string =>
+ pluralize(count, `most recent ${evaluationNoun}`, `most recent ${evaluationNoun}s`)
+
+ if (evaluationsTotal != null && evaluationsTotal > historyLimit) {
+ const tableSuffix = tableAvailable ? ` Use the table for older ${evaluationNoun}s.` : ''
+ return `Chart includes at most the ${recentEvaluations(historyLimit)}, from ${pluralize(
+ evaluationsTotal,
+ evaluationNoun
+ )} total.${tableSuffix}`
+ }
+ if (displayedCount < historyLimit) {
+ return `Chart includes the ${recentEvaluations(displayedCount)}.`
+ }
+ if (evaluationsTotal == null && displayedCount === historyLimit) {
+ return `Chart includes at most the ${recentEvaluations(historyLimit)}.`
+ }
+ return `Chart includes the ${recentEvaluations(displayedCount)}.`
+}
+
+export function AlertEvaluationHistoryChart({
+ points,
+ valueLabel,
+ thresholds,
+ historyLimit,
+ evaluationsTotal,
+ evaluationNoun = 'check',
+ tableAvailable = false,
+ classifyUnusualWithoutThresholds = false,
+}: AlertEvaluationHistoryChartProps): JSX.Element {
+ const chartSeries = useMemo(
+ () => ({
+ values: points.map((point) => point.value),
+ labels: points.map((point) => point.label),
+ }),
+ [points]
+ )
+ const { values, labels } = chartSeries
+ const hasHistoricalFiringState = useMemo(() => points.some((point) => point.firedAtTime !== undefined), [points])
+
+ const pointClassifications = useMemo((): PointClassification[] => {
+ if (values.length === 0) {
+ return []
+ }
+ if (hasHistoricalFiringState) {
+ return points.map((point) => {
+ if (point.firedAtTime) {
+ return 'historical'
+ }
+ return matchesThreshold(point.value, thresholds) ? 'currentOnly' : 'none'
+ })
+ }
+ if (thresholds.length > 0) {
+ return values.map((value) => (matchesThreshold(value, thresholds) ? 'historical' : 'none'))
+ }
+ if (!classifyUnusualWithoutThresholds) {
+ return values.map(() => 'none')
+ }
+ const window = Math.min(ROLLING_WINDOW, Math.max(2, Math.ceil(values.length / 4)))
+ const trailingAverage = rollingMean(values, window)
+ return detectSpikesAboveTrend(values, trailingAverage).map((flagged) => (flagged ? 'historical' : 'none'))
+ }, [classifyUnusualWithoutThresholds, hasHistoricalFiringState, points, thresholds, values])
+
+ const thresholdAnnotations = useMemo(() => {
+ if (thresholds.length === 0) {
+ return undefined
+ }
+ return Object.fromEntries(
+ thresholds.map((threshold, index) => [
+ `${threshold.direction}-${index}`,
+ {
+ type: 'line' as const,
+ yMin: threshold.value,
+ yMax: threshold.value,
+ borderColor:
+ threshold.direction === 'upper' ? 'rgba(220, 38, 38, 0.72)' : 'rgba(234, 88, 12, 0.75)',
+ borderWidth: 1.5,
+ borderDash: [5, 4],
+ label: {
+ display: true,
+ content: threshold.label,
+ position: 'start' as const,
+ font: { size: 9 },
+ color: threshold.direction === 'upper' ? 'rgba(220, 38, 38, 0.95)' : 'rgba(234, 88, 12, 0.95)',
+ backgroundColor: 'transparent',
+ },
+ },
+ ])
+ )
+ }, [thresholds])
+
+ const { canvasRef } = useChart({
+ getConfig: () => ({
+ type: 'line' as const,
+ data: {
+ labels,
+ datasets: [
+ {
+ label: valueLabel,
+ data: values,
+ showLine: false,
+ borderWidth: 0,
+ backgroundColor: 'transparent',
+ fill: false,
+ pointRadius: (context) => (pointClassifications[context.dataIndex] === 'none' ? 4 : 4.5),
+ pointHoverRadius: (context) => (pointClassifications[context.dataIndex] === 'none' ? 5 : 5.5),
+ pointStyle: (context) => {
+ const classification = pointClassifications[context.dataIndex]
+ if (classification === 'historical') {
+ return 'rect'
+ }
+ if (classification === 'currentOnly') {
+ return 'triangle'
+ }
+ return 'circle'
+ },
+ pointBackgroundColor: (context) => {
+ const classification = pointClassifications[context.dataIndex]
+ if (classification === 'historical') {
+ return 'rgba(220, 38, 38, 0.92)'
+ }
+ if (classification === 'currentOnly') {
+ return 'rgba(234, 88, 12, 0.85)'
+ }
+ return 'transparent'
+ },
+ pointBorderColor: (context) => {
+ const classification = pointClassifications[context.dataIndex]
+ if (classification === 'historical') {
+ return 'rgba(127, 29, 29, 1)'
+ }
+ if (classification === 'currentOnly') {
+ return 'rgba(154, 52, 18, 1)'
+ }
+ return 'rgba(99, 102, 241, 0.95)'
+ },
+ pointBorderWidth: 1.75,
+ },
+ ],
+ },
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ interaction: { mode: 'nearest' as const, axis: 'x' as const, intersect: false },
+ plugins: {
+ legend: { display: false },
+ ...(thresholdAnnotations ? { annotation: { annotations: thresholdAnnotations } } : {}),
+ tooltip: {
+ enabled: true,
+ callbacks: {
+ title: (items) => (items[0] ? String(items[0].label) : ''),
+ label: (context) => {
+ const value = context.parsed.y
+ if (value == null || Number.isNaN(value)) {
+ return context.dataset.label ?? ''
+ }
+ const classification = pointClassifications[context.dataIndex]
+ let suffix = ''
+ if (classification === 'historical') {
+ suffix = hasHistoricalFiringState
+ ? ' (triggered the alert)'
+ : thresholds.length > 0
+ ? ' (outside threshold)'
+ : ' (unusual compared to recent values)'
+ } else if (classification === 'currentOnly') {
+ suffix = ' (would trigger the alert now)'
+ }
+ return `${valueLabel}: ${humanFriendlyNumber(value)}${suffix}`
+ },
+ },
+ },
+ },
+ scales: {
+ x: {
+ display: true,
+ ticks: { maxRotation: 45, minRotation: 0, autoSkip: true, maxTicksLimit: 6, font: { size: 9 } },
+ grid: { display: true, color: 'rgba(0,0,0,0.06)', drawTicks: false },
+ },
+ y: {
+ display: true,
+ position: 'left' as const,
+ ticks: {
+ maxTicksLimit: 5,
+ font: { size: 10 },
+ callback: (value: string | number) => humanFriendlyNumber(Number(value)),
+ },
+ grid: { color: 'rgba(0,0,0,0.06)' },
+ },
+ },
+ },
+ }),
+ deps: [chartSeries, valueLabel, thresholdAnnotations, pointClassifications, hasHistoricalFiringState],
+ })
+
+ const historicalCount = pointClassifications.filter((classification) => classification === 'historical').length
+ const currentOnlyCount = pointClassifications.filter((classification) => classification === 'currentOnly').length
+ const flaggedCount = historicalCount + currentOnlyCount
+ const historyCaption = useMemo(
+ () => buildHistoryCaption(points.length, historyLimit, evaluationsTotal, evaluationNoun, tableAvailable),
+ [evaluationNoun, evaluationsTotal, historyLimit, points.length, tableAvailable]
+ )
+
+ let summary = 'Each hollow dot is one evaluation.'
+ if (flaggedCount > 0) {
+ const summaryParts: string[] = []
+ if (historicalCount > 0) {
+ if (hasHistoricalFiringState) {
+ summaryParts.push(`${pluralize(historicalCount, evaluationNoun)} triggered the alert.`)
+ } else if (thresholds.length > 0) {
+ summaryParts.push(`${pluralize(historicalCount, evaluationNoun)} outside threshold.`)
+ } else {
+ summaryParts.push(`${pluralize(historicalCount, evaluationNoun)} flagged as unusual.`)
+ }
+ }
+ if (currentOnlyCount > 0) {
+ summaryParts.push(
+ `${pluralize(currentOnlyCount, evaluationNoun)} would trigger the alert under the current thresholds.`
+ )
+ }
+ summary = summaryParts.join(' ')
+ } else if (hasHistoricalFiringState) {
+ summary += ' Red squares mark evaluations that triggered the alert at the time they ran.'
+ } else if (thresholds.length > 0) {
+ summary += ' Red squares mark evaluations outside the configured threshold.'
+ } else if (classifyUnusualWithoutThresholds) {
+ summary += ' Red squares mark values flagged as unusual compared to recent values.'
+ }
+ if (thresholds.length > 0) {
+ summary += ' Dashed lines are the configured alert thresholds.'
+ }
+
+ return (
+ <div className="space-y-2">
+ <p className="text-muted text-xs mb-0">{historyCaption}</p>
+ <div className="h-56 w-full min-h-56">
+ <canvas ref={canvasRef} />
+ </div>
+ <p className="text-muted text-xs mb-0">{summary}</p>
+ {hasHistoricalFiringState && currentOnlyCount > 0 ? (
+ <p className="text-muted text-xs mb-0">
+ Red squares fired at the time they ran. Orange triangles would fire under the current thresholds.
+ </p>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx b/products/alerts/frontend/components/AlertIntervalRow.tsx
similarity index 57%
rename from products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx
rename to products/alerts/frontend/components/AlertIntervalRow.tsx
index 97a65bb968f1..eeda212530de 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx
+++ b/products/alerts/frontend/components/AlertIntervalRow.tsx
@@ -1,6 +1,5 @@
import { useValues } from 'kea'
-import { IconClock } from '@posthog/icons'
import { LemonSelect, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
@@ -12,6 +11,7 @@ import { userLogic } from 'scenes/userLogic'
import { AlertCalculationInterval } from '~/queries/schema/schema-general'
import { AvailableFeature } from '~/types'
+import { AlertDefinitionRow, AlertNextEvaluationStatus } from 'products/alerts/frontend/components/AlertDefinition'
import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
import {
cadenceFinerThanInsightInterval,
@@ -37,6 +37,19 @@ export interface AlertIntervalRowProps {
onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
}
+function getHogQLEvaluatedText(alertForm: AlertFormType): string {
+ if (!isHogQLAlertConfig(alertForm.config)) {
+ return ''
+ }
+ if (alertForm.config.evaluation === 'any_row') {
+ return 'and check every row of the result'
+ }
+ if (alertForm.config.evaluation === 'first_row') {
+ return "and evaluate the query's first (newest) row"
+ }
+ return "and evaluate the query's last (newest) row"
+}
+
export function AlertIntervalRow({
alertForm,
creatingNewAlert,
@@ -51,21 +64,54 @@ export function AlertIntervalRow({
const hasHighFrequencyAlertsEntitlement = hasAvailableFeature(AvailableFeature.HIGH_FREQUENCY_ALERTS)
const hasRealTimeAlertsEntitlement = hasAvailableFeature(AvailableFeature.REAL_TIME_ALERTS)
const realTimeAlertsEnabled = useFeatureFlag('ALERTS_REAL_TIME_INTERVAL')
- const hogqlEvaluation = isHogQLAlertConfig(alertForm.config) ? alertForm.config.evaluation : null
- const hogqlEvaluatedText =
- hogqlEvaluation === 'any_row'
- ? 'and check every row of the result'
- : hogqlEvaluation === 'first_row'
- ? "and evaluate the query's first (newest) row"
- : "and evaluate the query's last (newest) row"
+
+ let evaluatedWindow: JSX.Element
+ if (!supportsTimeWindow(alertForm.config)) {
+ evaluatedWindow = <div>{getHogQLEvaluatedText(alertForm)}</div>
+ } else {
+ const period =
+ isTrendsAlertConfig(alertForm.config) && alertForm.config.check_ongoing_interval ? 'current' : 'last'
+ evaluatedWindow = (
+ <div data-attr="alertForm-trend-interval">
+ and check {period}{' '}
+ <Tooltip
+ title={
+ <>
+ Set by the insight's <b>grouped by</b> interval. Edit the insight to change it.
+ </>
+ }
+ >
+ <span className="font-semibold underline decoration-dotted cursor-help">
+ {trendInterval ?? 'day'}
+ </span>
+ </Tooltip>
+ </div>
+ )
+ }
+
+ let nextEvaluation: JSX.Element | null = null
+ if (!creatingNewAlert && alert) {
+ let status: JSX.Element
+ if (nextPlannedEvaluationStale) {
+ status = <span>We'll recalculate this after you save.</span>
+ } else if (alert.next_check_at) {
+ status = <TZLabel time={alert.next_check_at} />
+ } else {
+ status = <span>We're calculating this. This can take a few minutes.</span>
+ }
+ nextEvaluation = (
+ <AlertNextEvaluationStatus loading={!nextPlannedEvaluationStale && !alert.next_check_at}>
+ {status}
+ </AlertNextEvaluationStatus>
+ )
+ }
+
+ const scheduleLabel =
+ alertForm.calculation_interval === AlertCalculationInterval.REAL_TIME ? 'Run alert' : 'Run alert every'
+
return (
- <>
- <div className="flex flex-wrap gap-x-3 gap-y-2 items-center">
- <div>
- {alertForm.calculation_interval === AlertCalculationInterval.REAL_TIME
- ? 'Run alert'
- : 'Run alert every'}
- </div>
+ <div className="space-y-2">
+ <AlertDefinitionRow label={scheduleLabel}>
<LemonField name="calculation_interval">
{({ value, onChange }) => (
<LemonSelect
@@ -76,7 +122,6 @@ export function AlertIntervalRow({
options={getAlertIntervalOptions(
hasHighFrequencyAlertsEntitlement,
hasRealTimeAlertsEntitlement,
- // Keep the option visible for alerts that already use it, even if the rollout flag is off
realTimeAlertsEnabled || value === AlertCalculationInterval.REAL_TIME
)}
onChange={(interval) => {
@@ -103,48 +148,9 @@ export function AlertIntervalRow({
/>
)}
</LemonField>
- {!supportsTimeWindow(alertForm.config) ? (
- // SQL queries own their time window — there is no insight interval to echo here,
- // so state what is actually evaluated instead of a trends-style "check last day".
- <div>{hogqlEvaluatedText}</div>
- ) : (
- <div data-attr="alertForm-trend-interval">
- and check{' '}
- {isTrendsAlertConfig(alertForm?.config) && alertForm.config.check_ongoing_interval
- ? 'current'
- : 'last'}{' '}
- <Tooltip
- title={
- <>
- Set by the insight's <b>grouped by</b> interval. Edit the insight to change it.
- </>
- }
- >
- <span className="font-semibold underline decoration-dotted cursor-help">
- {trendInterval ?? 'day'}
- </span>
- </Tooltip>
- </div>
- )}
- </div>
- {!creatingNewAlert && alert ? (
- <div className="text-sm text-muted flex flex-wrap items-center gap-x-2 gap-y-0">
- <IconClock
- className={`size-4 shrink-0 text-muted motion-reduce:animate-none${
- !nextPlannedEvaluationStale && !alert.next_check_at ? ' animate-spin' : ''
- }`}
- aria-hidden
- />
- <span className="shrink-0">Next planned evaluation:</span>
- {nextPlannedEvaluationStale ? (
- <span>We'll recalculate this after you save.</span>
- ) : alert.next_check_at ? (
- <TZLabel time={alert.next_check_at} />
- ) : (
- <span>We're calculating this. This can take a few minutes.</span>
- )}
- </div>
- ) : null}
- </>
+ {evaluatedWindow}
+ </AlertDefinitionRow>
+ {nextEvaluation}
+ </div>
)
}
diff --git a/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx
new file mode 100644
index 000000000000..98473a79b332
--- /dev/null
+++ b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx
@@ -0,0 +1,263 @@
+import { ReactNode } from 'react'
+
+import { IconExternal, IconTrash } from '@posthog/icons'
+import {
+ LemonButton,
+ LemonInput,
+ LemonSelect,
+ LemonSelectOptions,
+ LemonSkeleton,
+ LemonTag,
+ LemonTagType,
+} from '@posthog/lemon-ui'
+
+import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/SlackIntegrationHelpers'
+
+import { IntegrationType } from '~/types'
+
+interface AlertNotificationDestinationIconAction {
+ kind: 'icon'
+ url: string
+ tooltip: string
+ targetBlank?: boolean
+}
+
+interface AlertNotificationDestinationButtonAction {
+ kind: 'button'
+ label: string
+ url?: string
+ disabledReason?: string
+ dataAttr?: string
+}
+
+export interface AlertNotificationDestinationView {
+ key: string
+ title: string
+ detail?: string | null
+ tags?: { label: string; type?: LemonTagType }[]
+ viewAction?: AlertNotificationDestinationIconAction | AlertNotificationDestinationButtonAction
+ onDelete: () => void
+}
+
+export interface PendingAlertNotificationDestinationView {
+ key: string
+ label: string
+ status: string
+ onRemove: () => void
+}
+
+export interface AlertNotificationUrlInput {
+ placeholder: string
+ helpText?: ReactNode
+}
+
+interface AlertNotificationDestinationEditorProps<NotificationType extends string> {
+ description?: ReactNode
+ destinations: {
+ showExisting: boolean
+ existingLoading: boolean
+ existing: AlertNotificationDestinationView[]
+ pending: PendingAlertNotificationDestinationView[]
+ }
+ notificationType: {
+ options: LemonSelectOptions<NotificationType>
+ value: NotificationType
+ onChange: (type: NotificationType) => void
+ }
+ slack: {
+ notificationType: NotificationType
+ integration?: IntegrationType
+ channelValue: string | null
+ onChannelValueChange: (value: string | null) => void
+ }
+ url?: {
+ input: AlertNotificationUrlInput
+ value: string
+ onChange: (value: string) => void
+ }
+ add: {
+ onClick: () => void
+ disabledReason?: string
+ }
+}
+
+function DestinationViewAction({
+ action,
+}: {
+ action: AlertNotificationDestinationView['viewAction']
+}): JSX.Element | null {
+ if (!action) {
+ return null
+ }
+
+ switch (action.kind) {
+ case 'icon':
+ return (
+ <LemonButton
+ icon={<IconExternal />}
+ size="xsmall"
+ to={action.url}
+ targetBlank={action.targetBlank}
+ hideExternalLinkIcon
+ tooltip={action.tooltip}
+ />
+ )
+ case 'button':
+ return (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ to={action.url}
+ disabledReason={action.disabledReason}
+ data-attr={action.dataAttr}
+ >
+ {action.label}
+ </LemonButton>
+ )
+ default: {
+ const exhaustiveCheck: never = action
+ return exhaustiveCheck
+ }
+ }
+}
+
+function ExistingDestinations({
+ loading,
+ destinations,
+}: {
+ loading: boolean
+ destinations: AlertNotificationDestinationView[]
+}): JSX.Element | null {
+ if (loading) {
+ return <LemonSkeleton className="h-8" repeat={2} />
+ }
+
+ if (destinations.length === 0) {
+ return null
+ }
+
+ return (
+ <div className="space-y-2">
+ {destinations.map((destination) => (
+ <div key={destination.key} className="flex items-center justify-between border rounded p-2 gap-2">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-sm font-medium truncate">{destination.title}</span>
+ {destination.tags?.map((tag) => (
+ <LemonTag key={tag.label} type={tag.type} size="small">
+ {tag.label}
+ </LemonTag>
+ ))}
+ </div>
+ {destination.detail ? (
+ <span className="text-xs text-muted-alt truncate block">{destination.detail}</span>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ <DestinationViewAction action={destination.viewAction} />
+ <LemonButton
+ icon={<IconTrash />}
+ size="xsmall"
+ status="danger"
+ onClick={destination.onDelete}
+ tooltip="Delete notification"
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function PendingDestinations({
+ destinations,
+}: {
+ destinations: PendingAlertNotificationDestinationView[]
+}): JSX.Element | null {
+ if (destinations.length === 0) {
+ return null
+ }
+
+ return (
+ <div className="space-y-2">
+ {destinations.map((destination) => (
+ <div key={destination.key} className="flex items-center justify-between border rounded p-2 gap-2">
+ <span className="text-sm min-w-0 truncate flex flex-col">
+ {destination.label}
+ <span className="text-muted-alt">{destination.status}</span>
+ </span>
+ <LemonButton
+ icon={<IconTrash />}
+ size="xsmall"
+ status="danger"
+ onClick={destination.onRemove}
+ tooltip="Remove notification"
+ />
+ </div>
+ ))}
+ </div>
+ )
+}
+
+export function AlertNotificationDestinationEditor<NotificationType extends string>({
+ description,
+ destinations,
+ notificationType,
+ slack,
+ url,
+ add,
+}: AlertNotificationDestinationEditorProps<NotificationType>): JSX.Element {
+ let slackDestinationInput: JSX.Element | null = null
+ if (notificationType.value === slack.notificationType) {
+ if (slack.integration) {
+ slackDestinationInput = (
+ <SlackChannelPicker
+ value={slack.channelValue ?? undefined}
+ onChange={slack.onChannelValueChange}
+ integration={slack.integration}
+ />
+ )
+ } else {
+ slackDestinationInput = <SlackNotConfiguredBanner />
+ }
+ }
+
+ return (
+ <div className="space-y-4">
+ {description ? <p className="text-xs text-muted-alt m-0">{description}</p> : null}
+
+ {destinations.showExisting ? (
+ <ExistingDestinations loading={destinations.existingLoading} destinations={destinations.existing} />
+ ) : null}
+
+ <PendingDestinations destinations={destinations.pending} />
+
+ <div className="space-y-3 border rounded p-3">
+ <LemonSelect
+ fullWidth
+ options={notificationType.options}
+ value={notificationType.value}
+ onChange={notificationType.onChange}
+ />
+
+ {slackDestinationInput}
+
+ {url ? (
+ <div className="space-y-1">
+ <LemonInput
+ placeholder={url.input.placeholder}
+ value={url.value}
+ onChange={url.onChange}
+ fullWidth
+ />
+ {url.input.helpText ? <p className="text-xs text-muted-alt m-0">{url.input.helpText}</p> : null}
+ </div>
+ ) : null}
+
+ <LemonButton type="secondary" size="small" onClick={add.onClick} disabledReason={add.disabledReason}>
+ Add notification
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/components/editAlertModal/HogQLAlertPreview.tsx b/products/alerts/frontend/components/HogQLAlertPreview.tsx
similarity index 100%
rename from products/alerts/frontend/components/editAlertModal/HogQLAlertPreview.tsx
rename to products/alerts/frontend/components/HogQLAlertPreview.tsx
diff --git a/products/alerts/frontend/components/QuietHoursFields.stories.tsx b/products/alerts/frontend/components/QuietHoursFields.stories.tsx
deleted file mode 100644
index 7bb9a732d687..000000000000
--- a/products/alerts/frontend/components/QuietHoursFields.stories.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-import { useState } from 'react'
-
-import { AlertCalculationInterval } from '~/queries/schema/schema-general'
-
-import type { ScheduleRestriction } from 'products/alerts/frontend/types'
-
-import type { QuietHoursFieldsProps } from './QuietHoursFields'
-import { QuietHoursFields } from './QuietHoursFields'
-
-type QuietHoursStoryArgs = Omit<QuietHoursFieldsProps, 'scheduleRestriction' | 'onChange'> & {
- /** Quiet hours checkbox + initial state; include in host `key` so Storybook can reset. */
- quietHoursEnabled: boolean
- /** Seeds the first row until controls change (see `key` on the host). */
- windowStart: string
- windowEnd: string
-}
-
-function QuietHoursStoryHost({
- quietHoursEnabled,
- windowStart,
- windowEnd,
- teamTimezone,
- calculationInterval,
-}: QuietHoursStoryArgs): JSX.Element {
- const [scheduleRestriction, setScheduleRestriction] = useState<ScheduleRestriction | null>(() =>
- quietHoursEnabled ? { blocked_windows: [{ start: windowStart, end: windowEnd }] } : null
- )
-
- return (
- <QuietHoursFields
- scheduleRestriction={scheduleRestriction}
- onChange={setScheduleRestriction}
- teamTimezone={teamTimezone}
- calculationInterval={calculationInterval}
- />
- )
-}
-
-const meta: Meta<QuietHoursStoryArgs> = {
- title: 'Components/Alerts/Quiet hours fields',
- args: {
- quietHoursEnabled: true,
- windowStart: '22:00',
- windowEnd: '07:00',
- teamTimezone: 'America/New_York',
- calculationInterval: AlertCalculationInterval.HOURLY,
- },
- argTypes: {
- quietHoursEnabled: { control: 'boolean' },
- windowStart: { control: 'text' },
- windowEnd: { control: 'text' },
- calculationInterval: {
- control: 'select',
- options: Object.values(AlertCalculationInterval),
- },
- },
- render: (args) => (
- <div className="max-w-[600px]">
- <QuietHoursStoryHost
- key={`${args.quietHoursEnabled}-${args.windowStart}-${args.windowEnd}-${args.teamTimezone}-${args.calculationInterval}`}
- {...args}
- />
- </div>
- ),
-}
-export default meta
-
-type Story = StoryObj<typeof meta>
-
-export const Default: Story = {}
diff --git a/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
deleted file mode 100644
index 795049aeda85..000000000000
--- a/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { Group } from 'kea-forms'
-
-import { IconInfo } from '@posthog/icons'
-import { LemonCheckbox, LemonCollapse, Tooltip } from '@posthog/lemon-ui'
-
-import { LemonField } from 'lib/lemon-ui/LemonField'
-
-import { AlertCalculationInterval } from '~/queries/schema/schema-general'
-
-import { AlertFormType, ongoingIntervalField } from 'products/alerts/frontend/logic/alertFormLogic'
-import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
-
-import { QuietHoursFields } from '../QuietHoursFields'
-
-export interface AlertAdvancedOptionsSectionProps {
- alertForm: AlertFormType
- canCheckOngoingInterval: boolean
- projectTimezone: string
- enabledAdvancedOptionsCount: number
- onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
-}
-
-export function AlertAdvancedOptionsSection({
- alertForm,
- canCheckOngoingInterval: can_check_ongoing_interval,
- projectTimezone,
- enabledAdvancedOptionsCount,
- onSetAlertFormValue,
-}: AlertAdvancedOptionsSectionProps): JSX.Element {
- const ongoing = ongoingIntervalField(alertForm?.config, can_check_ongoing_interval)
- return (
- <div className="deprecated-space-y-2">
- <LemonCollapse
- panels={[
- {
- key: 'advanced',
- header: {
- type: enabledAdvancedOptionsCount > 0 ? 'primary' : 'tertiary',
- children: (
- <span className="flex w-full min-w-0 items-center justify-between gap-2">
- <span className="min-w-0">Advanced options</span>
- {enabledAdvancedOptionsCount > 0 ? (
- <span
- className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-current/20 bg-current/10 text-xs font-semibold tabular-nums leading-none"
- aria-label={`${enabledAdvancedOptionsCount} advanced option${
- enabledAdvancedOptionsCount === 1 ? '' : 's'
- } on`}
- >
- {enabledAdvancedOptionsCount}
- </span>
- ) : null}
- </span>
- ),
- },
- content: (
- <div className="space-y-2">
- {ongoing.show && (
- <Group name={['config']}>
- <div className="flex gap-1">
- <LemonField name="check_ongoing_interval">
- <LemonCheckbox
- checked={ongoing.checked}
- data-attr="alertForm-check-ongoing-interval"
- fullWidth
- label="Check ongoing period"
- disabledReason={ongoing.disabledReason}
- />
- </LemonField>
- <Tooltip title={ongoing.tooltip} placement="right" delayMs={0}>
- <IconInfo />
- </Tooltip>
- </div>
- </Group>
- )}
- <LemonField name="skip_weekend">
- <LemonCheckbox
- checked={
- (alertForm?.calculation_interval === AlertCalculationInterval.DAILY ||
- isSubDailyAlertInterval(
- alertForm?.calculation_interval ?? AlertCalculationInterval.DAILY
- )) &&
- alertForm?.skip_weekend
- }
- data-attr="alertForm-skip-weekend"
- fullWidth
- label="Skip checking on weekends"
- disabledReason={
- alertForm?.calculation_interval !== AlertCalculationInterval.DAILY &&
- !isSubDailyAlertInterval(
- alertForm?.calculation_interval ?? AlertCalculationInterval.DAILY
- ) &&
- 'Can only skip weekend checking for 15-minute, hourly, or daily alerts'
- }
- />
- </LemonField>
- <QuietHoursFields
- scheduleRestriction={alertForm.schedule_restriction}
- calculationInterval={alertForm.calculation_interval}
- teamTimezone={projectTimezone}
- onChange={(next) => onSetAlertFormValue('schedule_restriction', next)}
- />
- </div>
- ),
- },
- ]}
- />
- </div>
- )
-}
diff --git a/products/alerts/frontend/components/editAlertModal/editAlertModalUtils.tsx b/products/alerts/frontend/components/editAlertModalUtils.tsx
similarity index 100%
rename from products/alerts/frontend/components/editAlertModal/editAlertModalUtils.tsx
rename to products/alerts/frontend/components/editAlertModalUtils.tsx
diff --git a/products/alerts/frontend/views/AlertHistoryChart.stories.tsx b/products/alerts/frontend/views/AlertHistoryChart.stories.tsx
index 75d3fba8bb10..8b0615152f4f 100644
--- a/products/alerts/frontend/views/AlertHistoryChart.stories.tsx
+++ b/products/alerts/frontend/views/AlertHistoryChart.stories.tsx
@@ -190,7 +190,7 @@ function withHistoricalFirings(
}
const meta: Meta<typeof AlertHistoryChart> = {
- title: 'Components/Alerts/Alert history chart',
+ title: 'Products/Alerts/Alert history chart',
component: AlertHistoryChart,
args: {
historyLimit: CHART_CHECKS_LIMIT,
diff --git a/products/alerts/frontend/views/AlertHistoryChart.tsx b/products/alerts/frontend/views/AlertHistoryChart.tsx
index af38d9f992ec..fe969c633446 100644
--- a/products/alerts/frontend/views/AlertHistoryChart.tsx
+++ b/products/alerts/frontend/views/AlertHistoryChart.tsx
@@ -1,22 +1,17 @@
-import annotationPlugin from 'chartjs-plugin-annotation'
-import { useMemo } from 'react'
-
-import { Chart } from 'lib/Chart'
-import { useChart } from 'lib/hooks/useChart'
import { humanFriendlyNumber } from 'lib/utils/numbers'
-import { pluralize } from 'lib/utils/strings'
import { InsightThresholdType } from '~/queries/schema/schema-general'
+import {
+ AlertEvaluationHistoryChart,
+ AlertEvaluationThreshold,
+} from 'products/alerts/frontend/components/AlertEvaluationHistoryChart'
+
import type { AlertHistoryChartPoint } from '../logic/alertLogic'
import type { AlertType } from '../types'
export type { AlertHistoryChartPoint }
-Chart.register(annotationPlugin)
-
-const ROLLING_WINDOW = 5
-
type ThresholdLineMode = 'value' | 'anomaly_probability'
interface ChartThresholdContext {
@@ -27,33 +22,34 @@ interface ChartThresholdContext {
}
function getChartThresholdContext(alert: AlertType, chartPlotsAnomalyScore: boolean): ChartThresholdContext | null {
- const dc = alert.detector_config
- if (dc && typeof dc === 'object' && 'type' in dc) {
- if (dc.type === 'ensemble') {
+ const detectorConfig = alert.detector_config
+ if (detectorConfig && typeof detectorConfig === 'object' && 'type' in detectorConfig) {
+ if (detectorConfig.type === 'ensemble') {
return null
}
- if (dc.type === 'threshold') {
- const upper = 'upper_bound' in dc && typeof dc.upper_bound === 'number' ? dc.upper_bound : null
- const lower = 'lower_bound' in dc && typeof dc.lower_bound === 'number' ? dc.lower_bound : null
+ if (detectorConfig.type === 'threshold') {
+ const upper =
+ 'upper_bound' in detectorConfig && typeof detectorConfig.upper_bound === 'number'
+ ? detectorConfig.upper_bound
+ : null
+ const lower =
+ 'lower_bound' in detectorConfig && typeof detectorConfig.lower_bound === 'number'
+ ? detectorConfig.lower_bound
+ : null
if (upper == null && lower == null) {
return null
}
- return {
- lower,
- upper,
- boundType: 'absolute',
- lineMode: 'value',
- }
+ return { lower, upper, boundType: 'absolute', lineMode: 'value' }
}
if (
chartPlotsAnomalyScore &&
- 'threshold' in dc &&
- typeof dc.threshold === 'number' &&
- !Number.isNaN(dc.threshold)
+ 'threshold' in detectorConfig &&
+ typeof detectorConfig.threshold === 'number' &&
+ !Number.isNaN(detectorConfig.threshold)
) {
return {
lower: null,
- upper: dc.threshold,
+ upper: detectorConfig.threshold,
boundType: 'absolute',
lineMode: 'anomaly_probability',
}
@@ -61,58 +57,50 @@ function getChartThresholdContext(alert: AlertType, chartPlotsAnomalyScore: bool
return null
}
- const cfg = alert.threshold?.configuration
- const lower = cfg?.bounds?.lower ?? null
- const upper = cfg?.bounds?.upper ?? null
+ const thresholdConfiguration = alert.threshold?.configuration
+ const lower = thresholdConfiguration?.bounds?.lower ?? null
+ const upper = thresholdConfiguration?.bounds?.upper ?? null
if (lower == null && upper == null) {
return null
}
return {
lower,
upper,
- boundType: cfg?.type === InsightThresholdType.PERCENTAGE ? 'percentage' : 'absolute',
+ boundType: thresholdConfiguration?.type === InsightThresholdType.PERCENTAGE ? 'percentage' : 'absolute',
lineMode: 'value',
}
}
-function formatThresholdLabel(value: number, ctx: ChartThresholdContext): string {
- if (ctx.lineMode === 'anomaly_probability') {
- return `${Math.round(value * 100)}% prob.`
+function formatThresholdLabel(value: number, context: ChartThresholdContext): string {
+ if (context.lineMode === 'anomaly_probability') {
+ return `${Math.round(value * 100)}% probability`
}
- if (ctx.boundType === 'percentage') {
- return `${humanFriendlyNumber(value * 100)}% Δ`
+ if (context.boundType === 'percentage') {
+ return `${humanFriendlyNumber(value * 100)}% change`
}
return humanFriendlyNumber(value)
}
-function rollingMean(values: number[], window: number): number[] {
- const w = Math.max(1, Math.min(window, values.length))
- const out: number[] = []
- for (let i = 0; i < values.length; i++) {
- const start = Math.max(0, i - w + 1)
- const slice = values.slice(start, i + 1)
- out.push(slice.reduce((a, b) => a + b, 0) / slice.length)
- }
- return out
-}
-
-/** Upward deviation from trailing mean — good enough to eyeball spikes in alert history. */
-function detectSpikesAboveTrend(values: number[], trailingMean: number[]): boolean[] {
- if (values.length === 0) {
+function buildThresholds(context: ChartThresholdContext | null): AlertEvaluationThreshold[] {
+ if (!context) {
return []
}
- const minV = Math.min(...values)
- const maxV = Math.max(...values)
- const range = maxV - minV || Math.max(Math.abs(maxV), 1)
- const globalMean = values.reduce((a, b) => a + b, 0) / values.length
- const variance = values.reduce((s, v) => s + (v - globalMean) ** 2, 0) / values.length
- const std = Math.sqrt(variance) || range * 0.05
-
- return values.map((v, i) => {
- const baseline = trailingMean[i] ?? v
- const margin = Math.max(0.12 * range, 0.85 * std)
- return v > baseline + margin
- })
+ const thresholds: AlertEvaluationThreshold[] = []
+ if (context.upper != null) {
+ thresholds.push({
+ direction: 'upper',
+ value: context.upper,
+ label: `Upper (${formatThresholdLabel(context.upper, context)})`,
+ })
+ }
+ if (context.lower != null) {
+ thresholds.push({
+ direction: 'lower',
+ value: context.lower,
+ label: `Lower (${formatThresholdLabel(context.lower, context)})`,
+ })
+ }
+ return thresholds
}
export function AlertHistoryChart({
@@ -127,309 +115,21 @@ export function AlertHistoryChart({
valueLabel: string
alert: AlertType
chartPlotsAnomalyScore: boolean
- /** Max number of newest checks loaded for this chart (matches API `checks_limit`). */
historyLimit: number
- /** Total checks for this alert when known (retrieve only); used to explain truncation. */
checksTotal?: number | null
}): JSX.Element {
- const chartSeriesComputeds = useMemo(() => {
- const values = points.map((p) => p.value)
- const labels = points.map((p) => p.label)
- return { values, labels }
- }, [points])
-
- const { values, labels } = chartSeriesComputeds
-
- const thresholdCtx = useMemo(
- () => getChartThresholdContext(alert, chartPlotsAnomalyScore),
- [alert, chartPlotsAnomalyScore]
- )
-
- const hasHistoricalFiringState = useMemo(() => points.some((p) => p.firedAtTime !== undefined), [points])
-
- /**
- * Per-point visual state:
- * 'historical' — check actually fired at the time it ran (recorded on AlertCheck.state)
- * 'currentOnly' — didn't fire then, but would fire under the *current* thresholds (threshold tightened since)
- * 'none' — didn't fire then, wouldn't fire now
- *
- * When no historical state is present (e.g. Storybook fixtures), falls back to treating the current-threshold
- * / spike-heuristic match as 'historical' — preserves the pre-existing single-color behaviour for those cases.
- */
- const pointClass = useMemo((): ('historical' | 'currentOnly' | 'none')[] => {
- if (values.length === 0) {
- return []
- }
- const upper = thresholdCtx?.upper ?? null
- const lower = thresholdCtx?.lower ?? null
- const currentRuleFlag = (v: number): boolean => {
- if (upper != null && v > upper) {
- return true
- }
- if (lower != null && v < lower) {
- return true
- }
- return false
- }
- const canReapplyCurrentRule = upper != null || lower != null
-
- if (hasHistoricalFiringState) {
- return points.map((p, i) => {
- if (p.firedAtTime) {
- return 'historical'
- }
- if (canReapplyCurrentRule && currentRuleFlag(values[i])) {
- return 'currentOnly'
- }
- return 'none'
- })
- }
- if (canReapplyCurrentRule) {
- return values.map((v) => (currentRuleFlag(v) ? 'historical' : 'none'))
- }
- const window = Math.min(ROLLING_WINDOW, Math.max(2, Math.ceil(values.length / 4)))
- const trailingAvg = rollingMean(values, window)
- const spikeFlags = detectSpikesAboveTrend(values, trailingAvg)
- return spikeFlags.map((flag) => (flag ? 'historical' : 'none'))
- }, [values, points, thresholdCtx, hasHistoricalFiringState])
-
- const thresholdAnnotations = useMemo(() => {
- if (!thresholdCtx) {
- return undefined
- }
- const annotations: Record<string, Record<string, unknown>> = {}
- if (thresholdCtx.upper != null) {
- annotations.upperThreshold = {
- type: 'line',
- yMin: thresholdCtx.upper,
- yMax: thresholdCtx.upper,
- borderColor: 'rgba(220, 38, 38, 0.72)',
- borderWidth: 1.5,
- borderDash: [5, 4],
- label: {
- display: true,
- content: `Upper (${formatThresholdLabel(thresholdCtx.upper, thresholdCtx)})`,
- position: 'start',
- font: { size: 9 },
- color: 'rgba(220, 38, 38, 0.95)',
- backgroundColor: 'transparent',
- },
- }
- }
- if (thresholdCtx.lower != null) {
- annotations.lowerThreshold = {
- type: 'line',
- yMin: thresholdCtx.lower,
- yMax: thresholdCtx.lower,
- borderColor: 'rgba(234, 88, 12, 0.75)',
- borderWidth: 1.5,
- borderDash: [5, 4],
- label: {
- display: true,
- content: `Lower (${formatThresholdLabel(thresholdCtx.lower, thresholdCtx)})`,
- position: 'start',
- font: { size: 9 },
- color: 'rgba(234, 88, 12, 0.95)',
- backgroundColor: 'transparent',
- },
- }
- }
- return Object.keys(annotations).length > 0 ? annotations : undefined
- }, [thresholdCtx])
-
- const { canvasRef } = useChart({
- getConfig: () => ({
- type: 'line' as const,
- data: {
- labels,
- datasets: [
- {
- label: valueLabel,
- data: values,
- showLine: false,
- borderWidth: 0,
- backgroundColor: 'transparent',
- fill: false,
- pointRadius: (ctx) => (pointClass[ctx.dataIndex] === 'none' ? 4 : 4.5),
- pointHoverRadius: (ctx) => (pointClass[ctx.dataIndex] === 'none' ? 5 : 5.5),
- // Shape encodes category so it's legible without relying on red/orange alone:
- // historical -> square, currentOnly -> triangle, none -> circle.
- pointStyle: (ctx) => {
- const cls = pointClass[ctx.dataIndex]
- if (cls === 'historical') {
- return 'rect'
- }
- if (cls === 'currentOnly') {
- return 'triangle'
- }
- return 'circle'
- },
- pointBackgroundColor: (ctx) => {
- const cls = pointClass[ctx.dataIndex]
- if (cls === 'historical') {
- return 'rgba(220, 38, 38, 0.92)'
- }
- if (cls === 'currentOnly') {
- return 'rgba(234, 88, 12, 0.85)'
- }
- return 'transparent'
- },
- pointBorderColor: (ctx) => {
- const cls = pointClass[ctx.dataIndex]
- if (cls === 'historical') {
- return 'rgba(127, 29, 29, 1)'
- }
- if (cls === 'currentOnly') {
- return 'rgba(154, 52, 18, 1)'
- }
- return 'rgba(99, 102, 241, 0.95)'
- },
- pointBorderWidth: 1.75,
- },
- ],
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- interaction: { mode: 'nearest' as const, axis: 'x' as const, intersect: false },
- plugins: {
- legend: {
- display: false,
- },
- ...(thresholdAnnotations ? { annotation: { annotations: thresholdAnnotations } } : {}),
- tooltip: {
- enabled: true,
- callbacks: {
- title: (items) => (items[0] ? String(items[0].label) : ''),
- label: (ctx) => {
- const y = ctx.parsed.y
- if (y == null || Number.isNaN(y)) {
- return ctx.dataset.label ?? ''
- }
- const formatted = humanFriendlyNumber(y)
- const cls = pointClass[ctx.dataIndex]
- let tag = ''
- if (cls === 'historical') {
- tag = hasHistoricalFiringState
- ? ' (triggered the alert)'
- : thresholdCtx && (thresholdCtx.upper != null || thresholdCtx.lower != null)
- ? ' (outside threshold)'
- : ' (unusual compared to recent values)'
- } else if (cls === 'currentOnly') {
- tag = ' (would trigger the alert now)'
- }
- return `${valueLabel}: ${formatted}${tag}`
- },
- },
- },
- },
- scales: {
- x: {
- display: true,
- ticks: {
- maxRotation: 45,
- minRotation: 0,
- autoSkip: true,
- maxTicksLimit: 6,
- font: { size: 9 },
- },
- grid: { display: true, color: 'rgba(0,0,0,0.06)', drawTicks: false },
- },
- y: {
- display: true,
- position: 'left' as const,
- ticks: {
- maxTicksLimit: 5,
- font: { size: 10 },
- callback: (value: string | number) => humanFriendlyNumber(Number(value)),
- },
- grid: { color: 'rgba(0,0,0,0.06)' },
- },
- },
- },
- }),
- deps: [
- chartSeriesComputeds,
- valueLabel,
- thresholdAnnotations,
- pointClass,
- thresholdCtx,
- hasHistoricalFiringState,
- ],
- })
-
- const historicalCount = pointClass.filter((c) => c === 'historical').length
- const currentOnlyCount = pointClass.filter((c) => c === 'currentOnly').length
- const flaggedCount = historicalCount + currentOnlyCount
-
- const historyCaption = useMemo((): string => {
- const displayedCount = points.length
- const recentChecksPhrase = (n: number): string => pluralize(n, 'most recent check', 'most recent checks')
- if (checksTotal != null && checksTotal > historyLimit) {
- return `Chart includes at most the ${recentChecksPhrase(historyLimit)}, from ${pluralize(checksTotal, 'check')} total. Use the table for older checks.`
- }
- if (displayedCount < historyLimit) {
- return `Chart includes the ${recentChecksPhrase(displayedCount)}.`
- }
- if (checksTotal == null && displayedCount === historyLimit) {
- return `Chart includes at most the ${recentChecksPhrase(historyLimit)}.`
- }
- return `Chart includes the ${recentChecksPhrase(displayedCount)}.`
- }, [historyLimit, checksTotal, points.length])
+ const thresholdContext = getChartThresholdContext(alert, chartPlotsAnomalyScore)
return (
- <div className="space-y-2">
- <p className="text-muted text-xs mb-0">{historyCaption}</p>
- <div className="h-56 w-full min-h-56">
- <canvas ref={canvasRef} />
- </div>
- {flaggedCount > 0 ? (
- <p className="text-muted text-xs mb-0">
- {historicalCount > 0 ? (
- hasHistoricalFiringState ? (
- `${pluralize(historicalCount, 'check')} triggered the alert.`
- ) : thresholdCtx?.lineMode === 'anomaly_probability' ? (
- `${pluralize(historicalCount, 'check')} above the probability cutoff.`
- ) : thresholdCtx && (thresholdCtx.upper != null || thresholdCtx.lower != null) ? (
- `${pluralize(historicalCount, 'check')} outside threshold.`
- ) : (
- `${pluralize(historicalCount, 'check')} flagged as unusual compared to recent values.`
- )
- ) : (
- <>No checks triggered the alert at the time.</>
- )}
- {currentOnlyCount > 0 ? (
- <>
- {' '}
- {historicalCount > 0
- ? `${pluralize(currentOnlyCount, 'other check')} would`
- : `${pluralize(currentOnlyCount, 'check')} would`}{' '}
- trigger the alert under the current thresholds.
- </>
- ) : null}
- </p>
- ) : (
- <p className="text-muted text-xs mb-0">
- {hasHistoricalFiringState
- ? 'Each hollow dot is one evaluation. When present, red squares mark checks that triggered the alert at the time they ran.'
- : thresholdCtx?.lineMode === 'anomaly_probability'
- ? 'Each hollow dot is one evaluation. When present, red squares mark checks that triggered the alert above the cutoff.'
- : thresholdCtx && (thresholdCtx.upper != null || thresholdCtx.lower != null)
- ? 'Each hollow dot is one evaluation. When present, red squares mark checks that triggered the alert.'
- : 'Each hollow dot is one evaluation. When present, red squares mark values flagged as unusual compared to recent values.'}{' '}
- {thresholdCtx
- ? chartPlotsAnomalyScore
- ? 'Dashed lines are your configured alert thresholds (or detector probability cutoff).'
- : 'Dashed lines are your configured alert thresholds.'
- : 'Threshold lines appear when this alert has explicit bounds or a detector probability threshold.'}
- </p>
- )}
- {hasHistoricalFiringState && thresholdCtx && currentOnlyCount > 0 ? (
- <p className="text-muted text-xs mb-0">
- {historicalCount > 0 ? 'Red squares fired at the time they ran. ' : ''}
- Orange triangles would fire under the current thresholds but didn't when they ran.
- </p>
- ) : null}
- </div>
+ <AlertEvaluationHistoryChart
+ points={points}
+ valueLabel={valueLabel}
+ thresholds={buildThresholds(thresholdContext)}
+ historyLimit={historyLimit}
+ evaluationsTotal={checksTotal}
+ evaluationNoun="check"
+ tableAvailable
+ classifyUnusualWithoutThresholds
+ />
)
}
diff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsx
index 5a81690f963b..5accebd79491 100644
--- a/products/alerts/frontend/views/EditAlertModal.tsx
+++ b/products/alerts/frontend/views/EditAlertModal.tsx
@@ -2,14 +2,12 @@ import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { useCallback, useMemo } from 'react'
-import { IconCalendar, IconChevronLeft } from '@posthog/icons'
-import { LemonCheckbox, LemonInput, Link, SpinnerOverlay } from '@posthog/lemon-ui'
+import { SpinnerOverlay } 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'
@@ -22,11 +20,17 @@ import { AlertCalculationInterval, AlertState } from '~/queries/schema/schema-ge
import { isFunnelsQuery, isInsightVizNode } from '~/queries/utils'
import { FunnelVizType, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
-import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection'
-import { AlertDefinitionSection } from 'products/alerts/frontend/components/editAlertModal/AlertDefinitionSection'
-import { AlertIntervalRow } from 'products/alerts/frontend/components/editAlertModal/AlertIntervalRow'
-import { AlertNotificationSection } from 'products/alerts/frontend/components/editAlertModal/AlertNotificationSection'
+import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/AlertAdvancedOptionsSection'
+import { AlertTimezoneNotice } from 'products/alerts/frontend/components/AlertDefinition'
+import { AlertDefinitionSection } from 'products/alerts/frontend/components/AlertDefinitionSection'
+import {
+ AlertEditor,
+ AlertEditorFormDetails,
+ AlertEditorSection,
+} from 'products/alerts/frontend/components/AlertEditor'
+import { AlertIntervalRow } from 'products/alerts/frontend/components/AlertIntervalRow'
import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { InsightAlertNotificationSection } from 'products/alerts/frontend/views/InsightAlertNotificationSection'
import { SnoozeButton } from '../components/SnoozeButton'
import { alertFormLogic, canCheckOngoingInterval, insightAlertKindForQuery } from '../logic/alertFormLogic'
@@ -36,7 +40,7 @@ import { isNextPlannedEvaluationStale } from '../logic/alertSchedulingStale'
import { insightAlertsLogic } from '../logic/insightAlertsLogic'
import { supportsAnomalyDetection, supportsOngoingInterval } from '../types'
import type { AlertType } from '../types'
-import { AlertHistorySection, AlertHistorySectionSkeleton } from './AlertHistorySection'
+import { AlertHistorySection } from './AlertHistorySection'
interface EditAlertModalProps {
isOpen: boolean | undefined
@@ -216,6 +220,29 @@ export function EditAlertModal({
can_check_ongoing_interval,
])
+ const leadingActions = (
+ <div className="flex gap-2">
+ {!creatingNewAlert ? (
+ <LemonButton type="secondary" status="danger" onClick={deleteAlert}>
+ Delete alert
+ </LemonButton>
+ ) : null}
+ {!creatingNewAlert && alert?.state === AlertState.FIRING ? (
+ <SnoozeButton onChange={snoozeAlert} value={alert?.snoozed_until} />
+ ) : null}
+ {!creatingNewAlert && alert?.state === AlertState.SNOOZED ? (
+ <LemonButton
+ type="secondary"
+ status="default"
+ onClick={clearSnooze}
+ tooltip={`Currently snoozed until ${formatDate(dayjs(alert?.snoozed_until), 'MMM D, HH:mm')}`}
+ >
+ Clear snooze
+ </LemonButton>
+ ) : null}
+ </div>
+ )
+
return (
<LemonModal onClose={handleClose} isOpen={isOpen} width={900} simple title="">
{alertLoading && !alert ? (
@@ -228,41 +255,33 @@ export function EditAlertModal({
enableFormOnSubmit
className="LemonModal__layout"
>
- <LemonModal.Header>
- <div className="flex items-center gap-2">
- <LemonButton icon={<IconChevronLeft />} onClick={handleClose} size="xsmall" />
-
- <h3>{creatingNewAlert ? 'New' : 'Edit '} Alert</h3>
- </div>
- </LemonModal.Header>
-
- <LemonModal.Content>
+ <AlertEditor
+ title={creatingNewAlert ? 'New alert' : 'Edit alert'}
+ className="min-h-0 flex-1 overflow-hidden"
+ contentClassName="min-h-0 flex-1 overflow-y-auto"
+ onBack={handleClose}
+ isEditing={!creatingNewAlert}
+ isSubmitting={isAlertFormSubmitting}
+ hasChanges={alertFormChanged}
+ hasPendingChanges={hasPendingNotifications}
+ onSubmitAttempted={setAlertFormSubmitAttempted}
+ leadingActions={leadingActions}
+ >
<div className="deprecated-space-y-6">
- <div className="deprecated-space-y-4">
- <div className="flex gap-4 items-center">
- <LemonField className="flex-auto" name="name">
- <LemonInput placeholder="Alert name" data-attr="alertForm-name" />
- </LemonField>
- <LemonField name="enabled">
- <LemonCheckbox
- checked={alertForm?.enabled}
- data-attr="alertForm-enabled"
- fullWidth
- label="Enabled"
+ <AlertEditorFormDetails
+ enabled={{ checked: alertForm.enabled, dataAttr: 'alertForm-enabled' }}
+ activity={
+ alert?.created_by ? (
+ <UserActivityIndicator
+ at={alert.created_at}
+ by={alert.created_by}
+ prefix="Created"
/>
- </LemonField>
- </div>
- {alert?.created_by ? (
- <UserActivityIndicator
- at={alert.created_at}
- by={alert.created_by}
- prefix="Created"
- />
- ) : null}
- </div>
+ ) : undefined
+ }
+ />
- <div className="deprecated-space-y-3">
- <h3 className="mb-0">Definition</h3>
+ <AlertEditorSection title="Definition">
<div className="deprecated-space-y-3">
<AlertDefinitionSection
alertForm={alertForm}
@@ -304,23 +323,14 @@ export function EditAlertModal({
onSetAlertFormValue={setAlertFormValue}
/>
</div>
- </div>
+ </AlertEditorSection>
- <div className="text-muted text-sm flex flex-wrap items-start gap-2">
- <IconCalendar className="size-4 shrink-0 text-muted mt-0.5" aria-hidden />
- <span className="min-w-0">
- Times use your project timezone ({projectTimezone}).{' '}
- <Link
- to={urls.settings('environment-customization', 'date-and-time')}
- target="_blank"
- targetBlankIcon={false}
- >
- Change in settings
- </Link>
- </span>
- </div>
+ <AlertTimezoneNotice
+ timezone={projectTimezone}
+ settingsUrl={urls.settings('environment-customization', 'date-and-time')}
+ />
- <AlertNotificationSection
+ <InsightAlertNotificationSection
alertForm={alertForm}
alertId={alertId}
insightShortId={insightShortId}
@@ -337,56 +347,8 @@ export function EditAlertModal({
/>
</div>
- {alertId ? (
- alert ? (
- <AlertHistorySection alertId={alert.id} />
- ) : alertLoading ? (
- <AlertHistorySectionSkeleton />
- ) : null
- ) : null}
- </LemonModal.Content>
-
- <LemonModal.Footer>
- <div className="flex-1">
- <div className="flex gap-2">
- {!creatingNewAlert ? (
- <LemonButton type="secondary" status="danger" onClick={deleteAlert}>
- Delete alert
- </LemonButton>
- ) : null}
- {!creatingNewAlert && alert?.state === AlertState.FIRING ? (
- <SnoozeButton onChange={snoozeAlert} value={alert?.snoozed_until} />
- ) : null}
- {!creatingNewAlert && alert?.state === AlertState.SNOOZED ? (
- <LemonButton
- type="secondary"
- status="default"
- onClick={clearSnooze}
- tooltip={`Currently snoozed until ${formatDate(
- dayjs(alert?.snoozed_until),
- 'MMM D, HH:mm'
- )}`}
- >
- Clear snooze
- </LemonButton>
- ) : null}
- </div>
- </div>
- <LemonButton
- type="primary"
- htmlType="submit"
- loading={isAlertFormSubmitting}
- disabledReason={
- !creatingNewAlert &&
- !alertFormChanged &&
- !hasPendingNotifications &&
- 'No changes to save'
- }
- onClick={() => setAlertFormSubmitAttempted()}
- >
- {creatingNewAlert ? 'Create alert' : 'Save'}
- </LemonButton>
- </LemonModal.Footer>
+ {alertId && alert ? <AlertHistorySection alertId={alert.id} /> : null}
+ </AlertEditor>
</Form>
)}
</LemonModal>
diff --git a/products/alerts/frontend/views/InlineAlertNotifications.tsx b/products/alerts/frontend/views/InlineAlertNotifications.tsx
index e44e73faff7c..b38569955d35 100644
--- a/products/alerts/frontend/views/InlineAlertNotifications.tsx
+++ b/products/alerts/frontend/views/InlineAlertNotifications.tsx
@@ -1,20 +1,23 @@
import { useActions, useValues } from 'kea'
import { useEffect } from 'react'
-import { IconExternal, IconTrash } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonSelect, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
-
-import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/SlackIntegrationHelpers'
import { slackIntegrationLogic } from 'lib/integrations/slackIntegrationLogic'
import { urls } from 'scenes/urls'
import { HogFunctionType, SlackChannelType } from '~/types'
+import {
+ AlertNotificationDestinationEditor,
+ AlertNotificationDestinationView,
+ AlertNotificationUrlInput,
+ PendingAlertNotificationDestinationView,
+} from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'
import {
ALERT_NOTIFICATION_TYPE_DISCORD,
ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,
ALERT_NOTIFICATION_TYPE_SLACK,
ALERT_NOTIFICATION_TYPE_WEBHOOK,
+ AlertNotificationType,
PendingAlertNotification,
} from 'products/alerts/frontend/logic/alertNotifications'
@@ -22,14 +25,14 @@ import { ALERT_NOTIFICATION_TYPE_OPTIONS, alertNotificationLogic } from '../logi
function resolveSlackChannelName(channelValue: string, slackChannels: SlackChannelType[]): string | null {
const channelId = channelValue.split('|')[0]
- return slackChannels.find((c) => c.id === channelId)?.name ?? null
+ return slackChannels.find((channel) => channel.id === channelId)?.name ?? null
}
function getHogFunctionDestination(
- hf: HogFunctionType,
+ hogFunction: HogFunctionType,
slackChannels: SlackChannelType[]
): { type: string; detail: string | null } {
- const channelValue = hf.inputs?.channel?.value
+ const channelValue = hogFunction.inputs?.channel?.value
if (channelValue && typeof channelValue === 'string') {
const channelName = resolveSlackChannelName(channelValue, slackChannels)
return { type: 'Slack', detail: channelName ? `#${channelName}` : null }
@@ -37,19 +40,80 @@ function getHogFunctionDestination(
if (channelValue) {
return { type: 'Slack', detail: null }
}
- if (hf.template_id === 'template-discord') {
- const webhookUrl = hf.inputs?.webhookUrl?.value
+ if (hogFunction.template_id === 'template-discord') {
+ const webhookUrl = hogFunction.inputs?.webhookUrl?.value
return { type: 'Discord', detail: typeof webhookUrl === 'string' ? webhookUrl : null }
}
- if (hf.template_id === 'template-microsoft-teams') {
- const webhookUrl = hf.inputs?.webhookUrl?.value
+ if (hogFunction.template_id === 'template-microsoft-teams') {
+ const webhookUrl = hogFunction.inputs?.webhookUrl?.value
return { type: 'Microsoft Teams', detail: typeof webhookUrl === 'string' ? webhookUrl : null }
}
- const urlValue = hf.inputs?.url?.value
+ const urlValue = hogFunction.inputs?.url?.value
if (urlValue && typeof urlValue === 'string') {
return { type: 'Webhook', detail: urlValue }
}
- return { type: hf.name, detail: null }
+ return { type: hogFunction.name, detail: null }
+}
+
+function getNotificationLabel(notification: PendingAlertNotification): string {
+ switch (notification.type) {
+ case ALERT_NOTIFICATION_TYPE_SLACK:
+ return `Slack: #${notification.slackChannelName ?? 'channel'}`
+ case ALERT_NOTIFICATION_TYPE_DISCORD:
+ return `Discord: ${notification.webhookUrl}`
+ case ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS:
+ return `Microsoft Teams: ${notification.webhookUrl}`
+ case ALERT_NOTIFICATION_TYPE_WEBHOOK:
+ return `Webhook: ${notification.webhookUrl}`
+ default: {
+ const exhaustiveCheck: never = notification
+ return exhaustiveCheck
+ }
+ }
+}
+
+function getUrlInput(type: AlertNotificationType): AlertNotificationUrlInput | undefined {
+ switch (type) {
+ case ALERT_NOTIFICATION_TYPE_DISCORD:
+ return { placeholder: 'https://discord.com/api/webhooks/...' }
+ case ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS:
+ return { placeholder: 'https://<region>.logic.azure.com:443/workflows/...' }
+ case ALERT_NOTIFICATION_TYPE_WEBHOOK:
+ return { placeholder: 'https://example.com/webhook' }
+ case ALERT_NOTIFICATION_TYPE_SLACK:
+ return undefined
+ default: {
+ const exhaustiveCheck: never = type
+ return exhaustiveCheck
+ }
+ }
+}
+
+function getAddDisabledReason(
+ selectedType: AlertNotificationType,
+ hasSlackIntegration: boolean,
+ slackChannelValue: string | null,
+ webhookUrl: string
+): string | undefined {
+ if (selectedType === ALERT_NOTIFICATION_TYPE_SLACK) {
+ if (!hasSlackIntegration) {
+ return 'Connect Slack first'
+ }
+ if (!slackChannelValue) {
+ return 'Select a Slack channel'
+ }
+ return undefined
+ }
+ if (webhookUrl) {
+ return undefined
+ }
+ if (selectedType === ALERT_NOTIFICATION_TYPE_DISCORD) {
+ return 'Enter a Discord webhook URL'
+ }
+ if (selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS) {
+ return 'Enter a Microsoft Teams workflow URL'
+ }
+ return 'Enter a webhook URL'
}
interface InlineAlertNotificationsProps {
@@ -99,7 +163,6 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr
slackChannelName: channelLabel?.replace('#', '') ?? channelId,
}
}
- // Discord, Microsoft Teams, and the generic webhook are all just a single webhook URL
if (!webhookUrl) {
return null
}
@@ -120,161 +183,70 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr
addPendingNotification(notification)
if (notification.type === ALERT_NOTIFICATION_TYPE_SLACK) {
setSlackChannelValue(null)
- } else {
- setWebhookUrl('')
+ return
}
+ setWebhookUrl('')
}
- const getNotificationLabel = (notification: PendingAlertNotification): string => {
- if (notification.type === ALERT_NOTIFICATION_TYPE_SLACK) {
- return `Slack: #${notification.slackChannelName ?? 'channel'}`
- }
- if (notification.type === ALERT_NOTIFICATION_TYPE_DISCORD) {
- return `Discord: ${notification.webhookUrl}`
- }
- if (notification.type === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS) {
- return `Microsoft Teams: ${notification.webhookUrl}`
+ const existingDestinations: AlertNotificationDestinationView[] = existingHogFunctions.map((hogFunction) => {
+ const destination = getHogFunctionDestination(hogFunction, slackChannels)
+ return {
+ key: hogFunction.id,
+ title: destination.type,
+ detail: destination.detail,
+ tags: [
+ { label: hogFunction.enabled ? 'Active' : 'Paused', type: hogFunction.enabled ? 'success' : 'default' },
+ ],
+ viewAction: {
+ kind: 'icon',
+ url: urls.hogFunction(hogFunction.id),
+ tooltip: 'Open destination',
+ targetBlank: true,
+ },
+ onDelete: () => deleteExistingHogFunction(hogFunction),
}
- return `Webhook: ${notification.webhookUrl}`
- }
-
- return (
- <div className="space-y-4">
- {alertId && (
- <div>
- {existingHogFunctionsLoading ? (
- <LemonSkeleton className="h-8" repeat={2} />
- ) : existingHogFunctions.length > 0 ? (
- <div className="space-y-2">
- {existingHogFunctions.map((hf) => {
- const { type: destType, detail } = getHogFunctionDestination(hf, slackChannels)
- return (
- <div
- key={hf.id}
- className="flex items-center justify-between border rounded p-2 gap-2"
- >
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-sm font-medium">{destType}</span>
- <LemonTag type={hf.enabled ? 'success' : 'default'} size="small">
- {hf.enabled ? 'Active' : 'Paused'}
- </LemonTag>
- </div>
- {detail && (
- <span className="text-xs text-muted-alt truncate block">{detail}</span>
- )}
- </div>
- <div className="flex items-center gap-1 shrink-0">
- <LemonButton
- icon={<IconExternal />}
- size="xsmall"
- to={urls.hogFunction(hf.id)}
- targetBlank
- hideExternalLinkIcon
- tooltip="Open destination"
- />
- <LemonButton
- icon={<IconTrash />}
- size="xsmall"
- status="danger"
- onClick={() => deleteExistingHogFunction(hf)}
- tooltip="Delete notification"
- />
- </div>
- </div>
- )
- })}
- </div>
- ) : null}
- </div>
- )}
-
- {pendingNotifications.length > 0 && (
- <div className="space-y-2">
- {pendingNotifications.map((notification, index) => (
- <div key={index} className="flex items-center justify-between border rounded p-2 gap-2">
- <span className="text-sm min-w-0 truncate">
- {getNotificationLabel(notification)}{' '}
- <span className="text-muted-alt">(pending - click Save to apply)</span>
- </span>
- <LemonButton
- icon={<IconTrash />}
- size="xsmall"
- status="danger"
- onClick={() => removePendingNotification(index)}
- tooltip="Remove notification"
- />
- </div>
- ))}
- </div>
- )}
-
- <div className="space-y-3 border rounded p-3">
- <div className="flex gap-2 items-end">
- <div className="flex-1">
- <LemonSelect
- fullWidth
- options={ALERT_NOTIFICATION_TYPE_OPTIONS}
- value={selectedType}
- onChange={(value) => setSelectedType(value)}
- />
- </div>
- </div>
-
- {selectedType === ALERT_NOTIFICATION_TYPE_SLACK && (
- <>
- {!firstSlackIntegration ? (
- <SlackNotConfiguredBanner />
- ) : (
- <SlackChannelPicker
- value={slackChannelValue ?? undefined}
- onChange={(value) => setSlackChannelValue(value)}
- integration={firstSlackIntegration}
- />
- )}
- </>
- )}
+ })
+
+ const pendingDestinations: PendingAlertNotificationDestinationView[] = pendingNotifications.map(
+ (notification, index) => ({
+ key: `${notification.type}-${index}`,
+ label: getNotificationLabel(notification),
+ status: '(pending, click Save to apply)',
+ onRemove: () => removePendingNotification(index),
+ })
+ )
- {(selectedType === ALERT_NOTIFICATION_TYPE_WEBHOOK ||
- selectedType === ALERT_NOTIFICATION_TYPE_DISCORD ||
- selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS) && (
- <LemonInput
- placeholder={
- selectedType === ALERT_NOTIFICATION_TYPE_DISCORD
- ? 'https://discord.com/api/webhooks/...'
- : selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS
- ? 'https://<region>.logic.azure.com:443/workflows/...'
- : 'https://example.com/webhook'
- }
- value={webhookUrl}
- onChange={setWebhookUrl}
- fullWidth
- />
- )}
+ const urlInput = getUrlInput(selectedType)
- <LemonButton
- type="secondary"
- size="small"
- onClick={handleAdd}
- disabledReason={
- selectedType === ALERT_NOTIFICATION_TYPE_SLACK
- ? !firstSlackIntegration
- ? 'Connect Slack first'
- : !slackChannelValue
- ? 'Select a Slack channel'
- : undefined
- : !webhookUrl
- ? selectedType === ALERT_NOTIFICATION_TYPE_DISCORD
- ? 'Enter a Discord webhook URL'
- : selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS
- ? 'Enter a Microsoft Teams workflow URL'
- : 'Enter a webhook URL'
- : undefined
- }
- >
- Add notification
- </LemonButton>
- </div>
- </div>
+ return (
+ <AlertNotificationDestinationEditor
+ destinations={{
+ showExisting: Boolean(alertId),
+ existingLoading: existingHogFunctionsLoading,
+ existing: existingDestinations,
+ pending: pendingDestinations,
+ }}
+ notificationType={{
+ options: ALERT_NOTIFICATION_TYPE_OPTIONS,
+ value: selectedType,
+ onChange: setSelectedType,
+ }}
+ slack={{
+ notificationType: ALERT_NOTIFICATION_TYPE_SLACK,
+ integration: firstSlackIntegration,
+ channelValue: slackChannelValue,
+ onChannelValueChange: setSlackChannelValue,
+ }}
+ url={urlInput ? { input: urlInput, value: webhookUrl, onChange: setWebhookUrl } : undefined}
+ add={{
+ onClick: handleAdd,
+ disabledReason: getAddDisabledReason(
+ selectedType,
+ Boolean(firstSlackIntegration),
+ slackChannelValue,
+ webhookUrl
+ ),
+ }}
+ />
)
}
diff --git a/products/alerts/frontend/components/editAlertModal/AlertNotificationSection.tsx b/products/alerts/frontend/views/InsightAlertNotificationSection.tsx
similarity index 57%
rename from products/alerts/frontend/components/editAlertModal/AlertNotificationSection.tsx
rename to products/alerts/frontend/views/InsightAlertNotificationSection.tsx
index 1a9490434c70..9254812df699 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertNotificationSection.tsx
+++ b/products/alerts/frontend/views/InsightAlertNotificationSection.tsx
@@ -2,12 +2,13 @@ import { MemberSelectMultiple } from 'lib/components/MemberSelectMultiple'
import { InsightShortId } from '~/types'
+import { AlertEditorSection } from 'products/alerts/frontend/components/AlertEditor'
import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
import { AlertType } from 'products/alerts/frontend/types'
import { AlertDestinationSelector } from 'products/alerts/frontend/views/AlertDestinationSelector'
import { InlineAlertNotifications } from 'products/alerts/frontend/views/InlineAlertNotifications'
-export interface AlertNotificationSectionProps {
+export interface InsightAlertNotificationSectionProps {
alertForm: AlertFormType
alertId: AlertType['id'] | undefined
insightShortId: InsightShortId
@@ -15,21 +16,33 @@ export interface AlertNotificationSectionProps {
onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
}
-export function AlertNotificationSection({
+export function InsightAlertNotificationSection({
alertForm,
alertId,
insightShortId,
inlineNotificationsEnabled,
onSetAlertFormValue,
-}: AlertNotificationSectionProps): JSX.Element {
+}: InsightAlertNotificationSectionProps): JSX.Element {
+ let destinations: JSX.Element
+ if (inlineNotificationsEnabled) {
+ destinations = <InlineAlertNotifications alertId={alertId} />
+ } else if (alertId) {
+ destinations = (
+ <div className="flex flex-col">
+ <AlertDestinationSelector alertId={alertId} insightShortId={insightShortId} />
+ </div>
+ )
+ } else {
+ destinations = <div className="text-muted-alt">Save alert first to add destinations (e.g. Slack, Webhooks)</div>
+ }
+
return (
- <div>
- <h3>Notification</h3>
- <div className="flex gap-4 items-center mt-2">
+ <AlertEditorSection title="Notification">
+ <div className="flex gap-4 items-center">
<div>E-mail</div>
<div className="flex-auto">
<MemberSelectMultiple
- value={alertForm.subscribed_users?.map((u) => u.id) ?? []}
+ value={alertForm.subscribed_users?.map((user) => user.id) ?? []}
idKey="id"
onChange={(value) => onSetAlertFormValue('subscribed_users', value)}
/>
@@ -37,17 +50,7 @@ export function AlertNotificationSection({
</div>
<h4 className="mt-4">Destinations</h4>
- <div className="mt-4">
- {inlineNotificationsEnabled ? (
- <InlineAlertNotifications alertId={alertId} />
- ) : alertId ? (
- <div className="flex flex-col">
- <AlertDestinationSelector alertId={alertId} insightShortId={insightShortId} />
- </div>
- ) : (
- <div className="text-muted-alt">Save alert first to add destinations (e.g. Slack, Webhooks)</div>
- )}
- </div>
- </div>
+ <div className="mt-4">{destinations}</div>
+ </AlertEditorSection>
)
}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
index e02c86ab7d3c..888558b34456 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
@@ -3,12 +3,19 @@ import { BindLogic, useActions, useValues } from 'kea'
import { LemonButton, LemonModal, LemonTable, LemonTableColumns, LemonTag, LemonTagType } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
import { truncate } from 'lib/utils/strings'
+import {
+ AlertEvaluationHistoryChart,
+ AlertEvaluationHistoryPoint,
+ AlertEvaluationThreshold,
+} from 'products/alerts/frontend/components/AlertEvaluationHistoryChart'
import {
LogsAlertConfigurationApi,
LogsAlertEventApi,
LogsAlertEventKindEnumApi,
+ LogsAlertThresholdOperatorEnumApi,
} from 'products/logs/frontend/generated/api.schemas'
import { LogsAlertEventHistoryLogicProps, logsAlertEventHistoryLogic } from './logsAlertEventHistoryLogic'
@@ -23,9 +30,9 @@ export function LogsAlertEventHistoryModal({ alert, onClose }: LogsAlertEventHis
<LemonModal
isOpen={alert !== null}
onClose={onClose}
- width={640}
+ width={960}
title={alert ? `Alert history · ${alert.name}` : 'Alert history'}
- description="Transitions, errors, and user actions."
+ description="Evaluations, transitions, errors, and user actions."
>
{alert ? <LogsAlertEventHistoryContent alert={alert} /> : null}
</LemonModal>
@@ -37,14 +44,34 @@ export function LogsAlertEventHistoryContent({ alert }: { alert: LogsAlertConfig
return (
<BindLogic logic={logsAlertEventHistoryLogic} props={logicProps}>
- <LogsAlertEventTimeline />
+ <LogsAlertEventTimeline alert={alert} />
</BindLogic>
)
}
-function LogsAlertEventTimeline(): JSX.Element {
+function getHistoryThresholds(alert: LogsAlertConfigurationApi): AlertEvaluationThreshold[] {
+ const thresholdValue = alert.threshold_count ?? 100
+ if (alert.threshold_operator === LogsAlertThresholdOperatorEnumApi.Below) {
+ return [{ direction: 'lower', value: thresholdValue, label: `Below (${thresholdValue})` }]
+ }
+ return [{ direction: 'upper', value: thresholdValue, label: `Above (${thresholdValue})` }]
+}
+
+function getHistoryPoints(events: LogsAlertEventApi[]): AlertEvaluationHistoryPoint[] {
+ return events
+ .filter((event) => event.kind === LogsAlertEventKindEnumApi.Check && event.result_count !== null)
+ .sort((left, right) => left.created_at.localeCompare(right.created_at))
+ .map((event) => ({
+ label: dayjs(event.created_at).format('MMM D, HH:mm'),
+ value: event.result_count ?? 0,
+ firedAtTime: event.state_after === 'firing',
+ }))
+}
+
+function LogsAlertEventTimeline({ alert }: { alert: LogsAlertConfigurationApi }): JSX.Element {
const { eventsPage, eventsPageLoading } = useValues(logsAlertEventHistoryLogic)
const { loadMore } = useActions(logsAlertEventHistoryLogic)
+ const historyPoints = getHistoryPoints(eventsPage.results)
const columns: LemonTableColumns<LogsAlertEventApi> = [
{
@@ -74,13 +101,22 @@ function LogsAlertEventTimeline(): JSX.Element {
: ''
return (
- <div className="space-y-3">
+ <div className="space-y-4">
+ {historyPoints.length > 0 ? (
+ <AlertEvaluationHistoryChart
+ points={historyPoints}
+ valueLabel="Matching logs"
+ thresholds={getHistoryThresholds(alert)}
+ historyLimit={Math.max(historyPoints.length, 1)}
+ evaluationNoun="evaluation"
+ />
+ ) : null}
<LemonTable
columns={columns}
dataSource={eventsPage.results}
rowKey="id"
loading={eventsPageLoading}
- emptyState="No events yet. Transitions and user actions will appear here."
+ emptyState="No events yet. Evaluations, transitions, and user actions will appear here."
size="small"
expandable={{
rowExpandable: () => true,
@@ -121,20 +157,11 @@ function describeEvent(event: LogsAlertEventApi): EventDescription {
if (event.kind !== LogsAlertEventKindEnumApi.Check) {
return { ...CONTROL_PLANE_DESCRIPTIONS[event.kind], detail: formatTransition(event) }
}
-
if (event.error_message && event.state_after === 'broken') {
- return {
- label: 'Auto-disabled',
- type: 'caution',
- detail: '5 consecutive errors',
- }
+ return { label: 'Auto-disabled', type: 'caution', detail: '5 consecutive errors' }
}
if (event.error_message) {
- return {
- label: 'Errored',
- type: 'warning',
- detail: truncate(event.error_message, 80),
- }
+ return { label: 'Errored', type: 'warning', detail: truncate(event.error_message, 80) }
}
if (event.state_before !== 'firing' && event.state_after === 'firing') {
return {
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
index aacdd3ca8885..6969c76240f7 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
@@ -2,7 +2,7 @@ import { BindLogic, useActions, useValues } from 'kea'
import { memo, useCallback, useMemo, useRef, useState } from 'react'
import { IconInfo } from '@posthog/icons'
-import { LemonDivider, LemonDropdown, LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
+import { LemonDropdown, LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
import { InfiniteSelectResults } from 'lib/components/TaxonomicFilter/InfiniteSelectResults'
import { TaxonomicFilterSearchInput } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
@@ -16,6 +16,9 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
+import { AlertAdvancedOptions } from 'products/alerts/frontend/components/AlertAdvancedOptions'
+import { AlertDefinitionRow } from 'products/alerts/frontend/components/AlertDefinition'
+import { AlertEditorSection } from 'products/alerts/frontend/components/AlertEditor'
import { ServiceFilter } from 'products/logs/frontend/components/LogsViewer/Filters/ServiceFilter'
import { SeverityLevelsFilter } from 'products/logs/frontend/components/LogsViewer/Filters/SeverityLevelsFilter'
import { LogsAlertThresholdOperatorEnumApi } from 'products/logs/frontend/generated/api.schemas'
@@ -106,67 +109,70 @@ export function LogsAlertForm(): JSX.Element {
(group: UniversalFiltersGroup) => setAlertFormValue('filterGroup', group),
[setAlertFormValue]
)
+ const enabledAdvancedOptionsCount =
+ Number(alertForm.evaluationPeriods > 1 || alertForm.datapointsToAlarm > 1) +
+ Number(alertForm.cooldownMinutes > 0)
return (
<div className="space-y-6 max-w-2xl">
- <div className="space-y-3">
- <h3 className="text-base font-semibold m-0">Filters</h3>
- <p className="text-xs text-secondary m-0">Every 5 minutes, query for logs matching these filters.</p>
- <LemonField name="severityLevels" label="Severity">
- <SeverityLevelsFilter
- value={alertForm.severityLevels}
- onChange={(levels) => setAlertFormValue('severityLevels', levels)}
- />
- </LemonField>
- <LemonField.Pure label="Service">
- <ServiceFilter
- value={alertForm.serviceNames}
- onChange={(names) => setAlertFormValue('serviceNames', names)}
- />
- </LemonField.Pure>
- <LemonField name="filterGroup" label="Attributes">
- <AlertFilterGroup filterGroup={alertForm.filterGroup} onChange={handleFilterGroupChange} />
- </LemonField>
- </div>
-
- <LemonDivider />
+ <AlertEditorSection
+ title="Definition"
+ description="Checks run every 5 minutes. Each check queries logs matching these filters."
+ >
+ <div className="space-y-6">
+ <div className="space-y-5">
+ <h4 className="m-0">Filters</h4>
+ <LemonField name="severityLevels" label="Severity">
+ <SeverityLevelsFilter
+ value={alertForm.severityLevels}
+ onChange={(levels) => setAlertFormValue('severityLevels', levels)}
+ />
+ </LemonField>
+ <LemonField.Pure label="Service">
+ <ServiceFilter
+ value={alertForm.serviceNames}
+ onChange={(names) => setAlertFormValue('serviceNames', names)}
+ />
+ </LemonField.Pure>
+ <LemonField name="filterGroup" label="Attributes">
+ <AlertFilterGroup filterGroup={alertForm.filterGroup} onChange={handleFilterGroupChange} />
+ </LemonField>
+ </div>
- <div className="space-y-3">
- <h3 className="text-base font-semibold m-0">Rules</h3>
- <div className="flex items-center gap-2 flex-wrap">
- <span className="text-sm">Alert if count goes</span>
- <LemonSegmentedButton
- value={alertForm.thresholdOperator}
- onChange={(value) => setAlertFormValue('thresholdOperator', value)}
- options={[
- { value: LogsAlertThresholdOperatorEnumApi.Above, label: 'above' },
- { value: LogsAlertThresholdOperatorEnumApi.Below, label: 'below' },
- ]}
- size="small"
- />
- <LemonInput
- type="number"
- min={0}
- value={alertForm.thresholdCount}
- onChange={(val) => setAlertFormValue('thresholdCount', val ?? 0)}
- className="w-24"
- size="small"
- data-attr="logs-alert-threshold-count"
- />
- <span className="text-sm">in the last</span>
- <LemonSelect
- value={alertForm.windowMinutes}
- onChange={(val) => setAlertFormValue('windowMinutes', val ?? 10)}
- options={WINDOW_OPTIONS}
- size="small"
- />
+ <div className="space-y-2">
+ <h4 className="m-0">Trigger condition</h4>
+ <AlertDefinitionRow label="Alert if count goes">
+ <LemonSegmentedButton
+ value={alertForm.thresholdOperator}
+ onChange={(value) => setAlertFormValue('thresholdOperator', value)}
+ options={[
+ { value: LogsAlertThresholdOperatorEnumApi.Above, label: 'above' },
+ { value: LogsAlertThresholdOperatorEnumApi.Below, label: 'below' },
+ ]}
+ size="small"
+ />
+ <LemonInput
+ type="number"
+ min={0}
+ value={alertForm.thresholdCount}
+ onChange={(value) => setAlertFormValue('thresholdCount', value ?? 0)}
+ className="w-24"
+ size="small"
+ data-attr="logs-alert-threshold-count"
+ />
+ <span className="text-sm">in the last</span>
+ <LemonSelect
+ value={alertForm.windowMinutes}
+ onChange={(value) => setAlertFormValue('windowMinutes', value ?? 10)}
+ options={WINDOW_OPTIONS}
+ size="small"
+ />
+ </AlertDefinitionRow>
+ </div>
</div>
- </div>
+ </AlertEditorSection>
- <LemonDivider />
-
- <div className="space-y-4">
- <h3 className="text-base font-semibold m-0">Advanced</h3>
+ <AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount}>
<LemonField.Pure
label={
<span className="inline-flex items-center gap-1">
@@ -184,7 +190,7 @@ export function LogsAlertForm(): JSX.Element {
min={1}
max={alertForm.evaluationPeriods}
value={alertForm.datapointsToAlarm}
- onChange={(val) => setAlertFormValue('datapointsToAlarm', val ?? 1)}
+ onChange={(value) => setAlertFormValue('datapointsToAlarm', value ?? 1)}
className="w-16"
size="small"
/>
@@ -194,8 +200,8 @@ export function LogsAlertForm(): JSX.Element {
min={alertForm.datapointsToAlarm}
max={10}
value={alertForm.evaluationPeriods}
- onChange={(val) => {
- const newPeriods = val ?? alertForm.datapointsToAlarm
+ onChange={(value) => {
+ const newPeriods = value ?? alertForm.datapointsToAlarm
setAlertFormValue('evaluationPeriods', newPeriods)
if (alertForm.datapointsToAlarm > newPeriods) {
setAlertFormValue('datapointsToAlarm', newPeriods)
@@ -224,14 +230,14 @@ export function LogsAlertForm(): JSX.Element {
type="number"
min={0}
value={alertForm.cooldownMinutes}
- onChange={(val) => setAlertFormValue('cooldownMinutes', val ?? 0)}
+ onChange={(value) => setAlertFormValue('cooldownMinutes', value ?? 0)}
className="w-24"
size="small"
/>
<span className="text-sm">minutes</span>
</div>
</LemonField.Pure>
- </div>
+ </AlertAdvancedOptions>
</div>
)
}
@@ -243,6 +249,11 @@ const AlertFilterGroup = memo(function AlertFilterGroup({
filterGroup: UniversalFiltersGroup
onChange: (group: UniversalFiltersGroup) => void
}): JSX.Element {
+ const newlyAddedFilterIndex = useRef<number | null>(null)
+ const markBlankFilterAsNew = useCallback((index: number): void => {
+ newlyAddedFilterIndex.current = index
+ }, [])
+
return (
<UniversalFilters
rootKey={taxonomicFilterLogicKey}
@@ -251,14 +262,14 @@ const AlertFilterGroup = memo(function AlertFilterGroup({
onChange={onChange}
>
<div className="space-y-2">
- <AlertFilterSearch />
- <AlertAppliedFilters />
+ <AlertFilterSearch onAddBlankFilter={markBlankFilterAsNew} />
+ <AlertAppliedFilters initiallyOpenFilterIndex={newlyAddedFilterIndex.current} />
</div>
</UniversalFilters>
)
})
-function AlertFilterSearch(): JSX.Element {
+function AlertFilterSearch({ onAddBlankFilter }: { onAddBlankFilter: (index: number) => void }): JSX.Element {
const [visible, setVisible] = useState<boolean>(false)
const { addGroupFilter, setGroupValues } = useActions(universalFiltersLogic)
const { filterGroup } = useValues(universalFiltersLogic)
@@ -279,6 +290,7 @@ function AlertFilterSearch(): JSX.Element {
taxonomicGroupTypes,
onChange: (taxonomicGroup, value, item) => {
if (item.value === undefined) {
+ onAddBlankFilter(filterGroupRef.current.values.length)
addGroupFilter(taxonomicGroup, value, item)
setVisible(false)
return
@@ -301,7 +313,7 @@ function AlertFilterSearch(): JSX.Element {
},
autoSelectItem: true,
}),
- [addGroupFilter, setGroupValues]
+ [addGroupFilter, onAddBlankFilter, setGroupValues]
)
const showDropdown = useCallback(() => setVisible(true), [])
@@ -328,13 +340,18 @@ function AlertFilterSearch(): JSX.Element {
searchInputRef={searchInputRef}
onClose={onClose}
onChange={showDropdown}
+ autoFocus={false}
/>
</LemonDropdown>
</BindLogic>
)
}
-function AlertAppliedFilters(): JSX.Element | null {
+function AlertAppliedFilters({
+ initiallyOpenFilterIndex = null,
+}: {
+ initiallyOpenFilterIndex?: number | null
+}): JSX.Element | null {
const { filterGroup } = useValues(universalFiltersLogic)
const { replaceGroupValue, removeGroupValue } = useActions(universalFiltersLogic)
@@ -356,7 +373,9 @@ function AlertAppliedFilters(): JSX.Element | null {
filter={filterOrGroup}
onRemove={() => removeGroupValue(index)}
onChange={(value) => replaceGroupValue(index, value)}
- initiallyOpen={filterOrGroup.type !== PropertyFilterType.HogQL}
+ initiallyOpen={
+ index === initiallyOpenFilterIndex && filterOrGroup.type !== PropertyFilterType.HogQL
+ }
/>
)
})}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx
index 9d100996017a..958b15949217 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx
@@ -1,23 +1,34 @@
import { useActions, useValues } from 'kea'
import { useEffect } from 'react'
-import { IconTrash } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonSelect, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
-
-import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/SlackIntegrationHelpers'
import { slackIntegrationLogic } from 'lib/integrations/slackIntegrationLogic'
import { urls } from 'scenes/urls'
+import {
+ AlertNotificationDestinationEditor,
+ AlertNotificationDestinationView,
+ PendingAlertNotificationDestinationView,
+} from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'
+
import { LOGS_ALERT_NOTIFICATION_TYPE_OPTIONS, logsAlertNotificationLogic } from './logsAlertNotificationLogic'
import {
getHogFunctionEventKind,
LOGS_ALERT_NOTIFICATION_TYPE_SLACK,
LOGS_ALERT_NOTIFICATION_TYPE_TEAMS,
- LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK,
PendingLogsAlertNotification,
resolveGroupLabel,
} from './logsAlertUtils'
+function getNotificationLabel(notification: PendingLogsAlertNotification): string {
+ if (notification.type === LOGS_ALERT_NOTIFICATION_TYPE_SLACK) {
+ return `Slack: #${notification.slackChannelName ?? 'channel'}`
+ }
+ if (notification.type === LOGS_ALERT_NOTIFICATION_TYPE_TEAMS) {
+ return `Microsoft Teams: ${notification.webhookUrl}`
+ }
+ return `Webhook: ${notification.webhookUrl}`
+}
+
export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.Element {
const {
existingHogFunctionsLoading,
@@ -27,9 +38,11 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.E
selectedType,
slackChannelValue,
webhookUrl,
+ urlInput,
+ addDisabledReason,
} = useValues(logsAlertNotificationLogic)
const {
- addPendingNotification,
+ addSelectedNotification,
removePendingNotification,
deleteExistingDestination,
setSelectedType,
@@ -47,202 +60,59 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.E
}
}, [firstSlackIntegration?.id, loadAllSlackChannels, firstSlackIntegration])
- const handleAdd = (): void => {
- if (selectedType === LOGS_ALERT_NOTIFICATION_TYPE_SLACK) {
- if (!slackChannelValue || !firstSlackIntegration) {
- return
- }
- const parts = slackChannelValue.split('|')
- const channelId = parts[0]
- const channelName = parts[1]?.replace('#', '') ?? channelId
-
- const notification: PendingLogsAlertNotification = {
- type: LOGS_ALERT_NOTIFICATION_TYPE_SLACK,
- slackWorkspaceId: firstSlackIntegration.id,
- slackChannelId: channelId,
- slackChannelName: channelName,
- }
- addPendingNotification(notification)
- setSlackChannelValue(null)
- } else {
- if (!webhookUrl) {
- return
- }
- addPendingNotification({ type: selectedType, webhookUrl })
- setWebhookUrl('')
- }
- }
-
- const getNotificationLabel = (notification: PendingLogsAlertNotification): string => {
- if (notification.type === LOGS_ALERT_NOTIFICATION_TYPE_SLACK) {
- return `Slack: #${notification.slackChannelName ?? 'channel'}`
- }
- if (notification.type === LOGS_ALERT_NOTIFICATION_TYPE_TEAMS) {
- return `Microsoft Teams: ${notification.webhookUrl}`
+ const existingDestinations: AlertNotificationDestinationView[] = destinationGroups.map((group) => {
+ const detailHogFunctionId =
+ group.hogFunctions.find((hogFunction) => getHogFunctionEventKind(hogFunction) === 'firing')?.id ??
+ group.hogFunctions[0]?.id
+ const detailUrl =
+ alertId && detailHogFunctionId ? urls.logsAlertNotificationDetail(alertId, detailHogFunctionId) : undefined
+
+ return {
+ key: group.key,
+ title: resolveGroupLabel(group, slackChannels),
+ tags: [{ label: group.enabled ? 'Active' : 'Paused', type: group.enabled ? 'success' : 'default' }],
+ viewAction: {
+ kind: 'button',
+ label: 'View',
+ url: detailUrl,
+ disabledReason: detailUrl ? undefined : 'Save the alert to view details',
+ dataAttr: 'logs-alert-destination-view',
+ },
+ onDelete: () => deleteExistingDestination(group),
}
- return `Webhook: ${notification.webhookUrl}`
- }
+ })
+
+ const pendingDestinations: PendingAlertNotificationDestinationView[] = pendingNotifications.map(
+ (notification, index) => ({
+ key: `${notification.type}-${index}`,
+ label: getNotificationLabel(notification),
+ status: alertId ? '(saving...)' : '(pending, save alert to apply)',
+ onRemove: () => removePendingNotification(index),
+ })
+ )
return (
- <div className="flex flex-col gap-2">
- <p className="text-xs text-muted-alt m-0">
- Each destination delivers notifications for all alert events — firing, resolved, and broken.
- </p>
- {(existingHogFunctionsLoading || destinationGroups.length > 0) && (
- <div>
- {existingHogFunctionsLoading ? (
- <LemonSkeleton className="h-8" repeat={2} />
- ) : destinationGroups.length > 0 ? (
- <div className="space-y-2">
- {destinationGroups.map((group) => {
- const detailHogFunctionId =
- group.hogFunctions.find((hf) => getHogFunctionEventKind(hf) === 'firing')?.id ??
- group.hogFunctions[0]?.id
- const detailUrl =
- alertId && detailHogFunctionId
- ? urls.logsAlertNotificationDetail(alertId, detailHogFunctionId)
- : undefined
- return (
- <div
- key={group.key}
- className="flex items-center justify-between border rounded p-2 gap-2"
- >
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 flex-wrap">
- <span className="text-sm font-medium truncate">
- {resolveGroupLabel(group, slackChannels)}
- </span>
- <LemonTag type={group.enabled ? 'success' : 'default'} size="small">
- {group.enabled ? 'Active' : 'Paused'}
- </LemonTag>
- </div>
- </div>
- <div className="flex items-center gap-1 shrink-0">
- <LemonButton
- size="xsmall"
- type="secondary"
- to={detailUrl}
- disabledReason={
- detailUrl ? undefined : 'Save the alert to view details'
- }
- data-attr="logs-alert-destination-view"
- >
- View
- </LemonButton>
- <LemonButton
- icon={<IconTrash />}
- size="xsmall"
- status="danger"
- onClick={() => deleteExistingDestination(group)}
- tooltip="Delete notification"
- />
- </div>
- </div>
- )
- })}
- </div>
- ) : null}
- </div>
- )}
-
- {pendingNotifications.length > 0 && (
- <div className="space-y-2">
- {pendingNotifications.map((notification, index) => (
- <div
- key={
- notification.type === LOGS_ALERT_NOTIFICATION_TYPE_SLACK
- ? `slack-${notification.slackChannelId}`
- : `${notification.type}-${notification.webhookUrl}`
- }
- className="flex items-center justify-between border rounded p-2 gap-2"
- >
- <span className="text-sm min-w-0 truncate flex flex-col">
- {getNotificationLabel(notification)}{' '}
- <span className="text-muted-alt">
- {alertId ? '(saving…)' : '(pending — save alert to apply)'}
- </span>
- </span>
- <LemonButton
- icon={<IconTrash />}
- size="xsmall"
- status="danger"
- onClick={() => removePendingNotification(index)}
- tooltip="Remove notification"
- />
- </div>
- ))}
- </div>
- )}
-
- <div className="space-y-3 border rounded p-3">
- <div className="flex gap-2 items-end">
- <div className="flex-1">
- <LemonSelect
- fullWidth
- options={LOGS_ALERT_NOTIFICATION_TYPE_OPTIONS}
- value={selectedType}
- onChange={(value) => setSelectedType(value)}
- />
- </div>
- </div>
-
- {selectedType === LOGS_ALERT_NOTIFICATION_TYPE_SLACK && (
- <>
- {!firstSlackIntegration ? (
- <SlackNotConfiguredBanner />
- ) : (
- <SlackChannelPicker
- value={slackChannelValue ?? undefined}
- onChange={(value) => setSlackChannelValue(value)}
- integration={firstSlackIntegration}
- />
- )}
- </>
- )}
-
- {selectedType === LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK && (
- <LemonInput
- placeholder="https://example.com/webhook"
- value={webhookUrl}
- onChange={setWebhookUrl}
- fullWidth
- />
- )}
-
- {selectedType === LOGS_ALERT_NOTIFICATION_TYPE_TEAMS && (
- <div className="space-y-1">
- <LemonInput
- placeholder="https://prod-00.westus.logic.azure.com:443/workflows/..."
- value={webhookUrl}
- onChange={setWebhookUrl}
- fullWidth
- />
- <p className="text-xs text-muted-alt m-0">
- Paste the URL from a Teams "Workflows" (Power Automate) or incoming webhook connector. We
- send a formatted Adaptive Card to it.
- </p>
- </div>
- )}
-
- <LemonButton
- type="secondary"
- size="small"
- onClick={handleAdd}
- disabledReason={
- selectedType === LOGS_ALERT_NOTIFICATION_TYPE_SLACK
- ? !firstSlackIntegration
- ? 'Connect Slack first'
- : !slackChannelValue
- ? 'Select a Slack channel'
- : undefined
- : !webhookUrl
- ? 'Enter a webhook URL'
- : undefined
- }
- >
- Add notification
- </LemonButton>
- </div>
- </div>
+ <AlertNotificationDestinationEditor
+ description="Each destination delivers notifications for all alert events: firing, resolved, and broken."
+ destinations={{
+ showExisting: true,
+ existingLoading: existingHogFunctionsLoading,
+ existing: existingDestinations,
+ pending: pendingDestinations,
+ }}
+ notificationType={{
+ options: LOGS_ALERT_NOTIFICATION_TYPE_OPTIONS,
+ value: selectedType,
+ onChange: setSelectedType,
+ }}
+ slack={{
+ notificationType: LOGS_ALERT_NOTIFICATION_TYPE_SLACK,
+ integration: firstSlackIntegration,
+ channelValue: slackChannelValue,
+ onChannelValueChange: setSlackChannelValue,
+ }}
+ url={urlInput ? { input: urlInput, value: webhookUrl, onChange: setWebhookUrl } : undefined}
+ add={{ onClick: addSelectedNotification, disabledReason: addDisabledReason }}
+ />
)
}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx
index d39f184381e8..743157f79434 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx
@@ -6,6 +6,7 @@ import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { AlertEditor, AlertEditorFormDetails } from 'products/alerts/frontend/components/AlertEditor'
import {
LogsAlertConfigurationApi,
LogsAlertConfigurationStateEnumApi,
@@ -58,7 +59,7 @@ function LogsAlertingSectionInner(): JSX.Element {
simple
width={720}
>
- {isModalOpen && <LogsAlertModalContent editingAlert={editingAlert} />}
+ {isModalOpen ? <LogsAlertModalContent editingAlert={editingAlert} /> : null}
</LemonModal>
<LogsAlertEventHistoryModal alert={viewingHistoryAlert} onClose={() => setViewingHistoryAlert(null)} />
</>
@@ -89,12 +90,27 @@ function LogsAlertModalContent({ editingAlert }: { editingAlert: LogsAlertConfig
enableFormOnSubmit
className="LemonModal__layout"
>
- <LemonModal.Header>
- <h3>{editingAlert ? 'Edit alert' : 'New alert'}</h3>
- <p className="text-muted text-sm m-0">Alerts are checked every 5 minutes.</p>
- </LemonModal.Header>
- <LemonModal.Content>
- {isBroken && editingAlert && (
+ <AlertEditor
+ title={editingAlert ? 'Edit alert' : 'New alert'}
+ className="min-h-0 flex-1 overflow-hidden"
+ contentClassName="min-h-0 flex-1 overflow-y-auto"
+ description="Alerts are checked every 5 minutes."
+ isEditing={editingAlert !== null}
+ isSubmitting={isAlertFormSubmitting}
+ hasChanges={alertFormChanged}
+ hasPendingChanges={hasPendingNotifications}
+ leadingActions={
+ <LemonButton
+ type="secondary"
+ icon={<IconTestTube />}
+ onClick={openSimulationPanel}
+ tooltip="Run this alert against historical data to see when it would have fired"
+ >
+ Simulate
+ </LemonButton>
+ }
+ >
+ {isBroken && editingAlert ? (
<LemonBanner
type="error"
className="mb-3"
@@ -108,37 +124,18 @@ function LogsAlertModalContent({ editingAlert }: { editingAlert: LogsAlertConfig
<div className="font-semibold">
This alert was auto-disabled after repeated check failures.
</div>
- {editingAlert.last_error_message && (
+ {editingAlert.last_error_message ? (
<div className="text-xs text-muted-alt mt-1">
Last error: {editingAlert.last_error_message}
</div>
- )}
+ ) : null}
</LemonBanner>
- )}
- <LogsAlertForm />
- </LemonModal.Content>
- <LemonModal.Footer>
- <LemonButton
- type="secondary"
- icon={<IconTestTube />}
- onClick={openSimulationPanel}
- tooltip="Run this alert against historical data to see when it would have fired"
- >
- Simulate
- </LemonButton>
- <LemonButton
- type="primary"
- htmlType="submit"
- loading={isAlertFormSubmitting}
- disabledReason={
- editingAlert && !alertFormChanged && !hasPendingNotifications
- ? 'No changes to save'
- : undefined
- }
- >
- {editingAlert ? 'Save' : 'Create alert'}
- </LemonButton>
- </LemonModal.Footer>
+ ) : null}
+ <div className="space-y-6 max-w-2xl">
+ <AlertEditorFormDetails />
+ <LogsAlertForm />
+ </div>
+ </AlertEditor>
</Form>
<LemonModal
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
index e3b1c33537fc..a6a941f43e9f 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
@@ -8,6 +8,7 @@ import { projectLogic } from 'scenes/projectLogic'
import { HogFunctionType, IntegrationType } from '~/types'
+import { AlertNotificationUrlInput } from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'
import { logsAlertsDestinationsCreate, logsAlertsDestinationsDeleteCreate } from 'products/logs/frontend/generated/api'
import type { UserBasicType } from '../../../../../frontend/src/types'
@@ -36,6 +37,7 @@ export interface LogsAlertNotificationLogicProps {
export interface logsAlertNotificationLogicValues {
slackIntegrations: IntegrationType[] | undefined // integrationsLogic
currentProjectId: number | null // projectLogic
+ addDisabledReason: string | undefined
destinationGroups: LogsAlertDestinationGroup[]
existingHogFunctions: HogFunctionType[]
existingHogFunctionsLoading: boolean
@@ -43,6 +45,7 @@ export interface logsAlertNotificationLogicValues {
pendingNotifications: PendingLogsAlertNotification[]
selectedType: LogsAlertNotificationType
slackChannelValue: string | null
+ urlInput: AlertNotificationUrlInput | undefined
webhookUrl: string
}
@@ -152,6 +155,9 @@ export interface logsAlertNotificationLogicActions {
addPendingNotification: (notification: PendingLogsAlertNotification) => {
notification: PendingLogsAlertNotification
}
+ addSelectedNotification: () => {
+ value: true
+ }
clearPendingNotifications: () => {
value: true
}
@@ -201,6 +207,13 @@ export interface logsAlertNotificationLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
firstSlackIntegration: (slackIntegrations: IntegrationType[] | undefined) => IntegrationType | undefined
+ urlInput: (selectedType: LogsAlertNotificationType) => AlertNotificationUrlInput | undefined
+ addDisabledReason: (
+ selectedType: LogsAlertNotificationType,
+ firstSlackIntegration: IntegrationType | undefined,
+ slackChannelValue: string | null,
+ webhookUrl: string
+ ) => string | undefined
destinationGroups: (existingHogFunctions: HogFunctionType[]) => LogsAlertDestinationGroup[]
}
}
@@ -224,6 +237,7 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([
actions({
addPendingNotification: (notification: PendingLogsAlertNotification) => ({ notification }),
+ addSelectedNotification: true,
removePendingNotification: (index: number) => ({ index }),
clearPendingNotifications: true,
setPendingNotifications: (notifications: PendingLogsAlertNotification[]) => ({ notifications }),
@@ -290,6 +304,39 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([
(s) => [s.slackIntegrations],
(slackIntegrations: IntegrationType[] | undefined): IntegrationType | undefined => slackIntegrations?.[0],
],
+ urlInput: [
+ (s) => [s.selectedType],
+ (selectedType: LogsAlertNotificationType): AlertNotificationUrlInput | undefined => {
+ if (selectedType === LOGS_ALERT_NOTIFICATION_TYPE_TEAMS) {
+ return {
+ placeholder: 'https://prod-00.westus.logic.azure.com:443/workflows/...',
+ helpText:
+ 'Paste the URL from a Teams "Workflows" (Power Automate) or incoming webhook connector. We send a formatted Adaptive Card to it.',
+ }
+ }
+ if (selectedType === LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK) {
+ return { placeholder: 'https://example.com/webhook' }
+ }
+ return undefined
+ },
+ ],
+ addDisabledReason: [
+ (s) => [s.selectedType, s.firstSlackIntegration, s.slackChannelValue, s.webhookUrl],
+ (
+ selectedType: LogsAlertNotificationType,
+ firstSlackIntegration: IntegrationType | undefined,
+ slackChannelValue: string | null,
+ webhookUrl: string
+ ): string | undefined => {
+ if (selectedType !== LOGS_ALERT_NOTIFICATION_TYPE_SLACK) {
+ return webhookUrl ? undefined : 'Enter a webhook URL'
+ }
+ if (!firstSlackIntegration) {
+ return 'Connect Slack first'
+ }
+ return slackChannelValue ? undefined : 'Select a Slack channel'
+ },
+ ],
// Channel-name resolution happens in the view — slackChannels lives in a dynamically-keyed logic.
destinationGroups: [
(s) => [s.existingHogFunctions],
@@ -299,6 +346,27 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([
}),
listeners(({ actions, values, props }) => ({
+ addSelectedNotification: () => {
+ if (values.selectedType === LOGS_ALERT_NOTIFICATION_TYPE_SLACK) {
+ if (!values.slackChannelValue || !values.firstSlackIntegration) {
+ return
+ }
+ const [channelId, channelLabel] = values.slackChannelValue.split('|')
+ actions.addPendingNotification({
+ type: LOGS_ALERT_NOTIFICATION_TYPE_SLACK,
+ slackWorkspaceId: values.firstSlackIntegration.id,
+ slackChannelId: channelId,
+ slackChannelName: channelLabel?.replace('#', '') ?? channelId,
+ })
+ actions.setSlackChannelValue(null)
+ return
+ }
+ if (!values.webhookUrl) {
+ return
+ }
+ actions.addPendingNotification({ type: values.selectedType, webhookUrl: values.webhookUrl })
+ actions.setWebhookUrl('')
+ },
addPendingNotification: () => {
if (props.alertId) {
actions.createPendingHogFunctions(props.alertId)
diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx b/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx
index a018e72ee38e..e35f86d3a226 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx
@@ -2,7 +2,7 @@ import { BindLogic, useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { IconChevronDown, IconTestTube } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonDialog, LemonModal, LemonTabs } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonCard, LemonDialog, LemonModal, LemonTabs } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { More } from 'lib/lemon-ui/LemonButton/More'
@@ -343,28 +343,30 @@ function ConfigurationTab(): JSX.Element {
}
return (
- <div className="flex flex-col gap-4">
- <div>
- <LemonButton
- type="secondary"
- icon={<IconTestTube />}
- onClick={openSimulationPanel}
- active={isSimulationPanelOpen}
- tooltip="Run this alert against historical data to see when it would have fired"
+ <LemonCard className="max-w-3xl p-6" hoverEffect={false}>
+ <div className="flex flex-col gap-6">
+ <div>
+ <LemonButton
+ type="secondary"
+ icon={<IconTestTube />}
+ onClick={openSimulationPanel}
+ active={isSimulationPanelOpen}
+ tooltip="Run this alert against historical data to see when it would have fired"
+ >
+ Simulate
+ </LemonButton>
+ </div>
+ <Form
+ logic={logsAlertFormLogic}
+ props={formLogicProps}
+ formKey="alertForm"
+ enableFormOnSubmit
+ className="flex flex-col gap-6"
>
- Simulate
- </LemonButton>
+ <LogsAlertForm />
+ </Form>
</div>
- <Form
- logic={logsAlertFormLogic}
- props={formLogicProps}
- formKey="alertForm"
- enableFormOnSubmit
- className="flex flex-col gap-6"
- >
- <LogsAlertForm />
- </Form>
- </div>
+ </LemonCard>
)
}
@@ -376,9 +378,11 @@ function NotificationsTab(): JSX.Element {
}
return (
- <div className="flex flex-col gap-4 max-w-xl">
- <LogsAlertNotifications alertId={alert.id} />
- </div>
+ <LemonCard className="max-w-3xl p-6" hoverEffect={false}>
+ <div className="max-w-2xl">
+ <LogsAlertNotifications alertId={alert.id} />
+ </div>
+ </LemonCard>
)
}