Skip to content

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

feat(alerts): add test delivery (#74314)

Matt Puaabcb8abd184a
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index fda982cee67c..afbaa3ddcff6 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -1151,6 +1151,16 @@ class SubscriptionTestDeliveryThrottle(PersonalApiKeyOrUserRateThrottle):
return self.cache_format % {"scope": self.scope, "ident": f"team_{team_id}"}
+class AlertTestDeliveryThrottle(PersonalApiKeyOrUserRateThrottle):
+ scope = "alert_test_delivery"
+ rate = "10/minute"
+
+ def get_cache_key(self, request, view):
+ team_id = self.safely_get_team_id_from_view(view)
+ if team_id:
+ return self.cache_format % {"scope": self.scope, "ident": f"team_{team_id}"}
+
+
class UserInterviewInviteThrottle(PersonalApiKeyOrUserRateThrottle):
# Cap how often a team can fire the user-interview send_invites action.
#
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 42c1a2a90fb5..9f492b0e2244 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -1,3 +1,4 @@
+from collections.abc import Collection
from dataclasses import dataclass
from datetime import UTC, datetime
@@ -127,7 +128,7 @@ def next_check_at_after_schedule_restriction_change(alert: AlertConfiguration) -
alert.next_check_at = old_next
-def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) -> None:
+def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) -> bool:
"""Trigger all HogFunctions linked to the alert as notification destinations by producing an internal event."""
logger.info(
@@ -148,11 +149,12 @@ def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) ->
**properties,
}
- produce_alert_internal_event(
+ result = produce_alert_internal_event(
team_id=alert.team_id,
event_name=INSIGHT_ALERT_FIRING_EVENT,
properties=props,
)
+ return result is not None
def send_notifications_for_breaches(
@@ -199,6 +201,25 @@ def send_notifications_for_breaches(
return email_targets
+def send_test_alert_email(alert: AlertConfiguration, recipients: Collection[str], idempotency_key: str) -> None:
+ insight_url = f"/project/{alert.team.pk}/insights/{alert.insight.short_id}"
+ send_alert_email(
+ recipients=recipients,
+ campaign_key=f"alert-test-notification-{idempotency_key}",
+ subject=f"Test alert: {alert.name} for {alert.team.name}",
+ template_name="alert_check_firing",
+ template_context={
+ "match_descriptions": ["This is a test alert. No action is needed."],
+ "insight_url": insight_url,
+ "insight_name": alert.insight.name,
+ "alert_url": f"{insight_url}?alert_id={alert.id}",
+ "alert_name": alert.name,
+ "project_name": alert.team.name,
+ "is_test": True,
+ },
+ )
+
+
def send_notifications_for_errors(alert: AlertConfiguration, error: dict) -> list[str]:
logger.info("Sending alert error notifications", alert_id=alert.id, error=error)
email_targets = alert.get_subscribed_users_emails()
diff --git a/posthog/templates/email/alert_check_firing.html b/posthog/templates/email/alert_check_firing.html
index 9c9a98e5132b..a28114ade708 100644
--- a/posthog/templates/email/alert_check_firing.html
+++ b/posthog/templates/email/alert_check_firing.html
@@ -1,7 +1,12 @@
{% extends "email/base.html" %} {% load posthog_assets %} {% block section %}
<p>
- The <a href="{% absolute_uri alert_url %}">{{ alert_name }}</a> alert is firing for <a
- href="{% absolute_uri insight_url %}">{{ insight_name }}</a> in project <strong>{{ project_name }}</strong>:
+ {% if is_test %}
+ This is a test delivery for the <a href="{% absolute_uri alert_url %}">{{ alert_name }}</a> alert on <a
+ href="{% absolute_uri insight_url %}">{{ insight_name }}</a> in project <strong>{{ project_name }}</strong>:
+ {% else %}
+ The <a href="{% absolute_uri alert_url %}">{{ alert_name }}</a> alert is firing for <a
+ href="{% absolute_uri insight_url %}">{{ insight_name }}</a> in project <strong>{{ project_name }}</strong>:
+ {% endif %}
</p>
<ul>
{% for item in match_descriptions %}
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index 180f0419ec21..25e76c983f37 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -11,7 +11,7 @@ from pydantic import (
Field as PydanticField,
RootModel,
)
-from rest_framework import serializers, viewsets
+from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.response import Response
@@ -33,6 +33,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.event_usage import get_request_analytics_properties
+from posthog.exceptions_capture import capture_exception
from posthog.helpers.trigram_search import (
MAX_SEARCH_LENGTH,
NAME_FIELD,
@@ -41,14 +42,20 @@ from posthog.helpers.trigram_search import (
)
from posthog.models import User
from posthog.permissions import get_authenticator_scopes
+from posthog.rate_limit import AlertTestDeliveryThrottle
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUES
from posthog.tasks.alerts.schedule_restriction import validate_and_normalize_schedule_restriction
-from posthog.tasks.alerts.utils import next_check_at_after_schedule_restriction_change
+from posthog.tasks.alerts.utils import (
+ next_check_at_after_schedule_restriction_change,
+ send_test_alert_email,
+ trigger_alert_hog_functions,
+)
from posthog.utils import relative_date_parse
from products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction
+from products.alerts.backend.destinations import count_active_alert_destinations
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.evaluation.detector import simulate_detector_on_insight
from products.alerts.backend.evaluation.validation import (
@@ -66,6 +73,8 @@ from products.alerts.backend.insight_alert_state_machine import (
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from products.product_analytics.backend.models.insight import Insight
+INSIGHT_ALERT_FIRING_EVENT = "$insight_alert_firing"
+
def _validate_interval_entitlement(
*,
@@ -892,6 +901,15 @@ class AlertSimulateResponseSerializer(serializers.Serializer):
)
+class AlertTestDeliveryResponseSerializer(serializers.Serializer):
+ destination_count = serializers.IntegerField(help_text="Number of active destinations queued for test delivery.")
+ email_recipient_count = serializers.IntegerField(help_text="Number of subscribed users sent a test email.")
+ failed_delivery_channels = serializers.ListField(
+ child=serializers.ChoiceField(choices=("email", "destination")),
+ help_text="Configured delivery channels that failed to schedule or send.",
+ )
+
+
@extend_schema_view(
list=extend_schema(
parameters=[
@@ -1096,6 +1114,83 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer = self.get_serializer(alerts, many=True)
return Response(serializer.data)
+ @extend_schema(
+ request=None,
+ responses={202: AlertTestDeliveryResponseSerializer},
+ description="Send a synthetic test notification to subscribed users and every active destination on this alert.",
+ )
+ @action(
+ detail=True,
+ methods=["POST"],
+ url_path="test-delivery",
+ required_scopes=["alert:write"],
+ throttle_classes=[AlertTestDeliveryThrottle],
+ )
+ def test_delivery(self, request, *args, **kwargs):
+ alert = self.get_object()
+ destination_count = count_active_alert_destinations(
+ team_id=alert.team_id,
+ alert_id=str(alert.id),
+ allowed_event_ids=(INSIGHT_ALERT_FIRING_EVENT,),
+ )
+ email_targets = alert.get_subscribed_users_emails()
+ if destination_count == 0 and not email_targets:
+ return Response(
+ {"detail": "Add an email recipient or active destination before sending a test."},
+ status=status.HTTP_409_CONFLICT,
+ )
+
+ failed_delivery_channels: list[str] = []
+ successful_email_count = 0
+ successful_destination_count = 0
+ if email_targets:
+ try:
+ send_test_alert_email(alert, recipients=email_targets, idempotency_key=str(uuid.uuid4()))
+ successful_email_count = len(email_targets)
+ except Exception as error:
+ capture_exception(
+ error,
+ additional_properties={"alert_id": str(alert.id), "feature": "alerts", "channel": "email"},
+ )
+ failed_delivery_channels.append("email")
+ if destination_count and trigger_alert_hog_functions(
+ alert,
+ {
+ "breaches": "Test alert from PostHog. No action is needed.",
+ "is_test": True,
+ "alert_name": f"[TEST] {alert.name}",
+ },
+ ):
+ successful_destination_count = destination_count
+ elif destination_count:
+ failed_delivery_channels.append("destination")
+
+ if successful_email_count == 0 and successful_destination_count == 0:
+ return Response(
+ {"detail": "Unable to start the test delivery. Check the configured channels and try again."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ posthoganalytics.capture(
+ distinct_id=str(request.user.distinct_id),
+ event="insight alert test delivery scheduled",
+ properties={
+ **get_request_analytics_properties(request),
+ "alert_id": str(alert.id),
+ "destination_count": successful_destination_count,
+ "email_recipient_count": successful_email_count,
+ "failed_delivery_channels": failed_delivery_channels,
+ "team_id": alert.team_id,
+ },
+ )
+ return Response(
+ {
+ "destination_count": successful_destination_count,
+ "email_recipient_count": successful_email_count,
+ "failed_delivery_channels": failed_delivery_channels,
+ },
+ status=status.HTTP_202_ACCEPTED,
+ )
+
@extend_schema(
request=AlertSimulateSerializer,
responses={200: AlertSimulateResponseSerializer},
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index 92e7b6310651..08c02396ebd3 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -6,6 +6,8 @@ from freezegun import freeze_time
from posthog.test.base import APIBaseTest, QueryMatchingTest
from unittest import mock
+from django.core.cache import cache
+
from parameterized import parameterized
from rest_framework import status
@@ -17,7 +19,7 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -1443,6 +1445,161 @@ class TestAlertSimulate(APIBaseTest):
assert AlertCheck.objects.count() == checks_before
+class TestAlertTestDelivery(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ insight = self.client.post(
+ f"/api/projects/{self.team.id}/insights",
+ data={
+ "query": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ "trendsFilter": {"display": "BoldNumber"},
+ }
+ },
+ ).json()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ data={
+ "insight": insight["id"],
+ "name": "Testable alert",
+ "subscribed_users": [],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ },
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+ self.alert = response.json()
+
+ def _create_destination(self, *, enabled: bool = True, alert_id: str | None = None) -> HogFunction:
+ return HogFunction.objects.create(
+ team=self.team,
+ name="Alert destination",
+ type="internal_destination",
+ template_id="template-webhook",
+ enabled=enabled,
+ inputs_schema=[],
+ inputs={},
+ hog="return event",
+ filters={
+ "events": [{"id": "$insight_alert_firing", "type": "events"}],
+ "properties": [
+ {
+ "key": "alert_id",
+ "value": alert_id or self.alert["id"],
+ "operator": "exact",
+ "type": "event",
+ }
+ ],
+ },
+ )
+
+ @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions")
+ def test_queues_test_delivery_for_active_destinations_without_changing_alert(self, mock_trigger) -> None:
+ mock_trigger.return_value = True
+ self._create_destination()
+ self._create_destination()
+ self._create_destination(enabled=False)
+ self._create_destination(alert_id="00000000-0000-0000-0000-000000000000")
+ alert_before = AlertConfiguration.objects.get(id=self.alert["id"])
+
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}/test-delivery/")
+
+ assert response.status_code == status.HTTP_202_ACCEPTED, response.content
+ assert response.json() == {
+ "destination_count": 2,
+ "email_recipient_count": 0,
+ "failed_delivery_channels": [],
+ }
+ mock_trigger.assert_called_once_with(
+ mock.ANY,
+ {
+ "breaches": "Test alert from PostHog. No action is needed.",
+ "is_test": True,
+ "alert_name": "[TEST] Testable alert",
+ },
+ )
+ alert_after = AlertConfiguration.objects.get(id=self.alert["id"])
+ assert alert_after.state == alert_before.state
+ assert alert_after.last_notified_at == alert_before.last_notified_at
+ assert AlertCheck.objects.filter(alert_configuration_id=self.alert["id"]).count() == 0
+
+ @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions")
+ @mock.patch("products.alerts.backend.email_notifications.EmailMessage")
+ def test_sends_test_delivery_to_subscribed_users_without_a_destination(
+ self, mock_email_message, mock_trigger
+ ) -> None:
+ alert = AlertConfiguration.objects.get(id=self.alert["id"])
+ AlertSubscription.objects.create(alert_configuration=alert, user=self.user)
+
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}/test-delivery/")
+
+ assert response.status_code == status.HTTP_202_ACCEPTED, response.content
+ assert response.json() == {
+ "destination_count": 0,
+ "email_recipient_count": 1,
+ "failed_delivery_channels": [],
+ }
+ mock_email_message.assert_called_once()
+ assert mock_email_message.call_args.kwargs["subject"] == "Test alert: Testable alert for Default project"
+ mock_email_message.return_value.add_recipient.assert_called_once_with(email=self.user.email)
+ mock_email_message.return_value.send.assert_called_once_with()
+ mock_trigger.assert_not_called()
+
+ @mock.patch("products.alerts.backend.api.alert.send_test_alert_email", side_effect=RuntimeError("email failed"))
+ @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions", return_value=True)
+ def test_destination_still_queues_when_email_fails(self, mock_trigger, _mock_email) -> None:
+ alert = AlertConfiguration.objects.get(id=self.alert["id"])
+ AlertSubscription.objects.create(alert_configuration=alert, user=self.user)
+ self._create_destination()
+
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}/test-delivery/")
+
+ assert response.status_code == status.HTTP_202_ACCEPTED, response.content
+ assert response.json() == {
+ "destination_count": 1,
+ "email_recipient_count": 0,
+ "failed_delivery_channels": ["email"],
+ }
+ mock_trigger.assert_called_once()
+
+ @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions", return_value=False)
+ def test_returns_service_unavailable_when_destination_fails_to_queue(self, mock_trigger) -> None:
+ self._create_destination()
+
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}/test-delivery/")
+
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE, response.content
+ assert response.json() == {
+ "detail": "Unable to start the test delivery. Check the configured channels and try again."
+ }
+ mock_trigger.assert_called_once()
+
+ @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions")
+ def test_rejects_test_delivery_without_active_destinations(self, mock_trigger) -> None:
+ self._create_destination(enabled=False)
+
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}/test-delivery/")
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert response.json() == {"detail": "Add an email recipient or active destination before sending a test."}
+ mock_trigger.assert_not_called()
+
+ @mock.patch("posthog.rate_limit.AlertTestDeliveryThrottle.rate", new="2/minute")
+ @mock.patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+ @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions")
+ def test_rate_limits_test_delivery_per_team(self, _mock_trigger, _rate_limit_enabled) -> None:
+ cache.clear()
+ self._create_destination()
+ endpoint = f"/api/projects/{self.team.id}/alerts/{self.alert['id']}/test-delivery/"
+
+ assert self.client.post(endpoint).status_code == status.HTTP_202_ACCEPTED
+ assert self.client.post(endpoint).status_code == status.HTTP_202_ACCEPTED
+ assert self.client.post(endpoint).status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ cache.clear()
+
+
class TestAlertEventProperties(APIBaseTest):
@parameterized.expand(
[
@@ -1771,6 +1928,13 @@ class TestAlertAPIKeyAccess(APIBaseTest):
(["alert:read"], "get", "/{alert_id}/", status.HTTP_200_OK, None),
(["alert:read"], "delete", "/{alert_id}/", status.HTTP_403_FORBIDDEN, "alert:write"),
(["alert:write"], "delete", "/{alert_id}/", status.HTTP_204_NO_CONTENT, None),
+ (
+ ["alert:read"],
+ "post",
+ "/{alert_id}/test-delivery/",
+ status.HTTP_403_FORBIDDEN,
+ "alert:write",
+ ),
]
)
def test_alert_api_key_access(self, scopes, http_method, endpoint_suffix, expected_status, error_scope):
diff --git a/products/alerts/backend/destinations.py b/products/alerts/backend/destinations.py
index ad28a2b585b1..d79d56541242 100644
--- a/products/alerts/backend/destinations.py
+++ b/products/alerts/backend/destinations.py
@@ -106,6 +106,17 @@ def soft_delete_all_alert_destinations(*, team_id: int, alert_id: str, allowed_e
return deleted_count
+def count_active_alert_destinations(*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> int:
+ return HogFunction.objects.filter(
+ _allowed_event_filter(allowed_event_ids),
+ team_id=team_id,
+ deleted=False,
+ enabled=True,
+ template_id__in=DESTINATION_TEMPLATE_IDS.values(),
+ filters__properties__contains=[{"key": "alert_id", "value": alert_id}],
+ ).count()
+
+
def _allowed_event_filter(allowed_event_ids: Collection[str]) -> Q:
if not allowed_event_ids:
raise ValueError("allowed_event_ids must not be empty")
diff --git a/products/alerts/backend/test/test_email_notifications.py b/products/alerts/backend/test/test_email_notifications.py
index eb54278f0cfb..b79a2d153c00 100644
--- a/products/alerts/backend/test/test_email_notifications.py
+++ b/products/alerts/backend/test/test_email_notifications.py
@@ -1,5 +1,7 @@
from unittest.mock import MagicMock, call, patch
+from django.template.loader import render_to_string
+
from products.alerts.backend.email_notifications import send_alert_email
@@ -39,3 +41,21 @@ def test_send_alert_email_delivers_to_every_recipient(MockEmailMessage: MagicMoc
call(email="[email protected]"),
]
message.send.assert_called_once_with()
+
+
+def test_alert_firing_email_labels_test_delivery_without_claiming_the_alert_is_firing() -> None:
+ html = render_to_string(
+ "email/alert_check_firing.html",
+ {
+ "match_descriptions": ["This is a test alert. No action is needed."],
+ "insight_url": "/project/1/insights/example",
+ "insight_name": "Example insight",
+ "alert_url": "/project/1/insights/example?alert_id=1",
+ "alert_name": "Example alert",
+ "project_name": "Example project",
+ "is_test": True,
+ },
+ )
+
+ assert "This is a test delivery" in html
+ assert "alert is firing" not in html
diff --git a/products/alerts/frontend/components/AlertEditor.tsx b/products/alerts/frontend/components/AlertEditor.tsx
index 9fac4dd05aab..c8f9c806e238 100644
--- a/products/alerts/frontend/components/AlertEditor.tsx
+++ b/products/alerts/frontend/components/AlertEditor.tsx
@@ -71,6 +71,7 @@ export interface AlertEditorActionsProps {
hasChanges: boolean
hasPendingChanges?: boolean
leadingActions?: ReactNode
+ trailingActions?: ReactNode
onSubmitAttempted?: () => void
showNoChangesLabel?: boolean
}
@@ -81,6 +82,7 @@ export function AlertEditorActions({
hasChanges,
hasPendingChanges = false,
leadingActions,
+ trailingActions,
onSubmitAttempted,
showNoChangesLabel = false,
}: AlertEditorActionsProps): JSX.Element {
@@ -93,16 +95,19 @@ export function AlertEditorActions({
return (
<>
- {leadingActions ? <div className="flex-1">{leadingActions}</div> : null}
- <LemonButton
- type="primary"
- htmlType="submit"
- loading={isSubmitting}
- disabledReason={disabledReason}
- onClick={onSubmitAttempted}
- >
- {buttonLabel}
- </LemonButton>
+ {leadingActions ? <div className="w-full sm:min-w-0 sm:flex-1">{leadingActions}</div> : null}
+ <div className="flex w-full items-center justify-end gap-2 sm:w-auto">
+ {trailingActions}
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ loading={isSubmitting}
+ disabledReason={disabledReason}
+ onClick={onSubmitAttempted}
+ >
+ {buttonLabel}
+ </LemonButton>
+ </div>
</>
)
}
@@ -128,7 +133,7 @@ export function AlertEditor({
<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">
+ <footer className="flex flex-col gap-2 border-t p-4 sm:flex-row sm:items-center sm:justify-end">
<AlertEditorActions {...actionsProps} />
</footer>
</div>
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index 54178736f77d..cc8c2cfbf06e 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -749,6 +749,27 @@ export interface PatchedAlertApi {
readonly search_match_type?: SearchMatchTypeEnumApi | null
}
+/**
+ * * `email` - email
+ * * `destination` - destination
+ */
+export type FailedDeliveryChannelsEnumApi =
+ (typeof FailedDeliveryChannelsEnumApi)[keyof typeof FailedDeliveryChannelsEnumApi]
+
+export const FailedDeliveryChannelsEnumApi = {
+ Email: 'email',
+ Destination: 'destination',
+} as const
+
+export interface AlertTestDeliveryResponseApi {
+ /** Number of active destinations queued for test delivery. */
+ destination_count: number
+ /** Number of subscribed users sent a test email. */
+ email_recipient_count: number
+ /** Configured delivery channels that failed to schedule or send. */
+ failed_delivery_channels: FailedDeliveryChannelsEnumApi[]
+}
+
export interface AlertSimulateApi {
/** Insight ID to simulate the detector on. */
insight: number
diff --git a/products/alerts/frontend/generated/api.ts b/products/alerts/frontend/generated/api.ts
index cb3a2d4c1fd7..05452550b5f5 100644
--- a/products/alerts/frontend/generated/api.ts
+++ b/products/alerts/frontend/generated/api.ts
@@ -12,6 +12,7 @@ import type {
AlertApi,
AlertSimulateApi,
AlertSimulateResponseApi,
+ AlertTestDeliveryResponseApi,
AlertsListParams,
AlertsRetrieveParams,
InsightsThresholdsListParams,
@@ -157,6 +158,24 @@ export const alertsDestroy = async (projectId: string, id: string, options?: Req
})
}
+export const getAlertsTestDeliveryCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/alerts/${id}/test-delivery/`
+}
+
+/**
+ * Send a synthetic test notification to subscribed users and every active destination on this alert.
+ */
+export const alertsTestDeliveryCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AlertTestDeliveryResponseApi> => {
+ return apiMutator<AlertTestDeliveryResponseApi>(getAlertsTestDeliveryCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getAlertsSimulateCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/alerts/simulate/`
}
diff --git a/products/alerts/frontend/logic/alertNotificationLogic.test.ts b/products/alerts/frontend/logic/alertNotificationLogic.test.ts
index 36207d4a2f34..f81c1fe988ea 100644
--- a/products/alerts/frontend/logic/alertNotificationLogic.test.ts
+++ b/products/alerts/frontend/logic/alertNotificationLogic.test.ts
@@ -6,6 +6,7 @@ import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { initKeaTests } from '~/test/init'
import { HogFunctionType, IntegrationType } from '~/types'
+import { alertsTestDeliveryCreate } from 'products/alerts/frontend/generated/api'
import {
ALERT_NOTIFICATION_TYPE_DISCORD,
ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,
@@ -15,6 +16,10 @@ import {
import { alertNotificationLogic } from './alertNotificationLogic'
+jest.mock('products/alerts/frontend/generated/api', () => ({
+ alertsTestDeliveryCreate: jest.fn(),
+}))
+
describe('alertNotificationLogic', () => {
let logic: ReturnType<typeof alertNotificationLogic.build>
let createSpy: jest.SpyInstance
@@ -94,6 +99,24 @@ describe('alertNotificationLogic', () => {
await expectLogic(logic).toMatchValues({ integrationsFailed: false })
})
+ it('sends a test delivery for the saved alert', async () => {
+ jest.mocked(alertsTestDeliveryCreate).mockResolvedValue({
+ destination_count: 2,
+ email_recipient_count: 1,
+ failed_delivery_channels: [],
+ })
+ logic = alertNotificationLogic({ alertId: 'alert-123' })
+ logic.mount()
+
+ logic.actions.sendTestDelivery()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(alertsTestDeliveryCreate).toHaveBeenCalledWith('997', 'alert-123')
+ await expectLogic(logic).toMatchValues({
+ testDeliveryResult: { destination_count: 2, email_recipient_count: 1, failed_delivery_channels: [] },
+ })
+ })
+
it('clears the channel when an integrations refresh removes the selected workspace', async () => {
logic = alertNotificationLogic({ alertId: 'alert-123' })
logic.mount()
diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.ts
index f3545e5e7ff5..6b4420e63095 100644
--- a/products/alerts/frontend/logic/alertNotificationLogic.ts
+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts
@@ -10,6 +10,8 @@ import { projectLogic } from 'scenes/projectLogic'
import { HogFunctionType, IntegrationType } from '~/types'
+import { alertsTestDeliveryCreate } from 'products/alerts/frontend/generated/api'
+import type { AlertTestDeliveryResponseApi } from 'products/alerts/frontend/generated/api.schemas'
import {
ALERT_NOTIFICATION_TYPE_DISCORD,
ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,
@@ -33,6 +35,7 @@ export const ALERT_NOTIFICATION_TYPE_OPTIONS = [
export interface AlertNotificationLogicProps {
alertId?: string
+ loadDestinations?: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -48,6 +51,8 @@ export interface alertNotificationLogicValues {
selectedSlackIntegrationId: number | null
selectedType: AlertNotificationType
slackChannelValue: string | null
+ testDeliveryResult: AlertTestDeliveryResponseApi | null
+ testDeliveryResultLoading: boolean
webhookUrl: string
}
@@ -198,6 +203,21 @@ export interface alertNotificationLogicActions {
removePendingNotification: (index: number) => {
index: number
}
+ sendTestDelivery: () => any
+ sendTestDeliveryFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ sendTestDeliverySuccess: (
+ testDeliveryResult: AlertTestDeliveryResponseApi,
+ payload?: any
+ ) => {
+ testDeliveryResult: AlertTestDeliveryResponseApi
+ payload?: any
+ }
setPendingNotifications: (notifications: PendingAlertNotification[]) => {
notifications: PendingAlertNotification[]
}
@@ -236,7 +256,7 @@ export type alertNotificationLogicType = MakeLogicType<
export const alertNotificationLogic = kea<alertNotificationLogicType>([
path(['lib', 'components', 'Alerts', 'alertNotificationLogic']),
props({} as AlertNotificationLogicProps),
- key(({ alertId }) => alertId ?? 'new'),
+ key(({ alertId, loadDestinations = true }) => `${alertId ?? 'new'}-${loadDestinations ? 'full' : 'test-only'}`),
connect({
values: [projectLogic, ['currentProjectId'], integrationsLogic, ['integrationsLoading', 'slackIntegrations']],
@@ -325,7 +345,7 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
],
}),
- loaders(({ props }) => ({
+ loaders(({ props, values }) => ({
existingHogFunctions: [
[] as HogFunctionType[],
{
@@ -342,6 +362,17 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
},
},
],
+ testDeliveryResult: [
+ null as AlertTestDeliveryResponseApi | null,
+ {
+ sendTestDelivery: async () => {
+ if (!props.alertId || values.currentProjectId === null) {
+ throw new Error('Save the alert before sending a test.')
+ }
+ return alertsTestDeliveryCreate(String(values.currentProjectId), props.alertId)
+ },
+ },
+ ],
})),
listeners(({ actions, values, props }) => ({
@@ -451,10 +482,32 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
actions.loadExistingHogFunctions()
},
+ sendTestDeliverySuccess: ({ testDeliveryResult }) => {
+ const destinationCount = testDeliveryResult.destination_count
+ const emailCount = testDeliveryResult.email_recipient_count
+ const deliveryTargets: string[] = []
+ if (emailCount > 0) {
+ deliveryTargets.push(`${emailCount} email ${emailCount === 1 ? 'recipient' : 'recipients'}`)
+ }
+ if (destinationCount > 0) {
+ deliveryTargets.push(`${destinationCount} ${destinationCount === 1 ? 'destination' : 'destinations'}`)
+ }
+ if (testDeliveryResult.failed_delivery_channels.length > 0) {
+ lemonToast.warning(
+ `Test delivery started for ${deliveryTargets.join(' and ')}, but failed for ${testDeliveryResult.failed_delivery_channels.join(' and ')}.`
+ )
+ return
+ }
+ lemonToast.success(`Test delivery started for ${deliveryTargets.join(' and ')}.`)
+ },
+ sendTestDeliveryFailure: ({ errorObject }) => {
+ const detail = errorObject?.detail
+ lemonToast.error(typeof detail === 'string' ? detail : 'Unable to send the test. Try again.')
+ },
})),
afterMount(({ actions, props }) => {
- if (props.alertId) {
+ if (props.alertId && props.loadDestinations !== false) {
actions.loadExistingHogFunctions()
}
}),
diff --git a/products/alerts/frontend/logic/alertsLogic.test.ts b/products/alerts/frontend/logic/alertsLogic.test.ts
index 49fce6e0099f..fd5b361c5ab3 100644
--- a/products/alerts/frontend/logic/alertsLogic.test.ts
+++ b/products/alerts/frontend/logic/alertsLogic.test.ts
@@ -4,6 +4,7 @@ import api from 'lib/api'
import { AlertState } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
+import { HogFunctionType } from '~/types'
import { AlertType } from '../types'
import { alertsLogic } from './alertsLogic'
@@ -24,16 +25,19 @@ const alert = {
describe('alertsLogic', () => {
let deleteSpy: jest.SpyInstance
let listSpy: jest.SpyInstance
+ let hogFunctionsListSpy: jest.SpyInstance
let updateSpy: jest.SpyInstance
beforeEach(() => {
initKeaTests()
listSpy = jest.spyOn(api.alerts, 'list').mockResolvedValue({ results: [alert], count: 1 })
+ hogFunctionsListSpy = jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({ results: [], count: 0 })
})
afterEach(() => {
deleteSpy?.mockRestore()
listSpy.mockRestore()
+ hogFunctionsListSpy.mockRestore()
updateSpy?.mockRestore()
})
@@ -105,4 +109,38 @@ describe('alertsLogic', () => {
logic.unmount()
})
+
+ it('counts only enabled destinations for alerts on the current page', async () => {
+ hogFunctionsListSpy.mockResolvedValue({
+ count: 3,
+ results: [
+ {
+ id: 'destination-1',
+ enabled: true,
+ filters: { properties: [{ key: 'alert_id', value: alert.id }] },
+ },
+ {
+ id: 'destination-2',
+ enabled: false,
+ filters: { properties: [{ key: 'alert_id', value: alert.id }] },
+ },
+ {
+ id: 'destination-for-other-alert',
+ enabled: true,
+ filters: { properties: [{ key: 'alert_id', value: 'other-alert' }] },
+ },
+ ] as unknown as HogFunctionType[],
+ })
+
+ const logic = alertsLogic()
+ logic.mount()
+
+ await expectLogic(logic)
+ .toFinishAllListeners()
+ .toMatchValues({
+ alertDestinationCounts: { [alert.id]: 1 },
+ })
+
+ logic.unmount()
+ })
})
diff --git a/products/alerts/frontend/logic/alertsLogic.ts b/products/alerts/frontend/logic/alertsLogic.ts
index 03ccc18e7950..33861388e736 100644
--- a/products/alerts/frontend/logic/alertsLogic.ts
+++ b/products/alerts/frontend/logic/alertsLogic.ts
@@ -11,6 +11,7 @@ import { AlertState } from '~/queries/schema/schema-general'
import { AlertType } from '../types'
import { AlertLogicProps } from './alertLogic'
+import { buildAlertFilterConfig } from './alertNotifications'
export interface AlertsLogicProps extends AlertLogicProps {}
@@ -28,6 +29,8 @@ export const DEFAULT_ALERTS_FILTERS: AlertsFilters = {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertsLogicValues {
+ alertDestinationCounts: Record<string, number>
+ alertDestinationCountsLoading: boolean
alerts: AlertType[]
alertsCount: number
alertsResponse: {
@@ -49,6 +52,21 @@ export interface alertsLogicActions {
deleteAlert: (alert: AlertType) => {
alert: AlertType
}
+ loadAlertDestinationCounts: (alerts: AlertType[]) => AlertType[]
+ loadAlertDestinationCountsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAlertDestinationCountsSuccess: (
+ alertDestinationCounts: Record<string, number>,
+ payload?: AlertType[]
+ ) => {
+ alertDestinationCounts: Record<string, number>
+ payload?: AlertType[]
+ }
loadAlerts: () => any
loadAlertsFailure: (
error: string,
@@ -196,6 +214,36 @@ export const alertsLogic = kea<alertsLogicType>([
},
},
],
+ alertDestinationCounts: [
+ {} as Record<string, number>,
+ {
+ loadAlertDestinationCounts: async (alerts: AlertType[]) => {
+ if (alerts.length === 0) {
+ return {}
+ }
+ const alertIds = new Set(alerts.map((alert) => alert.id))
+ const response = await api.hogFunctions.list({
+ types: ['internal_destination'],
+ filter_groups: alerts.map((alert) => buildAlertFilterConfig(alert.id)),
+ full: true,
+ limit: 500,
+ })
+ return response.results.reduce<Record<string, number>>((counts, hogFunction) => {
+ if (!hogFunction.enabled) {
+ return counts
+ }
+ const alertIdProperty = hogFunction.filters?.properties?.find(
+ (property) => property.key === 'alert_id'
+ )
+ const alertId = alertIdProperty?.value
+ if (typeof alertId === 'string' && alertIds.has(alertId)) {
+ counts[alertId] = (counts[alertId] ?? 0) + 1
+ }
+ return counts
+ }, {})
+ },
+ },
+ ],
})),
selectors(({ actions }) => ({
@@ -268,6 +316,9 @@ export const alertsLogic = kea<alertsLogicType>([
actions.setAlertToggling(alert.id, false)
}
},
+ loadAlertsSuccess: ({ alertsResponse }) => {
+ actions.loadAlertDestinationCounts(alertsResponse.results)
+ },
})),
afterMount(({ actions }) => actions.loadAlerts()),
diff --git a/products/alerts/frontend/views/EditAlertModalV2.tsx b/products/alerts/frontend/views/EditAlertModalV2.tsx
index c67e87856cb2..f1d897852d7a 100644
--- a/products/alerts/frontend/views/EditAlertModalV2.tsx
+++ b/products/alerts/frontend/views/EditAlertModalV2.tsx
@@ -45,7 +45,7 @@ import { supportsAnomalyDetection, supportsOngoingInterval } from '../types'
import type { AlertType } from '../types'
import { AlertHistorySection } from './AlertHistorySection'
import type { ResolvedAlertModalProps } from './EditAlertModal'
-import { AlertLeadingActions } from './EditAlertModalV2/AlertLeadingActions'
+import { AlertEnabledAction, AlertLeadingActions } from './EditAlertModalV2/AlertLeadingActions'
import { buildWizardSteps } from './EditAlertModalV2/buildWizardSteps'
import { EditAlertTabs } from './EditAlertModalV2/EditAlertTabs'
@@ -143,8 +143,13 @@ export function EditAlertModalV2({
const inlineNotificationsEnabled = useFeatureFlag('ALERTS_INLINE_NOTIFICATIONS')
const investigationAgentEnabled = useFeatureFlag('ALERTS_INVESTIGATION_AGENT')
- const { existingHogFunctions, pendingNotifications } = useValues(alertNotificationLogic({ alertId: alertId }))
+ const notificationLogic = alertNotificationLogic({ alertId })
+ const { existingHogFunctions, pendingNotifications, testDeliveryResultLoading } = useValues(notificationLogic)
+ const { sendTestDelivery } = useActions(notificationLogic)
const hasPendingNotifications = inlineNotificationsEnabled && pendingNotifications.length > 0
+ const hasTestDeliveryTargets =
+ (alert?.subscribed_users?.some((user) => Boolean(user.email)) ?? false) ||
+ existingHogFunctions.some((hogFunction) => hogFunction.enabled)
const handleClose = useCallback(() => {
clearSimulation()
@@ -264,6 +269,12 @@ export function EditAlertModalV2({
onDeleteAlert={deleteAlert}
onSnoozeAlert={snoozeAlert}
onClearSnooze={clearSnooze}
+ onSendTestDelivery={sendTestDelivery}
+ testDeliveryLoading={testDeliveryResultLoading}
+ testDeliveryDisabledReason={
+ alertFormChanged || hasPendingNotifications ? 'Save changes before testing.' : undefined
+ }
+ showTestDelivery={hasTestDeliveryTargets}
/>
)
@@ -406,6 +417,7 @@ export function EditAlertModalV2({
hasPendingChanges={hasPendingNotifications}
onSubmitAttempted={setAlertFormSubmitAttempted}
leadingActions={leadingActions}
+ trailingActions={<AlertEnabledAction alertForm={alertForm} />}
>
<div className="space-y-3">
<EditAlertTabs
diff --git a/products/alerts/frontend/views/EditAlertModalV2/AlertLeadingActions.tsx b/products/alerts/frontend/views/EditAlertModalV2/AlertLeadingActions.tsx
index 25382143b1ec..c981b9ad7756 100644
--- a/products/alerts/frontend/views/EditAlertModalV2/AlertLeadingActions.tsx
+++ b/products/alerts/frontend/views/EditAlertModalV2/AlertLeadingActions.tsx
@@ -18,6 +18,10 @@ interface AlertLeadingActionsProps {
onDeleteAlert: () => void
onSnoozeAlert: (snoozeUntil: string) => void
onClearSnooze: () => void
+ onSendTestDelivery: () => void
+ testDeliveryLoading: boolean
+ testDeliveryDisabledReason?: string
+ showTestDelivery: boolean
}
export function AlertLeadingActions({
@@ -26,9 +30,13 @@ export function AlertLeadingActions({
onDeleteAlert,
onSnoozeAlert,
onClearSnooze,
+ onSendTestDelivery,
+ testDeliveryLoading,
+ testDeliveryDisabledReason,
+ showTestDelivery,
}: AlertLeadingActionsProps): JSX.Element {
return (
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
<LemonButton
type="secondary"
status="danger"
@@ -54,6 +62,16 @@ export function AlertLeadingActions({
value={alert?.snoozed_until}
disabledReason={alert?.state === AlertState.FIRING ? undefined : 'Only firing alerts can be snoozed'}
/>
+ {showTestDelivery ? (
+ <LemonButton
+ type="secondary"
+ onClick={onSendTestDelivery}
+ loading={testDeliveryLoading}
+ disabledReason={testDeliveryDisabledReason}
+ >
+ Test delivery
+ </LemonButton>
+ ) : null}
{alert?.state === AlertState.SNOOZED ? (
<LemonButton
type="secondary"
@@ -64,11 +82,14 @@ export function AlertLeadingActions({
Clear snooze
</LemonButton>
) : null}
- <div className="ml-auto">
- <LemonField name="enabled" className="m-0">
- <LemonSwitch checked={alertForm.enabled} data-attr="alertForm-enabled" label="Enabled" />
- </LemonField>
- </div>
</div>
)
}
+
+export function AlertEnabledAction({ alertForm }: Pick<AlertLeadingActionsProps, 'alertForm'>): JSX.Element {
+ return (
+ <LemonField name="enabled" className="m-0">
+ <LemonSwitch checked={alertForm.enabled} data-attr="alertForm-enabled" label="Enabled" />
+ </LemonField>
+ )
+}
diff --git a/products/alerts/frontend/views/InlineAlertNotifications.tsx b/products/alerts/frontend/views/InlineAlertNotifications.tsx
index d2b7f4c72263..e88fd842d778 100644
--- a/products/alerts/frontend/views/InlineAlertNotifications.tsx
+++ b/products/alerts/frontend/views/InlineAlertNotifications.tsx
@@ -232,39 +232,41 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr
const urlInput = getUrlInput(selectedType)
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,
- integrationsLoading,
- integrationsFailed,
- onRetryIntegrations: loadIntegrations,
- integrations: slackIntegrations,
- integration: selectedSlackIntegration,
- onIntegrationChange: setSelectedSlackIntegrationId,
- channelValue: slackChannelValue,
- onChannelValueChange: setSlackChannelValue,
- }}
- url={urlInput ? { input: urlInput, value: webhookUrl, onChange: setWebhookUrl } : undefined}
- add={{
- onClick: handleAdd,
- disabledReason: getAlertNotificationAddDisabledReason(
- selectedType,
- Boolean(selectedSlackIntegration),
- slackChannelValue,
- webhookUrl
- ),
- }}
- />
+ <div>
+ <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,
+ integrationsLoading,
+ integrationsFailed,
+ onRetryIntegrations: loadIntegrations,
+ integrations: slackIntegrations,
+ integration: selectedSlackIntegration,
+ onIntegrationChange: setSelectedSlackIntegrationId,
+ channelValue: slackChannelValue,
+ onChannelValueChange: setSlackChannelValue,
+ }}
+ url={urlInput ? { input: urlInput, value: webhookUrl, onChange: setWebhookUrl } : undefined}
+ add={{
+ onClick: handleAdd,
+ disabledReason: getAlertNotificationAddDisabledReason(
+ selectedType,
+ Boolean(selectedSlackIntegration),
+ slackChannelValue,
+ webhookUrl
+ ),
+ }}
+ />
+ </div>
)
}
diff --git a/products/alerts/frontend/views/InsightAlerts.tsx b/products/alerts/frontend/views/InsightAlerts.tsx
index 4fa7eaaffd68..6ec1cefe7fd4 100644
--- a/products/alerts/frontend/views/InsightAlerts.tsx
+++ b/products/alerts/frontend/views/InsightAlerts.tsx
@@ -3,15 +3,15 @@ import { router } from 'kea-router'
import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'
import { IconEllipsis } from '@posthog/icons'
-import { LemonButton, LemonDialog, LemonSwitch, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonButton, LemonDialog, LemonMenu, LemonSwitch, Link, Tooltip } from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
import { TZLabel } from 'lib/components/TZLabel'
+import type { LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from 'lib/ui/quill'
import { urls } from 'scenes/urls'
import { AlertState, ProductKey } from '~/queries/schema/schema-general'
@@ -20,6 +20,7 @@ import { AlertStateIndicator } from '../components/AlertDefinition'
import { AlertsFiltersBar } from '../components/AlertsFiltersBar'
import { alertIntervalDisplayLabel } from '../logic/alertIntervalHelpers'
import { alertLogic } from '../logic/alertLogic'
+import { alertNotificationLogic } from '../logic/alertNotificationLogic'
import { alertsLogic } from '../logic/alertsLogic'
import { AlertType } from '../types'
import { EditAlertModal } from './EditAlertModal'
@@ -30,6 +31,47 @@ interface InsightAlertsProps {
alertId: AlertType['id'] | null
}
+interface AlertRowMenuProps {
+ alert: AlertType
+ destinationCount: number
+ deleting: boolean
+ onDelete: () => void
+}
+
+function AlertRowMenu({ alert, destinationCount, deleting, onDelete }: AlertRowMenuProps): JSX.Element {
+ const notificationLogic = alertNotificationLogic({ alertId: alert.id, loadDestinations: false })
+ const { testDeliveryResultLoading } = useValues(notificationLogic)
+ const { sendTestDelivery } = useActions(notificationLogic)
+
+ const canTestDelivery = alert.subscribed_users.some((user) => Boolean(user.email)) || destinationCount > 0
+ const menuItems: LemonMenuItems = [
+ canTestDelivery && {
+ label: 'Test delivery',
+ 'data-attr': 'insight-alert-row-send-test',
+ disabledReason: testDeliveryResultLoading ? 'Sending test delivery…' : null,
+ onClick: sendTestDelivery,
+ },
+ {
+ label: 'Delete',
+ status: 'danger' as const,
+ 'data-attr': 'insight-alert-row-delete',
+ disabledReason: deleting ? 'Deleting…' : null,
+ onClick: onDelete,
+ },
+ ]
+
+ return (
+ <LemonMenu items={menuItems} placement="bottom-end">
+ <LemonButton
+ type="tertiary"
+ size="small"
+ icon={<IconEllipsis />}
+ aria-label={`More options for ${alert.name}`}
+ />
+ </LemonMenu>
+ )
+}
+
export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {
const { push } = useActions(router)
const logic = alertsLogic()
@@ -42,6 +84,7 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {
alertsCount,
isFiltering,
togglingAlertIds,
+ alertDestinationCounts,
} = useValues(logic)
const { alert } = useValues(alertLogic({ alertId }))
@@ -155,44 +198,27 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {
{
title: '',
render: (_, alert) => (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <LemonButton
- type="tertiary"
- size="small"
- icon={<IconEllipsis />}
- aria-label={`More options for ${alert.name}`}
- />
- }
- />
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- variant="destructive"
- data-attr="insight-alert-row-delete"
- disabled={deletingAlertIds.has(alert.id)}
- onClick={() => {
- LemonDialog.open({
- title: `Delete "${alert.name}"?`,
- description:
- 'This alert will be permanently deleted. This action cannot be undone.',
- primaryButton: {
- children: 'Delete',
- type: 'primary',
- status: 'danger',
- onClick: () => deleteAlert(alert),
- 'data-attr': 'insight-alert-delete-confirm',
- },
- secondaryButton: {
- children: 'Cancel',
- },
- })
- }}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ <AlertRowMenu
+ alert={alert}
+ destinationCount={alertDestinationCounts[alert.id] ?? 0}
+ deleting={deletingAlertIds.has(alert.id)}
+ onDelete={() => {
+ LemonDialog.open({
+ title: `Delete "${alert.name}"?`,
+ description: 'This alert will be permanently deleted. This action cannot be undone.',
+ primaryButton: {
+ children: 'Delete',
+ type: 'primary',
+ status: 'danger',
+ onClick: () => deleteAlert(alert),
+ 'data-attr': 'insight-alert-delete-confirm',
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ },
+ })
+ }}
+ />
),
},
]
diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yaml
index f0748259608c..210870194a71 100644
--- a/products/alerts/mcp/tools.yaml
+++ b/products/alerts/mcp/tools.yaml
@@ -148,6 +148,9 @@ tools:
alerts-simulate-create:
operation: alerts_simulate_create
enabled: false
+ alerts-test-delivery-create:
+ operation: alerts_test_delivery_create
+ enabled: false
alerts-update:
operation: alerts_update
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bfc7e4588c36..e4109b174f9e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8797,6 +8797,27 @@ export namespace Schemas {
breakdown_results?: BreakdownSimulationResult[];
}
+ /**
+ * * `email` - email
+ * * `destination` - destination
+ */
+ export type FailedDeliveryChannelsEnum = typeof FailedDeliveryChannelsEnum[keyof typeof FailedDeliveryChannelsEnum];
+
+
+ export const FailedDeliveryChannelsEnum = {
+ Email: 'email',
+ Destination: 'destination',
+ } as const;
+
+ export interface AlertTestDeliveryResponse {
+ /** Number of active destinations queued for test delivery. */
+ destination_count: number;
+ /** Number of subscribed users sent a test email. */
+ email_recipient_count: number;
+ /** Configured delivery channels that failed to schedule or send. */
+ failed_delivery_channels: FailedDeliveryChannelsEnum[];
+ }
+
/**
* * `trace` - trace
* * `generation` - generation