: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): add scan requests for programmatic callers (#113767)
Tue Haulundf1f9879530e0
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex ec63a2b59461..52a7f6cdad1d 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -338,6 +338,7 @@ rules:|ReplayObservation|ReplayObservationLabel|ReplayObservationMedia+ |ReplayObservationRequest|ReplayObservationUsage|ReplayObservationView|ReplayScanner@@ -788,6 +789,7 @@ rules:|ReplayObservation|ReplayObservationLabel|ReplayObservationMedia+ |ReplayObservationRequest|ReplayObservationUsage|ReplayObservationView|ReplayScannerdiff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex b797a95cc5e7..268ec41065ba 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -376,6 +376,8 @@ export const PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION = ['loop:write','experiment:read','offline_evaluation_ingestion:write',+ 'replay_scanner:write',+ 'session_recording:read',] as constexport type ProjectSecretAPIKeyAllowedScope = (typeof PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION)[number]diff --git a/posthog/scopes.py b/posthog/scopes.pyindex c710b509d4f0..1bc155c0d70d 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -269,6 +269,10 @@ PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIS# experiments into a warehouse don't need a credential tied to one person's account.("experiment", "read"),("offline_evaluation_ingestion", "write"),+ # Lets a service start Replay Vision scans and read their results back through `vision/requests/`.+ # Both are needed together; every other replay_scanner and session_recording route stays PSAK-denied.+ ("replay_scanner", "write"),+ ("session_recording", "read"),]# Server-side scope assignment string-set constants (see RFC: server-side scopediff --git a/products/replay_vision/README.md b/products/replay_vision/README.mdindex 3d19528b647d..c32ec04683bd 100644--- a/products/replay_vision/README.md+++ b/products/replay_vision/README.md@@ -61,7 +61,7 @@ The template lives in `frontend/src/scenes/experiments/replayVisionScanner.ts` a## Layout-- `backend/models/` — `ReplayScanner`, `ReplayObservation`, `ReplayScannerBackfill`, observation labels (ratings), usage receipts, and `TeamReplayVisionConfig` (the team's cross-scanner search suggestions).+- `backend/models/` — `ReplayScanner`, `ReplayObservation`, `ReplayScannerBackfill`, `ReplayObservationRequest` (one handle over a programmatic batch of scans, served at `vision/requests/` and open to project secret API keys), observation labels (ratings), usage receipts, and `TeamReplayVisionConfig` (the team's cross-scanner search suggestions).- `backend/api/` — DRF viewsets and serializers (scanners, observations, backfills, quota, stats, live progress over SSE).- `backend/queries/` — ClickHouse candidate selection (watermark + settle window + eligibility + sampling), the backfill's bounded descending walk and its exact count, and volume estimates.- `backend/temporal/` — the apply workflow and its activities, per-scanner sweep, per-backfill tick, schedule reconciler (+ observation and backfill-schedule reapers), estimate refresher, vision alerts, and the Gemini file cleanup sweep.diff --git a/products/replay_vision/backend/api/__init__.py b/products/replay_vision/backend/api/__init__.pyindex 09ae3fa0c507..a072bac4a209 100644--- a/products/replay_vision/backend/api/__init__.py+++ b/products/replay_vision/backend/api/__init__.py@@ -1,4 +1,5 @@from products.replay_vision.backend.api.backfills import ReplayScannerBackfillViewSet+from products.replay_vision.backend.api.observation_requests import ObservationRequestViewSetfrom products.replay_vision.backend.api.observations import ReplayObservationViewSet, SessionReplayObservationViewSetfrom products.replay_vision.backend.api.quota import VisionQuotaViewSetfrom products.replay_vision.backend.api.scanner_scouts import ScannerScoutViewSet@@ -8,6 +9,7 @@ from products.replay_vision.backend.api.variants import ReplayScannerVariantsViefrom products.replay_vision.backend.api.vision_alerts import VisionAlertViewSet__all__ = [+ "ObservationRequestViewSet","ReplayObservationViewSet","ReplayScannerBackfillViewSet","ReplayScannerViewSet",diff --git a/products/replay_vision/backend/api/observation_requests.py b/products/replay_vision/backend/api/observation_requests.pynew file mode 100644index 000000000000..cc4d53e5a6e0--- /dev/null+++ b/products/replay_vision/backend/api/observation_requests.py@@ -0,0 +1,380 @@+"""API for programmatic scan requests: start scans for named sessions and read them back as one handle."""++from typing import Any, cast++from django.db import models+from django.db.models import Q, QuerySet++import structlog+import posthoganalytics+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field+from pydantic import ValidationError as PydanticValidationError+from rest_framework import mixins, serializers, status, viewsets+from rest_framework.exceptions import PermissionDenied, ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.auth import ProjectSecretAPIKeyAuthentication+from posthog.models.user import User+from posthog.permissions import is_authenticated_via_project_secret_api_key, is_scout_sandbox_request+from posthog.rate_limit import PersonalOrProjectSecretApiKeyRateThrottle, ProjectSecretApiKeyTeamRateThrottle++from products.replay_vision.backend.api.errors import ReplayVisionErrorSerializer+from products.replay_vision.backend.api.observations import ScannerResultSerializer+from products.replay_vision.backend.api.scanners import BulkObserveResultSerializer, InlineScanConfigSerializer+from products.replay_vision.backend.consent import AI_CONSENT_REQUIRED_CODE, is_ai_data_processing_approved+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation+from products.replay_vision.backend.models.replay_observation_request import (+ ObservationRequestSource,+ ReplayObservationRequest,+)+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType+from products.replay_vision.backend.observation_requests import (+ IdempotencyKeyConflict,+ InlineScanSpec,+ RequestProgress,+ RequestSession,+ RequestSessionState,+ create_observation_request,+ request_progress,+)+from products.replay_vision.backend.scanner_access import (+ accessible_observations,+ can_read_targeted_experiment,+ readable_observation_scanner_ids,+)+from products.replay_vision.backend.scanning import MAX_SESSIONS_PER_SCAN+from products.replay_vision.backend.scout_writes import refuse_scout_scanner_scan+from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTH+from products.replay_vision.backend.temporal.types import ScannerResult++logger = structlog.get_logger(__name__)+++class ObservationRequestStatus(models.TextChoices):+ RUNNING = "running", "Running"+ COMPLETED = "completed", "Completed"+++class CreateObservationRequestSerializer(serializers.Serializer):+ """Body of POST /vision/requests/ - the sessions plus a saved scanner or an inline question."""++ session_ids = serializers.ListField(+ child=serializers.CharField(max_length=MAX_SESSION_ID_LENGTH),+ allow_empty=False,+ max_length=MAX_SESSIONS_PER_SCAN,+ help_text=(+ f"Session recording IDs to scan, at most {MAX_SESSIONS_PER_SCAN} per request. Scans start until the "+ "in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than "+ "failing the whole request. Duplicates are dropped."+ ),+ )+ scanner_id = serializers.UUIDField(+ required=False,+ help_text="A saved scanner to apply to the sessions. Pass this or `inline`, not both.",+ )+ inline = InlineScanConfigSerializer(+ required=False,+ help_text=(+ "A question to ask without saving a scanner first. Asking the same question again reuses the "+ "answers already given for the same sessions. Pass this or `scanner_id`, not both."+ ),+ )+ idempotency_key = serializers.CharField(+ required=False,+ max_length=200,+ help_text=(+ "Any unique string per logical request, such as a UUID. Sending the same key again returns the "+ "first request instead of starting new scans, so a retry after a timeout never charges twice."+ ),+ )+ reference = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ max_length=200,+ help_text="Your own id for this request, such as a ticket or job id. Returned unchanged.",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ if ("scanner_id" in attrs) == ("inline" in attrs):+ raise ValidationError("Pass either `scanner_id` or `inline`.")+ attrs["session_ids"] = list(dict.fromkeys(attrs["session_ids"]))+ return attrs+++class ObservationRequestSessionSerializer(BulkObserveResultSerializer):+ """One session of a request: how it started and where it stands now."""++ state = serializers.ChoiceField(+ choices=RequestSessionState.choices,+ help_text=(+ "Where the session stands now. 'pending' and 'running' are still in progress; 'succeeded' has a "+ "result; 'failed' and 'ineligible' finished without one; 'skipped' never started because a limit "+ "was reached (`scan_outcome` names which); 'lost' started but produced nothing before the scan "+ "timed out."+ ),+ )+ observation_id = serializers.SerializerMethodField(+ help_text="The observation for this session, once one exists. Null before that."+ )+ scanner_result = serializers.SerializerMethodField(+ help_text="The scanner's answer for this session. Null until the session succeeds."+ )++ @extend_schema_field(serializers.UUIDField(allow_null=True))+ def get_observation_id(self, session: RequestSession) -> str | None:+ return str(session.observation.id) if session.observation is not None else None++ @extend_schema_field(ScannerResultSerializer(allow_null=True))+ def get_scanner_result(self, session: RequestSession) -> dict | None:+ observation = session.observation+ if observation is None or observation.status != ObservationStatus.SUCCEEDED or not observation.scanner_result:+ return None+ try:+ return ScannerResult.model_validate(observation.scanner_result).model_dump(mode="json")+ except PydanticValidationError:+ logger.exception(+ "replay_vision.observation_request.malformed_scanner_result", observation_id=str(observation.id)+ )+ return None+++class ObservationRequestSerializer(serializers.Serializer):+ """A scan request and the current state of each of its sessions."""++ id = serializers.UUIDField(help_text="Request ID. Poll `GET /vision/requests/{id}/` with it.")+ status = serializers.ChoiceField(+ choices=ObservationRequestStatus.choices,+ help_text="'completed' once every session has settled, whether or not it produced a result.",+ )+ scanner_id = serializers.UUIDField(+ allow_null=True,+ help_text=(+ "The scanner the sessions were scanned with. For an inline question this is a hidden scanner, "+ "shared by every request that asks the same question. Null when nothing could start."+ ),+ )+ reference = serializers.CharField(help_text="The `reference` sent with the request.")+ created_at = serializers.DateTimeField(help_text="When the request was made.")+ sessions = ObservationRequestSessionSerializer(many=True, help_text="One entry per session, in request order.")+++def _distinct_id(request: Request) -> str:+ # Both a real user and the synthetic user a project secret API key authenticates as carry one.+ return str(getattr(request.user, "distinct_id", ""))+++class ObservationRequestBurstThrottle(PersonalOrProjectSecretApiKeyRateThrottle):+ scope = "replay_vision_observation_request_burst"+ rate = "60/minute"+++class ObservationRequestSustainedThrottle(PersonalOrProjectSecretApiKeyRateThrottle):+ scope = "replay_vision_observation_request_sustained"+ rate = "1000/hour"+++class ObservationRequestPSAKTeamBurstThrottle(ProjectSecretApiKeyTeamRateThrottle):+ scope = "replay_vision_observation_request_psak_team_burst"+ rate = "60/minute"+++class ObservationRequestPSAKTeamSustainedThrottle(ProjectSecretApiKeyTeamRateThrottle):+ scope = "replay_vision_observation_request_psak_team_sustained"+ rate = "1000/hour"+++class ObservationRequestViewSet(TeamAndOrgViewSetMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):+ """Start scans for named sessions from code, and read their results back through one request id."""++ scope_object = "replay_scanner"+ # Reading a request returns what the scanner saw in each recording, so every action needs both scopes.+ required_scopes = ["replay_scanner:write", "session_recording:read"]+ authentication_classes = [ProjectSecretAPIKeyAuthentication]+ psak_allowed_actions = ["create", "retrieve"]+ serializer_class = ObservationRequestSerializer+ # `objects` is fail-closed; `safely_get_queryset` re-scopes to the request team.+ queryset = ReplayObservationRequest.objects.unscoped()+ http_method_names = ["get", "post", "head", "options"]++ def get_throttles(self) -> list:+ if self.action == "create":+ return [+ ObservationRequestBurstThrottle(),+ ObservationRequestSustainedThrottle(),+ ObservationRequestPSAKTeamBurstThrottle(),+ ObservationRequestPSAKTeamSustainedThrottle(),+ ]+ return super().get_throttles()++ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:+ super().initial(request, *args, **kwargs)+ # Requests are stored under the project's main environment while scanners and observations stay per+ # environment, so a child environment could reach its siblings' requests and results.+ if self.team.parent_team_id is not None:+ raise ValidationError("Scan requests are only available in the project's main environment.")+ if self.action == "create":+ refuse_scout_scanner_scan(is_scout_sandbox_request(request))+ if not self._is_service_call and not self.user_access_control.check_access_level_for_resource(+ "session_recording", required_level="viewer"+ ):+ raise PermissionDenied("Scan requests return recording contents, so they need session recording access.")++ @property+ def _is_service_call(self) -> bool:+ # A project secret API key is project-wide by design, so it skips object-level access checks.+ return is_authenticated_via_project_secret_api_key(self.request)++ def safely_get_queryset(self, queryset: QuerySet[ReplayObservationRequest]) -> QuerySet[ReplayObservationRequest]:+ queryset = queryset.filter(team_id=self.team_id).select_related("scanner").order_by("-created_at")+ if self._is_service_call:+ return queryset+ readable = readable_observation_scanner_ids(self.user_access_control, self.team_id)+ return queryset.filter(Q(scanner_id__in=readable) | Q(scanner__isnull=True))++ def _render(self, request: ReplayObservationRequest) -> dict[str, Any]:+ progress = request_progress(request)+ if self._is_service_call:+ sessions = progress.sessions+ completed = request.completed_at is not None or progress.settled+ else:+ # Judged on the visible rows alone: a hidden row still in flight would otherwise show through `status`.+ sessions = self._readable_sessions(progress.sessions)+ completed = RequestProgress(sessions=sessions).settled+ return ObservationRequestSerializer(+ {+ "id": request.id,+ "status": ObservationRequestStatus.COMPLETED if completed else ObservationRequestStatus.RUNNING,+ "scanner_id": request.scanner_id,+ "reference": request.reference,+ "created_at": request.created_at,+ "sessions": sessions,+ }+ ).data++ def _readable_sessions(self, sessions: list[RequestSession]) -> list[RequestSession]:+ # A row authorizes against the experiment in its own snapshot, like every other observation read. A denied+ # row is dropped, not blanked, since its state alone says the session was scanned and how it went.+ ids = [s.observation.id for s in sessions if s.observation is not None]+ readable = set(+ accessible_observations(+ self.user_access_control,+ self.team_id,+ ReplayObservation.objects.filter(team_id=self.team_id, id__in=ids),+ ).values_list("id", flat=True)+ )+ return [s for s in sessions if s.observation is None or s.observation.id in readable]++ @extend_schema(responses={200: ObservationRequestSerializer})+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return Response(self._render(self.get_object()))++ @extend_schema(+ request=CreateObservationRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=ObservationRequestSerializer,+ description="A request with this `idempotency_key` already exists. Nothing new was started.",+ ),+ 202: ObservationRequestSerializer,+ 409: OpenApiResponse(+ response=ReplayVisionErrorSerializer,+ description="This `idempotency_key` already names a request made by another caller.",+ ),+ },+ )+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Scan sessions with a saved scanner or an inline question. Poll the returned request for results."""+ if not is_ai_data_processing_approved(self.team.id):+ raise ValidationError(+ "Your organization needs to allow AI analysis before you run a Replay Vision scan.",+ code=AI_CONSENT_REQUIRED_CODE,+ )+ body = CreateObservationRequestSerializer(data=request.data)+ body.is_valid(raise_exception=True)+ data = body.validated_data++ scanner: ReplayScanner | None = None+ inline: InlineScanSpec | None = None+ if "scanner_id" in data:+ scanner = ReplayScanner.objects.filter(team_id=self.team_id, id=data["scanner_id"]).first()+ if scanner is None:+ raise ValidationError({"scanner_id": "No scanner with this id exists in this project."})+ self._check_can_scan_with(scanner)+ else:+ if not self._is_service_call and not self.user_access_control.check_access_level_for_resource(+ "replay_scanner", required_level="editor"+ ):+ raise PermissionDenied("Asking an inline question requires edit access to the project's scanners.")+ spec = data["inline"]+ inline = InlineScanSpec(+ scanner_type=ScannerType(spec["scanner_type"]),+ scanner_config=spec["scanner_config"],+ model=spec["model"],+ )++ user = None if self._is_service_call else cast(User, request.user)+ try:+ observation_request, created = create_observation_request(+ team=self.team,+ user=user,+ source=ObservationRequestSource.PROJECT_SECRET_API_KEY+ if self._is_service_call+ else ObservationRequestSource.USER,+ session_ids=data["session_ids"],+ scanner=scanner,+ inline=inline,+ idempotency_key=data.get("idempotency_key"),+ reference=data["reference"],+ )+ except IdempotencyKeyConflict:+ return Response(+ ReplayVisionErrorSerializer(+ {"detail": "This idempotency_key is already used by another caller. Send a new one."}+ ).data,+ status=status.HTTP_409_CONFLICT,+ )+ if not created and not self._is_service_call and not self._can_read(observation_request):+ # The key is the caller's, but their access may have narrowed since they made the request.+ return Response(+ ReplayVisionErrorSerializer({"detail": "You can no longer read the request this key names."}).data,+ status=status.HTTP_409_CONFLICT,+ )+ if created:+ self._capture_created(request, observation_request, kind="scanner" if scanner is not None else "inline")+ return Response(+ self._render(observation_request), status=status.HTTP_202_ACCEPTED if created else status.HTTP_200_OK+ )++ def _can_read(self, observation_request: ReplayObservationRequest) -> bool:+ return (+ self.safely_get_queryset(ReplayObservationRequest.objects.unscoped())+ .filter(id=observation_request.id)+ .exists()+ )++ def _check_can_scan_with(self, scanner: ReplayScanner) -> None:+ if self._is_service_call:+ return+ if not self.user_access_control.check_access_level_for_object(scanner, "editor"):+ raise PermissionDenied("Scanning with this scanner requires edit access to it.")+ if not can_read_targeted_experiment(self.user_access_control, self.team_id, scanner):+ raise PermissionDenied("Scanning with this scanner requires access to its experiment.")++ def _capture_created(self, request: Request, observation_request: ReplayObservationRequest, *, kind: str) -> None:+ # report_user_action drops synthetic users, so capture directly to count both auth paths alike.+ outcomes = [o["scan_outcome"] for o in observation_request.start_outcomes]+ posthoganalytics.capture(+ distinct_id=_distinct_id(request),+ event="replay_vision_observation_request_created",+ properties={+ "auth_method": observation_request.source,+ "kind": kind,+ "requested": len(observation_request.session_ids),+ "started": outcomes.count("started"),+ "has_idempotency_key": observation_request.idempotency_key is not None,+ },+ groups={"organization": str(self.team.organization_id), "project": str(self.team.uuid)},+ )diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 3890a113818a..adbd24c636f1 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1366,19 +1366,9 @@ class BulkObserveResponseSerializer(serializers.Serializer):)-class InlineScanRequestSerializer(serializers.Serializer):- """Body of POST /vision/scanners/inline_scan/ - a prompt plus the sessions to point it at."""+class InlineScanConfigSerializer(serializers.Serializer):+ """A question asked inline, without saving a scanner first."""- session_ids = serializers.ListField(- child=serializers.CharField(max_length=MAX_SESSION_ID_LENGTH),- allow_empty=False,- max_length=MAX_SESSIONS_PER_SCAN,- help_text=(- f"Session recording IDs to scan, at most {MAX_SESSIONS_PER_SCAN} per request. Scans start "- "until the in-flight limit or monthly credit quota is reached; the rest are reported as "- "skipped rather than failing the whole batch."- ),- )prompt = serializers.CharField(max_length=MAX_PROMPT_LENGTH,help_text="What to look for in these sessions, in plain language. The same instruction a saved scanner carries.",@@ -1432,6 +1422,21 @@ class InlineScanRequestSerializer(serializers.Serializer):return attrs+class InlineScanRequestSerializer(InlineScanConfigSerializer):+ """Body of POST /vision/scanners/inline_scan/ - a prompt plus the sessions to point it at."""++ session_ids = serializers.ListField(+ child=serializers.CharField(max_length=MAX_SESSION_ID_LENGTH),+ allow_empty=False,+ max_length=MAX_SESSIONS_PER_SCAN,+ help_text=(+ f"Session recording IDs to scan, at most {MAX_SESSIONS_PER_SCAN} per request. Scans start "+ "until the in-flight limit or monthly credit quota is reached; the rest are reported as "+ "skipped rather than failing the whole batch."+ ),+ )++class InlineScanResponseSerializer(BulkObserveResponseSerializer):"""`bulk_observe`'s partial-success shape plus the id to read the results back through."""diff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.pyindex a3c3c6e0fb33..6f0b1093301f 100644--- a/products/replay_vision/backend/api/trigger.py+++ b/products/replay_vision/backend/api/trigger.py@@ -151,7 +151,7 @@ def start_apply_scanner_workflow(scanner: ReplayScanner,session_id: str,*,- triggered_by_user_id: int,+ triggered_by_user_id: int | None,trigger: ObservationTrigger,team_in_flight_rows: int | None = None,scanner_in_flight_rows: int | None = None,diff --git a/products/replay_vision/backend/migrations/0119_replayobservationrequest.py b/products/replay_vision/backend/migrations/0119_replayobservationrequest.pynew file mode 100644index 000000000000..1e8ba603cc20--- /dev/null+++ b/products/replay_vision/backend/migrations/0119_replayobservationrequest.py@@ -0,0 +1,119 @@+# Generated by Django 5.2.18 on 2026-10-08 09:17++import django.db.models.deletion+import django.contrib.postgres.fields+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1394_backfill_secret_tokens_to_psak"),+ ("replay_vision", "0118_drop_replayobservationmedia_clip_columns"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="ReplayObservationRequest",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "session_ids",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=200),+ help_text="Session recording ids, in request order.",+ size=None,+ ),+ ),+ (+ "start_outcomes",+ models.JSONField(+ help_text="Per-session `{session_id, scan_outcome}` from the moment the request started, in request order."+ ),+ ),+ (+ "idempotency_key",+ models.CharField(blank=True, max_length=200, null=True),+ ),+ (+ "reference",+ models.CharField(+ blank=True,+ default="",+ help_text="Caller-supplied correlation id, echoed back unchanged.",+ max_length=200,+ ),+ ),+ (+ "source",+ models.CharField(+ choices=[+ ("user", "User"),+ ("project_secret_api_key", "Project secret API key"),+ ],+ max_length=32,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("completed_at", models.DateTimeField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "scanner",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="replay_vision.replayscanner",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "indexes": [+ models.Index(fields=["team", "created_at"], name="rvor_team_created_idx"),+ models.Index(+ condition=models.Q(("completed_at__isnull", True)),+ fields=["created_at"],+ name="rvor_open_created_idx",+ ),+ ],+ "constraints": [+ models.UniqueConstraint(+ condition=models.Q(("idempotency_key__isnull", False)),+ fields=("team", "idempotency_key"),+ name="rvor_team_idempotency_key_unique",+ )+ ],+ },+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 19a8d6f6730f..a8e4e1fde979 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0118_drop_replayobservationmedia_clip_columns+0119_replayobservationrequestdiff --git a/products/replay_vision/backend/models/__init__.py b/products/replay_vision/backend/models/__init__.pyindex 384046d0f07f..361bec47e5ca 100644--- a/products/replay_vision/backend/models/__init__.py+++ b/products/replay_vision/backend/models/__init__.py@@ -1,6 +1,7 @@from products.replay_vision.backend.models.replay_observation import ReplayObservationfrom products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabelfrom products.replay_vision.backend.models.replay_observation_media import ReplayObservationMedia+from products.replay_vision.backend.models.replay_observation_request import ReplayObservationRequestfrom products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsagefrom products.replay_vision.backend.models.replay_observation_view import ReplayObservationViewfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner@@ -17,6 +18,7 @@ __all__ = ["ReplayObservation","ReplayObservationLabel","ReplayObservationMedia",+ "ReplayObservationRequest","ReplayObservationUsage","ReplayObservationView","ReplayScanner",diff --git a/products/replay_vision/backend/models/replay_observation_request.py b/products/replay_vision/backend/models/replay_observation_request.pynew file mode 100644index 000000000000..36a2cd8399e3--- /dev/null+++ b/products/replay_vision/backend/models/replay_observation_request.py@@ -0,0 +1,61 @@+from django.contrib.postgres.fields import ArrayField+from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel+++class ObservationRequestSource(models.TextChoices):+ USER = "user", "User"+ PROJECT_SECRET_API_KEY = "project_secret_api_key", "Project secret API key"+++class ReplayObservationRequest(TeamScopedRootMixin, UUIDModel):+ """One programmatic ask to scan named sessions, read back through one handle.++ The observations stay keyed by (scanner, session), so a request holds no results of its own: it+ records which sessions it asked for and what happened when each one started.+ """++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ # SET_NULL because an inline scanner that started nothing is never minted, and one that ends up with no+ # observations is reaped; the request must outlive both so the caller still sees why nothing ran.+ scanner = models.ForeignKey(+ "replay_vision.ReplayScanner",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="+",+ )+ session_ids = ArrayField(models.CharField(max_length=200), help_text="Session recording ids, in request order.")+ start_outcomes = models.JSONField(+ help_text="Per-session `{session_id, scan_outcome}` from the moment the request started, in request order."+ )+ idempotency_key = models.CharField(max_length=200, null=True, blank=True)+ reference = models.CharField(+ max_length=200, blank=True, default="", help_text="Caller-supplied correlation id, echoed back unchanged."+ )+ source = models.CharField(max_length=32, choices=ObservationRequestSource.choices)+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ created_at = models.DateTimeField(auto_now_add=True)+ completed_at = models.DateTimeField(null=True, blank=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["team", "idempotency_key"],+ condition=models.Q(idempotency_key__isnull=False),+ name="rvor_team_idempotency_key_unique",+ ),+ ]+ indexes = [+ models.Index(fields=["team", "created_at"], name="rvor_team_created_idx"),+ models.Index(+ fields=["created_at"], name="rvor_open_created_idx", condition=models.Q(completed_at__isnull=True)+ ),+ ]++ def __str__(self) -> str:+ return f"{self.id} [{len(self.session_ids)} sessions]"diff --git a/products/replay_vision/backend/observation_requests.py b/products/replay_vision/backend/observation_requests.pynew file mode 100644index 000000000000..0cf733cc8e7b--- /dev/null+++ b/products/replay_vision/backend/observation_requests.py@@ -0,0 +1,220 @@+"""Programmatic scan requests: one handle over a batch of on-demand scans.++A request points either a saved scanner or an inline question at named sessions, through the same+`scanning` helpers the scanner endpoints use, so quota, caps and dedup behave exactly as they do there.+Nothing here checks consent or access; the caller does, as with `scanning`.+"""++from collections.abc import Sequence+from datetime import datetime, timedelta+from typing import Any++from django.db import IntegrityError, models, transaction+from django.db.models import Q+from django.utils import timezone++from posthog.dataclasses import frozen+from posthog.models.team import Team+from posthog.models.user import User++from products.replay_vision.backend.models.replay_observation import TERMINAL_STATUSES, ReplayObservation+from products.replay_vision.backend.models.replay_observation_request import (+ ObservationRequestSource,+ ReplayObservationRequest,+)+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType+from products.replay_vision.backend.scanning import run_inline_scan, scan_existing_scanner+from products.replay_vision.backend.temporal.constants import APPLY_SCANNER_EXECUTION_TIMEOUT++# Start outcomes that put a workflow behind the session, so an observation row is expected for it.+_OBSERVED_OUTCOMES = frozenset({"started", "already_running", "already_scanned"})+++class RequestSessionState(models.TextChoices):+ # Started, but its observation row isn't written yet.+ PENDING = "pending", "Pending"+ RUNNING = "running", "Running"+ SUCCEEDED = "succeeded", "Succeeded"+ FAILED = "failed", "Failed"+ INELIGIBLE = "ineligible", "Ineligible"+ # Never started because a limit was reached; see the session's `scan_outcome` for which one.+ SKIPPED = "skipped", "Skipped"+ # Started, but never settled before the scan workflow's own timeout ran out.+ LOST = "lost", "Lost"+++_UNSETTLED_STATES = frozenset({RequestSessionState.PENDING, RequestSessionState.RUNNING})++# Starting up to 200 scans takes seconds, so a request whose outcomes are still unwritten after this+# lost the process that was starting them.+_STARTUP_GRACE = timedelta(minutes=10)+++class IdempotencyKeyConflict(Exception):+ """The key already names a request someone else made, so it can't be handed back to this caller."""+++@frozen+class InlineScanSpec:+ scanner_type: ScannerType+ scanner_config: dict[str, Any]+ model: str+++@frozen+class RequestSession:+ session_id: str+ scan_outcome: str+ state: RequestSessionState+ observation: ReplayObservation | None+++@frozen+class RequestProgress:+ sessions: list[RequestSession]++ @property+ def settled(self) -> bool:+ return all(s.state not in _UNSETTLED_STATES for s in self.sessions)+++def create_observation_request(+ *,+ team: Team,+ user: User | None,+ source: ObservationRequestSource,+ session_ids: list[str],+ scanner: ReplayScanner | None,+ inline: InlineScanSpec | None,+ idempotency_key: str | None,+ reference: str,+) -> tuple[ReplayObservationRequest, bool]:+ """Start scans for the sessions and record them as one request. Returns (request, created).++ A repeated idempotency key returns the first request untouched, so a caller that retries after a+ timeout never pays twice. The row is inserted before any scan starts, which makes the unique index+ the arbiter between two concurrent calls with the same key. A key is only handed back to the same+ caller: another one gets `IdempotencyKeyConflict`, never a request it may not be allowed to read.+ """+ if (scanner is None) == (inline is None):+ raise ValueError("Pass exactly one of scanner or inline.")+ if idempotency_key:+ existing = ReplayObservationRequest.objects.for_team(team.id).filter(idempotency_key=idempotency_key).first()+ if existing is not None:+ return _same_caller(existing, team, source, user), False+ try:+ with transaction.atomic():+ request = ReplayObservationRequest.objects.for_team(team.id).create(+ team=team,+ scanner=scanner,+ session_ids=session_ids,+ start_outcomes=[],+ idempotency_key=idempotency_key or None,+ reference=reference,+ source=source,+ created_by=user,+ )+ except IntegrityError:+ if not idempotency_key:+ raise+ existing = ReplayObservationRequest.objects.for_team(team.id).get(idempotency_key=idempotency_key)+ return _same_caller(existing, team, source, user), False++ try:+ if scanner is not None:+ _, results = scan_existing_scanner(scanner=scanner, session_ids=session_ids, user=user)+ else:+ assert inline is not None+ scan = run_inline_scan(+ team=team,+ user=user,+ session_ids=session_ids,+ scanner_type=inline.scanner_type,+ scanner_config=inline.scanner_config,+ model=inline.model,+ )+ scanner, results = scan.scanner, scan.results+ except Exception:+ # Free the key so the caller's retry starts the scans instead of reading back an empty request.+ request.delete()+ raise++ request.scanner = scanner+ request.start_outcomes = results+ if not any(r["scan_outcome"] in _OBSERVED_OUTCOMES for r in results):+ request.completed_at = timezone.now()+ request.save(update_fields=["scanner", "start_outcomes", "completed_at"])+ return request, True+++def _same_caller(+ request: ReplayObservationRequest, team: Team, source: ObservationRequestSource, user: User | None+) -> ReplayObservationRequest:+ if request.source != source or request.created_by_id != (user.id if user is not None else None):+ raise IdempotencyKeyConflict()+ # Requests are stored under the project's canonical team, but scanners and observations stay per environment,+ # so a key from another environment of the same project must not read this environment's results.+ if request.scanner is not None and request.scanner.team_id != team.id:+ raise IdempotencyKeyConflict()+ return request+++def request_progress(request: ReplayObservationRequest, *, now: datetime | None = None) -> RequestProgress:+ """Where each of the request's sessions stands, read from the observations it started."""+ return request_progress_many([request], now=now)[request.id]+++def request_progress_many(+ requests: Sequence[ReplayObservationRequest], *, now: datetime | None = None+) -> dict[Any, RequestProgress]:+ """`request_progress` for many requests, keyed by request id, with one observation query in total."""+ now = now or timezone.now()+ wanted = Q()+ for request in requests:+ if request.scanner_id is not None and request.start_outcomes:+ wanted |= Q(team_id=request.team_id, scanner_id=request.scanner_id, session_id__in=request.session_ids)+ observations: dict[tuple[Any, str], ReplayObservation] = {}+ if wanted:+ observations = {(o.scanner_id, o.session_id): o for o in ReplayObservation.objects.filter(wanted)}+ return {request.id: _progress(request, observations, now) for request in requests}+++def _progress(+ request: ReplayObservationRequest, observations: dict[tuple[Any, str], ReplayObservation], now: datetime+) -> RequestProgress:+ age = now - request.created_at+ if not request.start_outcomes:+ # Still starting, or the process starting it died; either way nothing has run to read back.+ state = RequestSessionState.PENDING if age < _STARTUP_GRACE else RequestSessionState.FAILED+ return RequestProgress(+ sessions=[+ RequestSession(session_id=sid, scan_outcome="failed", state=state, observation=None)+ for sid in request.session_ids+ ]+ )+ # A scan that outlives its workflow's timeout is dead even if its row still says running, and the+ # orphan reaper only catches up later.+ expired = age > APPLY_SCANNER_EXECUTION_TIMEOUT+ return RequestProgress(+ sessions=[+ _session(outcome, observations.get((request.scanner_id, outcome["session_id"])), expired)+ for outcome in request.start_outcomes+ ]+ )+++def _session(outcome: dict[str, str], observation: ReplayObservation | None, expired: bool) -> RequestSession:+ scan_outcome = outcome["scan_outcome"]+ if scan_outcome not in _OBSERVED_OUTCOMES:+ state = RequestSessionState.FAILED if scan_outcome == "failed" else RequestSessionState.SKIPPED+ elif observation is not None and observation.status in TERMINAL_STATUSES:+ state = RequestSessionState(observation.status)+ elif expired:+ state = RequestSessionState.LOST+ elif observation is None:+ state = RequestSessionState.PENDING+ else:+ state = RequestSessionState.RUNNING+ return RequestSession(+ session_id=outcome["session_id"], scan_outcome=scan_outcome, state=state, observation=observation+ )diff --git a/products/replay_vision/backend/routes.py b/products/replay_vision/backend/routes.pyindex cab997202fd9..bf0544993121 100644--- a/products/replay_vision/backend/routes.py+++ b/products/replay_vision/backend/routes.py@@ -1,6 +1,7 @@from posthog.api.routing import RouterRegistryfrom products.replay_vision.backend.api import (+ ObservationRequestViewSet,ReplayObservationViewSet,ReplayScannerBackfillViewSet,ReplayScannerVariantsViewSet,@@ -41,5 +42,8 @@ def register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"vision/observations", SessionReplayObservationViewSet, "project_vision_observations", ["team_id"])+ routers.projects.register(+ r"vision/requests", ObservationRequestViewSet, "project_vision_observation_requests", ["team_id"]+ )routers.projects.register(r"vision/quota", VisionQuotaViewSet, "project_vision_quota", ["team_id"])routers.projects.register(r"vision/alerts", VisionAlertViewSet, "project_vision_alerts", ["team_id"])diff --git a/products/replay_vision/backend/scanning.py b/products/replay_vision/backend/scanning.pyindex fc2b3d7db2d5..f7e7d811c304 100644--- a/products/replay_vision/backend/scanning.py+++ b/products/replay_vision/backend/scanning.py@@ -161,7 +161,7 @@ def start_observations(*,scanner: ReplayScanner,session_ids: list[str],- user: User,+ user: User | None,headroom: ScanHeadroom,finished: frozenset[str],) -> tuple[int, list[dict[str, str]]]:@@ -196,7 +196,7 @@ def start_observations(_, outcome = start_apply_scanner_workflow(scanner,session_id,- triggered_by_user_id=user.id,+ triggered_by_user_id=user.id if user is not None else None,trigger=ObservationTrigger.ON_DEMAND,# Row counts are this request's snapshot; the atomic claim inside makes racing requests# visible to each other, which the snapshot alone cannot.@@ -224,7 +224,7 @@ def start_observations(def scan_existing_scanner(- *, scanner: ReplayScanner, session_ids: list[str], user: User+ *, scanner: ReplayScanner, session_ids: list[str], user: User | None) -> tuple[int, list[dict[str, str]]]:"""Point a saved scanner at named sessions."""return start_observations(@@ -239,7 +239,7 @@ def scan_existing_scanner(def run_inline_scan(*,team: Team,- user: User,+ user: User | None,session_ids: list[str],scanner_type: ScannerType,scanner_config: dict[str, Any],diff --git a/products/replay_vision/backend/tests/test_observation_requests_api.py b/products/replay_vision/backend/tests/test_observation_requests_api.pynew file mode 100644index 000000000000..c348fbb5bee3--- /dev/null+++ b/products/replay_vision/backend/tests/test_observation_requests_api.py@@ -0,0 +1,284 @@+from datetime import timedelta+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.utils import timezone++from parameterized import parameterized+from rest_framework.test import APIClient++from posthog.models import ProjectSecretAPIKey, Team+from posthog.models.personal_api_key import hash_key_value+from posthog.models.utils import generate_random_token_secret++from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)+from products.replay_vision.backend.models.replay_observation_request import ReplayObservationRequest+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.observation_requests import request_progress+from products.replay_vision.backend.temporal.constants import APPLY_SCANNER_EXECUTION_TIMEOUT+from products.replay_vision.backend.tests.helpers import create_experiment, snapshot_for+++class TestObservationRequestAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # Started in setUp, not as class decorators, so @parameterized cases keep their argument order.+ self.start_workflow = self._patch("products.replay_vision.backend.api.trigger.async_to_sync").return_value+ self._patch("products.replay_vision.backend.api.trigger.sync_connect")+ self._patch("products.replay_vision.backend.api.observation_requests.posthoganalytics")+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ self.scanner = ReplayScanner.objects.create(+ team=self.team,+ name="checkout",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user check out?"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )++ @property+ def url(self) -> str:+ return f"/api/projects/{self.team.id}/vision/requests/"++ def _psak_client(self, scopes: list[str], team: Team | None = None) -> APIClient:+ raw = generate_random_token_secret()+ ProjectSecretAPIKey.objects.create(+ team=team or self.team,+ label="ci",+ secure_value=hash_key_value(raw),+ mask_value=f"{raw[:4]}...{raw[-4:]}",+ scopes=scopes,+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw}")+ return client++ def _patch(self, target: str) -> MagicMock:+ patcher = patch(target)+ self.addCleanup(patcher.stop)+ return patcher.start()++ def test_project_secret_key_starts_scans_without_a_user(self) -> None:+ client = self._psak_client(["replay_scanner:write", "session_recording:read"])++ response = client.post(+ self.url,+ {"session_ids": ["s1", "s2", "s1"], "scanner_id": str(self.scanner.id), "reference": "job-7"},+ format="json",+ )++ self.assertEqual(response.status_code, 202, response.json())+ body = response.json()+ self.assertEqual(body["status"], "running")+ self.assertEqual(body["reference"], "job-7")+ self.assertEqual(+ [(s["session_id"], s["state"]) for s in body["sessions"]], [("s1", "pending"), ("s2", "pending")]+ )+ inputs = self.start_workflow.call_args.args[1]+ self.assertIsNone(inputs.triggered_by_user_id)+ self.assertEqual(+ ReplayObservationRequest.objects.for_team(self.team.id).get(id=body["id"]).source, "project_secret_api_key"+ )++ read = client.get(f"{self.url}{body['id']}/")+ self.assertEqual(read.status_code, 200, read.json())++ @parameterized.expand(+ [+ ("missing_session_recording_scope", ["replay_scanner:write"], None),+ ("key_from_another_project", ["replay_scanner:write", "session_recording:read"], "other"),+ ]+ )+ def test_project_secret_key_is_refused(self, _name: str, scopes: list[str], team: str | None) -> None:+ other = Team.objects.create(organization=self.organization) if team else None+ client = self._psak_client(scopes, team=other)++ response = client.post(self.url, {"session_ids": ["s1"], "scanner_id": str(self.scanner.id)}, format="json")++ self.assertEqual(response.status_code, 403, response.json())+ self.start_workflow.assert_not_called()++ def test_repeated_idempotency_key_returns_the_first_request_without_starting_scans(self) -> None:+ payload = {"session_ids": ["s1"], "scanner_id": str(self.scanner.id), "idempotency_key": "abc"}++ first = self.client.post(self.url, payload, format="json")+ starts = self.start_workflow.call_count+ second = self.client.post(self.url, {**payload, "session_ids": ["s9"]}, format="json")++ self.assertEqual((first.status_code, second.status_code), (202, 200), second.json())+ self.assertEqual(second.json()["id"], first.json()["id"])+ self.assertEqual(self.start_workflow.call_count, starts)++ # Another caller reusing the key must not read back a request it may not be allowed to see.+ other = self._psak_client(["replay_scanner:write", "session_recording:read"]).post(+ self.url, payload, format="json"+ )+ self.assertEqual(other.status_code, 409, other.json())+ self.assertEqual(self.start_workflow.call_count, starts)++ def test_reading_a_request_hides_rows_recorded_under_an_experiment_the_caller_cannot_view(self) -> None:+ experiment = create_experiment(self.team, "restricted-flag")+ self.scanner.experiment_targeting = {"experiment_id": experiment.id, "variant": "test"}+ self.scanner.save(update_fields=["experiment_targeting"])+ ReplayObservation.objects.create(+ scanner=self.scanner,+ team=self.team,+ session_id="s1",+ scanner_snapshot=snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.ON_DEMAND,+ status=ObservationStatus.RUNNING,+ )+ # Clearing the targeting lets the scanner pass its own gate; the row's snapshot must still block it.+ self.scanner.experiment_targeting = None+ self.scanner.save(update_fields=["experiment_targeting"])+ request = ReplayObservationRequest.objects.for_team(self.team.id).create(+ team=self.team,+ scanner=self.scanner,+ session_ids=["s1"],+ start_outcomes=[{"session_id": "s1", "scan_outcome": "already_scanned"}],+ source="user",+ created_by=self.user,+ )++ with patch(+ "products.access_control.backend.facade.user_access_control.UserAccessControl.filter_queryset_by_access_level",+ side_effect=lambda qs, **_: qs.exclude(pk=experiment.pk) if qs.model is type(experiment) else qs,+ ):+ response = self.client.get(f"{self.url}{request.id}/")++ self.assertEqual(response.status_code, 200, response.json())+ # Neither the row nor whether it is still running may show: `status` reads only the visible rows.+ self.assertEqual((response.json()["sessions"], response.json()["status"]), ([], "completed"))++ @parameterized.expand([("create", "post"), ("retrieve", "get")])+ def test_a_child_environment_cannot_use_scan_requests(self, _name: str, method: str) -> None:+ payload = {"session_ids": ["s1"], "inline": {"prompt": "anything"}, "idempotency_key": "shared"}+ scopes = ["replay_scanner:write", "session_recording:read"]+ parent = self._psak_client(scopes).post(self.url, payload, format="json")+ child = Team.objects.create(organization=self.organization, parent_team=self.team, name="child env")+ child_client = self._psak_client(scopes, team=child)+ child_url = f"/api/projects/{child.id}/vision/requests/"++ # Requests are stored under the main environment, so a child must not reach them by key or by id.+ response = (+ child_client.post(child_url, payload, format="json")+ if method == "post"+ else child_client.get(f"{child_url}{parent.json()['id']}/")+ )++ self.assertEqual((parent.status_code, response.status_code), (202, 400), response.json())++ def test_inline_question_mints_a_hidden_scanner_and_reports_its_id(self) -> None:++ response = self.client.post(+ self.url, {"session_ids": ["s1"], "inline": {"prompt": "did they rage click?"}}, format="json"+ )++ self.assertEqual(response.status_code, 202, response.json())+ scanner = ReplayScanner.all_origins.get(id=response.json()["scanner_id"])+ self.assertEqual(scanner.origin, "inline")++ @parameterized.expand(+ [+ ("no_ai_consent", {"consent": False}, 400),+ ("both_scanner_and_inline", {"inline": True}, 400),+ ]+ )+ def test_create_is_refused(self, _name: str, case: dict[str, Any], expected: int) -> None:+ if case.get("consent") is False:+ self.organization.is_ai_data_processing_approved = False+ self.organization.save()+ payload: dict[str, Any] = {"session_ids": ["s1"], "scanner_id": str(self.scanner.id)}+ if case.get("inline"):+ payload["inline"] = {"prompt": "x"}++ response = self.client.post(self.url, payload, format="json")++ self.assertEqual(response.status_code, expected, response.json())+ self.start_workflow.assert_not_called()+ self.assertFalse(ReplayObservationRequest.objects.for_team(self.team.id).exists())+++class TestRequestProgress(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.scanner = ReplayScanner.objects.create(+ team=self.team,+ name="checkout",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user check out?"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )++ def _observe(self, session_id: str, status: ObservationStatus) -> None:+ ReplayObservation.objects.create(+ scanner=self.scanner,+ team=self.team,+ session_id=session_id,+ scanner_snapshot=snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.ON_DEMAND,+ status=status,+ completed_at=timezone.now()+ if status not in (ObservationStatus.PENDING, ObservationStatus.RUNNING)+ else None,+ )++ @parameterized.expand(+ [+ ("still_running", ObservationStatus.RUNNING, timedelta(0), "running", False),+ ("succeeded", ObservationStatus.SUCCEEDED, timedelta(0), "succeeded", True),+ ("row_not_written_yet", None, timedelta(0), "pending", False),+ ("row_never_written", None, APPLY_SCANNER_EXECUTION_TIMEOUT + timedelta(minutes=1), "lost", True),+ (+ "row_stuck_running",+ ObservationStatus.RUNNING,+ APPLY_SCANNER_EXECUTION_TIMEOUT + timedelta(minutes=1),+ "lost",+ True,+ ),+ ]+ )+ def test_session_state_follows_its_observation(+ self, _name: str, status: ObservationStatus | None, age: timedelta, state: str, settled: bool+ ) -> None:+ if status is not None:+ self._observe("s1", status)+ request = ReplayObservationRequest.objects.for_team(self.team.id).create(+ team=self.team,+ scanner=self.scanner,+ session_ids=["s1", "s2"],+ start_outcomes=[+ {"session_id": "s1", "scan_outcome": "started"},+ {"session_id": "s2", "scan_outcome": "skipped_quota"},+ ],+ source="user",+ )++ progress = request_progress(request, now=request.created_at + age)++ self.assertEqual([s.state for s in progress.sessions], [state, "skipped"])+ self.assertEqual(progress.settled, settled)++ @parameterized.expand(+ [+ ("still_starting", timedelta(0), "pending", False),+ ("starter_died", timedelta(hours=1), "failed", True),+ ]+ )+ def test_a_request_whose_scans_are_still_starting_is_not_settled(+ self, _name: str, age: timedelta, state: str, settled: bool+ ) -> None:+ request = ReplayObservationRequest.objects.for_team(self.team.id).create(+ team=self.team, scanner=None, session_ids=["s1"], start_outcomes=[], source="user"+ )++ progress = request_progress(request, now=request.created_at + age)++ self.assertEqual([s.state for s in progress.sessions], [state])+ self.assertEqual(progress.settled, settled)diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 3457005dcece..633caf44b3c7 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -965,6 +965,185 @@ export interface VisionSpendSeriesApi {readonly days: readonly VisionSpendDayApi[]}+/**+ * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite+ * * `gemini-3-flash-preview` - Gemini 3 Flash+ * * `gemini-3.8-flash` - Gemini 3.8 Flash+ */+export type ScannerModelEnumApi = (typeof ScannerModelEnumApi)[keyof typeof ScannerModelEnumApi]++export const ScannerModelEnumApi = {+ Gemini35FlashLite: 'gemini-3.5-flash-lite',+ Gemini3FlashPreview: 'gemini-3-flash-preview',+ Gemini38Flash: 'gemini-3.8-flash',+} as const++/**+ * A question asked inline, without saving a scanner first.+ */+export interface InlineScanConfigApi {+ /**+ * What to look for in these sessions, in plain language. The same instruction a saved scanner carries.+ * @maxLength 20000+ */+ prompt: string+ /** What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.+ *+ * * `monitor` - Monitor+ * * `classifier` - Classifier+ * * `scorer` - Scorer+ * * `summarizer` - Summarizer+ * * `experiment` - Experiment */+ scanner_type?: ScannerTypeEnumApi+ /** Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here. */+ scanner_config?: unknown+ /** Model to scan with. Determines what each observation costs in credits.+ *+ * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite+ * * `gemini-3-flash-preview` - Gemini 3 Flash+ * * `gemini-3.8-flash` - Gemini 3.8 Flash */+ model?: ScannerModelEnumApi+}++/**+ * Body of POST /vision/requests/ - the sessions plus a saved scanner or an inline question.+ */+export interface CreateObservationRequestApi {+ /**+ * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole request. Duplicates are dropped.+ * @maxItems 200+ * @items.maxLength 128+ */+ session_ids: string[]+ /** A saved scanner to apply to the sessions. Pass this or `inline`, not both. */+ scanner_id?: string+ /** A question to ask without saving a scanner first. Asking the same question again reuses the answers already given for the same sessions. Pass this or `scanner_id`, not both. */+ inline?: InlineScanConfigApi+ /**+ * Any unique string per logical request, such as a UUID. Sending the same key again returns the first request instead of starting new scans, so a retry after a timeout never charges twice.+ * @maxLength 200+ */+ idempotency_key?: string+ /**+ * Your own id for this request, such as a ticket or job id. Returned unchanged.+ * @maxLength 200+ */+ reference?: string+}++/**+ * * `running` - Running+ * * `completed` - Completed+ */+export type ObservationRequestStatusEnumApi =+ (typeof ObservationRequestStatusEnumApi)[keyof typeof ObservationRequestStatusEnumApi]++export const ObservationRequestStatusEnumApi = {+ Running: 'running',+ Completed: 'completed',+} as const++/**+ * * `started` - Started+ * * `already_running` - Already running+ * * `already_scanned` - Already scanned+ * * `skipped_limit` - Skipped, in-flight limit reached+ * * `skipped_quota` - Skipped, the org's credit quota for this period was reached+ * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached+ * * `failed` - Failed to start+ */+export type ScanOutcomeEnumApi = (typeof ScanOutcomeEnumApi)[keyof typeof ScanOutcomeEnumApi]++export const ScanOutcomeEnumApi = {+ Started: 'started',+ AlreadyRunning: 'already_running',+ AlreadyScanned: 'already_scanned',+ SkippedLimit: 'skipped_limit',+ SkippedQuota: 'skipped_quota',+ SkippedScannerLimit: 'skipped_scanner_limit',+ Failed: 'failed',+} as const++/**+ * * `pending` - Pending+ * * `running` - Running+ * * `succeeded` - Succeeded+ * * `failed` - Failed+ * * `ineligible` - Ineligible+ * * `skipped` - Skipped+ * * `lost` - Lost+ */+export type RequestSessionStateEnumApi = (typeof RequestSessionStateEnumApi)[keyof typeof RequestSessionStateEnumApi]++export const RequestSessionStateEnumApi = {+ Pending: 'pending',+ Running: 'running',+ Succeeded: 'succeeded',+ Failed: 'failed',+ Ineligible: 'ineligible',+ Skipped: 'skipped',+ Lost: 'lost',+} as const++/**+ * One session of a request: how it started and where it stands now.+ */+export interface ObservationRequestSessionApi {+ /** The session recording this outcome is for. */+ session_id: string+ /** 'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a finished observation for this session, so nothing was started and nothing was charged (read it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was reached before this session; 'skipped_quota' - the org's credit quota for this period would be exceeded; 'skipped_scanner_limit' - this scanner's own credit limit would be exceeded; 'failed' - the workflow failed to start.+ *+ * * `started` - Started+ * * `already_running` - Already running+ * * `already_scanned` - Already scanned+ * * `skipped_limit` - Skipped, in-flight limit reached+ * * `skipped_quota` - Skipped, the org's credit quota for this period was reached+ * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached+ * * `failed` - Failed to start */+ scan_outcome: ScanOutcomeEnumApi+ /** Where the session stands now. 'pending' and 'running' are still in progress; 'succeeded' has a result; 'failed' and 'ineligible' finished without one; 'skipped' never started because a limit was reached (`scan_outcome` names which); 'lost' started but produced nothing before the scan timed out.+ *+ * * `pending` - Pending+ * * `running` - Running+ * * `succeeded` - Succeeded+ * * `failed` - Failed+ * * `ineligible` - Ineligible+ * * `skipped` - Skipped+ * * `lost` - Lost */+ state: RequestSessionStateEnumApi+ /**+ * The observation for this session, once one exists. Null before that.+ * @nullable+ */+ readonly observation_id: string | null+ /** The scanner's answer for this session. Null until the session succeeds. */+ readonly scanner_result: ScannerResultApi | null+}++/**+ * A scan request and the current state of each of its sessions.+ */+export interface ObservationRequestApi {+ /** Request ID. Poll `GET /vision/requests/{id}/` with it. */+ id: string+ /** 'completed' once every session has settled, whether or not it produced a result.+ *+ * * `running` - Running+ * * `completed` - Completed */+ status: ObservationRequestStatusEnumApi+ /**+ * The scanner the sessions were scanned with. For an inline question this is a hidden scanner, shared by every request that asks the same question. Null when nothing could start.+ * @nullable+ */+ scanner_id: string | null+ /** The `reference` sent with the request. */+ reference: string+ /** When the request was made. */+ created_at: string+ /** One entry per session, in request order. */+ sessions: ObservationRequestSessionApi[]+}+/*** * `ai` - AI draft* * `template` - Template@@ -1001,19 +1180,6 @@ export const ScannerProviderEnumApi = {Google: 'google',} as const-/**- * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite- * * `gemini-3-flash-preview` - Gemini 3 Flash- * * `gemini-3.8-flash` - Gemini 3.8 Flash- */-export type ScannerModelEnumApi = (typeof ScannerModelEnumApi)[keyof typeof ScannerModelEnumApi]--export const ScannerModelEnumApi = {- Gemini35FlashLite: 'gemini-3.5-flash-lite',- Gemini3FlashPreview: 'gemini-3-flash-preview',- Gemini38Flash: 'gemini-3.8-flash',-} as const-/*** The experiment a scanner watches. Scans derive their person-scoped exposure filter from* this blob at query time, so it is the only place an experiment can enter a scanner's@@ -1363,27 +1529,6 @@ export interface BulkObserveRequestApi {session_ids: string[]}-/**- * * `started` - Started- * * `already_running` - Already running- * * `already_scanned` - Already scanned- * * `skipped_limit` - Skipped, in-flight limit reached- * * `skipped_quota` - Skipped, the org's credit quota for this period was reached- * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached- * * `failed` - Failed to start- */-export type ScanOutcomeEnumApi = (typeof ScanOutcomeEnumApi)[keyof typeof ScanOutcomeEnumApi]--export const ScanOutcomeEnumApi = {- Started: 'started',- AlreadyRunning: 'already_running',- AlreadyScanned: 'already_scanned',- SkippedLimit: 'skipped_limit',- SkippedQuota: 'skipped_quota',- SkippedScannerLimit: 'skipped_scanner_limit',- Failed: 'failed',-} as const-/*** Per-session outcome of a bulk scan trigger.*/@@ -2569,12 +2714,6 @@ export interface EstimateResponseApi {* Body of POST /vision/scanners/inline_scan/ - a prompt plus the sessions to point it at.*/export interface InlineScanRequestApi {- /**- * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.- * @maxItems 200- * @items.maxLength 128- */- session_ids: string[]/*** What to look for in these sessions, in plain language. The same instruction a saved scanner carries.* @maxLength 20000@@ -2596,6 +2735,12 @@ export interface InlineScanRequestApi {* * `gemini-3-flash-preview` - Gemini 3 Flash* * `gemini-3.8-flash` - Gemini 3.8 Flash */model?: ScannerModelEnumApi+ /**+ * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.+ * @maxItems 200+ * @items.maxLength 128+ */+ session_ids: string[]}/**diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 71e18316d6ca..52b286896134 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -16,6 +16,7 @@ import type {BackfillWindowApi,BulkObserveRequestApi,BulkObserveResponseApi,+ CreateObservationRequestApi,CreateTaskFromObservationResponseApi,DraftScannerRequestApi,DraftScannerResponseApi,@@ -24,6 +25,7 @@ import type {ExperimentVariantsReadoutApi,InlineScanRequestApi,InlineScanResponseApi,+ ObservationRequestApi,ObservationSearchResponseApi,ObservationSignalReportApi,ObservationStatsApi,@@ -625,6 +627,44 @@ export const environmentVisionQuotaSpendSeriesRetrieve = async (})}+export const getVisionRequestsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/vision/requests/`+}++/**+ * Scan sessions with a saved scanner or an inline question. Poll the returned request for results.+ */+export const visionRequestsCreate = async (+ projectId: string,+ createObservationRequestApi: CreateObservationRequestApi,+ options?: RequestInit+): Promise<ObservationRequestApi> => {+ return apiMutator<ObservationRequestApi>(getVisionRequestsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(createObservationRequestApi),+ })+}++export const getVisionRequestsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/vision/requests/${id}/`+}++/**+ * Start scans for named sessions from code, and read their results back through one request id.+ */+export const visionRequestsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ObservationRequestApi> => {+ return apiMutator<ObservationRequestApi>(getVisionRequestsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getVisionScannersListUrl = (projectId: string, params?: VisionScannersListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 9380bc253a3b..a15afee83ac2 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -475,6 +475,87 @@ export const VisionObservationsSearchViewedCreateBody = /* @__PURE__ */ zod.obje.describe("Scope to a single scanner's observations. Defaults to every scanner you can read."),})+/**+ * Scan sessions with a saved scanner or an inline question. Poll the returned request for results.+ */+export const visionRequestsCreateBodySessionIdsItemMax = 128++export const visionRequestsCreateBodySessionIdsMax = 200++export const visionRequestsCreateBodyInlineOnePromptMax = 20000++export const visionRequestsCreateBodyInlineOneScannerTypeDefault = `monitor`+export const visionRequestsCreateBodyInlineOneModelDefault = `gemini-3-flash-preview`+export const visionRequestsCreateBodyIdempotencyKeyMax = 200++export const visionRequestsCreateBodyReferenceDefault = ``+export const visionRequestsCreateBodyReferenceMax = 200++export const VisionRequestsCreateBody = /* @__PURE__ */ zod+ .object({+ session_ids: zod+ .array(zod.string().max(visionRequestsCreateBodySessionIdsItemMax))+ .max(visionRequestsCreateBodySessionIdsMax)+ .describe(+ 'Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole request. Duplicates are dropped.'+ ),+ scanner_id: zod+ .uuid()+ .optional()+ .describe('A saved scanner to apply to the sessions. Pass this or `inline`, not both.'),+ inline: zod+ .object({+ prompt: zod+ .string()+ .max(visionRequestsCreateBodyInlineOnePromptMax)+ .describe(+ 'What to look for in these sessions, in plain language. The same instruction a saved scanner carries.'+ ),+ scanner_type: zod+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'experiment'])+ .describe(+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'+ )+ .default(visionRequestsCreateBodyInlineOneScannerTypeDefault)+ .describe(+ "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment"+ ),+ scanner_config: zod+ .unknown()+ .optional()+ .describe(+ 'Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here.'+ ),+ model: zod+ .enum(['gemini-3.5-flash-lite', 'gemini-3-flash-preview', 'gemini-3.8-flash'])+ .describe(+ '\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.8-flash` - Gemini 3.8 Flash'+ )+ .default(visionRequestsCreateBodyInlineOneModelDefault)+ .describe(+ 'Model to scan with. Determines what each observation costs in credits.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.8-flash` - Gemini 3.8 Flash'+ ),+ })+ .describe('A question asked inline, without saving a scanner first.')+ .optional()+ .describe(+ 'A question to ask without saving a scanner first. Asking the same question again reuses the answers already given for the same sessions. Pass this or `scanner_id`, not both.'+ ),+ idempotency_key: zod+ .string()+ .max(visionRequestsCreateBodyIdempotencyKeyMax)+ .optional()+ .describe(+ 'Any unique string per logical request, such as a UUID. Sending the same key again returns the first request instead of starting new scans, so a retry after a timeout never charges twice.'+ ),+ reference: zod+ .string()+ .max(visionRequestsCreateBodyReferenceMax)+ .default(visionRequestsCreateBodyReferenceDefault)+ .describe('Your own id for this request, such as a ticket or job id. Returned unchanged.'),+ })+ .describe('Body of POST \/vision\/requests\/ - the sessions plus a saved scanner or an inline question.')+/*** CRUD for Replay Vision scanners.*/@@ -1310,23 +1391,16 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod* recording ID. It resolves to the Summarize button's own scanner only when the prompt and* `scanner_config` match what the button sends, since the config is what the key fingerprints.*/-export const visionScannersInlineScanCreateBodySessionIdsItemMax = 128--export const visionScannersInlineScanCreateBodySessionIdsMax = 200-export const visionScannersInlineScanCreateBodyPromptMax = 20000export const visionScannersInlineScanCreateBodyScannerTypeDefault = `monitor`export const visionScannersInlineScanCreateBodyModelDefault = `gemini-3-flash-preview`+export const visionScannersInlineScanCreateBodySessionIdsItemMax = 128++export const visionScannersInlineScanCreateBodySessionIdsMax = 200export const VisionScannersInlineScanCreateBody = /* @__PURE__ */ zod.object({- session_ids: zod- .array(zod.string().max(visionScannersInlineScanCreateBodySessionIdsItemMax))- .max(visionScannersInlineScanCreateBodySessionIdsMax)- .describe(- 'Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.'- ),prompt: zod.string().max(visionScannersInlineScanCreateBodyPromptMax)@@ -1357,6 +1431,12 @@ export const VisionScannersInlineScanCreateBody = /* @__PURE__ */ zod.describe('Model to scan with. Determines what each observation costs in credits.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.8-flash` - Gemini 3.8 Flash'),+ session_ids: zod+ .array(zod.string().max(visionScannersInlineScanCreateBodySessionIdsItemMax))+ .max(visionScannersInlineScanCreateBodySessionIdsMax)+ .describe(+ 'Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.'+ ),}).describe('Body of POST \/vision\/scanners\/inline_scan\/ - a prompt plus the sessions to point it at.')diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 929454d261d5..5183b0ee8ba2 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -367,6 +367,31 @@ tools:today, zero-filled on days without spend. Spend covers every project in the organization. Use it to see whenspend picked up or to project where the period will end; `vision-quota-get` gives the running total and thelimit.+ vision-requests-create:+ operation: vision_requests_create+ enabled: true+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Request session scans+ description: >+ Scan up to 200 session recordings with a saved scanner (`scanner_id`) or a one-off question (`inline`, with+ the same `prompt`, `scanner_type`, `scanner_config` and `model` fields as `vision-scanners-inline-scan`),+ and get back one request id that covers every session. Pass an `idempotency_key` when you might retry the+ call: the same key returns the first request instead of starting and charging for the scans again. Results+ are not inline. Poll `vision-requests-get` with the returned `id` until `status` is `completed`; each+ session then carries its `state` and, when it succeeded, its `scanner_result`. Sessions past a credit or+ concurrency limit come back as `skipped` with the reason in `scan_outcome`, rather than failing the call.+ requires_ai_consent: true+ vision-requests-get:+ operation: vision_requests_retrieve+ enabled: true+ title: Get a session scan request+ description: >+ Read a scan request made with `vision-requests-create`: its `status` (`running` until every session has+ settled, then `completed`) and, for each session, its `state`, `observation_id` and `scanner_result` once it+ succeeded.vision-scanners-affected-cohort-create:operation: vision_scanners_affected_cohort_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 5883da7e9018..fe84ace4dde9 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -13808,6 +13808,35 @@"readOnlyHint": true}},+ "vision-requests-create": {+ "description": "Scan up to 200 session recordings with a saved scanner (`scanner_id`) or a one-off question (`inline`, with the same `prompt`, `scanner_type`, `scanner_config` and `model` fields as `vision-scanners-inline-scan`), and get back one request id that covers every session. Pass an `idempotency_key` when you might retry the call: the same key returns the first request instead of starting and charging for the scans again. Results are not inline. Poll `vision-requests-get` with the returned `id` until `status` is `completed`; each session then carries its `state` and, when it succeeded, its `scanner_result`. Sessions past a credit or concurrency limit come back as `skipped` with the reason in `scan_outcome`, rather than failing the call.",+ "category": "Replay vision",+ "feature": "replay_vision",+ "summary": "Request session scans",+ "title": "Request session scans",+ "required_scopes": ["replay_scanner:write", "session_recording:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "requires_ai_consent": true+ },+ "vision-requests-get": {+ "description": "Read a scan request made with `vision-requests-create`: its `status` (`running` until every session has settled, then `completed`) and, for each session, its `state`, `observation_id` and `scanner_result` once it succeeded.",+ "category": "Replay vision",+ "feature": "replay_vision",+ "summary": "Get a session scan request",+ "title": "Get a session scan request",+ "required_scopes": ["replay_scanner:write", "session_recording:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"vision-scanners-affected-cohort-create": {"description": "Create a static cohort of the users a scanner matched within the trailing window (default 30 days). Monitors count verdict-yes observations and take no qualifiers; classifiers require `tag`; scorers require `min_score` and/or `max_score`. The cohort is a dated snapshot and does not live-update; calling again creates a new cohort. Use it anywhere cohorts work: funnel breakdowns, retention, survey targeting, experiment exclusion. Fails when the window has no users or none resolve to a person profile.","category": "Replay vision",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex a859006e3546..459a4b8f975f 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -14486,6 +14486,35 @@"readOnlyHint": true}},+ "vision-requests-create": {+ "description": "Scan up to 200 session recordings with a saved scanner (`scanner_id`) or a one-off question (`inline`, with the same `prompt`, `scanner_type`, `scanner_config` and `model` fields as `vision-scanners-inline-scan`), and get back one request id that covers every session. Pass an `idempotency_key` when you might retry the call: the same key returns the first request instead of starting and charging for the scans again. Results are not inline. Poll `vision-requests-get` with the returned `id` until `status` is `completed`; each session then carries its `state` and, when it succeeded, its `scanner_result`. Sessions past a credit or concurrency limit come back as `skipped` with the reason in `scan_outcome`, rather than failing the call.",+ "category": "Replay vision",+ "feature": "replay_vision",+ "summary": "Request session scans",+ "title": "Request session scans",+ "required_scopes": ["replay_scanner:write", "session_recording:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "requires_ai_consent": true+ },+ "vision-requests-get": {+ "description": "Read a scan request made with `vision-requests-create`: its `status` (`running` until every session has settled, then `completed`) and, for each session, its `state`, `observation_id` and `scanner_result` once it succeeded.",+ "category": "Replay vision",+ "feature": "replay_vision",+ "summary": "Get a session scan request",+ "title": "Get a session scan request",+ "required_scopes": ["replay_scanner:write", "session_recording:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"vision-scanners-affected-cohort-create": {"description": "Create a static cohort of the users a scanner matched within the trailing window (default 30 days). Monitors count verdict-yes observations and take no qualifiers; classifiers require `tag`; scorers require `min_score` and/or `max_score`. The cohort is a dated snapshot and does not live-update; calling again creates a new cohort. Use it anywhere cohorts work: funnel breakdowns, retention, survey targeting, experiment exclusion. Fails when the window has no users or none resolve to a person profile.","category": "Replay vision",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 40cc8aa6fa88..54bb3ac9b1f7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26225,6 +26225,91 @@ export namespace Schemas {representative_email: string;}+ /**+ * * `monitor` - Monitor+ * * `classifier` - Classifier+ * * `scorer` - Scorer+ * * `summarizer` - Summarizer+ * * `experiment` - Experiment+ */+ export type ScannerTypeEnum = typeof ScannerTypeEnum[keyof typeof ScannerTypeEnum];+++ export const ScannerTypeEnum = {+ Monitor: 'monitor',+ Classifier: 'classifier',+ Scorer: 'scorer',+ Summarizer: 'summarizer',+ Experiment: 'experiment',+ } as const;++ /**+ * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite+ * * `gemini-3-flash-preview` - Gemini 3 Flash+ * * `gemini-3.8-flash` - Gemini 3.8 Flash+ */+ export type ScannerModelEnum = typeof ScannerModelEnum[keyof typeof ScannerModelEnum];+++ export const ScannerModelEnum = {+ Gemini35FlashLite: 'gemini-3.5-flash-lite',+ Gemini3FlashPreview: 'gemini-3-flash-preview',+ Gemini38Flash: 'gemini-3.8-flash',+ } as const;++ /**+ * A question asked inline, without saving a scanner first.+ */+ export interface InlineScanConfig {+ /**+ * What to look for in these sessions, in plain language. The same instruction a saved scanner carries.+ * @maxLength 20000+ */+ prompt: string;+ /** What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.+ *+ * * `monitor` - Monitor+ * * `classifier` - Classifier+ * * `scorer` - Scorer+ * * `summarizer` - Summarizer+ * * `experiment` - Experiment */+ scanner_type?: ScannerTypeEnum;+ /** Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here. */+ scanner_config?: unknown;+ /** Model to scan with. Determines what each observation costs in credits.+ *+ * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite+ * * `gemini-3-flash-preview` - Gemini 3 Flash+ * * `gemini-3.8-flash` - Gemini 3.8 Flash */+ model?: ScannerModelEnum;+ }++ /**+ * Body of POST /vision/requests/ - the sessions plus a saved scanner or an inline question.+ */+ export interface CreateObservationRequest {+ /**+ * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole request. Duplicates are dropped.+ * @maxItems 200+ * @items.maxLength 128+ */+ session_ids: string[];+ /** A saved scanner to apply to the sessions. Pass this or `inline`, not both. */+ scanner_id?: string;+ /** A question to ask without saving a scanner first. Asking the same question again reuses the answers already given for the same sessions. Pass this or `scanner_id`, not both. */+ inline?: InlineScanConfig;+ /**+ * Any unique string per logical request, such as a UUID. Sending the same key again returns the first request instead of starting new scans, so a retry after a timeout never charges twice.+ * @maxLength 200+ */+ idempotency_key?: string;+ /**+ * Your own id for this request, such as a ticket or job id. Returned unchanged.+ * @maxLength 200+ */+ reference?: string;+ }+/*** Typed output for view set `create`.*/@@ -37611,24 +37696,6 @@ export namespace Schemas {monthly_credit_budget?: number;}- /**- * * `monitor` - Monitor- * * `classifier` - Classifier- * * `scorer` - Scorer- * * `summarizer` - Summarizer- * * `experiment` - Experiment- */- export type ScannerTypeEnum = typeof ScannerTypeEnum[keyof typeof ScannerTypeEnum];--- export const ScannerTypeEnum = {- Monitor: 'monitor',- Classifier: 'classifier',- Scorer: 'scorer',- Summarizer: 'summarizer',- Experiment: 'experiment',- } as const;-/*** * `focused` - Focused* * `balanced` - Balanced@@ -37643,20 +37710,6 @@ export namespace Schemas {Comprehensive: 'comprehensive',} as const;- /**- * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite- * * `gemini-3-flash-preview` - Gemini 3 Flash- * * `gemini-3.8-flash` - Gemini 3.8 Flash- */- export type ScannerModelEnum = typeof ScannerModelEnum[keyof typeof ScannerModelEnum];--- export const ScannerModelEnum = {- Gemini35FlashLite: 'gemini-3.5-flash-lite',- Gemini3FlashPreview: 'gemini-3-flash-preview',- Gemini38Flash: 'gemini-3.8-flash',- } as const;-/*** The experiment a scanner watches. Scans derive their person-scoped exposure filter from* this blob at query time, so it is the only place an experiment can enter a scanner's@@ -58813,12 +58866,6 @@ export namespace Schemas {* Body of POST /vision/scanners/inline_scan/ - a prompt plus the sessions to point it at.*/export interface InlineScanRequest {- /**- * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.- * @maxItems 200- * @items.maxLength 128- */- session_ids: string[];/*** What to look for in these sessions, in plain language. The same instruction a saved scanner carries.* @maxLength 20000@@ -58840,6 +58887,12 @@ export namespace Schemas {* * `gemini-3-flash-preview` - Gemini 3 Flash* * `gemini-3.8-flash` - Gemini 3.8 Flash */model?: ScannerModelEnum;+ /**+ * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.+ * @maxItems 200+ * @items.maxLength 128+ */+ session_ids: string[];}/**@@ -67018,6 +67071,99 @@ export namespace Schemas {version_markers: ObservationVersionMarker[];}+ /**+ * * `running` - Running+ * * `completed` - Completed+ */+ export type ObservationRequestStatusEnum = typeof ObservationRequestStatusEnum[keyof typeof ObservationRequestStatusEnum];+++ export const ObservationRequestStatusEnum = {+ Running: 'running',+ Completed: 'completed',+ } as const;++ /**+ * * `pending` - Pending+ * * `running` - Running+ * * `succeeded` - Succeeded+ * * `failed` - Failed+ * * `ineligible` - Ineligible+ * * `skipped` - Skipped+ * * `lost` - Lost+ */+ export type RequestSessionStateEnum = typeof RequestSessionStateEnum[keyof typeof RequestSessionStateEnum];+++ export const RequestSessionStateEnum = {+ Pending: 'pending',+ Running: 'running',+ Succeeded: 'succeeded',+ Failed: 'failed',+ Ineligible: 'ineligible',+ Skipped: 'skipped',+ Lost: 'lost',+ } as const;++ /**+ * One session of a request: how it started and where it stands now.+ */+ export interface ObservationRequestSession {+ /** The session recording this outcome is for. */+ session_id: string;+ /** 'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a finished observation for this session, so nothing was started and nothing was charged (read it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was reached before this session; 'skipped_quota' - the org's credit quota for this period would be exceeded; 'skipped_scanner_limit' - this scanner's own credit limit would be exceeded; 'failed' - the workflow failed to start.+ *+ * * `started` - Started+ * * `already_running` - Already running+ * * `already_scanned` - Already scanned+ * * `skipped_limit` - Skipped, in-flight limit reached+ * * `skipped_quota` - Skipped, the org's credit quota for this period was reached+ * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached+ * * `failed` - Failed to start */+ scan_outcome: ScanOutcomeEnum;+ /** Where the session stands now. 'pending' and 'running' are still in progress; 'succeeded' has a result; 'failed' and 'ineligible' finished without one; 'skipped' never started because a limit was reached (`scan_outcome` names which); 'lost' started but produced nothing before the scan timed out.+ *+ * * `pending` - Pending+ * * `running` - Running+ * * `succeeded` - Succeeded+ * * `failed` - Failed+ * * `ineligible` - Ineligible+ * * `skipped` - Skipped+ * * `lost` - Lost */+ state: RequestSessionStateEnum;+ /**+ * The observation for this session, once one exists. Null before that.+ * @nullable+ */+ readonly observation_id: string | null;+ /** The scanner's answer for this session. Null until the session succeeds. */+ readonly scanner_result: ScannerResult | null;+ }++ /**+ * A scan request and the current state of each of its sessions.+ */+ export interface ObservationRequest {+ /** Request ID. Poll `GET /vision/requests/{id}/` with it. */+ id: string;+ /** 'completed' once every session has settled, whether or not it produced a result.+ *+ * * `running` - Running+ * * `completed` - Completed */+ status: ObservationRequestStatusEnum;+ /**+ * The scanner the sessions were scanned with. For an inline question this is a hidden scanner, shared by every request that asks the same question. Null when nothing could start.+ * @nullable+ */+ scanner_id: string | null;+ /** The `reference` sent with the request. */+ reference: string;+ /** When the request was made. */+ created_at: string;+ /** One entry per session, in request order. */+ sessions: ObservationRequestSession[];+ }+export interface ObservationSearchResult {/** The matching observation. */observation: ReplayObservation;diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex 957a383dac8b..161696c89870 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 49 enabled ops+ * PostHog API - MCP 51 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -670,6 +670,107 @@ export const EnvironmentVisionQuotaSpendSeriesRetrieveParams = () => zod.object(),})+/**+ * Scan sessions with a saved scanner or an inline question. Poll the returned request for results.+ */+export const VisionRequestsCreateParams = () => zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const visionRequestsCreateBodySessionIdsItemMax = 128++export const visionRequestsCreateBodySessionIdsMax = 200++export const visionRequestsCreateBodyInlineOnePromptMax = 20000++export const visionRequestsCreateBodyInlineOneScannerTypeDefault = `monitor`+export const visionRequestsCreateBodyInlineOneModelDefault = `gemini-3-flash-preview`+export const visionRequestsCreateBodyIdempotencyKeyMax = 200++export const visionRequestsCreateBodyReferenceDefault = ``+export const visionRequestsCreateBodyReferenceMax = 200++export const VisionRequestsCreateBody = () => zod+ .object({+ session_ids: zod+ .array(zod.string().max(visionRequestsCreateBodySessionIdsItemMax))+ .max(visionRequestsCreateBodySessionIdsMax)+ .describe(+ 'Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole request. Duplicates are dropped.'+ ),+ scanner_id: zod+ .string()+ .optional()+ .describe('A saved scanner to apply to the sessions. Pass this or `inline`, not both.'),+ inline: zod+ .object({+ prompt: zod+ .string()+ .max(visionRequestsCreateBodyInlineOnePromptMax)+ .describe(+ 'What to look for in these sessions, in plain language. The same instruction a saved scanner carries.'+ ),+ scanner_type: zod+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'experiment'])+ .describe(+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'+ )+ .default(visionRequestsCreateBodyInlineOneScannerTypeDefault)+ .describe(+ "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment"+ ),+ scanner_config: zod+ .unknown()+ .optional()+ .describe(+ 'Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here.'+ ),+ model: zod+ .enum(['gemini-3.5-flash-lite', 'gemini-3-flash-preview', 'gemini-3.8-flash'])+ .describe(+ '\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.8-flash` - Gemini 3.8 Flash'+ )+ .default(visionRequestsCreateBodyInlineOneModelDefault)+ .describe(+ 'Model to scan with. Determines what each observation costs in credits.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.8-flash` - Gemini 3.8 Flash'+ ),+ })+ .describe('A question asked inline, without saving a scanner first.')+ .optional()+ .describe(+ 'A question to ask without saving a scanner first. Asking the same question again reuses the answers already given for the same sessions. Pass this or `scanner_id`, not both.'+ ),+ idempotency_key: zod+ .string()+ .max(visionRequestsCreateBodyIdempotencyKeyMax)+ .optional()+ .describe(+ 'Any unique string per logical request, such as a UUID. Sending the same key again returns the first request instead of starting new scans, so a retry after a timeout never charges twice.'+ ),+ reference: zod+ .string()+ .max(visionRequestsCreateBodyReferenceMax)+ .default(visionRequestsCreateBodyReferenceDefault)+ .describe('Your own id for this request, such as a ticket or job id. Returned unchanged.'),+ })+ .describe('Body of POST \/vision\/requests\/ - the sessions plus a saved scanner or an inline question.')++/**+ * Start scans for named sessions from code, and read their results back through one request id.+ */+export const VisionRequestsRetrieveParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this replay observation request.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})+/*** CRUD for Replay Vision scanners.*/@@ -2062,23 +2163,16 @@ export const VisionScannersInlineScanCreateParams = () => zod.object({),})-export const visionScannersInlineScanCreateBodySessionIdsItemMax = 128--export const visionScannersInlineScanCreateBodySessionIdsMax = 200-export const visionScannersInlineScanCreateBodyPromptMax = 20000export const visionScannersInlineScanCreateBodyScannerTypeDefault = `monitor`export const visionScannersInlineScanCreateBodyModelDefault = `gemini-3-flash-preview`+export const visionScannersInlineScanCreateBodySessionIdsItemMax = 128++export const visionScannersInlineScanCreateBodySessionIdsMax = 200export const VisionScannersInlineScanCreateBody = () => zod.object({- session_ids: zod- .array(zod.string().max(visionScannersInlineScanCreateBodySessionIdsItemMax))- .max(visionScannersInlineScanCreateBodySessionIdsMax)- .describe(- 'Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.'- ),prompt: zod.string().max(visionScannersInlineScanCreateBodyPromptMax)@@ -2109,6 +2203,12 @@ export const VisionScannersInlineScanCreateBody = () => zod.describe('Model to scan with. Determines what each observation costs in credits.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.8-flash` - Gemini 3.8 Flash'),+ session_ids: zod+ .array(zod.string().max(visionScannersInlineScanCreateBodySessionIdsItemMax))+ .max(visionScannersInlineScanCreateBodySessionIdsMax)+ .describe(+ 'Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.'+ ),}).describe('Body of POST \/vision\/scanners\/inline_scan\/ - a prompt plus the sessions to point it at.')diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.tsindex 8b0d697c84f5..6d95d9e2e618 100644--- a/services/mcp/src/tools/generated/replay_vision.ts+++ b/services/mcp/src/tools/generated/replay_vision.ts@@ -605,6 +605,62 @@ const visionQuotaSpendSeriesGet = (): ToolBase<},})+const VisionRequestsCreateSchema = () => {+ const VisionRequestsCreateBody = orvalSchemas.VisionRequestsCreateBody()+ return VisionRequestsCreateBody+}++const visionRequestsCreate = (): ToolBase<+ ReturnType<typeof VisionRequestsCreateSchema>,+ Schemas.ObservationRequest+> => ({+ name: 'vision-requests-create',+ schema: VisionRequestsCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof VisionRequestsCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.session_ids !== undefined) {+ body['session_ids'] = params.session_ids+ }+ if (params.scanner_id !== undefined) {+ body['scanner_id'] = params.scanner_id+ }+ if (params.inline !== undefined) {+ body['inline'] = params.inline+ }+ if (params.idempotency_key !== undefined) {+ body['idempotency_key'] = params.idempotency_key+ }+ if (params.reference !== undefined) {+ body['reference'] = params.reference+ }+ const result = await context.api.request<Schemas.ObservationRequest>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/requests/`,+ body,+ })+ return result+ },+})++const VisionRequestsGetSchema = () => {+ const VisionRequestsRetrieveParams = orvalSchemas.VisionRequestsRetrieveParams()+ return VisionRequestsRetrieveParams.omit({ project_id: true })+}++const visionRequestsGet = (): ToolBase<ReturnType<typeof VisionRequestsGetSchema>, Schemas.ObservationRequest> => ({+ name: 'vision-requests-get',+ schema: VisionRequestsGetSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof VisionRequestsGetSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ObservationRequest>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/requests/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})+const VisionScannersAffectedCohortCreateSchema = () => {const VisionScannersAffectedCohortCreateBody = orvalSchemas.VisionScannersAffectedCohortCreateBody()const VisionScannersAffectedCohortCreateParams = orvalSchemas.VisionScannersAffectedCohortCreateParams()@@ -1075,9 +1131,6 @@ const visionScannersInlineScan = (): ToolBase<ReturnType<typeof VisionScannersInhandler: async (context: Context, params: z.infer<ReturnType<typeof VisionScannersInlineScanSchema>>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}- if (params.session_ids !== undefined) {- body['session_ids'] = params.session_ids- }if (params.prompt !== undefined) {body['prompt'] = params.prompt}@@ -1090,6 +1143,9 @@ const visionScannersInlineScan = (): ToolBase<ReturnType<typeof VisionScannersInif (params.model !== undefined) {body['model'] = params.model}+ if (params.session_ids !== undefined) {+ body['session_ids'] = params.session_ids+ }const result = await context.api.request<unknown>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/inline_scan/`,@@ -1638,6 +1694,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'vision-observations-signal-reports-list': visionObservationsSignalReportsList,'vision-quota-get': visionQuotaGet,'vision-quota-spend-series-get': visionQuotaSpendSeriesGet,+ 'vision-requests-create': visionRequestsCreate,+ 'vision-requests-get': visionRequestsGet,'vision-scanners-affected-cohort-create': visionScannersAffectedCohortCreate,'vision-scanners-backfills-cancel': visionScannersBackfillsCancel,'vision-scanners-backfills-create': visionScannersBackfillsCreate,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-requests-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-requests-create.jsonnew file mode 100644index 000000000000..9763923a3837--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-requests-create.json@@ -0,0 +1,59 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "description": "Body of POST /vision/requests/ - the sessions plus a saved scanner or an inline question.",+ "properties": {+ "idempotency_key": {+ "description": "Any unique string per logical request, such as a UUID. Sending the same key again returns the first request instead of starting new scans, so a retry after a timeout never charges twice.",+ "maxLength": 200,+ "type": "string"+ },+ "inline": {+ "description": "A question to ask without saving a scanner first. Asking the same question again reuses the answers already given for the same sessions. Pass this or `scanner_id`, not both.",+ "properties": {+ "model": {+ "default": "gemini-3-flash-preview",+ "description": "Model to scan with. Determines what each observation costs in credits.\n\n* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.8-flash` - Gemini 3.8 Flash",+ "enum": ["gemini-3.5-flash-lite", "gemini-3-flash-preview", "gemini-3.8-flash"],+ "type": "string"+ },+ "prompt": {+ "description": "What to look for in these sessions, in plain language. The same instruction a saved scanner carries.",+ "maxLength": 20000,+ "type": "string"+ },+ "scanner_config": {+ "description": "Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here."+ },+ "scanner_type": {+ "default": "monitor",+ "description": "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer\n* `experiment` - Experiment",+ "enum": ["monitor", "classifier", "scorer", "summarizer", "experiment"],+ "type": "string"+ }+ },+ "required": ["prompt"],+ "type": "object"+ },+ "reference": {+ "default": "",+ "description": "Your own id for this request, such as a ticket or job id. Returned unchanged.",+ "maxLength": 200,+ "type": "string"+ },+ "scanner_id": {+ "description": "A saved scanner to apply to the sessions. Pass this or `inline`, not both.",+ "type": "string"+ },+ "session_ids": {+ "description": "Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole request. Duplicates are dropped.",+ "items": {+ "maxLength": 128,+ "type": "string"+ },+ "maxItems": 200,+ "type": "array"+ }+ },+ "required": ["session_ids"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-requests-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-requests-get.jsonnew file mode 100644index 000000000000..06f89393603e--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-requests-get.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this replay observation request.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan.jsonindex 13888cfb8fc8..0a8ea05d8e18 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan.json@@ -32,6 +32,6 @@"type": "array"}},- "required": ["session_ids", "prompt"],+ "required": ["prompt", "session_ids"],"type": "object"}