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(replay-vision): deliver digests to webhooks (#74077)

Kim Svatos Dugand01fa50881fb
diff --git a/products/replay_vision/backend/api/delivery.py b/products/replay_vision/backend/api/delivery.py
index c06c174b3848..2c33d7352727 100644
--- a/products/replay_vision/backend/api/delivery.py
+++ b/products/replay_vision/backend/api/delivery.py
@@ -20,6 +20,11 @@ logger = structlog.get_logger(__name__)
EVENT_NAME = "$replay_vision_action_ready"
_INTERNAL_DESTINATION = "internal_destination"
_SLACK_TEMPLATE = "template-slack"
+_WEBHOOK_TEMPLATE = "template-webhook"
+
+# Marks our webhook payloads so a consumer can pin the schema and we can evolve it without breaking them.
+# Mirrors the alerts/logs destination convention (products/alerts/backend/destination_configs.py).
+_WEBHOOK_HEADERS = {"Content-Type": "application/json", "X-PostHog-Webhook-Version": "1"}
def _managed_destinations(action: VisionAction, team: Team) -> QuerySet[HogFunction]:
@@ -42,11 +47,13 @@ def _channel_id(value: str) -> str:
return value.split("|", 1)[0].strip()
-def _slack_destination_payload(action: VisionAction, target: dict[str, Any]) -> dict[str, Any]:
+def _base_destination_payload(action: VisionAction, template_id: str) -> dict[str, Any]:
+ """The internal_destination scaffold every delivery type shares: the trigger filter that binds the
+ destination to this action, plus its enabled state. Callers fill in `inputs` per template."""
return {
"type": _INTERNAL_DESTINATION,
"enabled": action.enabled,
- "template_id": _SLACK_TEMPLATE,
+ "template_id": template_id,
"name": f"Replay Vision · {action.name}",
"filters": {
"events": [{"id": EVENT_NAME, "type": "events"}],
@@ -54,6 +61,12 @@ def _slack_destination_payload(action: VisionAction, target: dict[str, Any]) ->
{"key": "vision_action_id", "value": str(action.id), "operator": "exact", "type": "event"},
],
},
+ }
+
+
+def _slack_destination_payload(action: VisionAction, target: dict[str, Any]) -> dict[str, Any]:
+ return {
+ **_base_destination_payload(action, _SLACK_TEMPLATE),
"inputs": {
"slack_workspace": {"value": target["integration_id"]},
"channel": {"value": _channel_id(target["channel"])},
@@ -67,6 +80,42 @@ def _slack_destination_payload(action: VisionAction, target: dict[str, Any]) ->
}
+def _webhook_destination_payload(action: VisionAction, target: dict[str, Any]) -> dict[str, Any]:
+ # A structured JSON envelope (not the Slack-formatted text) so machine consumers get clean fields.
+ # `type` routes on the event kind (digest / alert_fired / alert_recovered); `data` carries the report
+ # plus the run link. Template strings resolve against the emitted event's properties at delivery time.
+ body = {
+ "id": "{event.uuid}",
+ "type": "replay_vision.{event.properties.event_kind}",
+ "timestamp": "{event.properties.emitted_at}",
+ "data": {
+ "vision_action_id": "{event.properties.vision_action_id}",
+ "run_id": "{event.properties.vision_action_run_id}",
+ "scanner_id": "{event.properties.scanner_id}",
+ "action_name": "{event.properties.action_name}",
+ "scanner_name": "{event.properties.scanner_name}",
+ "observation_count": "{event.properties.observation_count}",
+ "report": "{event.properties.report_markdown}",
+ "run_url": "{event.properties.run_url}",
+ },
+ }
+ return {
+ **_base_destination_payload(action, _WEBHOOK_TEMPLATE),
+ "inputs": {
+ "url": {"value": target["url"]},
+ "method": {"value": "POST"},
+ "headers": {"value": _WEBHOOK_HEADERS},
+ "body": {"value": body},
+ },
+ }
+
+
+def _destination_payload(action: VisionAction, target: dict[str, Any]) -> dict[str, Any]:
+ if target.get("type") == "webhook":
+ return _webhook_destination_payload(action, target)
+ return _slack_destination_payload(action, target)
+
+
def provision_delivery(action: VisionAction, *, request: Request, team: Team) -> None:
"""Reconcile this action's `internal_destination` HogFunctions to its `delivery_config`.
@@ -81,7 +130,7 @@ def provision_delivery(action: VisionAction, *, request: Request, team: Team) ->
# HogFunctionSerializer.create() reads context["request"].user, so provisioning stays in the viewset.
context = {"request": request, "team_id": team.id, "get_team": lambda: team, "is_create": True}
for target in action.delivery_config:
- serializer = HogFunctionSerializer(data=_slack_destination_payload(action, target), context=context)
+ serializer = HogFunctionSerializer(data=_destination_payload(action, target), context=context)
serializer.is_valid(raise_exception=True)
serializer.save()
diff --git a/products/replay_vision/backend/temporal/vision_actions/activities.py b/products/replay_vision/backend/temporal/vision_actions/activities.py
index e4f58dd93b93..1e9a125d2786 100644
--- a/products/replay_vision/backend/temporal/vision_actions/activities.py
+++ b/products/replay_vision/backend/temporal/vision_actions/activities.py
@@ -3,6 +3,7 @@
from datetime import UTC, datetime, timedelta
from uuid import UUID
+from django.conf import settings
from django.db import transaction
from django.db.models import Q
@@ -179,7 +180,11 @@ async def emit_action_ready_activity(inputs: EmitActionReadyInputs) -> None:
def _emit(inputs: EmitActionReadyInputs) -> None:
- run = VisionActionRun.objects.for_team(inputs.team_id).select_related("vision_action", "team").get(pk=inputs.run_id)
+ run = (
+ VisionActionRun.objects.for_team(inputs.team_id)
+ .select_related("vision_action", "vision_action__scanner", "team")
+ .get(pk=inputs.run_id)
+ )
action = run.vision_action
team = run.team
@@ -187,6 +192,17 @@ def _emit(inputs: EmitActionReadyInputs) -> None:
# Nothing to deliver to; the run row (synthesized_markdown) is the in-app artifact.
return
+ output = run.output if isinstance(run.output, dict) else {}
+ # An alert's recovery bookend rides output.recovered; group summaries never set it. The event_kind
+ # lets a webhook consumer route on `replay_vision.{kind}` without parsing the report text.
+ is_recovery = bool(output.get("recovered"))
+ if action.mode != ActionMode.ALERT:
+ event_kind = "digest"
+ elif is_recovery:
+ event_kind = "alert_recovered"
+ else:
+ event_kind = "alert_fired"
+
# Private internal event (cdp_internal_events topic), NOT the public capture pipeline — an
# internal_destination HogFunction filtered on vision_action_id delivers it. This is non-forgeable
# with the public project token, and (unlike capture) it does NOT land in the analytics events
@@ -201,10 +217,24 @@ def _emit(inputs: EmitActionReadyInputs) -> None:
"vision_action_id": str(action.id),
"scanner_id": str(action.scanner_id) if action.scanner_id else None,
"vision_action_run_id": str(run.id),
- "slack_text": run.output.get("slack", ""),
+ "slack_text": output.get("slack", ""),
# Pre-split section blocks so the full report renders as ONE Slack message; None (not
# []) when absent so Slack falls back to slack_text rather than rejecting empty blocks.
- "slack_blocks": run.output.get("slack_blocks") or None,
+ "slack_blocks": output.get("slack_blocks") or None,
+ # Structured fields the webhook body references, so consumers get clean JSON rather than
+ # the Slack-formatted text. The report is the canonical markdown, not the mrkdwn variant.
+ "event_kind": event_kind,
+ "is_recovery": is_recovery,
+ "action_name": action.name,
+ "scanner_name": action.scanner.name if action.scanner_id else None,
+ "observation_count": run.observation_count,
+ "report_markdown": run.synthesized_markdown,
+ "run_url": _run_url(team.id, str(action.id), str(run.id)),
+ "emitted_at": (run.scheduled_at or run.created_at).isoformat(),
},
),
)
+
+
+def _run_url(team_id: int, action_id: str, run_id: str) -> str:
+ return f"{settings.SITE_URL}/project/{team_id}/replay-vision/actions/{action_id}/runs/{run_id}"
diff --git a/products/replay_vision/backend/tests/test_vision_action_delivery.py b/products/replay_vision/backend/tests/test_vision_action_delivery.py
index 928aca66ed8b..367dc12bffbc 100644
--- a/products/replay_vision/backend/tests/test_vision_action_delivery.py
+++ b/products/replay_vision/backend/tests/test_vision_action_delivery.py
@@ -1,9 +1,11 @@
-from typing import Any
+from typing import Any, cast
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from parameterized import parameterized
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as template_slack
@@ -11,15 +13,37 @@ from posthog.models import Team
from posthog.models.integration import Integration
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
-from products.replay_vision.backend.api.delivery import EVENT_NAME
+from products.replay_vision.backend.api.delivery import EVENT_NAME, provision_delivery
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
from products.replay_vision.backend.models.vision_action import VisionAction
+# The webhook template is defined in the nodejs registry (no Python source object like Slack's). The
+# serializer only needs the row to resolve by id and expose its inputs schema, so a minimal stand-in
+# with the same inputs is enough to exercise provisioning.
+_WEBHOOK_TEMPLATE = {
+ "id": "template-webhook",
+ "name": "HTTP Webhook",
+ "description": "Sends a webhook templated by the incoming event data",
+ "type": "destination",
+ "status": "stable",
+ "free": False,
+ "category": ["Custom"],
+ "code_language": "hog",
+ "code": "let res := fetch(inputs.url, {'method': inputs.method, 'headers': inputs.headers, 'body': inputs.body})",
+ "inputs_schema": [
+ {"key": "url", "type": "string", "label": "Webhook URL", "required": True},
+ {"key": "method", "type": "string", "label": "Method", "required": False},
+ {"key": "body", "type": "json", "label": "JSON Body", "required": False},
+ {"key": "headers", "type": "dictionary", "label": "Headers", "required": False},
+ ],
+}
+
class TestVisionActionDelivery(APIBaseTest):
def setUp(self) -> None:
super().setUp()
sync_template_to_db(template_slack)
+ sync_template_to_db(_WEBHOOK_TEMPLATE)
self.flag_patcher = patch(
"products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled",
return_value=True,
@@ -80,6 +104,27 @@ class TestVisionActionDelivery(APIBaseTest):
self.assertEqual(resp.status_code, 201, resp.content)
return VisionAction.all_teams.get(id=resp.json()["id"])
+ def _request(self) -> Request:
+ # provision_delivery threads a DRF Request into HogFunctionSerializer, which reads request.user.
+ drf_request = Request(APIRequestFactory().post("/"))
+ drf_request.user = self.user
+ return cast(Request, drf_request)
+
+ def _provision_action(self, delivery_config: list[dict[str, Any]]) -> VisionAction:
+ """Create an action with delivery_config set on the model and provision it directly, bypassing
+ the API serializer so a delivery type's provisioning can be exercised independently of the
+ serializer that gates which types the API accepts."""
+ action = VisionAction(
+ team=self.team,
+ scanner=self.scanner,
+ name=f"provisioned-{VisionAction.all_teams.count()}",
+ trigger_config={"rrule": "FREQ=DAILY", "timezone": "UTC"},
+ delivery_config=delivery_config,
+ )
+ action.save()
+ provision_delivery(action, request=self._request(), team=self.team)
+ return action
+
def _destinations(self, action: VisionAction) -> list[HogFunction]:
"""The action's live internal_destination HogFunctions — found by the vision_action_id filter
(no FK; the trigger filter is the binding), mirroring delivery._managed_destinations."""
@@ -210,3 +255,46 @@ class TestVisionActionDelivery(APIBaseTest):
resp = self.client.patch(f"{self.actions_url}{action.id}/", data={"delivery_config": []}, format="json")
self.assertEqual(resp.status_code, 200, resp.content)
self.assertEqual(self._destinations(action), [])
+
+ def test_webhook_target_provisions_webhook_destination(self) -> None:
+ # A webhook target must resolve to the template-webhook destination with the URL, a POST, the
+ # versioned header, and a body that references the emitted event's structured props — otherwise
+ # the webhook fires with a malformed/empty payload.
+ action = self._provision_action([{"type": "webhook", "url": "https://example.com/hook"}])
+
+ destinations = self._destinations(action)
+ self.assertEqual(len(destinations), 1)
+ fn = destinations[0]
+ self.assertEqual(fn.template_id, "template-webhook")
+ inputs = self._inputs(fn)
+ self.assertEqual(inputs["url"]["value"], "https://example.com/hook")
+ self.assertEqual(inputs["method"]["value"], "POST")
+ self.assertEqual(inputs["headers"]["value"]["X-PostHog-Webhook-Version"], "1")
+ body = inputs["body"]["value"]
+ self.assertEqual(body["type"], "replay_vision.{event.properties.event_kind}")
+ self.assertEqual(body["data"]["report"], "{event.properties.report_markdown}")
+ self.assertEqual(body["data"]["run_url"], "{event.properties.run_url}")
+ # The trigger filter still binds the destination to this action (the same bind-by-filter as Slack).
+ self.assertEqual(self._filters(fn)["properties"][0]["value"], str(action.id))
+
+ def test_mixed_slack_and_webhook_targets(self) -> None:
+ action = self._provision_action(
+ [
+ {"type": "slack", "integration_id": self.integration.id, "channel": "C1|#general"},
+ {"type": "webhook", "url": "https://example.com/hook"},
+ ]
+ )
+ by_template = {fn.template_id for fn in self._destinations(action)}
+ self.assertEqual(by_template, {"template-slack", "template-webhook"})
+
+ def test_reprovision_switches_slack_to_webhook(self) -> None:
+ # Reconcile is archive-and-recreate: switching a target's type must drop the stale Slack
+ # destination and stand up the webhook one, not leave both firing.
+ action = self._provision_action([{"type": "slack", "integration_id": self.integration.id, "channel": "#a"}])
+ self.assertEqual([d.template_id for d in self._destinations(action)], ["template-slack"])
+
+ action.delivery_config = [{"type": "webhook", "url": "https://example.com/hook"}]
+ action.save(update_fields=["delivery_config"])
+ provision_delivery(action, request=self._request(), team=self.team)
+
+ self.assertEqual([d.template_id for d in self._destinations(action)], ["template-webhook"])
diff --git a/products/replay_vision/backend/tests/test_vision_action_engine.py b/products/replay_vision/backend/tests/test_vision_action_engine.py
index 8e99cf09b6ac..2447de024dd8 100644
--- a/products/replay_vision/backend/tests/test_vision_action_engine.py
+++ b/products/replay_vision/backend/tests/test_vision_action_engine.py
@@ -258,6 +258,8 @@ class TestEngineActivities(BaseTest):
vision_action=action,
team=self.team,
idempotency_key="k",
+ synthesized_markdown="hello **world**",
+ observation_count=3,
output={"slack": "hello *world*", "slack_blocks": [{"type": "section"}]},
)
run.save()
@@ -276,6 +278,46 @@ class TestEngineActivities(BaseTest):
self.assertEqual(event.properties["vision_action_id"], str(action.id))
self.assertEqual(event.properties["slack_text"], "hello *world*")
self.assertEqual(event.properties["slack_blocks"], [{"type": "section"}])
+ # Structured fields the webhook body references — the raw markdown report (not the mrkdwn),
+ # the run link, and a digest/alert routing kind. Dropping these silently empties webhook bodies.
+ self.assertEqual(event.properties["event_kind"], "digest")
+ self.assertFalse(event.properties["is_recovery"])
+ self.assertEqual(event.properties["report_markdown"], "hello **world**")
+ self.assertEqual(event.properties["observation_count"], 3)
+ self.assertEqual(event.properties["action_name"], action.name)
+ self.assertEqual(event.properties["scanner_name"], action.scanner.name)
+ self.assertIn(f"/replay-vision/actions/{action.id}/runs/{run.id}", event.properties["run_url"])
+
+ @parameterized.expand(
+ [
+ ("alert_fired", {}, "alert_fired"),
+ ("alert_recovered", {"recovered": True}, "alert_recovered"),
+ ]
+ )
+ def test_emit_event_kind_for_alert(self, _label: str, extra_output: dict, expected_kind: str) -> None:
+ # A webhook consumer routes on `replay_vision.{event_kind}`; an alert's recovery bookend
+ # (output.recovered) must surface as a distinct kind from the firing that preceded it.
+ action = _action(
+ self.team,
+ mode="alert",
+ alert_config=EVERY_MATCH,
+ delivery_config=[{"type": "webhook", "url": "https://example.com/hook"}],
+ )
+ run = VisionActionRun(
+ vision_action=action,
+ team=self.team,
+ idempotency_key=f"k-{_label}",
+ synthesized_markdown="fired",
+ output={"slack": "fired", **extra_output},
+ )
+ run.save()
+
+ with patch.object(act, "produce_internal_event") as mock_emit:
+ act._emit(EmitActionReadyInputs(run_id=run.id, team_id=self.team.id))
+
+ event = mock_emit.call_args.kwargs["event"]
+ self.assertEqual(event.properties["event_kind"], expected_kind)
+ self.assertEqual(event.properties["is_recovery"], extra_output.get("recovered", False))
def test_emit_noops_without_delivery(self) -> None:
# No destinations configured → nothing to emit; the run row itself is the in-app artifact.