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): add CRUD API for lenses and observations (#58203)

Tue Haulund5adac1ec2bc6
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 298e30be3b5e..3da653401470 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -173,7 +173,7 @@ rules:
|QuickFilter
|QuickFilterContext
|ReplayLens
- |ReplayLensObservation
+ |ReplayObservation
|Repo
|RepoRoutingRule
|SandboxEnvironment
@@ -385,7 +385,7 @@ rules:
|QuickFilter
|QuickFilterContext
|ReplayLens
- |ReplayLensObservation
+ |ReplayObservation
|Repo
|RepoRoutingRule
|SandboxEnvironment
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 1d6124f2290f..7c17faa2197f 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -94,6 +94,7 @@ export const API_SCOPES: APIScope[] = [
},
{ key: 'property_definition', objectName: 'Property definition', objectPlural: 'property definitions' },
{ key: 'query', objectName: 'Query', objectPlural: 'queries', disabledActions: ['write'] },
+ { key: 'replay_lens', objectName: 'Replay lens', objectPlural: 'replay lenses' },
{ key: 'revenue_analytics', objectName: 'Revenue analytics', objectPlural: 'revenue analytics' },
{ key: 'session_recording', objectName: 'Session recording', objectPlural: 'session recordings' },
{
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 03bf282bf729..14a6dbea5fa4 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5331,6 +5331,7 @@ export type APIScopeObject =
| 'project'
| 'property_definition'
| 'query'
+ | 'replay_lens'
| 'revenue_analytics'
| 'session_recording'
| 'session_recording_playlist'
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index 81c2cc4a45f4..a818076c9134 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -108,6 +108,7 @@ from products.notebooks.backend.api.notebook import NotebookViewSet
from products.notifications.backend.presentation.views import NotificationsViewSet
from products.posthog_ai.backend.api import MCPToolsViewSet
from products.product_tours.backend.api import ProductTourViewSet
+from products.replay_vision.backend.api import ReplayLensViewSet, ReplayObservationViewSet
from products.signals.backend.views import SignalViewSet
from products.tracing.backend.presentation.views import SpansViewSet as TracingSpansViewSet
from products.user_interviews.backend.api import UserInterviewViewSet
@@ -1531,6 +1532,19 @@ environments_router.register(
["team_id"],
)
+environment_vision_lenses_router = environments_router.register(
+ r"vision/lenses",
+ ReplayLensViewSet,
+ "environment_vision_lenses",
+ ["team_id"],
+)
+environment_vision_lenses_router.register(
+ r"observations",
+ ReplayObservationViewSet,
+ "environment_vision_lens_observations",
+ ["team_id", "lens_id"],
+)
+
environments_router.register(
r"change_requests",
approval_api.ChangeRequestViewSet,
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 53a1d2da5254..6baed0bbe7c2 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -295,6 +295,8 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:
return "warehouse_table"
if name == "customerjourney":
return "customer_journey"
+ if name in ("replaylens", "replayobservation"):
+ return "replay_lens"
if name not in API_SCOPE_OBJECTS or name in INTERNAL_API_SCOPE_OBJECTS:
return None
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 8977ab1880dc..44f53b88302a 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -76,6 +76,7 @@ APIScopeObject = Literal[
"project",
"property_definition",
"query", # Covers query and events endpoints
+ "replay_lens",
"revenue_analytics",
"session_recording",
"session_recording_playlist",
@@ -121,7 +122,7 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"clickhouse_t
# OAuth metadata. Used for alpha / not-yet-public products where a user can
# manually paste the scope into a PAT but where we don't want OAuth-based
# clients (the consent screen, MCP, third-party apps) to discover it.
-OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"user_interview_DO_NOT_USE"})
+OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"user_interview_DO_NOT_USE", "replay_lens"})
PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIScopeActions]] = [("endpoint", "read")]
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 78380d8de99f..3c0f1e8862ee 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -422,6 +422,12 @@ SPECTACULAR_SETTINGS = {
"MCPAuthTypeEnum": "products.mcp_store.backend.models.AUTH_TYPE_CHOICES",
"TaskRunStatusEnum": "products.tasks.backend.models.TaskRun.Status",
"TaskRunEnvironmentEnum": "products.tasks.backend.models.TaskRun.Environment",
+ "ModelEnum": "posthog.batch_exports.models.BatchExport.Model",
+ "LensModelEnum": "products.replay_vision.backend.models.replay_lens.LensModel",
+ "LensTypeEnum": "products.replay_vision.backend.models.replay_lens.LensType",
+ "LensProviderEnum": "products.replay_vision.backend.models.replay_lens.LensProvider",
+ "ObservationStatusEnum": "products.replay_vision.backend.models.replay_observation.ObservationStatus",
+ "ObservationTriggerEnum": "products.replay_vision.backend.models.replay_observation.ObservationTrigger",
# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---
"PropertyGroupOperator": ["AND", "OR"],
"PropertyFilterTypeEnum": [
diff --git a/products/replay_vision/README.md b/products/replay_vision/README.md
index bf1c0e77eb31..b6c99f2e89c4 100644
--- a/products/replay_vision/README.md
+++ b/products/replay_vision/README.md
@@ -10,10 +10,8 @@ A sub-product of Session Replay. Users configure named **lenses** that PostHog a
## Layout
-- `backend/models/` — `ReplayLens`, `ReplayLensObservation`, and their enums.
-- `backend/temporal/` — Vision-owned Temporal workflows (e.g. `ApplyLensWorkflow`, the per-lens schedule, the reconciler, the reaper).
-- `backend/presentation/` — DRF viewsets, serializers, URL routing.
-- `backend/facade/` — thin contract layer for cross-product access; this product is `backend:contract-check`-isolated, so external imports must enter through `facade/api.py`.
-- `backend/logic/` — business logic; keeps the facade and viewsets thin.
+- `backend/models/` — `ReplayLens`, `ReplayObservation`, and their enums.
+- `backend/api/` — DRF viewsets, serializers, URL routing.
+- `backend/feature_flag.py` — `replay-vision` flag check + permission.
- `backend/admin.py` — Django admin registrations for both models.
- `frontend/` — kea-first scenes and logics for the lens management UI.
diff --git a/products/replay_vision/backend/admin.py b/products/replay_vision/backend/admin.py
index e059dd03a97e..07f0c91d1587 100644
--- a/products/replay_vision/backend/admin.py
+++ b/products/replay_vision/backend/admin.py
@@ -1,20 +1,20 @@
from django.contrib import admin
from django.http import HttpRequest
-from products.replay_vision.backend.models import ReplayLens, ReplayLensObservation
+from products.replay_vision.backend.models import ReplayLens, ReplayObservation
@admin.register(ReplayLens)
class ReplayLensAdmin(admin.ModelAdmin):
- list_display = ("name", "team", "lens_type", "status", "is_builtin", "emits_signals", "created_at")
- list_filter = ("lens_type", "status", "is_builtin", "emits_signals")
+ list_display = ("name", "team", "lens_type", "enabled", "emits_signals", "created_at")
+ list_filter = ("lens_type", "enabled", "emits_signals")
search_fields = ("name", "description")
raw_id_fields = ("team", "created_by")
readonly_fields = ("id", "created_at", "updated_at", "last_swept_at", "lens_version")
[email protected](ReplayLensObservation)
-class ReplayLensObservationAdmin(admin.ModelAdmin):
[email protected](ReplayObservation)
+class ReplayObservationAdmin(admin.ModelAdmin):
list_display = ("lens", "session_id", "status", "triggered_by", "created_at", "completed_at")
list_filter = ("status", "triggered_by")
search_fields = ("session_id", "workflow_id")
diff --git a/products/replay_vision/backend/api/__init__.py b/products/replay_vision/backend/api/__init__.py
new file mode 100644
index 000000000000..31fa94b9c980
--- /dev/null
+++ b/products/replay_vision/backend/api/__init__.py
@@ -0,0 +1,4 @@
+from products.replay_vision.backend.api.lenses import ReplayLensViewSet
+from products.replay_vision.backend.api.observations import ReplayObservationViewSet
+
+__all__ = ["ReplayLensViewSet", "ReplayObservationViewSet"]
diff --git a/products/replay_vision/backend/api/lenses.py b/products/replay_vision/backend/api/lenses.py
new file mode 100644
index 000000000000..e9201c14c959
--- /dev/null
+++ b/products/replay_vision/backend/api/lenses.py
@@ -0,0 +1,187 @@
+from typing import Any, NoReturn, cast
+
+from django.db import IntegrityError
+from django.db.models import QuerySet
+
+import django_filters
+from django_filters.rest_framework import DjangoFilterBackend
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, viewsets
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import UserBasicSerializer
+from posthog.models.user import User
+
+from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission
+from products.replay_vision.backend.models.replay_lens import LensModel, LensProvider, LensType, ReplayLens
+
+VISION_TAG = "replay_vision"
+
+
+class ReplayLensSerializer(serializers.ModelSerializer):
+ name = serializers.CharField(
+ max_length=255,
+ help_text="Human-readable lens name. Unique within the team.",
+ )
+ description = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Free-form description shown in the lens management UI.",
+ )
+ lens_type = serializers.ChoiceField(
+ choices=LensType.choices,
+ help_text="What the lens does: monitor, classifier, scorer, summarizer, or indexer.",
+ )
+ # TODO: validate `lens_config` shape per `lens_type` via Pydantic discriminated union (deferred to follow-up PR)
+ lens_config = serializers.JSONField(
+ help_text="Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc.",
+ )
+ # TODO: type `query` against `posthog.schema.RecordingsQuery` (deferred to follow-up PR)
+ query = serializers.JSONField(
+ required=False,
+ help_text="Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user.",
+ )
+ sampling_rate = serializers.FloatField(
+ required=False,
+ min_value=0.0,
+ max_value=1.0,
+ help_text="0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).",
+ )
+ provider = serializers.ChoiceField(
+ choices=LensProvider.choices,
+ required=False,
+ help_text="LLM provider. v1 is Google-only.",
+ )
+ model = serializers.ChoiceField(
+ choices=LensModel.choices,
+ help_text="Concrete model to use for this lens.",
+ )
+ enabled = serializers.BooleanField(
+ required=False,
+ help_text="When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work.",
+ )
+ emits_signals = serializers.BooleanField(
+ required=False,
+ help_text="When true, the prompt is augmented with the Signal side mission and the lens emits PostHog Signals.",
+ )
+
+ lens_version = serializers.IntegerField(
+ read_only=True,
+ help_text="Increments on every config-changing save. Observations snapshot this value.",
+ )
+ last_swept_at = serializers.DateTimeField(
+ read_only=True,
+ help_text="Watermark for the lens's last scheduled fire. Mirrors Temporal schedule state for recovery.",
+ )
+ created_by = UserBasicSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="User who created the lens.",
+ )
+
+ class Meta:
+ model = ReplayLens
+ fields = [
+ "id",
+ "name",
+ "description",
+ "lens_type",
+ "lens_config",
+ "query",
+ "sampling_rate",
+ "provider",
+ "model",
+ "enabled",
+ "emits_signals",
+ "lens_version",
+ "last_swept_at",
+ "created_at",
+ "created_by",
+ "updated_at",
+ ]
+ read_only_fields = [
+ "id",
+ "lens_version",
+ "last_swept_at",
+ "created_at",
+ "created_by",
+ "updated_at",
+ ]
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ # Surface the (team_id, name) uniqueness as a 400 instead of letting the DB raise 500.
+ name = attrs.get("name")
+ if name is not None:
+ team = self.context["get_team"]()
+ duplicates = ReplayLens.objects.filter(team=team, name=name)
+ if self.instance is not None:
+ duplicates = duplicates.exclude(pk=self.instance.pk)
+ if duplicates.exists():
+ raise serializers.ValidationError({"name": "A lens with this name already exists in this team."})
+ return attrs
+
+ def create(self, validated_data: dict[str, Any]) -> ReplayLens:
+ team = self.context["get_team"]()
+ user = cast(User, self.context["request"].user)
+ try:
+ return ReplayLens.objects.create(team=team, created_by=user, **validated_data)
+ except IntegrityError as e:
+ self._reraise_unique_name_violation(e)
+
+ def update(self, instance: ReplayLens, validated_data: dict[str, Any]) -> ReplayLens:
+ 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:
+ # Narrow to the unique-name constraint so other future constraints aren't mis-reported as duplicates.
+ if "replay_lens_unique_team_name" in str(error):
+ raise serializers.ValidationError({"name": "A lens with this name already exists in this team."})
+ raise error
+
+
+class ReplayLensFilter(django_filters.FilterSet):
+ enabled = django_filters.BooleanFilter(
+ field_name="enabled",
+ help_text="Filter to enabled vs disabled lenses.",
+ )
+ lens_type = django_filters.ChoiceFilter(
+ field_name="lens_type",
+ choices=LensType.choices,
+ help_text="Filter by lens type (monitor, classifier, scorer, summarizer, indexer).",
+ )
+ emits_signals = django_filters.BooleanFilter(
+ field_name="emits_signals",
+ help_text="Filter to lenses that emit Signals.",
+ )
+ order_by = django_filters.OrderingFilter(
+ fields=(
+ ("name", "name"),
+ ("created_at", "created_at"),
+ ("updated_at", "updated_at"),
+ ("lens_type", "lens_type"),
+ ),
+ help_text="Sort lenses by name, created_at, updated_at, or lens_type. Prefix with `-` for descending.",
+ )
+
+ class Meta:
+ model = ReplayLens
+ fields = ["enabled", "lens_type", "emits_signals"]
+
+
+@extend_schema(tags=[VISION_TAG])
+class ReplayLensViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ """CRUD for Replay Vision lenses."""
+
+ scope_object = "replay_lens"
+ permission_classes = [ReplayVisionEnabledPermission]
+ serializer_class = ReplayLensSerializer
+ queryset = ReplayLens.objects.all()
+ filter_backends = [DjangoFilterBackend]
+ filterset_class = ReplayLensFilter
+ http_method_names = ["get", "post", "patch", "delete", "head", "options"]
+
+ def safely_get_queryset(self, queryset: QuerySet[ReplayLens]) -> QuerySet[ReplayLens]:
+ return queryset.filter(team_id=self.team_id).select_related("created_by").order_by("name", "id")
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
new file mode 100644
index 000000000000..602a5a9c99ce
--- /dev/null
+++ b/products/replay_vision/backend/api/observations.py
@@ -0,0 +1,157 @@
+import uuid
+
+from django.db.models import QuerySet
+
+import django_filters
+from django_filters.rest_framework import DjangoFilterBackend
+from drf_spectacular.utils import extend_schema
+from rest_framework import mixins, serializers, viewsets
+from rest_framework.exceptions import NotFound, PermissionDenied
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import UserBasicSerializer
+
+from products.replay_vision.backend.api.lenses import VISION_TAG
+from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission
+from products.replay_vision.backend.models.replay_lens import ReplayLens
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ObservationTrigger,
+ ReplayObservation,
+)
+
+
+class ReplayObservationSerializer(serializers.ModelSerializer):
+ lens_id = serializers.UUIDField(read_only=True, help_text="The lens that produced this observation.")
+ session_id = serializers.CharField(read_only=True, help_text="Session recording id this lens was applied to.")
+ status = serializers.ChoiceField(
+ choices=ObservationStatus.choices,
+ read_only=True,
+ help_text="Observation status (pending, running, succeeded, failed).",
+ )
+ error_reason = serializers.CharField(
+ read_only=True,
+ allow_blank=True,
+ help_text="Populated on failure. Includes the malformed model response when validation fails.",
+ )
+ workflow_id = serializers.CharField(
+ read_only=True,
+ allow_blank=True,
+ help_text="Temporal workflow id for progress queries and debugging. Empty until the workflow starts.",
+ )
+ lens_version = serializers.IntegerField(
+ read_only=True,
+ help_text="The `ReplayLens.lens_version` value at the moment the workflow ran.",
+ )
+ # TODO: type against the same Pydantic shape used to validate `ReplayLens.lens_config` (deferred to follow-up PR)
+ lens_config_snapshot = serializers.JSONField(
+ read_only=True,
+ help_text="Snapshot of `ReplayLens.lens_config` at run time. Lens edits do not retroactively mutate observations.",
+ )
+ model_used = serializers.CharField(
+ read_only=True,
+ allow_blank=True,
+ help_text="Concrete model that ran the observation.",
+ )
+ provider_used = serializers.CharField(
+ read_only=True,
+ allow_blank=True,
+ help_text="Concrete provider that ran the observation.",
+ )
+ triggered_by = serializers.ChoiceField(
+ choices=ObservationTrigger.choices,
+ read_only=True,
+ help_text="Whether this observation came from the schedule or an on-demand request.",
+ )
+ triggered_by_user = UserBasicSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="User who triggered an on-demand observation. Null for scheduled observations.",
+ )
+
+ class Meta:
+ model = ReplayObservation
+ fields = [
+ "id",
+ "lens_id",
+ "session_id",
+ "status",
+ "error_reason",
+ "workflow_id",
+ "lens_version",
+ "lens_config_snapshot",
+ "model_used",
+ "provider_used",
+ "triggered_by",
+ "triggered_by_user",
+ "started_at",
+ "completed_at",
+ "created_at",
+ ]
+
+
+class ReplayObservationFilter(django_filters.FilterSet):
+ status = django_filters.ChoiceFilter(
+ field_name="status",
+ choices=ObservationStatus.choices,
+ help_text="Filter by observation status.",
+ )
+ triggered_by = django_filters.ChoiceFilter(
+ field_name="triggered_by",
+ choices=ObservationTrigger.choices,
+ help_text="Filter by trigger source (schedule or on_demand).",
+ )
+ session_id = django_filters.CharFilter(
+ field_name="session_id",
+ help_text="Filter to observations of a specific session recording.",
+ )
+ order_by = django_filters.OrderingFilter(
+ fields=(
+ ("created_at", "created_at"),
+ ("started_at", "started_at"),
+ ("completed_at", "completed_at"),
+ ("status", "status"),
+ ),
+ help_text="Sort observations by created_at, started_at, completed_at, or status. Prefix with `-` for descending.",
+ )
+
+ class Meta:
+ model = ReplayObservation
+ fields = ["status", "triggered_by", "session_id"]
+
+
+@extend_schema(tags=[VISION_TAG])
+class ReplayObservationViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
+ viewsets.GenericViewSet,
+):
+ """Read-only access to observations produced by a lens."""
+
+ scope_object = "replay_lens"
+ required_scopes = ["replay_lens:read", "session_recording:read"]
+ permission_classes = [ReplayVisionEnabledPermission]
+ serializer_class = ReplayObservationSerializer
+ queryset = ReplayObservation.objects.all()
+ filter_backends = [DjangoFilterBackend]
+ filterset_class = ReplayObservationFilter
+
+ def safely_get_queryset(self, queryset: QuerySet[ReplayObservation]) -> QuerySet[ReplayObservation]:
+ try:
+ lens_id = uuid.UUID(self.kwargs["parent_lookup_lens_id"])
+ except (KeyError, ValueError):
+ raise NotFound()
+ lens = ReplayLens.objects.filter(team_id=self.team_id, id=lens_id).first()
+ if lens is None:
+ raise NotFound()
+ # Inherit RBAC denies on the parent lens, plus require session_recording read since
+ # observations expose session_id and model output derived from the recording.
+ self.check_object_permissions(self.request, lens)
+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
+ raise PermissionDenied("Reading replay observations requires session_recording read access.")
+ return (
+ queryset.filter(team_id=self.team_id, lens_id=lens_id)
+ .select_related("triggered_by_user")
+ .order_by("-created_at", "id")
+ )
diff --git a/products/replay_vision/backend/feature_flag.py b/products/replay_vision/backend/feature_flag.py
new file mode 100644
index 000000000000..ef7ef94eaba4
--- /dev/null
+++ b/products/replay_vision/backend/feature_flag.py
@@ -0,0 +1,38 @@
+from typing import TYPE_CHECKING
+
+import posthoganalytics
+from rest_framework.exceptions import NotFound
+from rest_framework.permissions import BasePermission
+from rest_framework.request import Request
+from rest_framework.views import APIView
+
+if TYPE_CHECKING:
+ from posthog.models.team.team import Team
+ from posthog.models.user import User
+
+REPLAY_VISION_FEATURE_FLAG = "replay-vision"
+
+
+def is_replay_vision_enabled(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,
+ distinct_id,
+ groups={"organization": organization_id, "project": project_id},
+ group_properties={"organization": {"id": organization_id}, "project": {"id": project_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+
+
+class ReplayVisionEnabledPermission(BasePermission):
+ """Hide Vision endpoints behind the `replay-vision` flag — 404 (not 403) when off."""
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ if not is_replay_vision_enabled(request.user, view.team): # type: ignore[arg-type, attr-defined]
+ raise NotFound()
+ return True
diff --git a/products/replay_vision/backend/migrations/0002_rename_replaylensobservation_replayobservation_and_more.py b/products/replay_vision/backend/migrations/0002_rename_replaylensobservation_replayobservation_and_more.py
new file mode 100644
index 000000000000..c67dc77b0f6e
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0002_rename_replaylensobservation_replayobservation_and_more.py
@@ -0,0 +1,79 @@
+# Generated by Django 5.2.13 on 2026-05-09 07:49
+
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1152_fix_device_bucketing_persist_across_auth"),
+ ("replay_vision", "0001_initial"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.RenameModel(
+ old_name="ReplayLensObservation",
+ new_name="ReplayObservation",
+ ),
+ migrations.RemoveConstraint(
+ model_name="replayobservation",
+ name="replay_lens_observation_unique_lens_session",
+ ),
+ migrations.RemoveConstraint(
+ model_name="replayobservation",
+ name="replay_lens_observation_completed_at_matches_status",
+ ),
+ migrations.RemoveIndex(
+ model_name="replaylens",
+ name="rl_team_status_idx",
+ ),
+ migrations.RemoveField(
+ model_name="replaylens",
+ name="is_builtin",
+ ),
+ migrations.RemoveField(
+ model_name="replaylens",
+ name="status",
+ ),
+ migrations.RemoveField(
+ model_name="replaylens",
+ name="status_reason",
+ ),
+ migrations.AddField(
+ model_name="replaylens",
+ name="enabled",
+ field=models.BooleanField(
+ default=True,
+ help_text="When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work.",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="replaylens",
+ index=models.Index(fields=["team", "enabled"], name="rl_team_enabled_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="replayobservation",
+ constraint=models.UniqueConstraint(
+ fields=("lens", "session_id"),
+ name="replay_observation_unique_lens_session",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="replayobservation",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ models.Q(
+ ("completed_at__isnull", True),
+ ("status__in", ["pending", "running"]),
+ ),
+ models.Q(
+ ("completed_at__isnull", False),
+ ("status__in", ["succeeded", "failed"]),
+ ),
+ _connector="OR",
+ ),
+ name="replay_observation_completed_at_matches_status",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index cbab66dde92a..0d5d7236ddc7 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_initial
+0002_rename_replaylensobservation_replayobservation_and_more
diff --git a/products/replay_vision/backend/models/__init__.py b/products/replay_vision/backend/models/__init__.py
index 39e85bd9d156..e17740799d9b 100644
--- a/products/replay_vision/backend/models/__init__.py
+++ b/products/replay_vision/backend/models/__init__.py
@@ -1,4 +1,4 @@
from products.replay_vision.backend.models.replay_lens import ReplayLens
-from products.replay_vision.backend.models.replay_lens_observation import ReplayLensObservation
+from products.replay_vision.backend.models.replay_observation import ReplayObservation
-__all__ = ["ReplayLens", "ReplayLensObservation"]
+__all__ = ["ReplayLens", "ReplayObservation"]
diff --git a/products/replay_vision/backend/models/replay_lens.py b/products/replay_vision/backend/models/replay_lens.py
index b0f61fbc500b..fbeefe0f40bb 100644
--- a/products/replay_vision/backend/models/replay_lens.py
+++ b/products/replay_vision/backend/models/replay_lens.py
@@ -13,12 +13,6 @@ class LensType(models.TextChoices):
INDEXER = "indexer", "Indexer"
-class LensStatus(models.TextChoices):
- ACTIVE = "active", "Active"
- PAUSED = "paused", "Paused"
- ERROR = "error", "Error"
-
-
class LensProvider(models.TextChoices):
GOOGLE = "google", "Google"
@@ -54,15 +48,10 @@ class ReplayLens(UUIDModel):
provider = models.CharField(max_length=32, choices=LensProvider.choices, default=LensProvider.GOOGLE)
model = models.CharField(max_length=64, choices=LensModel.choices)
- status = models.CharField(
- max_length=16,
- choices=LensStatus.choices,
- default=LensStatus.ACTIVE,
- help_text="Lifecycle state. Only `active` lenses are scheduled; `paused` and `error` lenses have their schedules removed by the reconciler.",
+ enabled = models.BooleanField(
+ default=True,
+ help_text="When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work.",
)
- status_reason = models.TextField(blank=True, default="")
-
- is_builtin = models.BooleanField(default=False)
emits_signals = models.BooleanField(default=False)
lens_version = models.PositiveIntegerField(
@@ -87,10 +76,9 @@ class ReplayLens(UUIDModel):
),
]
indexes = [
- models.Index(fields=["team", "status"], name="rl_team_status_idx"),
+ models.Index(fields=["team", "enabled"], name="rl_team_enabled_idx"),
]
- # Fields that bump `lens_version` when changed — only those affecting what the lens does.
_VERSION_TRACKED_FIELDS = (
"lens_type",
"lens_config",
@@ -102,8 +90,7 @@ class ReplayLens(UUIDModel):
)
def save(self, *args, **kwargs) -> None:
- # Bump lens_version when any tracked field actually changed; SELECT FOR UPDATE
- # inside transaction.atomic() so concurrent saves can't both bump from the same baseline.
+ # SELECT FOR UPDATE so concurrent saves can't both bump lens_version from the same baseline.
update_fields = kwargs.get("update_fields")
if update_fields is not None:
relevant = [f for f in self._VERSION_TRACKED_FIELDS if f in update_fields]
diff --git a/products/replay_vision/backend/models/replay_lens_observation.py b/products/replay_vision/backend/models/replay_observation.py
similarity index 82%
rename from products/replay_vision/backend/models/replay_lens_observation.py
rename to products/replay_vision/backend/models/replay_observation.py
index 8d7f122dfc9b..2095f577b148 100644
--- a/products/replay_vision/backend/models/replay_lens_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -16,7 +16,7 @@ class ObservationTrigger(models.TextChoices):
ON_DEMAND = "on_demand", "On demand"
-class ReplayLensObservation(UUIDModel):
+class ReplayObservation(UUIDModel):
"""One application of a `ReplayLens` to a session recording (see README)."""
lens = models.ForeignKey("replay_vision.ReplayLens", on_delete=models.CASCADE, related_name="observations")
@@ -67,21 +67,19 @@ class ReplayLensObservation(UUIDModel):
class Meta:
constraints = [
- # At-most-once: failed/succeeded rows are sticky; admin deletes to re-trigger.
- models.UniqueConstraint(fields=["lens", "session_id"], name="replay_lens_observation_unique_lens_session"),
- # Terminal status ⇔ completed_at non-null.
+ # Failed/succeeded rows are sticky; admin deletes to re-trigger.
+ models.UniqueConstraint(fields=["lens", "session_id"], name="replay_observation_unique_lens_session"),
models.CheckConstraint(
condition=(
models.Q(status__in=["pending", "running"], completed_at__isnull=True)
| models.Q(status__in=["succeeded", "failed"], completed_at__isnull=False)
),
- name="replay_lens_observation_completed_at_matches_status",
+ name="replay_observation_completed_at_matches_status",
),
]
indexes = [
models.Index(fields=["team", "created_at"], name="rlo_team_created_idx"),
models.Index(fields=["lens", "status"], name="rlo_lens_status_idx"),
- # Partial index for the reaper's workflow_id lookups; excludes pending rows.
models.Index(
fields=["workflow_id"],
name="rlo_workflow_id_idx",
@@ -90,24 +88,20 @@ class ReplayLensObservation(UUIDModel):
]
def save(self, *args, **kwargs) -> None:
- # Tenant invariant: observation.team_id must equal lens.team_id; validated only on create.
+ # Tenant invariant: observation.team_id must match lens.team_id.
if self._state.adding:
lens_team_id = self.lens.team_id
if self.team_id and self.team_id != lens_team_id:
- raise ValueError(
- f"ReplayLensObservation.team_id ({self.team_id}) must match lens.team_id ({lens_team_id})"
- )
+ raise ValueError(f"ReplayObservation.team_id ({self.team_id}) must match lens.team_id ({lens_team_id})")
self.team_id = lens_team_id
super().save(*args, **kwargs)
def mark_succeeded(self) -> None:
- """Transition to terminal `succeeded` while satisfying the completed_at invariant."""
self.status = ObservationStatus.SUCCEEDED
self.completed_at = timezone.now()
self.save(update_fields=["status", "completed_at"])
def mark_failed(self, error_reason: str) -> None:
- """Transition to terminal `failed` with a non-empty reason while satisfying the completed_at invariant."""
self.status = ObservationStatus.FAILED
self.error_reason = error_reason
self.completed_at = timezone.now()
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index e69de29bb2d1..4127e9f001f6 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -0,0 +1,329 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import Organization, Team
+
+from products.replay_vision.backend.models.replay_lens import LensModel, LensProvider, LensType, ReplayLens
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ObservationTrigger,
+ ReplayObservation,
+)
+
+
+class _VisionAPITestCase(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()
+
+ def tearDown(self) -> None:
+ self.flag_patcher.stop()
+ super().tearDown()
+
+ @property
+ def lenses_url(self) -> str:
+ return f"/api/environments/{self.team.id}/vision/lenses/"
+
+ def observations_url(self, lens_id: str) -> str:
+ return f"/api/environments/{self.team.id}/vision/lenses/{lens_id}/observations/"
+
+ def _create_lens(self, **overrides) -> ReplayLens:
+ defaults = {
+ "team": self.team,
+ "name": "my-lens",
+ "lens_type": LensType.MONITOR,
+ "lens_config": {"prompt": "did the user check out?"},
+ "model": LensModel.GEMINI_3_FLASH,
+ }
+ defaults.update(overrides)
+ return ReplayLens.objects.create(**defaults)
+
+
+class TestReplayLensViewSet(_VisionAPITestCase):
+ def test_create_minimal(self) -> None:
+ resp = self.client.post(
+ self.lenses_url,
+ data={
+ "name": "checkout-monitor",
+ "lens_type": LensType.MONITOR,
+ "lens_config": {"prompt": "did checkout complete?"},
+ "model": LensModel.GEMINI_3_FLASH,
+ },
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 201, resp.json())
+ body = resp.json()
+ self.assertEqual(body["name"], "checkout-monitor")
+ self.assertTrue(body["enabled"])
+ self.assertEqual(body["sampling_rate"], 1.0)
+ self.assertEqual(body["lens_version"], 1)
+ self.assertEqual(body["created_by"]["id"], self.user.id)
+
+ @parameterized.expand(["name", "lens_type", "lens_config", "model"])
+ def test_create_validates_required_field(self, missing_field: str) -> None:
+ payload = {
+ "name": f"missing-{missing_field}",
+ "lens_type": LensType.MONITOR,
+ "lens_config": {"prompt": "p"},
+ "model": LensModel.GEMINI_3_FLASH,
+ }
+ del payload[missing_field]
+ resp = self.client.post(self.lenses_url, data=payload, format="json")
+ self.assertEqual(resp.status_code, 400)
+ self.assertEqual(resp.json()["attr"], missing_field)
+
+ def test_create_round_trips_provider(self) -> None:
+ resp = self.client.post(
+ self.lenses_url,
+ data={
+ "name": "explicit-provider",
+ "lens_type": LensType.MONITOR,
+ "lens_config": {"prompt": "p"},
+ "model": LensModel.GEMINI_3_FLASH,
+ "provider": LensProvider.GOOGLE,
+ },
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 201)
+ self.assertEqual(resp.json()["provider"], LensProvider.GOOGLE)
+
+ @parameterized.expand([("below", -0.1), ("above", 1.5)])
+ def test_create_rejects_out_of_range_sampling_rate(self, _label: str, value: float) -> None:
+ resp = self.client.post(
+ self.lenses_url,
+ data={
+ "name": f"rate-{value}",
+ "lens_type": LensType.MONITOR,
+ "lens_config": {"prompt": "p"},
+ "model": LensModel.GEMINI_3_FLASH,
+ "sampling_rate": value,
+ },
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 400)
+ self.assertEqual(resp.json()["attr"], "sampling_rate")
+
+ def test_create_duplicate_name_rejected(self) -> None:
+ self._create_lens(name="dup")
+ resp = self.client.post(
+ self.lenses_url,
+ data={
+ "name": "dup",
+ "lens_type": LensType.MONITOR,
+ "lens_config": {"prompt": "p"},
+ "model": LensModel.GEMINI_3_FLASH,
+ },
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 400)
+
+ def test_list_returns_only_team_lenses(self) -> None:
+ self._create_lens(name="ours")
+ other_org = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_org, name="other-team")
+ ReplayLens.objects.create(
+ team=other_team,
+ name="theirs",
+ lens_type=LensType.MONITOR,
+ lens_config={"prompt": "p"},
+ model=LensModel.GEMINI_3_FLASH,
+ )
+ resp = self.client.get(self.lenses_url)
+ self.assertEqual(resp.status_code, 200)
+ names = [r["name"] for r in resp.json()["results"]]
+ self.assertEqual(names, ["ours"])
+
+ def test_retrieve(self) -> None:
+ lens = self._create_lens()
+ resp = self.client.get(f"{self.lenses_url}{lens.id}/")
+ self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.json()["id"], str(lens.id))
+
+ def test_patch_bumps_lens_version_on_tracked_change(self) -> None:
+ lens = self._create_lens()
+ resp = self.client.patch(
+ f"{self.lenses_url}{lens.id}/",
+ data={"sampling_rate": 0.5},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual(resp.json()["lens_version"], 2)
+ self.assertEqual(resp.json()["sampling_rate"], 0.5)
+
+ def test_patch_does_not_bump_on_metadata_change(self) -> None:
+ lens = self._create_lens()
+ resp = self.client.patch(
+ f"{self.lenses_url}{lens.id}/",
+ data={"description": "now described"},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.json()["lens_version"], 1)
+
+ def test_delete(self) -> None:
+ lens = self._create_lens()
+ resp = self.client.delete(f"{self.lenses_url}{lens.id}/")
+ self.assertEqual(resp.status_code, 204)
+ self.assertFalse(ReplayLens.objects.filter(id=lens.id).exists())
+
+ @parameterized.expand(
+ [
+ ("enabled", "false", 1),
+ ("lens_type", LensType.CLASSIFIER, 1),
+ ("emits_signals", "true", 1),
+ ]
+ )
+ def test_filterset(self, field: str, value: str, expected_count: int) -> None:
+ if field == "enabled":
+ self._create_lens(name="enabled-lens")
+ self._create_lens(name="disabled-lens", enabled=False)
+ elif field == "lens_type":
+ self._create_lens(name="monitor-lens")
+ self._create_lens(name="classifier-lens", lens_type=LensType.CLASSIFIER)
+ elif field == "emits_signals":
+ self._create_lens(name="silent")
+ self._create_lens(name="loud", emits_signals=True)
+ resp = self.client.get(f"{self.lenses_url}?{field}={value}")
+ self.assertEqual(resp.status_code, 200)
+ self.assertEqual(len(resp.json()["results"]), expected_count)
+
+ def test_order_by_descending(self) -> None:
+ self._create_lens(name="a-lens")
+ self._create_lens(name="b-lens")
+ resp = self.client.get(f"{self.lenses_url}?order_by=-name")
+ self.assertEqual(resp.status_code, 200)
+ self.assertEqual([r["name"] for r in resp.json()["results"]], ["b-lens", "a-lens"])
+
+
+class TestReplayLensViewSetFeatureFlag(APIBaseTest):
+ @property
+ def lenses_url(self) -> str:
+ return f"/api/environments/{self.team.id}/vision/lenses/"
+
+ @patch("products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled", return_value=False)
+ def test_flag_off_returns_404_on_list(self, _flag_mock) -> None:
+ resp = self.client.get(self.lenses_url)
+ self.assertEqual(resp.status_code, 404)
+
+ @patch("products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled", return_value=False)
+ def test_flag_off_returns_404_on_create(self, _flag_mock) -> None:
+ resp = self.client.post(self.lenses_url, data={"name": "x"}, format="json")
+ self.assertEqual(resp.status_code, 404)
+
+
+class TestReplayObservationViewSet(_VisionAPITestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.lens = self._create_lens()
+
+ def _create_observation(self, **overrides) -> ReplayObservation:
+ defaults = {
+ "lens": self.lens,
+ "session_id": "sess-1",
+ "lens_version": self.lens.lens_version,
+ "lens_config_snapshot": self.lens.lens_config,
+ "triggered_by": ObservationTrigger.SCHEDULE,
+ }
+ defaults.update(overrides)
+ return ReplayObservation.objects.create(**defaults)
+
+ def test_list_observations_for_lens(self) -> None:
+ self._create_observation(session_id="s1")
+ self._create_observation(session_id="s2")
+ resp = self.client.get(self.observations_url(str(self.lens.id)))
+ self.assertEqual(resp.status_code, 200)
+ self.assertEqual(len(resp.json()["results"]), 2)
+
+ def test_malformed_lens_id_returns_404(self) -> None:
+ resp = self.client.get(self.observations_url("not-a-uuid"))
+ self.assertEqual(resp.status_code, 404)
+
+ def test_unknown_lens_id_returns_404(self) -> None:
+ import uuid as _uuid
+
+ resp = self.client.get(self.observations_url(str(_uuid.uuid4())))
+ self.assertEqual(resp.status_code, 404)
+
+ def test_other_team_lens_id_returns_404(self) -> None:
+ other_org = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_org, name="other")
+ other_lens = ReplayLens.objects.create(
+ team=other_team,
+ name="theirs",
+ lens_type=LensType.MONITOR,
+ lens_config={"prompt": "p"},
+ model=LensModel.GEMINI_3_FLASH,
+ )
+ resp = self.client.get(self.observations_url(str(other_lens.id)))
+ self.assertEqual(resp.status_code, 404)
+
+ def test_list_excludes_observations_from_other_lens(self) -> None:
+ other_lens = self._create_lens(name="other-lens")
+ self._create_observation(session_id="ours")
+ ReplayObservation.objects.create(
+ lens=other_lens,
+ session_id="theirs",
+ lens_version=other_lens.lens_version,
+ lens_config_snapshot=other_lens.lens_config,
+ triggered_by=ObservationTrigger.SCHEDULE,
+ )
+ resp = self.client.get(self.observations_url(str(self.lens.id)))
+ sessions = [r["session_id"] for r in resp.json()["results"]]
+ self.assertEqual(sessions, ["ours"])
+
+ def test_retrieve_observation(self) -> None:
+ obs = self._create_observation()
+ resp = self.client.get(f"{self.observations_url(str(self.lens.id))}{obs.id}/")
+ self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.json()["session_id"], obs.session_id)
+
+ @parameterized.expand(
+ [
+ ("status", ObservationStatus.FAILED, 1),
+ ("triggered_by", ObservationTrigger.ON_DEMAND, 1),
+ ("session_id", "needle", 1),
+ ]
+ )
+ def test_filterset(self, field: str, value: str, expected_count: int) -> None:
+ if field == "status":
+ self._create_observation(session_id="ok")
+ self._create_observation(
+ session_id="bad",
+ status=ObservationStatus.FAILED,
+ error_reason="oops",
+ completed_at=timezone.now(),
+ )
+ elif field == "triggered_by":
+ self._create_observation(session_id="auto")
+ self._create_observation(session_id="manual", triggered_by=ObservationTrigger.ON_DEMAND)
+ elif field == "session_id":
+ self._create_observation(session_id="needle")
+ self._create_observation(session_id="haystack")
+ resp = self.client.get(f"{self.observations_url(str(self.lens.id))}?{field}={value}")
+ self.assertEqual(resp.status_code, 200)
+ self.assertEqual(len(resp.json()["results"]), expected_count)
+
+ def test_order_by_created_at_descending(self) -> None:
+ first = self._create_observation(session_id="first")
+ second = self._create_observation(session_id="second")
+ resp = self.client.get(f"{self.observations_url(str(self.lens.id))}?order_by=-created_at")
+ self.assertEqual(resp.status_code, 200)
+ ids = [r["id"] for r in resp.json()["results"]]
+ self.assertEqual(ids, [str(second.id), str(first.id)])
+
+ def test_pagination(self) -> None:
+ for i in range(3):
+ self._create_observation(session_id=f"s{i}")
+ resp = self.client.get(f"{self.observations_url(str(self.lens.id))}?limit=2")
+ self.assertEqual(resp.status_code, 200)
+ body = resp.json()
+ self.assertEqual(len(body["results"]), 2)
+ self.assertIsNotNone(body.get("next"))
diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.py
index 48c6cbe1a993..ab704d64e49a 100644
--- a/products/replay_vision/backend/tests/test_models.py
+++ b/products/replay_vision/backend/tests/test_models.py
@@ -5,13 +5,12 @@ from django.utils import timezone
from parameterized import parameterized
-from products.replay_vision.backend.models import ReplayLens, ReplayLensObservation
-from products.replay_vision.backend.models.replay_lens import LensModel, LensProvider, LensStatus, LensType
-from products.replay_vision.backend.models.replay_lens_observation import ObservationStatus, ObservationTrigger
+from products.replay_vision.backend.models import ReplayLens, ReplayObservation
+from products.replay_vision.backend.models.replay_lens import LensModel, LensProvider, LensType
+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ObservationTrigger
def _make_lens(team, **overrides) -> ReplayLens:
- """Shared lens factory for both test classes; pass `team=self.team` from a BaseTest."""
defaults = {
"team": team,
"name": "my-lens",
@@ -30,11 +29,10 @@ class TestReplayLens(BaseTest):
def test_create_with_required_fields(self) -> None:
lens = self._create_lens()
self.assertEqual(lens.lens_type, LensType.MONITOR)
- self.assertEqual(lens.status, LensStatus.ACTIVE)
+ self.assertTrue(lens.enabled)
self.assertEqual(lens.provider, LensProvider.GOOGLE)
self.assertEqual(lens.sampling_rate, 1.0)
self.assertEqual(lens.lens_version, 1)
- self.assertFalse(lens.is_builtin)
self.assertFalse(lens.emits_signals)
self.assertIsNotNone(lens.last_swept_at)
@@ -120,11 +118,11 @@ class TestReplayLens(BaseTest):
def test_lens_version_does_not_bump_with_non_tracked_update_fields(self) -> None:
lens = self._create_lens()
lens.lens_config = {"prompt": "in-memory only"} # tracked change in memory
- lens.status = LensStatus.PAUSED
- lens.save(update_fields=["status"]) # save only status — tracked change shouldn't bump
+ lens.enabled = False
+ lens.save(update_fields=["enabled"]) # save only enabled — tracked change shouldn't bump
lens.refresh_from_db()
self.assertEqual(lens.lens_version, 1)
- self.assertEqual(lens.status, LensStatus.PAUSED)
+ self.assertFalse(lens.enabled)
def test_lens_version_bumps_with_tracked_update_field_persists(self) -> None:
lens = self._create_lens()
@@ -135,13 +133,13 @@ class TestReplayLens(BaseTest):
self.assertEqual(lens.lens_config, {"prompt": "persisted"})
-class TestReplayLensObservation(BaseTest):
+class TestReplayObservation(BaseTest):
def _create_lens(self, **overrides) -> ReplayLens:
return _make_lens(self.team, **overrides)
- def _create_observation(self, lens: ReplayLens, session_id: str = "abc-123") -> ReplayLensObservation:
+ def _create_observation(self, lens: ReplayLens, session_id: str = "abc-123") -> ReplayObservation:
# team is auto-populated from lens by save() override.
- return ReplayLensObservation.objects.create(
+ return ReplayObservation.objects.create(
lens=lens,
session_id=session_id,
lens_version=lens.lens_version,
@@ -181,11 +179,11 @@ class TestReplayLensObservation(BaseTest):
self._create_observation(lens)
lens_id = lens.id
lens.delete()
- self.assertEqual(ReplayLensObservation.objects.filter(lens_id=lens_id).count(), 0)
+ self.assertEqual(ReplayObservation.objects.filter(lens_id=lens_id).count(), 0)
def test_team_id_auto_populated_from_lens(self) -> None:
lens = self._create_lens()
- obs = ReplayLensObservation.objects.create(
+ obs = ReplayObservation.objects.create(
lens=lens,
session_id="auto-team",
lens_version=lens.lens_version,
@@ -198,7 +196,7 @@ class TestReplayLensObservation(BaseTest):
lens = self._create_lens()
other_team = self.organization.teams.create(name="other")
with self.assertRaises(ValueError):
- ReplayLensObservation.objects.create(
+ ReplayObservation.objects.create(
lens=lens,
team=other_team,
session_id="mismatch",
@@ -230,9 +228,9 @@ class TestReplayLensObservation(BaseTest):
kwargs["completed_at"] = timezone.now()
if expect_error:
with self.assertRaises(IntegrityError):
- ReplayLensObservation.objects.create(**kwargs)
+ ReplayObservation.objects.create(**kwargs)
else:
- ReplayLensObservation.objects.create(**kwargs)
+ ReplayObservation.objects.create(**kwargs)
def test_team_delete_cascades_to_lens_and_observations(self) -> None:
other_team = self.organization.teams.create(name="cascade-target")
@@ -247,14 +245,14 @@ class TestReplayLensObservation(BaseTest):
lens_id = lens.id
other_team.delete()
self.assertFalse(ReplayLens.objects.filter(id=lens_id).exists())
- self.assertEqual(ReplayLensObservation.objects.filter(lens_id=lens_id).count(), 0)
+ self.assertEqual(ReplayObservation.objects.filter(lens_id=lens_id).count(), 0)
def test_user_delete_nulls_triggered_by_user(self) -> None:
from django.contrib.auth import get_user_model
ephemeral = get_user_model().objects.create_user(email="[email protected]", password="x", first_name="Eph")
lens = self._create_lens()
- obs = ReplayLensObservation.objects.create(
+ obs = ReplayObservation.objects.create(
lens=lens,
session_id="user-cascade",
lens_version=lens.lens_version,
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..bfdfd4c801f6
--- /dev/null
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -0,0 +1,397 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * * `monitor` - Monitor
+ * `classifier` - Classifier
+ * `scorer` - Scorer
+ * `summarizer` - Summarizer
+ * `indexer` - Indexer
+ */
+export type LensTypeEnumApi = (typeof LensTypeEnumApi)[keyof typeof LensTypeEnumApi]
+
+export const LensTypeEnumApi = {
+ Monitor: 'monitor',
+ Classifier: 'classifier',
+ Scorer: 'scorer',
+ Summarizer: 'summarizer',
+ Indexer: 'indexer',
+} as const
+
+/**
+ * * `google` - Google
+ */
+export type LensProviderEnumApi = (typeof LensProviderEnumApi)[keyof typeof LensProviderEnumApi]
+
+export const LensProviderEnumApi = {
+ Google: 'google',
+} as const
+
+/**
+ * * `gemini-3-flash` - Gemini 3 Flash
+ * `gemini-3-flash-lite` - Gemini 3 Flash Lite
+ */
+export type LensModelEnumApi = (typeof LensModelEnumApi)[keyof typeof LensModelEnumApi]
+
+export const LensModelEnumApi = {
+ Gemini3Flash: 'gemini-3-flash',
+ Gemini3FlashLite: 'gemini-3-flash-lite',
+} 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 ReplayLensApi {
+ readonly id: string
+ /**
+ * Human-readable lens name. Unique within the team.
+ * @maxLength 255
+ */
+ name: string
+ /** Free-form description shown in the lens management UI. */
+ description?: string
+ /** What the lens does: monitor, classifier, scorer, summarizer, or indexer.
+
+ * `monitor` - Monitor
+ * `classifier` - Classifier
+ * `scorer` - Scorer
+ * `summarizer` - Summarizer
+ * `indexer` - Indexer */
+ lens_type: LensTypeEnumApi
+ /** Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc. */
+ lens_config: unknown
+ /** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
+ query?: unknown
+ /**
+ * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).
+ * @minimum 0
+ * @maximum 1
+ */
+ sampling_rate?: number
+ /** LLM provider. v1 is Google-only.
+
+ * `google` - Google */
+ provider?: LensProviderEnumApi
+ /** Concrete model to use for this lens.
+
+ * `gemini-3-flash` - Gemini 3 Flash
+ * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ model: LensModelEnumApi
+ /** When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work. */
+ enabled?: boolean
+ /** When true, the prompt is augmented with the Signal side mission and the lens emits PostHog Signals. */
+ emits_signals?: boolean
+ /** Increments on every config-changing save. Observations snapshot this value. */
+ readonly lens_version: number
+ /** Watermark for the lens's last scheduled fire. Mirrors Temporal schedule state for recovery. */
+ readonly last_swept_at: string
+ readonly created_at: string
+ /** User who created the lens. */
+ readonly created_by: UserBasicApi | null
+ readonly updated_at: string
+}
+
+export interface PaginatedReplayLensListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: ReplayLensApi[]
+}
+
+/**
+ * * `pending` - Pending
+ * `running` - Running
+ * `succeeded` - Succeeded
+ * `failed` - Failed
+ */
+export type ObservationStatusEnumApi = (typeof ObservationStatusEnumApi)[keyof typeof ObservationStatusEnumApi]
+
+export const ObservationStatusEnumApi = {
+ Pending: 'pending',
+ Running: 'running',
+ Succeeded: 'succeeded',
+ Failed: 'failed',
+} as const
+
+/**
+ * * `schedule` - Schedule
+ * `on_demand` - On demand
+ */
+export type ObservationTriggerEnumApi = (typeof ObservationTriggerEnumApi)[keyof typeof ObservationTriggerEnumApi]
+
+export const ObservationTriggerEnumApi = {
+ Schedule: 'schedule',
+ OnDemand: 'on_demand',
+} as const
+
+export interface ReplayObservationApi {
+ readonly id: string
+ /** The lens that produced this observation. */
+ readonly lens_id: string
+ /** Session recording id this lens was applied to. */
+ readonly session_id: string
+ /** Observation status (pending, running, succeeded, failed).
+
+ * `pending` - Pending
+ * `running` - Running
+ * `succeeded` - Succeeded
+ * `failed` - Failed */
+ readonly status: ObservationStatusEnumApi
+ /** Populated on failure. Includes the malformed model response when validation fails. */
+ readonly error_reason: string
+ /** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
+ readonly workflow_id: string
+ /** The `ReplayLens.lens_version` value at the moment the workflow ran. */
+ readonly lens_version: number
+ /** Snapshot of `ReplayLens.lens_config` at run time. Lens edits do not retroactively mutate observations. */
+ readonly lens_config_snapshot: unknown
+ /** Concrete model that ran the observation. */
+ readonly model_used: string
+ /** Concrete provider that ran the observation. */
+ readonly provider_used: string
+ /** Whether this observation came from the schedule or an on-demand request.
+
+ * `schedule` - Schedule
+ * `on_demand` - On demand */
+ readonly triggered_by: ObservationTriggerEnumApi
+ /** User who triggered an on-demand observation. Null for scheduled observations. */
+ readonly triggered_by_user: UserBasicApi | null
+ /** @nullable */
+ started_at?: string | null
+ /** @nullable */
+ completed_at?: string | null
+ readonly created_at: string
+}
+
+export interface PaginatedReplayObservationListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: ReplayObservationApi[]
+}
+
+export interface PatchedReplayLensApi {
+ readonly id?: string
+ /**
+ * Human-readable lens name. Unique within the team.
+ * @maxLength 255
+ */
+ name?: string
+ /** Free-form description shown in the lens management UI. */
+ description?: string
+ /** What the lens does: monitor, classifier, scorer, summarizer, or indexer.
+
+ * `monitor` - Monitor
+ * `classifier` - Classifier
+ * `scorer` - Scorer
+ * `summarizer` - Summarizer
+ * `indexer` - Indexer */
+ lens_type?: LensTypeEnumApi
+ /** Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc. */
+ lens_config?: unknown
+ /** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
+ query?: unknown
+ /**
+ * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).
+ * @minimum 0
+ * @maximum 1
+ */
+ sampling_rate?: number
+ /** LLM provider. v1 is Google-only.
+
+ * `google` - Google */
+ provider?: LensProviderEnumApi
+ /** Concrete model to use for this lens.
+
+ * `gemini-3-flash` - Gemini 3 Flash
+ * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ model?: LensModelEnumApi
+ /** When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work. */
+ enabled?: boolean
+ /** When true, the prompt is augmented with the Signal side mission and the lens emits PostHog Signals. */
+ emits_signals?: boolean
+ /** Increments on every config-changing save. Observations snapshot this value. */
+ readonly lens_version?: number
+ /** Watermark for the lens's last scheduled fire. Mirrors Temporal schedule state for recovery. */
+ readonly last_swept_at?: string
+ readonly created_at?: string
+ /** User who created the lens. */
+ readonly created_by?: UserBasicApi | null
+ readonly updated_at?: string
+}
+
+export type VisionLensesListParams = {
+ /**
+ * Filter to lenses that emit Signals.
+ */
+ emits_signals?: boolean
+ /**
+ * Filter to enabled vs disabled lenses.
+ */
+ enabled?: boolean
+ /**
+ * Filter by lens type (monitor, classifier, scorer, summarizer, indexer).
+
+* `monitor` - Monitor
+* `classifier` - Classifier
+* `scorer` - Scorer
+* `summarizer` - Summarizer
+* `indexer` - Indexer
+ */
+ lens_type?: VisionLensesListLensType
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Sort lenses by name, created_at, updated_at, or lens_type. Prefix with `-` for descending.
+
+* `name` - Name
+* `-name` - Name (descending)
+* `created_at` - Created at
+* `-created_at` - Created at (descending)
+* `updated_at` - Updated at
+* `-updated_at` - Updated at (descending)
+* `lens_type` - Lens type
+* `-lens_type` - Lens type (descending)
+ */
+ order_by?: string[]
+}
+
+export type VisionLensesListLensType = (typeof VisionLensesListLensType)[keyof typeof VisionLensesListLensType]
+
+export const VisionLensesListLensType = {
+ Classifier: 'classifier',
+ Indexer: 'indexer',
+ Monitor: 'monitor',
+ Scorer: 'scorer',
+ Summarizer: 'summarizer',
+} as const
+
+export type VisionLensesObservationsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Sort observations by created_at, started_at, completed_at, or status. Prefix with `-` for descending.
+
+* `created_at` - Created at
+* `-created_at` - Created at (descending)
+* `started_at` - Started at
+* `-started_at` - Started at (descending)
+* `completed_at` - Completed at
+* `-completed_at` - Completed at (descending)
+* `status` - Status
+* `-status` - Status (descending)
+ */
+ order_by?: string[]
+ /**
+ * Filter to observations of a specific session recording.
+ */
+ session_id?: string
+ /**
+ * Filter by observation status.
+
+* `pending` - Pending
+* `running` - Running
+* `succeeded` - Succeeded
+* `failed` - Failed
+ */
+ status?: VisionLensesObservationsListStatus
+ /**
+ * Filter by trigger source (schedule or on_demand).
+
+* `schedule` - Schedule
+* `on_demand` - On demand
+ */
+ triggered_by?: VisionLensesObservationsListTriggeredBy
+}
+
+export type VisionLensesObservationsListStatus =
+ (typeof VisionLensesObservationsListStatus)[keyof typeof VisionLensesObservationsListStatus]
+
+export const VisionLensesObservationsListStatus = {
+ Failed: 'failed',
+ Pending: 'pending',
+ Running: 'running',
+ Succeeded: 'succeeded',
+} as const
+
+export type VisionLensesObservationsListTriggeredBy =
+ (typeof VisionLensesObservationsListTriggeredBy)[keyof typeof VisionLensesObservationsListTriggeredBy]
+
+export const VisionLensesObservationsListTriggeredBy = {
+ OnDemand: 'on_demand',
+ Schedule: 'schedule',
+} as const
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
new file mode 100644
index 000000000000..f9aaf7394923
--- /dev/null
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -0,0 +1,196 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ PaginatedReplayLensListApi,
+ PaginatedReplayObservationListApi,
+ PatchedReplayLensApi,
+ ReplayLensApi,
+ ReplayObservationApi,
+ VisionLensesListParams,
+ VisionLensesObservationsListParams,
+} from './api.schemas'
+
+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
+
+type WritableKeys<T> = {
+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
+}[keyof T]
+
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
+
+type Writable<T> = Pick<T, WritableKeys<T>>
+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
+ ? {
+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
+ }
+ : DistributeReadOnlyOverUnions<T>
+
+export const getVisionLensesListUrl = (projectId: string, params?: VisionLensesListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/environments/${projectId}/vision/lenses/?${stringifiedParams}`
+ : `/api/environments/${projectId}/vision/lenses/`
+}
+
+/**
+ * CRUD for Replay Vision lenses.
+ */
+export const visionLensesList = async (
+ projectId: string,
+ params?: VisionLensesListParams,
+ options?: RequestInit
+): Promise<PaginatedReplayLensListApi> => {
+ return apiMutator<PaginatedReplayLensListApi>(getVisionLensesListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getVisionLensesCreateUrl = (projectId: string) => {
+ return `/api/environments/${projectId}/vision/lenses/`
+}
+
+/**
+ * CRUD for Replay Vision lenses.
+ */
+export const visionLensesCreate = async (
+ projectId: string,
+ replayLensApi: NonReadonly<ReplayLensApi>,
+ options?: RequestInit
+): Promise<ReplayLensApi> => {
+ return apiMutator<ReplayLensApi>(getVisionLensesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(replayLensApi),
+ })
+}
+
+export const getVisionLensesObservationsListUrl = (
+ projectId: string,
+ lensId: string,
+ params?: VisionLensesObservationsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/environments/${projectId}/vision/lenses/${lensId}/observations/?${stringifiedParams}`
+ : `/api/environments/${projectId}/vision/lenses/${lensId}/observations/`
+}
+
+/**
+ * Read-only access to observations produced by a lens.
+ */
+export const visionLensesObservationsList = async (
+ projectId: string,
+ lensId: string,
+ params?: VisionLensesObservationsListParams,
+ options?: RequestInit
+): Promise<PaginatedReplayObservationListApi> => {
+ return apiMutator<PaginatedReplayObservationListApi>(
+ getVisionLensesObservationsListUrl(projectId, lensId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getVisionLensesObservationsRetrieveUrl = (projectId: string, lensId: string, id: string) => {
+ return `/api/environments/${projectId}/vision/lenses/${lensId}/observations/${id}/`
+}
+
+/**
+ * Read-only access to observations produced by a lens.
+ */
+export const visionLensesObservationsRetrieve = async (
+ projectId: string,
+ lensId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ReplayObservationApi> => {
+ return apiMutator<ReplayObservationApi>(getVisionLensesObservationsRetrieveUrl(projectId, lensId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getVisionLensesRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/environments/${projectId}/vision/lenses/${id}/`
+}
+
+/**
+ * CRUD for Replay Vision lenses.
+ */
+export const visionLensesRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ReplayLensApi> => {
+ return apiMutator<ReplayLensApi>(getVisionLensesRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getVisionLensesPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/environments/${projectId}/vision/lenses/${id}/`
+}
+
+/**
+ * CRUD for Replay Vision lenses.
+ */
+export const visionLensesPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedReplayLensApi?: NonReadonly<PatchedReplayLensApi>,
+ options?: RequestInit
+): Promise<ReplayLensApi> => {
+ return apiMutator<ReplayLensApi>(getVisionLensesPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedReplayLensApi),
+ })
+}
+
+export const getVisionLensesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/environments/${projectId}/vision/lenses/${id}/`
+}
+
+/**
+ * CRUD for Replay Vision lenses.
+ */
+export const visionLensesDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getVisionLensesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..be9946cb0fb4
--- /dev/null
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -0,0 +1,135 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * CRUD for Replay Vision lenses.
+ */
+export const visionLensesCreateBodyNameMax = 255
+
+export const visionLensesCreateBodySamplingRateMin = 0
+export const visionLensesCreateBodySamplingRateMax = 1
+
+export const VisionLensesCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(visionLensesCreateBodyNameMax).describe('Human-readable lens name. Unique within the team.'),
+ description: zod.string().optional().describe('Free-form description shown in the lens management UI.'),
+ lens_type: zod
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'indexer'])
+ .describe(
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `indexer` - Indexer'
+ )
+ .describe(
+ 'What the lens does: monitor, classifier, scorer, summarizer, or indexer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `indexer` - Indexer'
+ ),
+ lens_config: zod
+ .unknown()
+ .describe(
+ 'Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc.'
+ ),
+ query: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`\/`date_to` are stripped on save — the schedule controls time, not the user.'
+ ),
+ sampling_rate: zod
+ .number()
+ .min(visionLensesCreateBodySamplingRateMin)
+ .max(visionLensesCreateBodySamplingRateMax)
+ .optional()
+ .describe('0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).'),
+ provider: zod
+ .enum(['google'])
+ .describe('\* `google` - Google')
+ .optional()
+ .describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),
+ model: zod
+ .enum(['gemini-3-flash', 'gemini-3-flash-lite'])
+ .describe('\* `gemini-3-flash` - Gemini 3 Flash\n\* `gemini-3-flash-lite` - Gemini 3 Flash Lite')
+ .describe(
+ 'Concrete model to use for this lens.\n\n\* `gemini-3-flash` - Gemini 3 Flash\n\* `gemini-3-flash-lite` - Gemini 3 Flash Lite'
+ ),
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe("When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work."),
+ emits_signals: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'When true, the prompt is augmented with the Signal side mission and the lens emits PostHog Signals.'
+ ),
+})
+
+/**
+ * CRUD for Replay Vision lenses.
+ */
+export const visionLensesPartialUpdateBodyNameMax = 255
+
+export const visionLensesPartialUpdateBodySamplingRateMin = 0
+export const visionLensesPartialUpdateBodySamplingRateMax = 1
+
+export const VisionLensesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(visionLensesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Human-readable lens name. Unique within the team.'),
+ description: zod.string().optional().describe('Free-form description shown in the lens management UI.'),
+ lens_type: zod
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'indexer'])
+ .describe(
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `indexer` - Indexer'
+ )
+ .optional()
+ .describe(
+ 'What the lens does: monitor, classifier, scorer, summarizer, or indexer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `indexer` - Indexer'
+ ),
+ lens_config: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc.'
+ ),
+ query: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`\/`date_to` are stripped on save — the schedule controls time, not the user.'
+ ),
+ sampling_rate: zod
+ .number()
+ .min(visionLensesPartialUpdateBodySamplingRateMin)
+ .max(visionLensesPartialUpdateBodySamplingRateMax)
+ .optional()
+ .describe('0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).'),
+ provider: zod
+ .enum(['google'])
+ .describe('\* `google` - Google')
+ .optional()
+ .describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),
+ model: zod
+ .enum(['gemini-3-flash', 'gemini-3-flash-lite'])
+ .describe('\* `gemini-3-flash` - Gemini 3 Flash\n\* `gemini-3-flash-lite` - Gemini 3 Flash Lite')
+ .optional()
+ .describe(
+ 'Concrete model to use for this lens.\n\n\* `gemini-3-flash` - Gemini 3 Flash\n\* `gemini-3-flash-lite` - Gemini 3 Flash Lite'
+ ),
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe("When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work."),
+ emits_signals: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'When true, the prompt is augmented with the Signal side mission and the lens emits PostHog Signals.'
+ ),
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e71617340929..7e4662df6314 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18895,6 +18895,46 @@ export namespace Schemas {
created_at: string;
}
+ /**
+ * * `gemini-3-flash` - Gemini 3 Flash
+ * `gemini-3-flash-lite` - Gemini 3 Flash Lite
+ */
+ export type LensModelEnum = typeof LensModelEnum[keyof typeof LensModelEnum];
+
+
+ export const LensModelEnum = {
+ Gemini3Flash: 'gemini-3-flash',
+ Gemini3FlashLite: 'gemini-3-flash-lite',
+ } as const;
+
+ /**
+ * * `google` - Google
+ */
+ export type LensProviderEnum = typeof LensProviderEnum[keyof typeof LensProviderEnum];
+
+
+ export const LensProviderEnum = {
+ Google: 'google',
+ } as const;
+
+ /**
+ * * `monitor` - Monitor
+ * `classifier` - Classifier
+ * `scorer` - Scorer
+ * `summarizer` - Summarizer
+ * `indexer` - Indexer
+ */
+ export type LensTypeEnum = typeof LensTypeEnum[keyof typeof LensTypeEnum];
+
+
+ export const LensTypeEnum = {
+ Monitor: 'monitor',
+ Classifier: 'classifier',
+ Scorer: 'scorer',
+ Summarizer: 'summarizer',
+ Indexer: 'indexer',
+ } as const;
+
export type LimitContext = typeof LimitContext[keyof typeof LimitContext];
@@ -20080,6 +20120,34 @@ export namespace Schemas {
event_definition_id?: string | null;
}
+ /**
+ * * `pending` - Pending
+ * `running` - Running
+ * `succeeded` - Succeeded
+ * `failed` - Failed
+ */
+ export type ObservationStatusEnum = typeof ObservationStatusEnum[keyof typeof ObservationStatusEnum];
+
+
+ export const ObservationStatusEnum = {
+ Pending: 'pending',
+ Running: 'running',
+ Succeeded: 'succeeded',
+ Failed: 'failed',
+ } as const;
+
+ /**
+ * * `schedule` - Schedule
+ * `on_demand` - On demand
+ */
+ export type ObservationTriggerEnum = typeof ObservationTriggerEnum[keyof typeof ObservationTriggerEnum];
+
+
+ export const ObservationTriggerEnum = {
+ Schedule: 'schedule',
+ OnDemand: 'on_demand',
+ } as const;
+
export interface OfflineExperimentItemsRequest {
/** `$ai_experiment_id` whose offline-evaluation items to return. */
experiment_id: string;
@@ -21683,6 +21751,113 @@ export namespace Schemas {
results: QuickFilter[];
}
+ export interface ReplayLens {
+ readonly id: string;
+ /**
+ * Human-readable lens name. Unique within the team.
+ * @maxLength 255
+ */
+ name: string;
+ /** Free-form description shown in the lens management UI. */
+ description?: string;
+ /** What the lens does: monitor, classifier, scorer, summarizer, or indexer.
+
+ * `monitor` - Monitor
+ * `classifier` - Classifier
+ * `scorer` - Scorer
+ * `summarizer` - Summarizer
+ * `indexer` - Indexer */
+ lens_type: LensTypeEnum;
+ /** Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc. */
+ lens_config: unknown;
+ /** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
+ query?: unknown;
+ /**
+ * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).
+ * @minimum 0
+ * @maximum 1
+ */
+ sampling_rate?: number;
+ /** LLM provider. v1 is Google-only.
+
+ * `google` - Google */
+ provider?: LensProviderEnum;
+ /** Concrete model to use for this lens.
+
+ * `gemini-3-flash` - Gemini 3 Flash
+ * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ model: LensModelEnum;
+ /** When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work. */
+ enabled?: boolean;
+ /** When true, the prompt is augmented with the Signal side mission and the lens emits PostHog Signals. */
+ emits_signals?: boolean;
+ /** Increments on every config-changing save. Observations snapshot this value. */
+ readonly lens_version: number;
+ /** Watermark for the lens's last scheduled fire. Mirrors Temporal schedule state for recovery. */
+ readonly last_swept_at: string;
+ readonly created_at: string;
+ /** User who created the lens. */
+ readonly created_by: UserBasic | null;
+ readonly updated_at: string;
+ }
+
+ export interface PaginatedReplayLensList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: ReplayLens[];
+ }
+
+ export interface ReplayObservation {
+ readonly id: string;
+ /** The lens that produced this observation. */
+ readonly lens_id: string;
+ /** Session recording id this lens was applied to. */
+ readonly session_id: string;
+ /** Observation status (pending, running, succeeded, failed).
+
+ * `pending` - Pending
+ * `running` - Running
+ * `succeeded` - Succeeded
+ * `failed` - Failed */
+ readonly status: ObservationStatusEnum;
+ /** Populated on failure. Includes the malformed model response when validation fails. */
+ readonly error_reason: string;
+ /** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
+ readonly workflow_id: string;
+ /** The `ReplayLens.lens_version` value at the moment the workflow ran. */
+ readonly lens_version: number;
+ /** Snapshot of `ReplayLens.lens_config` at run time. Lens edits do not retroactively mutate observations. */
+ readonly lens_config_snapshot: unknown;
+ /** Concrete model that ran the observation. */
+ readonly model_used: string;
+ /** Concrete provider that ran the observation. */
+ readonly provider_used: string;
+ /** Whether this observation came from the schedule or an on-demand request.
+
+ * `schedule` - Schedule
+ * `on_demand` - On demand */
+ readonly triggered_by: ObservationTriggerEnum;
+ /** User who triggered an on-demand observation. Null for scheduled observations. */
+ readonly triggered_by_user: UserBasic | null;
+ /** @nullable */
+ started_at?: string | null;
+ /** @nullable */
+ completed_at?: string | null;
+ readonly created_at: string;
+ }
+
+ export interface PaginatedReplayObservationList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: ReplayObservation[];
+ }
+
export type RepoBaselineFilePaths = {[key: string]: string};
export interface Repo {
@@ -27645,6 +27820,56 @@ export namespace Schemas {
person_id?: string;
}
+ export interface PatchedReplayLens {
+ readonly id?: string;
+ /**
+ * Human-readable lens name. Unique within the team.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Free-form description shown in the lens management UI. */
+ description?: string;
+ /** What the lens does: monitor, classifier, scorer, summarizer, or indexer.
+
+ * `monitor` - Monitor
+ * `classifier` - Classifier
+ * `scorer` - Scorer
+ * `summarizer` - Summarizer
+ * `indexer` - Indexer */
+ lens_type?: LensTypeEnum;
+ /** Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc. */
+ lens_config?: unknown;
+ /** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
+ query?: unknown;
+ /**
+ * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).
+ * @minimum 0
+ * @maximum 1
+ */
+ sampling_rate?: number;
+ /** LLM provider. v1 is Google-only.
+
+ * `google` - Google */
+ provider?: LensProviderEnum;
+ /** Concrete model to use for this lens.
+
+ * `gemini-3-flash` - Gemini 3 Flash
+ * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ model?: LensModelEnum;
+ /** When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work. */
+ enabled?: boolean;
+ /** When true, the prompt is augmented with the Signal side mission and the lens emits PostHog Signals. */
+ emits_signals?: boolean;
+ /** Increments on every config-changing save. Observations snapshot this value. */
+ readonly lens_version?: number;
+ /** Watermark for the lens's last scheduled fire. Mirrors Temporal schedule state for recovery. */
+ readonly last_swept_at?: string;
+ readonly created_at?: string;
+ /** User who created the lens. */
+ readonly created_by?: UserBasic | null;
+ readonly updated_at?: string;
+ }
+
export interface PatchedReviewQueueItemUpdate {
/** Review queue ID that should own this pending trace. */
queue_id?: string;
@@ -38516,6 +38741,121 @@ export namespace Schemas {
offset?: number;
};
+ export type VisionLensesListParams = {
+ /**
+ * Filter to lenses that emit Signals.
+ */
+ emits_signals?: boolean;
+ /**
+ * Filter to enabled vs disabled lenses.
+ */
+ enabled?: boolean;
+ /**
+ * Filter by lens type (monitor, classifier, scorer, summarizer, indexer).
+
+ * `monitor` - Monitor
+ * `classifier` - Classifier
+ * `scorer` - Scorer
+ * `summarizer` - Summarizer
+ * `indexer` - Indexer
+ */
+ lens_type?: VisionLensesListLensType;
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Sort lenses by name, created_at, updated_at, or lens_type. Prefix with `-` for descending.
+
+ * `name` - Name
+ * `-name` - Name (descending)
+ * `created_at` - Created at
+ * `-created_at` - Created at (descending)
+ * `updated_at` - Updated at
+ * `-updated_at` - Updated at (descending)
+ * `lens_type` - Lens type
+ * `-lens_type` - Lens type (descending)
+ */
+ order_by?: string[];
+ };
+
+ export type VisionLensesListLensType = typeof VisionLensesListLensType[keyof typeof VisionLensesListLensType];
+
+
+ export const VisionLensesListLensType = {
+ Classifier: 'classifier',
+ Indexer: 'indexer',
+ Monitor: 'monitor',
+ Scorer: 'scorer',
+ Summarizer: 'summarizer',
+ } as const;
+
+ export type VisionLensesObservationsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Sort observations by created_at, started_at, completed_at, or status. Prefix with `-` for descending.
+
+ * `created_at` - Created at
+ * `-created_at` - Created at (descending)
+ * `started_at` - Started at
+ * `-started_at` - Started at (descending)
+ * `completed_at` - Completed at
+ * `-completed_at` - Completed at (descending)
+ * `status` - Status
+ * `-status` - Status (descending)
+ */
+ order_by?: string[];
+ /**
+ * Filter to observations of a specific session recording.
+ */
+ session_id?: string;
+ /**
+ * Filter by observation status.
+
+ * `pending` - Pending
+ * `running` - Running
+ * `succeeded` - Succeeded
+ * `failed` - Failed
+ */
+ status?: VisionLensesObservationsListStatus;
+ /**
+ * Filter by trigger source (schedule or on_demand).
+
+ * `schedule` - Schedule
+ * `on_demand` - On demand
+ */
+ triggered_by?: VisionLensesObservationsListTriggeredBy;
+ };
+
+ export type VisionLensesObservationsListStatus = typeof VisionLensesObservationsListStatus[keyof typeof VisionLensesObservationsListStatus];
+
+
+ export const VisionLensesObservationsListStatus = {
+ Failed: 'failed',
+ Pending: 'pending',
+ Running: 'running',
+ Succeeded: 'succeeded',
+ } as const;
+
+ export type VisionLensesObservationsListTriggeredBy = typeof VisionLensesObservationsListTriggeredBy[keyof typeof VisionLensesObservationsListTriggeredBy];
+
+
+ export const VisionLensesObservationsListTriggeredBy = {
+ OnDemand: 'on_demand',
+ Schedule: 'schedule',
+ } as const;
+
export type WarehouseSavedQueryDraftsListParams = {
/**
* Number of results to return per page.