: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): let Max run scans, with confirmation before spending (#78754)
Tue Haulund839590a039d5
diff --git a/ee/hogai/core/agent_modes/presets/session_replay.py b/ee/hogai/core/agent_modes/presets/session_replay.pyindex 8d7090f7c6be..106e23c21fba 100644--- a/ee/hogai/core/agent_modes/presets/session_replay.py+++ b/ee/hogai/core/agent_modes/presets/session_replay.py@@ -101,12 +101,24 @@ class SessionReplayAgentToolkit(AgentToolkit):@propertydef tools(self) -> list[type["MaxTool"]]:# Lazy import keeps the product dependency off this module's import path (see test_toolkit_imports).- from products.replay_vision.backend.max_tools import SearchReplayVisionObservationsTool+ from products.replay_vision.backend.max_tools import (+ CreateReplayVisionActionTool,+ CreateReplayVisionScannerTool,+ GetReplayVisionQuotaTool,+ RetryReplayVisionObservationTool,+ ScanReplayVisionSessionsTool,+ SearchReplayVisionObservationsTool,+ )tools: list[type[MaxTool]] = [FilterSessionRecordingsTool,SummarizeSessionsTool,SearchReplayVisionObservationsTool,+ ScanReplayVisionSessionsTool,+ RetryReplayVisionObservationTool,+ GetReplayVisionQuotaTool,+ CreateReplayVisionScannerTool,+ CreateReplayVisionActionTool,]return toolsdiff --git a/ee/hogai/test/test_tool.py b/ee/hogai/test/test_tool.pyindex cb0782cd56d1..714fa0dd94c7 100644--- a/ee/hogai/test/test_tool.py+++ b/ee/hogai/test/test_tool.py@@ -1,3 +1,4 @@+import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import patch@@ -8,7 +9,7 @@ from posthog.rbac.user_access_control import UserAccessControlfrom ee.hogai.core.context import set_node_pathfrom ee.hogai.registry import CONTEXTUAL_TOOL_NAME_TO_TOOL, _import_max_tools-from ee.hogai.tool import ClientToolCallRequest, MaxTool+from ee.hogai.tool import ApprovalResumePayload, ClientToolCallRequest, MaxToolfrom ee.hogai.tool_errors import (MaxToolAccessDeniedError,MaxToolError,@@ -490,3 +491,41 @@ class TestToolAccessControlDeclarations(BaseTest):f"Tools without access control declaration: {missing_access_control}. "f"Either add get_required_resource_access() or add to TOOLS_WITHOUT_ACCESS_CONTROL with a reason.")+++class _ApprovalArgs(BaseModel):+ count: int+++class TestDangerousOperationBindsApprovedArguments(BaseTest):+ """An approving user may edit the arguments; the tool must run what they approved, not what was asked."""++ class _SpendingTool(MaxTool):+ name: str = "create_feature_flag"+ description: str = "test"+ thinking_message: str = "test"+ args_schema: type[BaseModel] = _ApprovalArgs++ def get_required_resource_access(self):+ # Every registered tool must declare this, and subclassing registers under the shared name.+ return [("feature_flag", "editor")]++ async def is_dangerous_operation(self, **kwargs) -> bool:+ return True++ async def _arun_impl(self, count: int) -> tuple[str, dict]:+ return f"ran with {count}", {"count": count}++ @pytest.mark.asyncio+ async def test_edited_arguments_reach_the_implementation(self):+ # The approval payload used to be merged into a local copy of kwargs, so an edit at the prompt+ # was discarded and the original operation ran. On a tool that spends money, that charges for+ # something the user did not approve.+ tool = self._SpendingTool(team=self.team, user=self.user)+ approved = ApprovalResumePayload(action="approve", payload={"count": 5}, proposal_id="p1")++ with patch("ee.hogai.tool.interrupt", return_value=approved.model_dump()):+ content, artifact = await tool._arun_with_context(count=200)++ assert artifact["count"] == 5+ assert "5" in contentdiff --git a/ee/hogai/tool.py b/ee/hogai/tool.pyindex 2606ea0128c1..b226105e4125 100644--- a/ee/hogai/tool.py+++ b/ee/hogai/tool.py@@ -211,14 +211,14 @@ class MaxTool(AssistantContextMixin, AssistantDispatcherMixin, BaseTool):def _run_with_context(self, *args, **kwargs):"""Sets the context for the tool."""with set_node_path(self.node_path):- if permission_check_result := async_to_sync(self._check_dangerous_operation)(**kwargs):+ if permission_check_result := async_to_sync(self._check_dangerous_operation)(kwargs):return permission_check_resultreturn self._run_impl(*args, **kwargs)async def _arun_with_context(self, *args, **kwargs):"""Sets the context for the tool. Checks for approved/dangerous operations before executing."""with set_node_path(self.node_path):- if permission_check_result := await self._check_dangerous_operation(**kwargs):+ if permission_check_result := await self._check_dangerous_operation(kwargs):return permission_check_resultreturn await self._arun_impl(*args, **kwargs)@@ -347,19 +347,25 @@ class MaxTool(AssistantContextMixin, AssistantDispatcherMixin, BaseTool):resource_name = resource or obj._meta.model_nameraise MaxToolAccessDeniedError(resource_name, required_level, action=action)- async def _check_dangerous_operation(self, **kwargs) -> tuple[str, Any] | None:+ async def _check_dangerous_operation(self, kwargs: dict[str, Any]) -> tuple[str, Any] | None:+ """Takes the caller's kwargs dict by reference, not unpacked.++ An approving user may edit the arguments, and `_handle_dangerous_operation` writes them back+ into this dict. Unpacking here would hand each level a fresh copy, so the edits would be+ discarded and the caller would execute the operation the user did not approve.+ """if not await self.is_dangerous_operation(**kwargs):return None# Handle dangerous operation approval flow# Pre-compute preview before calling _handle_dangerous_operationpreview = await self.format_dangerous_operation_preview(**kwargs)- dangerous_result = self._handle_dangerous_operation(preview=preview, **kwargs)+ dangerous_result = self._handle_dangerous_operation(kwargs, preview=preview)if dangerous_result is not None:return dangerous_resultreturn None- def _handle_dangerous_operation(self, preview: str | None = None, **kwargs) -> tuple[str, Any] | None:+ def _handle_dangerous_operation(self, kwargs: dict[str, Any], preview: str | None = None) -> tuple[str, Any] | None:"""Handle dangerous operation approval flow using LangGraph's interrupt().diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 7bd8cbb2d080..b5f83dde6cf8 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -4113,6 +4113,11 @@"summarize_replay_vision_summaries","draft_replay_vision_scanner_prompt","search_replay_vision_observations",+ "scan_replay_vision_sessions",+ "retry_replay_vision_observation",+ "get_replay_vision_quota",+ "create_replay_vision_scanner",+ "create_replay_vision_action","upsert_account","upsert_account_notebook","open_account"diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.tsindex d465a4e83d87..7e2dbd8423a9 100644--- a/frontend/src/queries/schema/schema-assistant-messages.ts+++ b/frontend/src/queries/schema/schema-assistant-messages.ts@@ -520,6 +520,11 @@ export type AssistantTool =| 'summarize_replay_vision_summaries'| 'draft_replay_vision_scanner_prompt'| 'search_replay_vision_observations'+ | 'scan_replay_vision_sessions'+ | 'retry_replay_vision_observation'+ | 'get_replay_vision_quota'+ | 'create_replay_vision_scanner'+ | 'create_replay_vision_action'| 'upsert_account'| 'upsert_account_notebook'| 'open_account'diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex a8c055313a43..4c1cff62639e 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -790,6 +790,66 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {return 'Searching observations...'},},+ scan_replay_vision_sessions: {+ name: 'Scan recordings',+ description: 'Scan recordings with Replay Vision to answer a question about them',+ icon: iconForType('session_replay'),+ modes: [AgentMode.SessionReplay],+ displayFormatter: (toolCall) => {+ if (toolCall.status === 'completed') {+ return 'Started scanning recordings'+ }+ return 'Starting scans...'+ },+ },+ retry_replay_vision_observation: {+ name: 'Retry a scan',+ description: 'Retry a scan on a recording whose observation failed',+ icon: iconForType('session_replay'),+ modes: [AgentMode.SessionReplay],+ displayFormatter: (toolCall) => {+ if (toolCall.status === 'completed') {+ return 'Retried the scan'+ }+ return 'Retrying the scan...'+ },+ },+ get_replay_vision_quota: {+ name: 'Check Replay Vision credits',+ description: 'Check Replay Vision credits left in the monthly budget',+ icon: iconForType('session_replay'),+ modes: [AgentMode.SessionReplay],+ displayFormatter: (toolCall) => {+ if (toolCall.status === 'completed') {+ return 'Checked Replay Vision credits'+ }+ return 'Checking Replay Vision credits...'+ },+ },+ create_replay_vision_scanner: {+ name: 'Create a scanner',+ description: 'Create a scanner that watches new recordings as they arrive',+ icon: iconForType('session_replay'),+ modes: [AgentMode.SessionReplay],+ displayFormatter: (toolCall) => {+ if (toolCall.status === 'completed') {+ return 'Created the scanner'+ }+ return 'Creating the scanner...'+ },+ },+ create_replay_vision_action: {+ name: 'Summarize a scanner',+ description: 'Summarize a scanner on a recurring schedule',+ icon: iconForType('session_replay'),+ modes: [AgentMode.SessionReplay],+ displayFormatter: (toolCall) => {+ if (toolCall.status === 'completed') {+ return 'Set up the summary'+ }+ return 'Setting up the summary...'+ },+ },create_survey: {name: 'Create surveys',description: 'Create surveys in seconds',diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 09b7ddf430a4..d6dc7fc8a11a 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -427,6 +427,11 @@ class AssistantTool(StrEnum):SUMMARIZE_REPLAY_VISION_SUMMARIES = "summarize_replay_vision_summaries"DRAFT_REPLAY_VISION_SCANNER_PROMPT = "draft_replay_vision_scanner_prompt"SEARCH_REPLAY_VISION_OBSERVATIONS = "search_replay_vision_observations"+ SCAN_REPLAY_VISION_SESSIONS = "scan_replay_vision_sessions"+ RETRY_REPLAY_VISION_OBSERVATION = "retry_replay_vision_observation"+ GET_REPLAY_VISION_QUOTA = "get_replay_vision_quota"+ CREATE_REPLAY_VISION_SCANNER = "create_replay_vision_scanner"+ CREATE_REPLAY_VISION_ACTION = "create_replay_vision_action"UPSERT_ACCOUNT = "upsert_account"UPSERT_ACCOUNT_NOTEBOOK = "upsert_account_notebook"OPEN_ACCOUNT = "open_account"diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 5d3dcc7c0c4a..66c40816a66e 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -81,7 +81,12 @@ from products.replay_vision.backend.quota import (current_period_bounds,sum_enabled_scanner_estimated_credits,)-from products.replay_vision.backend.scanner_config import scanner_config_error+from products.replay_vision.backend.scanner_config import (+ MAX_PROMPT_LENGTH,+ MAX_TAG_LENGTH,+ acting_user,+ scanner_config_error,+)from products.replay_vision.backend.scanning import MAX_SESSIONS_PER_SCAN, run_inline_scan, scan_existing_scannerfrom products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tagsfrom products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH@@ -90,9 +95,6 @@ from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LEN_QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")# Size caps enforced at the write boundary; scanner_config is copied into every observation's snapshot.-_MAX_PROMPT_LENGTH = 20_000-_MAX_TAGS = 100-_MAX_TAG_LENGTH = 100_MAX_DESCRIPTION_LENGTH = 1_000logger = structlog.get_logger(__name__)@@ -425,7 +427,7 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Modedef create(self, validated_data: dict[str, Any]) -> ReplayScanner:team = self.context["get_team"]()- user = cast(User, self.context["request"].user)+ user = acting_user(self.context)if not team.organization.is_ai_data_processing_approved:raise serializers.ValidationError("Your organization needs to allow AI analysis before you can create a Replay Vision scanner."@@ -445,7 +447,7 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode"replay_vision_scanner_created",_scanner_lifecycle_properties(scanner),team=team,- request=self.context["request"],+ request=self.context.get("request"),)return scanner@@ -465,8 +467,8 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Modeif needs_refresh:_refresh_estimate_fail_soft(scanner)changed_fields = sorted(field for field, value in before.items() if getattr(scanner, field) != value)- request = self.context["request"]- user = cast(User, request.user)+ request = self.context.get("request")+ user = acting_user(self.context)team = self.context["get_team"]()if scanner.enabled != was_enabled:report_user_action(@@ -635,7 +637,6 @@ class ObserveResponseSerializer(serializers.Serializer):# One request can start at most this many scans. Bounds the fan-out of a single bulk trigger well# under the in-flight caps; the frontend selects from one loaded page, so this is rarely the binding# limit — the concurrency headroom usually is.-BULK_OBSERVE_MAX_SESSIONS = MAX_SESSIONS_PER_SCANclass BulkObserveRequestSerializer(serializers.Serializer):@@ -644,9 +645,9 @@ class BulkObserveRequestSerializer(serializers.Serializer):session_ids = serializers.ListField(child=serializers.CharField(max_length=MAX_SESSION_ID_LENGTH),allow_empty=False,- max_length=BULK_OBSERVE_MAX_SESSIONS,+ max_length=MAX_SESSIONS_PER_SCAN,help_text=(- f"Session recording IDs to scan on demand, at most {BULK_OBSERVE_MAX_SESSIONS} per request. "+ f"Session recording IDs to scan on demand, at most {MAX_SESSIONS_PER_SCAN} per request. ""Scans start until the in-flight limit or monthly credit quota is reached; the rest are ""reported as skipped rather than failing the whole batch. Already-running sessions are a no-op."),@@ -707,15 +708,15 @@ class InlineScanRequestSerializer(serializers.Serializer):session_ids = serializers.ListField(child=serializers.CharField(max_length=MAX_SESSION_ID_LENGTH),allow_empty=False,- max_length=BULK_OBSERVE_MAX_SESSIONS,+ max_length=MAX_SESSIONS_PER_SCAN,help_text=(- f"Session recording IDs to scan, at most {BULK_OBSERVE_MAX_SESSIONS} per request. Scans start "+ f"Session recording IDs to scan, at most {MAX_SESSIONS_PER_SCAN} per request. Scans start ""until the in-flight limit or monthly credit quota is reached; the rest are reported as ""skipped rather than failing the whole batch."),)prompt = serializers.CharField(- max_length=_MAX_PROMPT_LENGTH,+ max_length=MAX_PROMPT_LENGTH,help_text="What to look for in these sessions, in plain language. The same instruction a saved scanner carries.",)scanner_type = serializers.ChoiceField(@@ -995,7 +996,7 @@ class _ImpactQualifiersSerializer(serializers.Serializer):required=False,allow_null=True,default=None,- max_length=_MAX_TAG_LENGTH,+ max_length=MAX_TAG_LENGTH,help_text=("Classifier scanners only, required for them: count sessions carrying this tag ""(fixed or freeform). Not applicable to other scanner types."@@ -1193,6 +1194,12 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi# Observation output exposes recording contents, so observe requires session_recording read.if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):raise PermissionDenied("Triggering an on-demand observation requires session_recording read access.")+ # Every scan entrypoint gates this: create_observation fails closed on consent once the workflow+ # is already running, so without the check the caller gets a 202 for a scan that never happens.+ if not self.team.organization.is_ai_data_processing_approved:+ raise ValidationError(+ "Your organization needs to allow AI analysis before you can run a Replay Vision scan."+ )try:check_observation_quota(self.team.organization_id, observation_credits_for_model(scanner.model))@@ -1262,6 +1269,13 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi# Observation output exposes recording contents, so this requires session_recording read.if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):raise PermissionDenied("Triggering on-demand observations requires session_recording read access.")+ # The scan sends recordings to an LLM, the same reason observe, inline_scan and retry gate on+ # this. Without it a batch was accepted and then silently scanned nothing, because+ # create_observation fails closed on consent once the workflow is already running.+ if not self.team.organization.is_ai_data_processing_approved:+ raise ValidationError(+ "Your organization needs to allow AI analysis before you can run a Replay Vision scan."+ )body = BulkObserveRequestSerializer(data=request.data)body.is_valid(raise_exception=True)diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.pyindex c75eae12bad8..5593e08fd727 100644--- a/products/replay_vision/backend/api/vision_actions.py+++ b/products/replay_vision/backend/api/vision_actions.py@@ -28,7 +28,6 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializerfrom posthog.models.integration import Integration-from posthog.models.user import Userfrom products.replay_vision.backend.api.delivery import archive_delivery, provision_deliveryfrom products.replay_vision.backend.api.errors import ReplayVisionErrorSerializer@@ -52,6 +51,7 @@ from products.replay_vision.backend.models.vision_action import ()from products.replay_vision.backend.rrule import validate_rrule, validate_timezonefrom products.replay_vision.backend.scanner_access import is_uuid, readable_scanner_ids+from products.replay_vision.backend.scanner_config import acting_userfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdictlogger = structlog.get_logger(__name__)@@ -433,11 +433,11 @@ class VisionActionSerializer(serializers.ModelSerializer):requested = [str(s) for s in (selection.get("scanner_ids") or ([scanner.id] if scanner else []))]if not requested:return- request = self.context.get("request")- if request is None or not getattr(request.user, "is_authenticated", False):+ user = acting_user(self.context)+ if user is None or not getattr(user, "is_authenticated", False):returnteam = self.context["get_team"]()- readable = set(readable_scanner_ids(request.user, team, requested))+ readable = set(readable_scanner_ids(user, team, requested))if set(requested) - readable:raise serializers.ValidationError({"scanner": "You don't have access to one or more scanners this action targets."}@@ -538,8 +538,8 @@ class VisionActionSerializer(serializers.ModelSerializer):demote.update(is_scanner_digest=False)def _authorize_demotions(self, actions: QuerySet[VisionAction]) -> None:- request = self.context.get("request")- if request is None or not getattr(request.user, "is_authenticated", False):+ user = acting_user(self.context)+ if user is None or not getattr(user, "is_authenticated", False):return# The bound scanner is the promotion target (already editor-checked upstream); the exposure is# each demoted digest's selection.scanner_ids, which _validate_scanner_access guards on a direct@@ -551,7 +551,7 @@ class VisionActionSerializer(serializers.ModelSerializer):if not requested:returnteam = self.context["get_team"]()- readable = set(readable_scanner_ids(request.user, team, list(requested)))+ readable = set(readable_scanner_ids(user, team, list(requested)))if requested - readable:raise serializers.ValidationError({"is_scanner_digest": "You don't have access to a scanner the current digest reads from."}@@ -559,7 +559,7 @@ class VisionActionSerializer(serializers.ModelSerializer):def create(self, validated_data: dict[str, Any]) -> VisionAction:team = self.context["get_team"]()- user = cast(User, self.context["request"].user)+ user = acting_user(self.context)if validated_data.get("is_scanner_digest"):self._demote_existing_digest(validated_data["scanner"])if self._has_derived_digest_name(validated_data):diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex d6bebb11309e..3d669af9d40b 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -1,10 +1,11 @@import uuidfrom dataclasses import dataclass-from typing import Any+from typing import Any, ClassVarimport structlogfrom posthoganalytics import capture_exceptionfrom pydantic import BaseModel, Field+from rest_framework.exceptions import Throttledfrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_query@@ -12,23 +13,41 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.api.embedding_worker import async_generate_embeddingfrom posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.exceptions import QuotaLimitExceeded+from posthog.models.team import Team+from posthog.models.user import Userfrom posthog.rbac.user_access_control import AccessControlLevelfrom posthog.scopes import APIScopeObjectfrom posthog.sync import database_sync_to_async+from products.replay_vision.backend.api.scanners import ReplayScannerSerializer+from products.replay_vision.backend.api.vision_actions import VisionActionSerializer+from products.replay_vision.backend.billing import CREDITS_PER_DOLLAR, observation_credits_for_model+from products.replay_vision.backend.consent import is_ai_data_processing_approvedfrom products.replay_vision.backend.embeddings import (EMBEDDING_DOCUMENT_TYPE,EMBEDDING_PRODUCT,OBSERVATION_EMBEDDING_MODEL,)-from products.replay_vision.backend.feature_flag import is_replay_vision_enabled+from products.replay_vision.backend.feature_flag import is_replay_vision_actions_enabled, is_replay_vision_enabledfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation-from products.replay_vision.backend.models.replay_scanner import ScannerType+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.models.vision_action import ActionModefrom products.replay_vision.backend.observation_formatting import EVENT_ID_CITATION_RE, format_line, read_output+from products.replay_vision.backend.quota import compute_quota_snapshotfrom products.replay_vision.backend.scanner_access import (+ is_uuid,scanner_for_reading_observations,scanners_for_reading_observations,)+from products.replay_vision.backend.scanner_config import scanner_config_error+from products.replay_vision.backend.scanning import (+ MAX_SESSIONS_PER_SCAN,+ RetryOutcome,+ retry_observation,+ run_inline_scan,+ scan_existing_scanner,+)from products.replay_vision.backend.tags import clickhouse_slugify_sql, slugify_tagfrom ee.hogai.tool import MaxTool@@ -137,7 +156,55 @@ class DraftScannerPromptArgs(BaseModel):)-class DraftReplayVisionScannerPromptTool(MaxTool):+class ReplayVisionGatesMixin:+ """Shared gates for every Replay Vision tool.++ A plain mixin rather than a MaxTool subclass: `MaxTool.__init_subclass__` requires every subclass to+ carry a `name` registered in `AssistantTool`, so an abstract intermediate isn't expressible. Mixed in+ ahead of MaxTool, its `is_dangerous_operation` still wins the MRO.++ `spends_credits` defaults to True on purpose. `MaxTool.is_dangerous_operation` defaults to False, so+ a tool that spends the org's credits and forgets to override it charges them with no confirmation,+ and nothing downstream catches that: scanning.py starts the workflow either way. Inverting the+ default here makes the omission cost a needless prompt instead of a needless charge. Read-only tools+ opt out explicitly, with a reason.+ """++ spends_credits: ClassVar[bool] = True++ # Supplied by MaxTool, which every user of this mixin also inherits.+ _user: User+ _team: Team++ async def is_dangerous_operation(self, **kwargs) -> bool:+ return self.spends_credits++ @database_sync_to_async+ def _is_enabled(self) -> bool:+ return is_replay_vision_enabled(self._user, self._team)++ @database_sync_to_async+ def _gates(self) -> tuple[bool, bool]:+ """Both preconditions on one hop. `_is_enabled` can be a network flag evaluation, so running it+ in series ahead of the consent read costs two dispatches for one decision."""+ return is_replay_vision_enabled(self._user, self._team), is_ai_data_processing_approved(self._team.id)++ @staticmethod+ def _not_enabled() -> tuple[str, dict[str, Any]]:+ return "Replay Vision is not enabled for this project.", {"error": "not_enabled"}++ @staticmethod+ def _no_ai_consent() -> tuple[str, dict[str, Any]]:+ return (+ "This organization hasn't enabled AI analysis of recordings, which Replay Vision needs. "+ "An admin can turn it on in organization settings.",+ {"error": "no_ai_consent"},+ )+++class DraftReplayVisionScannerPromptTool(ReplayVisionGatesMixin, MaxTool):+ # Reads and form-fills only; nothing here starts a scan.+ spends_credits: ClassVar[bool] = Falsename: str = "draft_replay_vision_scanner_prompt"description: str = DRAFT_PROMPT_TOOL_DESCRIPTIONargs_schema: type[BaseModel] = DraftScannerPromptArgs@@ -152,7 +219,7 @@ class DraftReplayVisionScannerPromptTool(MaxTool):async def _arun_impl(self, prompt: str, scanner_type: str | None = None) -> tuple[str, dict[str, Any]]:if not await self._is_enabled():- return "Replay Vision is not enabled for this project.", {"error": "not_enabled"}+ return self._not_enabled()cleaned = prompt.strip()if not cleaned:@@ -165,10 +232,6 @@ class DraftReplayVisionScannerPromptTool(MaxTool):"scanner_type": resolved_type if resolved_type in VALID_SCANNER_TYPES else None,}- @database_sync_to_async- def _is_enabled(self) -> bool:- return is_replay_vision_enabled(self._user, self._team)-class SummarizeSummariesArgs(BaseModel):scanner_id: str | None = Field(@@ -177,7 +240,9 @@ class SummarizeSummariesArgs(BaseModel):)-class SummarizeReplayVisionSummariesTool(MaxTool):+class SummarizeReplayVisionSummariesTool(ReplayVisionGatesMixin, MaxTool):+ # Reads and form-fills only; nothing here starts a scan.+ spends_credits: ClassVar[bool] = Falsename: str = "summarize_replay_vision_summaries"description: str = SUMMARIZE_SUMMARIES_TOOL_DESCRIPTIONargs_schema: type[BaseModel] = SummarizeSummariesArgs@@ -206,7 +271,7 @@ class SummarizeReplayVisionSummariesTool(MaxTool):# Gate on the product flag, matching the Vision API viewsets — the tool must not return# data when Replay Vision is disabled for the org.if not is_replay_vision_enabled(self._user, self._team):- return "Replay Vision is not enabled for this project.", {"error": "not_enabled"}+ return self._not_enabled()scanner = scanner_for_reading_observations(self._team.id, scanner_id)if scanner is None:@@ -356,7 +421,9 @@ class SearchObservationsArgs(BaseModel):)-class SearchReplayVisionObservationsTool(MaxTool):+class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):+ # Reads and form-fills only; nothing here starts a scan.+ spends_credits: ClassVar[bool] = Falsename: str = "search_replay_vision_observations"description: str = SEARCH_OBSERVATIONS_TOOL_DESCRIPTIONargs_schema: type[BaseModel] = SearchObservationsArgs@@ -582,3 +649,690 @@ class SearchReplayVisionObservationsTool(MaxTool):ch_user=ClickHouseUser.REPLAY_VISION,)return [row[0] for row in (result.results or [])]+++# Everything a scan costs is priced per observation from this model unless a saved scanner names another.+DEFAULT_SCAN_MODEL = ScannerModel.GEMINI_3_FLASH_PREVIEW++# Pinned to the hour the built-in digest uses, so a summary Max sets up fires at the same time as+# every UI-created one rather than at whatever `starts_at` happened to be.+_SUMMARY_HOUR = 8+# The two cadences worth offering in a chat; anything finer belongs in the UI's rrule editor.+# The scan tool takes no tags or scale, so it offers only the types a prompt alone configures.+_INLINE_SCAN_TYPES = {ScannerType.MONITOR, ScannerType.SUMMARIZER}++_CADENCE_RRULES = {+ "daily": f"FREQ=DAILY;BYHOUR={_SUMMARY_HOUR};BYMINUTE=0",+ "weekly": f"FREQ=WEEKLY;BYHOUR={_SUMMARY_HOUR};BYMINUTE=0",+}+++def _dedup(session_ids: list[str]) -> list[str]:+ """Order-preserving; the same session twice in one batch would just be a wasted no-op."""+ return [s for s in dict.fromkeys(sid.strip() for sid in session_ids) if s]+++def _truncate(text: str, limit: int = 120) -> str:+ collapsed = " ".join(text.split())+ return collapsed if len(collapsed) <= limit else collapsed[: limit - 1] + "\u2026"+++def _spend_sentence(team: Team, model: str, count: int) -> str:+ """The credit sentence every confirmation prompt ends with.++ Spelled out in credits and dollars against what's left, because the whole point of the confirmation+ is that the user can see what the action costs before it happens.+ """+ cost = observation_credits_for_model(model) * count+ remaining = compute_quota_snapshot(team.organization_id).remaining+ if remaining is None:+ return (+ f"about {cost} credits (${cost / CREDITS_PER_DOLLAR:,.2f}). This project has no monthly credit limit set."+ )+ return f"about {cost} credits (${cost / CREDITS_PER_DOLLAR:,.2f}) of the {remaining} left this month."+++def _scan_summary(started: int, results: list[dict[str, str]]) -> str:+ counts: dict[str, int] = {}+ for result in results:+ counts[result["scan_outcome"]] = counts.get(result["scan_outcome"], 0) + 1+ parts = [f"Started {started} scan(s)."]+ if counts.get("already_scanned"):+ parts.append(f"{counts['already_scanned']} already had an answer, reused at no charge.")+ if counts.get("already_running"):+ parts.append(f"{counts['already_running']} were already being scanned.")+ if counts.get("skipped_quota"):+ parts.append(f"{counts['skipped_quota']} were skipped: the monthly credit budget is used up.")+ if counts.get("skipped_limit"):+ parts.append(f"{counts['skipped_limit']} were skipped: too many scans already running.")+ if counts.get("failed"):+ parts.append(f"{counts['failed']} failed to start.")+ if started:+ parts.append("Each recording takes a few minutes. Results appear on the recordings when they finish.")+ return " ".join(parts)+++SCAN_SESSIONS_TOOL_DESCRIPTION = """+Use this tool to have Replay Vision watch specific session recordings and answer a question about them.++# When to use+- The user has recordings in hand (from search_session_recordings, from context, or as explicit ids) and+ asks what happened in them, whether something occurred, or to classify or score them+- The user asks to run an existing scanner against particular sessions++# How it works+Each session is scanned by an LLM that watches the recording. Scanning costs credits from the project's+monthly Replay Vision budget, so the user is asked to confirm before anything starts.++Pass `prompt` for a one-off question: nothing is saved and nothing runs on a schedule. Pass `scanner_id`+instead to run a saved scanner over these sessions. Asking the same question twice reuses the answers it+already has rather than charging again.++# What it returns+Confirmation that scans started, and the scan id to read results through. Results are NOT immediate:+each recording takes minutes. Tell the user results will appear on the recordings, and use+search_replay_vision_observations afterwards to read them.+"""+++class ScanSessionsArgs(BaseModel):+ session_ids: list[str] = Field(+ description="Session recording ids to scan. Ask the user rather than guessing if you don't have them."+ )+ prompt: str | None = Field(+ default=None,+ description=(+ "What to look for, in plain language, for a one-off question. Leave unset when passing "+ "scanner_id. Write it as a direct instruction grounded in what is observable in a recording."+ ),+ )+ scanner_id: str | None = Field(+ default=None,+ description="Run this saved scanner over the sessions instead of a one-off prompt.",+ )+ scanner_type: str = Field(+ default="monitor",+ description=(+ "For a one-off prompt: 'monitor' for an open-ended yes/no observation (the default), "+ "'summarizer' for a free-text summary. Ignored when scanner_id is set."+ ),+ )+++class ScanReplayVisionSessionsTool(ReplayVisionGatesMixin, MaxTool):+ name: str = "scan_replay_vision_sessions"+ description: str = SCAN_SESSIONS_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = ScanSessionsArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ # Scanning mints or runs a scanner and spends credits, so it needs the same bar as creating one,+ # plus recording read because the output exposes recording contents.+ return [("replay_scanner", "editor"), ("session_recording", "viewer")]++ async def format_dangerous_operation_preview(+ self, session_ids: list[str], prompt: str | None = None, scanner_id: str | None = None, **kwargs+ ) -> str:+ return await self._preview(_dedup(session_ids), prompt, scanner_id)++ @database_sync_to_async+ def _preview(self, sessions: list[str], prompt: str | None, scanner_id: str | None) -> str:+ """One hop: the scanner lookup and the credit sentence share a connection."""+ model: str = DEFAULT_SCAN_MODEL+ what = f'the question "{_truncate(prompt or "")}"'+ if scanner_id:+ # The same gate the execution path applies. Without it, anyone who can use the tool could+ # pass a scanner id they can't read and see its name and cost in their own approval prompt.+ scanner = self._editable_scanner(scanner_id)+ model = scanner.model if scanner else DEFAULT_SCAN_MODEL+ # The scanner name is user-editable, so it stays out of model-visible tool output; this+ # preview is rendered to the user who owns it, not fed back to the model.+ what = f"the saved scanner '{scanner.name}'" if scanner else f"the saved scanner (id {scanner_id})"+ return f"**Scan {len(sessions)} session(s)** with {what}. This spends {_spend_sentence(self._team, model, len(sessions))}"++ def _editable_scanner(self, scanner_id: str) -> ReplayScanner | None:+ """A saved scanner this user may run.++ Configured only: an inline scan's scanner is a throwaway the reaper may collect, so re-targeting+ one would point a scan at a row that can vanish underneath it.+ """+ if not is_uuid(scanner_id):+ return None+ scanner = ReplayScanner.objects.filter(team_id=self._team.id, id=scanner_id).first()+ if scanner is None or not self.user_access_control.check_access_level_for_object(scanner, "editor"):+ return None+ return scanner++ async def _arun_impl(+ self,+ session_ids: list[str],+ prompt: str | None = None,+ scanner_id: str | None = None,+ scanner_type: str = "monitor",+ ) -> tuple[str, dict[str, Any]]:+ enabled, consent = await self._gates()+ if not enabled:+ return self._not_enabled()+ sessions = _dedup(session_ids)+ if not sessions:+ return "No session ids to scan.", {"error": "no_sessions"}+ if len(sessions) > MAX_SESSIONS_PER_SCAN:+ return (+ f"That's {len(sessions)} recordings; {MAX_SESSIONS_PER_SCAN} is the most one scan can take. "+ "Narrow the selection and try again.",+ {"error": "too_many_sessions"},+ )+ if not consent:+ return self._no_ai_consent()+ return await self._start_scan(sessions, prompt, scanner_id, scanner_type)++ @database_sync_to_async+ def _start_scan(+ self, sessions: list[str], prompt: str | None, scanner_id: str | None, scanner_type: str+ ) -> tuple[str, dict[str, Any]]:+ if scanner_id:+ scanner = self._editable_scanner(scanner_id)+ if scanner is None:+ return f"Scanner {scanner_id} not found.", {"error": "not_found"}+ started, results = scan_existing_scanner(scanner=scanner, session_ids=sessions, user=self._user)+ return _scan_summary(started, results), {"scan_id": str(scanner.id), "results": results}++ if not prompt or not prompt.strip():+ return "Pass either a prompt or a scanner_id.", {"error": "no_prompt"}+ # Only the two types whose whole config is a prompt. A classifier or scorer would need tags or+ # a scale, which this tool's schema deliberately doesn't take, and would fail validation with a+ # message about a field the model was never offered.+ resolved_type = scanner_type if scanner_type in _INLINE_SCAN_TYPES else ScannerType.MONITOR+ config = {"prompt": prompt.strip()}+ # Length and shape, through the validator the API uses. This config persists on the scanner and+ # is copied into every observation snapshot, so an unbounded prompt would live on both.+ message = scanner_config_error(ScannerType(resolved_type), config)+ if message is not None:+ return message, {"error": "invalid_config"}+ scan = run_inline_scan(+ team=self._team,+ user=self._user,+ session_ids=sessions,+ scanner_type=ScannerType(resolved_type),+ scanner_config=config,+ model=DEFAULT_SCAN_MODEL,+ )+ if scan.scanner is None:+ return (+ "Nothing started: this project's monthly Replay Vision credits are used up.",+ {"error": "quota_exhausted"},+ )+ return _scan_summary(scan.started, scan.results), {"scan_id": str(scan.scanner.id), "results": scan.results}+++QUOTA_TOOL_DESCRIPTION = """+Use this tool to read the project's Replay Vision credit budget for the current billing month.++# When to use+- Before proposing a broad scanner or a large batch of scans, to check what the budget can absorb+- The user asks what Replay Vision has cost, how much budget is left, or why scans are being skipped++# What it returns+Credits used, credits remaining, the monthly limit, when the period resets, and the projected monthly+spend of the scanners already running. Reading this costs nothing.+"""+++class ReplayVisionQuotaArgs(BaseModel):+ pass+++class GetReplayVisionQuotaTool(ReplayVisionGatesMixin, MaxTool):+ # Reading the budget spends nothing.+ spends_credits: ClassVar[bool] = False+ name: str = "get_replay_vision_quota"+ description: str = QUOTA_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = ReplayVisionQuotaArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("replay_scanner", "viewer")]++ async def _arun_impl(self) -> tuple[str, dict[str, Any]]:+ if not await self._is_enabled():+ return self._not_enabled()+ return await self._read()++ @database_sync_to_async+ def _read(self) -> tuple[str, dict[str, Any]]:+ snapshot = compute_quota_snapshot(self._team.organization_id)+ resets = snapshot.period_end.strftime("%b %-d")+ if snapshot.credit_limit is None:+ content = (+ f"{snapshot.credits_used} credits used this period, which resets on {resets}. "+ "This project has no monthly credit limit set."+ )+ else:+ content = (+ f"{snapshot.credits_used} of {snapshot.credit_limit} credits used, "+ f"{snapshot.remaining} left. The period resets on {resets}. "+ f"Scanners already running are projected to use {snapshot.projected_monthly_credits} a month."+ )+ return content, {+ "credits_used": snapshot.credits_used,+ "credit_limit": snapshot.credit_limit,+ "credits_remaining": snapshot.remaining,+ "projected_monthly_credits": snapshot.projected_monthly_credits,+ "period_end": snapshot.period_end.isoformat(),+ }+++RETRY_OBSERVATION_TOOL_DESCRIPTION = """+Use this tool to scan a recording again after its observation failed or came back ineligible.++# When to use+- The user asks to retry, re-run, or try again on an observation that failed+- A search result shows a failed observation and the user wants another attempt++# What it does+Deletes the failed result and starts a fresh scan of the same recording with the same scanner. This+costs credits like any other scan, so the user is asked to confirm first. Only failed and ineligible+observations can be retried; a succeeded one already has its answer.+"""+++class RetryObservationArgs(BaseModel):+ observation_id: str = Field(description="The failed or ineligible observation to scan again.")+++class RetryReplayVisionObservationTool(ReplayVisionGatesMixin, MaxTool):+ name: str = "retry_replay_vision_observation"+ description: str = RETRY_OBSERVATION_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = RetryObservationArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("replay_scanner", "editor"), ("session_recording", "viewer")]++ async def format_dangerous_operation_preview(self, observation_id: str, **kwargs) -> str:+ return await self._preview(observation_id)++ @database_sync_to_async+ def _preview(self, observation_id: str) -> str:+ """One hop: the observation lookup and the credit sentence share a connection."""+ # Access-checked before anything is rendered: the preview would otherwise disclose the recording+ # id and cost of an observation whose scanner the caller can't read.+ observation = self._editable_observation(observation_id)+ if observation is None:+ return f"Retry observation {observation_id}"+ spend = _spend_sentence(self._team, observation.scanner.model, 1)+ return f"**Scan recording {observation.session_id} again**, replacing the failed result. This spends {spend}"++ def _editable_observation(self, observation_id: str) -> ReplayObservation | None:+ """An observation this user may retry. Observations inherit their scanner's RBAC, and both the+ preview and the execution path need the same answer."""+ if not is_uuid(observation_id):+ return None+ observation = (+ ReplayObservation.objects.filter(team_id=self._team.id, id=observation_id).select_related("scanner").first()+ )+ if observation is None or not self.user_access_control.check_access_level_for_object(+ observation.scanner, "editor"+ ):+ return None+ return observation++ async def _arun_impl(self, observation_id: str) -> tuple[str, dict[str, Any]]:+ enabled, consent = await self._gates()+ if not enabled:+ return self._not_enabled()+ if not consent:+ return self._no_ai_consent()+ return await self._retry(observation_id)++ @database_sync_to_async+ def _retry(self, observation_id: str) -> tuple[str, dict[str, Any]]:+ observation = self._editable_observation(observation_id)+ if observation is None:+ return f"Observation {observation_id} not found.", {"error": "not_found"}+ try:+ outcome, _ = retry_observation(observation=observation, user=self._user)+ except QuotaLimitExceeded:+ return (+ "Not retried: this project's monthly Replay Vision credits are used up.",+ {"error": "quota_exhausted"},+ )+ except Throttled:+ return (+ "Not retried: too many scans are already running for this project. Try again in a few minutes.",+ {"error": "capped"},+ )+ if outcome is RetryOutcome.NOT_RETRYABLE:+ return (+ "Only failed or ineligible observations can be retried.",+ {"error": "not_retryable"},+ )+ if outcome is RetryOutcome.ALREADY_RUNNING:+ return (+ "The previous run for that recording is still finishing. Try again in a moment.",+ {"error": "already_running"},+ )+ if outcome is RetryOutcome.CAPPED:+ return (+ "Too many scans are already running for this project. Try again in a few minutes.",+ {"error": "capped"},+ )+ if outcome is not RetryOutcome.STARTED:+ return "Couldn't start the retry. Try again in a moment.", {"error": "start_failed"}+ return (+ f"Scanning recording {observation.session_id} again. It takes a few minutes.",+ {"session_id": observation.session_id, "scanner_id": str(observation.scanner_id)},+ )+++def _first_error(errors: Any) -> str:+ """The first message out of a DRF error tree, for a chat that has no field to attach it to."""+ if isinstance(errors, dict):+ for value in errors.values():+ return _first_error(value)+ if isinstance(errors, list) and errors:+ return _first_error(errors[0])+ # Neutralized: a uniqueness message echoes a user-editable name straight back into model context.+ return neutralize_markup(str(errors))+++def _scanner_config_for(+ scanner_type: ScannerType,+ prompt: str,+ *,+ tags: list[str] | None,+ scale_min: float | None,+ scale_max: float | None,+ length: str | None,+) -> dict[str, Any]:+ """Assemble the per-type config from flat args.++ Flat rather than a nested object because the model fills these in one shot, and a missing piece+ should come back as the validator's own message ("Scale is required.") rather than a schema error.+ Type-specific keys are only included for their type, since the validator rejects unknown ones.+ """+ config: dict[str, Any] = {"prompt": prompt.strip()}+ if scanner_type == ScannerType.CLASSIFIER and tags is not None:+ config["tags"] = tags+ if scanner_type == ScannerType.SCORER and (scale_min is not None or scale_max is not None):+ config["scale"] = {"min": scale_min, "max": scale_max}+ if scanner_type == ScannerType.SUMMARIZER and length is not None:+ config["length"] = length+ return config+++CREATE_SCANNER_TOOL_DESCRIPTION = """+Use this tool to create a Replay Vision scanner: a standing watch that scans every future recording+matching a filter.++# When to use+- The user wants recordings that haven't happened yet to be scanned automatically+- The user asks to monitor, track, classify or score sessions on an ongoing basis++# When NOT to use+- The user has recordings in hand and a question about them. That's scan_replay_vision_sessions, which+ saves nothing and schedules nothing. Never create a scanner just to answer one question and delete it.++# Cost+An enabled scanner sweeps every 5 minutes and spends credits on each matching recording, so it can drain+a monthly budget on its own. Creating one enabled asks the user to confirm, with the projected monthly+spend. Create it disabled (`enabled: false`) to set it up without spending anything yet.++Call get_replay_vision_quota first when proposing anything broad, and prefer a `sampling_rate` below 1.0+over an unfiltered scanner.+"""+++class CreateScannerArgs(BaseModel):+ name: str = Field(description="Human-readable name, unique within the project.")+ prompt: str = Field(+ description=(+ "The instruction the model follows while watching one recording. Write it as a direct, "+ "specific question grounded in observable behavior, e.g. 'Did the user fail to complete "+ "checkout?'. Avoid vague adjectives and anything the model can't see in a recording."+ )+ )+ scanner_type: str = Field(+ default="monitor",+ description=(+ "What each observation produces: 'monitor' for a yes/no answer with a reason, 'classifier' "+ "to assign tags from a fixed vocabulary, 'scorer' for a number on a scale, 'summarizer' for "+ "a free-text summary."+ ),+ )+ tags: list[str] | None = Field(+ default=None,+ description=(+ "Classifiers only, and required for them: the fixed vocabulary the model picks from, e.g. "+ "['abandoned cart', 'payment error', 'browsing']. Cover the outcomes the user cares about "+ "and keep them distinguishable from each other."+ ),+ )+ scale_min: float | None = Field(+ default=None,+ description="Scorers only, and required for them: the low end of the scale, e.g. 0.",+ )+ scale_max: float | None = Field(+ default=None,+ description="Scorers only, and required for them: the high end of the scale, e.g. 5.",+ )+ length: str | None = Field(+ default=None,+ description="Summarizers only, optional: 'short', 'medium' (the default) or 'long'.",+ )+ sampling_rate: float = Field(+ default=1.0,+ description="Fraction of matching recordings to scan, 0 to 1. Lower this to control spend.",+ )+ enabled: bool = Field(+ default=False,+ description=(+ "Leave false to create it without starting the sweep, which spends nothing. Set true only "+ "when the user has agreed to the recurring cost."+ ),+ )+++class CreateReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):+ name: str = "create_replay_vision_scanner"+ description: str = CREATE_SCANNER_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = CreateScannerArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("replay_scanner", "editor"), ("session_recording", "viewer")]++ async def is_dangerous_operation(self, enabled: bool = False, **kwargs) -> bool:+ # Argument-dependent, so the mixin's `spends_credits` doesn't decide it: a disabled scanner has+ # no schedule and spends nothing, and only an enabled one needs a decision.+ return enabled is True++ async def format_dangerous_operation_preview(self, name: str = "", sampling_rate: float = 1.0, **kwargs) -> str:+ return await self._preview(name, sampling_rate)++ @database_sync_to_async+ def _preview(self, name: str, sampling_rate: float) -> str:+ spend = _spend_sentence(self._team, DEFAULT_SCAN_MODEL, 1)+ sampled = "" if sampling_rate >= 1.0 else f" It samples {sampling_rate:.0%} of them."+ return (+ f"**Create and enable** scanner '{name}'. It scans every new recording from now on, "+ f"sweeping every 5 minutes.{sampled} Each recording costs {spend} "+ "Create it disabled instead if you want to size it first."+ )++ async def _arun_impl(+ self,+ name: str,+ prompt: str,+ scanner_type: str = "monitor",+ sampling_rate: float = 1.0,+ enabled: bool = False,+ tags: list[str] | None = None,+ scale_min: float | None = None,+ scale_max: float | None = None,+ length: str | None = None,+ ) -> tuple[str, dict[str, Any]]:+ is_on, consent = await self._gates()+ if not is_on:+ return self._not_enabled()+ # Not gated on `enabled`: the serializer refuses to create either kind without consent, so+ # checking only for enabled ones turned the disabled path into an unhandled exception.+ if not consent:+ return self._no_ai_consent()+ return await self._create(+ name, prompt, scanner_type, sampling_rate, enabled, tags, scale_min, scale_max, length+ )++ @database_sync_to_async+ def _create(+ self,+ name: str,+ prompt: str,+ scanner_type: str,+ sampling_rate: float,+ enabled: bool,+ tags: list[str] | None,+ scale_min: float | None,+ scale_max: float | None,+ length: str | None,+ ) -> tuple[str, dict[str, Any]]:+ resolved_type = scanner_type if scanner_type in VALID_SCANNER_TYPES else ScannerType.MONITOR+ # Through the serializer, not ReplayScanner.objects.create: it owns the sampling-rate floor below+ # which a scanner silently never scans, the unique-name race, the estimate refresh, the built-in+ # daily digest, and the lifecycle event. A scanner Max makes should be the same object the UI makes.+ serializer = ReplayScannerSerializer(+ data={+ "name": name.strip(),+ "scanner_type": resolved_type,+ "scanner_config": _scanner_config_for(+ ScannerType(resolved_type),+ prompt,+ tags=tags,+ scale_min=scale_min,+ scale_max=scale_max,+ length=length,+ ),+ "model": DEFAULT_SCAN_MODEL,+ "sampling_rate": sampling_rate,+ "enabled": enabled,+ },+ context={"get_team": lambda: self._team, "user": self._user},+ )+ if not serializer.is_valid():+ return _first_error(serializer.errors), {"error": "invalid_config"}+ scanner = serializer.save()+ state = (+ "It's running and will scan new recordings as they arrive."+ if enabled+ else "It's turned off for now, so it isn't scanning or spending anything. Enable it when you're ready."+ )+ # The name stays out of `content`, which the model reads: it's user-editable from here on, and+ # the file's own rule keeps it outside the data fence. The artifact goes to the frontend.+ return f"Created the {resolved_type} scanner. {state}", {+ "scanner_name": scanner.name,+ "scanner_id": str(scanner.id),+ "enabled": enabled,+ }+++CREATE_ACTION_TOOL_DESCRIPTION = """+Use this tool to set up a recurring summary of what a Replay Vision scanner is finding.++# When to use+- The user wants a daily or weekly digest of a scanner's observations+- The user asks to be kept updated on what a scanner is seeing, without reading each observation++# What it does+Creates a scheduled group summary: on the cadence you give it, one report is synthesized from the+observations the scanner produced since the last run. It starts no new scans, so it spends no Replay+Vision credits, but each run calls the synthesis model and bills the team's AI credits. That recurs+until someone disables it, so the user is asked to confirm before it is created.++The report appears in the app. Delivering it to Slack or a webhook needs an integration id, so point the+user at the scanner's "Summaries and alerts" tab for that rather than guessing one.++For an alert that fires on a condition rather than a cadence, point the user at that tab too: alerts need+a threshold, a metric and a window that are easier to set there.+"""+++class CreateVisionActionArgs(BaseModel):+ scanner_id: str = Field(description="The scanner whose observations get summarized.")+ name: str = Field(description="Human-readable name, unique within the project.")+ cadence: str = Field(+ default="daily",+ description="How often the summary runs: 'daily' or 'weekly'.",+ )+ focus: str | None = Field(+ default=None,+ description="Optional steer on what the summary should emphasize, e.g. 'group by the feature involved'.",+ )+++class CreateReplayVisionActionTool(ReplayVisionGatesMixin, MaxTool):+ # It spends no Replay Vision observation credits, but each run calls the synthesis model with+ # `$ai_billable`, so it commits the team to recurring AI spend that continues until someone disables+ # it. Recurring, agent-created spend is the case the confirmation exists for.+ spends_credits: ClassVar[bool] = True+ name: str = "create_replay_vision_action"+ description: str = CREATE_ACTION_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = CreateVisionActionArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("vision_action", "editor"), ("session_recording", "viewer")]++ async def format_dangerous_operation_preview(self, name: str = "", cadence: str = "daily", **kwargs) -> str:+ return (+ f"**Create a {cadence} summary** '{name}'. It runs on that schedule from now on, and each run "+ "calls the synthesis model and bills the project's AI credits. It keeps running until someone "+ "disables it. This spends no Replay Vision scanning credits."+ )++ async def _arun_impl(+ self, scanner_id: str, name: str, cadence: str = "daily", focus: str | None = None+ ) -> tuple[str, dict[str, Any]]:+ # Actions sit behind their own flag, and the API 404s without it. Checking only the product flag+ # would let Max create a scheduled job on a project that can't see or manage it.+ if not await self._actions_enabled():+ return "Replay Vision actions are not enabled for this project.", {"error": "not_enabled"}+ return await self._create(scanner_id, name, cadence, focus)++ @database_sync_to_async+ def _actions_enabled(self) -> bool:+ return is_replay_vision_enabled(self._user, self._team) and is_replay_vision_actions_enabled(+ self._user, self._team+ )++ @database_sync_to_async+ def _create(self, scanner_id: str, name: str, cadence: str, focus: str | None) -> tuple[str, dict[str, Any]]:+ rrule = _CADENCE_RRULES.get(cadence.strip().lower())+ if rrule is None:+ return "Cadence has to be 'daily' or 'weekly'.", {"error": "invalid_cadence"}+ # Configured scanners only: a summary is a standing job, and an inline scan's scanner is a+ # throwaway the reaper may collect.+ scanner = (+ ReplayScanner.objects.filter(team_id=self._team.id, id=scanner_id).first() if is_uuid(scanner_id) else None+ )+ # Editor, not viewer: an action is automation bound to the scanner, and _check_action_scanner_access+ # object-checks the target at editor level for writes. Viewer here would let a per-scanner+ # restriction that blocks the API be walked around through Max.+ if scanner is None or not self.user_access_control.check_access_level_for_object(scanner, "editor"):+ return f"Scanner {scanner_id} not found.", {"error": "not_found"}+ # Through the serializer so the rrule and timezone are validated and the unique-name race is+ # handled, rather than writing a trigger_config the scheduler later chokes on.+ serializer = VisionActionSerializer(+ data={+ "name": name.strip(),+ "scanner": str(scanner.id),+ "mode": ActionMode.GROUP_SUMMARY,+ "trigger_config": {"rrule": rrule, "timezone": self._team.timezone or "UTC"},+ "synthesis_config": {"prompt_guide": focus.strip()} if focus and focus.strip() else {},+ },+ # team_id is not optional: the scanner field is team-scoped and fails safe to .none(),+ # so without it the scanner never resolves and every call fails validation.+ context={"get_team": lambda: self._team, "team_id": self._team.id, "user": self._user},+ )+ if not serializer.is_valid():+ return _first_error(serializer.errors), {"error": "invalid_config"}+ action = serializer.save()+ return (+ f"Created a {cadence} summary of that scanner's observations. It appears on the scanner's "+ "'Summaries and alerts' tab, and you can add Slack or webhook delivery there.",+ {"vision_action_id": str(action.id)},+ )diff --git a/products/replay_vision/backend/scanner_config.py b/products/replay_vision/backend/scanner_config.pyindex c0321b278dd4..905d10c75cd2 100644--- a/products/replay_vision/backend/scanner_config.py+++ b/products/replay_vision/backend/scanner_config.py@@ -3,17 +3,19 @@Its own module because both the API serializers and Max validate a config before saving or scanningwith it, and neither should import the other."""-from typing import Any+from typing import Any, castfrom pydantic import ValidationError as PydanticValidationError+from posthog.models.user import User+from products.replay_vision.backend.models.replay_scanner import ScannerTypefrom products.replay_vision.backend.tags import slugify_tagfrom products.replay_vision.backend.temporal.scanners import validate_scanner_config-_MAX_PROMPT_LENGTH = 20_000-_MAX_TAGS = 100-_MAX_TAG_LENGTH = 100+MAX_PROMPT_LENGTH = 20_000+MAX_TAGS = 100+MAX_TAG_LENGTH = 100def scanner_config_error(scanner_type: ScannerType, scanner_config: Any) -> str | None:@@ -22,18 +24,18 @@ def scanner_config_error(scanner_type: ScannerType, scanner_config: Any) -> strprompt = scanner_config.get("prompt")if not isinstance(prompt, str) or not prompt.strip():return "Prompt is required."- if len(prompt) > _MAX_PROMPT_LENGTH:- return f"Prompt can be at most {_MAX_PROMPT_LENGTH:,} characters."+ if len(prompt) > MAX_PROMPT_LENGTH:+ return f"Prompt can be at most {MAX_PROMPT_LENGTH:,} characters."if scanner_type == ScannerType.CLASSIFIER:tags = scanner_config.get("tags") or []if len(tags) == 0:return "Tag vocabulary must have at least one tag."- if len(tags) > _MAX_TAGS:- return f"Tag vocabulary can have at most {_MAX_TAGS} tags."+ if len(tags) > MAX_TAGS:+ return f"Tag vocabulary can have at most {MAX_TAGS} tags."if any(not isinstance(t, str) or not t.strip() for t in tags):return "Tags can't be blank."- if any(len(t) > _MAX_TAG_LENGTH for t in tags):- return f"Tags can be at most {_MAX_TAG_LENGTH} characters."+ if any(len(t) > MAX_TAG_LENGTH for t in tags):+ return f"Tags can be at most {MAX_TAG_LENGTH} characters."# Uniqueness on the slug, since filtering/stripping/search all compare slugified tags downstream.slugged: dict[str, str] = {}for t in tags:@@ -61,3 +63,14 @@ def scanner_config_error(scanner_type: ScannerType, scanner_config: Any) -> strif unknown:return f"Unknown scanner configuration keys: {', '.join(sorted(unknown))}."return None+++def acting_user(context: dict[str, Any]) -> User:+ """Who a serializer write is on behalf of.++ Max has no DRF request, so it passes `user` in the context directly. Everything else that reads the+ request stays optional, since `report_user_action` treats a missing one as "no request-derived+ properties" rather than an error.+ """+ request = context.get("request")+ return cast(User, context.get("user") or (request.user if request is not None else None))diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 12cfeed720f0..75844f6e3492 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -1598,6 +1598,28 @@ class TestObserveAction(_VisionAPITestCase):def observe_url(self, scanner_id: str) -> str:return f"{self.scanners_url}{scanner_id}/observe/"+ def test_no_scan_entrypoint_starts_without_ai_consent(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # This gate went in per-endpoint and was missed twice, on bulk_observe and then observe. Both+ # returned 202 for a scan that never ran, because create_observation fails closed on consent+ # once the workflow is already going. Covering all of them together is what stops a third.+ # Plain loop, not @parameterized: class-level @patch mis-orders expanded args.+ mock_sync_connect.return_value = MagicMock()+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow+ self.organization.is_ai_data_processing_approved = False+ self.organization.save()+ cases = [+ (f"{self.scanners_url}{self.scanner.id}/observe/", {"session_id": "s1"}),+ (f"{self.scanners_url}{self.scanner.id}/bulk_observe/", {"session_ids": ["s1"]}),+ (f"{self.scanners_url}inline_scan/", {"session_ids": ["s1"], "prompt": "did it fail?"}),+ ]+ for url, body in cases:+ resp = self.client.post(url, data=body, format="json")+ self.assertEqual(resp.status_code, 400, f"{url}: {resp.json()}")+ start_workflow.assert_not_called()+def test_a_settled_session_returns_the_existing_observation_and_starts_nothing(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:diff --git a/products/replay_vision/backend/tests/test_max_tools.py b/products/replay_vision/backend/tests/test_max_tools.pyindex b0aae04db8f9..ceb5e82fe336 100644--- a/products/replay_vision/backend/tests/test_max_tools.py+++ b/products/replay_vision/backend/tests/test_max_tools.py@@ -1,8 +1,9 @@import uuid+from typing import Anyimport pytestfrom posthog.test.base import BaseTest-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, PropertyMock, patchfrom django.utils import timezone@@ -10,8 +11,15 @@ from asgiref.sync import sync_to_asyncfrom langchain_core.runnables import RunnableConfigfrom parameterized import parameterized+from posthog.models.team import Team+from products.replay_vision.backend.max_tools import (+ CreateReplayVisionActionTool,+ CreateReplayVisionScannerTool,DraftReplayVisionScannerPromptTool,+ GetReplayVisionQuotaTool,+ RetryReplayVisionObservationTool,+ ScanReplayVisionSessionsTool,SearchReplayVisionObservationsTool,SummarizeReplayVisionSummariesTool,_ObservationFilters,@@ -22,8 +30,13 @@ from products.replay_vision.backend.models.replay_observation import (ReplayObservation,)from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.models.vision_action import VisionAction+from products.replay_vision.backend.scanner_config import MAX_PROMPT_LENGTH+from products.replay_vision.backend.scanning import MAX_SESSIONS_PER_SCANfrom products.replay_vision.backend.tags import slugify_tag+from ee.hogai.tool import ApprovalResumePayload+_FLAG_PATH = "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled"_GENERATE_EMBEDDING_PATH = "products.replay_vision.backend.max_tools.async_generate_embedding"_EXECUTE_HOGQL_PATH = "products.replay_vision.backend.max_tools.execute_hogql_query"@@ -483,3 +496,437 @@ class TestObservationFiltersTagClause:assert "arrayMap" in clauses[0]# The clause carries no inlined tag value — it lives only in the parameterized placeholder, verbatim.assert placeholders["tags"].value == tags+++class TestReplayVisionChargeConfirmation(BaseTest):+ """Every tool that spends Replay Vision credits has to ask first, and say what it costs."""++ def _tool(self, tool_cls):+ config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}+ return tool_cls(team=self.team, user=self.user, config=config)++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_every_charging_tool_asks_before_spending(self):+ # The framework only interrupts for approval when is_dangerous_operation returns True, so a tool+ # that spends credits and forgets to override it would charge the org with no prompt at all.+ # Plain loop, not @parameterized: the tools take different kwargs.+ cases: list[tuple[type, dict[str, Any]]] = [+ (ScanReplayVisionSessionsTool, {"session_ids": ["s1"], "prompt": "did it fail?"}),+ (RetryReplayVisionObservationTool, {"observation_id": str(uuid.uuid4())}),+ (CreateReplayVisionScannerTool, {"enabled": True}),+ # No Replay Vision credits, but each run bills the team's AI credits, on a schedule+ # that continues until someone disables it.+ (CreateReplayVisionActionTool, {}),+ ]+ for tool_cls, kwargs in cases:+ assert await self._tool(tool_cls).is_dangerous_operation(**kwargs) is True, tool_cls.__name__++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_tools_that_spend_nothing_do_not_ask(self):+ # A confirmation prompt for a free action trains users to click through the ones that aren't.+ assert await self._tool(GetReplayVisionQuotaTool).is_dangerous_operation() is False+ # A scanner created disabled has no schedule, so it spends nothing until someone enables it.+ assert await self._tool(CreateReplayVisionScannerTool).is_dangerous_operation(enabled=False) is False++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_scan_preview_names_the_cost_and_the_budget(self):+ # The preview is the only thing the user sees before approving, so it has to carry the number.+ preview = await self._tool(ScanReplayVisionSessionsTool).format_dangerous_operation_preview(+ session_ids=["s1", "s2", "s1"], prompt="did the user hit the coupon bug?"+ )++ # Deduplicated: the same session twice would be a no-op, and charging for it in the preview lies.+ assert "2 session(s)" in preview+ assert "credits" in preview+ assert "did the user hit the coupon bug?" in preview++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_scanner_preview_says_it_is_recurring(self):+ # An enabled scanner's cost is unbounded and recurring, which is the part a user needs to weigh.+ preview = await self._tool(CreateReplayVisionScannerTool).format_dangerous_operation_preview(+ name="checkout-failures", sampling_rate=0.25+ )++ assert "every new recording" in preview+ assert "25%" in preview+ assert "credits" in preview++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_scan_refuses_a_batch_larger_than_one_scan_can_take(self):+ with patch(_FLAG_PATH, return_value=True):+ content, artifact = await self._tool(ScanReplayVisionSessionsTool)._arun_impl(+ session_ids=[f"s{i}" for i in range(MAX_SESSIONS_PER_SCAN + 1)], prompt="did it fail?"+ )++ assert artifact["error"] == "too_many_sessions"+ assert "Narrow the selection" in content++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_scan_stops_when_the_organization_has_not_allowed_ai(self):+ # Fail closed: this is the gate that keeps recordings out of an LLM without consent.+ self.organization.is_ai_data_processing_approved = False+ await sync_to_async(self.organization.save)()++ with patch(_FLAG_PATH, return_value=True):+ content, artifact = await self._tool(ScanReplayVisionSessionsTool)._arun_impl(+ session_ids=["s1"], prompt="did it fail?"+ )++ assert artifact["error"] == "no_ai_consent"+ assert "AI analysis" in content+++class TestCreateReplayVisionScannerTool(BaseTest):+ def _tool(self) -> CreateReplayVisionScannerTool:+ config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}+ return CreateReplayVisionScannerTool(team=self.team, user=self.user, config=config)++ @parameterized.expand(+ [+ ("monitor", {}, {}),+ (+ "classifier",+ {"tags": ["abandoned cart", "payment error"]},+ {"tags": ["abandoned cart", "payment error"]},+ ),+ ("scorer", {"scale_min": 0, "scale_max": 5}, {"scale": {"min": 0, "max": 5}}),+ ("summarizer", {"length": "short"}, {"length": "short"}),+ ]+ )+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_creates_each_scanner_type_with_its_own_config(self, scanner_type, kwargs, expected_extra):+ # Each type needs different config keys, and the shared validator rejects both a missing one and+ # an unknown one. This pins that the tool assembles a config the API would also accept.+ with patch(_FLAG_PATH, return_value=True):+ _, artifact = await self._tool()._arun_impl(+ name=f"{scanner_type}-scanner", prompt="Did the user check out?", scanner_type=scanner_type, **kwargs+ )++ assert "error" not in artifact, artifact+ scanner = await sync_to_async(ReplayScanner.objects.get)(id=artifact["scanner_id"])+ assert scanner.scanner_type == scanner_type+ assert scanner.scanner_config == {"prompt": "Did the user check out?", **expected_extra}+ # Disabled by default, so creating one never starts spending on its own.+ assert scanner.enabled is False++ @parameterized.expand(+ [+ ("classifier_without_tags", "classifier", {}),+ ("scorer_without_scale", "scorer", {}),+ ]+ )+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_rejects_a_type_missing_its_required_config(self, _name, scanner_type, kwargs):+ # Without this the tool would create a scanner the apply workflow can't run.+ with patch(_FLAG_PATH, return_value=True):+ content, artifact = await self._tool()._arun_impl(+ name="incomplete", prompt="Rate the frustration.", scanner_type=scanner_type, **kwargs+ )++ assert artifact["error"] == "invalid_config"+ assert content+ assert not await sync_to_async(ReplayScanner.objects.filter(name="incomplete").exists)()++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_scanner_gets_everything_the_api_gives_it(self):+ # Going direct to ReplayScanner.objects.create skipped the estimate refresh, the built-in daily+ # digest and the lifecycle event, so a Max-made scanner was a second-class one. Routing through+ # the serializer is what keeps them the same object.+ with (+ patch(_FLAG_PATH, return_value=True),+ patch("products.replay_vision.backend.api.scanners._refresh_estimate_fail_soft") as refresh,+ patch("products.replay_vision.backend.api.scanners.report_user_action") as report,+ ):+ _, artifact = await self._tool()._arun_impl(name="from-max", prompt="Did checkout fail?")++ assert "error" not in artifact, artifact+ refresh.assert_called_once()+ assert report.call_args.args[1] == "replay_vision_scanner_created"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_rejects_a_sampling_rate_that_would_never_scan(self):+ # Below one modulo bucket the candidate query matches nothing, so the serializer floors it. The+ # tool used to accept any 0..1 value and could create a scanner that silently never ran.+ with patch(_FLAG_PATH, return_value=True):+ _, artifact = await self._tool()._arun_impl(+ name="too-sparse", prompt="Did checkout fail?", sampling_rate=0.000001+ )++ assert artifact["error"] == "invalid_config"+ assert not await sync_to_async(ReplayScanner.objects.filter(name="too-sparse").exists)()+++_ACTIONS_FLAG_PATH = "products.replay_vision.backend.max_tools.is_replay_vision_actions_enabled"+++class TestCreateReplayVisionActionTool(BaseTest):+ def _tool(self) -> CreateReplayVisionActionTool:+ config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}+ return CreateReplayVisionActionTool(team=self.team, user=self.user, config=config)++ def _scanner(self) -> ReplayScanner:+ return ReplayScanner.objects.create(+ team=self.team,+ name="my-scanner",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user check out?"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )++ @parameterized.expand([("daily",), ("weekly",)])+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_creates_a_summary_on_the_given_cadence(self, cadence):+ # The scanner field is team-scoped and fails safe to .none() without team_id in the serializer+ # context, so without it every call failed validation and the tool could never create anything.+ scanner = await sync_to_async(self._scanner)()++ with patch(_FLAG_PATH, return_value=True), patch(_ACTIONS_FLAG_PATH, return_value=True):+ content, artifact = await self._tool()._arun_impl(+ scanner_id=str(scanner.id), name=f"{cadence}-summary", cadence=cadence+ )++ assert "error" not in artifact, artifact+ action = await sync_to_async(+ lambda: VisionAction.objects.for_team(self.team.id).get(id=artifact["vision_action_id"])+ )()+ assert action.scanner_id == scanner.id+ # An hour is pinned so it fires at a stable time, like every UI-created action and the digest.+ assert "BYHOUR" in action.trigger_config["rrule"]+ assert cadence in content++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_rejects_a_scanner_from_another_team(self):+ other_team = await sync_to_async(Team.objects.create)(organization=self.organization, name="other")+ scanner = await sync_to_async(ReplayScanner.objects.create)(+ team=other_team,+ name="theirs",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )++ with patch(_FLAG_PATH, return_value=True), patch(_ACTIONS_FLAG_PATH, return_value=True):+ _, artifact = await self._tool()._arun_impl(scanner_id=str(scanner.id), name="cross-team")++ assert artifact["error"] == "not_found"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_refuses_when_the_actions_flag_is_off(self):+ # The action API 404s without this flag, so Max must not be a way around it.+ scanner = await sync_to_async(self._scanner)()++ with patch(_FLAG_PATH, return_value=True), patch(_ACTIONS_FLAG_PATH, return_value=False):+ _, artifact = await self._tool()._arun_impl(scanner_id=str(scanner.id), name="gated")++ assert artifact["error"] == "not_enabled"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_requires_editor_on_the_scanner_not_just_viewer(self):+ # An action is automation bound to the scanner. The API object-checks it at editor level, so+ # viewer here would let a per-scanner restriction be walked around through Max.+ scanner = await sync_to_async(self._scanner)()+ tool = self._tool()++ with (+ patch(_FLAG_PATH, return_value=True),+ patch(_ACTIONS_FLAG_PATH, return_value=True),+ patch.object(type(tool), "user_access_control", new_callable=PropertyMock) as uac,+ ):+ # Viewer yes, editor no: exactly the grant the API refuses.+ uac.return_value = MagicMock(+ check_access_level_for_object=MagicMock(side_effect=lambda _s, level: level == "viewer")+ )+ _, artifact = await tool._arun_impl(scanner_id=str(scanner.id), name="viewer-only")++ assert artifact["error"] == "not_found"+++class TestReplayVisionToolAuthorization(BaseTest):+ """Both the preview and the execution path have to refuse; the preview is what leaks."""++ def _tool(self, tool_cls):+ config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}+ return tool_cls(team=self.team, user=self.user, config=config)++ def _scanner(self) -> ReplayScanner:+ return ReplayScanner.objects.create(+ team=self.team,+ name="secret-scanner",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_scan_preview_does_not_name_a_scanner_the_user_cannot_edit(self):+ # The preview renders before execution, so without its own check it discloses the name and the+ # model-derived cost of a scanner RBAC hides. Denial is forced at the access-control boundary+ # rather than through fixtures, since the test user is an org admin by default.+ scanner = await sync_to_async(self._scanner)()+ tool = self._tool(ScanReplayVisionSessionsTool)++ with patch.object(type(tool), "user_access_control", new_callable=PropertyMock) as uac:+ uac.return_value = MagicMock(check_access_level_for_object=MagicMock(return_value=False))+ preview = await tool.format_dangerous_operation_preview(session_ids=["s1"], scanner_id=str(scanner.id))++ assert "secret-scanner" not in preview++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_scan_refuses_a_scanner_the_user_cannot_edit(self):+ scanner = await sync_to_async(self._scanner)()+ tool = self._tool(ScanReplayVisionSessionsTool)++ with (+ patch(_FLAG_PATH, return_value=True),+ patch.object(type(tool), "user_access_control", new_callable=PropertyMock) as uac,+ ):+ uac.return_value = MagicMock(check_access_level_for_object=MagicMock(return_value=False))+ _, artifact = await tool._arun_impl(session_ids=["s1"], scanner_id=str(scanner.id))++ assert artifact["error"] == "not_found"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_scan_refuses_a_scanner_from_another_team(self):+ other_team = await sync_to_async(Team.objects.create)(organization=self.organization, name="other")+ scanner = await sync_to_async(ReplayScanner.objects.create)(+ team=other_team,+ name="theirs",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )++ with patch(_FLAG_PATH, return_value=True):+ _, artifact = await self._tool(ScanReplayVisionSessionsTool)._arun_impl(+ session_ids=["s1"], scanner_id=str(scanner.id)+ )++ assert artifact["error"] == "not_found"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_scan_rejects_an_oversized_prompt(self):+ # The prompt persists on the inline scanner and is copied into every observation snapshot, so+ # the cap belongs on this path too, not only on the DRF serializer.+ with patch(_FLAG_PATH, return_value=True):+ _, artifact = await self._tool(ScanReplayVisionSessionsTool)._arun_impl(+ session_ids=["s1"], prompt="x" * (MAX_PROMPT_LENGTH + 1)+ )++ assert artifact["error"] == "invalid_config"+++class TestReplayVisionApprovalFlowEndToEnd(BaseTest):+ """Through `_arun_with_context`, the entry point the agent actually calls.++ Every other test here calls `_arun_impl` directly, which skips the approval machinery entirely, so+ none of them would notice a tool that spends the org's credits without ever asking.+ """++ def _tool(self, tool_cls):+ config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}+ return tool_cls(team=self.team, user=self.user, config=config)++ def _scanner(self) -> ReplayScanner:+ return ReplayScanner.objects.create(+ team=self.team,+ name="checkout",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user check out?"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )++ @staticmethod+ def _resume(action: str, payload: dict | None = None, feedback: str | None = None) -> dict:+ return ApprovalResumePayload(action=action, payload=payload, feedback=feedback, proposal_id="p1").model_dump()++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_rejecting_a_scan_starts_nothing(self):+ # The whole point of the gate: a refused scan must not reach the workflow starter.+ start = MagicMock()+ with (+ patch(_FLAG_PATH, return_value=True),+ patch("products.replay_vision.backend.api.trigger.sync_connect", MagicMock()),+ patch("products.replay_vision.backend.api.trigger.async_to_sync", return_value=start),+ patch("ee.hogai.tool.interrupt", return_value=self._resume("reject", feedback="too expensive")),+ ):+ content, _ = await self._tool(ScanReplayVisionSessionsTool)._arun_with_context(+ session_ids=["s1", "s2"], prompt="did the user rage click?"+ )++ assert "rejected" in content+ assert "too expensive" in content+ start.assert_not_called()+ assert not await sync_to_async(ReplayScanner.all_origins.filter(origin="inline").exists)()++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_the_preview_the_user_sees_carries_the_cost(self):+ # The interrupt payload is what the frontend renders. If the cost never reaches it, the user is+ # approving a blank cheque, and no assertion on format_dangerous_operation_preview would notice.+ seen = {}++ def _capture(request):+ seen["preview"] = request.preview if hasattr(request, "preview") else request.get("preview")+ return self._resume("reject")++ with patch(_FLAG_PATH, return_value=True), patch("ee.hogai.tool.interrupt", side_effect=_capture):+ await self._tool(ScanReplayVisionSessionsTool)._arun_with_context(+ session_ids=["s1", "s2"], prompt="did the user rage click?"+ )++ assert "2 session(s)" in seen["preview"]+ assert "credits" in seen["preview"]++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_approving_an_edited_session_list_scans_only_what_was_approved(self):+ # The user trims the batch at the prompt. Before the framework fix this ran the original list,+ # charging for recordings they had just removed.+ scanner = await sync_to_async(self._scanner)()+ start = MagicMock(return_value=MagicMock())+ with (+ patch(_FLAG_PATH, return_value=True),+ patch("products.replay_vision.backend.api.trigger.sync_connect", MagicMock()),+ patch("products.replay_vision.backend.api.trigger.async_to_sync", return_value=start),+ patch(+ "ee.hogai.tool.interrupt",+ return_value=self._resume("approve", payload={"session_ids": ["s1"], "scanner_id": str(scanner.id)}),+ ),+ ):+ _, artifact = await self._tool(ScanReplayVisionSessionsTool)._arun_with_context(+ session_ids=["s1", "s2", "s3"], scanner_id=str(scanner.id)+ )++ assert [r["session_id"] for r in artifact["results"]] == ["s1"]+ assert start.call_count == 1++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_reading_the_quota_never_interrupts(self):+ # A prompt for a free action trains people to click through the ones that cost money.+ interrupt = MagicMock()+ with patch(_FLAG_PATH, return_value=True), patch("ee.hogai.tool.interrupt", interrupt):+ content, artifact = await self._tool(GetReplayVisionQuotaTool)._arun_with_context()++ interrupt.assert_not_called()+ assert "error" not in artifact+ assert "credits" in content