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): vision actions API (#64702)

Kim Svatos Duganedee12001f81
diff --git a/posthog/scopes.py b/posthog/scopes.py
index f42461d85488..9ab78957bec7 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -105,6 +105,7 @@ APIScopeObject = Literal[
"usage_metric",
"user",
"user_interview", # Alpha product — access gated by feature flag at the MCP/API layer rather than by hiding the scope.
+ "vision_action",
"visual_review",
"warehouse_objects",
"warehouse_table",
diff --git a/products/replay_vision/backend/api/__init__.py b/products/replay_vision/backend/api/__init__.py
index 55979c5102fb..5417d0771ce6 100644
--- a/products/replay_vision/backend/api/__init__.py
+++ b/products/replay_vision/backend/api/__init__.py
@@ -1,10 +1,12 @@
from products.replay_vision.backend.api.observations import ReplayObservationViewSet, SessionReplayObservationViewSet
from products.replay_vision.backend.api.quota import VisionQuotaViewSet
from products.replay_vision.backend.api.scanners import ReplayScannerViewSet
+from products.replay_vision.backend.api.vision_actions import VisionActionViewSet
__all__ = [
"ReplayObservationViewSet",
"ReplayScannerViewSet",
"SessionReplayObservationViewSet",
+ "VisionActionViewSet",
"VisionQuotaViewSet",
]
diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.py
new file mode 100644
index 000000000000..c6e5335b8d09
--- /dev/null
+++ b/products/replay_vision/backend/api/vision_actions.py
@@ -0,0 +1,308 @@
+from typing import Any, NoReturn, cast
+
+from django.db import IntegrityError
+from django.db.models import QuerySet
+
+import structlog
+from rest_framework import serializers, viewsets
+from rest_framework.exceptions import PermissionDenied
+from rest_framework.request import Request
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
+from posthog.api.shared import UserBasicSerializer
+from posthog.models.integration import Integration
+from posthog.models.user import User
+
+from products.replay_vision.backend.feature_flag import (
+ ReplayVisionActionsEnabledPermission,
+ ReplayVisionEnabledPermission,
+)
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.models.vision_action import ActionMode, TriggerType, VisionAction
+from products.replay_vision.backend.rrule import validate_rrule, validate_timezone
+
+logger = structlog.get_logger(__name__)
+
+
+class TriggerConfigSerializer(serializers.Serializer):
+ """Schedule trigger parameters. Threshold triggers are reserved and rejected at the API for now."""
+
+ rrule = serializers.CharField(
+ required=False,
+ allow_blank=False,
+ help_text="iCal RRULE string controlling the schedule cadence (no DTSTART — the start is managed separately).",
+ )
+ timezone = serializers.CharField(
+ required=False,
+ default="UTC",
+ help_text="IANA timezone name the RRULE is expanded in, e.g. 'Europe/Prague'. Defaults to 'UTC'.",
+ )
+
+
+class SelectionSerializer(serializers.Serializer):
+ """Observation filter applied at synthesis time. All keys optional; this typed shape is the
+ allowlist, so unknown input keys are dropped rather than persisted."""
+
+ scanner_type = serializers.CharField(
+ required=False,
+ help_text="Filter observations by scanner type (monitor/classifier/scorer/summarizer).",
+ )
+ scanner_ids = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ help_text="Restrict to observations produced by these scanner IDs.",
+ )
+ verdict = serializers.CharField(
+ required=False,
+ help_text="Filter to observations with this monitor verdict.",
+ )
+ tags = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ help_text="Filter to observations carrying any of these classifier tags.",
+ )
+ min_score = serializers.FloatField(
+ required=False,
+ help_text="Lower bound (inclusive) on scorer score.",
+ )
+ max_score = serializers.FloatField(
+ required=False,
+ help_text="Upper bound (inclusive) on scorer score.",
+ )
+ status = serializers.CharField(
+ required=False,
+ help_text="Filter to observations with this processing status.",
+ )
+ window_days = serializers.IntegerField(
+ required=False,
+ help_text="Lookback window in days for the observations gathered at synthesis time.",
+ )
+
+
+class SynthesisConfigSerializer(serializers.Serializer):
+ """Options for the group-summary synthesis step."""
+
+ prompt_guide = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=500,
+ help_text="Free-form guidance steering how the group summary is written.",
+ )
+
+
+class DeliveryTargetSerializer(serializers.Serializer):
+ """A single delivery destination. MVP supports Slack only."""
+
+ type = serializers.ChoiceField(
+ choices=[("slack", "Slack")],
+ help_text="Destination channel type. MVP supports 'slack' only.",
+ )
+ integration_id = serializers.IntegerField(
+ help_text="ID of the Slack Integration on this team used to deliver the summary.",
+ )
+ channel = serializers.CharField(
+ help_text="Slack channel ID or name the summary is posted to.",
+ )
+
+
+class VisionActionSerializer(serializers.ModelSerializer):
+ name = serializers.CharField(
+ max_length=255,
+ help_text="Human-readable action name. Unique within the team.",
+ )
+ scanner = TeamScopedPrimaryKeyRelatedField(
+ queryset=ReplayScanner.objects.all(),
+ help_text="Scanner whose observations this action operates on. Must belong to the same team.",
+ )
+ enabled = serializers.BooleanField(
+ required=False,
+ help_text="When false, the scheduler skips this action.",
+ )
+ trigger_type = serializers.ChoiceField(
+ choices=TriggerType.choices,
+ required=False,
+ help_text="What fires the action. MVP supports 'schedule' only.",
+ )
+ mode = serializers.ChoiceField(
+ choices=ActionMode.choices,
+ required=False,
+ help_text="What the action produces. MVP supports 'group_summary' only.",
+ )
+ trigger_config = TriggerConfigSerializer(
+ required=False,
+ help_text="Trigger parameters. For schedule triggers: {rrule, timezone}.",
+ )
+ selection = SelectionSerializer(
+ required=False,
+ help_text="Observation filter applied at synthesis time.",
+ )
+ synthesis_config = SynthesisConfigSerializer(
+ required=False,
+ help_text="Synthesis options for the group summary, e.g. {prompt_guide}.",
+ )
+ delivery_config = DeliveryTargetSerializer(
+ many=True,
+ required=False,
+ help_text="List of delivery destinations the synthesized summary is sent to.",
+ )
+
+ next_run_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="Computed next fire time for schedule triggers; the scheduler scans this.",
+ )
+ last_run_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="Timestamp of the most recent run, or null if it has never run.",
+ )
+ hog_flow_id = serializers.UUIDField(
+ read_only=True,
+ allow_null=True,
+ help_text="ID of the delivery flow provisioned for this action. Null until delivery is wired up.",
+ )
+ created_by = UserBasicSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="User who created the action.",
+ )
+
+ class Meta:
+ model = VisionAction
+ fields = [
+ "id",
+ "name",
+ "scanner",
+ "enabled",
+ "trigger_type",
+ "mode",
+ "trigger_config",
+ "selection",
+ "synthesis_config",
+ "delivery_config",
+ "next_run_at",
+ "last_run_at",
+ "hog_flow_id",
+ "created_at",
+ "created_by",
+ "updated_at",
+ ]
+ read_only_fields = [
+ "id",
+ "next_run_at",
+ "last_run_at",
+ "hog_flow_id",
+ "created_at",
+ "created_by",
+ "updated_at",
+ ]
+
+ def validate_trigger_type(self, value: str) -> str:
+ if value == TriggerType.THRESHOLD:
+ raise serializers.ValidationError("Threshold triggers are not supported yet. Use 'schedule'.")
+ return value
+
+ def validate_mode(self, value: str) -> str:
+ if value == ActionMode.PER_OBSERVATION:
+ raise serializers.ValidationError("Per-observation mode is not supported yet. Use 'group_summary'.")
+ return value
+
+ def validate_delivery_config(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ # IDOR guard: every referenced integration must belong to the team.
+ team = self.context["get_team"]()
+ for target in value:
+ if target.get("type") != "slack":
+ raise serializers.ValidationError("Only 'slack' delivery targets are supported.")
+ # DeliveryTargetSerializer guarantees integration_id is present and an int — subscript so
+ # mypy sees a concrete value, not Optional, for the id lookup.
+ integration_id = target["integration_id"]
+ if not Integration.objects.filter(team=team, id=integration_id, kind="slack").exists():
+ raise serializers.ValidationError(f"Slack integration {integration_id} not found in this team.")
+ return value
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ self._validate_schedule(attrs)
+ self._validate_unique_name(attrs)
+ return attrs
+
+ def _validate_schedule(self, attrs: dict[str, Any]) -> None:
+ trigger_type = attrs.get("trigger_type", getattr(self.instance, "trigger_type", TriggerType.SCHEDULE))
+ trigger_config = attrs.get("trigger_config", getattr(self.instance, "trigger_config", None)) or {}
+ if trigger_type != TriggerType.SCHEDULE:
+ return
+ try:
+ validate_timezone(trigger_config.get("timezone", "UTC"))
+ except ValueError as e:
+ raise serializers.ValidationError({"trigger_config": {"timezone": str(e)}})
+ rrule = trigger_config.get("rrule")
+ if not rrule:
+ return
+ try:
+ validate_rrule(rrule)
+ except ValueError as e:
+ raise serializers.ValidationError({"trigger_config": {"rrule": str(e)}})
+
+ def _validate_unique_name(self, attrs: dict[str, Any]) -> None:
+ # Surface the (team, name) uniqueness as a 400 instead of letting the DB raise 500.
+ name = attrs.get("name")
+ if name is None:
+ return
+ team = self.context["get_team"]()
+ duplicates = VisionAction.objects.for_team(team.id).filter(name=name)
+ if self.instance is not None:
+ duplicates = duplicates.exclude(pk=self.instance.pk)
+ if duplicates.exists():
+ raise serializers.ValidationError({"name": "An action with this name already exists in this team."})
+
+ def create(self, validated_data: dict[str, Any]) -> VisionAction:
+ team = self.context["get_team"]()
+ user = cast(User, self.context["request"].user)
+ try:
+ # for_team()'s filter doesn't propagate into create(), so team is still passed explicitly.
+ return VisionAction.objects.for_team(team.id).create(team=team, created_by=user, **validated_data)
+ except IntegrityError as e:
+ self._reraise_unique_name_violation(e)
+
+ def update(self, instance: VisionAction, validated_data: dict[str, Any]) -> VisionAction:
+ try:
+ return super().update(instance, validated_data)
+ except IntegrityError as e:
+ self._reraise_unique_name_violation(e)
+
+ @staticmethod
+ def _reraise_unique_name_violation(error: IntegrityError) -> NoReturn:
+ if "vision_action_unique_team_name" in str(error):
+ raise serializers.ValidationError({"name": "An action with this name already exists in this team."})
+ raise error
+
+
+class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ """CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations."""
+
+ scope_object = "vision_action"
+ scope_object_read_actions = ["list", "retrieve"]
+ scope_object_write_actions = ["create", "update", "partial_update", "destroy"]
+ permission_classes = [ReplayVisionEnabledPermission, ReplayVisionActionsEnabledPermission]
+ serializer_class = VisionActionSerializer
+ # `objects` is fail-closed; `safely_get_queryset` re-scopes to the request team.
+ queryset = VisionAction.objects.unscoped()
+ http_method_names = ["get", "post", "patch", "delete", "head", "options"]
+
+ # Configuring an action reads observations derived from recordings and sends them off-platform.
+ _CONFIG_ACTIONS = {"create", "update", "partial_update"}
+
+ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
+ if self.action in self._CONFIG_ACTIONS:
+ return ["vision_action:write", "session_recording:read"]
+ return None
+
+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:
+ super().initial(request, *args, **kwargs)
+ if self.action in self._CONFIG_ACTIONS and not self.user_access_control.check_access_level_for_resource(
+ "session_recording", required_level="viewer"
+ ):
+ raise PermissionDenied("Configuring a Replay Vision action requires session_recording read access.")
+
+ def safely_get_queryset(self, queryset: QuerySet[VisionAction]) -> QuerySet[VisionAction]:
+ return queryset.filter(team_id=self.team_id).select_related("scanner", "created_by").order_by("name", "id")
diff --git a/products/replay_vision/backend/feature_flag.py b/products/replay_vision/backend/feature_flag.py
index ef7ef94eaba4..ac2b56c92518 100644
--- a/products/replay_vision/backend/feature_flag.py
+++ b/products/replay_vision/backend/feature_flag.py
@@ -11,15 +11,17 @@ if TYPE_CHECKING:
from posthog.models.user import User
REPLAY_VISION_FEATURE_FLAG = "replay-vision"
+# Gates the "and then…" VisionAction sub-feature, separate from product access above.
+REPLAY_VISION_ACTIONS_FEATURE_FLAG = "replay-vision-actions"
-def is_replay_vision_enabled(user: "User", team: "Team") -> bool:
+def _vision_flag_enabled(flag_key: str, user: "User", team: "Team") -> bool:
distinct_id = user.distinct_id or str(user.uuid)
organization_id = str(team.organization_id)
project_id = str(team.id)
return bool(
posthoganalytics.feature_enabled(
- REPLAY_VISION_FEATURE_FLAG,
+ flag_key,
distinct_id,
groups={"organization": organization_id, "project": project_id},
group_properties={"organization": {"id": organization_id}, "project": {"id": project_id}},
@@ -29,6 +31,14 @@ def is_replay_vision_enabled(user: "User", team: "Team") -> bool:
)
+def is_replay_vision_enabled(user: "User", team: "Team") -> bool:
+ return _vision_flag_enabled(REPLAY_VISION_FEATURE_FLAG, user, team)
+
+
+def is_replay_vision_actions_enabled(user: "User", team: "Team") -> bool:
+ return _vision_flag_enabled(REPLAY_VISION_ACTIONS_FEATURE_FLAG, user, team)
+
+
class ReplayVisionEnabledPermission(BasePermission):
"""Hide Vision endpoints behind the `replay-vision` flag — 404 (not 403) when off."""
@@ -36,3 +46,12 @@ class ReplayVisionEnabledPermission(BasePermission):
if not is_replay_vision_enabled(request.user, view.team): # type: ignore[arg-type, attr-defined]
raise NotFound()
return True
+
+
+class ReplayVisionActionsEnabledPermission(BasePermission):
+ """Hide Vision *action* endpoints behind the `replay-vision-actions` flag — 404 (not 403) when off."""
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ if not is_replay_vision_actions_enabled(request.user, view.team): # type: ignore[arg-type, attr-defined]
+ raise NotFound()
+ return True
diff --git a/products/replay_vision/backend/routes.py b/products/replay_vision/backend/routes.py
index 498b7a16da52..cb77aa353389 100644
--- a/products/replay_vision/backend/routes.py
+++ b/products/replay_vision/backend/routes.py
@@ -4,6 +4,7 @@ from products.replay_vision.backend.api import (
ReplayObservationViewSet,
ReplayScannerViewSet,
SessionReplayObservationViewSet,
+ VisionActionViewSet,
VisionQuotaViewSet,
)
@@ -22,3 +23,4 @@ def register_routes(routers: RouterRegistry) -> None:
r"vision/observations", SessionReplayObservationViewSet, "project_vision_observations", ["team_id"]
)
routers.register_legacy_dual_route(r"vision/quota", VisionQuotaViewSet, "project_vision_quota", ["team_id"])
+ routers.projects.register(r"vision/actions", VisionActionViewSet, "project_vision_actions", ["team_id"])
diff --git a/products/replay_vision/backend/rrule.py b/products/replay_vision/backend/rrule.py
index fc2469ca9c9f..c35e59d2a4d8 100644
--- a/products/replay_vision/backend/rrule.py
+++ b/products/replay_vision/backend/rrule.py
@@ -7,7 +7,7 @@ common module rather than wiring a product-to-product import.
"""
from datetime import UTC, datetime
-from zoneinfo import ZoneInfo
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from dateutil.rrule import rrulestr
@@ -26,6 +26,18 @@ def validate_rrule(rrule_string: str) -> None:
raise ValueError(str(e)) from e
+def validate_timezone(timezone_str: str) -> None:
+ """Validate an IANA timezone name. Raises ValueError if unknown/invalid.
+
+ Without this, an unvalidated TZ string is accepted at the API and only blows up later in
+ `compute_next_occurrences` (ZoneInfo lookup) inside the scheduling workflow.
+ """
+ try:
+ ZoneInfo(timezone_str)
+ except (ZoneInfoNotFoundError, ValueError) as e:
+ raise ValueError(f"Unknown timezone: {timezone_str!r}") from e
+
+
def compute_next_occurrences(
rrule_string: str,
starts_at: datetime,
diff --git a/products/replay_vision/backend/tests/test_vision_action_models.py b/products/replay_vision/backend/tests/test_vision_action_models.py
index f367cab34a41..673b36fc1b7c 100644
--- a/products/replay_vision/backend/tests/test_vision_action_models.py
+++ b/products/replay_vision/backend/tests/test_vision_action_models.py
@@ -19,7 +19,7 @@ from products.replay_vision.backend.models.vision_action import (
VisionActionRunStatus,
default_selection,
)
-from products.replay_vision.backend.rrule import compute_next_occurrences, validate_rrule
+from products.replay_vision.backend.rrule import compute_next_occurrences, validate_rrule, validate_timezone
DAILY_9AM = "FREQ=DAILY;BYHOUR=9;BYMINUTE=0;BYSECOND=0"
@@ -251,6 +251,15 @@ class TestRruleHelper(BaseTest):
def test_validate_accepts_valid(self) -> None:
validate_rrule("FREQ=WEEKLY;BYDAY=MO,WE,FR;BYHOUR=9")
+ def test_validate_timezone_accepts_valid(self) -> None:
+ validate_timezone("Europe/Prague")
+ validate_timezone("UTC")
+
+ @parameterized.expand([("unknown", "Mars/Phobos"), ("garbage", "not a tz"), ("empty", "")])
+ def test_validate_timezone_rejects_invalid(self, _label: str, tz: str) -> None:
+ with self.assertRaises(ValueError):
+ validate_timezone(tz)
+
def test_occurrences_are_future_and_utc(self) -> None:
starts = datetime(2026, 1, 1, tzinfo=UTC)
after = datetime(2026, 6, 1, 12, 0, tzinfo=UTC)
diff --git a/products/replay_vision/backend/tests/test_vision_actions_api.py b/products/replay_vision/backend/tests/test_vision_actions_api.py
new file mode 100644
index 000000000000..f325cd5f341d
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py
@@ -0,0 +1,220 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from posthog.models import Organization, Team
+from posthog.models.integration import Integration
+
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.models.vision_action import VisionAction
+
+
+class _VisionActionAPITestCase(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.flag_patcher = patch(
+ "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled",
+ return_value=True,
+ )
+ self.flag_patcher.start()
+ self.scanner = self._create_scanner()
+ self.integration = self._create_slack_integration()
+
+ def tearDown(self) -> None:
+ self.flag_patcher.stop()
+ super().tearDown()
+
+ @property
+ def actions_url(self) -> str:
+ return f"/api/projects/{self.team.id}/vision/actions/"
+
+ def _create_scanner(self, team: Team | None = None, name: str = "my-scanner") -> ReplayScanner:
+ return ReplayScanner.objects.create(
+ team=team or self.team,
+ name=name,
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "did the user check out?"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ )
+
+ def _create_slack_integration(self, team: Team | None = None) -> Integration:
+ return Integration.objects.create(
+ team=team or self.team,
+ kind="slack",
+ integration_id="T_TEST",
+ config={"team": {"name": "Test Workspace"}},
+ sensitive_config={"access_token": "test-token"},
+ created_by=self.user,
+ )
+
+ def _create_payload(self, **overrides: Any) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "name": "daily-summary",
+ "scanner": str(self.scanner.id),
+ "trigger_config": {"rrule": "FREQ=DAILY", "timezone": "UTC"},
+ "selection": {"scanner_type": "summarizer", "window_days": 1},
+ "synthesis_config": {"prompt_guide": "keep it short"},
+ "delivery_config": [
+ {"type": "slack", "integration_id": self.integration.id, "channel": "#general"},
+ ],
+ }
+ payload.update(overrides)
+ return payload
+
+
+class TestVisionActionViewSet(_VisionActionAPITestCase):
+ def test_create_happy_path(self) -> None:
+ resp = self.client.post(self.actions_url, data=self._create_payload(), format="json")
+ self.assertEqual(resp.status_code, 201, resp.content)
+ data = resp.json()
+ self.assertEqual(data["name"], "daily-summary")
+ self.assertEqual(data["scanner"], str(self.scanner.id))
+ self.assertEqual(data["trigger_type"], "schedule")
+ self.assertEqual(data["mode"], "group_summary")
+ self.assertIsNotNone(data["next_run_at"])
+ self.assertIsNone(data["last_run_at"])
+ self.assertIsNone(data["hog_flow_id"])
+ self.assertEqual(data["created_by"]["id"], self.user.id)
+
+ action = VisionAction.all_teams.get(id=data["id"])
+ self.assertEqual(action.team_id, self.team.id)
+ self.assertEqual(action.delivery_config[0]["integration_id"], self.integration.id)
+ self.assertIsNotNone(action.next_run_at)
+
+ def test_list(self) -> None:
+ self.client.post(self.actions_url, data=self._create_payload(), format="json")
+ resp = self.client.get(self.actions_url)
+ self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.json()["count"], 1)
+
+ def test_actions_flag_off_hides_endpoint(self) -> None:
+ # `replay-vision-actions` gates the sub-feature even when product-level `replay-vision` is on.
+ def _flags(flag_key: str, *args: Any, **kwargs: Any) -> bool:
+ return flag_key != "replay-vision-actions"
+
+ with patch("products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled", side_effect=_flags):
+ list_resp = self.client.get(self.actions_url)
+ create_resp = self.client.post(self.actions_url, data=self._create_payload(), format="json")
+ self.assertEqual(list_resp.status_code, 404, list_resp.content)
+ self.assertEqual(create_resp.status_code, 404, create_resp.content)
+
+ def test_retrieve(self) -> None:
+ created = self.client.post(self.actions_url, data=self._create_payload(), format="json").json()
+ resp = self.client.get(f"{self.actions_url}{created['id']}/")
+ self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.json()["id"], created["id"])
+
+ def test_patch(self) -> None:
+ created = self.client.post(self.actions_url, data=self._create_payload(), format="json").json()
+ resp = self.client.patch(
+ f"{self.actions_url}{created['id']}/", data={"name": "renamed", "enabled": False}, format="json"
+ )
+ self.assertEqual(resp.status_code, 200, resp.content)
+ self.assertEqual(resp.json()["name"], "renamed")
+ self.assertFalse(resp.json()["enabled"])
+
+ def test_delete(self) -> None:
+ created = self.client.post(self.actions_url, data=self._create_payload(), format="json").json()
+ resp = self.client.delete(f"{self.actions_url}{created['id']}/")
+ self.assertEqual(resp.status_code, 204)
+ self.assertFalse(VisionAction.all_teams.filter(id=created["id"]).exists())
+
+ def test_reject_threshold_trigger(self) -> None:
+ resp = self.client.post(self.actions_url, data=self._create_payload(trigger_type="threshold"), format="json")
+ self.assertEqual(resp.status_code, 400)
+ self.assertIn("threshold", resp.json()["detail"].lower())
+
+ def test_reject_per_observation_mode(self) -> None:
+ resp = self.client.post(self.actions_url, data=self._create_payload(mode="per_observation"), format="json")
+ self.assertEqual(resp.status_code, 400)
+ self.assertIn("per-observation", resp.json()["detail"].lower())
+
+ def test_invalid_rrule(self) -> None:
+ resp = self.client.post(
+ self.actions_url,
+ data=self._create_payload(trigger_config={"rrule": "NOT_A_RULE", "timezone": "UTC"}),
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 400)
+
+ def test_invalid_timezone(self) -> None:
+ # An unknown TZ must be rejected at the API, not blow up later in the scheduling workflow.
+ resp = self.client.post(
+ self.actions_url,
+ data=self._create_payload(trigger_config={"rrule": "FREQ=DAILY", "timezone": "Mars/Phobos"}),
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 400, resp.content)
+
+ def test_duplicate_name(self) -> None:
+ self.client.post(self.actions_url, data=self._create_payload(), format="json")
+ resp = self.client.post(self.actions_url, data=self._create_payload(), format="json")
+ self.assertEqual(resp.status_code, 400)
+ self.assertEqual(resp.json()["attr"], "name")
+
+ def test_selection_valid_accepted(self) -> None:
+ resp = self.client.post(
+ self.actions_url,
+ data=self._create_payload(
+ selection={"scanner_type": "scorer", "min_score": 0.5, "max_score": 1.0, "tags": ["a", "b"]}
+ ),
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 201, resp.content)
+ action = VisionAction.all_teams.get(id=resp.json()["id"])
+ self.assertEqual(action.selection["min_score"], 0.5)
+
+ def test_selection_unknown_key_ignored(self) -> None:
+ # The typed SelectionSerializer is the allowlist; unknown keys are dropped, not persisted.
+ resp = self.client.post(
+ self.actions_url,
+ data=self._create_payload(selection={"scanner_type": "summarizer", "bogus_key": "x"}),
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 201, resp.content)
+ action = VisionAction.all_teams.get(id=resp.json()["id"])
+ self.assertNotIn("bogus_key", action.selection)
+
+
+class TestVisionActionCrossTeamIDOR(_VisionActionAPITestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.other_org = Organization.objects.create(name="other-org")
+ self.other_team = Team.objects.create(organization=self.other_org, name="other-team")
+ self.other_scanner = self._create_scanner(team=self.other_team, name="other-scanner")
+ self.other_integration = self._create_slack_integration(team=self.other_team)
+ self.other_action = VisionAction.all_teams.create(
+ team=self.other_team,
+ scanner=self.other_scanner,
+ name="other-action",
+ )
+
+ def test_cannot_retrieve_other_team_action(self) -> None:
+ resp = self.client.get(f"{self.actions_url}{self.other_action.id}/")
+ self.assertEqual(resp.status_code, 404)
+
+ def test_cannot_patch_other_team_action(self) -> None:
+ resp = self.client.patch(f"{self.actions_url}{self.other_action.id}/", data={"name": "hijack"}, format="json")
+ self.assertEqual(resp.status_code, 404)
+
+ def test_cannot_delete_other_team_action(self) -> None:
+ resp = self.client.delete(f"{self.actions_url}{self.other_action.id}/")
+ self.assertEqual(resp.status_code, 404)
+ self.assertTrue(VisionAction.all_teams.filter(id=self.other_action.id).exists())
+
+ def test_cannot_bind_other_team_scanner(self) -> None:
+ resp = self.client.post(
+ self.actions_url, data=self._create_payload(scanner=str(self.other_scanner.id)), format="json"
+ )
+ self.assertEqual(resp.status_code, 400)
+
+ def test_cannot_reference_other_team_integration(self) -> None:
+ resp = self.client.post(
+ self.actions_url,
+ data=self._create_payload(
+ delivery_config=[{"type": "slack", "integration_id": self.other_integration.id, "channel": "#x"}]
+ ),
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 400)
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 95421b92cdb4..b5fe62d10e59 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -7,6 +7,259 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * * `schedule` - Schedule
+ * * `threshold` - Threshold
+ */
+export type TriggerTypeEnumApi = (typeof TriggerTypeEnumApi)[keyof typeof TriggerTypeEnumApi]
+
+export const TriggerTypeEnumApi = {
+ Schedule: 'schedule',
+ Threshold: 'threshold',
+} as const
+
+/**
+ * * `group_summary` - Group summary
+ * * `per_observation` - Per observation
+ */
+export type VisionActionModeEnumApi = (typeof VisionActionModeEnumApi)[keyof typeof VisionActionModeEnumApi]
+
+export const VisionActionModeEnumApi = {
+ GroupSummary: 'group_summary',
+ PerObservation: 'per_observation',
+} as const
+
+/**
+ * Schedule trigger parameters. Threshold triggers are reserved and rejected at the API for now.
+ */
+export interface TriggerConfigApi {
+ /** iCal RRULE string controlling the schedule cadence (no DTSTART — the start is managed separately). */
+ rrule?: string
+ /** IANA timezone name the RRULE is expanded in, e.g. 'Europe/Prague'. Defaults to 'UTC'. */
+ timezone?: string
+}
+
+/**
+ * Observation filter applied at synthesis time. All keys optional; this typed shape is the
+ * allowlist, so unknown input keys are dropped rather than persisted.
+ */
+export interface SelectionApi {
+ /** Filter observations by scanner type (monitor/classifier/scorer/summarizer). */
+ scanner_type?: string
+ /** Restrict to observations produced by these scanner IDs. */
+ scanner_ids?: string[]
+ /** Filter to observations with this monitor verdict. */
+ verdict?: string
+ /** Filter to observations carrying any of these classifier tags. */
+ tags?: string[]
+ /** Lower bound (inclusive) on scorer score. */
+ min_score?: number
+ /** Upper bound (inclusive) on scorer score. */
+ max_score?: number
+ /** Filter to observations with this processing status. */
+ status?: string
+ /** Lookback window in days for the observations gathered at synthesis time. */
+ window_days?: number
+}
+
+/**
+ * Options for the group-summary synthesis step.
+ */
+export interface SynthesisConfigApi {
+ /**
+ * Free-form guidance steering how the group summary is written.
+ * @maxLength 500
+ */
+ prompt_guide?: string
+}
+
+/**
+ * * `slack` - Slack
+ */
+export type DeliveryTargetTypeEnumApi = (typeof DeliveryTargetTypeEnumApi)[keyof typeof DeliveryTargetTypeEnumApi]
+
+export const DeliveryTargetTypeEnumApi = {
+ Slack: 'slack',
+} as const
+
+/**
+ * A single delivery destination. MVP supports Slack only.
+ */
+export interface DeliveryTargetApi {
+ /** Destination channel type. MVP supports 'slack' only.
+ *
+ * * `slack` - Slack */
+ type: DeliveryTargetTypeEnumApi
+ /** ID of the Slack Integration on this team used to deliver the summary. */
+ integration_id: number
+ /** Slack channel ID or name the summary is posted to. */
+ channel: string
+}
+
+/**
+ * * `engineering` - Engineering
+ * * `data` - Data
+ * * `product` - Product Management
+ * * `founder` - Founder
+ * * `leadership` - Leadership
+ * * `marketing` - Marketing
+ * * `sales` - Sales / Success
+ * * `other` - Other
+ */
+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
+
+export const RoleAtOrganizationEnumApi = {
+ Engineering: 'engineering',
+ Data: 'data',
+ Product: 'product',
+ Founder: 'founder',
+ Leadership: 'leadership',
+ Marketing: 'marketing',
+ Sales: 'sales',
+ Other: 'other',
+} as const
+
+export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
+
+export const BlankEnumApi = {
+ '': '',
+} as const
+
+/**
+ * @nullable
+ */
+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null
+
+export interface UserBasicApi {
+ readonly id: number
+ readonly uuid: string
+ /**
+ * @maxLength 200
+ * @nullable
+ */
+ distinct_id?: string | null
+ /** @maxLength 150 */
+ first_name?: string
+ /** @maxLength 150 */
+ last_name?: string
+ /** @maxLength 254 */
+ email: string
+ /** @nullable */
+ is_email_verified?: boolean | null
+ /** @nullable */
+ readonly hedgehog_config: UserBasicApiHedgehogConfig
+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
+}
+
+export interface VisionActionApi {
+ readonly id: string
+ /**
+ * Human-readable action name. Unique within the team.
+ * @maxLength 255
+ */
+ name: string
+ /** Scanner whose observations this action operates on. Must belong to the same team. */
+ scanner: string
+ /** When false, the scheduler skips this action. */
+ enabled?: boolean
+ /** What fires the action. MVP supports 'schedule' only.
+ *
+ * * `schedule` - Schedule
+ * * `threshold` - Threshold */
+ trigger_type?: TriggerTypeEnumApi
+ /** What the action produces. MVP supports 'group_summary' only.
+ *
+ * * `group_summary` - Group summary
+ * * `per_observation` - Per observation */
+ mode?: VisionActionModeEnumApi
+ /** Trigger parameters. For schedule triggers: {rrule, timezone}. */
+ trigger_config?: TriggerConfigApi
+ /** Observation filter applied at synthesis time. */
+ selection?: SelectionApi
+ /** Synthesis options for the group summary, e.g. {prompt_guide}. */
+ synthesis_config?: SynthesisConfigApi
+ /** List of delivery destinations the synthesized summary is sent to. */
+ delivery_config?: DeliveryTargetApi[]
+ /**
+ * Computed next fire time for schedule triggers; the scheduler scans this.
+ * @nullable
+ */
+ readonly next_run_at: string | null
+ /**
+ * Timestamp of the most recent run, or null if it has never run.
+ * @nullable
+ */
+ readonly last_run_at: string | null
+ /**
+ * ID of the delivery flow provisioned for this action. Null until delivery is wired up.
+ * @nullable
+ */
+ readonly hog_flow_id: string | null
+ readonly created_at: string
+ /** User who created the action. */
+ readonly created_by: UserBasicApi | null
+ readonly updated_at: string
+}
+
+export interface PaginatedVisionActionListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: VisionActionApi[]
+}
+
+export interface PatchedVisionActionApi {
+ readonly id?: string
+ /**
+ * Human-readable action name. Unique within the team.
+ * @maxLength 255
+ */
+ name?: string
+ /** Scanner whose observations this action operates on. Must belong to the same team. */
+ scanner?: string
+ /** When false, the scheduler skips this action. */
+ enabled?: boolean
+ /** What fires the action. MVP supports 'schedule' only.
+ *
+ * * `schedule` - Schedule
+ * * `threshold` - Threshold */
+ trigger_type?: TriggerTypeEnumApi
+ /** What the action produces. MVP supports 'group_summary' only.
+ *
+ * * `group_summary` - Group summary
+ * * `per_observation` - Per observation */
+ mode?: VisionActionModeEnumApi
+ /** Trigger parameters. For schedule triggers: {rrule, timezone}. */
+ trigger_config?: TriggerConfigApi
+ /** Observation filter applied at synthesis time. */
+ selection?: SelectionApi
+ /** Synthesis options for the group summary, e.g. {prompt_guide}. */
+ synthesis_config?: SynthesisConfigApi
+ /** List of delivery destinations the synthesized summary is sent to. */
+ delivery_config?: DeliveryTargetApi[]
+ /**
+ * Computed next fire time for schedule triggers; the scheduler scans this.
+ * @nullable
+ */
+ readonly next_run_at?: string | null
+ /**
+ * Timestamp of the most recent run, or null if it has never run.
+ * @nullable
+ */
+ readonly last_run_at?: string | null
+ /**
+ * ID of the delivery flow provisioned for this action. Null until delivery is wired up.
+ * @nullable
+ */
+ readonly hog_flow_id?: string | null
+ readonly created_at?: string
+ /** User who created the action. */
+ readonly created_by?: UserBasicApi | null
+ readonly updated_at?: string
+}
+
/**
* * `pending` - Pending
* * `running` - Running
@@ -113,61 +366,6 @@ export const ObservationTriggerEnumApi = {
OnDemand: 'on_demand',
} as const
-/**
- * * `engineering` - Engineering
- * * `data` - Data
- * * `product` - Product Management
- * * `founder` - Founder
- * * `leadership` - Leadership
- * * `marketing` - Marketing
- * * `sales` - Sales / Success
- * * `other` - Other
- */
-export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
-
-export const RoleAtOrganizationEnumApi = {
- Engineering: 'engineering',
- Data: 'data',
- Product: 'product',
- Founder: 'founder',
- Leadership: 'leadership',
- Marketing: 'marketing',
- Sales: 'sales',
- Other: 'other',
-} as const
-
-export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
-
-export const BlankEnumApi = {
- '': '',
-} as const
-
-/**
- * @nullable
- */
-export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null
-
-export interface UserBasicApi {
- readonly id: number
- readonly uuid: string
- /**
- * @maxLength 200
- * @nullable
- */
- distinct_id?: string | null
- /** @maxLength 150 */
- first_name?: string
- /** @maxLength 150 */
- last_name?: string
- /** @maxLength 254 */
- email: string
- /** @nullable */
- is_email_verified?: boolean | null
- /** @nullable */
- readonly hedgehog_config: UserBasicApiHedgehogConfig
- role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
-}
-
export interface ReplayObservationApi {
readonly id: string
/** The scanner that produced this observation. */
@@ -532,6 +730,17 @@ export interface ScannerStatsResponseApi {
by_type: ScannerStatsByTypeApi
}
+export type VisionActionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type VisionObservationsListParams = {
/**
* Number of results to return per page.
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index 0219e583ee81..bfd855b313e0 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -16,11 +16,15 @@ import type {
ObserveResponseApi,
PaginatedReplayObservationListApi,
PaginatedReplayScannerListApi,
+ PaginatedVisionActionListApi,
PatchedReplayScannerApi,
+ PatchedVisionActionApi,
ReplayObservationApi,
ReplayScannerApi,
ScannerCreatorsResponseApi,
ScannerStatsResponseApi,
+ VisionActionApi,
+ VisionActionsListParams,
VisionObservationsListParams,
VisionQuotaApi,
VisionScannersListParams,
@@ -45,6 +49,109 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getVisionActionsListUrl = (projectId: string, params?: VisionActionsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/vision/actions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/vision/actions/`
+}
+
+/**
+ * CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ */
+export const visionActionsList = async (
+ projectId: string,
+ params?: VisionActionsListParams,
+ options?: RequestInit
+): Promise<PaginatedVisionActionListApi> => {
+ return apiMutator<PaginatedVisionActionListApi>(getVisionActionsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getVisionActionsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/vision/actions/`
+}
+
+/**
+ * CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ */
+export const visionActionsCreate = async (
+ projectId: string,
+ visionActionApi: NonReadonly<VisionActionApi>,
+ options?: RequestInit
+): Promise<VisionActionApi> => {
+ return apiMutator<VisionActionApi>(getVisionActionsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(visionActionApi),
+ })
+}
+
+export const getVisionActionsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/actions/${id}/`
+}
+
+/**
+ * CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ */
+export const visionActionsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<VisionActionApi> => {
+ return apiMutator<VisionActionApi>(getVisionActionsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getVisionActionsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/actions/${id}/`
+}
+
+/**
+ * CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ */
+export const visionActionsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedVisionActionApi?: NonReadonly<PatchedVisionActionApi>,
+ options?: RequestInit
+): Promise<VisionActionApi> => {
+ return apiMutator<VisionActionApi>(getVisionActionsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedVisionActionApi),
+ })
+}
+
+export const getVisionActionsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/actions/${id}/`
+}
+
+/**
+ * CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ */
+export const visionActionsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getVisionActionsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getVisionObservationsListUrl = (projectId: string, params: VisionObservationsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index f40a7c1b20ec..86a44c1c3c4f 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -9,6 +9,216 @@
*/
import * as zod from 'zod'
+/**
+ * CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ */
+export const visionActionsCreateBodyNameMax = 255
+
+export const visionActionsCreateBodyTriggerConfigOneTimezoneDefault = `UTC`
+export const visionActionsCreateBodySynthesisConfigOnePromptGuideMax = 500
+
+export const VisionActionsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(visionActionsCreateBodyNameMax)
+ .describe('Human-readable action name. Unique within the team.'),
+ scanner: zod.uuid().describe('Scanner whose observations this action operates on. Must belong to the same team.'),
+ enabled: zod.boolean().optional().describe('When false, the scheduler skips this action.'),
+ trigger_type: zod
+ .enum(['schedule', 'threshold'])
+ .describe('\* `schedule` - Schedule\n\* `threshold` - Threshold')
+ .optional()
+ .describe(
+ "What fires the action. MVP supports 'schedule' only.\n\n\* `schedule` - Schedule\n\* `threshold` - Threshold"
+ ),
+ mode: zod
+ .enum(['group_summary', 'per_observation'])
+ .describe('\* `group_summary` - Group summary\n\* `per_observation` - Per observation')
+ .optional()
+ .describe(
+ "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `per_observation` - Per observation"
+ ),
+ trigger_config: zod
+ .object({
+ rrule: zod
+ .string()
+ .optional()
+ .describe(
+ 'iCal RRULE string controlling the schedule cadence (no DTSTART — the start is managed separately).'
+ ),
+ timezone: zod
+ .string()
+ .default(visionActionsCreateBodyTriggerConfigOneTimezoneDefault)
+ .describe("IANA timezone name the RRULE is expanded in, e.g. 'Europe\/Prague'. Defaults to 'UTC'."),
+ })
+ .describe('Schedule trigger parameters. Threshold triggers are reserved and rejected at the API for now.')
+ .optional()
+ .describe('Trigger parameters. For schedule triggers: {rrule, timezone}.'),
+ selection: zod
+ .object({
+ scanner_type: zod
+ .string()
+ .optional()
+ .describe('Filter observations by scanner type (monitor\/classifier\/scorer\/summarizer).'),
+ scanner_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe('Restrict to observations produced by these scanner IDs.'),
+ verdict: zod.string().optional().describe('Filter to observations with this monitor verdict.'),
+ tags: zod
+ .array(zod.string())
+ .optional()
+ .describe('Filter to observations carrying any of these classifier tags.'),
+ min_score: zod.number().optional().describe('Lower bound (inclusive) on scorer score.'),
+ max_score: zod.number().optional().describe('Upper bound (inclusive) on scorer score.'),
+ status: zod.string().optional().describe('Filter to observations with this processing status.'),
+ window_days: zod
+ .number()
+ .optional()
+ .describe('Lookback window in days for the observations gathered at synthesis time.'),
+ })
+ .describe(
+ 'Observation filter applied at synthesis time. All keys optional; this typed shape is the\nallowlist, so unknown input keys are dropped rather than persisted.'
+ )
+ .optional()
+ .describe('Observation filter applied at synthesis time.'),
+ synthesis_config: zod
+ .object({
+ prompt_guide: zod
+ .string()
+ .max(visionActionsCreateBodySynthesisConfigOnePromptGuideMax)
+ .optional()
+ .describe('Free-form guidance steering how the group summary is written.'),
+ })
+ .describe('Options for the group-summary synthesis step.')
+ .optional()
+ .describe('Synthesis options for the group summary, e.g. {prompt_guide}.'),
+ delivery_config: zod
+ .array(
+ zod
+ .object({
+ type: zod
+ .enum(['slack'])
+ .describe('\* `slack` - Slack')
+ .describe("Destination channel type. MVP supports 'slack' only.\n\n\* `slack` - Slack"),
+ integration_id: zod
+ .number()
+ .describe('ID of the Slack Integration on this team used to deliver the summary.'),
+ channel: zod.string().describe('Slack channel ID or name the summary is posted to.'),
+ })
+ .describe('A single delivery destination. MVP supports Slack only.')
+ )
+ .optional()
+ .describe('List of delivery destinations the synthesized summary is sent to.'),
+})
+
+/**
+ * CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.
+ */
+export const visionActionsPartialUpdateBodyNameMax = 255
+
+export const visionActionsPartialUpdateBodyTriggerConfigOneTimezoneDefault = `UTC`
+export const visionActionsPartialUpdateBodySynthesisConfigOnePromptGuideMax = 500
+
+export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(visionActionsPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Human-readable action name. Unique within the team.'),
+ scanner: zod
+ .uuid()
+ .optional()
+ .describe('Scanner whose observations this action operates on. Must belong to the same team.'),
+ enabled: zod.boolean().optional().describe('When false, the scheduler skips this action.'),
+ trigger_type: zod
+ .enum(['schedule', 'threshold'])
+ .describe('\* `schedule` - Schedule\n\* `threshold` - Threshold')
+ .optional()
+ .describe(
+ "What fires the action. MVP supports 'schedule' only.\n\n\* `schedule` - Schedule\n\* `threshold` - Threshold"
+ ),
+ mode: zod
+ .enum(['group_summary', 'per_observation'])
+ .describe('\* `group_summary` - Group summary\n\* `per_observation` - Per observation')
+ .optional()
+ .describe(
+ "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `per_observation` - Per observation"
+ ),
+ trigger_config: zod
+ .object({
+ rrule: zod
+ .string()
+ .optional()
+ .describe(
+ 'iCal RRULE string controlling the schedule cadence (no DTSTART — the start is managed separately).'
+ ),
+ timezone: zod
+ .string()
+ .default(visionActionsPartialUpdateBodyTriggerConfigOneTimezoneDefault)
+ .describe("IANA timezone name the RRULE is expanded in, e.g. 'Europe\/Prague'. Defaults to 'UTC'."),
+ })
+ .describe('Schedule trigger parameters. Threshold triggers are reserved and rejected at the API for now.')
+ .optional()
+ .describe('Trigger parameters. For schedule triggers: {rrule, timezone}.'),
+ selection: zod
+ .object({
+ scanner_type: zod
+ .string()
+ .optional()
+ .describe('Filter observations by scanner type (monitor\/classifier\/scorer\/summarizer).'),
+ scanner_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe('Restrict to observations produced by these scanner IDs.'),
+ verdict: zod.string().optional().describe('Filter to observations with this monitor verdict.'),
+ tags: zod
+ .array(zod.string())
+ .optional()
+ .describe('Filter to observations carrying any of these classifier tags.'),
+ min_score: zod.number().optional().describe('Lower bound (inclusive) on scorer score.'),
+ max_score: zod.number().optional().describe('Upper bound (inclusive) on scorer score.'),
+ status: zod.string().optional().describe('Filter to observations with this processing status.'),
+ window_days: zod
+ .number()
+ .optional()
+ .describe('Lookback window in days for the observations gathered at synthesis time.'),
+ })
+ .describe(
+ 'Observation filter applied at synthesis time. All keys optional; this typed shape is the\nallowlist, so unknown input keys are dropped rather than persisted.'
+ )
+ .optional()
+ .describe('Observation filter applied at synthesis time.'),
+ synthesis_config: zod
+ .object({
+ prompt_guide: zod
+ .string()
+ .max(visionActionsPartialUpdateBodySynthesisConfigOnePromptGuideMax)
+ .optional()
+ .describe('Free-form guidance steering how the group summary is written.'),
+ })
+ .describe('Options for the group-summary synthesis step.')
+ .optional()
+ .describe('Synthesis options for the group summary, e.g. {prompt_guide}.'),
+ delivery_config: zod
+ .array(
+ zod
+ .object({
+ type: zod
+ .enum(['slack'])
+ .describe('\* `slack` - Slack')
+ .describe("Destination channel type. MVP supports 'slack' only.\n\n\* `slack` - Slack"),
+ integration_id: zod
+ .number()
+ .describe('ID of the Slack Integration on this team used to deliver the summary.'),
+ channel: zod.string().describe('Slack channel ID or name the summary is posted to.'),
+ })
+ .describe('A single delivery destination. MVP supports Slack only.')
+ )
+ .optional()
+ .describe('List of delivery destinations the synthesized summary is sent to.'),
+})
+
/**
* CRUD for Replay Vision scanners.
*/
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index 8c3c3b6801d8..ecea933272e1 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -9,6 +9,21 @@ feature: replay_vision
url_prefix: /replay-vision
ui_apps: {}
tools:
+ vision-actions-create:
+ operation: vision_actions_create
+ enabled: false
+ vision-actions-destroy:
+ operation: vision_actions_destroy
+ enabled: false
+ vision-actions-list:
+ operation: vision_actions_list
+ enabled: false
+ vision-actions-partial-update:
+ operation: vision_actions_partial_update
+ enabled: false
+ vision-actions-retrieve:
+ operation: vision_actions_retrieve
+ enabled: false
vision-observations-list:
operation: vision_observations_list
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e1a63def3f80..835c56495704 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17173,6 +17173,30 @@ export namespace Schemas {
Failed: 'failed',
} as const;
+ /**
+ * * `slack` - Slack
+ */
+ export type DeliveryTargetTypeEnum = typeof DeliveryTargetTypeEnum[keyof typeof DeliveryTargetTypeEnum];
+
+
+ export const DeliveryTargetTypeEnum = {
+ Slack: 'slack',
+ } as const;
+
+ /**
+ * A single delivery destination. MVP supports Slack only.
+ */
+ export interface DeliveryTarget {
+ /** Destination channel type. MVP supports 'slack' only.
+ *
+ * * `slack` - Slack */
+ type: DeliveryTargetTypeEnum;
+ /** ID of the Slack Integration on this team used to deliver the summary. */
+ integration_id: number;
+ /** Slack channel ID or name the summary is posted to. */
+ channel: string;
+ }
+
export interface DependentFlag {
/** Feature flag ID */
id: number;
@@ -33667,6 +33691,133 @@ export namespace Schemas {
results: ViewLink[];
}
+ /**
+ * * `schedule` - Schedule
+ * * `threshold` - Threshold
+ */
+ export type TriggerTypeEnum = typeof TriggerTypeEnum[keyof typeof TriggerTypeEnum];
+
+
+ export const TriggerTypeEnum = {
+ Schedule: 'schedule',
+ Threshold: 'threshold',
+ } as const;
+
+ /**
+ * * `group_summary` - Group summary
+ * * `per_observation` - Per observation
+ */
+ export type VisionActionModeEnum = typeof VisionActionModeEnum[keyof typeof VisionActionModeEnum];
+
+
+ export const VisionActionModeEnum = {
+ GroupSummary: 'group_summary',
+ PerObservation: 'per_observation',
+ } as const;
+
+ /**
+ * Schedule trigger parameters. Threshold triggers are reserved and rejected at the API for now.
+ */
+ export interface TriggerConfig {
+ /** iCal RRULE string controlling the schedule cadence (no DTSTART — the start is managed separately). */
+ rrule?: string;
+ /** IANA timezone name the RRULE is expanded in, e.g. 'Europe/Prague'. Defaults to 'UTC'. */
+ timezone?: string;
+ }
+
+ /**
+ * Observation filter applied at synthesis time. All keys optional; this typed shape is the
+ * allowlist, so unknown input keys are dropped rather than persisted.
+ */
+ export interface Selection {
+ /** Filter observations by scanner type (monitor/classifier/scorer/summarizer). */
+ scanner_type?: string;
+ /** Restrict to observations produced by these scanner IDs. */
+ scanner_ids?: string[];
+ /** Filter to observations with this monitor verdict. */
+ verdict?: string;
+ /** Filter to observations carrying any of these classifier tags. */
+ tags?: string[];
+ /** Lower bound (inclusive) on scorer score. */
+ min_score?: number;
+ /** Upper bound (inclusive) on scorer score. */
+ max_score?: number;
+ /** Filter to observations with this processing status. */
+ status?: string;
+ /** Lookback window in days for the observations gathered at synthesis time. */
+ window_days?: number;
+ }
+
+ /**
+ * Options for the group-summary synthesis step.
+ */
+ export interface SynthesisConfig {
+ /**
+ * Free-form guidance steering how the group summary is written.
+ * @maxLength 500
+ */
+ prompt_guide?: string;
+ }
+
+ export interface VisionAction {
+ readonly id: string;
+ /**
+ * Human-readable action name. Unique within the team.
+ * @maxLength 255
+ */
+ name: string;
+ /** Scanner whose observations this action operates on. Must belong to the same team. */
+ scanner: string;
+ /** When false, the scheduler skips this action. */
+ enabled?: boolean;
+ /** What fires the action. MVP supports 'schedule' only.
+ *
+ * * `schedule` - Schedule
+ * * `threshold` - Threshold */
+ trigger_type?: TriggerTypeEnum;
+ /** What the action produces. MVP supports 'group_summary' only.
+ *
+ * * `group_summary` - Group summary
+ * * `per_observation` - Per observation */
+ mode?: VisionActionModeEnum;
+ /** Trigger parameters. For schedule triggers: {rrule, timezone}. */
+ trigger_config?: TriggerConfig;
+ /** Observation filter applied at synthesis time. */
+ selection?: Selection;
+ /** Synthesis options for the group summary, e.g. {prompt_guide}. */
+ synthesis_config?: SynthesisConfig;
+ /** List of delivery destinations the synthesized summary is sent to. */
+ delivery_config?: DeliveryTarget[];
+ /**
+ * Computed next fire time for schedule triggers; the scheduler scans this.
+ * @nullable
+ */
+ readonly next_run_at: string | null;
+ /**
+ * Timestamp of the most recent run, or null if it has never run.
+ * @nullable
+ */
+ readonly last_run_at: string | null;
+ /**
+ * ID of the delivery flow provisioned for this action. Null until delivery is wired up.
+ * @nullable
+ */
+ readonly hog_flow_id: string | null;
+ readonly created_at: string;
+ /** User who created the action. */
+ readonly created_by: UserBasic | null;
+ readonly updated_at: string;
+ }
+
+ export interface PaginatedVisionActionList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: VisionAction[];
+ }
+
export interface WarehouseColumnAnnotation {
readonly id: string;
/** ID of the data warehouse table this annotation describes. */
@@ -40559,6 +40710,56 @@ export namespace Schemas {
configuration?: unknown;
}
+ export interface PatchedVisionAction {
+ readonly id?: string;
+ /**
+ * Human-readable action name. Unique within the team.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Scanner whose observations this action operates on. Must belong to the same team. */
+ scanner?: string;
+ /** When false, the scheduler skips this action. */
+ enabled?: boolean;
+ /** What fires the action. MVP supports 'schedule' only.
+ *
+ * * `schedule` - Schedule
+ * * `threshold` - Threshold */
+ trigger_type?: TriggerTypeEnum;
+ /** What the action produces. MVP supports 'group_summary' only.
+ *
+ * * `group_summary` - Group summary
+ * * `per_observation` - Per observation */
+ mode?: VisionActionModeEnum;
+ /** Trigger parameters. For schedule triggers: {rrule, timezone}. */
+ trigger_config?: TriggerConfig;
+ /** Observation filter applied at synthesis time. */
+ selection?: Selection;
+ /** Synthesis options for the group summary, e.g. {prompt_guide}. */
+ synthesis_config?: SynthesisConfig;
+ /** List of delivery destinations the synthesized summary is sent to. */
+ delivery_config?: DeliveryTarget[];
+ /**
+ * Computed next fire time for schedule triggers; the scheduler scans this.
+ * @nullable
+ */
+ readonly next_run_at?: string | null;
+ /**
+ * Timestamp of the most recent run, or null if it has never run.
+ * @nullable
+ */
+ readonly last_run_at?: string | null;
+ /**
+ * ID of the delivery flow provisioned for this action. Null until delivery is wired up.
+ * @nullable
+ */
+ readonly hog_flow_id?: string | null;
+ readonly created_at?: string;
+ /** User who created the action. */
+ readonly created_by?: UserBasic | null;
+ readonly updated_at?: string;
+ }
+
export interface PatchedWarehouseColumnAnnotation {
readonly id?: string;
/** ID of the data warehouse table this annotation describes. */
@@ -62806,6 +63007,17 @@ export namespace Schemas {
offset?: number;
};
+ export type VisionActionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type VisionObservationsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index a90173cc8632..8005c18e2fc5 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -183,6 +183,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'user:write',
'user_interview:read',
'user_interview:write',
+ 'vision_action:read',
+ 'vision_action:write',
'visual_review:read',
'visual_review:write',
'warehouse_objects:read',