: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 access control support for scanners and actions (#69742)
Reece Jones63b80e95e582
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.tsindex 6df627095334..b304115bff84 100644--- a/common/storybook/.storybook/app-context.ts+++ b/common/storybook/.storybook/app-context.ts@@ -93,5 +93,6 @@ export const getStorybookAppContext = (): AppContext => ({toolbar: 'viewer',error_tracking: 'manager',metrics: 'manager',+ replay_scanner: 'manager',},})diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f2eb681dcac7..268cffa94d1f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6947,9 +6947,9 @@ snapshots:scenes-app-settings-authentication-domains--one-unverified-domain--light:hash: v1.k794b7964.b1ae6dbc8feb673159fcc13f4a8fd5ee856c63ad1204e839a1b55ef70d109c81.W5sqRIJDHcdkKlYg4ghfwpbKS2FmlQKF_N-1C83h9Mgscenes-app-settings-environment--settings-environment-access-control--dark:- hash: v1.k794b7964.f0c837b6c5d1c5314f2ba768e843900490a282acafbabcc3dda9d6c23a936985.1tSvgzXNssLetAF7ZfGyEoY_whaDHGIzvuImLTGmOkA+ hash: v1.k794b7964.f371f0993dc42cd074258604780e8a90dcc80dd7319a2a0e15fd007f910bec43.XcwFTTHCfVcHpz1rc4P3qWgeboGmLt4lWDPKbdI9UVEscenes-app-settings-environment--settings-environment-access-control--light:- hash: v1.k794b7964.8e6e03e733477128947f48a00c106621bd89b31c6c3e7e5a7c22220bcd413a59.2gfPtWtNG5V5f9FcZoBY5YIDO0WXU2Q6ovz0BxC4NXk+ hash: v1.k794b7964.2bf13d938e2e771c04106ea1c77873ff914ff2c19d3328f74810d8f56812d2bd.ILHlhbk7257G41f-oFgJ_cT-IKHaNd4zaL5XdEmpUVwscenes-app-settings-environment--settings-environment-autocapture--dark:hash: v1.k794b7964.2183cf0082a1556d6df553572df4ab3813c96288a8b9a80e669c005908230c3e.-ybX8d6KyxaSa-yJDVccZm2CkK8Fl8qLSbw9jGhSIx4scenes-app-settings-environment--settings-environment-autocapture--light:diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsxindex b097b2f5d10a..7e2628229dd1 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx@@ -7,6 +7,7 @@ import {IconDatabase,IconDecisionTree,IconDownload,+ IconEye,IconFlask,IconHome,IconLive,@@ -78,6 +79,8 @@ export function ScopeIcon(props: { scope: APIScopeObject }): JSX.Element | nullreturn <IconSpotlight />case 'property_definition':return <IconApps />+ case 'replay_scanner':+ return <IconEye />case 'revenue_analytics':return <IconPiggyBank />case 'session_recording':diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.tsindex 1f96546e9c50..647fcfd61f78 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts@@ -1136,6 +1136,7 @@ export const accessControlLogic = kea<accessControlLogicType>([const resourceToRoute: Partial<Record<APIScopeObject, string>> = {warehouse_view: 'warehouse_saved_queries',early_access_feature: 'early_access_feature',+ replay_scanner: 'vision/scanners',}const route = resourceToRoute[resource] ?? `${resource}s`return `api/projects/${currentProjectId}/${route}/${resource_id}/access_controls`diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.tsindex d46de141c9c9..10f6a0e335ae 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts@@ -33,6 +33,7 @@ export const RESOURCE_ROLLOUT_FLAG_REQUIREMENTS: Partial<Record<AccessControlRes[AccessControlResourceType.Metrics]: FEATURE_FLAGS.METRICS,[AccessControlResourceType.RevenueAnalytics]: FEATURE_FLAGS.REVENUE_ANALYTICS,[AccessControlResourceType.Tracing]: FEATURE_FLAGS.TRACING,+ [AccessControlResourceType.ReplayScanner]: FEATURE_FLAGS.REPLAY_VISION,}export function isResourceRolledOut(@@ -185,6 +186,7 @@ export const resourcesAccessControlLogic = kea<resourcesAccessControlLogicType>(AccessControlResourceType.RevenueAnalytics,AccessControlResourceType.SessionRecording,AccessControlResourceType.ErrorTracking,+ AccessControlResourceType.ReplayScanner,AccessControlResourceType.Survey,AccessControlResourceType.WebAnalytics,AccessControlResourceType.Toolbar,diff --git a/frontend/src/lib/utils/accessControlUtils.ts b/frontend/src/lib/utils/accessControlUtils.tsindex 217ed8a0abf8..2a20bd4b24c3 100644--- a/frontend/src/lib/utils/accessControlUtils.ts+++ b/frontend/src/lib/utils/accessControlUtils.ts@@ -84,6 +84,9 @@ export const pluralizeResource = (resource: APIScopeObject): string => {return 'toolbar'} else if (resource === AccessControlResourceType.Workflow) {return 'workflows'+ } else if (resource === AccessControlResourceType.ReplayScanner) {+ // Covers both scanners and their scheduled summary actions — "replay vision" is the product name.+ return 'replay vision'}return resource.replace(/_/g, ' ') + 's'@@ -132,6 +135,8 @@ export const resourceTypeToString = (resourceType: AccessControlResourceType): sreturn 'tracing resource'} else if (resourceType === AccessControlResourceType.Workflow) {return 'workflow'+ } else if (resourceType === AccessControlResourceType.ReplayScanner) {+ return 'replay vision resource'}return resourceType.replace(/_/g, ' ')diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 379f7c7c1b23..b6abcf7a4bdb 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -140,6 +140,13 @@ export enum Scene {ReplaySettings = 'ReplaySettings',ReplaySingle = 'ReplaySingle',ReplayKiosk = 'ReplayKiosk',+ ReplayVision = 'ReplayVision',+ ReplayVisionScanner = 'ReplayVisionScanner',+ ReplayVisionScannerEditor = 'ReplayVisionScannerEditor',+ ReplayVisionObservation = 'ReplayVisionObservation',+ ReplayVisionAction = 'ReplayVisionAction',+ ReplayVisionActionEditor = 'ReplayVisionActionEditor',+ ReplayVisionActionRun = 'ReplayVisionActionRun',ResourceTransfer = 'ResourceTransfer',RevenueAnalytics = 'RevenueAnalytics',SqlVariableEdit = 'SqlVariableEdit',@@ -343,6 +350,15 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr[Scene.ReplaySingle]: AccessControlResourceType.SessionRecording,[Scene.ReplayPlaylist]: AccessControlResourceType.SessionRecording,+ // Replay vision+ [Scene.ReplayVision]: AccessControlResourceType.ReplayScanner,+ [Scene.ReplayVisionScanner]: AccessControlResourceType.ReplayScanner,+ [Scene.ReplayVisionScannerEditor]: AccessControlResourceType.ReplayScanner,+ [Scene.ReplayVisionObservation]: AccessControlResourceType.ReplayScanner,+ [Scene.ReplayVisionAction]: AccessControlResourceType.ReplayScanner,+ [Scene.ReplayVisionActionEditor]: AccessControlResourceType.ReplayScanner,+ [Scene.ReplayVisionActionRun]: AccessControlResourceType.ReplayScanner,+// Revenue analytics[Scene.RevenueAnalytics]: AccessControlResourceType.RevenueAnalytics,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex c4869915247c..a77464924e58 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -313,6 +313,7 @@ export enum AccessControlResourceType {ActivityLog = 'activity_log',ErrorTracking = 'error_tracking',Tracing = 'tracing',+ ReplayScanner = 'replay_scanner',Toolbar = 'toolbar',}diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.pyindex 7dc081503602..f08e15e66598 100644--- a/posthog/rbac/user_access_control.py+++ b/posthog/rbac/user_access_control.py@@ -81,6 +81,7 @@ ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = ("logs","metrics","tracing",+ "replay_scanner","toolbar",)@@ -106,6 +107,10 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {# the frontend mapping in sceneTypes.ts: Scene.MarketingAnalytics -># AccessControlResourceType.WebAnalytics)."marketing_analytics": "web_analytics",+ # Vision actions are a second data model of the Replay Vision product (the+ # scanner's "and then…" automations) — configured via the same single+ # replay_scanner rule rather than a separate resource.+ "vision_action": "replay_scanner",}WAREHOUSE_ACCESS_SCOPES: frozenset[str] = frozenset(diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 944e2a54c014..d43b1a404196 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -873,13 +873,13 @@ class ReplayObservationViewSet(description=("Set or update the observation's shared label: whether the scanner scored the session correctly, ""plus optional feedback on what it got wrong. One label per observation, shared across the team; "- "these labels feed prompt improvement. Requires session recording edit access."+ "these labels feed prompt improvement. Requires editor access to the scanner."),)@extend_schema(methods=["DELETE"],responses={204: None},- description="Remove the observation's shared label. Requires session recording edit access.",+ description="Remove the observation's shared label. Requires editor access to the scanner.",)@action(detail=True,@@ -895,11 +895,10 @@ class ReplayObservationViewSet(raise NotFound()observation = self.get_object()# Label writes are scanner writes; the session route's get_object only object-checks the observation row.+ # `label`'s required_scopes carries replay_scanner:write, so this already resolves to an editor-level+ # check — object-level too, so a per-scanner grant correctly overrides a resource-wide "none" default.scanner = getattr(self, "_scanner_for_url_cache", None) or observation.scannerself.check_object_permissions(self.request, scanner)- # Editing the shared label needs edit access, not just the viewer access reading needs.- if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="editor"):- raise PermissionDenied("Editing observation labels requires session_recording edit access.")user = cast(User, request.user)if request.method == "DELETE":ReplayObservationLabel.objects.filter(observation=observation, team_id=observation.team_id).delete()diff --git a/products/replay_vision/backend/api/prompt_suggestions.py b/products/replay_vision/backend/api/prompt_suggestions.pyindex c6e9a98ed463..9109506df077 100644--- a/products/replay_vision/backend/api/prompt_suggestions.py+++ b/products/replay_vision/backend/api/prompt_suggestions.py@@ -256,10 +256,11 @@ class ReplayScannerPromptSuggestionViewSet(self._scanner_for_url_cache = scannerreturn scanner- def _require_editor(self) -> None:- # Generating and acting on suggestions mutates team-wide scanner state, matching the "Edit scanner" gate.- if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="editor"):- raise PermissionDenied("Managing prompt suggestions requires session_recording edit access.")+ def _require_editor(self, scanner: ReplayScanner) -> None:+ # Generating and acting on suggestions mutates team-wide scanner state — object-check the scanner+ # itself (replay_scanner editor), mirroring the `retry` action in observations.py, rather than+ # gating on the unrelated session_recording resource.+ self.check_object_permissions(self.request, scanner)def safely_get_queryset(self, queryset: QuerySet[ReplayScannerPromptSuggestion]@@ -304,8 +305,8 @@ class ReplayScannerPromptSuggestionViewSet(responses={200: ReplayScannerPromptSuggestionSerializer},description=("Generate a fresh prompt suggestion from the team's current ratings. The previous pending "- "suggestion becomes history (superseded). Requires at least one rated observation and session "- "recording edit access."+ "suggestion becomes history (superseded). Requires at least one rated observation and editor "+ "access to the scanner."),)# Each call is an inline LLM request, so it gets the shared AI rate limits on top of the editor gate.@@ -317,7 +318,7 @@ class ReplayScannerPromptSuggestionViewSet()def generate(self, request: Request, **kwargs: Any) -> Response:scanner = self._scanner_for_url()- self._require_editor()+ self._require_editor(scanner)user = cast(User, request.user)try:suggestion = generate_prompt_suggestion(scanner, user)@@ -341,7 +342,7 @@ class ReplayScannerPromptSuggestionViewSet(@action(detail=True, methods=["post"], required_scopes=["replay_scanner:write", "session_recording:read"])def apply(self, request: Request, **kwargs: Any) -> Response:scanner = self._scanner_for_url()- self._require_editor()+ self._require_editor(scanner)suggestion = self.get_object()input_serializer = ApplyPromptSuggestionRequestSerializer(data=request.data)input_serializer.is_valid(raise_exception=True)@@ -397,7 +398,7 @@ class ReplayScannerPromptSuggestionViewSet(@action(detail=True, methods=["post"], required_scopes=["replay_scanner:write", "session_recording:read"])def evaluate(self, request: Request, **kwargs: Any) -> Response:scanner = self._scanner_for_url()- self._require_editor()+ self._require_editor(scanner)suggestion = self.get_object()input_serializer = EvaluatePromptSuggestionRequestSerializer(data=request.data)input_serializer.is_valid(raise_exception=True)@@ -470,13 +471,13 @@ class ReplayScannerPromptSuggestionViewSet(responses={200: ReplayScannerPromptSuggestionSerializer},description=("Dismiss this suggestion without applying it. Only the current pending suggestion can be "- "dismissed. Requires session recording edit access."+ "dismissed. Requires editor access to the scanner."),)@action(detail=True, methods=["post"], required_scopes=["replay_scanner:write", "session_recording:read"])def dismiss(self, request: Request, **kwargs: Any) -> Response:- self._scanner_for_url()- self._require_editor()+ scanner = self._scanner_for_url()+ self._require_editor(scanner)suggestion = self.get_object()with transaction.atomic():suggestion = ReplayScannerPromptSuggestion.objects.select_for_update().get(diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 14eec701ca1d..b39d56c4875b 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -21,6 +21,8 @@ from posthog.schema import RecordingsQueryfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.models.user import User+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin+from posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom products.replay_vision.backend.api.filters import (MultiChoiceFilter,@@ -175,7 +177,9 @@ class FeedbackThemesSerializer(serializers.Serializer):generated_at = serializers.DateTimeField(help_text="When the summary was generated.")-class ReplayScannerSerializer(serializers.ModelSerializer):+class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):+ """A Replay Vision scanner: its type, targeting query, and AI configuration."""+name = serializers.CharField(max_length=255,help_text="Human-readable scanner name. Unique within the team.",@@ -311,6 +315,7 @@ class ReplayScannerSerializer(serializers.ModelSerializer):"created_by","updated_at","feedback_themes",+ "user_access_level",]read_only_fields = ["id",@@ -324,6 +329,7 @@ class ReplayScannerSerializer(serializers.ModelSerializer):"created_by","updated_at","feedback_themes",+ "user_access_level",]@extend_schema_field(serializers.IntegerField())@@ -938,13 +944,13 @@ class AffectedCohortResponseSerializer(serializers.Serializer):]))-class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):"""CRUD for Replay Vision scanners."""scope_object = "replay_scanner"# Custom actions must be listed explicitly or personal-API-key callers 403 silently.scope_object_read_actions = ["list", "retrieve", "creators", "stats"]- scope_object_write_actions = ["create", "update", "partial_update", "destroy", "observe"]+ scope_object_write_actions = ["create", "update", "partial_update", "destroy", "observe", "bulk_observe"]permission_classes = [ReplayVisionEnabledPermission]serializer_class = ReplayScannerSerializerqueryset = ReplayScanner.objects.all()@@ -958,7 +964,9 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:if self.action in self._CONFIG_ACTIONS:return ["replay_scanner:write", "session_recording:read"]- return None+ # Falls through to AccessControlViewSetMixin's scope requirements for its+ # access_controls/resource_access_controls/users_with_access actions.+ return super().dangerously_get_required_scopes(request, view)def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:super().initial(request, *args, **kwargs)@@ -1213,9 +1221,13 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):sampling_rate: float = body.validated_data["sampling_rate"]# Reject a scanner_id outside this project before doing any work, so it can't silently undercount the others-sum.+ # Treat missing object-level access the same as missing-entirely so a denied scanner's existence and+ # credit usage can't be inferred by comparing responses (mirrors the `suggest_tags` action below).scanner_id = body.validated_data.get("scanner_id")- if scanner_id is not None and not ReplayScanner.objects.filter(team_id=self.team_id, pk=scanner_id).exists():- raise serializers.ValidationError({"scanner_id": "No scanner with this id exists in this project."})+ if scanner_id is not None:+ scanner = ReplayScanner.objects.filter(team_id=self.team_id, pk=scanner_id).first()+ if scanner is None or not self.user_access_control.check_access_level_for_object(scanner, "viewer"):+ raise serializers.ValidationError({"scanner_id": "No scanner with this id exists in this project."})# validate_query already validated this; the empty-dict default needs `kind` to parse.query_dict: dict[str, Any] = dict(body.validated_data.get("query") or {})diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.pyindex 0757fb84374e..a844cc75ce2c 100644--- a/products/replay_vision/backend/api/vision_actions.py+++ b/products/replay_vision/backend/api/vision_actions.py@@ -3,6 +3,7 @@ from typing import Any, NoReturn, cast, get_argsfrom django.db import IntegrityError, transactionfrom django.db.models import QuerySet+from django.shortcuts import get_object_or_404import structlogfrom drf_spectacular.types import OpenApiTypes@@ -10,6 +11,7 @@ from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schemafrom rest_framework import mixins, serializers, viewsetsfrom rest_framework.exceptions import NotFound, PermissionDeniedfrom rest_framework.request import Request+from rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixin@@ -36,7 +38,7 @@ from products.replay_vision.backend.models.vision_action import (VisionActionRunStatus,)from products.replay_vision.backend.rrule import validate_rrule, validate_timezone-from products.replay_vision.backend.scanner_access import readable_scanner_ids+from products.replay_vision.backend.scanner_access import is_uuid, readable_scanner_idsfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdictlogger = structlog.get_logger(__name__)@@ -194,6 +196,8 @@ MAX_ENABLED_ALERTS_PER_SCANNER = 10class VisionActionSerializer(serializers.ModelSerializer):+ """A Replay Vision action: a scheduled "and then…" automation over a scanner's observations."""+name = serializers.CharField(max_length=255,help_text="Human-readable action name. Unique within the team.",@@ -452,6 +456,32 @@ class VisionActionSerializer(serializers.ModelSerializer):raise error+def _selection_target_ids(scanner_id: uuid.UUID, selection: dict[str, Any] | None) -> set[str]:+ """Scanner ids an action's selection pulls observations from, beyond its bound `scanner`."""+ configured = (selection or {}).get("scanner_ids") or []+ return {str(s) for s in configured if is_uuid(s)} - {str(scanner_id)}+++def _check_action_scanner_access(+ view: TeamAndOrgViewSetMixin, scanner: ReplayScanner, selection: dict[str, Any] | None+) -> None:+ """Authorize every scanner an action can read from. The bound `scanner` is object-checked at+ whatever level `view.action` requires (editor to mutate the action, viewer to read it) — unchanged+ from before. Scanners named only in `selection.scanner_ids` are pure data sources the action never+ mutates, so they always need just viewer access regardless of `view.action`, the same bar as reading+ their observations directly — requiring editor there would block legitimately folding a view-only+ scanner's data into another scanner's summary.+ """+ view.check_object_permissions(view.request, scanner)+ other_ids = _selection_target_ids(scanner.id, selection)+ if not other_ids:+ return+ other_scanners = ReplayScanner.objects.filter(team_id=scanner.team_id, id__in=other_ids)+ for other_scanner in other_scanners:+ if not view.user_access_control.check_access_level_for_object(other_scanner, "viewer"):+ raise PermissionDenied("You don't have access to one or more scanners this action targets.")++@extend_schema_view(list=extend_schema(parameters=[@@ -467,6 +497,10 @@ class VisionActionSerializer(serializers.ModelSerializer):class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"""CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations."""+ # Deliberately NOT an AccessControlViewSetMixin: vision_action inherits its access level+ # from replay_scanner (see RESOURCE_INHERITANCE_MAP) so the product is configured via a+ # single rule. Exposing `/{id}/access_controls` here would let an object-level grant on+ # one action bypass that shared resource-level setting.scope_object = "vision_action"scope_object_read_actions = ["list", "retrieve"]scope_object_write_actions = ["create", "update", "partial_update", "destroy"]@@ -491,8 +525,29 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):):raise PermissionDenied("Configuring a Replay Vision action requires session_recording read access.")+ def safely_get_object(self, queryset: QuerySet[VisionAction]) -> VisionAction:+ action = get_object_or_404(queryset, pk=self.kwargs["pk"])+ # Per-scanner object-level grants are stored against `replay_scanner` + the scanner's id, not+ # `vision_action` + the action's id — the generic check_object_permissions() call the base+ # get_object() makes against `action` itself can only ever see the resource-level default,+ # never a scanner-specific override. Check the scanner directly too (mirroring the+ # `retry`/`label` pattern in observations.py), and every other scanner `selection.scanner_ids`+ # reads from, so a scanner-specific grant or restriction actually applies.+ _check_action_scanner_access(self, action.scanner, action.selection)+ return action+def safely_get_queryset(self, queryset: QuerySet[VisionAction]) -> QuerySet[VisionAction]:queryset = queryset.filter(team_id=self.team_id).select_related("scanner", "created_by")+ if self.action == "list":+ # `vision_action` never carries its own object-level access-control rows (see the class+ # docstring), so the generic queryset filtering in TeamAndOrgViewSetMixin is a no-op for this+ # model. Filter to the caller's accessible scanners explicitly instead, mirroring the+ # `creators`/`stats` pattern in scanners.py, so a scanner-level restriction actually hides+ # that scanner's actions from the list.+ accessible_scanners = self.user_access_control.filter_queryset_by_access_level(+ ReplayScanner.objects.filter(team_id=self.team_id)+ )+ queryset = queryset.filter(scanner_id__in=accessible_scanners.values_list("id", flat=True))# The per-scanner "Actions" tab scopes the list to one scanner.scanner_id = self.request.query_params.get("scanner")if scanner_id:@@ -506,6 +561,12 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return queryset.order_by("name", "id")def perform_create(self, serializer: BaseSerializer) -> None:+ # The resource-level check in `has_permission` only reflects the project-wide default; object-check+ # the target scanner too (and every other scanner `selection.scanner_ids` reads from) so a+ # scanner-specific restriction blocks new actions that read from it as well.+ _check_action_scanner_access(+ self, serializer.validated_data["scanner"], serializer.validated_data.get("selection")+ )# Atomic so a destination-provisioning failure rolls back the action row rather than leaving an# action that looks created but never delivers.with transaction.atomic():@@ -514,6 +575,14 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def perform_update(self, serializer: BaseSerializer) -> None:instance = cast(VisionAction, serializer.instance)+ # A PATCH can rebind `scanner`/`selection` to different ones; object-check whichever scanner (and+ # selection scanners) the action will end up pointing at — falling back to the current values so+ # an edit that leaves targeting untouched (e.g. delivery_config only) still revalidates against it.+ # Without the fallback, an editor of scanner A could freely rewrite delivery_config on an action+ # whose (unrelated, unchanged) selection reads from a scanner B they've never had access to.+ new_scanner = serializer.validated_data.get("scanner", instance.scanner)+ new_selection = serializer.validated_data.get("selection", instance.selection)+ _check_action_scanner_access(self, new_scanner, new_selection)# Snapshot the destination-affecting fields BEFORE save() — DRF mutates `instance` in place, so# these must be read pre-save for the change comparison to be meaningful.old_delivery = instance.delivery_config@@ -725,17 +794,42 @@ class VisionActionRunViewSet(# The list omits the report body + observations to stay light; retrieve returns the full detail.return VisionActionRunListSerializer if self.action == "list" else VisionActionRunSerializer+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ run = self.get_object()+ self._check_run_observation_scanner_access(run)+ return Response(self.get_serializer(run).data)++ def _check_run_observation_scanner_access(self, run: VisionActionRun) -> None:+ # A run's observation_ids reflect whatever the action's `selection` was AT RUN TIME — since+ # selection.scanner_ids can be edited later, a historical run may have drawn from a scanner the+ # action no longer targets (or the caller never had access to). Authorize the scanners those+ # observations actually came from before exposing the synthesized report, rather than trusting+ # the action's current selection. These scanners are read-only data sources for the report, like+ # the selection check in `_check_action_scanner_access`, so viewer access is enough.+ ids = run.observation_ids if isinstance(run.observation_ids, list) else []+ if not ids:+ return+ scanner_ids = set(+ ReplayObservation.objects.filter(team_id=run.team_id, id__in=ids).values_list("scanner_id", flat=True)+ )+ for scanner in ReplayScanner.objects.filter(team_id=self.team_id, id__in=scanner_ids):+ if not self.user_access_control.check_access_level_for_object(scanner, "viewer"):+ raise PermissionDenied("You don't have access to one or more scanners behind this run's report.")+def _action_for_url(self) -> VisionAction:try:action_id = uuid.UUID(self.kwargs["parent_lookup_vision_action_id"])except (KeyError, ValueError):raise NotFound()- action = VisionAction.objects.for_team(self.team_id).filter(id=action_id).first()+ action = VisionAction.objects.for_team(self.team_id).select_related("scanner").filter(id=action_id).first()if action is None:raise NotFound()# Runs expose recording-derived summaries, so reading them inherits the action's RBAC and also- # requires session_recording read (mirrors the observations endpoint).- self.check_object_permissions(self.request, action)+ # requires session_recording read (mirrors the observations endpoint). Per-scanner object-level+ # grants are stored against `replay_scanner` + the scanner's id, not `vision_action` + the action's+ # id, so check the scanner directly (and every other scanner `selection.scanner_ids` reads from) —+ # checking `action` itself would only ever see the resource-level default.+ _check_action_scanner_access(self, action.scanner, action.selection)if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):raise PermissionDenied("Reading vision action runs requires session_recording read access.")return actiondiff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.pyindex 0dbf615c5770..5c6261b4dd80 100644--- a/products/replay_vision/backend/models/replay_scanner.py+++ b/products/replay_vision/backend/models/replay_scanner.py@@ -1,3 +1,4 @@+import datetime as dtfrom typing import TYPE_CHECKINGfrom django.core.validators import MaxValueValidator, MinValueValidator@@ -13,6 +14,12 @@ if TYPE_CHECKING:from posthog.schema import RecordingsQuery+# Lives here, not in queries/scanner_candidate_query (which imports SamplingMode from this+# module), so `initial_watermark`'s default callable never needs to import back up into the+# query layer — models must stay a dependency leaf for the query layer, never the reverse.+# 30-min inactivity timeout + 5-min merge-lag buffer.+SETTLE_INTERVAL = dt.timedelta(minutes=35)+class ScannerType(models.TextChoices):MONITOR = "monitor", "Monitor"@@ -43,10 +50,6 @@ def initial_watermark() -> "datetime":"""A new scanner's sweep watermark, started one settle-interval back so its first sweep immediately picks uprecordings that have just cleared the settle window instead of a ~settle-interval cold start; it advancesforward normally from there, so there's no re-scan."""- from products.replay_vision.backend.queries.scanner_candidate_query import ( # noqa: PLC0415 — keep the heavy hogql query module off the model import path- SETTLE_INTERVAL,- )-return timezone.now() - SETTLE_INTERVALdiff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.pyindex be6d071adbf7..92f126e472bf 100644--- a/products/replay_vision/backend/queries/scanner_candidate_query.py+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py@@ -17,7 +17,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models import Teamfrom posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery-from products.replay_vision.backend.models.replay_scanner import SamplingMode+from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, SamplingModefrom products.replay_vision.backend.temporal.constants import (MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,MAX_SESSION_ID_LENGTH,@@ -28,9 +28,6 @@ from products.replay_vision.backend.temporal.constants import (logger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)-# 30-min inactivity timeout + 5-min merge-lag buffer.-SETTLE_INTERVAL = dt.timedelta(minutes=35)-# Partition prune anchored to the SDK's 24h session_id rotation + 2h headroom for skew and lag._PARTITION_LOOKBACK = dt.timedelta(hours=26)diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.pynew file mode 100644index 000000000000..702967afc4d1--- /dev/null+++ b/products/replay_vision/backend/tests/test_access_control.py@@ -0,0 +1,315 @@+from unittest.mock import MagicMock, patch++from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, PersonalAPIKey, User+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.replay_vision.backend.models.replay_observation import ReplayObservation+from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun, VisionActionRunStatus+from products.replay_vision.backend.tests.test_api import _VisionAPITestCase+from products.replay_vision.backend.tests.test_vision_actions_api import _VisionActionAPITestCase++try:+ from ee.models.rbac.access_control import AccessControl+except ImportError:+ pass+++class _AccessControlTestCase(_VisionAPITestCase):+ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")++ def _set_resource_default(self, resource: str, access_level: str) -> None:+ AccessControl.objects.update_or_create(+ team=self.team,+ resource=resource,+ resource_id=None,+ organization_member=None,+ role=None,+ defaults={"access_level": access_level},+ )++ def _grant_object_access(self, user: User, resource: str, resource_id: str, access_level: str) -> None:+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=resource_id,+ access_level=access_level,+ organization_member=membership,+ )++ def _personal_api_key(self, user: User, scopes: list[str]) -> str:+ value = generate_random_token_personal()+ PersonalAPIKey.objects.create(label="ac-test", user=user, secure_value=hash_key_value(value), scopes=scopes)+ return value+++class TestReplayScannerAccessControl(_AccessControlTestCase):+ def test_resource_default_none_blocks_list_and_retrieve(self) -> None:+ scanner = self._create_scanner()+ self._set_resource_default("replay_scanner", "none")++ self.client.force_login(self.other_user)+ list_resp = self.client.get(self.scanners_url)+ self.assertEqual(list_resp.status_code, 403, list_resp.json())++ retrieve_resp = self.client.get(f"{self.scanners_url}{scanner.id}/")+ self.assertEqual(retrieve_resp.status_code, 403, retrieve_resp.json())++ def test_viewer_access_cannot_create_or_update_scanner(self) -> None:+ scanner = self._create_scanner()+ self._set_resource_default("replay_scanner", "viewer")++ self.client.force_login(self.other_user)+ create_resp = self.client.post(+ self.scanners_url,+ data={+ "name": "viewer-created",+ "scanner_type": "monitor",+ "scanner_config": {"prompt": "well?"},+ "model": "gemini-3-flash",+ },+ format="json",+ )+ self.assertEqual(create_resp.status_code, 403, create_resp.json())++ update_resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data={"name": "renamed"}, format="json")+ self.assertEqual(update_resp.status_code, 403, update_resp.json())++ def test_object_level_grant_overrides_resource_default_none(self) -> None:+ allowed_scanner = self._create_scanner(name="allowed")+ blocked_scanner = self._create_scanner(name="blocked")+ self._set_resource_default("replay_scanner", "none")+ self._grant_object_access(self.other_user, "replay_scanner", str(allowed_scanner.id), "viewer")++ self.client.force_login(self.other_user)+ allowed_resp = self.client.get(f"{self.scanners_url}{allowed_scanner.id}/")+ self.assertEqual(allowed_resp.status_code, 200, allowed_resp.json())++ blocked_resp = self.client.get(f"{self.scanners_url}{blocked_scanner.id}/")+ self.assertEqual(blocked_resp.status_code, 403, blocked_resp.json())++ def test_user_access_level_exposed_on_scanner(self) -> None:+ scanner = self._create_scanner()+ self._set_resource_default("replay_scanner", "viewer")++ self.client.force_login(self.other_user)+ resp = self.client.get(f"{self.scanners_url}{scanner.id}/")+ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertEqual(resp.json()["user_access_level"], "viewer")++ def test_access_controls_endpoint_requires_access_control_scope(self) -> None:+ # Regression guard: ReplayScannerViewSet overrides dangerously_get_required_scopes for its+ # own config actions — it must still fall through to AccessControlViewSetMixin's scope+ # requirements for access_controls/resource_access_controls, or personal-API-key callers+ # would bypass the access_control:read/write scope check entirely.+ scanner = self._create_scanner()+ read_key = self._personal_api_key(self.user, ["replay_scanner:read", "session_recording:read"])+ ac_key = self._personal_api_key(+ self.user, ["replay_scanner:read", "session_recording:read", "access_control:read"]+ )++ denied = self.client.get(+ f"{self.scanners_url}{scanner.id}/access_controls/", HTTP_AUTHORIZATION=f"Bearer {read_key}"+ )+ self.assertEqual(denied.status_code, 403, denied.json())++ allowed = self.client.get(+ f"{self.scanners_url}{scanner.id}/access_controls/", HTTP_AUTHORIZATION=f"Bearer {ac_key}"+ )+ self.assertEqual(allowed.status_code, 200, allowed.json())++ @patch("products.replay_vision.backend.api.trigger.sync_connect")+ @patch("products.replay_vision.backend.api.trigger.async_to_sync")+ def test_bulk_observe_requires_replay_scanner_editor_level(+ self, mock_async_to_sync: MagicMock, mock_sync_connect: MagicMock+ ) -> None:+ # bulk_observe is a newer write action alongside observe/create/update/destroy — this guards+ # against it silently losing RBAC coverage (e.g. an incomplete scope_object_write_actions entry)+ # the way observe's object-level check protects that action.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ scanner = self._create_scanner()+ self._set_resource_default("replay_scanner", "viewer")+ bulk_url = f"{self.scanners_url}{scanner.id}/bulk_observe/"++ self.client.force_login(self.other_user)+ denied = self.client.post(bulk_url, data={"session_ids": ["s1"]}, format="json")+ self.assertEqual(denied.status_code, 403, denied.json())++ self._grant_object_access(self.other_user, "replay_scanner", str(scanner.id), "editor")+ allowed = self.client.post(bulk_url, data={"session_ids": ["s1"]}, format="json")+ self.assertEqual(allowed.status_code, 202, allowed.json())++ def test_estimate_treats_denied_scanner_as_not_found(self) -> None:+ # A scanner_id the caller can't view must be rejected the same way as one that doesn't exist —+ # otherwise comparing responses (with/without the id) leaks whether it exists and its credit usage.+ # A resource-wide "none" default would block the whole `estimate` action at the permission layer+ # before this object-level check ever runs, so deny only this one scanner instead.+ blocked_scanner = self._create_scanner(name="blocked")+ self._grant_object_access(self.other_user, "replay_scanner", str(blocked_scanner.id), "none")++ self.client.force_login(self.other_user)+ resp = self.client.post(+ f"{self.scanners_url}estimate/", data={"scanner_id": str(blocked_scanner.id)}, format="json"+ )+ self.assertEqual(resp.status_code, 400, resp.json())+ self.assertEqual(resp.json()["attr"], "scanner_id")+++class TestVisionActionAccessControlInheritance(_VisionActionAPITestCase):+ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")++ def _set_replay_scanner_resource_default(self, access_level: str) -> None:+ AccessControl.objects.update_or_create(+ team=self.team,+ resource="replay_scanner",+ resource_id=None,+ organization_member=None,+ role=None,+ defaults={"access_level": access_level},+ )++ def _grant_scanner_access(self, user: User, scanner_id: str, access_level: str) -> None:+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="replay_scanner",+ resource_id=scanner_id,+ access_level=access_level,+ organization_member=membership,+ )++ def test_vision_action_inherits_replay_scanner_resource_level(self) -> None:+ # vision_action has no resource-level rule of its own (RESOURCE_INHERITANCE_MAP points it at+ # replay_scanner) — a "none" default on replay_scanner must block vision_action reads too.+ self._set_replay_scanner_resource_default("none")++ self.client.force_login(self.other_user)+ resp = self.client.get(self.actions_url)+ self.assertEqual(resp.status_code, 403, resp.json())++ def test_vision_action_create_requires_replay_scanner_editor_level(self) -> None:+ self._set_replay_scanner_resource_default("viewer")++ self.client.force_login(self.other_user)+ resp = self.client.post(self.actions_url, data=self._create_payload(), format="json")+ self.assertEqual(resp.status_code, 403, resp.json())++ self._set_replay_scanner_resource_default("editor")+ resp = self.client.post(self.actions_url, data=self._create_payload(name="second-action"), format="json")+ self.assertEqual(resp.status_code, 201, resp.json())++ def test_vision_action_has_no_own_access_controls_endpoint(self) -> None:+ # Deliberate: vision_action is configured via the single replay_scanner rule, not its own+ # object-level grants (see the comment on VisionActionViewSet).+ action = VisionAction.objects.for_team(self.team.id).create(+ team=self.team,+ created_by=self.user,+ name="digest",+ scanner=self.scanner,+ )+ resp = self.client.get(f"{self.actions_url}{action.id}/access_controls/")+ self.assertEqual(resp.status_code, 404, resp.json())++ def test_retrieve_blocked_when_selection_scanner_is_denied(self) -> None:+ # `selection.scanner_ids` lets an action pull observations from scanners beyond the one it's+ # bound to — retrieving the action must authorize those too, not just the bound scanner. The+ # bound scanner rides the ambient default ("editor", unrestricted); only `other_scanner` gets an+ # explicit object-level denial, isolating the new selection-scanner check from the bound one.+ other_scanner = self._create_scanner(name="other-scanner")+ self._grant_scanner_access(self.other_user, str(other_scanner.id), "none")+ action = VisionAction.objects.for_team(self.team.id).create(+ team=self.team,+ created_by=self.user,+ name="digest",+ scanner=self.scanner,+ selection={"scanner_ids": [str(self.scanner.id), str(other_scanner.id)]},+ )++ self.client.force_login(self.other_user)+ resp = self.client.get(f"{self.actions_url}{action.id}/")+ self.assertEqual(resp.status_code, 403, resp.json())++ def test_update_revalidates_selection_scanner_when_only_delivery_changes(self) -> None:+ # A PATCH that touches neither `scanner` nor `selection` must still revalidate the action's+ # existing selection — otherwise an editor of the bound scanner could freely rewrite delivery+ # destinations on an action whose (untouched) selection reads from a scanner they can't access.+ other_scanner = self._create_scanner(name="other-scanner")+ self._grant_scanner_access(self.other_user, str(other_scanner.id), "none")+ action = VisionAction.objects.for_team(self.team.id).create(+ team=self.team,+ created_by=self.user,+ name="digest",+ scanner=self.scanner,+ selection={"scanner_ids": [str(self.scanner.id), str(other_scanner.id)]},+ )++ self.client.force_login(self.other_user)+ resp = self.client.patch(+ f"{self.actions_url}{action.id}/",+ data={"delivery_config": [{"type": "slack", "integration_id": self.integration.id, "channel": "#new"}]},+ format="json",+ )+ self.assertEqual(resp.status_code, 403, resp.json())+ action.refresh_from_db()+ self.assertEqual(action.delivery_config, [])++ def test_run_report_blocked_when_observation_scanner_is_denied(self) -> None:+ # A run's observation_ids reflect whatever scanners it actually drew from at run time. If+ # `selection` is edited later (or access is revoked), a historical run can still cite an+ # observation from a scanner the caller can no longer see — the report must not expose it, even+ # though the action's current selection and bound scanner remain fully accessible.+ other_scanner = self._create_scanner(name="other-scanner")+ self._grant_scanner_access(self.other_user, str(other_scanner.id), "none")+ action = VisionAction.objects.for_team(self.team.id).create(+ team=self.team, created_by=self.user, name="digest", scanner=self.scanner+ )+ observation = ReplayObservation.objects.create(scanner=other_scanner, session_id="sess-1")+ run = VisionActionRun.all_teams.create(+ team=self.team,+ vision_action=action,+ idempotency_key="run-1",+ status=VisionActionRunStatus.COMPLETED,+ observation_ids=[str(observation.id)],+ )++ self.client.force_login(self.other_user)+ runs_url = f"{self.actions_url}{action.id}/runs/"+ list_resp = self.client.get(runs_url)+ self.assertEqual(list_resp.status_code, 200, list_resp.json()) # lightweight rows carry no report body++ retrieve_resp = self.client.get(f"{runs_url}{run.id}/")+ self.assertEqual(retrieve_resp.status_code, 403, retrieve_resp.json())++ def test_update_cannot_rebind_action_onto_a_restricted_scanner(self) -> None:+ # Editor on `self.scanner`, but only viewer on `other_scanner` — enough to read it (so the+ # serializer's separate readable-scanner-ids check doesn't fire first) but not enough to bind+ # an action to it.+ other_scanner = self._create_scanner(name="other-scanner")+ self._set_replay_scanner_resource_default("none")+ self._grant_scanner_access(self.other_user, str(self.scanner.id), "editor")+ self._grant_scanner_access(self.other_user, str(other_scanner.id), "viewer")+ action = VisionAction.objects.for_team(self.team.id).create(+ team=self.team, created_by=self.user, name="digest", scanner=self.scanner+ )++ self.client.force_login(self.other_user)+ resp = self.client.patch(+ f"{self.actions_url}{action.id}/", data={"scanner": str(other_scanner.id)}, format="json"+ )+ self.assertEqual(resp.status_code, 403, resp.json())+ action.refresh_from_db()+ self.assertEqual(action.scanner_id, self.scanner.id)diff --git a/products/replay_vision/backend/tests/test_observation_labels_api.py b/products/replay_vision/backend/tests/test_observation_labels_api.pyindex 0b53e77de957..8d52476a44e9 100644--- a/products/replay_vision/backend/tests/test_observation_labels_api.py+++ b/products/replay_vision/backend/tests/test_observation_labels_api.py@@ -213,10 +213,10 @@ class TestObservationLabels(_VisionAPITestCase):self.assertEqual(label, {"is_correct": False, "feedback": "shared feedback"})def _deny_editor(self):- # Viewer access still passes (reading observations); only editor is withheld.+ # Viewer-level object checks still pass (reading observations); only editor is withheld.return patch(- "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_resource",- side_effect=lambda resource, required_level=None, **_: required_level != "editor",+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_object",+ side_effect=lambda obj, required_level=None, **_: required_level != "editor",)def test_editing_label_requires_editor_access(self) -> None:diff --git a/products/replay_vision/backend/tests/test_prompt_suggestions_api.py b/products/replay_vision/backend/tests/test_prompt_suggestions_api.pyindex 1104ff4fa80c..ff344aa0d645 100644--- a/products/replay_vision/backend/tests/test_prompt_suggestions_api.py+++ b/products/replay_vision/backend/tests/test_prompt_suggestions_api.py@@ -451,8 +451,8 @@ class TestPromptSuggestions(_VisionAPITestCase):def test_mutations_require_editor_access(self) -> None:self._create_rated_observation("sess-1", False, "should be yes")with patch(- "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_resource",- side_effect=lambda resource, required_level=None, **_: required_level != "editor",+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_object",+ side_effect=lambda obj, required_level=None, **_: required_level != "editor",):resp = self.client.post(self._suggestions_url("generate/"))self.assertEqual(resp.status_code, 403)diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsxindex ea4aeabf6197..5931823da8a9 100644--- a/products/replay_vision/frontend/components/ObservationCard.tsx+++ b/products/replay_vision/frontend/components/ObservationCard.tsx@@ -1,13 +1,13 @@+import { useValues } from 'kea'+import { IconRefresh, IconRewindPlay, IconSparkles } from '@posthog/icons'import { LemonButton, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { colonDelimitedDuration } from 'lib/utils/durations'import { urls } from 'scenes/urls'-import { AccessControlLevel, AccessControlResourceType } from '~/types'-import type { ReplayObservationApi } from '../generated/api.schemas'+import { replayScannerLogic } from '../replay_scanners/replayScannerLogic'import {type ClassifierScannerConfig,type ScorerScannerConfig,@@ -18,6 +18,7 @@ import {parseIneligibleReason,scannerTypeLabel,} from '../replay_scanners/types'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'import { parseCitedSegments } from '../utils/citations'import { ObservationProgressBar } from './ObservationProgressBar'@@ -371,6 +372,7 @@ export function ObservationDockCard({const snapshot = observation.scanner_snapshotconst scannerType = snapshot?.scanner_typeconst result = readResult(observation)+ const { scanner } = useValues(replayScannerLogic({ id: observation.scanner_id }))return (<div className="border rounded p-3 bg-surface-primary space-y-2">@@ -389,21 +391,17 @@ export function ObservationDockCard({<div className="space-y-2"><FailureDetail errorReason={observation.error_reason} />{onRetry && (- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconRefresh />}+ onClick={onRetry}+ loading={retrying}+ disabledReason={getReplayVisionEditDisabledReason(scanner?.user_access_level)}+ data-attr="vision-dock-retry-observation">- <LemonButton- size="xsmall"- type="secondary"- icon={<IconRefresh />}- onClick={onRetry}- loading={retrying}- data-attr="vision-dock-retry-observation"- >- Retry scan- </LemonButton>- </AccessControlAction>+ Retry scan+ </LemonButton>)}</div>)}diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 05d22ff7ae29..b76684d95428 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -244,6 +244,9 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+/**+ * A Replay Vision action: a scheduled "and then…" automation over a scanner's observations.+ */export interface VisionActionApi {readonly id: string/**@@ -308,6 +311,9 @@ export interface PaginatedVisionActionListApi {results: VisionActionApi[]}+/**+ * A Replay Vision action: a scheduled "and then…" automation over a scanner's observations.+ */export interface PatchedVisionActionApi {readonly id?: string/**@@ -739,6 +745,9 @@ export interface FeedbackThemesApi {generated_at: string}+/**+ * A Replay Vision scanner: its type, targeting query, and AI configuration.+ */export interface ReplayScannerApi {readonly id: string/**@@ -811,6 +820,11 @@ export interface ReplayScannerApi {readonly updated_at: string/** AI summary of the team's written thumbs-down feedback into recurring failure modes. Refreshed with prompt recommendations; null until enough feedback accumulates. */readonly feedback_themes: FeedbackThemesApi | null+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null}export interface PaginatedReplayScannerListApi {@@ -822,6 +836,9 @@ export interface PaginatedReplayScannerListApi {results: ReplayScannerApi[]}+/**+ * A Replay Vision scanner: its type, targeting query, and AI configuration.+ */export interface PatchedReplayScannerApi {readonly id?: string/**@@ -894,6 +911,11 @@ export interface PatchedReplayScannerApi {readonly updated_at?: string/** AI summary of the team's written thumbs-down feedback into recurring failure modes. Refreshed with prompt recommendations; null until enough feedback accumulates. */readonly feedback_themes?: FeedbackThemesApi | null+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level?: string | null}/**diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 4bcc23517b28..154e4b493bb3 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -319,7 +319,7 @@ export const getVisionObservationsLabelCreateUrl = (projectId: string, id: strin}/**- * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires session recording edit access.+ * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires editor access to the scanner.*/export const visionObservationsLabelCreate = async (projectId: string,@@ -340,7 +340,7 @@ export const getVisionObservationsLabelDestroyUrl = (projectId: string, id: stri}/**- * Remove the observation's shared label. Requires session recording edit access.+ * Remove the observation's shared label. Requires editor access to the scanner.*/export const visionObservationsLabelDestroy = async (projectId: string,@@ -692,7 +692,7 @@ export const getVisionScannersObservationsLabelCreateUrl = (projectId: string, s}/**- * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires session recording edit access.+ * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires editor access to the scanner.*/export const visionScannersObservationsLabelCreate = async (projectId: string,@@ -717,7 +717,7 @@ export const getVisionScannersObservationsLabelDestroyUrl = (projectId: string,}/**- * Remove the observation's shared label. Requires session recording edit access.+ * Remove the observation's shared label. Requires editor access to the scanner.*/export const visionScannersObservationsLabelDestroy = async (projectId: string,@@ -860,7 +860,7 @@ export const getVisionScannersPromptSuggestionsDismissCreateUrl = (}/**- * Dismiss this suggestion without applying it. Only the current pending suggestion can be dismissed. Requires session recording edit access.+ * Dismiss this suggestion without applying it. Only the current pending suggestion can be dismissed. Requires editor access to the scanner.*/export const visionScannersPromptSuggestionsDismissCreate = async (projectId: string,@@ -932,7 +932,7 @@ export const getVisionScannersPromptSuggestionsGenerateCreateUrl = (projectId: s}/**- * Generate a fresh prompt suggestion from the team's current ratings. The previous pending suggestion becomes history (superseded). Requires at least one rated observation and session recording edit access.+ * Generate a fresh prompt suggestion from the team's current ratings. The previous pending suggestion becomes history (superseded). Requires at least one rated observation and editor access to the scanner.*/export const visionScannersPromptSuggestionsGenerateCreate = async (projectId: string,diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 3fa577a05a07..829d7bc7a269 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -21,152 +21,156 @@ export const visionActionsCreateBodyAlertConfigOneFrequencyDefault = `on_breach`export const visionActionsCreateBodyAlertConfigOneMetricDefault = `count`export const visionActionsCreateBodyAlertConfigOneDirectionDefault = `above`-export const VisionActionsCreateBody = /* @__PURE__ */ zod.object({- name: zod- .string()- .max(visionActionsCreateBodyNameMax)- .describe('Human-readable action name. Unique within the team.'),- scanner: zod.uuid().describe('Scanner whose observations this action operates on. Must belong to the same team.'),- enabled: zod.boolean().optional().describe('When false, the scheduler skips this action.'),- is_scanner_digest: zod- .boolean()- .optional()- .describe(- "Marks this action as the scanner's built-in daily digest, the one summary surfaced on the scanner overview. At most one digest per scanner."- ),- trigger_type: zod- .enum(['schedule', 'threshold'])- .describe('\* `schedule` - Schedule\n\* `threshold` - Threshold')- .optional()- .describe(- "What fires the action. MVP supports 'schedule' only.\n\n\* `schedule` - Schedule\n\* `threshold` - Threshold"- ),- mode: zod- .enum(['group_summary', 'alert', 'per_observation'])- .describe('\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation')- .optional()- .describe(- "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation"- ),- trigger_config: zod- .object({- rrule: zod- .string()- .optional()- .describe(- 'iCal RRULE string controlling the schedule cadence (no DTSTART — the start is managed separately).'- ),- timezone: zod- .string()- .default(visionActionsCreateBodyTriggerConfigOneTimezoneDefault)- .describe("IANA timezone name the RRULE is expanded in, e.g. 'Europe\/Prague'. Defaults to 'UTC'."),- })- .describe('Schedule trigger parameters. Threshold triggers are reserved and rejected at the API for now.')- .optional()- .describe('Trigger parameters. For schedule triggers: {rrule, timezone}.'),- selection: zod- .object({- scanner_ids: zod- .array(zod.string())- .optional()- .describe('Restrict to observations produced by these scanner IDs. Defaults to the bound scanner.'),- verdict: zod- .array(- zod- .enum(['yes', 'no', 'inconclusive'])- .describe('\* `yes` - yes\n\* `no` - no\n\* `inconclusive` - inconclusive')- )- .optional()- .describe('Only run on monitor observations with one of these verdicts (yes\/no\/inconclusive).'),- tags: zod- .array(zod.string())- .optional()- .describe('Only run on classifier observations carrying any of these tags (fixed or freeform).'),- min_score: zod- .number()- .optional()- .describe('Only run on scorer observations with a score at or above this value (inclusive).'),- max_score: zod- .number()- .optional()- .describe('Only run on scorer observations with a score at or below this value (inclusive).'),- })- .describe(- 'The action\'s targeting predicate (\"run this on…\") applied when gathering observations. All keys\noptional; this typed shape is the allowlist, so unknown input keys are dropped rather than persisted.'- )- .optional()- .describe("Targeting predicate: which of the scanner's observations this action runs on."),- synthesis_config: zod- .object({- prompt_guide: zod- .string()- .max(visionActionsCreateBodySynthesisConfigOnePromptGuideMax)- .optional()- .describe('Free-form guidance steering how the group summary is written.'),- })- .describe('Options for the group-summary synthesis step.')- .optional()- .describe('Synthesis options for the group summary, e.g. {prompt_guide}.'),- alert_config: zod- .object({- frequency: zod- .enum(['every_match', 'on_breach'])- .describe('\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed')- .default(visionActionsCreateBodyAlertConfigOneFrequencyDefault)- .describe(- "'every_match' notifies about every new matching observation (batched per check); 'on_breach' notifies once when the threshold condition starts holding. Defaults to 'on_breach'.\n\n\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed"- ),- metric: zod- .enum(['count', 'avg_score'])- .describe('\* `count` - Count of matching observations\n\* `avg_score` - Average score')- .default(visionActionsCreateBodyAlertConfigOneMetricDefault)- .describe(- "What to measure over the window: 'count' of targeted observations, or 'avg_score' (the mean scorer score; scorer scanners only). every_match supports 'count' only.\n\n\* `count` - Count of matching observations\n\* `avg_score` - Average score"- ),- threshold: zod- .number()- .optional()- .describe(- "The alert fires when the metric is at or above ('above') or at or below ('below') this value, per 'direction'. Required for on_breach; ignored for every_match."- ),- direction: zod- .enum(['above', 'below'])- .describe('\* `above` - At or above\n\* `below` - At or below')- .default(visionActionsCreateBodyAlertConfigOneDirectionDefault)- .describe(- "Which side of the threshold breaches: 'above' fires when the metric is at or above it, 'below' when at or below (e.g. an average score dropping under a floor). Both inclusive. Defaults to 'above'; ignored for every_match.\n\n\* `above` - At or above\n\* `below` - At or below"- ),- window_days: zod- .union([zod.literal(1), zod.literal(3), zod.literal(7), zod.literal(14), zod.literal(30)])- .describe('\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days')- .optional()- .describe(- "Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).\n\n\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days"- ),- })- .describe(- "The alert condition for mode='alert', applied after `selection` targeting. 'every_match'\nnotifies about each new match since the previous check; 'on_breach' compares a metric to a\nthreshold over a rolling window and notifies on the transition into breach."- )- .optional()- .describe("Alert condition; required when mode is 'alert', ignored otherwise."),- delivery_config: zod- .array(- zod- .object({- type: zod- .enum(['slack'])- .describe('\* `slack` - Slack')- .describe("Destination channel type. MVP supports 'slack' only.\n\n\* `slack` - Slack"),- integration_id: zod- .number()- .describe('ID of the Slack Integration on this team used to deliver the summary.'),- channel: zod.string().describe('Slack channel ID or name the summary is posted to.'),- })- .describe('A single delivery destination. MVP supports Slack only.')- )- .optional()- .describe('List of delivery destinations the synthesized summary is sent to.'),-})+export const VisionActionsCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(visionActionsCreateBodyNameMax)+ .describe('Human-readable action name. Unique within the team.'),+ scanner: zod+ .uuid()+ .describe('Scanner whose observations this action operates on. Must belong to the same team.'),+ enabled: zod.boolean().optional().describe('When false, the scheduler skips this action.'),+ is_scanner_digest: zod+ .boolean()+ .optional()+ .describe(+ "Marks this action as the scanner's built-in daily digest, the one summary surfaced on the scanner overview. At most one digest per scanner."+ ),+ trigger_type: zod+ .enum(['schedule', 'threshold'])+ .describe('\* `schedule` - Schedule\n\* `threshold` - Threshold')+ .optional()+ .describe(+ "What fires the action. MVP supports 'schedule' only.\n\n\* `schedule` - Schedule\n\* `threshold` - Threshold"+ ),+ mode: zod+ .enum(['group_summary', 'alert', 'per_observation'])+ .describe('\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation')+ .optional()+ .describe(+ "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation"+ ),+ trigger_config: zod+ .object({+ rrule: zod+ .string()+ .optional()+ .describe(+ 'iCal RRULE string controlling the schedule cadence (no DTSTART — the start is managed separately).'+ ),+ timezone: zod+ .string()+ .default(visionActionsCreateBodyTriggerConfigOneTimezoneDefault)+ .describe("IANA timezone name the RRULE is expanded in, e.g. 'Europe\/Prague'. Defaults to 'UTC'."),+ })+ .describe('Schedule trigger parameters. Threshold triggers are reserved and rejected at the API for now.')+ .optional()+ .describe('Trigger parameters. For schedule triggers: {rrule, timezone}.'),+ selection: zod+ .object({+ scanner_ids: zod+ .array(zod.string())+ .optional()+ .describe('Restrict to observations produced by these scanner IDs. Defaults to the bound scanner.'),+ verdict: zod+ .array(+ zod+ .enum(['yes', 'no', 'inconclusive'])+ .describe('\* `yes` - yes\n\* `no` - no\n\* `inconclusive` - inconclusive')+ )+ .optional()+ .describe('Only run on monitor observations with one of these verdicts (yes\/no\/inconclusive).'),+ tags: zod+ .array(zod.string())+ .optional()+ .describe('Only run on classifier observations carrying any of these tags (fixed or freeform).'),+ min_score: zod+ .number()+ .optional()+ .describe('Only run on scorer observations with a score at or above this value (inclusive).'),+ max_score: zod+ .number()+ .optional()+ .describe('Only run on scorer observations with a score at or below this value (inclusive).'),+ })+ .describe(+ 'The action\'s targeting predicate (\"run this on…\") applied when gathering observations. All keys\noptional; this typed shape is the allowlist, so unknown input keys are dropped rather than persisted.'+ )+ .optional()+ .describe("Targeting predicate: which of the scanner's observations this action runs on."),+ synthesis_config: zod+ .object({+ prompt_guide: zod+ .string()+ .max(visionActionsCreateBodySynthesisConfigOnePromptGuideMax)+ .optional()+ .describe('Free-form guidance steering how the group summary is written.'),+ })+ .describe('Options for the group-summary synthesis step.')+ .optional()+ .describe('Synthesis options for the group summary, e.g. {prompt_guide}.'),+ alert_config: zod+ .object({+ frequency: zod+ .enum(['every_match', 'on_breach'])+ .describe('\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed')+ .default(visionActionsCreateBodyAlertConfigOneFrequencyDefault)+ .describe(+ "'every_match' notifies about every new matching observation (batched per check); 'on_breach' notifies once when the threshold condition starts holding. Defaults to 'on_breach'.\n\n\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed"+ ),+ metric: zod+ .enum(['count', 'avg_score'])+ .describe('\* `count` - Count of matching observations\n\* `avg_score` - Average score')+ .default(visionActionsCreateBodyAlertConfigOneMetricDefault)+ .describe(+ "What to measure over the window: 'count' of targeted observations, or 'avg_score' (the mean scorer score; scorer scanners only). every_match supports 'count' only.\n\n\* `count` - Count of matching observations\n\* `avg_score` - Average score"+ ),+ threshold: zod+ .number()+ .optional()+ .describe(+ "The alert fires when the metric is at or above ('above') or at or below ('below') this value, per 'direction'. Required for on_breach; ignored for every_match."+ ),+ direction: zod+ .enum(['above', 'below'])+ .describe('\* `above` - At or above\n\* `below` - At or below')+ .default(visionActionsCreateBodyAlertConfigOneDirectionDefault)+ .describe(+ "Which side of the threshold breaches: 'above' fires when the metric is at or above it, 'below' when at or below (e.g. an average score dropping under a floor). Both inclusive. Defaults to 'above'; ignored for every_match.\n\n\* `above` - At or above\n\* `below` - At or below"+ ),+ window_days: zod+ .union([zod.literal(1), zod.literal(3), zod.literal(7), zod.literal(14), zod.literal(30)])+ .describe('\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days')+ .optional()+ .describe(+ "Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).\n\n\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days"+ ),+ })+ .describe(+ "The alert condition for mode='alert', applied after `selection` targeting. 'every_match'\nnotifies about each new match since the previous check; 'on_breach' compares a metric to a\nthreshold over a rolling window and notifies on the transition into breach."+ )+ .optional()+ .describe("Alert condition; required when mode is 'alert', ignored otherwise."),+ delivery_config: zod+ .array(+ zod+ .object({+ type: zod+ .enum(['slack'])+ .describe('\* `slack` - Slack')+ .describe("Destination channel type. MVP supports 'slack' only.\n\n\* `slack` - Slack"),+ integration_id: zod+ .number()+ .describe('ID of the Slack Integration on this team used to deliver the summary.'),+ channel: zod.string().describe('Slack channel ID or name the summary is posted to.'),+ })+ .describe('A single delivery destination. MVP supports Slack only.')+ )+ .optional()+ .describe('List of delivery destinations the synthesized summary is sent to.'),+ })+ .describe('A Replay Vision action: a scheduled \"and then…\" automation over a scanner\'s observations.')/*** CRUD for Replay Vision actions — scheduled "and then…" automations over a scanner's observations.@@ -180,159 +184,161 @@ export const visionActionsPartialUpdateBodyAlertConfigOneFrequencyDefault = `on_export const visionActionsPartialUpdateBodyAlertConfigOneMetricDefault = `count`export const visionActionsPartialUpdateBodyAlertConfigOneDirectionDefault = `above`-export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod- .string()- .max(visionActionsPartialUpdateBodyNameMax)- .optional()- .describe('Human-readable action name. Unique within the team.'),- scanner: zod- .uuid()- .optional()- .describe('Scanner whose observations this action operates on. Must belong to the same team.'),- enabled: zod.boolean().optional().describe('When false, the scheduler skips this action.'),- is_scanner_digest: zod- .boolean()- .optional()- .describe(- "Marks this action as the scanner's built-in daily digest, the one summary surfaced on the scanner overview. At most one digest per scanner."- ),- trigger_type: zod- .enum(['schedule', 'threshold'])- .describe('\* `schedule` - Schedule\n\* `threshold` - Threshold')- .optional()- .describe(- "What fires the action. MVP supports 'schedule' only.\n\n\* `schedule` - Schedule\n\* `threshold` - Threshold"- ),- mode: zod- .enum(['group_summary', 'alert', 'per_observation'])- .describe('\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation')- .optional()- .describe(- "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation"- ),- trigger_config: zod- .object({- rrule: zod- .string()- .optional()- .describe(- 'iCal RRULE string controlling the schedule cadence (no DTSTART — the start is managed separately).'- ),- timezone: zod- .string()- .default(visionActionsPartialUpdateBodyTriggerConfigOneTimezoneDefault)- .describe("IANA timezone name the RRULE is expanded in, e.g. 'Europe\/Prague'. Defaults to 'UTC'."),- })- .describe('Schedule trigger parameters. Threshold triggers are reserved and rejected at the API for now.')- .optional()- .describe('Trigger parameters. For schedule triggers: {rrule, timezone}.'),- selection: zod- .object({- scanner_ids: zod- .array(zod.string())- .optional()- .describe('Restrict to observations produced by these scanner IDs. Defaults to the bound scanner.'),- verdict: zod- .array(- zod- .enum(['yes', 'no', 'inconclusive'])- .describe('\* `yes` - yes\n\* `no` - no\n\* `inconclusive` - inconclusive')- )- .optional()- .describe('Only run on monitor observations with one of these verdicts (yes\/no\/inconclusive).'),- tags: zod- .array(zod.string())- .optional()- .describe('Only run on classifier observations carrying any of these tags (fixed or freeform).'),- min_score: zod- .number()- .optional()- .describe('Only run on scorer observations with a score at or above this value (inclusive).'),- max_score: zod- .number()- .optional()- .describe('Only run on scorer observations with a score at or below this value (inclusive).'),- })- .describe(- 'The action\'s targeting predicate (\"run this on…\") applied when gathering observations. All keys\noptional; this typed shape is the allowlist, so unknown input keys are dropped rather than persisted.'- )- .optional()- .describe("Targeting predicate: which of the scanner's observations this action runs on."),- synthesis_config: zod- .object({- prompt_guide: zod- .string()- .max(visionActionsPartialUpdateBodySynthesisConfigOnePromptGuideMax)- .optional()- .describe('Free-form guidance steering how the group summary is written.'),- })- .describe('Options for the group-summary synthesis step.')- .optional()- .describe('Synthesis options for the group summary, e.g. {prompt_guide}.'),- alert_config: zod- .object({- frequency: zod- .enum(['every_match', 'on_breach'])- .describe('\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed')- .default(visionActionsPartialUpdateBodyAlertConfigOneFrequencyDefault)- .describe(- "'every_match' notifies about every new matching observation (batched per check); 'on_breach' notifies once when the threshold condition starts holding. Defaults to 'on_breach'.\n\n\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed"- ),- metric: zod- .enum(['count', 'avg_score'])- .describe('\* `count` - Count of matching observations\n\* `avg_score` - Average score')- .default(visionActionsPartialUpdateBodyAlertConfigOneMetricDefault)- .describe(- "What to measure over the window: 'count' of targeted observations, or 'avg_score' (the mean scorer score; scorer scanners only). every_match supports 'count' only.\n\n\* `count` - Count of matching observations\n\* `avg_score` - Average score"- ),- threshold: zod- .number()- .optional()- .describe(- "The alert fires when the metric is at or above ('above') or at or below ('below') this value, per 'direction'. Required for on_breach; ignored for every_match."- ),- direction: zod- .enum(['above', 'below'])- .describe('\* `above` - At or above\n\* `below` - At or below')- .default(visionActionsPartialUpdateBodyAlertConfigOneDirectionDefault)- .describe(- "Which side of the threshold breaches: 'above' fires when the metric is at or above it, 'below' when at or below (e.g. an average score dropping under a floor). Both inclusive. Defaults to 'above'; ignored for every_match.\n\n\* `above` - At or above\n\* `below` - At or below"- ),- window_days: zod- .union([zod.literal(1), zod.literal(3), zod.literal(7), zod.literal(14), zod.literal(30)])- .describe('\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days')- .optional()- .describe(- "Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).\n\n\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days"- ),- })- .describe(- "The alert condition for mode='alert', applied after `selection` targeting. 'every_match'\nnotifies about each new match since the previous check; 'on_breach' compares a metric to a\nthreshold over a rolling window and notifies on the transition into breach."- )- .optional()- .describe("Alert condition; required when mode is 'alert', ignored otherwise."),- delivery_config: zod- .array(- zod- .object({- type: zod- .enum(['slack'])- .describe('\* `slack` - Slack')- .describe("Destination channel type. MVP supports 'slack' only.\n\n\* `slack` - Slack"),- integration_id: zod- .number()- .describe('ID of the Slack Integration on this team used to deliver the summary.'),- channel: zod.string().describe('Slack channel ID or name the summary is posted to.'),- })- .describe('A single delivery destination. MVP supports Slack only.')- )- .optional()- .describe('List of delivery destinations the synthesized summary is sent to.'),-})+export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(visionActionsPartialUpdateBodyNameMax)+ .optional()+ .describe('Human-readable action name. Unique within the team.'),+ scanner: zod+ .uuid()+ .optional()+ .describe('Scanner whose observations this action operates on. Must belong to the same team.'),+ enabled: zod.boolean().optional().describe('When false, the scheduler skips this action.'),+ is_scanner_digest: zod+ .boolean()+ .optional()+ .describe(+ "Marks this action as the scanner's built-in daily digest, the one summary surfaced on the scanner overview. At most one digest per scanner."+ ),+ trigger_type: zod+ .enum(['schedule', 'threshold'])+ .describe('\* `schedule` - Schedule\n\* `threshold` - Threshold')+ .optional()+ .describe(+ "What fires the action. MVP supports 'schedule' only.\n\n\* `schedule` - Schedule\n\* `threshold` - Threshold"+ ),+ mode: zod+ .enum(['group_summary', 'alert', 'per_observation'])+ .describe('\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation')+ .optional()+ .describe(+ "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation"+ ),+ trigger_config: zod+ .object({+ rrule: zod+ .string()+ .optional()+ .describe(+ 'iCal RRULE string controlling the schedule cadence (no DTSTART — the start is managed separately).'+ ),+ timezone: zod+ .string()+ .default(visionActionsPartialUpdateBodyTriggerConfigOneTimezoneDefault)+ .describe("IANA timezone name the RRULE is expanded in, e.g. 'Europe\/Prague'. Defaults to 'UTC'."),+ })+ .describe('Schedule trigger parameters. Threshold triggers are reserved and rejected at the API for now.')+ .optional()+ .describe('Trigger parameters. For schedule triggers: {rrule, timezone}.'),+ selection: zod+ .object({+ scanner_ids: zod+ .array(zod.string())+ .optional()+ .describe('Restrict to observations produced by these scanner IDs. Defaults to the bound scanner.'),+ verdict: zod+ .array(+ zod+ .enum(['yes', 'no', 'inconclusive'])+ .describe('\* `yes` - yes\n\* `no` - no\n\* `inconclusive` - inconclusive')+ )+ .optional()+ .describe('Only run on monitor observations with one of these verdicts (yes\/no\/inconclusive).'),+ tags: zod+ .array(zod.string())+ .optional()+ .describe('Only run on classifier observations carrying any of these tags (fixed or freeform).'),+ min_score: zod+ .number()+ .optional()+ .describe('Only run on scorer observations with a score at or above this value (inclusive).'),+ max_score: zod+ .number()+ .optional()+ .describe('Only run on scorer observations with a score at or below this value (inclusive).'),+ })+ .describe(+ 'The action\'s targeting predicate (\"run this on…\") applied when gathering observations. All keys\noptional; this typed shape is the allowlist, so unknown input keys are dropped rather than persisted.'+ )+ .optional()+ .describe("Targeting predicate: which of the scanner's observations this action runs on."),+ synthesis_config: zod+ .object({+ prompt_guide: zod+ .string()+ .max(visionActionsPartialUpdateBodySynthesisConfigOnePromptGuideMax)+ .optional()+ .describe('Free-form guidance steering how the group summary is written.'),+ })+ .describe('Options for the group-summary synthesis step.')+ .optional()+ .describe('Synthesis options for the group summary, e.g. {prompt_guide}.'),+ alert_config: zod+ .object({+ frequency: zod+ .enum(['every_match', 'on_breach'])+ .describe('\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed')+ .default(visionActionsPartialUpdateBodyAlertConfigOneFrequencyDefault)+ .describe(+ "'every_match' notifies about every new matching observation (batched per check); 'on_breach' notifies once when the threshold condition starts holding. Defaults to 'on_breach'.\n\n\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed"+ ),+ metric: zod+ .enum(['count', 'avg_score'])+ .describe('\* `count` - Count of matching observations\n\* `avg_score` - Average score')+ .default(visionActionsPartialUpdateBodyAlertConfigOneMetricDefault)+ .describe(+ "What to measure over the window: 'count' of targeted observations, or 'avg_score' (the mean scorer score; scorer scanners only). every_match supports 'count' only.\n\n\* `count` - Count of matching observations\n\* `avg_score` - Average score"+ ),+ threshold: zod+ .number()+ .optional()+ .describe(+ "The alert fires when the metric is at or above ('above') or at or below ('below') this value, per 'direction'. Required for on_breach; ignored for every_match."+ ),+ direction: zod+ .enum(['above', 'below'])+ .describe('\* `above` - At or above\n\* `below` - At or below')+ .default(visionActionsPartialUpdateBodyAlertConfigOneDirectionDefault)+ .describe(+ "Which side of the threshold breaches: 'above' fires when the metric is at or above it, 'below' when at or below (e.g. an average score dropping under a floor). Both inclusive. Defaults to 'above'; ignored for every_match.\n\n\* `above` - At or above\n\* `below` - At or below"+ ),+ window_days: zod+ .union([zod.literal(1), zod.literal(3), zod.literal(7), zod.literal(14), zod.literal(30)])+ .describe('\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days')+ .optional()+ .describe(+ "Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).\n\n\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days"+ ),+ })+ .describe(+ "The alert condition for mode='alert', applied after `selection` targeting. 'every_match'\nnotifies about each new match since the previous check; 'on_breach' compares a metric to a\nthreshold over a rolling window and notifies on the transition into breach."+ )+ .optional()+ .describe("Alert condition; required when mode is 'alert', ignored otherwise."),+ delivery_config: zod+ .array(+ zod+ .object({+ type: zod+ .enum(['slack'])+ .describe('\* `slack` - Slack')+ .describe("Destination channel type. MVP supports 'slack' only.\n\n\* `slack` - Slack"),+ integration_id: zod+ .number()+ .describe('ID of the Slack Integration on this team used to deliver the summary.'),+ channel: zod.string().describe('Slack channel ID or name the summary is posted to.'),+ })+ .describe('A single delivery destination. MVP supports Slack only.')+ )+ .optional()+ .describe('List of delivery destinations the synthesized summary is sent to.'),+ })+ .describe('A Replay Vision action: a scheduled \"and then…\" automation over a scanner\'s observations.')/**- * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires session recording edit access.+ * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires editor access to the scanner.*/export const visionObservationsLabelCreateBodyFeedbackDefault = ``export const visionObservationsLabelCreateBodyFeedbackMax = 5000@@ -360,72 +366,76 @@ export const visionScannersCreateBodyDescriptionMax = 1000export const visionScannersCreateBodySamplingRateMin = 0export const visionScannersCreateBodySamplingRateMax = 1-export const VisionScannersCreateBody = /* @__PURE__ */ zod.object({- name: zod- .string()- .max(visionScannersCreateBodyNameMax)- .describe('Human-readable scanner name. Unique within the team.'),- description: zod- .string()- .max(visionScannersCreateBodyDescriptionMax)- .optional()- .describe('Free-form description shown in the scanner management UI.'),- scanner_type: zod- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])- .describe(- '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'- )- .describe(- 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'- ),- scanner_config: zod- .unknown()- .describe(- 'Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`.'- ),- query: zod- .unknown()- .optional()- .describe(- 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`\/`date_to` are stripped on save — the schedule controls time, not the user.'- ),- sampling_rate: zod- .number()- .min(visionScannersCreateBodySamplingRateMin)- .max(visionScannersCreateBodySamplingRateMax)- .optional()- .describe(- '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'- ),- sampling_mode: zod- .enum(['focused', 'balanced', 'comprehensive'])- .describe('\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive')- .optional()- .describe(- 'Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive'- ),- provider: zod- .enum(['google'])- .describe('\* `google` - Google')- .optional()- .describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),- model: zod- .enum(['gemini-3.5-flash-lite', 'gemini-3.6-flash'])- .describe('\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3.6-flash` - Gemini 3.6 Flash')- .describe(- 'Concrete model to use for this scanner.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3.6-flash` - Gemini 3.6 Flash'- ),- enabled: zod- .boolean()- .optional()- .describe("When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work."),- emits_signals: zod- .boolean()- .optional()- .describe(- 'When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals.'- ),-})+export const VisionScannersCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(visionScannersCreateBodyNameMax)+ .describe('Human-readable scanner name. Unique within the team.'),+ description: zod+ .string()+ .max(visionScannersCreateBodyDescriptionMax)+ .optional()+ .describe('Free-form description shown in the scanner management UI.'),+ scanner_type: zod+ .enum(['monitor', 'classifier', 'scorer', 'summarizer'])+ .describe(+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'+ )+ .describe(+ 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'+ ),+ scanner_config: zod+ .unknown()+ .describe(+ 'Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`.'+ ),+ query: zod+ .unknown()+ .optional()+ .describe(+ 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`\/`date_to` are stripped on save — the schedule controls time, not the user.'+ ),+ sampling_rate: zod+ .number()+ .min(visionScannersCreateBodySamplingRateMin)+ .max(visionScannersCreateBodySamplingRateMax)+ .optional()+ .describe(+ '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'+ ),+ sampling_mode: zod+ .enum(['focused', 'balanced', 'comprehensive'])+ .describe('\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive')+ .optional()+ .describe(+ 'Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive'+ ),+ provider: zod+ .enum(['google'])+ .describe('\* `google` - Google')+ .optional()+ .describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),+ model: zod+ .enum(['gemini-3.5-flash-lite', 'gemini-3.6-flash'])+ .describe('\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3.6-flash` - Gemini 3.6 Flash')+ .describe(+ 'Concrete model to use for this scanner.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3.6-flash` - Gemini 3.6 Flash'+ ),+ enabled: zod+ .boolean()+ .optional()+ .describe(+ "When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work."+ ),+ emits_signals: zod+ .boolean()+ .optional()+ .describe(+ 'When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals.'+ ),+ })+ .describe('A Replay Vision scanner: its type, targeting query, and AI configuration.')/*** CRUD for Replay Vision scanners.@@ -437,76 +447,80 @@ export const visionScannersPartialUpdateBodyDescriptionMax = 1000export const visionScannersPartialUpdateBodySamplingRateMin = 0export const visionScannersPartialUpdateBodySamplingRateMax = 1-export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod- .string()- .max(visionScannersPartialUpdateBodyNameMax)- .optional()- .describe('Human-readable scanner name. Unique within the team.'),- description: zod- .string()- .max(visionScannersPartialUpdateBodyDescriptionMax)- .optional()- .describe('Free-form description shown in the scanner management UI.'),- scanner_type: zod- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])- .describe(- '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'- )- .optional()- .describe(- 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'- ),- scanner_config: zod- .unknown()- .optional()- .describe(- 'Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`.'- ),- query: zod- .unknown()- .optional()- .describe(- 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`\/`date_to` are stripped on save — the schedule controls time, not the user.'- ),- sampling_rate: zod- .number()- .min(visionScannersPartialUpdateBodySamplingRateMin)- .max(visionScannersPartialUpdateBodySamplingRateMax)- .optional()- .describe(- '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'- ),- sampling_mode: zod- .enum(['focused', 'balanced', 'comprehensive'])- .describe('\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive')- .optional()- .describe(- 'Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive'- ),- provider: zod- .enum(['google'])- .describe('\* `google` - Google')- .optional()- .describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),- model: zod- .enum(['gemini-3.5-flash-lite', 'gemini-3.6-flash'])- .describe('\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3.6-flash` - Gemini 3.6 Flash')- .optional()- .describe(- 'Concrete model to use for this scanner.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3.6-flash` - Gemini 3.6 Flash'- ),- enabled: zod- .boolean()- .optional()- .describe("When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work."),- emits_signals: zod- .boolean()- .optional()- .describe(- 'When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals.'- ),-})+export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(visionScannersPartialUpdateBodyNameMax)+ .optional()+ .describe('Human-readable scanner name. Unique within the team.'),+ description: zod+ .string()+ .max(visionScannersPartialUpdateBodyDescriptionMax)+ .optional()+ .describe('Free-form description shown in the scanner management UI.'),+ scanner_type: zod+ .enum(['monitor', 'classifier', 'scorer', 'summarizer'])+ .describe(+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'+ )+ .optional()+ .describe(+ 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'+ ),+ scanner_config: zod+ .unknown()+ .optional()+ .describe(+ 'Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`.'+ ),+ query: zod+ .unknown()+ .optional()+ .describe(+ 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`\/`date_to` are stripped on save — the schedule controls time, not the user.'+ ),+ sampling_rate: zod+ .number()+ .min(visionScannersPartialUpdateBodySamplingRateMin)+ .max(visionScannersPartialUpdateBodySamplingRateMax)+ .optional()+ .describe(+ '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'+ ),+ sampling_mode: zod+ .enum(['focused', 'balanced', 'comprehensive'])+ .describe('\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive')+ .optional()+ .describe(+ 'Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive'+ ),+ provider: zod+ .enum(['google'])+ .describe('\* `google` - Google')+ .optional()+ .describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),+ model: zod+ .enum(['gemini-3.5-flash-lite', 'gemini-3.6-flash'])+ .describe('\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3.6-flash` - Gemini 3.6 Flash')+ .optional()+ .describe(+ 'Concrete model to use for this scanner.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3.6-flash` - Gemini 3.6 Flash'+ ),+ enabled: zod+ .boolean()+ .optional()+ .describe(+ "When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work."+ ),+ emits_signals: zod+ .boolean()+ .optional()+ .describe(+ 'When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals.'+ ),+ })+ .describe('A Replay Vision scanner: its type, targeting query, and AI configuration.')/*** Save the users this scanner matched as a static cohort, for surveys, funnels, and retention analysis.@@ -578,7 +592,7 @@ export const VisionScannersObserveCreateBody = /* @__PURE__ */ zod.describe('Body of POST \/vision\/scanners\/{id}\/observe\/.')/**- * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires session recording edit access.+ * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires editor access to the scanner.*/export const visionScannersObservationsLabelCreateBodyFeedbackDefault = ``export const visionScannersObservationsLabelCreateBodyFeedbackMax = 5000diff --git a/products/replay_vision/frontend/observations/ObservationLabelControl.tsx b/products/replay_vision/frontend/observations/ObservationLabelControl.tsxindex 7af02185ee35..957c33861d5f 100644--- a/products/replay_vision/frontend/observations/ObservationLabelControl.tsx+++ b/products/replay_vision/frontend/observations/ObservationLabelControl.tsx@@ -4,37 +4,41 @@ import { useState } from 'react'import { IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled } from '@posthog/icons'import { LemonButton, LemonTextArea, Tooltip } from '@posthog/lemon-ui'-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'--import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { AccessControlLevel } from '~/types'import type { ReplayObservationLabelApi } from '../generated/api.schemas'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'import { observationLabelLogic } from './observationLabelLogic'export interface ObservationLabelProps {observationId: stringinitialLabel?: ReplayObservationLabelApi | nullonChange?: (label: ReplayObservationLabelApi | null) => void+ /** The observation's scanner's effective access level, for object-level overrides. Falls back to the+ * resource default when the caller doesn't have the scanner loaded. */+ scannerUserAccessLevel?: AccessControlLevel | null}const FEEDBACK_PLACEHOLDER = 'Optional: what did it get right or wrong, and why? Used to improve the prompt.'-function useEditAccess(): string | null {- // Editing the shared rating mutates team-wide data, so it needs edit access (matches the "Edit scanner" gate).- return getAccessControlDisabledReason(AccessControlResourceType.SessionRecording, AccessControlLevel.Editor)+function useEditAccess(scannerUserAccessLevel?: AccessControlLevel | null): string | null {+ // Editing the shared rating mutates team-wide data derived from a recording, so it needs the same+ // bar as the backend label write: replay_scanner editor AND session_recording viewer.+ return getReplayVisionEditDisabledReason(scannerUserAccessLevel)}function FeedbackEditor({observationId,initialLabel,onChange,+ scannerUserAccessLevel,compact,onBlur,}: ObservationLabelProps & { compact: boolean; onBlur?: () => void }): JSX.Element {const logic = observationLabelLogic({ observationId, initialLabel, onChange })const { label, saving, feedbackDraft } = useValues(logic)const { setFeedbackDraft } = useActions(logic)- const canEdit = !useEditAccess()+ const canEdit = !useEditAccess(scannerUserAccessLevel)const feedbackSynced = feedbackDraft === (label?.feedback ?? '')return (@@ -69,11 +73,12 @@ export function ObservationLabelFeedback({observationId,initialLabel,onChange,+ scannerUserAccessLevel,}: ObservationLabelProps): JSX.Element {const logic = observationLabelLogic({ observationId, initialLabel, onChange })const { label, feedbackDraft } = useValues(logic)const [editing, setEditing] = useState(false)- const canEdit = !useEditAccess()+ const canEdit = !useEditAccess(scannerUserAccessLevel)if (!label) {return (@@ -104,6 +109,7 @@ export function ObservationLabelFeedback({observationId={observationId}initialLabel={initialLabel}onChange={onChange}+ scannerUserAccessLevel={scannerUserAccessLevel}compactonBlur={() => setEditing(false)}/>@@ -120,6 +126,7 @@ export function ObservationLabelControl({observationId,initialLabel,onChange,+ scannerUserAccessLevel,compact = false,}: ObservationLabelProps & { compact?: boolean }): JSX.Element {const logic = observationLabelLogic({ observationId, initialLabel, onChange })@@ -128,7 +135,7 @@ export function ObservationLabelControl({const thumbsUp = label?.is_correct === trueconst thumbsDown = label?.is_correct === false- const editDisabledReason = useEditAccess()+ const editDisabledReason = useEditAccess(scannerUserAccessLevel)// Clicking the active thumb again removes the rating.const buttons = (@@ -171,6 +178,7 @@ export function ObservationLabelControl({observationId={observationId}initialLabel={initialLabel}onChange={onChange}+ scannerUserAccessLevel={scannerUserAccessLevel}compact={false}/>)}diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsxindex 56fa9830c860..7544302d0b57 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx@@ -17,7 +17,6 @@ import {} from '@posthog/icons'import { LemonButton, LemonCard, LemonTag, Link, SpinnerOverlay } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { NotFound } from 'lib/components/NotFound'import { TZLabel } from 'lib/components/TZLabel'import { FEATURE_FLAGS } from 'lib/constants'@@ -38,7 +37,6 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'-import { AccessControlLevel, AccessControlResourceType } from '~/types'import { BooleanTag } from '../components/BooleanTag'import { CardHeader } from '../components/CardHeader'@@ -53,6 +51,7 @@ import {import { ObservationProgressBar } from '../components/ObservationProgressBar'import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'import { ScannerTypeBadge } from '../components/ScannerTypeBadge'+import { replayScannerLogic } from '../replay_scanners/replayScannerLogic'import {type ClassifierScannerConfig,type MonitorScannerConfig,@@ -67,6 +66,7 @@ import {OBSERVATION_TRIGGER_TAG,type ScannerType,} from '../replay_scanners/types'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'import { ObservationLabelControl } from './ObservationLabelControl'import { neighborFilterParams, observationDetailUrl, replayObservationLogic } from './replayObservationLogic'import { replayObservationSceneLogic } from './replayObservationSceneLogic'@@ -130,6 +130,10 @@ export function ReplayObservationSceneComponent(): JSX.Element {const { observation, observationLoading, retrying } = useValues(observationLogic)const { retryObservation } = useActions(observationLogic)+ // Hooks can't follow the early returns below, and the scanner id isn't known until `observation`+ // loads — 'new' is the sentinel replayScannerLogic already uses to skip its fetch, so this is a+ // harmless placeholder until the real id is available and the logic remounts keyed on it.+ const { scanner } = useValues(replayScannerLogic({ id: observation?.scanner_id ?? 'new' }))if (!featureFlags[FEATURE_FLAGS.REPLAY_VISION]) {// Flags load asynchronously, so wait for them before deciding the page doesn't exist.@@ -350,21 +354,17 @@ export function ReplayObservationSceneComponent(): JSX.Element {</LabeledRow>)}<div>- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}+ <LemonButton+ type="primary"+ size="small"+ icon={<IconRefresh />}+ onClick={() => retryObservation()}+ loading={retrying}+ disabledReason={getReplayVisionEditDisabledReason(scanner?.user_access_level)}+ data-attr="vision-observation-detail-retry">- <LemonButton- type="primary"- size="small"- icon={<IconRefresh />}- onClick={() => retryObservation()}- loading={retrying}- data-attr="vision-observation-detail-retry"- >- Retry scan- </LemonButton>- </AccessControlAction>+ Retry scan+ </LemonButton></div></div>)}diff --git a/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsxindex 4a3ccf00ff2c..c905ae653d2e 100644--- a/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx@@ -31,6 +31,7 @@ import {VisionAlertDirectionEnumApi,VisionAlertMetricEnumApi,} from '../generated/api.schemas'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'import { actionEditorSceneLogic } from './actionEditorSceneLogic'import { DEFAULT_CADENCE } from './cadence'import { replayScannerLogic } from './replayScannerLogic'@@ -579,6 +580,10 @@ export function ActionEditorSceneComponent(): JSX.Element {useValues(actionEditorSceneLogic)const { featureFlags, receivedFeatureFlags } = useValues(featureFlagLogic)const { featureFlagsTimedOut } = useValues(appLogic)+ // Hooks can't be skipped, and effectiveScannerId can be empty before the action/scanner resolve —+ // 'new' is the sentinel replayScannerLogic already uses to skip its fetch, a harmless placeholder+ // until the real id is available and the logic remounts keyed on it.+ const { scanner } = useValues(replayScannerLogic({ id: effectiveScannerId || 'new' }))if (!featureFlags[FEATURE_FLAGS.REPLAY_VISION] || !featureFlags[FEATURE_FLAGS.REPLAY_VISION_ACTIONS]) {// Flags load asynchronously, so wait for them before deciding the page doesn't exist.@@ -703,7 +708,10 @@ export function ActionEditorSceneComponent(): JSX.Element {htmlType="submit"form="action-editor-form"loading={isActionFormSubmitting}- disabledReason={!isAlert && noDays ? 'Pick at least one day to run on' : undefined}+ disabledReason={+ getReplayVisionEditDisabledReason(scanner?.user_access_level) ??+ (!isAlert && noDays ? 'Pick at least one day to run on' : undefined)+ }data-attr="vision-action-editor-save">{isNew ? (isAlert ? 'Create alert' : 'Create summary') : 'Save'}diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsxindex 9ab7ce05f09f..67c2c63b8068 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx@@ -3,7 +3,6 @@ import { useActions, useValues } from 'kea'import { IconSparkles } from '@posthog/icons'import { LemonBanner, LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { NotFound } from 'lib/components/NotFound'import { FEATURE_FLAGS } from 'lib/constants'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'@@ -16,11 +15,11 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'-import { AccessControlLevel, AccessControlResourceType } from '~/types'import { IngestionLimitBanner } from '../components/IngestionLimitBanner'import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'import { visionQuotaLogic } from '../logics/visionQuotaLogic'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'import { formatCredits } from '../utils/credits'import { quotaBannerState } from '../utils/quotaProjection'import { ObservationSearchMaxChat } from './components/ObservationSearchMaxChat'@@ -90,20 +89,16 @@ export function ReplayScannerSceneComponent(): JSX.Element {Improve scanner</LemonButton>)}- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}+ <LemonButton+ type="primary"+ size="small"+ to={urls.replayVisionScannerConfigure(scannerId)}+ disabledReason={getReplayVisionEditDisabledReason(scanner.user_access_level)}+ data-attr="vision-scanner-edit"+ data-ph-capture-attribute-scanner-type={scanner.scanner_type}>- <LemonButton- type="primary"- size="small"- to={urls.replayVisionScannerConfigure(scannerId)}- data-attr="vision-scanner-edit"- data-ph-capture-attribute-scanner-type={scanner.scanner_type}- >- Edit scanner- </LemonButton>- </AccessControlAction>+ Edit scanner+ </LemonButton><ReplayVisionFeedbackButton /></>}@@ -152,7 +147,12 @@ export function ReplayScannerSceneComponent(): JSX.Element {actionsTabEnabled && {key: ReplayScannerTab.Actions,label: 'Summaries and alerts',- content: <VisionActionsTab scannerId={scannerId} />,+ content: (+ <VisionActionsTab+ scannerId={scannerId}+ scannerUserAccessLevel={scanner.user_access_level}+ />+ ),},]}/>diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex a6dca82efec2..bd8be6d1a1ef 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -6,7 +6,6 @@ import { IconPencil, IconPlus, IconRefresh, IconSearch, IconTrash } from '@posthimport { LemonButton, LemonInput, LemonSwitch, LemonTable, Link, Spinner, SpinnerOverlay } from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { NotFound } from 'lib/components/NotFound'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'import { FEATURE_FLAGS } from 'lib/constants'@@ -21,12 +20,12 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'-import { AccessControlLevel, AccessControlResourceType } from '~/types'import { FilterPill } from '../components/FilterPill'import { IngestionLimitBanner } from '../components/IngestionLimitBanner'import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'import { ScannerTypeBadge } from '../components/ScannerTypeBadge'+import { getReplayVisionDeleteDisabledReason, getReplayVisionEditDisabledReason } from '../utils/accessControl'import { formatCredits } from '../utils/credits'import { VisionMetrics } from './components/VisionMetrics'import { type ScannersSorting, SCANNERS_PAGE_SIZE, replayScannersLogic } from './replayScannersLogic'@@ -96,20 +95,19 @@ export function ReplayScannersScene(): JSX.Element {key: 'enabled',render: (_, scanner) => (<div className="flex items-center gap-2">- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonSwitch- checked={scanner.enabled}- onChange={() => toggleScannerEnabled(scanner.id)}- disabledReason={togglingIds.includes(scanner.id) ? 'Updating…' : undefined}- size="small"- data-attr="vision-scanner-toggle-enabled"- data-ph-capture-attribute-scanner-type={scanner.scanner_type}- data-ph-capture-attribute-will-be-enabled={!scanner.enabled}- />- </AccessControlAction>+ <LemonSwitch+ checked={scanner.enabled}+ onChange={() => toggleScannerEnabled(scanner.id)}+ disabledReason={+ togglingIds.includes(scanner.id)+ ? 'Updating…'+ : getReplayVisionEditDisabledReason(scanner.user_access_level)+ }+ size="small"+ data-attr="vision-scanner-toggle-enabled"+ data-ph-capture-attribute-scanner-type={scanner.scanner_type}+ data-ph-capture-attribute-will-be-enabled={!scanner.enabled}+ /><span className={`inline-block min-w-[4.5rem] ${scanner.enabled ? 'text-success' : 'text-muted'}`}>{scanner.enabled ? 'Enabled' : 'Disabled'}</span>@@ -157,48 +155,43 @@ export function ReplayScannersScene(): JSX.Element {key: 'actions',render: (_, scanner) => (<div className="flex gap-1">- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- size="small"- type="secondary"- icon={<IconPencil />}- to={urls.replayVision(scanner.id)}- tooltip="Edit"- data-attr="vision-scanner-edit-row"- data-ph-capture-attribute-scanner-type={scanner.scanner_type}- />- </AccessControlAction>- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- size="small"- type="secondary"- status="danger"- icon={<IconTrash />}- loading={deletingIds.includes(scanner.id)}- disabledReason={deletingIds.includes(scanner.id) ? 'Deleting…' : undefined}- onClick={() =>- LemonDialog.open({- title: `Delete "${scanner.name || 'Untitled scanner'}"?`,- description: 'This cannot be undone.',- primaryButton: {- children: 'Delete',- status: 'danger',- onClick: () => deleteScanner(scanner.id),- },- secondaryButton: { children: 'Cancel' },- })- }- tooltip="Delete"- data-attr="vision-scanner-delete"- data-ph-capture-attribute-scanner-type={scanner.scanner_type}- />- </AccessControlAction>+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconPencil />}+ to={urls.replayVision(scanner.id)}+ disabledReason={getReplayVisionEditDisabledReason(scanner.user_access_level)}+ tooltip="Edit"+ data-attr="vision-scanner-edit-row"+ data-ph-capture-attribute-scanner-type={scanner.scanner_type}+ />+ <LemonButton+ size="small"+ type="secondary"+ status="danger"+ icon={<IconTrash />}+ loading={deletingIds.includes(scanner.id)}+ disabledReason={+ deletingIds.includes(scanner.id)+ ? 'Deleting…'+ : getReplayVisionDeleteDisabledReason(scanner.user_access_level)+ }+ onClick={() =>+ LemonDialog.open({+ title: `Delete "${scanner.name || 'Untitled scanner'}"?`,+ description: 'This cannot be undone.',+ primaryButton: {+ children: 'Delete',+ status: 'danger',+ onClick: () => deleteScanner(scanner.id),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+ tooltip="Delete"+ data-attr="vision-scanner-delete"+ data-ph-capture-attribute-scanner-type={scanner.scanner_type}+ /></div>),},@@ -213,20 +206,16 @@ export function ReplayScannersScene(): JSX.Element {actions={<><ReplayVisionFeedbackButton />- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlus />}+ to={urls.replayVisionTemplates()}+ disabledReason={getReplayVisionEditDisabledReason()}+ data-attr="vision-scanner-create">- <LemonButton- type="primary"- size="small"- icon={<IconPlus />}- to={urls.replayVisionTemplates()}- data-attr="vision-scanner-create"- >- New scanner- </LemonButton>- </AccessControlAction>+ New scanner+ </LemonButton></>}/>diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsxindex 6f1aeda89eaa..9030b23c4021 100644--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx@@ -33,6 +33,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'import { ScannerTemplatePicker } from './components/ScannerTemplatePicker'import { ScannerTriggers } from './components/ScannerTriggers'import { ScannerTypeConfigEditor } from './components/ScannerTypeConfigEditor'@@ -360,8 +361,10 @@ function EditorFooter({const prevStep = stepIndex > 0 ? visibleSteps[stepIndex - 1] : nullconst nextStep = stepIndex < visibleSteps.length - 1 ? visibleSteps[stepIndex + 1] : null// A broken duration filter (scans nothing) blocks the save — surface it as a disabled reason so the- // button explains itself instead of silently doing nothing.- const saveDisabledReason = durationValidationError ?? undefined+ // button explains itself instead of silently doing nothing. RBAC takes priority: it's the more+ // fundamental blocker, and this must match the backend's create/update requirement exactly — a+ // disabled-looking button that the backend would still accept (or vice versa) is a real bug here.+ const saveDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level) ?? durationValidationErrorreturn (<div className="flex items-center justify-between">@@ -380,6 +383,7 @@ function EditorFooter({<LemonButtontype="primary"loading={isSubmitting}+ disabledReason={saveDisabledReason}onClick={onAdvance}className="ml-auto"data-attr="vision-editor-next"diff --git a/products/replay_vision/frontend/replay_scanners/VisionActionScene.tsx b/products/replay_vision/frontend/replay_scanners/VisionActionScene.tsxindex d7e9bb93cb96..58ce20d22226 100644--- a/products/replay_vision/frontend/replay_scanners/VisionActionScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/VisionActionScene.tsx@@ -3,7 +3,6 @@ import { BindLogic, useValues } from 'kea'import { IconPencil } from '@posthog/icons'import { LemonButton, LemonCard, SpinnerOverlay } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { NotFound } from 'lib/components/NotFound'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -14,12 +13,13 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'-import { AccessControlLevel, AccessControlResourceType } from '~/types'import type { VisionActionApi } from '../generated/api.schemas'import { VisionActionModeEnumApi } from '../generated/api.schemas'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'import { humanizeCadence, parseRruleToCadence } from './cadence'import { VisionActionRuns } from './components/VisionActionRuns'+import { replayScannerLogic } from './replayScannerLogic'import { visionActionRunsLogic } from './visionActionRunsLogic'import { visionActionSceneLogic } from './visionActionSceneLogic'@@ -41,6 +41,9 @@ function ActionOverview({const guidance = action.synthesis_config?.prompt_guide?.trim()const isAlert = action.mode === VisionActionModeEnumApi.Alertconst everyMatch = action.alert_config?.frequency === 'every_match'+ // `action.scanner` is only the id — the action's own user_access_level would just reflect the+ // replay_scanner resource default, not a per-scanner object grant, so load the scanner itself.+ const { scanner } = useValues(replayScannerLogic({ id: action.scanner }))return (<>@@ -57,19 +60,15 @@ function ActionOverview({}resourceType={{ type: 'replay_vision' }}actions={- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}+ <LemonButton+ type="secondary"+ icon={<IconPencil />}+ to={urls.replayVisionActionEdit(action.id)}+ disabledReason={getReplayVisionEditDisabledReason(scanner?.user_access_level)}+ data-attr="vision-action-edit-from-page">- <LemonButton- type="secondary"- icon={<IconPencil />}- to={urls.replayVisionActionEdit(action.id)}- data-attr="vision-action-edit-from-page"- >- Edit- </LemonButton>- </AccessControlAction>+ Edit+ </LemonButton>}/>{!isAlert && (diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsxindex d3af4a6e16b3..20179a2e90ab 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx@@ -12,7 +12,6 @@ import {} from '@posthog/icons'import { LemonCard, LemonSwitch, LemonTag } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { TZLabel } from 'lib/components/TZLabel'import { UniversalFilterButton } from 'lib/components/UniversalFilters/UniversalFilterButton'import { FEATURE_FLAGS } from 'lib/constants'@@ -27,12 +26,13 @@ import {import { filtersFromUniversalFilterGroups } from 'scenes/session-recordings/utils'import { RecordingsQuery } from '~/queries/schema/schema-general'-import { AccessControlLevel, AccessControlResourceType, FilterLogicalOperator } from '~/types'+import { FilterLogicalOperator } from '~/types'import { BooleanTag } from '../../components/BooleanTag'import { CardHeader } from '../../components/CardHeader'import { LabeledRow } from '../../components/LabeledRow'import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { formatCredits } from '../../utils/credits'import { promptUnchangedSince } from '../../utils/labelStats'import { replayScannerLogic } from '../replayScannerLogic'@@ -280,19 +280,15 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):</LabeledRow><LabeledRow label="Status"><div className="flex items-center gap-2">- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonSwitch- checked={scanner.enabled}- onChange={() => toggleEnabled()}- loading={togglingEnabled}- data-attr="vision-scanner-toggle-enabled"- data-ph-capture-attribute-scanner-type={scanner.scanner_type}- data-ph-capture-attribute-will-be-enabled={!scanner.enabled}- />- </AccessControlAction>+ <LemonSwitch+ checked={scanner.enabled}+ onChange={() => toggleEnabled()}+ loading={togglingEnabled}+ disabledReason={getReplayVisionEditDisabledReason(scanner.user_access_level)}+ data-attr="vision-scanner-toggle-enabled"+ data-ph-capture-attribute-scanner-type={scanner.scanner_type}+ data-ph-capture-attribute-will-be-enabled={!scanner.enabled}+ /><span className="text-muted text-xs">{scanner.enabled ? 'Runs automatically on a schedule' : 'Runs on-demand only'}</span>diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsxindex 2c8978fe7b2d..241a9f6d082c 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx@@ -3,26 +3,14 @@ import { useActions, useValues } from 'kea'import { IconPlus } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { TZLabel } from 'lib/components/TZLabel'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { urls } from 'scenes/urls'-import { AccessControlLevel, AccessControlResourceType } from '~/types'-+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { replayScannerLogic } from '../replayScannerLogic'import { scannerDigestLogic } from '../scannerDigestLogic'-function EditorGate({ children }: { children: JSX.Element }): JSX.Element {- return (- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}- >- {children}- </AccessControlAction>- )-}-function CardShell({ children }: { children: React.ReactNode }): JSX.Element {return (<div className="border rounded p-4 flex flex-col gap-2" data-attr="vision-scanner-digest-card">@@ -52,6 +40,8 @@ export function ScannerDigestCard({const logic = scannerDigestLogic({ scannerId, scannerName })const { digest, latestRun, latestRunLoading, digestCreating, expanded, visionActionsLoading } = useValues(logic)const { createDigest, toggleExpanded, toggleActionEnabled } = useActions(logic)+ const { scanner } = useValues(replayScannerLogic({ id: scannerId }))+ const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)if (visionActionsLoading && !digest) {return null@@ -65,18 +55,17 @@ export function ScannerDigestCard({<span className="text-sm text-muted">Get a daily AI summary of what this scanner finds, right here.</span>- <EditorGate>- <LemonButton- type="primary"- size="small"- icon={<IconPlus />}- onClick={createDigest}- loading={digestCreating}- data-attr="vision-scanner-digest-create"- >- Turn on daily digest- </LemonButton>- </EditorGate>+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlus />}+ onClick={createDigest}+ loading={digestCreating}+ disabledReason={editDisabledReason}+ data-attr="vision-scanner-digest-create"+ >+ Turn on daily digest+ </LemonButton></div></CardShell>)@@ -88,16 +77,15 @@ export function ScannerDigestCard({<CardHeader /><div className="flex flex-wrap items-center justify-between gap-2"><span className="text-sm text-muted">The daily digest is paused.</span>- <EditorGate>- <LemonButton- type="secondary"- size="small"- onClick={() => toggleActionEnabled(digest.id)}- data-attr="vision-scanner-digest-resume"- >- Resume- </LemonButton>- </EditorGate>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => toggleActionEnabled(digest.id)}+ disabledReason={editDisabledReason}+ data-attr="vision-scanner-digest-resume"+ >+ Resume+ </LemonButton></div></CardShell>)diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex a88199f8e1e2..3707202c7708 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -3,19 +3,19 @@ import { useActions, useValues } from 'kea'import { IconEye, IconPlay, IconRefresh } from '@posthog/icons'import { LemonButton, LemonInput, LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { urls } from 'scenes/urls'-import { AccessControlLevel, AccessControlResourceType, DateMappingOption } from '~/types'+import { DateMappingOption } from '~/types'import { FilterPill } from '../../components/FilterPill'import { ObservationResultSummary, ObservationStatusTag } from '../../components/ObservationCard'import type { ReplayObservationApi } from '../../generated/api.schemas'import { observationDetailUrl } from '../../observations/replayObservationLogic'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import {OBSERVATIONS_PAGE_SIZE,ObservationStatusValue,@@ -169,20 +169,16 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):<div className="flex items-center gap-1"><ObservationStatusTag status={obs.status} errorReason={obs.error_reason} />{obs.status === 'failed' && (- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- size="xsmall"- type="secondary"- icon={<IconRefresh />}- onClick={() => retryObservation(obs.id)}- loading={retryingObservationIds.includes(obs.id)}- tooltip="Retry scan"- data-attr="vision-observation-retry"- />- </AccessControlAction>+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconRefresh />}+ onClick={() => retryObservation(obs.id)}+ loading={retryingObservationIds.includes(obs.id)}+ disabledReason={getReplayVisionEditDisabledReason(scanner?.user_access_level)}+ tooltip="Retry scan"+ data-attr="vision-observation-retry"+ />)}</div>),diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsxindex 488d8c855093..45c33e47e559 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx@@ -20,11 +20,9 @@ import { getColorVar } from 'lib/colors'import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { urls } from 'scenes/urls'import { themeLogic } from '~/layout/navigation-3000/themeLogic'-import { AccessControlLevel, AccessControlResourceType } from '~/types'import { ObservationResultSummary } from '../../components/ObservationCard'import type {@@ -35,6 +33,7 @@ import type {} from '../../generated/api.schemas'import { visionQuotaLogic } from '../../logics/visionQuotaLogic'import { ObservationLabelControl, ObservationLabelFeedback } from '../../observations/ObservationLabelControl'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { formatCredits } from '../../utils/credits'import { buildChartDayFormatter, fillLabelDays, versionAccuracyStrip } from '../../utils/labelStats'import { readConfidence } from '../../utils/observation'@@ -318,10 +317,7 @@ function ConfigRecommendationPanel({ scannerId }: { scannerId: string }): JSX.Elconst creditsPerTestSession = scanner ? (OBSERVATION_CREDITS_BY_MODEL[scanner.model] ?? 0) : 0const plannedTestCredits = plannedTestSessions * creditsPerTestSessionconst [historyOpen, setHistoryOpen] = useState(false)- const editDisabledReason = getAccessControlDisabledReason(- AccessControlResourceType.SessionRecording,- AccessControlLevel.Editor- )+ const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)const pastSuggestions = suggestionHistory.filter((s) => s.id !== currentSuggestion?.id)@@ -865,6 +861,7 @@ export function ScannerQualityTab({ scannerId }: { scannerId: string }): JSX.EleobservationId={obs.id}initialLabel={obs.label}onChange={(label) => labelChanged(obs.id, label)}+ scannerUserAccessLevel={scanner?.user_access_level}/>),},@@ -877,6 +874,7 @@ export function ScannerQualityTab({ scannerId }: { scannerId: string }): JSX.EleobservationId={obs.id}initialLabel={obs.label}onChange={(label) => labelChanged(obs.id, label)}+ scannerUserAccessLevel={scanner?.user_access_level}/>),},diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsxindex 0be903024ccf..e1ac23d982b1 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx@@ -4,7 +4,6 @@ import { useEffect, useRef, useState } from 'react'import { IconEye, IconPlay } from '@posthog/icons'import { LemonButton, LemonInput, LemonTable, Link } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { humanFriendlyDuration } from 'lib/utils/durations'@@ -15,20 +14,22 @@ import {} from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'import { urls } from 'scenes/urls'-import { AccessControlLevel, AccessControlResourceType, SessionRecordingType } from '~/types'+import { SessionRecordingType } from '~/types'import { ObservationStatusTag } from '../../components/ObservationCard'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { replayScannerLogic } from '../replayScannerLogic'import { IN_PROGRESS_STATUSES, scannerRunTabLogic } from '../scannerRunTabLogic'/** Manual entry: scan one session by pasting its recording ID. */function ScanBySessionId({ scannerId }: { scannerId: string }): JSX.Element {- const { triggeringOnDemandObservation, onDemandObservationSuccessCount } = useValues(+ const { scanner, triggeringOnDemandObservation, onDemandObservationSuccessCount } = useValues(replayScannerLogic({ id: scannerId }))const { triggerOnDemandObservation } = useActions(replayScannerLogic({ id: scannerId }))const [sessionId, setSessionId] = useState('')const lastSeenSuccessCount = useRef(onDemandObservationSuccessCount)+ const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)useEffect(() => {if (onDemandObservationSuccessCount > lastSeenSuccessCount.current) {@@ -63,21 +64,16 @@ function ScanBySessionId({ scannerId }: { scannerId: string }): JSX.Element {fullWidthdata-attr="vision-scanner-scan-session-input"/>- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}+ <LemonButton+ type="primary"+ icon={<IconPlay />}+ onClick={submit}+ loading={triggeringOnDemandObservation}+ disabledReason={editDisabledReason ?? (!trimmed ? 'Paste a session ID first' : undefined)}+ data-attr="vision-scanner-scan-session-submit">- <LemonButton- type="primary"- icon={<IconPlay />}- onClick={submit}- loading={triggeringOnDemandObservation}- disabledReason={!trimmed ? 'Paste a session ID first' : undefined}- data-attr="vision-scanner-scan-session-submit"- >- Scan recording- </LemonButton>- </AccessControlAction>+ Scan recording+ </LemonButton></div></div>)@@ -91,6 +87,8 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {scannerRunTabLogic({ scannerId }))const { setVisibleSessionIds, startScan, startBulkScan } = useActions(scannerRunTabLogic({ scannerId }))+ const { scanner } = useValues(replayScannerLogic({ id: scannerId }))+ const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)// Sync the playlist's visible rows into the logic, which owns the observation lookup and polling.const visibleIdsKey = sessionRecordings.map((recording) => recording.id).join(',')@@ -164,29 +162,25 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {)} else {content = (- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}+ <LemonButton+ fullWidth+ center+ size="small"+ type="secondary"+ icon={<IconPlay />}+ disabledReason={+ editDisabledReason ??+ (scanning+ ? 'Scan in progress…'+ : pendingId && pendingId !== recording.id+ ? 'Another scan is starting…'+ : undefined)+ }+ onClick={() => startScan(recording.id)}+ data-attr="vision-run-scan-recording">- <LemonButton- fullWidth- center- size="small"- type="secondary"- icon={<IconPlay />}- disabledReason={- scanning- ? 'Scan in progress…'- : pendingId && pendingId !== recording.id- ? 'Another scan is starting…'- : undefined- }- onClick={() => startScan(recording.id)}- data-attr="vision-run-scan-recording"- >- Scan recording- </LemonButton>- </AccessControlAction>+ Scan recording+ </LemonButton>)}return <div className="w-44">{content}</div>@@ -222,24 +216,20 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {? { disabledReason: 'Already scanned' }: true,renderActions: ({ selectedKeys, selectedCount, clearSelection }) => (- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlay />}+ loading={bulkScanning}+ disabledReason={editDisabledReason}+ onClick={() => {+ startBulkScan(selectedKeys as string[])+ clearSelection()+ }}+ data-attr="vision-run-bulk-scan">- <LemonButton- type="primary"- size="small"- icon={<IconPlay />}- loading={bulkScanning}- onClick={() => {- startBulkScan(selectedKeys as string[])- clearSelection()- }}- data-attr="vision-run-bulk-scan"- >- Scan {selectedCount} selected- </LemonButton>- </AccessControlAction>+ Scan {selectedCount} selected+ </LemonButton>),}}/>diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsxindex 3c3d9b2e9ddb..10630ef6cc2e 100644--- a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx@@ -1,11 +1,12 @@import { BindLogic, useActions, useValues } from 'kea'+import { cloneElement, ReactElement } from 'react'import * as xRayPng from '@posthog/brand/hoggies/png/x-ray'import { IconPencil, IconPlus, IconTrash } from '@posthog/icons'import { LemonButton, LemonSwitch, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'-import { AccessControlAction } from 'lib/components/AccessControlAction'+import { AccessControlActionChildrenProps } from 'lib/components/AccessControlAction'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'import { slackChannelDisplayName } from 'lib/integrations/slackChannel'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'@@ -13,9 +14,10 @@ import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { urls } from 'scenes/urls'-import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { AccessControlLevel } from '~/types'import type { VisionActionApi } from '../../generated/api.schemas'+import { getReplayVisionDeleteDisabledReason, getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { humanizeCadence, parseRruleToCadence } from '../cadence'import { visionActionsLogic } from '../visionActionsLogic'@@ -43,16 +45,26 @@ function humanizeSchedule(action: VisionActionApi): string {return humanizeCadence(parseRruleToCadence(rrule))}-// Every write control on this tab gates on the same session-recording Editor access — wrap once.-function EditorGate({ children }: { children: JSX.Element }): JSX.Element {- return (- <AccessControlAction- resourceType={AccessControlResourceType.SessionRecording}- minAccessLevel={AccessControlLevel.Editor}- >- {children}- </AccessControlAction>- )+// Every write control on this tab needs replay_scanner editor access; all but delete also need+// session_recording viewer access, since they configure or trigger processing of recording-derived+// data (delete doesn't). Pass `userAccessLevel` when a specific action's effective level is known, for+// object-level overrides. Can't use `AccessControlAction` here since it only checks one resource.+function EditorGate({+ children,+ userAccessLevel,+ requireSessionRecording = true,+}: {+ children: ReactElement<AccessControlActionChildrenProps>+ userAccessLevel?: AccessControlLevel+ requireSessionRecording?: boolean+}): JSX.Element {+ const disabledReason = requireSessionRecording+ ? getReplayVisionEditDisabledReason(userAccessLevel)+ : getReplayVisionDeleteDisabledReason(userAccessLevel)+ return cloneElement(children, {+ disabled: children.props.disabled ?? !!disabledReason,+ disabledReason: children.props.disabledReason ?? disabledReason,+ })}function deliverySummary(action: VisionActionApi): string {@@ -70,15 +82,27 @@ function deliverySummary(action: VisionActionApi): string {.join(', ')}-export function VisionActionsTab({ scannerId }: { scannerId: string }): JSX.Element {+export function VisionActionsTab({+ scannerId,+ scannerUserAccessLevel,+}: {+ scannerId: string+ scannerUserAccessLevel?: AccessControlLevel | null+}): JSX.Element {return (<BindLogic logic={visionActionsLogic} props={{ scannerId }}>- <VisionActionsTable scannerId={scannerId} />+ <VisionActionsTable scannerId={scannerId} scannerUserAccessLevel={scannerUserAccessLevel} /></BindLogic>)}-function VisionActionsTable({ scannerId }: { scannerId: string }): JSX.Element {+function VisionActionsTable({+ scannerId,+ scannerUserAccessLevel,+}: {+ scannerId: string+ scannerUserAccessLevel?: AccessControlLevel | null+}): JSX.Element {const { visionActions, visionActionsLoading, togglingIds } = useValues(visionActionsLogic)const { toggleActionEnabled, deleteAction } = useActions(visionActionsLogic)@@ -98,7 +122,7 @@ function VisionActionsTable({ scannerId }: { scannerId: string }): JSX.Element {description="Get scheduled summaries of this scanner's observations, synthesized by AI on the cadence you choose. Or set alerts that notify you when new matches appear or a threshold is reached. Both can deliver to Slack."actionElementOverride={<div className="flex gap-2">- <EditorGate>+ <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}><LemonButtontype="secondary"icon={<IconPlus />}@@ -108,7 +132,7 @@ function VisionActionsTable({ scannerId }: { scannerId: string }): JSX.Element {New summary</LemonButton></EditorGate>- <EditorGate>+ <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}><LemonButtontype="secondary"icon={<IconPlus />}@@ -156,7 +180,7 @@ function VisionActionsTable({ scannerId }: { scannerId: string }): JSX.Element {key: 'enabled',render: (_, action) => (<div className="flex items-center gap-2">- <EditorGate>+ <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}><LemonSwitchchecked={!!action.enabled}onChange={() => toggleActionEnabled(action.id)}@@ -195,7 +219,7 @@ function VisionActionsTable({ scannerId }: { scannerId: string }): JSX.Element {width: 0, // shrink to content so the buttons hug the right instead of floating in a wide columnrender: (_, action) => (<div className="flex gap-1">- <EditorGate>+ <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}><LemonButtonsize="small"type="secondary"@@ -205,7 +229,7 @@ function VisionActionsTable({ scannerId }: { scannerId: string }): JSX.Element {to={urls.replayVisionActionEdit(action.id)}/></EditorGate>- <EditorGate>+ <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined} requireSessionRecording={false}><LemonButtonsize="small"type="secondary"@@ -236,7 +260,7 @@ function VisionActionsTable({ scannerId }: { scannerId: string }): JSX.Element {return (<div className="flex flex-col gap-2"><div className="flex justify-end gap-2">- <EditorGate>+ <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}><LemonButtontype="secondary"icon={<IconPlus />}@@ -246,7 +270,7 @@ function VisionActionsTable({ scannerId }: { scannerId: string }): JSX.Element {New summary</LemonButton></EditorGate>- <EditorGate>+ <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}><LemonButtontype="secondary"icon={<IconPlus />}diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex cd24b211b97c..6dcd4e11b54d 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -25,6 +25,8 @@ import { recordingsQueryToUniversalFilters } from 'scenes/session-recordings/filimport { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'+import {visionScannersAffectedCohortCreate,visionScannersCreate,@@ -306,6 +308,7 @@ export interface replayScannerLogicValues {p75: number} | nullshowScannerErrors: boolean+ sidePanelContext: SidePanelSceneContext | nullsubmitIntent: 'advance' | 'save'tagSuggestions: TagSuggestionApi[]tagSuggestionsLoading: boolean@@ -629,6 +632,7 @@ export interface replayScannerLogicMeta {recentSessions: numbertotalSessions: number}+ sidePanelContext: (scanner: ReplayScanner, isNew: boolean) => SidePanelSceneContext | null}}@@ -1266,6 +1270,17 @@ export const replayScannerLogic = kea<replayScannerLogicType>([recentDays: stats?.coverage.recent_days ?? 14,}),],+ [SIDE_PANEL_CONTEXT_KEY]: [+ (s) => [s.scanner, s.isNew],+ (scanner: ReplayScanner | null, isNew: boolean): SidePanelSceneContext | null => {+ return scanner && !isNew+ ? {+ access_control_resource: 'replay_scanner',+ access_control_resource_id: scanner.id,+ }+ : null+ },+ ],}),listeners(({ actions, props, values, cache }) => {diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.tsindex 67f1ead2b065..5c4a50edf8cc 100644--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts@@ -140,6 +140,9 @@ export function newScanner(templateKey?: string | null): ReplayScanner {estimated_monthly_credits: null,// Seed price for the unsaved scanner; the server-computed value takes over after the first save.credits_per_observation: OBSERVATION_CREDITS_BY_MODEL[DEFAULT_MODEL],+ // An unsaved scanner has no object yet, so there's no effective access level for it —+ // create-time gating falls back to the resource-level default instead (see getReplayVisionEditDisabledReason).+ user_access_level: null,credits_this_month: 0,} as constdiff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex 6f799ef4f41b..7cefdd902884 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -1,6 +1,7 @@import { LemonTagType } from '@posthog/lemon-ui'import { RecordingsQuery } from '~/queries/schema/schema-general'+import { AccessControlLevel } from '~/types'import { ScannerModelEnumApi } from '../generated/api.schemas'import type {@@ -257,11 +258,15 @@ export const SAMPLING_MODE_OPTIONS: { value: SamplingMode; label: string; descriexport type ScannerCreatedBy = Omit<UserBasicApi, 'hedgehog_config'>// Derived from the generated schema so serializer changes fail typecheck; write-optional fields carry defaults.-export type BaseReplayScanner = Omit<ReplayScannerApi, 'scanner_type' | 'scanner_config' | 'query' | 'created_by'> &+export type BaseReplayScanner = Omit<+ ReplayScannerApi,+ 'scanner_type' | 'scanner_config' | 'query' | 'created_by' | 'user_access_level'+> &Required<Pick<ReplayScannerApi, 'sampling_rate' | 'enabled' | 'emits_signals' | 'provider'>> & {query: RecordingsQuery | nullcreated_by: ScannerCreatedBy | nullsampling_mode: SamplingMode+ user_access_level: AccessControlLevel | null}export interface MonitorScanner extends BaseReplayScanner {diff --git a/products/replay_vision/frontend/utils/accessControl.ts b/products/replay_vision/frontend/utils/accessControl.tsnew file mode 100644index 000000000000..674a9a225dab--- /dev/null+++ b/products/replay_vision/frontend/utils/accessControl.ts@@ -0,0 +1,37 @@+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++/**+ * Every Replay Vision write that creates, configures, or triggers processing of scanner/observation/+ * label/vision-action data requires BOTH replay_scanner editor access (the resource RBAC is actually+ * configured against — see RESOURCE_INHERITANCE_MAP) AND session_recording viewer access (since the+ * write exposes or processes recording-derived content). The backend enforces both unconditionally for+ * these actions (see `_scanner_for_url`/`initial()`'s `_CONFIG_ACTIONS` across scanners.py,+ * observations.py, prompt_suggestions.py, and vision_actions.py) — this must match exactly, or a+ * disabled-looking control can silently permit a request the backend blocks, and vice versa.+ */+export function getReplayVisionEditDisabledReason(scannerUserAccessLevel?: AccessControlLevel | null): string | null {+ return (+ getAccessControlDisabledReason(+ AccessControlResourceType.ReplayScanner,+ AccessControlLevel.Editor,+ scannerUserAccessLevel ?? undefined+ ) ?? getAccessControlDisabledReason(AccessControlResourceType.SessionRecording, AccessControlLevel.Viewer)+ )+}++/**+ * Deleting a scanner or vision action is the one write that skips the session_recording check —+ * destroy doesn't expose or process recording content (see `_CONFIG_ACTIONS`, which omits "destroy",+ * in ReplayScannerViewSet/VisionActionViewSet). Kept as its own export so delete call sites are+ * explicit about needing the narrower bar, rather than reusing the general helper and getting it+ * right by accident.+ */+export function getReplayVisionDeleteDisabledReason(scannerUserAccessLevel?: AccessControlLevel | null): string | null {+ return getAccessControlDisabledReason(+ AccessControlResourceType.ReplayScanner,+ AccessControlLevel.Editor,+ scannerUserAccessLevel ?? undefined+ )+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b6f5e4d787f6..79a9bd9fee95 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42193,6 +42193,9 @@ export namespace Schemas {Google: 'google',} as const;+ /**+ * A Replay Vision scanner: its type, targeting query, and AI configuration.+ */export interface ReplayScanner {readonly id: string;/**@@ -42265,6 +42268,11 @@ export namespace Schemas {readonly updated_at: string;/** AI summary of the team's written thumbs-down feedback into recurring failure modes. Refreshed with prompt recommendations; null until enough feedback accumulates. */readonly feedback_themes: FeedbackThemes | null;+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null;}export interface PaginatedReplayScannerList {@@ -45525,6 +45533,9 @@ export namespace Schemas {prompt_guide?: string;}+ /**+ * A Replay Vision action: a scheduled "and then…" automation over a scanner's observations.+ */export interface VisionAction {readonly id: string;/**@@ -50820,6 +50831,9 @@ export namespace Schemas {person_id?: string;}+ /**+ * A Replay Vision scanner: its type, targeting query, and AI configuration.+ */export interface PatchedReplayScanner {readonly id?: string;/**@@ -50892,6 +50906,11 @@ export namespace Schemas {readonly updated_at?: string;/** AI summary of the team's written thumbs-down feedback into recurring failure modes. Refreshed with prompt recommendations; null until enough feedback accumulates. */readonly feedback_themes?: FeedbackThemes | null;+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level?: string | null;}export interface PatchedReviewBlindSpotsConfigSelect {@@ -53119,6 +53138,9 @@ export namespace Schemas {configuration?: unknown;}+ /**+ * A Replay Vision action: a scheduled "and then…" automation over a scanner's observations.+ */export interface PatchedVisionAction {readonly id?: string;/**diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex 30eefcc06bb7..74d313860032 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -92,7 +92,7 @@ export const VisionObservationsRetrieveQueryParams = /* @__PURE__ */ zod.object(})/**- * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires session recording edit access.+ * Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires editor access to the scanner.*/export const VisionObservationsLabelCreateParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this replay observation.'),@@ -120,7 +120,7 @@ export const VisionObservationsLabelCreateBody = /* @__PURE__ */ zod.describe("The team's shared judgement on whether the scanner scored this session correctly.")/**- * Remove the observation's shared label. Requires session recording edit access.+ * Remove the observation's shared label. Requires editor access to the scanner.*/export const VisionObservationsLabelDestroyParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this replay observation.'),@@ -193,72 +193,76 @@ export const visionScannersCreateBodyDescriptionMax = 1000export const visionScannersCreateBodySamplingRateMin = 0export const visionScannersCreateBodySamplingRateMax = 1-export const VisionScannersCreateBody = /* @__PURE__ */ zod.object({- name: zod- .string()- .max(visionScannersCreateBodyNameMax)- .describe('Human-readable scanner name. Unique within the team.'),- description: zod- .string()- .max(visionScannersCreateBodyDescriptionMax)- .optional()- .describe('Free-form description shown in the scanner management UI.'),- scanner_type: zod- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])- .describe(- '* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer'- )- .describe(- 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer'- ),- scanner_config: zod- .unknown()- .describe(- 'Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`.'- ),- query: zod- .unknown()- .optional()- .describe(- 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user.'- ),- sampling_rate: zod- .number()- .min(visionScannersCreateBodySamplingRateMin)- .max(visionScannersCreateBodySamplingRateMax)- .optional()- .describe(- '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'- ),- sampling_mode: zod- .enum(['focused', 'balanced', 'comprehensive'])- .describe('* `focused` - Focused\n* `balanced` - Balanced\n* `comprehensive` - Comprehensive')- .optional()- .describe(- 'Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n* `focused` - Focused\n* `balanced` - Balanced\n* `comprehensive` - Comprehensive'- ),- provider: zod- .enum(['google'])- .describe('* `google` - Google')- .optional()- .describe('LLM provider. v1 is Google-only.\n\n* `google` - Google'),- model: zod- .enum(['gemini-3.5-flash-lite', 'gemini-3.6-flash'])- .describe('* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3.6-flash` - Gemini 3.6 Flash')- .describe(- 'Concrete model to use for this scanner.\n\n* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3.6-flash` - Gemini 3.6 Flash'- ),- enabled: zod- .boolean()- .optional()- .describe("When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work."),- emits_signals: zod- .boolean()- .optional()- .describe(- 'When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals.'- ),-})+export const VisionScannersCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(visionScannersCreateBodyNameMax)+ .describe('Human-readable scanner name. Unique within the team.'),+ description: zod+ .string()+ .max(visionScannersCreateBodyDescriptionMax)+ .optional()+ .describe('Free-form description shown in the scanner management UI.'),+ scanner_type: zod+ .enum(['monitor', 'classifier', 'scorer', 'summarizer'])+ .describe(+ '* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer'+ )+ .describe(+ 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer'+ ),+ scanner_config: zod+ .unknown()+ .describe(+ 'Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`.'+ ),+ query: zod+ .unknown()+ .optional()+ .describe(+ 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user.'+ ),+ sampling_rate: zod+ .number()+ .min(visionScannersCreateBodySamplingRateMin)+ .max(visionScannersCreateBodySamplingRateMax)+ .optional()+ .describe(+ '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'+ ),+ sampling_mode: zod+ .enum(['focused', 'balanced', 'comprehensive'])+ .describe('* `focused` - Focused\n* `balanced` - Balanced\n* `comprehensive` - Comprehensive')+ .optional()+ .describe(+ 'Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n* `focused` - Focused\n* `balanced` - Balanced\n* `comprehensive` - Comprehensive'+ ),+ provider: zod+ .enum(['google'])+ .describe('* `google` - Google')+ .optional()+ .describe('LLM provider. v1 is Google-only.\n\n* `google` - Google'),+ model: zod+ .enum(['gemini-3.5-flash-lite', 'gemini-3.6-flash'])+ .describe('* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3.6-flash` - Gemini 3.6 Flash')+ .describe(+ 'Concrete model to use for this scanner.\n\n* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3.6-flash` - Gemini 3.6 Flash'+ ),+ enabled: zod+ .boolean()+ .optional()+ .describe(+ "When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work."+ ),+ emits_signals: zod+ .boolean()+ .optional()+ .describe(+ 'When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals.'+ ),+ })+ .describe('A Replay Vision scanner: its type, targeting query, and AI configuration.')/*** CRUD for Replay Vision scanners.@@ -291,76 +295,80 @@ export const visionScannersPartialUpdateBodyDescriptionMax = 1000export const visionScannersPartialUpdateBodySamplingRateMin = 0export const visionScannersPartialUpdateBodySamplingRateMax = 1-export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod- .string()- .max(visionScannersPartialUpdateBodyNameMax)- .optional()- .describe('Human-readable scanner name. Unique within the team.'),- description: zod- .string()- .max(visionScannersPartialUpdateBodyDescriptionMax)- .optional()- .describe('Free-form description shown in the scanner management UI.'),- scanner_type: zod- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])- .describe(- '* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer'- )- .optional()- .describe(- 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer'- ),- scanner_config: zod- .unknown()- .optional()- .describe(- 'Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`.'- ),- query: zod- .unknown()- .optional()- .describe(- 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user.'- ),- sampling_rate: zod- .number()- .min(visionScannersPartialUpdateBodySamplingRateMin)- .max(visionScannersPartialUpdateBodySamplingRateMax)- .optional()- .describe(- '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'- ),- sampling_mode: zod- .enum(['focused', 'balanced', 'comprehensive'])- .describe('* `focused` - Focused\n* `balanced` - Balanced\n* `comprehensive` - Comprehensive')- .optional()- .describe(- 'Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n* `focused` - Focused\n* `balanced` - Balanced\n* `comprehensive` - Comprehensive'- ),- provider: zod- .enum(['google'])- .describe('* `google` - Google')- .optional()- .describe('LLM provider. v1 is Google-only.\n\n* `google` - Google'),- model: zod- .enum(['gemini-3.5-flash-lite', 'gemini-3.6-flash'])- .describe('* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3.6-flash` - Gemini 3.6 Flash')- .optional()- .describe(- 'Concrete model to use for this scanner.\n\n* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3.6-flash` - Gemini 3.6 Flash'- ),- enabled: zod- .boolean()- .optional()- .describe("When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work."),- emits_signals: zod- .boolean()- .optional()- .describe(- 'When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals.'- ),-})+export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(visionScannersPartialUpdateBodyNameMax)+ .optional()+ .describe('Human-readable scanner name. Unique within the team.'),+ description: zod+ .string()+ .max(visionScannersPartialUpdateBodyDescriptionMax)+ .optional()+ .describe('Free-form description shown in the scanner management UI.'),+ scanner_type: zod+ .enum(['monitor', 'classifier', 'scorer', 'summarizer'])+ .describe(+ '* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer'+ )+ .optional()+ .describe(+ 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer'+ ),+ scanner_config: zod+ .unknown()+ .optional()+ .describe(+ 'Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`.'+ ),+ query: zod+ .unknown()+ .optional()+ .describe(+ 'Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user.'+ ),+ sampling_rate: zod+ .number()+ .min(visionScannersPartialUpdateBodySamplingRateMin)+ .max(visionScannersPartialUpdateBodySamplingRateMax)+ .optional()+ .describe(+ '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'+ ),+ sampling_mode: zod+ .enum(['focused', 'balanced', 'comprehensive'])+ .describe('* `focused` - Focused\n* `balanced` - Balanced\n* `comprehensive` - Comprehensive')+ .optional()+ .describe(+ 'Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n* `focused` - Focused\n* `balanced` - Balanced\n* `comprehensive` - Comprehensive'+ ),+ provider: zod+ .enum(['google'])+ .describe('* `google` - Google')+ .optional()+ .describe('LLM provider. v1 is Google-only.\n\n* `google` - Google'),+ model: zod+ .enum(['gemini-3.5-flash-lite', 'gemini-3.6-flash'])+ .describe('* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3.6-flash` - Gemini 3.6 Flash')+ .optional()+ .describe(+ 'Concrete model to use for this scanner.\n\n* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3.6-flash` - Gemini 3.6 Flash'+ ),+ enabled: zod+ .boolean()+ .optional()+ .describe(+ "When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work."+ ),+ emits_signals: zod+ .boolean()+ .optional()+ .describe(+ 'When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals.'+ ),+ })+ .describe('A Replay Vision scanner: its type, targeting query, and AI configuration.')/*** CRUD for Replay Vision scanners.@@ -688,7 +696,7 @@ export const VisionScannersPromptSuggestionsApplyCreateBody = /* @__PURE__ */ zo})/**- * Dismiss this suggestion without applying it. Only the current pending suggestion can be dismissed. Requires session recording edit access.+ * Dismiss this suggestion without applying it. Only the current pending suggestion can be dismissed. Requires editor access to the scanner.*/export const VisionScannersPromptSuggestionsDismissCreateParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this replay scanner prompt suggestion.'),@@ -713,7 +721,7 @@ export const VisionScannersPromptSuggestionsCurrentRetrieveParams = /* @__PURE__})/**- * Generate a fresh prompt suggestion from the team's current ratings. The previous pending suggestion becomes history (superseded). Requires at least one rated observation and session recording edit access.+ * Generate a fresh prompt suggestion from the team's current ratings. The previous pending suggestion becomes history (superseded). Requires at least one rated observation and editor access to the scanner.*/export const VisionScannersPromptSuggestionsGenerateCreateParams = /* @__PURE__ */ zod.object({project_id: zod