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 snooze button to slack alert notifications (#72698)

Matt Brooker2a769f000554
diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts
index 56163ee94c81..5492d6f3e833 100644
--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts
+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts
@@ -967,6 +967,9 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Ho
{ type: 'divider' },
{
type: 'actions',
+ // The alert id in the block_id is what lets the datetimepicker action identify
+ // its alert — unlike select options, datetimepicker elements carry no value.
+ block_id: 'insight_alert_snooze:{event.properties.alert_id}',
elements: [
{
// Points to the anomaly investigation notebook when present, otherwise falls
@@ -984,6 +987,33 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Ho
text: { text: 'View Insight', type: 'plain_text' },
type: 'button',
},
+ {
+ action_id: 'insight_alert_snooze',
+ placeholder: { text: 'Snooze…', type: 'plain_text' },
+ options: [
+ {
+ text: { text: 'For 1 hour', type: 'plain_text' },
+ value: '{event.properties.alert_id}|1h',
+ },
+ {
+ text: { text: 'For 6 hours', type: 'plain_text' },
+ value: '{event.properties.alert_id}|6h',
+ },
+ {
+ text: { text: 'For 1 day', type: 'plain_text' },
+ value: '{event.properties.alert_id}|1d',
+ },
+ {
+ text: { text: 'For 1 week', type: 'plain_text' },
+ value: '{event.properties.alert_id}|1w',
+ },
+ {
+ text: { text: 'Pick a date & time…', type: 'plain_text' },
+ value: '{event.properties.alert_id}|custom',
+ },
+ ],
+ type: 'static_select',
+ },
],
},
],
diff --git a/posthog/models/activity_logging/model_activity.py b/posthog/models/activity_logging/model_activity.py
index 61db25fb15d9..032a4ed64d87 100644
--- a/posthog/models/activity_logging/model_activity.py
+++ b/posthog/models/activity_logging/model_activity.py
@@ -186,3 +186,30 @@ class ImpersonatedContext:
activity_storage.set_was_impersonated(True)
else:
activity_storage.clear_was_impersonated()
+
+
+class ActingUserContext:
+ """Attributes signal-driven activity logging to an explicit user outside request/middleware
+ context (background jobs, webhook handlers) where activity_storage would otherwise be empty
+ and the resulting log entries would record no actor. A `None` user makes this a no-op.
+ """
+
+ def __init__(self, user):
+ self.user = user
+ self.previous = None
+
+ def __enter__(self):
+ if self.user is not None:
+ # Save and restore rather than clear on exit, so a nested context can't
+ # silently erase an enclosing context's attribution.
+ self.previous = activity_storage.get_user()
+ activity_storage.set_user(self.user)
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ if self.user is None:
+ return
+ if self.previous is not None:
+ activity_storage.set_user(self.previous)
+ else:
+ activity_storage.clear_user()
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index 356b23baa85c..bbd6451d88b3 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -470,23 +470,21 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
if snoozed_until_param is None:
instance.state = AlertState.NOT_FIRING
instance.snoozed_until = None
+ AlertCheck.objects.create(
+ alert_configuration=instance,
+ calculated_value=None,
+ condition=instance.condition,
+ targets_notified={},
+ state=instance.state,
+ error=None,
+ )
else:
# always store snoozed_until as UTC time
# as we look at current UTC time to check when to run alerts
snoozed_until = relative_date_parse(
snoozed_until_param, ZoneInfo("UTC"), increase=True, always_truncate=True
)
- instance.state = AlertState.SNOOZED
- instance.snoozed_until = snoozed_until
-
- AlertCheck.objects.create(
- alert_configuration=instance,
- calculated_value=None,
- condition=instance.condition,
- targets_notified={},
- state=instance.state,
- error=None,
- )
+ instance.snooze(until=snoozed_until)
conditions_or_threshold_changed = False
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.py
index 295463e422b6..61e0da70cd2a 100644
--- a/products/alerts/backend/facade/api.py
+++ b/products/alerts/backend/facade/api.py
@@ -1,3 +1,19 @@
+import uuid
+from datetime import datetime, timedelta
+from typing import Literal
+from zoneinfo import ZoneInfo
+
+from django.db import transaction
+from django.utils import timezone
+
+import structlog
+
+from posthog.models.activity_logging.model_activity import ActingUserContext
+from posthog.models.user import User
+from posthog.rbac.user_access_control import UserAccessControl
+from posthog.user_permissions import UserPermissions
+from posthog.utils import relative_date_parse
+
from products.alerts.backend.destination_configs import (
DESTINATION_TEMPLATE_IDS,
AlertDestinationData,
@@ -12,14 +28,119 @@ from products.alerts.backend.destinations import (
soft_delete_all_alert_destinations,
)
from products.alerts.backend.email_notifications import send_alert_email
+from products.alerts.backend.models.alert import AlertConfiguration
+
+logger = structlog.get_logger(__name__)
+
+SlackSnoozeOutcome = Literal["snoozed", "no_access", "disabled", "not_found", "invalid_until"]
+
+# Mirrors the in-app SnoozeButton's DateFilter max — Slack's datetimepicker has no bounds of
+# its own, so the cap has to live here.
+SLACK_SNOOZE_MAX_DAYS = 31
+
+
+def get_alert_team_id(alert_id: uuid.UUID) -> int | None:
+ """The team an alert belongs to, or None if no such alert exists.
+
+ Lets callers outside this product (the Slack snooze-button handler) resolve an alert's team
+ — to find its workspace integration, and for region-ownership routing — without importing
+ the model directly.
+ """
+ # Slack webhook: no team context available yet — this lookup only resolves the team so the
+ # caller can find the workspace integration; authorization is derived from the alert row in
+ # snooze_alert_from_slack below, not from this lookup.
+ # nosemgrep: idor-lookup-without-team
+ return AlertConfiguration.objects.filter(id=alert_id).values_list("team_id", flat=True).first()
+
+
+def snooze_alert_from_slack(
+ alert_id: uuid.UUID, *, user: User, duration: str | None = None, until: datetime | None = None
+) -> SlackSnoozeOutcome:
+ """Snooze an alert on behalf of a Slack snooze interaction.
+
+ Takes exactly one of ``duration`` (a preset token like ``"1d"``, resolved with the same
+ ``relative_date_parse`` call the alerts API uses) or ``until`` (an absolute time from
+ Slack's datetimepicker, which must be in the future and at most ``SLACK_SNOOZE_MAX_DAYS``
+ out).
+
+ Owns all alert-side authorization and the mutation itself. `user` must already be confirmed
+ as a member of the alert's Slack-connected organization by the caller — the alert_id and
+ duration come from an untrusted Slack button value (user-editable hog function config), so
+ every access decision here is re-derived from the alert row, never taken on trust from the
+ caller.
+ """
+ if (duration is None) == (until is None):
+ raise ValueError("Pass exactly one of duration or until")
+ try:
+ # Slack webhook: no team context, and alert_id/duration come from an untrusted Slack
+ # button value. Authorization is derived below from the alert row itself (project
+ # membership + insight viewer access), never taken on trust from the caller.
+ # nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get
+ alert = AlertConfiguration.objects.select_related("insight", "team").get(id=alert_id)
+ except AlertConfiguration.DoesNotExist:
+ return "not_found"
+
+ # Mirrors TeamMemberAccessPermission (posthog/permissions.py): a non-admin member with no
+ # explicit membership in a private project must be denied, even though they belong to the
+ # organization. effective_membership_level falls back to the plain org membership level when
+ # the organization doesn't have ACCESS_CONTROL, so this never false-denies on non-EE orgs.
+ if UserPermissions(user).team(alert.team).effective_membership_level is None:
+ logger.warning("alert_snooze_no_project_membership", alert_id=str(alert_id), user_id=user.id)
+ return "no_access"
+
+ # Project membership doesn't imply access to every insight in it — mirrors
+ # _require_insight_viewer_access, the same check the alerts API itself uses.
+ if not UserAccessControl(user, team=alert.team).check_access_level_for_object(alert.insight, "viewer"):
+ logger.warning("alert_snooze_no_insight_access", alert_id=str(alert_id), user_id=user.id)
+ return "no_access"
+
+ if not alert.enabled:
+ # Fast path only — not the authoritative check. A concurrent disable between here and
+ # the row-locked re-check below must still be caught, so this just avoids taking a lock
+ # for the common case.
+ return "disabled"
+
+ if duration is not None:
+ # always store snoozed_until as UTC time, as we look at current UTC time to check when to
+ # run alerts — same call the alerts API uses so "1d" means the same thing everywhere.
+ snoozed_until = relative_date_parse(duration, ZoneInfo("UTC"), increase=True, always_truncate=True)
+ else:
+ assert until is not None
+ now = timezone.now()
+ if until <= now or until > now + timedelta(days=SLACK_SNOOZE_MAX_DAYS):
+ return "invalid_until"
+ snoozed_until = until.astimezone(ZoneInfo("UTC"))
+
+ with transaction.atomic():
+ try:
+ # Authoritative re-check under a row lock: without this, a concurrent disable
+ # between the fast-path check above and this mutation would still persist
+ # enabled=False alongside state=SNOOZED — a state the alert should never be in.
+ # nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get
+ locked_alert = AlertConfiguration.objects.select_for_update().get(id=alert_id)
+ except AlertConfiguration.DoesNotExist:
+ return "not_found"
+
+ if not locked_alert.enabled:
+ return "disabled"
+
+ with ActingUserContext(user):
+ locked_alert.snooze(until=snoozed_until)
+
+ return "snoozed"
+
__all__ = [
"DESTINATION_TEMPLATE_IDS",
"AlertDestinationData",
"AlertDestinationValidationError",
"DestinationType",
+ "SLACK_SNOOZE_MAX_DAYS",
+ "SlackSnoozeOutcome",
"build_alert_destination_config",
"create_alert_destination_hog_functions",
+ "get_alert_team_id",
+ "snooze_alert_from_slack",
"soft_delete_alert_destinations",
"soft_delete_all_alert_destinations",
"send_alert_email",
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index 5460555de631..1c17f9025bfb 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -4,7 +4,7 @@ from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING
from django.core.exceptions import ValidationError
-from django.db import models
+from django.db import models, transaction
if TYPE_CHECKING:
from posthog.event_usage import AnalyticsProps
@@ -229,6 +229,27 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
super().save(*args, **kwargs)
+ def snooze(self, *, until: datetime) -> AlertCheck:
+ """Snooze this alert until the given time, recording an audit AlertCheck row.
+
+ The check is created *after* save() so it reflects whatever actually got persisted —
+ save() forces a disabled alert's state back to NOT_FIRING, and the audit row must not
+ claim SNOOZED for an alert that was in fact left NOT_FIRING.
+ """
+ with transaction.atomic():
+ self.state = AlertState.SNOOZED
+ self.snoozed_until = until
+ self.save(update_fields=["state", "snoozed_until"])
+
+ return AlertCheck.objects.create(
+ alert_configuration=self,
+ calculated_value=None,
+ condition=self.condition,
+ targets_notified={},
+ state=self.state,
+ error=None,
+ )
+
def _get_event_properties(self) -> dict:
detector_config = self.detector_config or {}
detector_type = detector_config.get("type")
diff --git a/products/cdp/mcp/cdp_functions.yaml b/products/cdp/mcp/cdp_functions.yaml
index f76687ccf3f2..604eaaf358c9 100644
--- a/products/cdp/mcp/cdp_functions.yaml
+++ b/products/cdp/mcp/cdp_functions.yaml
@@ -61,11 +61,20 @@ tools:
{"type": "context", "elements": [{"type": "mrkdwn",
"text": "Project: <{project.url}|{project.name}>"}]},
{"type": "divider"},
- {"type": "actions", "elements": [
+ {"type": "actions", "block_id": "insight_alert_snooze:{event.properties.alert_id}", "elements": [
{"type": "button", "text": {"type": "plain_text", "text": "View Insight"},
"url": "{project.url}/insights/{event.properties.insight_id}"},
{"type": "button", "text": {"type": "plain_text", "text": "View Alert"},
- "url": "{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}"}
+ "url": "{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}"},
+ {"type": "static_select", "action_id": "insight_alert_snooze",
+ "placeholder": {"type": "plain_text", "text": "Snooze…"},
+ "options": [
+ {"text": {"type": "plain_text", "text": "For 1 hour"}, "value": "{event.properties.alert_id}|1h"},
+ {"text": {"type": "plain_text", "text": "For 6 hours"}, "value": "{event.properties.alert_id}|6h"},
+ {"text": {"type": "plain_text", "text": "For 1 day"}, "value": "{event.properties.alert_id}|1d"},
+ {"text": {"type": "plain_text", "text": "For 1 week"}, "value": "{event.properties.alert_id}|1w"},
+ {"text": {"type": "plain_text", "text": "Pick a date & time…"}, "value": "{event.properties.alert_id}|custom"}
+ ]}
]}
]}
}
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 2d038d4ccadc..5b7dbf119cb8 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -5,6 +5,7 @@ import uuid
import asyncio
import hashlib
from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
from typing import Any, Literal
from urllib.parse import urlparse, urlunparse
@@ -1305,7 +1306,10 @@ def resolve_posthog_user_from_event(
The probe is used to call Slack's ``users.info``; the candidate list scopes
the organization-membership check. A user with no membership in any
- connected org returns ``None`` so the caller can refuse the event.
+ connected org returns ``None`` so the caller can refuse the event. A
+ deactivated user is treated the same as "no membership" — every caller of
+ this helper (dismiss, channel approval, alert snooze, ...) authorizes off
+ the returned ``User``, so a deactivated account must not resolve to one.
``slack_email`` may be passed by callers that already have it (e.g.
``resolve_user_and_integrations``) so we don't repeat the cache lookup.
@@ -1325,7 +1329,7 @@ def resolve_posthog_user_from_event(
candidate_org_ids=org_ids,
)
if linked_user is not None and is_slack_app_oauth_enabled(probe_integration, slack_team_id):
- return linked_user
+ return linked_user if linked_user.is_active else None
if slack_email is None:
slack_email = get_slack_email_for_user(probe_integration, slack_user_id)
@@ -1333,7 +1337,9 @@ def resolve_posthog_user_from_event(
return None
try:
membership = (
- OrganizationMembership.objects.filter(organization_id__in=org_ids, user__email__iexact=slack_email)
+ OrganizationMembership.objects.filter(
+ organization_id__in=org_ids, user__email__iexact=slack_email, user__is_active=True
+ )
.select_related("user")
.first()
)
@@ -3285,30 +3291,364 @@ def _handle_signals_dismiss_report(payload: dict) -> HttpResponse:
return HttpResponse(status=200)
-def _post_signals_dismiss_feedback(payload: dict, *, dismissed: bool, slack_user_id: str) -> None:
- """Best-effort: replace the original message so it reads as dismissed."""
+def _replace_message_stripping_actions(payload: dict, text: str, *, keep_link_buttons: bool = True) -> None:
+ """Best-effort: replace the original message's interactive buttons with a context line.
+
+ When keep_link_buttons is True, link buttons (elements with a "url" key, e.g. "View in
+ PostHog") are preserved instead of being dropped along with the interactive ones.
+ """
response_url = payload.get("response_url")
if not response_url:
return
+ original_message = payload.get("message", {})
+ kept_blocks = []
+ for block in original_message.get("blocks", []):
+ if block.get("type") != "actions":
+ kept_blocks.append(block)
+ continue
+ if keep_link_buttons:
+ kept_elements = [el for el in block.get("elements", []) if "url" in el]
+ if kept_elements:
+ kept_blocks.append({**block, "elements": kept_elements})
+ kept_blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": text}]})
+
+ inbox_interactivity.post_response_url(response_url, {"replace_original": True, "text": text, "blocks": kept_blocks})
+
+
+def _post_signals_dismiss_feedback(payload: dict, *, dismissed: bool, slack_user_id: str) -> None:
+ """Best-effort: replace the original message so it reads as dismissed."""
if dismissed:
actor = f"<@{slack_user_id}>" if slack_user_id else "a reviewer"
text = f"✅ Dismissed by {actor}"
else:
text = "This report could not be dismissed — it may already be resolved or removed."
- original_message = payload.get("message", {})
- kept_blocks = [b for b in original_message.get("blocks", []) if b.get("type") != "actions"]
- kept_blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": text}]})
+ # keep_link_buttons=False: historical dismiss-capable messages carried "Review PR"/"Open in
+ # PostHog" link buttons in the same actions block as Dismiss (see the pre-removal
+ # slack_inbox_notifications.py block construction), so dropping the whole block here matches
+ # existing behavior rather than the default.
+ _replace_message_stripping_actions(payload, text, keep_link_buttons=False)
+
+
+# Snoozes an insight alert from the button on its firing Slack message.
+INSIGHT_ALERT_SNOOZE_ACTION_ID = "insight_alert_snooze"
+INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID = "insight_alert_snooze_until"
+# Slack's datetimepicker element can't carry a custom value, so the alert id rides on the
+# actions block's block_id instead (set by the alert-firing sub-template).
+INSIGHT_ALERT_SNOOZE_BLOCK_ID_PREFIX = "insight_alert_snooze:"
+
+INSIGHT_ALERT_SNOOZE_DURATION_LABELS: dict[str, str] = {
+ "1h": "1 hour",
+ "6h": "6 hours",
+ "1d": "1 day",
+ "1w": "1 week",
+}
+# Dropdown option that opens a modal date/time picker instead of snoozing immediately.
+INSIGHT_ALERT_SNOOZE_CUSTOM_TOKEN = "custom"
+INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID = "insight_alert_snooze_modal"
+INSIGHT_ALERT_SNOOZE_MODAL_DATE_BLOCK = "snooze_date"
+INSIGHT_ALERT_SNOOZE_MODAL_TIME_BLOCK = "snooze_time"
+
+
+def _insight_alert_snooze_action(payload: dict) -> dict | None:
+ return next(
+ (
+ a
+ for a in payload.get("actions", [])
+ if a.get("action_id") in (INSIGHT_ALERT_SNOOZE_ACTION_ID, INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID)
+ ),
+ None,
+ )
+
+
+def _parse_insight_alert_snooze_value(value: str) -> tuple[uuid.UUID, str] | None:
+ parts = value.split("|")
+ if len(parts) != 2:
+ return None
+ alert_uuid_str, duration = parts
+ if duration not in INSIGHT_ALERT_SNOOZE_DURATION_LABELS and duration != INSIGHT_ALERT_SNOOZE_CUSTOM_TOKEN:
+ return None
+ try:
+ alert_uuid = uuid.UUID(alert_uuid_str)
+ except (ValueError, AttributeError, TypeError):
+ return None
+ return alert_uuid, duration
+
+
+def _parse_insight_alert_snooze_action(action: dict) -> tuple[uuid.UUID, str | None, datetime | None] | None:
+ """Normalize the three snooze action shapes to (alert_uuid, duration_token, until).
+
+ Shapes: the preset static_select (value on selected_option), the legacy single button from
+ already-posted messages (value on the action itself), and the datetimepicker (unix timestamp
+ on selected_date_time, alert id on the block_id).
+ """
+ if action.get("action_id") == INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID:
+ block_id = action.get("block_id", "")
+ if not isinstance(block_id, str) or not block_id.startswith(INSIGHT_ALERT_SNOOZE_BLOCK_ID_PREFIX):
+ return None
+ try:
+ alert_uuid = uuid.UUID(block_id[len(INSIGHT_ALERT_SNOOZE_BLOCK_ID_PREFIX) :])
+ except (ValueError, AttributeError, TypeError):
+ return None
+ selected = action.get("selected_date_time")
+ if not isinstance(selected, int):
+ return None
+ try:
+ until = datetime.fromtimestamp(selected, tz=UTC)
+ except (OverflowError, OSError, ValueError):
+ return None
+ return alert_uuid, None, until
+
+ selected_option = action.get("selected_option")
+ value = selected_option.get("value") if isinstance(selected_option, dict) else action.get("value", "")
+ if not isinstance(value, str):
+ return None
+ parsed = _parse_insight_alert_snooze_value(value)
+ if parsed is None:
+ return None
+ return parsed[0], parsed[1], None
+
+
+def _snooze_modal_alert_uuid(view: dict) -> uuid.UUID | None:
+ """Alert UUID stashed in the snooze modal's private_metadata."""
+ try:
+ meta = json.loads(view.get("private_metadata", "") or "{}")
+ return uuid.UUID(meta.get("alert_id"))
+ except (json.JSONDecodeError, TypeError, ValueError, AttributeError):
+ return None
+
+
+def _extract_alert_snooze_hints(payload: dict) -> uuid.UUID | None:
+ """Alert UUID carried by a snooze interaction, used for region-ownership routing.
+
+ Covers both the dropdown/button block_actions and the date/time modal's view_submission
+ (which carries the alert id in private_metadata, not in an action).
+ """
+ view = payload.get("view")
+ if isinstance(view, dict) and view.get("callback_id") == INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID:
+ return _snooze_modal_alert_uuid(view)
+ action = _insight_alert_snooze_action(payload)
+ if not action:
+ return None
+ parsed = _parse_insight_alert_snooze_action(action)
+ return parsed[0] if parsed else None
+
+
+def _handle_insight_alert_snooze(payload: dict) -> HttpResponse:
+ """Snooze an insight alert when a user clicks 'Snooze' on its firing Slack message.
+
+ Only Slack-side concerns live here (parsing, workspace-integration match, org membership) —
+ alert-side authorization and the mutation itself belong to products.alerts and are reached
+ through its facade, never a direct cross-product model import (see tach.toml).
+ """
+ action = _insight_alert_snooze_action(payload)
+ slack_team_id = payload.get("team", {}).get("id")
+ if not action or not slack_team_id:
+ return HttpResponse(status=200)
+
+ parsed = _parse_insight_alert_snooze_action(action)
+ if parsed is None:
+ logger.info("insight_alert_snooze_malformed_value")
+ return HttpResponse(status=200)
+ alert_uuid, duration, until = parsed
+
+ from products.alerts.backend.facade.api import ( # noqa: PLC0415 — cross-product calls kept off the slack import path
+ SLACK_SNOOZE_MAX_DAYS,
+ get_alert_team_id,
+ snooze_alert_from_slack,
+ )
+
+ alert_team_id = get_alert_team_id(alert_uuid)
+ if alert_team_id is None:
+ logger.info("insight_alert_snooze_no_alert", alert_id=str(alert_uuid))
+ return HttpResponse(status=200)
+
+ try:
+ # Proves the Slack workspace the click came from is connected to the alert's team.
+ # nosemgrep: idor-lookup-without-team
+ integration = Integration.objects.get(
+ kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id, team_id=alert_team_id
+ )
+ except Integration.DoesNotExist:
+ logger.info("insight_alert_snooze_no_integration", alert_id=str(alert_uuid), slack_team_id=slack_team_id)
+ return HttpResponse(status=200)
+
+ slack_user_id = payload.get("user", {}).get("id", "")
+ org_member = _is_org_member(integration, slack_user_id)
+ if org_member is None:
+ logger.warning("insight_alert_snooze_not_org_member", alert_id=str(alert_uuid), slack_user_id=slack_user_id)
+ return HttpResponse(status=200)
+
+ # "Pick a date & time…" opens a modal instead of snoozing now. The real snooze happens on
+ # modal submit (_handle_insight_alert_snooze_modal_submit), which re-runs this same auth.
+ if duration == INSIGHT_ALERT_SNOOZE_CUSTOM_TOKEN:
+ _open_insight_alert_snooze_modal(integration, payload, alert_uuid)
+ return HttpResponse(status=200)
+
+ # Everything below this point is untrusted alert_id/duration re-derived from the alert row
+ # itself, not the Slack button value — see snooze_alert_from_slack's docstring.
+ outcome = snooze_alert_from_slack(alert_uuid, duration=duration, until=until, user=org_member)
+
+ if outcome == "not_found":
+ # Existed at get_alert_team_id but is gone now (race, e.g. concurrent delete) — same
+ # silent drop as the earlier not-found check.
+ logger.info("insight_alert_snooze_no_alert", alert_id=str(alert_uuid))
+ return HttpResponse(status=200)
+ if outcome == "no_access":
+ logger.warning("insight_alert_snooze_no_access", alert_id=str(alert_uuid), slack_user_id=slack_user_id)
+ return HttpResponse(status=200)
+ if outcome == "disabled":
+ logger.info("insight_alert_snooze_alert_disabled", alert_id=str(alert_uuid))
+ _replace_message_stripping_actions(payload, "This alert is disabled, so there is nothing to snooze.")
+ return HttpResponse(status=200)
+ if outcome == "invalid_until":
+ logger.info("insight_alert_snooze_invalid_until", alert_id=str(alert_uuid))
+ response_url = payload.get("response_url")
+ if response_url:
+ # Ephemeral so a bad pick doesn't clobber the alert message — the pickers stay usable.
+ inbox_interactivity.post_response_url(
+ response_url,
+ {
+ "response_type": "ephemeral",
+ "replace_original": False,
+ "text": f"Pick a time in the next {SLACK_SNOOZE_MAX_DAYS} days.",
+ },
+ )
+ return HttpResponse(status=200)
+
+ if duration is not None:
+ snoozed_wording = f"for {INSIGHT_ALERT_SNOOZE_DURATION_LABELS[duration]}"
+ else:
+ assert until is not None
+ snoozed_wording = f"until {until.strftime('%Y-%m-%d %H:%M')} UTC"
+ actor = f"<@{slack_user_id}>" if slack_user_id else "a teammate"
+ _replace_message_stripping_actions(payload, f"😴 Snoozed {snoozed_wording} by {actor}")
+ return HttpResponse(status=200)
+
+
+def _render_insight_alert_snooze_modal(private_metadata: str) -> dict:
+ tomorrow = (timezone.now() + timedelta(days=1)).date().isoformat()
+ return {
+ "type": "modal",
+ "callback_id": INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID,
+ "private_metadata": private_metadata,
+ "title": {"type": "plain_text", "text": "Snooze alert"},
+ "submit": {"type": "plain_text", "text": "Snooze"},
+ "close": {"type": "plain_text", "text": "Cancel"},
+ "blocks": [
+ {
+ "type": "input",
+ "block_id": INSIGHT_ALERT_SNOOZE_MODAL_DATE_BLOCK,
+ "label": {"type": "plain_text", "text": "Snooze until date"},
+ "element": {"type": "datepicker", "action_id": "date", "initial_date": tomorrow},
+ },
+ {
+ "type": "input",
+ "block_id": INSIGHT_ALERT_SNOOZE_MODAL_TIME_BLOCK,
+ "label": {"type": "plain_text", "text": "Time (UTC)"},
+ "element": {"type": "timepicker", "action_id": "time", "initial_time": "09:00"},
+ },
+ ],
+ }
+
+
+def _open_insight_alert_snooze_modal(integration: Integration, payload: dict, alert_uuid: uuid.UUID) -> None:
+ trigger_id = payload.get("trigger_id")
+ if not trigger_id:
+ return
+ container = payload.get("container", {}) or {}
+ private_metadata = json.dumps(
+ {
+ "alert_id": str(alert_uuid),
+ "channel": (payload.get("channel") or {}).get("id") or container.get("channel_id"),
+ "message_ts": (payload.get("message") or {}).get("ts") or container.get("message_ts"),
+ }
+ )
+ try:
+ SlackIntegration(integration).client.views_open(
+ trigger_id=trigger_id, view=_render_insight_alert_snooze_modal(private_metadata)
+ )
+ except Exception:
+ logger.exception("insight_alert_snooze_modal_open_failed", alert_id=str(alert_uuid))
+
+
+def _snooze_modal_error(message: str) -> JsonResponse:
+ # A view_submission error keeps the modal open and shows the message under the date field.
+ return JsonResponse({"response_action": "errors", "errors": {INSIGHT_ALERT_SNOOZE_MODAL_DATE_BLOCK: message}})
+
+def _handle_insight_alert_snooze_modal_submit(payload: dict) -> HttpResponse:
+ """Snooze an alert to the date/time picked in the modal opened from the 'Pick a date & time…'
+ dropdown option. Re-runs the same workspace/org authorization the block-action path does —
+ a modal can be submitted by anyone who has it open, so the submit is the authoritative gate.
+ """
+ view = payload.get("view", {})
+ try:
+ meta = json.loads(view.get("private_metadata", "") or "{}")
+ alert_uuid = uuid.UUID(meta.get("alert_id"))
+ except (json.JSONDecodeError, TypeError, ValueError, AttributeError):
+ return HttpResponse(status=200)
+
+ values = view.get("state", {}).get("values", {})
+ selected_date = values.get(INSIGHT_ALERT_SNOOZE_MODAL_DATE_BLOCK, {}).get("date", {}).get("selected_date")
+ selected_time = values.get(INSIGHT_ALERT_SNOOZE_MODAL_TIME_BLOCK, {}).get("time", {}).get("selected_time")
+ if not selected_date or not selected_time:
+ return _snooze_modal_error("Pick a date and time.")
+ try:
+ until = datetime.strptime(f"{selected_date} {selected_time}", "%Y-%m-%d %H:%M").replace(tzinfo=UTC)
+ except ValueError:
+ return _snooze_modal_error("Pick a date and time.")
+
+ slack_team_id = payload.get("team", {}).get("id")
+ slack_user_id = payload.get("user", {}).get("id", "")
+
+ from products.alerts.backend.facade.api import ( # noqa: PLC0415 — cross-product calls kept off the slack import path
+ SLACK_SNOOZE_MAX_DAYS,
+ get_alert_team_id,
+ snooze_alert_from_slack,
+ )
+
+ alert_team_id = get_alert_team_id(alert_uuid)
+ if alert_team_id is None or not slack_team_id:
+ return HttpResponse(status=200)
+ try:
+ # nosemgrep: idor-lookup-without-team
+ integration = Integration.objects.get(
+ kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id, team_id=alert_team_id
+ )
+ except Integration.DoesNotExist:
+ return HttpResponse(status=200)
+
+ org_member = _is_org_member(integration, slack_user_id)
+ if org_member is None:
+ return _snooze_modal_error("You don't have access to this alert.")
+
+ outcome = snooze_alert_from_slack(alert_uuid, until=until, user=org_member)
+ if outcome == "invalid_until":
+ return _snooze_modal_error(f"Pick a time in the next {SLACK_SNOOZE_MAX_DAYS} days.")
+ if outcome in ("no_access", "not_found", "disabled"):
+ logger.info("insight_alert_snooze_modal_submit_rejected", alert_id=str(alert_uuid), outcome=outcome)
+ return HttpResponse(status=200)
+
+ _post_insight_alert_snooze_modal_confirmation(integration, meta, until, slack_user_id)
+ return HttpResponse(status=200)
+
+
+def _post_insight_alert_snooze_modal_confirmation(
+ integration: Integration, meta: dict, until: datetime, slack_user_id: str
+) -> None:
+ channel = meta.get("channel")
+ if not channel:
+ return
+ actor = f"<@{slack_user_id}>" if slack_user_id else "a teammate"
+ text = f"😴 Snoozed until {until.strftime('%Y-%m-%d %H:%M')} UTC by {actor}"
try:
- requests.post(
- response_url,
- json={"replace_original": True, "text": text, "blocks": kept_blocks},
- timeout=5,
+ SlackIntegration(integration).client.chat_postMessage(
+ channel=channel, thread_ts=meta.get("message_ts"), text=text
)
- except requests.RequestException as e:
- logger.warning("signals_dismiss_report_feedback_failed", error=str(e))
+ except Exception:
+ logger.warning("insight_alert_snooze_modal_confirm_failed")
def _handle_terminate_task_submit(payload: dict) -> HttpResponse:
@@ -3369,6 +3709,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
terminate_integration_id, terminate_user_id = _extract_terminate_hints(payload)
authorship_integration_id, _ = _extract_action_value_hints(payload, "posthog_code_continue_as_bot")
dismiss_integration_id = _extract_dismiss_hints(payload)
+ alert_snooze_uuid = _extract_alert_snooze_hints(payload)
inbox_integration_id = inbox_interactivity.extract_inbox_hints(payload)
requesting_user = payload.get("user", {}).get("id", "")
slack_team_id = payload.get("team", {}).get("id")
@@ -3410,6 +3751,17 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
kind=SLACK_INTEGRATION_KIND,
integration_id=slack_team_id,
).exists()
+ elif slack_team_id and alert_snooze_uuid:
+ # Alert UUIDs are globally unique per region (each region has its own DB), so a local
+ # existence check alone settles region ownership — no need to consult Integration here.
+ # Authorization (workspace-integration match + org-member gate) is enforced in
+ # _handle_insight_alert_snooze. Routed through the alerts facade rather than the model
+ # directly — see tach.toml, products.slack_app doesn't depend on products.alerts's internals.
+ from products.alerts.backend.facade.api import ( # noqa: PLC0415 — cross-product lookup kept off the slack import path
+ get_alert_team_id,
+ )
+
+ local = get_alert_team_id(alert_snooze_uuid) is not None
elif slack_team_id and inbox_integration_id:
# Inbox onboarding buttons (create/join) are DMed to a user; any clicker may act, so this
# is gated only on owning the integration locally.
@@ -3501,6 +3853,8 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
return _handle_repo_picker_options(payload)
if payload_type == "view_submission":
+ if payload.get("view", {}).get("callback_id") == INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID:
+ return _handle_insight_alert_snooze_modal_submit(payload)
return _handle_app_home_view_submission(payload)
if payload_type == "block_actions":
@@ -3521,6 +3875,8 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
return _handle_channel_approval_deny(payload)
if action_id == SIGNALS_DISMISS_REPORT_ACTION_ID:
return _handle_signals_dismiss_report(payload)
+ if action_id in (INSIGHT_ALERT_SNOOZE_ACTION_ID, INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID):
+ return _handle_insight_alert_snooze(payload)
if action_id == onboarding.INBOX_CREATE_ACTION_ID:
return inbox_interactivity.handle_inbox_create(payload)
if action_id == onboarding.INBOX_JOIN_ACTION_ID:
diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
index b8b52ada8f62..0b8209cd7f70 100644
--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py
+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
@@ -1,8 +1,12 @@
import json
import time
+import uuid
+from datetime import UTC, datetime
from types import SimpleNamespace
-from typing import Any
+from typing import TYPE_CHECKING, Any
+from zoneinfo import ZoneInfo
+from freezegun import freeze_time
from unittest.mock import AsyncMock, MagicMock, patch
from django.core.cache import cache
@@ -11,13 +15,32 @@ from django.test import TestCase, override_settings
from parameterized import parameterized
from rest_framework.test import APIClient
+from posthog.constants import AvailableFeature
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.integration import Integration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
-
+from posthog.schema_enums import AlertState
+from posthog.utils import relative_date_parse
+
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
+from products.slack_app.backend.api import (
+ _extract_alert_snooze_hints,
+ _handle_insight_alert_snooze,
+ _handle_insight_alert_snooze_modal_submit,
+)
from products.slack_app.backend.tests.helpers import sign_slack_request
+if TYPE_CHECKING:
+ from ee.models.rbac.access_control import AccessControl
+else:
+ try:
+ from ee.models.rbac.access_control import AccessControl
+ except ImportError:
+ AccessControl = None
+
class TestPostHogCodeInteractivityHandler(TestCase):
def setUp(self):
@@ -905,7 +928,7 @@ class TestSignalsDismissReport(TestCase):
)
@patch("products.slack_app.backend.api._is_org_member")
- @patch("products.slack_app.backend.api.requests.post")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
@patch("products.slack_app.backend.api.SlackIntegration.slack_config")
def test_dismiss_suppresses_report_and_writes_artefact(self, mock_config, mock_requests_post, mock_is_org_member):
from products.signals.backend.models import SignalReport, SignalReportArtefact
@@ -926,7 +949,7 @@ class TestSignalsDismissReport(TestCase):
assert mock_requests_post.call_args.kwargs["json"]["replace_original"] is True
@patch("products.slack_app.backend.api._is_org_member")
- @patch("products.slack_app.backend.api.requests.post")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
@patch("products.slack_app.backend.api.SlackIntegration.slack_config")
def test_dismiss_refuses_non_org_member(self, mock_config, mock_requests_post, mock_is_org_member):
from products.signals.backend.models import SignalReport
@@ -941,7 +964,7 @@ class TestSignalsDismissReport(TestCase):
report.refresh_from_db()
assert report.status == SignalReport.Status.READY # not suppressed
- @patch("products.slack_app.backend.api.requests.post")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
@patch("products.slack_app.backend.api.SlackIntegration.slack_config")
def test_dismiss_ignores_report_from_another_team(self, mock_config, mock_requests_post):
from products.signals.backend.models import SignalReport
@@ -955,3 +978,543 @@ class TestSignalsDismissReport(TestCase):
assert response.status_code == 200
report.refresh_from_db()
assert report.status == SignalReport.Status.READY
+
+
+class TestInsightAlertSnooze(TestCase):
+ def setUp(self):
+ self.client = APIClient()
+ self.signing_secret = "posthog-code-test-secret"
+
+ self.organization = Organization.objects.create(name="Snooze Org")
+ self.team = Team.objects.create(organization=self.organization, name="Snooze Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="snooze-user-1")
+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T12345",
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+ self.insight = Insight.objects.create(team=self.team, short_id="insight1", name="Signups")
+ self.alert = AlertConfiguration.objects.create(
+ team=self.team,
+ insight=self.insight,
+ name="Signups alert",
+ state=AlertState.FIRING,
+ )
+
+ def _snooze_payload(self, value: str, *, slack_user_id: str = "U777") -> dict:
+ return self._payload_with_action(
+ {"action_id": "insight_alert_snooze", "value": value}, slack_user_id=slack_user_id
+ )
+
+ def _snooze_select_payload(self, value: str) -> dict:
+ return self._payload_with_action({"action_id": "insight_alert_snooze", "selected_option": {"value": value}})
+
+ def _snooze_until_payload(self, selected_date_time: int) -> dict:
+ return self._payload_with_action(
+ {
+ "action_id": "insight_alert_snooze_until",
+ "block_id": f"insight_alert_snooze:{self.alert.id}",
+ "selected_date_time": selected_date_time,
+ }
+ )
+
+ def _payload_with_action(self, action: dict, *, slack_user_id: str = "U777") -> dict:
+ return {
+ "type": "block_actions",
+ "team": {"id": "T12345"},
+ "user": {"id": slack_user_id},
+ "response_url": "https://hooks.slack.test/response",
+ "actions": [action],
+ "message": {
+ "ts": "1234.9999",
+ "blocks": [
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "action_id": "insight_alert_snooze",
+ "text": {"type": "plain_text", "text": "Snooze 1d"},
+ },
+ {"type": "button", "action_id": "view_alert", "url": "https://app.posthog.com/alerts/1"},
+ ],
+ }
+ ],
+ },
+ }
+
+ def _post_interactivity(self, payload: dict) -> Any:
+ body_str = f"payload={json.dumps(payload)}"
+ signature, ts = sign_slack_request(body_str.encode(), self.signing_secret)
+ return self.client.post(
+ "/slack/interactivity-callback/",
+ data=body_str,
+ content_type="application/x-www-form-urlencoded",
+ HTTP_X_SLACK_SIGNATURE=signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ )
+
+ @parameterized.expand(["1h", "6h", "1d", "1w"])
+ @freeze_time("2026-07-21T12:34:56Z")
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_sets_state_and_snoozed_until(
+ self, duration_token, mock_config, mock_requests_post, mock_is_org_member
+ ):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = self.user
+
+ # Duration tokens use the same relative_date_parse call (with always_truncate) as the
+ # alerts REST API's snooze path, so "1d"/"1w" snap to a UTC day boundary rather than
+ # landing exactly 24h/7d from the click — this locks in that the Slack path means the
+ # same thing the API does for the same token.
+ expected_snoozed_until = relative_date_parse(
+ duration_token, ZoneInfo("UTC"), increase=True, always_truncate=True
+ )
+ response = self._post_interactivity(self._snooze_select_payload(f"{self.alert.id}|{duration_token}"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.SNOOZED
+ assert self.alert.snoozed_until == expected_snoozed_until
+
+ assert AlertCheck.objects.filter(alert_configuration=self.alert, state=AlertState.SNOOZED).exists()
+
+ # Attributed to the resolved Slack clicker, not left blank — activity_storage has no
+ # user set in a webhook request, so this only passes if the handler attributes the save.
+ # Filtered to "updated" specifically since setUp's alert creation also logs an entry
+ # (with no actor) under the same scope/item_id.
+ activity_log = ActivityLog.objects.get(
+ scope="AlertConfiguration", item_id=str(self.alert.id), activity="updated"
+ )
+ assert activity_log.user_id == self.user.id
+
+ posted_blocks = mock_requests_post.call_args.kwargs["json"]["blocks"]
+ actions_block = next(b for b in posted_blocks if b["type"] == "actions")
+ assert all(el.get("action_id") != "insight_alert_snooze" for el in actions_block["elements"])
+ assert mock_requests_post.call_args.kwargs["json"]["replace_original"] is True
+
+ @freeze_time("2026-07-21T12:34:56Z")
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_legacy_button_shape_still_works(self, mock_config, mock_requests_post, mock_is_org_member):
+ # Messages posted before the select/datetimepicker template carry the value on the
+ # action itself — removing that fallback would break every already-delivered message.
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = self.user
+
+ response = self._post_interactivity(self._snooze_payload(f"{self.alert.id}|1d"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.SNOOZED
+ assert self.alert.snoozed_until == relative_date_parse(
+ "1d", ZoneInfo("UTC"), increase=True, always_truncate=True
+ )
+
+ @freeze_time("2026-07-21T12:34:56Z")
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_until_sets_exact_time(self, mock_config, mock_requests_post, mock_is_org_member):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = self.user
+
+ picked = datetime(2026, 7, 23, 9, 30, tzinfo=UTC)
+ response = self._post_interactivity(self._snooze_until_payload(int(picked.timestamp())))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.SNOOZED
+ assert self.alert.snoozed_until == picked
+ assert "Snoozed until 2026-07-23 09:30 UTC" in mock_requests_post.call_args.kwargs["json"]["text"]
+
+ @parameterized.expand(
+ [
+ ("in_the_past", -3600),
+ ("beyond_31_days", 32 * 24 * 3600),
+ ]
+ )
+ @freeze_time("2026-07-21T12:34:56Z")
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_until_rejects_out_of_bounds(
+ self, _name, offset_seconds, mock_config, mock_requests_post, mock_is_org_member
+ ):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = self.user
+
+ picked = int(datetime(2026, 7, 21, 12, 34, 56, tzinfo=UTC).timestamp()) + offset_seconds
+ response = self._post_interactivity(self._snooze_until_payload(picked))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+ # Feedback is ephemeral so a bad pick doesn't destroy the alert message and its pickers.
+ feedback = mock_requests_post.call_args.kwargs["json"]
+ assert feedback["response_type"] == "ephemeral"
+ assert feedback["replace_original"] is False
+
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_refuses_non_org_member(self, mock_config, mock_requests_post, mock_is_org_member):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = None
+
+ response = self._post_interactivity(self._snooze_payload(f"{self.alert.id}|1d"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+ mock_requests_post.assert_not_called()
+
+ @patch("products.slack_app.backend.api.get_slack_email_for_user")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_refuses_inactive_user(self, mock_config, mock_requests_post, mock_get_email):
+ # Exercises the real resolve_posthog_user_from_event path (not _is_org_member mocked
+ # away) so the user__is_active filter on the membership query actually runs — a
+ # deactivated user still in the workspace must not be able to snooze via an old message.
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ inactive_user = User.objects.create(
+ email="[email protected]", distinct_id="inactive-snoozer-1", is_active=False
+ )
+ OrganizationMembership.objects.create(user=inactive_user, organization=self.organization)
+ mock_get_email.return_value = inactive_user.email
+
+ response = self._post_interactivity(self._snooze_payload(f"{self.alert.id}|1d"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+ mock_requests_post.assert_not_called()
+
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_ignores_integration_from_another_team(self, mock_config, mock_requests_post):
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ self.integration.team = other_team
+ self.integration.save(update_fields=["team"])
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+
+ response = self._post_interactivity(self._snooze_payload(f"{self.alert.id}|1d"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+ mock_requests_post.assert_not_called()
+
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_refuses_without_project_membership(self, mock_config, mock_requests_post, mock_is_org_member):
+ # A non-admin org member with no explicit membership in a private project must be
+ # denied, even though they pass the org-membership check — mirrors
+ # TeamMemberAccessPermission on the API path.
+ if AccessControl is None:
+ self.skipTest("EE not available")
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = self.user
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"
+ )
+ OrganizationMembership.objects.filter(organization=self.organization, user=self.user).update(
+ level=OrganizationMembership.Level.MEMBER
+ )
+
+ response = self._post_interactivity(self._snooze_payload(f"{self.alert.id}|1d"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+ mock_requests_post.assert_not_called()
+
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_refuses_without_insight_access(self, mock_config, mock_requests_post, mock_is_org_member):
+ # Project membership doesn't imply access to every insight in it — mirrors the real
+ # alerts API, which gates on viewer access to the alert's specific insight.
+ if AccessControl is None:
+ self.skipTest("EE not available")
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = self.user
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ membership = OrganizationMembership.objects.get(organization=self.organization, user=self.user)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="insight",
+ resource_id=str(self.insight.id),
+ organization_member=membership,
+ access_level="none",
+ )
+
+ response = self._post_interactivity(self._snooze_payload(f"{self.alert.id}|1d"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+ mock_requests_post.assert_not_called()
+
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_snooze_disabled_alert_is_a_noop(self, mock_config, mock_requests_post, mock_is_org_member):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = self.user
+ self.alert.enabled = False
+ self.alert.save(update_fields=["enabled"])
+
+ response = self._post_interactivity(self._snooze_payload(f"{self.alert.id}|1d"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.snoozed_until is None
+ assert (
+ mock_requests_post.call_args.kwargs["json"]["text"]
+ == "This alert is disabled, so there is nothing to snooze."
+ )
+
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_malformed_value_is_dropped_before_reaching_handler(self, mock_config, mock_requests_post):
+ # _extract_alert_snooze_hints returns None for a value it can't parse, so the routing
+ # check never claims locality and the payload is dropped before _handle_insight_alert_snooze
+ # runs at all. This only proves the endpoint doesn't crash on garbage input — the guards
+ # inside the handler itself are covered directly in TestHandleInsightAlertSnoozeGuards.
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+
+ response = self._post_interactivity(self._snooze_payload("not-a-valid-value"))
+
+ assert response.status_code == 200
+ mock_requests_post.assert_not_called()
+
+
+class TestHandleInsightAlertSnoozeGuards(TestCase):
+ """Exercises _handle_insight_alert_snooze directly for its internal guards.
+
+ These payloads never reach the handler via the signed HTTP endpoint — malformed or
+ non-existent alert UUIDs fail the region-routing hint first (see
+ test_malformed_value_is_dropped_before_reaching_handler), so the only way to cover the
+ handler's own parsing/lookup guards is to call it directly.
+ """
+
+ def setUp(self):
+ self.organization = Organization.objects.create(name="Snooze Guard Org")
+ self.team = Team.objects.create(organization=self.organization, name="Snooze Guard Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="guard-user-1")
+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)
+ Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T99999",
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+ self.insight = Insight.objects.create(team=self.team, short_id="insight2", name="Guard insight")
+ self.alert = AlertConfiguration.objects.create(
+ team=self.team, insight=self.insight, name="Guard alert", state=AlertState.FIRING
+ )
+
+ def _payload(self, value: str) -> dict:
+ return {
+ "type": "block_actions",
+ "team": {"id": "T99999"},
+ "user": {"id": "U555"},
+ "response_url": "https://hooks.slack.test/response",
+ "actions": [{"action_id": "insight_alert_snooze", "value": value}],
+ "message": {"ts": "1.1", "blocks": []},
+ }
+
+ @parameterized.expand(
+ [
+ ("no_pipe", "not-a-valid-value"),
+ ("non_uuid_alert_id", "not-a-uuid|1d"),
+ ("unknown_duration", f"{uuid.uuid4()}|1y"),
+ ("unknown_alert", f"{uuid.uuid4()}|1d"),
+ ]
+ )
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ def test_guard_rejects_without_mutation(self, _name, value, mock_requests_post, mock_is_org_member):
+ mock_is_org_member.return_value = self.user
+
+ response = _handle_insight_alert_snooze(self._payload(value))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+ mock_requests_post.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("foreign_block_id", lambda self: {"block_id": "some_other_block", "selected_date_time": 1785000000}),
+ (
+ "non_int_timestamp",
+ lambda self: {"block_id": f"insight_alert_snooze:{self.alert.id}", "selected_date_time": "soon"},
+ ),
+ ]
+ )
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
+ def test_guard_rejects_malformed_datetimepicker(self, _name, action_fields, mock_requests_post, mock_is_org_member):
+ mock_is_org_member.return_value = self.user
+ payload = self._payload("ignored")
+ payload["actions"] = [{"action_id": "insight_alert_snooze_until", **action_fields(self)}]
+
+ response = _handle_insight_alert_snooze(payload)
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+ mock_requests_post.assert_not_called()
+
+
+class TestExtractAlertSnoozeHints(TestCase):
+ def _payload(self, value: str) -> dict:
+ return {"actions": [{"action_id": "insight_alert_snooze", "value": value}]}
+
+ def test_returns_uuid_for_valid_payload(self):
+ alert_id = uuid.uuid4()
+ result = _extract_alert_snooze_hints(self._payload(f"{alert_id}|1d"))
+ assert result == alert_id
+
+ @parameterized.expand(
+ [
+ ("no_pipe", "not-a-valid-value"),
+ ("unknown_duration", f"{uuid.uuid4()}|1y"),
+ ("non_uuid", "not-a-uuid|1d"),
+ ("no_actions", None),
+ ]
+ )
+ def test_returns_none_for_garbage(self, _name, value):
+ payload = self._payload(value) if value is not None else {"actions": []}
+ assert _extract_alert_snooze_hints(payload) is None
+
+
+class TestInsightAlertSnoozeModal(TestCase):
+ def setUp(self):
+ self.organization = Organization.objects.create(name="Snooze Modal Org")
+ self.team = Team.objects.create(organization=self.organization, name="Snooze Modal Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="modal-user-1")
+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T-MODAL",
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+ self.insight = Insight.objects.create(team=self.team, short_id="ins-modal", name="Signups")
+ self.alert = AlertConfiguration.objects.create(
+ team=self.team, insight=self.insight, name="Signups alert", state=AlertState.FIRING
+ )
+
+ def _select_custom_payload(self) -> dict:
+ return {
+ "type": "block_actions",
+ "team": {"id": "T-MODAL"},
+ "user": {"id": "U1"},
+ "trigger_id": "trig.123",
+ "channel": {"id": "C1"},
+ "message": {"ts": "111.222"},
+ "actions": [{"action_id": "insight_alert_snooze", "selected_option": {"value": f"{self.alert.id}|custom"}}],
+ }
+
+ def _modal_submit_payload(self, selected_date: str, selected_time: str, *, alert_id=None) -> dict:
+ return {
+ "type": "view_submission",
+ "team": {"id": "T-MODAL"},
+ "user": {"id": "U1"},
+ "view": {
+ "callback_id": "insight_alert_snooze_modal",
+ "private_metadata": json.dumps(
+ {"alert_id": str(alert_id or self.alert.id), "channel": "C1", "message_ts": "111.222"}
+ ),
+ "state": {
+ "values": {
+ "snooze_date": {"date": {"selected_date": selected_date}},
+ "snooze_time": {"time": {"selected_time": selected_time}},
+ }
+ },
+ },
+ }
+
+ @patch("products.slack_app.backend.api.SlackIntegration")
+ @patch("products.slack_app.backend.api._is_org_member")
+ def test_custom_option_opens_modal_without_snoozing(self, mock_is_org_member, mock_slack):
+ mock_is_org_member.return_value = self.user
+
+ response = _handle_insight_alert_snooze(self._select_custom_payload())
+
+ assert response.status_code == 200
+ mock_slack.return_value.client.views_open.assert_called_once()
+ view = mock_slack.return_value.client.views_open.call_args.kwargs["view"]
+ assert view["callback_id"] == "insight_alert_snooze_modal"
+ assert str(self.alert.id) in view["private_metadata"]
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+
+ @freeze_time("2026-07-21T12:00:00Z")
+ @patch("products.slack_app.backend.api.SlackIntegration")
+ @patch("products.slack_app.backend.api._is_org_member")
+ def test_modal_submit_snoozes_to_picked_time(self, mock_is_org_member, mock_slack):
+ mock_is_org_member.return_value = self.user
+
+ response = _handle_insight_alert_snooze_modal_submit(self._modal_submit_payload("2026-07-23", "09:30"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.SNOOZED
+ assert self.alert.snoozed_until == datetime(2026, 7, 23, 9, 30, tzinfo=UTC)
+ mock_slack.return_value.client.chat_postMessage.assert_called_once()
+
+ @parameterized.expand([("past", "2020-01-01", "09:00"), ("beyond_31_days", "2026-09-30", "09:00")])
+ @freeze_time("2026-07-21T12:00:00Z")
+ @patch("products.slack_app.backend.api.SlackIntegration")
+ @patch("products.slack_app.backend.api._is_org_member")
+ def test_modal_submit_rejects_out_of_bounds(self, _name, sel_date, sel_time, mock_is_org_member, mock_slack):
+ mock_is_org_member.return_value = self.user
+
+ response = _handle_insight_alert_snooze_modal_submit(self._modal_submit_payload(sel_date, sel_time))
+
+ assert json.loads(response.content)["response_action"] == "errors"
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+
+ @freeze_time("2026-07-21T12:00:00Z")
+ @patch("products.slack_app.backend.api.SlackIntegration")
+ @patch("products.slack_app.backend.api._is_org_member")
+ def test_modal_submit_refuses_non_org_member(self, mock_is_org_member, mock_slack):
+ mock_is_org_member.return_value = None
+
+ response = _handle_insight_alert_snooze_modal_submit(self._modal_submit_payload("2026-07-23", "09:00"))
+
+ assert response.status_code == 200
+ self.alert.refresh_from_db()
+ assert self.alert.state == AlertState.FIRING
+ assert self.alert.snoozed_until is None
+ mock_slack.return_value.client.chat_postMessage.assert_not_called()
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index fa1d329bf933..90e750059c96 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -935,7 +935,7 @@
}
},
"cdp-functions-create": {
- "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
+ "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Create function",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index f1606dda8e5a..961ebd5d720a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -950,7 +950,7 @@
}
},
"cdp-functions-create": {
- "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
+ "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"block_id\": \"insight_alert_snooze:{event.properties.alert_id}\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"},\n {\"type\": \"static_select\", \"action_id\": \"insight_alert_snooze\",\n \"placeholder\": {\"type\": \"plain_text\", \"text\": \"Snooze…\"},\n \"options\": [\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 hour\"}, \"value\": \"{event.properties.alert_id}|1h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 6 hours\"}, \"value\": \"{event.properties.alert_id}|6h\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 day\"}, \"value\": \"{event.properties.alert_id}|1d\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"For 1 week\"}, \"value\": \"{event.properties.alert_id}|1w\"},\n {\"text\": {\"type\": \"plain_text\", \"text\": \"Pick a date & time…\"}, \"value\": \"{event.properties.alert_id}|custom\"}\n ]}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Create function",
diff --git a/tach.toml b/tach.toml
index 19de2e7e8772..a45cbbead852 100644
--- a/tach.toml
+++ b/tach.toml
@@ -652,6 +652,7 @@ layer = "modules"
path = "products.slack_app"
depends_on = [
"posthog",
+ "products.alerts",
"products.conversations",
"products.dashboards",
"products.product_analytics",