Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-vision): give Max the whole scanner and summary lifecycle (#79364)

Tue Haulundf14217025ccd
diff --git a/ee/hogai/core/agent_modes/presets/session_replay.py b/ee/hogai/core/agent_modes/presets/session_replay.py
index 106e23c21fba..6f174e9c6444 100644
--- a/ee/hogai/core/agent_modes/presets/session_replay.py
+++ b/ee/hogai/core/agent_modes/presets/session_replay.py
@@ -102,12 +102,23 @@ class SessionReplayAgentToolkit(AgentToolkit):
def 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 (
+ AnalyzeReplayVisionImpactTool,
CreateReplayVisionActionTool,
CreateReplayVisionScannerTool,
+ DeleteReplayVisionActionTool,
+ DeleteReplayVisionScannerTool,
+ EstimateReplayVisionScannerTool,
GetReplayVisionQuotaTool,
+ LabelReplayVisionObservationTool,
+ ListReplayVisionScannersTool,
+ ReadReplayVisionActionsTool,
RetryReplayVisionObservationTool,
+ RunReplayVisionActionTool,
ScanReplayVisionSessionsTool,
SearchReplayVisionObservationsTool,
+ SuggestReplayVisionTagsTool,
+ UpdateReplayVisionActionTool,
+ UpdateReplayVisionScannerTool,
)
tools: list[type[MaxTool]] = [
@@ -119,6 +130,17 @@ class SessionReplayAgentToolkit(AgentToolkit):
GetReplayVisionQuotaTool,
CreateReplayVisionScannerTool,
CreateReplayVisionActionTool,
+ UpdateReplayVisionScannerTool,
+ AnalyzeReplayVisionImpactTool,
+ DeleteReplayVisionActionTool,
+ DeleteReplayVisionScannerTool,
+ EstimateReplayVisionScannerTool,
+ LabelReplayVisionObservationTool,
+ ListReplayVisionScannersTool,
+ ReadReplayVisionActionsTool,
+ RunReplayVisionActionTool,
+ SuggestReplayVisionTagsTool,
+ UpdateReplayVisionActionTool,
]
return tools
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 66f0c5d8c3a7..d9a8962cd4c5 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -4117,6 +4117,17 @@
"retry_replay_vision_observation",
"get_replay_vision_quota",
"create_replay_vision_scanner",
+ "update_replay_vision_scanner",
+ "list_replay_vision_scanners",
+ "delete_replay_vision_scanner",
+ "estimate_replay_vision_scanner",
+ "label_replay_vision_observation",
+ "analyze_replay_vision_impact",
+ "suggest_replay_vision_tags",
+ "read_replay_vision_actions",
+ "update_replay_vision_action",
+ "delete_replay_vision_action",
+ "run_replay_vision_action",
"create_replay_vision_action",
"upsert_account",
"upsert_account_notebook",
diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.ts
index 7e2dbd8423a9..2ca8cd62651e 100644
--- a/frontend/src/queries/schema/schema-assistant-messages.ts
+++ b/frontend/src/queries/schema/schema-assistant-messages.ts
@@ -524,6 +524,17 @@ export type AssistantTool =
| 'retry_replay_vision_observation'
| 'get_replay_vision_quota'
| 'create_replay_vision_scanner'
+ | 'update_replay_vision_scanner'
+ | 'list_replay_vision_scanners'
+ | 'delete_replay_vision_scanner'
+ | 'estimate_replay_vision_scanner'
+ | 'label_replay_vision_observation'
+ | 'analyze_replay_vision_impact'
+ | 'suggest_replay_vision_tags'
+ | 'read_replay_vision_actions'
+ | 'update_replay_vision_action'
+ | 'delete_replay_vision_action'
+ | 'run_replay_vision_action'
| 'create_replay_vision_action'
| 'upsert_account'
| 'upsert_account_notebook'
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index 4c1cff62639e..6a715ac01bb5 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -838,6 +838,18 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
return 'Creating the scanner...'
},
},
+ update_replay_vision_scanner: {
+ name: 'Update a scanner',
+ description: 'Update a scanner: turn it on or off, rename it, reword it, or change its sampling',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Updated the scanner'
+ }
+ return 'Updating the scanner...'
+ },
+ },
create_replay_vision_action: {
name: 'Summarize a scanner',
description: 'Summarize a scanner on a recurring schedule',
@@ -850,6 +862,126 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
return 'Setting up the summary...'
},
},
+ list_replay_vision_scanners: {
+ name: 'List scanners',
+ description: 'List scanners in this project, with their ids, status and sampling',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'List scanners'
+ }
+ return 'List scanners...'
+ },
+ },
+ delete_replay_vision_scanner: {
+ name: 'Delete a scanner',
+ description: 'Delete a scanner and every observation it produced',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Delete a scanner'
+ }
+ return 'Delete a scanner...'
+ },
+ },
+ estimate_replay_vision_scanner: {
+ name: 'Estimate scanner cost',
+ description: 'Estimate scanner cost: recordings a month and the credits they take',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Estimate scanner cost'
+ }
+ return 'Estimate scanner cost...'
+ },
+ },
+ label_replay_vision_observation: {
+ name: 'Rate a result',
+ description: 'Rate a result: tell Replay Vision whether a scanner got a recording right',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Rate a result'
+ }
+ return 'Rate a result...'
+ },
+ },
+ analyze_replay_vision_impact: {
+ name: 'Measure impact',
+ description: "Measure impact: how many sessions and people a scanner's findings affected",
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Measure impact'
+ }
+ return 'Measure impact...'
+ },
+ },
+ suggest_replay_vision_tags: {
+ name: 'Suggest tags',
+ description: 'Suggest tags for a classifier, grounded in what it has seen',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Suggest tags'
+ }
+ return 'Suggest tags...'
+ },
+ },
+ read_replay_vision_actions: {
+ name: 'Read summaries',
+ description: 'Read summaries and alerts, and the reports they have produced',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Read summaries'
+ }
+ return 'Read summaries...'
+ },
+ },
+ update_replay_vision_action: {
+ name: 'Update a summary',
+ description: 'Update a summary: pause it, resume it, rename it, or change its cadence',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Update a summary'
+ }
+ return 'Update a summary...'
+ },
+ },
+ delete_replay_vision_action: {
+ name: 'Delete a summary',
+ description: 'Delete a summary and every report it has produced',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Delete a summary'
+ }
+ return 'Delete a summary...'
+ },
+ },
+ run_replay_vision_action: {
+ name: 'Run a summary now',
+ description: 'Run a summary now instead of waiting for its schedule',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Run a summary now'
+ }
+ return 'Run a summary now...'
+ },
+ },
create_survey: {
name: 'Create surveys',
description: 'Create surveys in seconds',
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 43e9204e4114..fc7382bfbed4 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -431,6 +431,17 @@ class AssistantTool(StrEnum):
RETRY_REPLAY_VISION_OBSERVATION = "retry_replay_vision_observation"
GET_REPLAY_VISION_QUOTA = "get_replay_vision_quota"
CREATE_REPLAY_VISION_SCANNER = "create_replay_vision_scanner"
+ UPDATE_REPLAY_VISION_SCANNER = "update_replay_vision_scanner"
+ LIST_REPLAY_VISION_SCANNERS = "list_replay_vision_scanners"
+ DELETE_REPLAY_VISION_SCANNER = "delete_replay_vision_scanner"
+ ESTIMATE_REPLAY_VISION_SCANNER = "estimate_replay_vision_scanner"
+ LABEL_REPLAY_VISION_OBSERVATION = "label_replay_vision_observation"
+ ANALYZE_REPLAY_VISION_IMPACT = "analyze_replay_vision_impact"
+ SUGGEST_REPLAY_VISION_TAGS = "suggest_replay_vision_tags"
+ READ_REPLAY_VISION_ACTIONS = "read_replay_vision_actions"
+ UPDATE_REPLAY_VISION_ACTION = "update_replay_vision_action"
+ DELETE_REPLAY_VISION_ACTION = "delete_replay_vision_action"
+ RUN_REPLAY_VISION_ACTION = "run_replay_vision_action"
CREATE_REPLAY_VISION_ACTION = "create_replay_vision_action"
UPSERT_ACCOUNT = "upsert_account"
UPSERT_ACCOUNT_NOTEBOOK = "upsert_account_notebook"
diff --git a/products/replay_vision/backend/api/delivery.py b/products/replay_vision/backend/api/delivery.py
index 2c33d7352727..4d77d905ff2e 100644
--- a/products/replay_vision/backend/api/delivery.py
+++ b/products/replay_vision/backend/api/delivery.py
@@ -1,9 +1,13 @@
+from types import SimpleNamespace
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from posthog.models.user import User
from typing import Any
from django.db.models import QuerySet
import structlog
-from rest_framework.request import Request
from posthog.models import Team
@@ -116,7 +120,7 @@ def _destination_payload(action: VisionAction, target: dict[str, Any]) -> dict[s
return _slack_destination_payload(action, target)
-def provision_delivery(action: VisionAction, *, request: Request, team: Team) -> None:
+def provision_delivery(action: VisionAction, *, user: "User", team: Team) -> None:
"""Reconcile this action's `internal_destination` HogFunctions to its `delivery_config`.
Archive-and-recreate: drop the action's managed destinations, then create one per delivery target
@@ -127,8 +131,9 @@ def provision_delivery(action: VisionAction, *, request: Request, team: Team) ->
if not action.enabled or not action.delivery_config:
return
- # HogFunctionSerializer.create() reads context["request"].user, so provisioning stays in the viewset.
- context = {"request": request, "team_id": team.id, "get_team": lambda: team, "is_create": True}
+ # `HogFunctionSerializer.create()` reads only `context["request"].user`, so a user is all this needs.
+ # Taking one rather than a Request lets callers outside a viewset (the Max tools) provision too.
+ context = {"request": SimpleNamespace(user=user), "team_id": team.id, "get_team": lambda: team, "is_create": True}
for target in action.delivery_config:
serializer = HogFunctionSerializer(data=_destination_payload(action, target), context=context)
serializer.is_valid(raise_exception=True)
diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.py
index 5593e08fd727..7e47a7360acd 100644
--- a/products/replay_vision/backend/api/vision_actions.py
+++ b/products/replay_vision/backend/api/vision_actions.py
@@ -50,7 +50,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 is_uuid, readable_scanner_ids
+from products.replay_vision.backend.scanner_access import readable_scanner_ids, selection_target_ids
from products.replay_vision.backend.scanner_config import acting_user
from products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdict
@@ -589,12 +589,6 @@ 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:
@@ -606,7 +600,7 @@ def _check_action_scanner_access(
scanner's data into another scanner's summary.
"""
view.check_object_permissions(view.request, scanner)
- other_ids = _selection_target_ids(scanner.id, selection)
+ 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)
@@ -718,7 +712,7 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# action that looks created but never delivers.
with transaction.atomic():
action = serializer.save()
- provision_delivery(action, request=self.request, team=self.team)
+ provision_delivery(action, user=acting_user(self.get_serializer_context()), team=self.team)
def perform_update(self, serializer: BaseSerializer) -> None:
instance = cast(VisionAction, serializer.instance)
@@ -742,7 +736,7 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# enabled flag, or the name (each destination is named after the action). Cadence/selection
# edits don't touch the destinations, so they must not churn them.
if action.delivery_config != old_delivery or action.enabled != old_enabled or action.name != old_name:
- provision_delivery(action, request=self.request, team=self.team)
+ provision_delivery(action, user=acting_user(self.get_serializer_context()), team=self.team)
def perform_destroy(self, instance: VisionAction) -> None:
archive_delivery(instance, team=self.team)
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
index 3d669af9d40b..211452923463 100644
--- a/products/replay_vision/backend/max_tools.py
+++ b/products/replay_vision/backend/max_tools.py
@@ -1,6 +1,10 @@
import uuid
from dataclasses import dataclass
-from typing import Any, ClassVar
+from typing import TYPE_CHECKING, Any, ClassVar
+
+from django.db import transaction
+from django.db.models import QuerySet
+from django.utils import timezone
import structlog
from posthoganalytics import capture_exception
@@ -16,11 +20,13 @@ from 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 User
-from posthog.rbac.user_access_control import AccessControlLevel
+from posthog.rbac.user_access_control import AccessControlLevel, UserAccessControl
from posthog.scopes import APIScopeObject
-from posthog.sync import database_sync_to_async
+from posthog.sync import database_sync_to_async, database_sync_to_async_pool
+from products.replay_vision.backend.api.delivery import archive_delivery, provision_delivery
from products.replay_vision.backend.api.scanners import ReplayScannerSerializer
+from products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_process_vision_action_workflow
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_approved
@@ -30,15 +36,23 @@ from products.replay_vision.backend.embeddings import (
OBSERVATION_EMBEDDING_MODEL,
)
from products.replay_vision.backend.feature_flag import is_replay_vision_actions_enabled, is_replay_vision_enabled
+from products.replay_vision.backend.impact import compute_scanner_impact, create_affected_cohort
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
-from products.replay_vision.backend.models.vision_action import ActionMode
+from products.replay_vision.backend.models.vision_action import ActionMode, VisionAction, VisionActionRun
from products.replay_vision.backend.observation_formatting import EVENT_ID_CITATION_RE, format_line, read_output
+from products.replay_vision.backend.queries.scanner_volume_estimate import (
+ ESTIMATE_STALE_AFTER,
+ estimate_scanner_session_volume,
+ project_monthly_observations,
+)
from products.replay_vision.backend.quota import compute_quota_snapshot
from products.replay_vision.backend.scanner_access import (
is_uuid,
scanner_for_reading_observations,
scanners_for_reading_observations,
+ selection_target_ids,
)
from products.replay_vision.backend.scanner_config import scanner_config_error
from products.replay_vision.backend.scanning import (
@@ -48,6 +62,7 @@ from products.replay_vision.backend.scanning import (
run_inline_scan,
scan_existing_scanner,
)
+from products.replay_vision.backend.tag_suggestions import suggest_classifier_tags
from products.replay_vision.backend.tags import clickhouse_slugify_sql, slugify_tag
from ee.hogai.tool import MaxTool
@@ -163,21 +178,28 @@ class ReplayVisionGatesMixin:
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
+ `needs_confirmation` 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.
+
+ Spending credits is the usual reason to confirm but not the only one, which is why this isn't named
+ after cost: deleting a scanner spends nothing and still asks, because it destroys observations the
+ team already paid for.
"""
- spends_credits: ClassVar[bool] = True
+ needs_confirmation: ClassVar[bool] = True
- # Supplied by MaxTool, which every user of this mixin also inherits.
- _user: User
- _team: Team
+ # Supplied by MaxTool, which every user of this mixin also inherits. Typed only for the checker:
+ # a runtime annotation makes pydantic shadow MaxTool's `user_access_control` cached_property.
+ if TYPE_CHECKING:
+ _user: User
+ _team: Team
+ user_access_control: UserAccessControl
async def is_dangerous_operation(self, **kwargs) -> bool:
- return self.spends_credits
+ return self.needs_confirmation
@database_sync_to_async
def _is_enabled(self) -> bool:
@@ -189,10 +211,71 @@ class ReplayVisionGatesMixin:
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)
+ def _scanner_for(self, scanner_id: str, level: AccessControlLevel = "editor") -> "ReplayScanner | None":
+ """A saved scanner this user may act on at `level`.
+
+ Configured only: an inline scan's scanner is a throwaway the reaper may collect, so pointing a
+ saved-scanner operation at one would target 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, level):
+ return None
+ return scanner
+
+ def _action_for(self, action_id: str, level: AccessControlLevel = "editor") -> "VisionAction | None":
+ """An action this user may act on at `level`.
+
+ Mirrors `_check_action_scanner_access` on the API. The bound scanner is checked at `level`,
+ because an action is automation attached to it and a per-scanner restriction has to block it
+ here too. Scanners named only in the selection are pure data sources the action never mutates,
+ so viewer is the bar for those, but they are checked: a summary fans in their observations and
+ its report is derived from all of them.
+
+ The object check on the action itself does not cover either, since `vision_action` inherits the
+ `replay_scanner` resource rather than any individual scanner's ACL.
+ """
+ if not is_uuid(action_id):
+ return None
+ action = VisionAction.objects.for_team(self._team.id).filter(id=action_id).select_related("scanner").first()
+ if action is None or not self.user_access_control.check_access_level_for_object(action, level):
+ return None
+ if not self.user_access_control.check_access_level_for_object(action.scanner, level):
+ return None
+ source_ids = selection_target_ids(action.scanner_id, action.selection)
+ sources = ReplayScanner.objects.filter(team_id=self._team.id, id__in=source_ids)
+ if not all(self.user_access_control.check_access_level_for_object(s, "viewer") for s in sources):
+ return None
+ return action
+
+ def _observation_for(self, observation_id: str, level: AccessControlLevel = "editor") -> "ReplayObservation | None":
+ """An observation this user may act on at `level`. Observations inherit their scanner's RBAC."""
+ 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, level
+ ):
+ return None
+ return observation
+
+ @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
+ )
+
@staticmethod
def _not_enabled() -> tuple[str, dict[str, Any]]:
return "Replay Vision is not enabled for this project.", {"error": "not_enabled"}
+ @staticmethod
+ def _actions_not_enabled() -> tuple[str, dict[str, Any]]:
+ return "Replay Vision actions are not enabled for this project.", {"error": "not_enabled"}
+
@staticmethod
def _no_ai_consent() -> tuple[str, dict[str, Any]]:
return (
@@ -204,7 +287,7 @@ class ReplayVisionGatesMixin:
class DraftReplayVisionScannerPromptTool(ReplayVisionGatesMixin, MaxTool):
# Reads and form-fills only; nothing here starts a scan.
- spends_credits: ClassVar[bool] = False
+ needs_confirmation: ClassVar[bool] = False
name: str = "draft_replay_vision_scanner_prompt"
description: str = DRAFT_PROMPT_TOOL_DESCRIPTION
args_schema: type[BaseModel] = DraftScannerPromptArgs
@@ -242,7 +325,7 @@ class SummarizeSummariesArgs(BaseModel):
class SummarizeReplayVisionSummariesTool(ReplayVisionGatesMixin, MaxTool):
# Reads and form-fills only; nothing here starts a scan.
- spends_credits: ClassVar[bool] = False
+ needs_confirmation: ClassVar[bool] = False
name: str = "summarize_replay_vision_summaries"
description: str = SUMMARIZE_SUMMARIES_TOOL_DESCRIPTION
args_schema: type[BaseModel] = SummarizeSummariesArgs
@@ -423,7 +506,7 @@ class SearchObservationsArgs(BaseModel):
class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):
# Reads and form-fills only; nothing here starts a scan.
- spends_credits: ClassVar[bool] = False
+ needs_confirmation: ClassVar[bool] = False
name: str = "search_replay_vision_observations"
description: str = SEARCH_OBSERVATIONS_TOOL_DESCRIPTION
args_schema: type[BaseModel] = SearchObservationsArgs
@@ -661,6 +744,12 @@ _SUMMARY_HOUR = 8
# 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}
+_MAX_ACTION_RUNS = 10
+# A project can hold hundreds of scanners. The whole list lands in the model's context, so cap it and say so.
+_MAX_LISTED = 50
+# Free text from a model, so it gets a ceiling before it reaches a column.
+MAX_FEEDBACK_LENGTH = 1000
+
_CADENCE_RRULES = {
"daily": f"FREQ=DAILY;BYHOUR={_SUMMARY_HOUR};BYMINUTE=0",
"weekly": f"FREQ=WEEKLY;BYHOUR={_SUMMARY_HOUR};BYMINUTE=0",
@@ -677,19 +766,26 @@ def _truncate(text: str, limit: int = 120) -> str:
return collapsed if len(collapsed) <= limit else collapsed[: limit - 1] + "\u2026"
+def _credit_sentence(team: Team, cost: int, lead: str = "about") -> str:
+ """Credits and dollars against what's left. One phrasing, so a conversation never prices the same
+ number two different ways."""
+ return _price(cost, compute_quota_snapshot(team.organization_id).remaining, lead)
+
+
+def _price(cost: int, remaining: int | None, lead: str = "about") -> str:
+ priced = f"{lead} {cost} credits (${cost / CREDITS_PER_DOLLAR:,.2f})"
+ if remaining is None:
+ return f"{priced}. This project has no monthly credit limit set."
+ return f"{priced} of the {remaining} left this month."
+
+
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."
+ return _credit_sentence(team, observation_credits_for_model(model) * count)
def _scan_summary(started: int, results: list[dict[str, str]]) -> str:
@@ -782,26 +878,13 @@ class ScanReplayVisionSessionsTool(ReplayVisionGatesMixin, MaxTool):
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)
+ scanner = self._scanner_for(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],
@@ -830,7 +913,7 @@ class ScanReplayVisionSessionsTool(ReplayVisionGatesMixin, MaxTool):
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)
+ scanner = self._scanner_for(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)
@@ -883,7 +966,7 @@ class ReplayVisionQuotaArgs(BaseModel):
class GetReplayVisionQuotaTool(ReplayVisionGatesMixin, MaxTool):
# Reading the budget spends nothing.
- spends_credits: ClassVar[bool] = False
+ needs_confirmation: ClassVar[bool] = False
name: str = "get_replay_vision_quota"
description: str = QUOTA_TOOL_DESCRIPTION
args_schema: type[BaseModel] = ReplayVisionQuotaArgs
@@ -954,26 +1037,12 @@ class RetryReplayVisionObservationTool(ReplayVisionGatesMixin, MaxTool):
"""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)
+ observation = self._observation_for(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:
@@ -984,7 +1053,7 @@ class RetryReplayVisionObservationTool(ReplayVisionGatesMixin, MaxTool):
@database_sync_to_async
def _retry(self, observation_id: str) -> tuple[str, dict[str, Any]]:
- observation = self._editable_observation(observation_id)
+ observation = self._observation_for(observation_id)
if observation is None:
return f"Observation {observation_id} not found.", {"error": "not_found"}
try:
@@ -1139,7 +1208,7 @@ class CreateReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):
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
+ # Argument-dependent, so the mixin's `needs_confirmation` 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
@@ -1269,7 +1338,7 @@ 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
+ needs_confirmation: ClassVar[bool] = True
name: str = "create_replay_vision_action"
description: str = CREATE_ACTION_TOOL_DESCRIPTION
args_schema: type[BaseModel] = CreateVisionActionArgs
@@ -1290,15 +1359,9 @@ class CreateReplayVisionActionTool(ReplayVisionGatesMixin, MaxTool):
# 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 self._actions_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())
@@ -1336,3 +1399,938 @@ class CreateReplayVisionActionTool(ReplayVisionGatesMixin, MaxTool):
"'Summaries and alerts' tab, and you can add Slack or webhook delivery there.",
{"vision_action_id": str(action.id)},
)
+
+
+def _monthly_spend_sentence(team: Team, scanner: ReplayScanner, sampling_rate: float) -> str:
+ """Projected monthly cost of running a scanner, which is what enabling actually commits to.
+
+ A per-recording price understates a schedule. The estimate is the same number the UI shows before
+ saving; when it hasn't been computed yet, say so rather than imply a small one-off charge.
+ """
+ observations = scanner.estimated_monthly_observations
+ stale = scanner.estimated_at is None or timezone.now() - scanner.estimated_at >= ESTIMATE_STALE_AFTER
+ if observations is None or stale:
+ return "Its monthly volume hasn't been estimated recently, so the cost isn't known up front."
+ # The stored estimate is for the scanner's saved rate; rescale when the rate is changing.
+ if scanner.sampling_rate:
+ observations = round(observations * sampling_rate / scanner.sampling_rate)
+ cost = observation_credits_for_model(scanner.model) * observations
+ priced = _credit_sentence(team, cost, lead=f"about {observations} recordings a month,")
+ return f"That's {priced}"
+
+
+UPDATE_SCANNER_TOOL_DESCRIPTION = """
+Use this tool to change a saved Replay Vision scanner: turn it on or off, rename it, reword its prompt,
+or change how much of the matching traffic it samples.
+
+# When to use
+- The user wants to enable a scanner they created earlier, or pause one that's running
+- The user wants to reword what a scanner looks for, or dial its sampling up or down
+
+# Cost
+Enabling a scanner starts a sweep that runs every 5 minutes and spends credits on each matching
+recording, so enabling asks the user to confirm and shows the projected monthly spend. Raising the
+sampling rate on a scanner that is already running does the same, because it widens what gets scanned.
+Turning a scanner off, renaming it, or rewording its prompt spends nothing and doesn't ask.
+
+Rewording the prompt does not rescan anything already observed; it applies to recordings scanned from
+then on.
+"""
+
+
+class UpdateScannerArgs(BaseModel):
+ scanner_id: str = Field(description="The scanner to change.")
+ enabled: bool | None = Field(
+ default=None,
+ description="True to start its schedule, false to pause it. Leave unset to keep it as it is.",
+ )
+ name: str | None = Field(default=None, description="New name. Leave unset to keep the current one.")
+ prompt: str | None = Field(
+ default=None,
+ description="New instruction for the scanner. Leave unset to keep the current one.",
+ )
+ sampling_rate: float | None = Field(
+ default=None,
+ description="New fraction of matching recordings to scan, 0 to 1. Leave unset to keep the current one.",
+ )
+
+
+class UpdateReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):
+ name: str = "update_replay_vision_scanner"
+ description: str = UPDATE_SCANNER_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = UpdateScannerArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("replay_scanner", "editor"), ("session_recording", "viewer")]
+
+ async def is_dangerous_operation(
+ self, scanner_id: str = "", enabled: bool | None = None, sampling_rate: float | None = None, **kwargs
+ ) -> bool:
+ # Argument-dependent, so the mixin's `needs_confirmation` doesn't decide it. Only two edits commit
+ # the project to spend: starting the schedule, and widening what a running schedule scans.
+ # Pausing, renaming and rewording all cost nothing.
+ return await self._starts_or_widens_spending(scanner_id, enabled, sampling_rate)
+
+ @database_sync_to_async
+ def _starts_or_widens_spending(self, scanner_id: str, enabled: bool | None, sampling_rate: float | None) -> bool:
+ if enabled is True:
+ return True
+ scanner = self._scanner_for(scanner_id)
+ if scanner is None or enabled is False:
+ return False
+ return sampling_rate is not None and scanner.enabled and sampling_rate > scanner.sampling_rate
+
+ async def format_dangerous_operation_preview(
+ self, scanner_id: str = "", enabled: bool | None = None, sampling_rate: float | None = None, **kwargs
+ ) -> str:
+ return await self._preview(scanner_id, enabled, sampling_rate)
+
+ @database_sync_to_async
+ def _preview(self, scanner_id: str, enabled: bool | None, sampling_rate: float | None) -> str:
+ scanner = self._scanner_for(scanner_id)
+ if scanner is None:
+ return f"Update scanner {scanner_id}"
+ rate = sampling_rate if sampling_rate is not None else scanner.sampling_rate
+ action = "**Turn on**" if enabled is True else "**Widen**"
+ return (
+ f"{action} scanner '{scanner.name}'. It sweeps every 5 minutes, scanning "
+ f"{rate:.0%} of matching recordings, and keeps spending until it's turned off. "
+ f"{_monthly_spend_sentence(self._team, scanner, rate)}"
+ )
+
+ async def _arun_impl(
+ self,
+ scanner_id: str,
+ enabled: bool | None = None,
+ name: str | None = None,
+ prompt: str | None = None,
+ sampling_rate: float | None = None,
+ ) -> tuple[str, dict[str, Any]]:
+ is_on, consent = await self._gates()
+ if not is_on:
+ return self._not_enabled()
+ # The serializer refuses to enable without consent, so answer rather than raise.
+ if enabled is True and not consent:
+ return self._no_ai_consent()
+ return await self._update(scanner_id, enabled, name, prompt, sampling_rate)
+
+ @database_sync_to_async
+ def _update(
+ self,
+ scanner_id: str,
+ enabled: bool | None,
+ name: str | None,
+ prompt: str | None,
+ sampling_rate: float | None,
+ ) -> tuple[str, dict[str, Any]]:
+ scanner = self._scanner_for(scanner_id)
+ if scanner is None:
+ return f"Scanner {scanner_id} not found.", {"error": "not_found"}
+ data: dict[str, Any] = {}
+ if enabled is not None:
+ data["enabled"] = enabled
+ if name is not None:
+ data["name"] = name.strip()
+ if sampling_rate is not None:
+ data["sampling_rate"] = sampling_rate
+ if prompt is not None:
+ # Merged, not replaced: the rest of the config (tags, scale, length) belongs to its type.
+ data["scanner_config"] = {**scanner.scanner_config, "prompt": prompt.strip()}
+ if not data:
+ return "Nothing to change. Say what you want to update.", {"error": "no_changes"}
+ # Through the serializer so the sampling floor, the unique-name race, the estimate refresh on
+ # enable and the version bump all hold, exactly as they do for a UI edit.
+ serializer = ReplayScannerSerializer(
+ scanner,
+ data=data,
+ partial=True,
+ context={"get_team": lambda: self._team, "user": self._user},
+ )
+ if not serializer.is_valid():
+ return _first_error(serializer.errors), {"error": "invalid_config"}
+ updated = serializer.save()
+ state = "It's running now." if updated.enabled else "It's turned off, so it isn't scanning or spending."
+ return f"Updated the scanner. {state}", {
+ "scanner_id": str(updated.id),
+ "enabled": updated.enabled,
+ "changed": sorted(data),
+ }
+
+
+LIST_SCANNERS_TOOL_DESCRIPTION = """
+Use this tool to see the Replay Vision scanners in the project, and to turn a scanner the user names
+into the id every other Replay Vision tool needs.
+
+# When to use
+- The user refers to a scanner by name ("turn on my checkout scanner") and you don't have its id
+- The user asks what scanners exist, which are running, or what they're each watching
+- Before creating a scanner, to check whether one already covers the same question
+
+# What it returns
+Each scanner's id, name, type, whether it's running, its sampling rate, and its estimated monthly
+volume where one has been computed. Reading this costs nothing.
+"""
+
+
+class ListScannersArgs(BaseModel):
+ enabled_only: bool = Field(
+ default=False,
+ description="Only scanners currently running. Leave false to see paused ones too.",
+ )
+
+
+class ListReplayVisionScannersTool(ReplayVisionGatesMixin, MaxTool):
+ # Reading the list spends nothing.
+ needs_confirmation: ClassVar[bool] = False
+ name: str = "list_replay_vision_scanners"
+ description: str = LIST_SCANNERS_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = ListScannersArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("replay_scanner", "viewer")]
+
+ async def _arun_impl(self, enabled_only: bool = False) -> tuple[str, dict[str, Any]]:
+ if not await self._is_enabled():
+ return self._not_enabled()
+ return await self._list(enabled_only)
+
+ @database_sync_to_async
+ def _list(self, enabled_only: bool) -> tuple[str, dict[str, Any]]:
+ # Configured only, and RBAC-filtered like the scanner list endpoint: inline scans are throwaways
+ # and a scanner the caller can't read shouldn't be nameable here.
+ queryset = ReplayScanner.objects.filter(team_id=self._team.id)
+ if enabled_only:
+ queryset = queryset.filter(enabled=True)
+ readable = self.user_access_control.filter_queryset_by_access_level(queryset).order_by("name", "id")
+ scanners = [
+ {
+ "scanner_id": str(s.id),
+ # Names are user-editable, so they go back as untrusted data rather than as prose the
+ # model reads as its own instruction.
+ "name": neutralize_markup(s.name),
+ "scanner_type": s.scanner_type,
+ "enabled": s.enabled,
+ "sampling_rate": s.sampling_rate,
+ "estimated_monthly_observations": s.estimated_monthly_observations,
+ }
+ for s in readable[:_MAX_LISTED]
+ ]
+ if not scanners:
+ return "This project has no Replay Vision scanners yet.", {"scanners": []}
+ total = readable.count()
+ running = sum(1 for s in scanners if s["enabled"])
+ shown = f"{len(scanners)} of {total} scanner(s)" if total > len(scanners) else f"{len(scanners)} scanner(s)"
+ return (
+ f"{shown}, {running} of those running. Their ids are in the result, for use with the "
+ "other Replay Vision tools.",
+ {"scanners": scanners, "total": total},
+ )
+
+
+DELETE_SCANNER_TOOL_DESCRIPTION = """
+Use this tool to delete a Replay Vision scanner.
+
+# When to use
+- The user explicitly asks to delete or remove a scanner
+
+# What it does
+Deletes the scanner and every observation it ever produced. That history is not recoverable, and the
+usage already billed for those scans is not refunded. Pausing is almost always what someone wants
+instead, so offer update_replay_vision_scanner with enabled false first, and only delete when the user
+is clear that's what they mean. The user is asked to confirm, and the prompt says how many observations
+will go with it.
+"""
+
+
+class DeleteScannerArgs(BaseModel):
+ scanner_id: str = Field(description="The scanner to delete, along with all of its observations.")
+
+
+class DeleteReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):
+ # Spends nothing, but destroys history irreversibly, which is its own reason to ask.
+ needs_confirmation: ClassVar[bool] = True
+ name: str = "delete_replay_vision_scanner"
+ description: str = DELETE_SCANNER_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = DeleteScannerArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("replay_scanner", "editor")]
+
+ async def format_dangerous_operation_preview(self, scanner_id: str = "", **kwargs) -> str:
+ return await self._preview(scanner_id)
+
+ @database_sync_to_async
+ def _preview(self, scanner_id: str) -> str:
+ scanner = self._scanner_for(scanner_id)
+ if scanner is None:
+ return f"Delete scanner {scanner_id}"
+ observations = ReplayObservation.objects.filter(team_id=self._team.id, scanner_id=scanner.id).count()
+ return (
+ f"**Delete** scanner '{scanner.name}' and its {observations} observation(s). The results are "
+ "gone for good and the credits already spent on them aren't refunded. Pausing it instead "
+ "keeps the history."
+ )
+
+ async def _arun_impl(self, scanner_id: str) -> tuple[str, dict[str, Any]]:
+ if not await self._is_enabled():
+ return self._not_enabled()
+ return await self._delete(scanner_id)
+
+ @database_sync_to_async
+ def _delete(self, scanner_id: str) -> tuple[str, dict[str, Any]]:
+ scanner = self._scanner_for(scanner_id)
+ if scanner is None:
+ return f"Scanner {scanner_id} not found.", {"error": "not_found"}
+ name, deleted_id = scanner.name, str(scanner.id)
+ scanner.delete()
+ return "Deleted the scanner and its observations.", {"scanner_id": deleted_id, "name": name}
+
+
+ESTIMATE_SCANNER_TOOL_DESCRIPTION = """
+Use this tool to find out how many recordings a scanner would scan each month, and what that would
+cost, before creating or enabling one.
+
+# When to use
+- Before creating a scanner, especially a broad one, so the user can see the monthly spend first
+- Before enabling a scanner the user created earlier
+- The user asks how expensive a scanner would be, or how much traffic it would cover
+
+# What it returns
+Projected recordings a month, the credits that costs, and what's left in the monthly budget. Estimating
+costs nothing and scans nothing.
+
+Pass `scanner_id` to size a scanner that already exists. Pass `sampling_rate` on its own to see what a
+different rate would cost.
+"""
+
+
+class EstimateScannerArgs(BaseModel):
+ scanner_id: str = Field(description="The scanner to size.")
+ sampling_rate: float | None = Field(
+ default=None,
+ description="Try a different fraction of matching recordings, 0 to 1. Leave unset to use the scanner's own.",
+ )
+
+
+class EstimateReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):
+ # Counts candidate sessions; scans nothing.
+ needs_confirmation: ClassVar[bool] = False
+ name: str = "estimate_replay_vision_scanner"
+ description: str = ESTIMATE_SCANNER_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = EstimateScannerArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ # The candidate query runs over recording data, so a probed filter could leak recording metadata.
+ return [("replay_scanner", "viewer"), ("session_recording", "viewer")]
+
+ async def _arun_impl(self, scanner_id: str, sampling_rate: float | None = None) -> tuple[str, dict[str, Any]]:
+ if not await self._is_enabled():
+ return self._not_enabled()
+ return await self._estimate(scanner_id, sampling_rate)
+
+ def _cached_projection(self, scanner: ReplayScanner, rate: float) -> int | None:
+ """The stored estimate, when it's still good for this scanner.
+
+ `ReplayScanner.save` clears `estimated_at` whenever a volume input changes, so a fresh timestamp
+ means the number still matches the config. Rescaling by rate keeps a model iterating on sampling
+ off ClickHouse entirely, which is the common case for this tool.
+ """
+ if scanner.estimated_at is None or scanner.estimated_monthly_observations is None:
+ return None
+ if timezone.now() - scanner.estimated_at >= ESTIMATE_STALE_AFTER:
+ return None
+ if not scanner.sampling_rate:
+ return None
+ return round(scanner.estimated_monthly_observations * rate / scanner.sampling_rate)
+
+ @database_sync_to_async
+ def _estimate(self, scanner_id: str, sampling_rate: float | None) -> tuple[str, dict[str, Any]]:
+ scanner = self._scanner_for(scanner_id, "viewer")
+ if scanner is None:
+ return f"Scanner {scanner_id} not found.", {"error": "not_found"}
+ rate = scanner.sampling_rate if sampling_rate is None else sampling_rate
+ if not 0.0 <= rate <= 1.0:
+ return "Sampling rate has to be between 0 and 1.", {"error": "invalid_sampling_rate"}
+ observations = self._cached_projection(scanner, rate)
+ if observations is None:
+ try:
+ estimate = estimate_scanner_session_volume(
+ team=self._team,
+ query=scanner.recordings_query(),
+ sampling_mode=scanner.sampling_mode,
+ ch_user=ClickHouseUser.REPLAY_VISION,
+ )
+ except Exception:
+ logger.exception("replay_vision.max_tools.estimate_failed", scanner_id=scanner_id)
+ return "Couldn't work out the volume for that scanner just now.", {"error": "estimate_failed"}
+ observations = project_monthly_observations(estimate, rate)
+ cost = observation_credits_for_model(scanner.model) * observations
+ remaining = compute_quota_snapshot(self._team.organization_id).remaining
+ return (
+ f"About {observations} recordings a month at {rate:.0%} sampling, costing roughly "
+ f"{_price(cost, remaining, lead='')}".strip(),
+ {
+ "estimated_monthly_observations": observations,
+ "estimated_monthly_credits": cost,
+ "sampling_rate": rate,
+ "credits_remaining": remaining,
+ },
+ )
+
+
+READ_ACTIONS_TOOL_DESCRIPTION = """
+Use this tool to see the recurring summaries and alerts set up over Replay Vision scanners, and to read
+the reports they've produced.
+
+# When to use
+- The user asks what summaries or alerts exist, or which are running
+- The user asks what the latest summary said, or what a digest found
+- You need an action's id for update, run, or delete
+
+# What it returns
+With no `action_id`, every action with its id, name, mode, cadence and whether it's enabled. With an
+`action_id`, that action's recent runs and their synthesized reports. Reading costs nothing.
+"""
+
+
+class ReadActionsArgs(BaseModel):
+ action_id: str | None = Field(
+ default=None,
+ description="Read this action's recent runs and their reports. Leave unset to list every action.",
+ )
+
+
+class ReadReplayVisionActionsTool(ReplayVisionGatesMixin, MaxTool):
+ # Reading spends nothing.
+ needs_confirmation: ClassVar[bool] = False
+ name: str = "read_replay_vision_actions"
+ description: str = READ_ACTIONS_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = ReadActionsArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ # Reports quote recording-derived output, so reading them needs recording read.
+ return [("vision_action", "viewer"), ("session_recording", "viewer")]
+
+ async def _arun_impl(self, action_id: str | None = None) -> tuple[str, dict[str, Any]]:
+ if not await self._actions_enabled():
+ return self._actions_not_enabled()
+ return await self._read(action_id)
+
+ @database_sync_to_async
+ def _read(self, action_id: str | None) -> tuple[str, dict[str, Any]]:
+ if action_id is None:
+ readable = self._readable_actions().order_by("name", "id")
+ actions = [
+ {
+ "action_id": str(a.id),
+ # User-editable, so it goes back neutralized rather than as prose the model trusts.
+ "name": neutralize_markup(a.name),
+ "mode": a.mode,
+ "enabled": a.enabled,
+ "rrule": (a.trigger_config or {}).get("rrule"),
+ "scanner_id": str(a.scanner_id),
+ }
+ for a in readable[:_MAX_LISTED]
+ ]
+ if not actions:
+ return "This project has no Replay Vision summaries or alerts yet.", {"actions": []}
+ total = readable.count()
+ shown = f"{len(actions)} of {total} action(s)" if total > len(actions) else f"{len(actions)} action(s)"
+ return f"{shown}. Their ids are in the result.", {"actions": actions, "total": total}
+
+ action = self._action_for(action_id, "viewer")
+ if action is None:
+ return f"Action {action_id} not found.", {"error": "not_found"}
+ runs = [
+ {
+ "run_id": str(r.id),
+ "status": r.status,
+ "scheduled_at": r.scheduled_at.isoformat() if r.scheduled_at else None,
+ "observation_count": r.observation_count,
+ # The report is model-written over recording content, so it stays fenced.
+ "report": as_untrusted_data("report", [r.synthesized_markdown]) if r.synthesized_markdown else None,
+ }
+ for r in VisionActionRun.objects.for_team(self._team.id)
+ .filter(vision_action_id=action.id)
+ .order_by("-scheduled_at")[:_MAX_ACTION_RUNS]
+ if self._may_read_run(r)
+ ]
+ if not runs:
+ return "That action hasn't run yet.", {"action_id": action_id, "runs": []}
+ return f"The {len(runs)} most recent run(s) for that action.", {"action_id": action_id, "runs": runs}
+
+ def _may_read_run(self, run: VisionActionRun) -> bool:
+ """Whether this user may read the report a past run produced.
+
+ A run's `observation_ids` reflect the selection at run time, so a later selection edit, or a
+ grant revoked since, can leave the report drawing on a scanner the caller can't read. Same check
+ `VisionActionRunViewSet.retrieve` applies; viewer is the bar, as these are read-only sources.
+ """
+ ids = run.observation_ids if isinstance(run.observation_ids, list) else []
+ if not ids:
+ return True
+ scanner_ids = set(
+ ReplayObservation.objects.filter(team_id=self._team.id, id__in=ids).values_list("scanner_id", flat=True)
+ )
+ scanners = ReplayScanner.objects.filter(team_id=self._team.id, id__in=scanner_ids)
+ return all(self.user_access_control.check_access_level_for_object(s, "viewer") for s in scanners)
+
+ def _readable_actions(self) -> "QuerySet[VisionAction]":
+ """Actions whose bound scanner this user may read.
+
+ The resource-level filter isn't enough alone: `vision_action` inherits the `replay_scanner`
+ resource, not any individual scanner's ACL, so a per-scanner restriction would still leave the
+ action listed along with reports derived from that scanner's observations.
+ """
+ actions = self.user_access_control.filter_queryset_by_access_level(VisionAction.objects.for_team(self._team.id))
+ readable_scanners = self.user_access_control.filter_queryset_by_access_level(
+ ReplayScanner.objects.filter(team_id=self._team.id)
+ )
+ return actions.filter(scanner_id__in=readable_scanners.values("id"))
+
+
+UPDATE_ACTION_TOOL_DESCRIPTION = """
+Use this tool to change a recurring Replay Vision summary or alert: pause it, resume it, rename it, or
+change how often it runs.
+
+# When to use
+- The user wants to stop a summary that keeps arriving, or start one again
+- The user wants a daily digest weekly, or the other way round
+
+# Cost
+Resuming an action means each run calls the synthesis model and bills the project's AI credits, on that
+cadence, until it's paused again, so resuming asks the user to confirm. Pausing and renaming cost
+nothing.
+"""
+
+
+class UpdateActionArgs(BaseModel):
+ action_id: str = Field(description="The summary or alert to change.")
+ enabled: bool | None = Field(
+ default=None, description="False to pause it, true to resume. Leave unset to keep it as it is."
+ )
+ name: str | None = Field(default=None, description="New name. Leave unset to keep the current one.")
+ cadence: str | None = Field(
+ default=None, description="New cadence: 'daily' or 'weekly'. Leave unset to keep the current one."
+ )
+
+
+class UpdateReplayVisionActionTool(ReplayVisionGatesMixin, MaxTool):
+ name: str = "update_replay_vision_action"
+ description: str = UPDATE_ACTION_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = UpdateActionArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("vision_action", "editor"), ("session_recording", "viewer")]
+
+ async def is_dangerous_operation(self, enabled: bool | None = None, **kwargs) -> bool:
+ # Argument-dependent: resuming restarts recurring AI spend, pausing and renaming stop or cost nothing.
+ return enabled is True
+
+ async def format_dangerous_operation_preview(self, action_id: str = "", **kwargs) -> str:
+ return (
+ f"**Resume** summary {action_id}. Each run calls the synthesis model and bills the project's "
+ "AI credits, on its schedule, until it's paused again."
+ )
+
+ async def _arun_impl(
+ self, action_id: str, enabled: bool | None = None, name: str | None = None, cadence: str | None = None
+ ) -> tuple[str, dict[str, Any]]:
+ if not await self._actions_enabled():
+ return self._actions_not_enabled()
+ return await self._update(action_id, enabled, name, cadence)
+
+ @database_sync_to_async
+ def _update(
+ self, action_id: str, enabled: bool | None, name: str | None, cadence: str | None
+ ) -> tuple[str, dict[str, Any]]:
+ action = self._action_for(action_id)
+ if action is None:
+ return f"Action {action_id} not found.", {"error": "not_found"}
+ data: dict[str, Any] = {}
+ if enabled is not None:
+ data["enabled"] = enabled
+ if name is not None:
+ data["name"] = name.strip()
+ if cadence is not None:
+ rrule = _CADENCE_RRULES.get(cadence.strip().lower())
+ if rrule is None:
+ return "Cadence has to be 'daily' or 'weekly'.", {"error": "invalid_cadence"}
+ data["trigger_config"] = {**(action.trigger_config or {}), "rrule": rrule}
+ if not data:
+ return "Nothing to change. Say what you want to update.", {"error": "no_changes"}
+ # Through the serializer so the rrule and timezone stay valid and the unique-name race is handled.
+ serializer = VisionActionSerializer(
+ action,
+ data=data,
+ partial=True,
+ 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"}
+ old_enabled, old_name = action.enabled, action.name
+ # Atomic with the re-provision, matching `perform_update`: a destination failure has to roll the
+ # edit back rather than leave an action whose deliveries describe a state it's no longer in.
+ with transaction.atomic():
+ updated = serializer.save()
+ if updated.enabled != old_enabled or updated.name != old_name:
+ provision_delivery(updated, user=self._user, team=self._team)
+ state = "It's running on its schedule." if updated.enabled else "It's paused, so it won't run or spend."
+ return f"Updated the action. {state}", {"action_id": str(updated.id), "enabled": updated.enabled}
+
+
+DELETE_ACTION_TOOL_DESCRIPTION = """
+Use this tool to delete a recurring Replay Vision summary or alert.
+
+# When to use
+- The user explicitly asks to delete or remove a summary or an alert
+
+# What it does
+Deletes the action and its run history, including the reports it produced. That history is not
+recoverable, and its delivery destinations stop firing. Pausing keeps the history, so offer
+update_replay_vision_action with enabled false first unless the user is clear they want it gone.
+"""
+
+
+class DeleteActionArgs(BaseModel):
+ action_id: str = Field(description="The summary or alert to delete, along with its run history.")
+
+
+class DeleteReplayVisionActionTool(ReplayVisionGatesMixin, MaxTool):
+ # Spends nothing, but destroys the reports it produced.
+ needs_confirmation: ClassVar[bool] = True
+ name: str = "delete_replay_vision_action"
+ description: str = DELETE_ACTION_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = DeleteActionArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("vision_action", "editor")]
+
+ async def format_dangerous_operation_preview(self, action_id: str = "", **kwargs) -> str:
+ return (
+ f"**Delete** action {action_id} and every report it has produced. That history is gone for "
+ "good, and its Slack or webhook deliveries stop. Pausing it instead keeps the reports."
+ )
+
+ async def _arun_impl(self, action_id: str) -> tuple[str, dict[str, Any]]:
+ if not await self._actions_enabled():
+ return self._actions_not_enabled()
+ return await self._delete(action_id)
+
+ @database_sync_to_async
+ def _delete(self, action_id: str) -> tuple[str, dict[str, Any]]:
+ action = self._action_for(action_id)
+ if action is None:
+ return f"Action {action_id} not found.", {"error": "not_found"}
+ # Archive destinations before the row goes, matching `perform_destroy`.
+ archive_delivery(action, team=self._team)
+ action.delete()
+ return "Deleted the action and its reports.", {"action_id": action_id}
+
+
+RUN_ACTION_TOOL_DESCRIPTION = """
+Use this tool to run a Replay Vision summary now, without waiting for its schedule.
+
+# When to use
+- The user wants the latest summary immediately rather than at the next scheduled time
+
+# Cost
+Running it calls the synthesis model once and bills the project's AI credits, so the user is asked to
+confirm. The report is not returned immediately: synthesis takes a little while, and
+read_replay_vision_actions with the action's id shows it once it lands.
+"""
+
+
+class RunActionArgs(BaseModel):
+ action_id: str = Field(description="The summary to run now.")
+
+
+class RunReplayVisionActionTool(ReplayVisionGatesMixin, MaxTool):
+ # One synthesis call, billed to the project's AI credits.
+ needs_confirmation: ClassVar[bool] = True
+ name: str = "run_replay_vision_action"
+ description: str = RUN_ACTION_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = RunActionArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("vision_action", "editor"), ("session_recording", "viewer")]
+
+ async def format_dangerous_operation_preview(self, action_id: str = "", **kwargs) -> str:
+ return (
+ f"**Run** summary {action_id} now. It calls the synthesis model once and bills the project's "
+ "AI credits. This is a one-off; its schedule is unchanged."
+ )
+
+ async def _arun_impl(self, action_id: str) -> tuple[str, dict[str, Any]]:
+ if not await self._actions_enabled():
+ return self._actions_not_enabled()
+ _, consent = await self._gates()
+ if not consent:
+ return self._no_ai_consent()
+ return await self._run_now(action_id)
+
+ @database_sync_to_async
+ def _run_now(self, action_id: str) -> tuple[str, dict[str, Any]]:
+ action = self._action_for(action_id)
+ if action is None:
+ return f"Action {action_id} not found.", {"error": "not_found"}
+ if action.mode != ActionMode.GROUP_SUMMARY:
+ return "Only scheduled summaries can be run on demand.", {"error": "not_runnable"}
+ # scheduled_at=now anchors this run's observation window; the recurring schedule is untouched.
+ _, outcome = start_process_vision_action_workflow(action.id, self._team.id, scheduled_at=timezone.now())
+ if outcome is WorkflowStartOutcome.ALREADY_RUNNING:
+ return (
+ "That summary is already running. Its report will appear when it finishes.",
+ {"action_id": action_id, "already_running": True},
+ )
+ if outcome is not WorkflowStartOutcome.STARTED:
+ return "Couldn't start that summary. Try again in a moment.", {"error": "start_failed"}
+ return (
+ "Started the summary. It takes a little while; read it back with read_replay_vision_actions.",
+ {"action_id": action_id},
+ )
+
+
+LABEL_OBSERVATION_TOOL_DESCRIPTION = """
+Use this tool to record whether a Replay Vision scanner got a recording right.
+
+# When to use
+- The user says a particular result was wrong, or was a good catch
+- You've shown a user an observation and they've told you whether they agree with it
+
+# What it does
+Saves the team's shared verdict on that observation, with optional written context. It's how a scanner's
+accuracy gets tracked, and it feeds prompt improvements later. It costs nothing and doesn't rescan.
+"""
+
+
+class LabelObservationArgs(BaseModel):
+ observation_id: str = Field(description="The observation the user is judging.")
+ is_correct: bool = Field(description="True if the scanner got this recording right, false if it didn't.")
+ feedback: str | None = Field(
+ max_length=MAX_FEEDBACK_LENGTH,
+ default=None,
+ description="Optional note on what it got right or wrong, or what it should have concluded.",
+ )
+
+
+class LabelReplayVisionObservationTool(ReplayVisionGatesMixin, MaxTool):
+ # A rating; nothing is scanned.
+ needs_confirmation: ClassVar[bool] = False
+ name: str = "label_replay_vision_observation"
+ description: str = LABEL_OBSERVATION_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = LabelObservationArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("replay_scanner", "editor"), ("session_recording", "viewer")]
+
+ async def _arun_impl(
+ self, observation_id: str, is_correct: bool, feedback: str | None = None
+ ) -> tuple[str, dict[str, Any]]:
+ if not await self._is_enabled():
+ return self._not_enabled()
+ return await self._label(observation_id, is_correct, feedback)
+
+ @database_sync_to_async
+ def _label(self, observation_id: str, is_correct: bool, feedback: str | None) -> tuple[str, dict[str, Any]]:
+ observation = self._observation_for(observation_id)
+ if observation is None:
+ return f"Observation {observation_id} not found.", {"error": "not_found"}
+ # One shared label per observation, like the API: a second rating replaces the first. Atomic
+ # because the one-to-one turns two concurrent labels into an IntegrityError rather than a retry.
+ with transaction.atomic():
+ ReplayObservationLabel.objects.update_or_create(
+ observation=observation,
+ team_id=observation.team_id,
+ defaults={
+ "is_correct": is_correct,
+ "feedback": (feedback or "").strip()[:MAX_FEEDBACK_LENGTH],
+ "created_by": self._user,
+ },
+ )
+ verdict = "correct" if is_correct else "wrong"
+ return f"Recorded that the scanner was {verdict} on that recording.", {
+ "observation_id": observation_id,
+ "is_correct": is_correct,
+ }
+
+
+IMPACT_TOOL_DESCRIPTION = """
+Use this tool to find out how many sessions and people a scanner's findings affected, and optionally to
+put those people into a cohort.
+
+# When to use
+- The user asks how widespread something is: how many users hit the bug the scanner found
+- The user wants to act on the affected people, e.g. target them in a survey or exclude them from an
+ experiment
+
+# Narrowing
+Pass `tag` for a classifier, or `min_score` / `max_score` for a scorer, to count only the observations
+that match that outcome. Leave them unset to count everything the scanner flagged.
+
+# The cohort
+Set `create_cohort` to true only when the user has asked for one. It writes a static, dated cohort of
+the affected people that does not update itself; asking again makes another one. Counting costs nothing
+and scans nothing.
+"""
+
+
+class ImpactArgs(BaseModel):
+ scanner_id: str = Field(description="The scanner whose findings to measure.")
+ window_days: int = Field(default=30, ge=1, le=365, description="How many days back to count over, 1 to 365.")
+ tag: str | None = Field(default=None, description="Classifiers only: count just this tag.")
+ min_score: float | None = Field(default=None, description="Scorers only: count scores at or above this.")
+ max_score: float | None = Field(default=None, description="Scorers only: count scores at or below this.")
+ create_cohort: bool = Field(
+ default=False,
+ description="Also create a static cohort of the affected people. Only when the user asked for one.",
+ )
+
+
+class AnalyzeReplayVisionImpactTool(ReplayVisionGatesMixin, MaxTool):
+ # Counts existing observations; scans nothing.
+ name: str = "analyze_replay_vision_impact"
+ description: str = IMPACT_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = ImpactArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("replay_scanner", "viewer"), ("session_recording", "viewer")]
+
+ async def is_dangerous_operation(self, create_cohort: bool = False, **kwargs) -> bool:
+ # Counting is free. Writing a cohort is a lasting artifact in the project, so only that branch asks.
+ return create_cohort
+
+ async def format_dangerous_operation_preview(self, **kwargs) -> str:
+ return "**Create a cohort** of the people this scanner flagged. It's a static, dated snapshot."
+
+ async def _arun_impl(
+ self,
+ scanner_id: str,
+ window_days: int = 30,
+ tag: str | None = None,
+ min_score: float | None = None,
+ max_score: float | None = None,
+ create_cohort: bool = False,
+ ) -> tuple[str, dict[str, Any]]:
+ if not await self._is_enabled():
+ return self._not_enabled()
+ return await self._analyze(scanner_id, window_days, tag, min_score, max_score, create_cohort)
+
+ @database_sync_to_async
+ def _analyze(
+ self,
+ scanner_id: str,
+ window_days: int,
+ tag: str | None,
+ min_score: float | None,
+ max_score: float | None,
+ create_cohort: bool,
+ ) -> tuple[str, dict[str, Any]]:
+ # Cohort creation writes, so it needs editor; counting alone needs only viewer.
+ scanner = self._scanner_for(scanner_id, "editor" if create_cohort else "viewer")
+ if scanner is None:
+ return f"Scanner {scanner_id} not found.", {"error": "not_found"}
+ # Raises on filter/scanner-type mismatches the description invites Max to try, and the messages
+ # are written for a person, so hand them back instead of crashing the turn.
+ try:
+ impact = compute_scanner_impact(scanner, window_days, tag=tag, min_score=min_score, max_score=max_score)
+ except ValueError as exc:
+ return str(exc), {"error": "invalid_filters"}
+ artifact: dict[str, Any] = {
+ "affected_sessions": impact.affected_sessions,
+ "affected_users": impact.affected_users,
+ "sessions_without_user": impact.sessions_without_user,
+ "window_days": window_days,
+ }
+ content = (
+ f"{impact.affected_sessions} session(s) and {impact.affected_users} identified person(s) over the "
+ f"last {window_days} days. {impact.sessions_without_user} session(s) had no identified person."
+ )
+ if not create_cohort:
+ return content, artifact
+ # The tool's declared access covers reading the scanner, not writing a cohort. The API checks
+ # this separately for the same reason: cohort access isn't implied by the scanner's.
+ if not self.user_access_control.check_access_level_for_resource("cohort", required_level="editor"):
+ return f"{content} Saving them as a cohort needs cohort edit access.", artifact
+ try:
+ cohort, members = create_affected_cohort(
+ scanner, self._user, window_days, tag=tag, min_score=min_score, max_score=max_score
+ )
+ except ValueError as exc:
+ return f"{content} Couldn't build a cohort: {exc}", artifact
+ artifact |= {"cohort_id": cohort.id, "cohort_members": members}
+ return (
+ f"{content} Put {members} of them into a static cohort, which doesn't update itself.",
+ artifact,
+ )
+
+
+SUGGEST_TAGS_TOOL_DESCRIPTION = """
+Use this tool to propose additional tags for a classifier scanner, grounded in what it has actually seen.
+
+# When to use
+- The user says a classifier's tags don't cover what's showing up in their recordings
+- The user asks what other categories they should be classifying into
+
+# What it returns
+Suggested tags with a reason for each, drawn from the scanner's own observations and the team's other
+classifiers. It only suggests; adding one means updating the scanner's tag vocabulary in the UI, since
+changing a classifier's vocabulary affects how every future observation is read. Costs no Replay Vision
+credits.
+"""
+
+
+class SuggestTagsArgs(BaseModel):
+ scanner_id: str = Field(description="The classifier scanner to suggest additional tags for.")
+
+
+class SuggestReplayVisionTagsTool(ReplayVisionGatesMixin, MaxTool):
+ # Suggests only; nothing is scanned and no scanner is changed.
+ needs_confirmation: ClassVar[bool] = False
+ name: str = "suggest_replay_vision_tags"
+ description: str = SUGGEST_TAGS_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = SuggestTagsArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("replay_scanner", "viewer"), ("session_recording", "viewer")]
+
+ async def _arun_impl(self, scanner_id: str) -> tuple[str, dict[str, Any]]:
+ if not await self._is_enabled():
+ return self._not_enabled()
+ scanner = await self._resolve(scanner_id)
+ if scanner is None:
+ return f"Scanner {scanner_id} not found.", {"error": "not_found"}
+ if scanner.scanner_type != ScannerType.CLASSIFIER:
+ return "Only classifier scanners have a tag vocabulary.", {"error": "not_a_classifier"}
+ # Pooled rather than thread-sensitive: the model call carries a 90s timeout, and the shared
+ # executor would queue every other database operation behind it. Still connection-managed,
+ # because the suggestion path reads observations and event definitions.
+ return await database_sync_to_async_pool(self._suggest)(scanner)
+
+ @database_sync_to_async
+ def _resolve(self, scanner_id: str) -> "ReplayScanner | None":
+ return self._scanner_for(scanner_id, "viewer")
+
+ def _suggest(self, scanner: ReplayScanner) -> tuple[str, dict[str, Any]]:
+ scanner_id = str(scanner.id)
+ try:
+ config = scanner.scanner_config or {}
+ suggestions = suggest_classifier_tags(
+ team=self._team,
+ user=self._user,
+ prompt=config.get("prompt", ""),
+ current_tags=config.get("tags") or [],
+ multi_label=bool(config.get("multi_label")),
+ allow_freeform_tags=bool(config.get("allow_freeform_tags")),
+ scanner=scanner,
+ user_access_control=self.user_access_control,
+ )
+ except Exception:
+ logger.exception("replay_vision.max_tools.suggest_tags_failed", scanner_id=scanner_id)
+ return "Couldn't come up with tag suggestions just now.", {"error": "suggest_failed"}
+ if not suggestions:
+ return "Nothing worth adding to that scanner's tags right now.", {"suggestions": []}
+ # Model-written over recording content, so it stays behind the fence.
+ return as_untrusted_data("suggested tags", [f"{s.tag}: {s.rationale}" for s in suggestions]), {
+ "suggestions": [{"tag": s.tag, "rationale": s.rationale} for s in suggestions]
+ }
diff --git a/products/replay_vision/backend/scanner_access.py b/products/replay_vision/backend/scanner_access.py
index 0399c68f1201..a3f68325f5fd 100644
--- a/products/replay_vision/backend/scanner_access.py
+++ b/products/replay_vision/backend/scanner_access.py
@@ -6,7 +6,7 @@ Also home to the two queries that read observations back across scanner origins,
appears once instead of at every reading call site."""
import uuid
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from posthog.models.team import Team
from posthog.rbac.user_access_control import UserAccessControl
@@ -67,3 +67,13 @@ def readable_scanner_ids(user: "User", team: Team, scanner_ids: list[str]) -> li
ReplayScanner.objects.filter(team_id=team.id, id__in=valid_ids)
)
return [str(scanner_id) for scanner_id in readable.values_list("id", flat=True)]
+
+
+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`.
+
+ Shared so the API and the Max tools authorize an action against the same set. A summary fans in
+ observations from every scanner named here, so access to the bound one is not access to the report.
+ """
+ configured = (selection or {}).get("scanner_ids") or []
+ return {str(s) for s in configured if is_uuid(s)} - {str(scanner_id)}
diff --git a/products/replay_vision/backend/tests/test_max_tools.py b/products/replay_vision/backend/tests/test_max_tools.py
index ceb5e82fe336..533c6de4bb08 100644
--- a/products/replay_vision/backend/tests/test_max_tools.py
+++ b/products/replay_vision/backend/tests/test_max_tools.py
@@ -12,16 +12,25 @@ from langchain_core.runnables import RunnableConfig
from parameterized import parameterized
from posthog.models.team import Team
+from posthog.rbac.user_access_control import UserAccessControl
+import products.replay_vision.backend.max_tools as max_tools_module
from products.replay_vision.backend.max_tools import (
+ AnalyzeReplayVisionImpactTool,
CreateReplayVisionActionTool,
CreateReplayVisionScannerTool,
+ DeleteReplayVisionScannerTool,
DraftReplayVisionScannerPromptTool,
GetReplayVisionQuotaTool,
+ LabelReplayVisionObservationTool,
+ ListReplayVisionScannersTool,
+ ReadReplayVisionActionsTool,
RetryReplayVisionObservationTool,
+ RunReplayVisionActionTool,
ScanReplayVisionSessionsTool,
SearchReplayVisionObservationsTool,
SummarizeReplayVisionSummariesTool,
+ UpdateReplayVisionScannerTool,
_ObservationFilters,
)
from products.replay_vision.backend.models.replay_observation import (
@@ -29,15 +38,23 @@ from products.replay_vision.backend.models.replay_observation import (
ObservationTrigger,
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.models.replay_observation_label import ReplayObservationLabel
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerOrigin, ScannerType
+from products.replay_vision.backend.models.vision_action import (
+ ActionMode,
+ VisionAction,
+ VisionActionRun,
+ VisionActionRunStatus,
+)
from products.replay_vision.backend.scanner_config import MAX_PROMPT_LENGTH
from products.replay_vision.backend.scanning import MAX_SESSIONS_PER_SCAN
from products.replay_vision.backend.tags import slugify_tag
-from ee.hogai.tool import ApprovalResumePayload
+from ee.hogai.tool import ApprovalResumePayload, MaxTool
_FLAG_PATH = "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled"
+# The estimate refresh runs a ClickHouse query; these tests are about the tool, not the query.
+_REFRESH_ESTIMATE_PATH = "products.replay_vision.backend.api.scanners._refresh_estimate_fail_soft"
_GENERATE_EMBEDDING_PATH = "products.replay_vision.backend.max_tools.async_generate_embedding"
_EXECUTE_HOGQL_PATH = "products.replay_vision.backend.max_tools.execute_hogql_query"
@@ -930,3 +947,436 @@ class TestReplayVisionApprovalFlowEndToEnd(BaseTest):
interrupt.assert_not_called()
assert "error" not in artifact
assert "credits" in content
+
+
+class TestUpdateReplayVisionScannerTool(BaseTest):
+ def _tool(self, tool_cls=None):
+ config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}
+ cls = tool_cls or UpdateReplayVisionScannerTool
+ return cls(team=self.team, user=self.user, config=config)
+
+ def _scanner(self, **overrides) -> ReplayScanner:
+ defaults: dict = {
+ "team": self.team,
+ "name": "checkout",
+ "scanner_type": ScannerType.MONITOR,
+ "scanner_config": {"prompt": "did the user check out?"},
+ "model": ScannerModel.GEMINI_3_6_FLASH,
+ "enabled": False,
+ "estimated_monthly_observations": 400,
+ # The model always stamps this alongside the count; the preview treats a missing one as stale.
+ "estimated_at": timezone.now(),
+ }
+ defaults.update(overrides)
+ return ReplayScanner.objects.create(**defaults)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_a_scanner_created_by_max_can_then_be_enabled(self):
+ # The create tool defaults to disabled and tells Max to size it first, which was a dead end
+ # until this tool existed: nothing could turn the scanner on afterwards.
+ with patch(_FLAG_PATH, return_value=True), patch(_REFRESH_ESTIMATE_PATH):
+ _, created = await self._tool(CreateReplayVisionScannerTool)._arun_impl(
+ name="from-max", prompt="Did checkout fail?"
+ )
+ assert created["enabled"] is False
+
+ _, updated = await self._tool()._arun_impl(scanner_id=created["scanner_id"], enabled=True)
+
+ assert "error" not in updated, updated
+ assert updated["enabled"] is True
+ scanner = await sync_to_async(ReplayScanner.objects.get)(id=created["scanner_id"])
+ assert scanner.enabled is True
+
+ @parameterized.expand(
+ [
+ # Only starting a schedule or widening a running one commits the project to spend.
+ ("enabling", {"enabled": True}, True),
+ ("pausing", {"enabled": False}, False),
+ ("renaming", {"name": "renamed"}, False),
+ ("rewording", {"prompt": "Did they bounce?"}, False),
+ ]
+ )
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_only_spending_edits_ask_for_confirmation(self, _name, kwargs, expected):
+ scanner = await sync_to_async(self._scanner)()
+
+ assert await self._tool().is_dangerous_operation(scanner_id=str(scanner.id), **kwargs) is expected
+
+ @parameterized.expand(
+ [
+ ("raising_on_a_running_scanner", True, 0.9, True),
+ ("raising_on_a_paused_one", False, 0.9, False),
+ ("lowering", True, 0.1, False),
+ ]
+ )
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_sampling_changes_ask_only_when_they_widen_live_spend(self, _name, enabled, rate, expected):
+ scanner = await sync_to_async(self._scanner)(enabled=enabled, sampling_rate=0.5)
+
+ assert await self._tool().is_dangerous_operation(scanner_id=str(scanner.id), sampling_rate=rate) is expected
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_the_enable_preview_gives_the_monthly_cost_not_a_per_recording_one(self):
+ # A schedule's cost is recurring, so a per-recording price would understate what is being agreed to.
+ scanner = await sync_to_async(self._scanner)(sampling_rate=1.0)
+
+ preview = await self._tool().format_dangerous_operation_preview(scanner_id=str(scanner.id), enabled=True)
+
+ assert "400 recordings a month" in preview
+ assert "until it's turned off" in preview
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_says_so_when_the_volume_has_never_been_estimated(self):
+ # Silence here would read as a small one-off charge.
+ scanner = await sync_to_async(self._scanner)(estimated_monthly_observations=None)
+
+ preview = await self._tool().format_dangerous_operation_preview(scanner_id=str(scanner.id), enabled=True)
+
+ assert "hasn't been estimated" in preview
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_rewording_keeps_the_rest_of_the_config(self):
+ # A classifier's tags must survive a prompt edit; replacing the config would drop them.
+ scanner = await sync_to_async(self._scanner)(
+ scanner_type=ScannerType.CLASSIFIER,
+ scanner_config={"prompt": "classify this", "tags": ["abandoned", "paid"]},
+ )
+
+ with patch(_FLAG_PATH, return_value=True), patch(_REFRESH_ESTIMATE_PATH):
+ _, artifact = await self._tool()._arun_impl(scanner_id=str(scanner.id), prompt="classify it better")
+
+ assert "error" not in artifact, artifact
+ await sync_to_async(scanner.refresh_from_db)()
+ assert scanner.scanner_config == {"prompt": "classify it better", "tags": ["abandoned", "paid"]}
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_refuses_a_scanner_the_user_cannot_edit(self):
+ scanner = await sync_to_async(self._scanner)()
+ tool = self._tool()
+
+ 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(scanner_id=str(scanner.id), enabled=True)
+
+ assert artifact["error"] == "not_found"
+
+
+class TestEveryReplayVisionToolDeclaresItsCost(BaseTest):
+ """One place that pins what every tool costs.
+
+ The gate is per-tool, so the failure mode is a new tool quietly defaulting to the wrong side. This
+ enumerates the whole surface, so adding a tool without deciding fails here rather than in production.
+ """
+
+ # Every Replay Vision MaxTool, and whether using it should ask the user first.
+ _EXPECTED = {
+ # Spend Replay Vision observation credits.
+ "scan_replay_vision_sessions": True,
+ "retry_replay_vision_observation": True,
+ # Spend the project's AI credits, on a schedule or immediately.
+ "create_replay_vision_action": True,
+ "run_replay_vision_action": True,
+ # Destroy history irreversibly.
+ "delete_replay_vision_scanner": True,
+ "delete_replay_vision_action": True,
+ # Read-only, or write nothing that costs.
+ "list_replay_vision_scanners": False,
+ "estimate_replay_vision_scanner": False,
+ "get_replay_vision_quota": False,
+ "search_replay_vision_observations": False,
+ "summarize_replay_vision_summaries": False,
+ "draft_replay_vision_scanner_prompt": False,
+ "label_replay_vision_observation": False,
+ "analyze_replay_vision_impact": None, # only when it creates a cohort
+ "suggest_replay_vision_tags": False,
+ "read_replay_vision_actions": False,
+ # Argument-dependent, so they override is_dangerous_operation rather than the flag.
+ "create_replay_vision_scanner": None,
+ "update_replay_vision_scanner": None,
+ "update_replay_vision_action": None,
+ }
+
+ def _tools(self) -> dict[str, Any]:
+ return {
+ cls.model_fields["name"].default: cls
+ for cls in vars(max_tools_module).values()
+ if isinstance(cls, type)
+ and issubclass(cls, MaxTool)
+ and cls is not MaxTool
+ and isinstance(cls.model_fields.get("name") and cls.model_fields["name"].default, str)
+ }
+
+ def test_every_tool_is_accounted_for(self):
+ # A new tool that nobody classified is the thing this catches.
+ assert set(self._tools()) == set(self._EXPECTED), (
+ "A Replay Vision tool was added or renamed without deciding whether it needs confirmation."
+ )
+
+ def test_flagged_tools_match_their_declared_cost(self):
+ # Plain loop, not @parameterized: the mapping is the fixture.
+ for name, cls in self._tools().items():
+ expected = self._EXPECTED[name]
+ if expected is None:
+ # Argument-dependent tools decide per call; covered by their own tests.
+ assert "is_dangerous_operation" in vars(cls), f"{name} was expected to decide per call"
+ continue
+ assert cls.needs_confirmation is expected, name
+
+
+class TestReplayVisionLifecycleTools(BaseTest):
+ """The tools that close the create-then-manage loop."""
+
+ 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, **overrides) -> ReplayScanner:
+ defaults: dict = {
+ "team": self.team,
+ "name": "checkout",
+ "scanner_type": ScannerType.MONITOR,
+ "scanner_config": {"prompt": "did the user check out?"},
+ "model": ScannerModel.GEMINI_3_6_FLASH,
+ }
+ defaults.update(overrides)
+ return ReplayScanner.objects.create(**defaults)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_listing_gives_max_the_ids_every_other_tool_needs(self):
+ # Without this, "turn on my checkout scanner" is unresolvable: every write tool takes an id and
+ # nothing else in the toolset produces one.
+ scanner = await sync_to_async(self._scanner)()
+
+ with patch(_FLAG_PATH, return_value=True):
+ _, artifact = await self._tool(ListReplayVisionScannersTool)._arun_impl()
+
+ assert [s["scanner_id"] for s in artifact["scanners"]] == [str(scanner.id)]
+ assert artifact["scanners"][0]["name"] == "checkout"
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_listing_hides_inline_scans(self):
+ # An inline scan's scanner is a throwaway the reaper may collect; naming it here would invite
+ # Max to point standing operations at a row that can vanish.
+ await sync_to_async(self._scanner)()
+ await sync_to_async(ReplayScanner.all_origins.create)(
+ team=self.team,
+ name="",
+ origin=ScannerOrigin.INLINE,
+ inline_key="k",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "one-off"},
+ model=ScannerModel.GEMINI_3_6_FLASH,
+ enabled=False,
+ sampling_rate=0.0,
+ )
+
+ with patch(_FLAG_PATH, return_value=True):
+ _, artifact = await self._tool(ListReplayVisionScannersTool)._arun_impl()
+
+ assert len(artifact["scanners"]) == 1
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_delete_preview_says_how_much_history_goes_with_it(self):
+ # Deleting cascades the observations away, and the credits spent on them aren't refunded, so the
+ # count is the thing the user needs before agreeing.
+ scanner = await sync_to_async(self._scanner)()
+ await sync_to_async(ReplayObservation.objects.create)(
+ scanner=scanner,
+ session_id="s1",
+ scanner_snapshot={"scanner_type": "monitor"},
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=timezone.now(),
+ )
+
+ preview = await self._tool(DeleteReplayVisionScannerTool).format_dangerous_operation_preview(
+ scanner_id=str(scanner.id)
+ )
+
+ assert "1 observation(s)" in preview
+ assert "Pausing it instead" in preview
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_deleting_takes_the_observations_with_it(self):
+ scanner = await sync_to_async(self._scanner)()
+ await sync_to_async(ReplayObservation.objects.create)(
+ scanner=scanner,
+ session_id="s1",
+ scanner_snapshot={"scanner_type": "monitor"},
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=timezone.now(),
+ )
+
+ with patch(_FLAG_PATH, return_value=True):
+ _, artifact = await self._tool(DeleteReplayVisionScannerTool)._arun_impl(scanner_id=str(scanner.id))
+
+ assert "error" not in artifact, artifact
+ assert not await sync_to_async(ReplayObservation.objects.filter(session_id="s1").exists)()
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_labelling_records_the_teams_verdict(self):
+ scanner = await sync_to_async(self._scanner)()
+ observation = await sync_to_async(ReplayObservation.objects.create)(
+ scanner=scanner,
+ session_id="s1",
+ scanner_snapshot={"scanner_type": "monitor"},
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=timezone.now(),
+ )
+
+ with patch(_FLAG_PATH, return_value=True):
+ _, artifact = await self._tool(LabelReplayVisionObservationTool)._arun_impl(
+ observation_id=str(observation.id), is_correct=False, feedback="it missed the coupon step"
+ )
+
+ assert "error" not in artifact, artifact
+ label = await sync_to_async(ReplayObservationLabel.objects.get)(observation_id=observation.id)
+ assert label.is_correct is False
+ assert label.feedback == "it missed the coupon step"
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_impact_does_not_create_a_cohort_unless_asked(self):
+ # Cohort creation is a write with a dated, non-updating result, so it stays opt-in.
+ scanner = await sync_to_async(self._scanner)()
+
+ with patch(_FLAG_PATH, return_value=True):
+ _, artifact = await self._tool(AnalyzeReplayVisionImpactTool)._arun_impl(scanner_id=str(scanner.id))
+
+ assert "cohort_id" not in artifact
+ assert artifact["affected_sessions"] == 0
+
+
+class TestReplayVisionActionScannerAccess(BaseTest):
+ """A per-scanner restriction has to reach the action tools, not just the API.
+
+ Both holes these cover shipped in review-clean code: the object check on the action row passes even
+ when the user can't read the scanner, because `vision_action` inherits the `replay_scanner` resource
+ rather than any one scanner's ACL.
+ """
+
+ 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 _action_on_unreadable_scanner(self) -> VisionAction:
+ scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="private",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "did they check out?"},
+ model=ScannerModel.GEMINI_3_6_FLASH,
+ )
+ return VisionAction.all_teams.create(
+ team=self.team,
+ scanner=scanner,
+ name="weekly digest",
+ mode=ActionMode.GROUP_SUMMARY,
+ trigger_config={"rrule": "FREQ=WEEKLY;BYDAY=MO;BYHOUR=8"},
+ )
+
+ def _deny_scanners(self):
+ # Deny the scanner object while leaving the action row readable, which is the shape that slipped through.
+ return patch.object(
+ UserAccessControl,
+ "check_access_level_for_object",
+ side_effect=lambda obj, level, **kw: not isinstance(obj, ReplayScanner),
+ )
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_running_a_summary_needs_access_to_its_scanner(self):
+ action = await sync_to_async(self._action_on_unreadable_scanner)()
+
+ with patch(_FLAG_PATH, return_value=True), patch(_ACTIONS_FLAG_PATH, return_value=True), self._deny_scanners():
+ _, artifact = await self._tool(RunReplayVisionActionTool)._arun_impl(action_id=str(action.id))
+
+ assert artifact["error"] == "not_found"
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_listing_hides_actions_on_scanners_the_user_cannot_read(self):
+ # The queryset filter alone leaves these listed, along with the reports derived from them.
+ await sync_to_async(self._action_on_unreadable_scanner)()
+
+ with (
+ patch(_FLAG_PATH, return_value=True),
+ patch(_ACTIONS_FLAG_PATH, return_value=True),
+ patch.object(
+ UserAccessControl,
+ "filter_queryset_by_access_level",
+ side_effect=lambda qs, **kw: qs.none() if qs.model is ReplayScanner else qs,
+ ),
+ ):
+ _, artifact = await self._tool(ReadReplayVisionActionsTool)._arun_impl()
+
+ assert artifact["actions"] == []
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_alerts_cannot_be_run_on_demand(self):
+ # The API rejects this; alerts fire from their own trigger, so a manual run would bill for nothing.
+ action = await sync_to_async(self._action_on_unreadable_scanner)()
+ action.mode = ActionMode.ALERT
+ await sync_to_async(action.save)(update_fields=["mode"])
+
+ with patch(_FLAG_PATH, return_value=True), patch(_ACTIONS_FLAG_PATH, return_value=True):
+ _, artifact = await self._tool(RunReplayVisionActionTool)._arun_impl(action_id=str(action.id))
+
+ assert artifact["error"] == "not_runnable"
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_impact_reports_a_bad_filter_instead_of_crashing(self):
+ # A classifier with no tag is exactly what the tool description invites, and it used to raise.
+ scanner = await sync_to_async(ReplayScanner.objects.create)(
+ team=self.team,
+ name="themes",
+ scanner_type=ScannerType.CLASSIFIER,
+ scanner_config={"prompt": "what went wrong?", "tags": ["checkout"]},
+ model=ScannerModel.GEMINI_3_6_FLASH,
+ )
+
+ with patch(_FLAG_PATH, return_value=True):
+ _, artifact = await self._tool(AnalyzeReplayVisionImpactTool)._arun_impl(scanner_id=str(scanner.id))
+
+ assert artifact["error"] == "invalid_filters"
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_reading_one_actions_runs_returns_its_reports(self):
+ # The runs branch was unexercised, which is how a fail-closed manager call that raises rather
+ # than returning empty reached a reviewer instead of a test.
+ action = await sync_to_async(self._action_on_unreadable_scanner)()
+ await sync_to_async(VisionActionRun.all_teams.create)(
+ team=self.team,
+ vision_action=action,
+ status=VisionActionRunStatus.COMPLETED,
+ scheduled_at=timezone.now(),
+ synthesized_markdown="Checkout dropped off at payment.",
+ observation_count=3,
+ )
+
+ with patch(_FLAG_PATH, return_value=True), patch(_ACTIONS_FLAG_PATH, return_value=True):
+ _, artifact = await self._tool(ReadReplayVisionActionsTool)._arun_impl(action_id=str(action.id))
+
+ assert "error" not in artifact, artifact
+ assert len(artifact["runs"]) == 1
+ assert "Checkout dropped off" in artifact["runs"][0]["report"]
diff --git a/products/replay_vision/backend/tests/test_vision_action_delivery.py b/products/replay_vision/backend/tests/test_vision_action_delivery.py
index 367dc12bffbc..d54806fc7089 100644
--- a/products/replay_vision/backend/tests/test_vision_action_delivery.py
+++ b/products/replay_vision/backend/tests/test_vision_action_delivery.py
@@ -1,11 +1,9 @@
-from typing import Any, cast
+from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from parameterized import parameterized
-from rest_framework.request import Request
-from rest_framework.test import APIRequestFactory
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as template_slack
@@ -104,12 +102,6 @@ class TestVisionActionDelivery(APIBaseTest):
self.assertEqual(resp.status_code, 201, resp.content)
return VisionAction.all_teams.get(id=resp.json()["id"])
- def _request(self) -> Request:
- # provision_delivery threads a DRF Request into HogFunctionSerializer, which reads request.user.
- drf_request = Request(APIRequestFactory().post("/"))
- drf_request.user = self.user
- return cast(Request, drf_request)
-
def _provision_action(self, delivery_config: list[dict[str, Any]]) -> VisionAction:
"""Create an action with delivery_config set on the model and provision it directly, bypassing
the API serializer so a delivery type's provisioning can be exercised independently of the
@@ -122,7 +114,7 @@ class TestVisionActionDelivery(APIBaseTest):
delivery_config=delivery_config,
)
action.save()
- provision_delivery(action, request=self._request(), team=self.team)
+ provision_delivery(action, user=self.user, team=self.team)
return action
def _destinations(self, action: VisionAction) -> list[HogFunction]:
@@ -295,6 +287,6 @@ class TestVisionActionDelivery(APIBaseTest):
action.delivery_config = [{"type": "webhook", "url": "https://example.com/hook"}]
action.save(update_fields=["delivery_config"])
- provision_delivery(action, request=self._request(), team=self.team)
+ provision_delivery(action, user=self.user, team=self.team)
self.assertEqual([d.template_id for d in self._destinations(action)], ["template-webhook"])