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.

fix(replay-vision): turn off scanners that can never run (#127006)

Tue Haulund235c421ba7e1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index daf02ae64b1e..316b9f84b0a6 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -15262,6 +15262,18 @@ snapshots:
hash: v1.k794b7964.0dac77dbf97e99deb916b18c338f397b1c7c58d305dcb722c2c397f1efe2167f.CH2uxVc4xyfRne0meiJNYXeK1aiNC9KaBpAX_EVhWiQ
scenes-app-replay-vision-test-account-filter-settings-dialog--default--light:
hash: v1.k794b7964.4a45317cf1541935394cc4f27a9b29c17f0c8aeaebb6a832fd947dca51c1dacd.-SOqokEQ4yQf2ZbX4EM6nY2csQRt0E46XT4F1g_pTlE
+ scenes-app-replay-vision-turnonscannerdialogs--ai-analysis-off-for-member--dark:
+ hash: v1.k794b7964.238cf8eb3a06540830339849b738e02b6cac0d03b7438de02470a3638a1342d0.ozXyQycz4MSjgE431seFDLk5_6476JKQa5WU0zhUiok
+ scenes-app-replay-vision-turnonscannerdialogs--ai-analysis-off-for-member--light:
+ hash: v1.k794b7964.153bfc6e24f67d51d5ceb29e5dc824d21570e24b52203450f0c9d84afa3874c2.bFOeLkCAFHnYwgMGkmjbyYNYYQ_EWIyipgjO89aU7_E
+ scenes-app-replay-vision-turnonscannerdialogs--allow-ai-analysis--dark:
+ hash: v1.k794b7964.01e452a9ea0f81c71c5ebba699aec1bb6f0e0cd03490465d58edee3e64e9cf15.uIWrmx84lDf7ARJjo2q97S3LnZ0RE_xlzVLTb8yth-E
+ scenes-app-replay-vision-turnonscannerdialogs--allow-ai-analysis--light:
+ hash: v1.k794b7964.8679a15ce3dacad2c7f93831fa345f52f91a5bca338c5d9133514ba00aeddda4.Q9YaKK36sfV3blZJhhanRHc1IgO0p51Qpoka8p2h80w
+ scenes-app-replay-vision-turnonscannerdialogs--take-over-scanner--dark:
+ hash: v1.k794b7964.e391483793d6250bb523edbac11fcf15bdb907b2080050b568a7f5b507f7294e.aCN72Q-58kxiOHZ_2E_98WurauukO9ItvLt3lWnU2U4
+ scenes-app-replay-vision-turnonscannerdialogs--take-over-scanner--light:
+ hash: v1.k794b7964.eeb66851276718735e3a1250a6e6a9b4773cd8797a6eb824f002c6326a6977f1.yZjfBMDZiVyie0_KRHhuiaTNmSsqDvsfzUPmZQecm2o
scenes-app-saved-insights--empty-state--dark:
hash: v1.k794b7964.8186a1849accab762928456f98db977a9b097cf28199d7e1eb6c1e841500852c.SXNRf2LgiH3DkvhwUukZcGqDXngv1kGiEhGYUAhlKC8
scenes-app-saved-insights--empty-state--light:
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 0f0a032f57bb..c7df64259a3f 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -136,10 +136,14 @@ from products.replay_vision.backend.quota import (
spend_projection,
)
from products.replay_vision.backend.scanner_access import (
+ SCANNER_CREATOR_LOST_ACCESS_CODE,
accessible_experiment_ids,
accessible_observations,
+ can_read_targeted_experiment,
+ creator_can_scan,
is_experiment_accessible,
readable_observation_scanner_ids,
+ recording_viewer_access,
scanner_experiment_scope_q,
scanners_for_reading_observations,
)
@@ -575,6 +579,15 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
required=False,
help_text="When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work.",
)
+ take_over_as_creator = serializers.BooleanField(
+ required=False,
+ write_only=True,
+ help_text=(
+ "Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. "
+ "The caller becomes the scanner's creator, and scheduled scans then run as the caller. "
+ f"Without it, that request fails with code `{SCANNER_CREATOR_LOST_ACCESS_CODE}`."
+ ),
+ )
emits_signals = serializers.BooleanField(
required=False,
help_text="When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals.",
@@ -679,6 +692,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
"scanner_type",
"goal",
"creation_method",
+ "take_over_as_creator",
"scanner_config",
"prompt_question",
"query",
@@ -852,6 +866,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
if duplicates.exists():
raise serializers.ValidationError({"name": "A scanner with this name already exists in this team."})
self._reject_scanner_type_change(attrs)
+ self._check_turning_on(attrs)
self._restore_redacted_experiment_config(attrs)
self._validate_scanner_config(attrs)
self._validate_experiment_scanner(attrs)
@@ -867,6 +882,43 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
)
return attrs
+ def _check_turning_on(self, attrs: dict[str, Any]) -> None:
+ # The sweep turns a scanner without consent or a creator with recording access straight back off.
+ # Kept in attrs only when this save hands the scanner over, so `update` can act on it.
+ take_over = attrs.pop("take_over_as_creator", False)
+ if self.instance is None or self.instance.enabled or not attrs.get("enabled"):
+ return
+ if not self.context["get_team"]().organization.is_ai_data_processing_approved:
+ raise serializers.ValidationError(
+ "Your organization needs to allow AI analysis before you can turn on a Replay Vision scanner.",
+ code=AI_CONSENT_REQUIRED_CODE,
+ )
+ if not creator_can_scan(self.instance):
+ if not take_over:
+ raise serializers.ValidationError(
+ "This scanner's creator can no longer view recordings, so turning it on makes you its creator. "
+ "Confirm the take-over to turn it on.",
+ code=SCANNER_CREATOR_LOST_ACCESS_CODE,
+ )
+ self._check_can_take_over(self.instance)
+ attrs["take_over_as_creator"] = True
+
+ def _check_can_take_over(self, scanner: ReplayScanner) -> None:
+ # The creator scans as themselves and manages the scanner's access, so the new one needs all of it.
+ if recording_viewer_access(acting_user(self.context), scanner.team) is None:
+ raise serializers.ValidationError(
+ {"enabled": "You need access to session recordings to take over this scanner."}
+ )
+ access = cast(UserAccessControl, self.user_access_control)
+ if not access.check_can_modify_access_levels_for_object(scanner):
+ raise serializers.ValidationError(
+ {"enabled": "You need permission to manage this scanner's access to take it over."}
+ )
+ if not can_read_targeted_experiment(access, scanner.team_id, scanner):
+ raise serializers.ValidationError(
+ {"enabled": "You need access to this scanner's experiment to take it over."}
+ )
+
def _drop_redacted_targeting_clear(self, attrs: dict[str, Any]) -> None:
# to_representation redacts experiment_targeting to null for callers denied the experiment,
# and the editor form writes the whole object back on save. Without this, any save by such
@@ -1151,6 +1203,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
# Tags are not a scanner column: keep them out of the before/after getattr diff below.
# The mixin's update (reached via super()) persists them as TaggedItem rows.
tags = validated_data.pop("tags", None)
+ takes_over = validated_data.pop("take_over_as_creator", False)
# A scanner is built once, so this says nothing about an edit. Dropped here because the UI
# PATCHes the whole form back and would otherwise send it into the getattr diff below.
validated_data.pop("creation_method", None)
@@ -1163,6 +1216,9 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
# The UI PATCHes the whole form on save, so edits are detected by comparing values, not keys.
before = {field: getattr(instance, field) for field in validated_data}
was_enabled = instance.enabled
+ if takes_over:
+ # Set after `before`, so the handover is not reported as an edit.
+ validated_data["created_by"] = acting_user(self.context)
limit_changed = any(
field in validated_data and validated_data[field] != getattr(instance, field)
for field in ("credit_limit", "free_only")
diff --git a/products/replay_vision/backend/experiment_launch.py b/products/replay_vision/backend/experiment_launch.py
index 91e8647faa61..6c6ac7432aef 100644
--- a/products/replay_vision/backend/experiment_launch.py
+++ b/products/replay_vision/backend/experiment_launch.py
@@ -17,10 +17,13 @@ def start_scanners_waiting_for_launch(
Runs as the launch signal's receiver, and again from the reconciler for a launch whose receiver
failed, so it is safe to run more than once.
"""
+ # Deferred: pulls in access control, and this module loads in every process at startup.
+ from products.replay_vision.backend.scanner_access import creator_can_scan # noqa: PLC0415
+
started: list[ReplayScanner] = []
with transaction.atomic():
waiting = (
- ReplayScanner.objects.select_related("created_by", "team")
+ ReplayScanner.objects.select_related("created_by", "team__organization")
.select_for_update(of=("self",))
.filter(
team_id=team_id,
@@ -31,6 +34,10 @@ def start_scanners_waiting_for_launch(
)
)
for scanner in waiting:
+ if not scanner.team.organization.is_ai_data_processing_approved or not creator_can_scan(scanner):
+ # The sweep would turn it straight back off. It keeps waiting, so the reconciler's launch
+ # catch-up starts it once consent returns, and turning it on by hand clears the marker.
+ continue
# Cleared with the enable, so a reset and relaunch never turns on a scanner its owner
# turned off after the first launch.
scanner.scanner_config = {k: v for k, v in scanner.scanner_config.items() if k != START_ON_LAUNCH_KEY}
diff --git a/products/replay_vision/backend/facade/api.py b/products/replay_vision/backend/facade/api.py
index 24bfd3c8fecc..0e0545201f5b 100644
--- a/products/replay_vision/backend/facade/api.py
+++ b/products/replay_vision/backend/facade/api.py
@@ -24,6 +24,7 @@ from products.replay_vision.backend.scanner_access import (
can_read_targeted_experiment,
is_uuid,
readable_observation_scanner_ids,
+ recording_viewer_access,
)
from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTH
@@ -219,7 +220,6 @@ def start_workflow_observation_request(
WorkflowScanCapReached,
WorkflowScanCaps,
create_observation_request,
- recording_viewer_access,
request_progress,
step_result,
)
@@ -380,9 +380,6 @@ def workflow_scan_editor_error(*, user: User, team: "Team", scanner_id: UUID | N
The scan runs as the workflow's owner, but whoever saves or live-tests the step chooses the sessions it
reads, the scanner it uses and where the answers go, so they need the access the owner needs.
"""
- # Deferred: reach the temporal package, whose activities import this facade while it loads.
- from products.replay_vision.backend.observation_requests import recording_viewer_access # noqa: PLC0415
-
access = recording_viewer_access(user, team)
if access is None:
return "You need access to session recordings to use the Replay Vision step."
diff --git a/products/replay_vision/backend/observation_requests.py b/products/replay_vision/backend/observation_requests.py
index a519f8dea951..ca3914ccd708 100644
--- a/products/replay_vision/backend/observation_requests.py
+++ b/products/replay_vision/backend/observation_requests.py
@@ -21,7 +21,6 @@ import structlog
from posthog.api.statement_timeout import is_query_canceled
from posthog.dataclasses import frozen
from posthog.kafka_client.client import ProduceResult
-from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
from posthog.models.user import User
from posthog.slack.formatting import escape_slack_mrkdwn
@@ -42,7 +41,11 @@ from products.replay_vision.backend.models.replay_observation_request import (
)
from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner, ScannerType
from products.replay_vision.backend.queries.session_last_activity import fetch_session_last_activity
-from products.replay_vision.backend.scanner_access import can_read_observation, can_read_targeted_experiment
+from products.replay_vision.backend.scanner_access import (
+ can_read_observation,
+ can_read_targeted_experiment,
+ recording_viewer_access,
+)
from products.replay_vision.backend.scanning import run_inline_scan, scan_existing_scanner
from products.replay_vision.backend.temporal.constants import APPLY_SCANNER_EXECUTION_TIMEOUT
@@ -325,20 +328,6 @@ def start_waiting_requests(*, now: datetime | None = None, budget_seconds: float
return started
-def recording_viewer_access(user: User | None, team: Team) -> UserAccessControl | None:
- """The user's access in the project, when they are active, a member and can view its recordings."""
- if user is None or not user.is_active:
- return None
- if not OrganizationMembership.objects.filter(user=user, organization_id=team.organization_id).exists():
- return None
- access = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))
- if not access.has_project_access:
- return None
- if not access.check_access_level_for_resource("session_recording", required_level="viewer"):
- return None
- return access
-
-
def _creator_still_allowed(request: ReplayObservationRequest) -> bool:
"""Whether the person a waiting request runs as can still start it, hours after asking.
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index 683dc8d84e18..a29ced0fb8e9 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -519,7 +519,8 @@ def _sum_active_backfill_remaining_credits(organization_id: UUID) -> BackfillCom
"""
rows = (
ReplayScannerBackfill.objects.unscoped()
- .filter(team__organization_id=organization_id, status__in=ACTIVE_BACKFILL_STATUSES)
+ # A disabled scanner holds its backfills, so they owe nothing until it is turned back on.
+ .filter(team__organization_id=organization_id, status__in=ACTIVE_BACKFILL_STATUSES, scanner__enabled=True)
.values_list(
"total_count", "dispatched_count", "skipped_count", "credits_per_observation", "scanner__free_only"
)
diff --git a/products/replay_vision/backend/scanner_access.py b/products/replay_vision/backend/scanner_access.py
index 13a4b6707a19..a269aad60aab 100644
--- a/products/replay_vision/backend/scanner_access.py
+++ b/products/replay_vision/backend/scanner_access.py
@@ -13,7 +13,9 @@ from django.db.models import Q
from rest_framework.exceptions import NotFound, PermissionDenied
+from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
+from posthog.models.user import User
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
@@ -21,8 +23,6 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner
if TYPE_CHECKING:
from django.db.models import QuerySet
- from posthog.models.user import User
-
from products.replay_vision.backend.models.replay_observation import ReplayObservation
@@ -34,6 +34,29 @@ def is_uuid(value: str) -> bool:
return True
+# Error code clients key on to offer taking over a scanner whose creator lost recording access.
+SCANNER_CREATOR_LOST_ACCESS_CODE = "scanner_creator_lost_access"
+
+
+def recording_viewer_access(user: User | None, team: Team) -> UserAccessControl | None:
+ """The user's access in the project, when they are active, a member and can view its recordings."""
+ if user is None or not user.is_active:
+ return None
+ if not OrganizationMembership.objects.filter(user=user, organization_id=team.organization_id).exists():
+ return None
+ access = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))
+ if not access.has_project_access:
+ return None
+ if not access.check_access_level_for_resource("session_recording", required_level="viewer"):
+ return None
+ return access
+
+
+def creator_can_scan(scanner: ReplayScanner) -> bool:
+ """Whether the sweep, which reads recordings as the scanner's creator, can still read them."""
+ return scanner.created_by is None or recording_viewer_access(scanner.created_by, scanner.team) is not None
+
+
def scanners_for_reading_observations(team_id: int) -> "QuerySet[ReplayScanner]":
"""Every scanner whose observations can be read, inline scans included.
diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
index c54bfd20ecff..853d47634cc2 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -1,5 +1,6 @@
import time
import datetime as dt
+from typing import Literal
from django.utils import timezone
@@ -16,7 +17,6 @@ from posthog.schema import RecordingsQuery
from posthog.dataclasses import frozen
from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import read_stuck_session_ids
-from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.replay_scanner import (
SETTLE_INTERVAL,
@@ -42,6 +42,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
build_candidate_batch,
)
from products.replay_vision.backend.queries.variant_sampling import variant_sampling_plan_for_scope
+from products.replay_vision.backend.scanner_access import creator_can_scan
from products.replay_vision.backend.temporal.constants import (
DEEP_SWEEP_INTERVAL,
DEEP_SWEEP_MAX_EXECUTION_SECONDS,
@@ -158,40 +159,48 @@ def _fail_on_filter_error(scanner: ReplayScanner, error: Exception) -> None:
) from error
+def _disable_unrunnable_scanner(
+ scanner: ReplayScanner, reason: Literal["no_ai_consent", "creator_lost_access", "experiment_deleted"]
+) -> FindScannerCandidatesOutput:
+ """Turn the scanner off so the reconciler drops its schedule and the owner sees it off, not silently idle.
+
+ An experiment scanner's scouts are paused first: a disabled scanner has no schedule left to retry a
+ failed pause, so a failure keeps the scanner on and the next tick tries again.
+ """
+ if scanner.scanner_type == ScannerType.EXPERIMENT and not _stop_variant_analysis(scanner):
+ record_sweep_outcome(f"{reason}_pause_failed")
+ return FindScannerCandidatesOutput(candidates=[], saturated=False)
+ # nosemgrep: semgrep.rules.security.replay-vision-alert-state-direct-mutation — disables a ReplayScanner, not an alert; scanners have no state machine.
+ scanner.enabled = False
+ scanner.save(update_fields=["enabled"])
+ record_sweep_outcome(reason)
+ activity.logger.info("replay_vision.sweep.disabled_unrunnable_scanner scanner_id=%s reason=%s", scanner.id, reason)
+ return FindScannerCandidatesOutput(candidates=[], saturated=False)
+
+
@activity.defn
@track_activity()
def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> FindScannerCandidatesOutput:
# `enabled=True` short-circuits sweeps the instant a scanner is disabled.
scanner = (
ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id, enabled=True)
- .select_related("team", "created_by")
+ .select_related("team__organization", "created_by")
.first()
)
if scanner is None:
return FindScannerCandidatesOutput(candidates=[], saturated=False)
- # Defence in depth against the creator losing recording access after the scanner was saved.
- if scanner.created_by is not None and not UserAccessControl(
- user=scanner.created_by, team=scanner.team
- ).check_access_level_for_resource("session_recording", required_level="viewer"):
- return FindScannerCandidatesOutput(candidates=[], saturated=False)
+ # Without AI consent or the creator's recording access a scanner can never spend, so turn it off instead of leaving it silently idle.
+ if not scanner.team.organization.is_ai_data_processing_approved:
+ return _disable_unrunnable_scanner(scanner, "no_ai_consent")
+ if not creator_can_scan(scanner):
+ return _disable_unrunnable_scanner(scanner, "creator_lost_access")
lifecycle_block = _experiment_lifecycle_block(scanner)
sweep_until: dt.datetime | None = None
if lifecycle_block is not None and lifecycle_block.kind == "deleted":
- # A deleted experiment can't resolve a population again, so disable: the reconciler drops
- # the schedule and the owner sees the scanner off instead of silently idle. Its scout is
- # paused first: a disabled scanner has no schedule left to retry a failed pause, so a
- # failure keeps the scanner on and the next tick tries again.
- if not _stop_variant_analysis(scanner):
- record_sweep_outcome("experiment_deleted_pause_failed")
- return FindScannerCandidatesOutput(candidates=[], saturated=False)
- # nosemgrep: semgrep.rules.security.replay-vision-alert-state-direct-mutation — disables a ReplayScanner, not an alert; scanners have no state machine.
- scanner.enabled = False
- scanner.save(update_fields=["enabled"])
- record_sweep_outcome("experiment_deleted")
- activity.logger.info("replay_vision.sweep.disabled_experiment_scanner scanner_id=%s", inputs.scanner_id)
- return FindScannerCandidatesOutput(candidates=[], saturated=False)
+ # A deleted experiment can't resolve a population again.
+ return _disable_unrunnable_scanner(scanner, "experiment_deleted")
if lifecycle_block is not None:
end = lifecycle_block.end_date
if end is None or _swept_past(scanner, end):
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 34723f0317fa..2f94753aab7f 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -25,7 +25,7 @@ from posthog.api.tagged_item import set_tags_on_object
from posthog.constants import AvailableFeature
from posthog.event_usage import EventSource
from posthog.llm.system_one import NoulAnswer, SystemOneResult
-from posthog.models import Organization, PersonalAPIKey, Team, User
+from posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog, changes_between, replay_scanner_machine_fields
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.product_intent.product_intent import ProductIntent
@@ -66,6 +66,7 @@ from products.replay_vision.backend.queries import ESTIMATE_STALE_AFTER, SAVE_ES
from products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVAL
from products.replay_vision.backend.queries.scanner_volume_estimate import estimate_scanner_session_volume
from products.replay_vision.backend.quota import BillingPeriod, _current_period_bounds
+from products.replay_vision.backend.scanner_access import recording_viewer_access
from products.replay_vision.backend.scanner_draft import DraftError, ScannerDraft
from products.replay_vision.backend.search import ObservationMatch
from products.replay_vision.backend.semantic_space import SEMANTIC_DIMENSIONS, pack
@@ -220,24 +221,72 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertEqual(resp.status_code, 201)
self.assertEqual(resp.json()["sampling_rate"], value)
- def test_create_without_ai_consent_returns_tagged_400(self) -> None:
+ @parameterized.expand([("create",), ("turn_on",)])
+ def test_without_ai_consent_returns_tagged_400(self, action: str) -> None:
# The code is a contract the experiment wizard reads to keep this expected 400 out of error
# tracking, so it must stay stable, not just the status.
+ scanner = self._create_scanner(enabled=False)
self.organization.is_ai_data_processing_approved = False
self.organization.save()
- resp = self.client.post(
- self.scanners_url,
- data={
- "name": "needs-consent",
- "scanner_type": ScannerType.MONITOR,
- "scanner_config": {"prompt": "p"},
- "model": ScannerModel.GEMINI_3_8_FLASH,
- },
- format="json",
- )
+ if action == "create":
+ resp = self.client.post(
+ self.scanners_url,
+ data={
+ "name": "needs-consent",
+ "scanner_type": ScannerType.MONITOR,
+ "scanner_config": {"prompt": "p"},
+ "model": ScannerModel.GEMINI_3_8_FLASH,
+ },
+ format="json",
+ )
+ else:
+ resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", {"enabled": True}, format="json")
self.assertEqual(resp.status_code, 400, resp.json())
self.assertEqual(resp.json()["code"], "ai_data_processing_not_approved")
+ @parameterized.expand(
+ [
+ ("creator_left_without_take_over", True, False, "admin", "scanner_creator_lost_access", False, False),
+ ("creator_left_with_take_over", True, True, "admin", None, True, True),
+ ("taker_cannot_view_recordings", True, True, "no_recordings", "invalid_input", False, False),
+ ("taker_cannot_manage_access", True, True, "member", "invalid_input", False, False),
+ ("creator_still_member_ignores_take_over", False, True, "member", None, True, False),
+ ]
+ )
+ def test_turning_on_a_scanner_whose_creator_lost_access_needs_an_explicit_take_over(
+ self,
+ _name: str,
+ creator_left: bool,
+ take_over: bool,
+ taker: str,
+ error_code: str | None,
+ enabled: bool,
+ taken_over: bool,
+ ) -> None:
+ if taker != "member":
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ creator = User.objects.create_user(email="[email protected]", password="x", first_name="c")
+ if not creator_left:
+ self.organization.members.add(creator)
+ scanner = self._create_scanner(enabled=False, created_by=creator)
+
+ with patch(
+ "products.replay_vision.backend.api.scanners.recording_viewer_access",
+ side_effect=(lambda *_: None) if taker == "no_recordings" else None,
+ wraps=recording_viewer_access,
+ ):
+ resp = self.client.patch(
+ f"{self.scanners_url}{scanner.id}/", {"enabled": True, "take_over_as_creator": take_over}, format="json"
+ )
+
+ self.assertEqual(resp.status_code, 400 if error_code else 200, resp.json())
+ if error_code:
+ self.assertEqual(resp.json()["code"], error_code)
+ scanner.refresh_from_db()
+ self.assertEqual(scanner.enabled, enabled)
+ self.assertEqual(scanner.created_by, self.user if taken_over else creator)
+
def test_create_duplicate_name_rejected(self) -> None:
self._create_scanner(name="dup")
resp = self.client.post(
@@ -431,6 +480,10 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertEqual(waiting.status_code, 201, waiting.json())
other = post("waiting-on-other-draft", other_draft.id, enabled=False)
self.assertEqual(other.status_code, 201, other.json())
+ departed_creator = post("waiting-without-a-creator", draft.id, enabled=False)
+ ReplayScanner.objects.filter(id=departed_creator.json()["id"]).update(
+ created_by=User.objects.create_user(email="[email protected]", password="x", first_name="d")
+ )
early_enable = self.client.patch(
f"{self.scanners_url}{waiting.json()['id']}/", data={"enabled": True}, format="json"
@@ -445,6 +498,9 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertTrue(started.enabled)
self.assertNotIn("start_on_launch", started.scanner_config)
self.assertFalse(ReplayScanner.objects.get(id=other.json()["id"]).enabled)
+ never_started = ReplayScanner.objects.get(id=departed_creator.json()["id"])
+ self.assertFalse(never_started.enabled)
+ self.assertTrue(never_started.scanner_config["start_on_launch"])
# Setting a start date on a draft also launches it, through the experiment update path.
patch_launch = self.client.patch(
diff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.py
index 670f2cc95456..ad41369a1152 100644
--- a/products/replay_vision/backend/tests/test_backfills.py
+++ b/products/replay_vision/backend/tests/test_backfills.py
@@ -160,6 +160,8 @@ class TestBackfillQuotaCommitment:
scanner, status=BackfillStatus.PAUSED_QUOTA, total_count=10, dispatched_count=4, credits_per_observation=2
)
assert spend_projection(scanner.team.organization_id).backfills_committed_credits == 12
+ ReplayScanner.objects.filter(pk=scanner.pk).update(enabled=False)
+ assert spend_projection(scanner.team.organization_id).backfills_committed_credits == 0
@pytest.mark.django_db(transaction=True)
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index ce88f132854a..711cdf6cc573 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -236,15 +236,19 @@ class TestFindScannerCandidatesActivity:
assert abs(result.swept_through - settled_now) < dt.timedelta(minutes=1)
assert result.deep_swept_through == result.swept_through
- def test_a_deleted_experiment_keeps_its_scanner_on_until_the_scout_is_paused(self) -> None:
+ @parameterized.expand([("deleted_experiment",), ("no_ai_consent",)])
+ def test_an_experiment_scanner_stays_on_until_its_scout_is_paused(self, cause: str) -> None:
# A disabled scanner has no schedule left to retry the pause, and the scout would keep
# running on the customer's bill. So the scanner stays on until a later tick pauses it.
scanner = _make_scanner(scanner_type=ScannerType.EXPERIMENT)
experiment = create_experiment(scanner.team, "deleted-flag", launched=True, variants=["control", "test"])
scanner.scanner_config = {"prompt": "p", "experiment_id": experiment.id}
scanner.save()
- experiment.deleted = True
- experiment.save()
+ if cause == "deleted_experiment":
+ experiment.deleted = True
+ experiment.save()
+ else:
+ Organization.objects.filter(pk=scanner.team.organization_id).update(is_ai_data_processing_approved=False)
inputs = FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
with (
@@ -326,19 +330,28 @@ class TestFindScannerCandidatesActivity:
)
assert result == FindScannerCandidatesOutput(candidates=[], saturated=False)
- def test_returns_empty_when_creator_lost_session_recording_access(self) -> None:
- from posthog.models import User
+ @parameterized.expand([("creator_left_org",), ("creator_deactivated",), ("no_ai_consent",)])
+ def test_a_scanner_that_cannot_spend_is_turned_off_before_any_read(self, case: str) -> None:
+ scanner = _make_scanner()
+ if case != "no_ai_consent":
+ creator = User.objects.create_user(email="[email protected]", password="x", first_name="c")
+ if case == "creator_deactivated":
+ scanner.team.organization.members.add(creator)
+ User.objects.filter(pk=creator.pk).update(is_active=False)
+ scanner.created_by = creator
+ scanner.save(update_fields=["created_by"])
+ else:
+ Organization.objects.filter(pk=scanner.team.organization_id).update(is_ai_data_processing_approved=False)
- creator = User.objects.create_user(email="[email protected]", password="x", first_name="d")
- scanner = _make_scanner(created_by=creator)
- with patch(
- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.UserAccessControl.check_access_level_for_resource",
- return_value=False,
- ):
+ with _patched_queries() as (fast_query, deep_query):
result = find_scanner_candidates_activity(
FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
)
+
assert result == FindScannerCandidatesOutput(candidates=[], saturated=False)
+ assert not fast_query.called and not deep_query.called
+ scanner.refresh_from_db()
+ assert not scanner.enabled
def test_targeted_scanner_with_no_creator_skips_instead_of_failing(self) -> None:
# The exposure filter refuses userless principals, so a deleted creator would otherwise
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 577ee575c085..a3068d5b1718 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -1285,6 +1285,8 @@ export interface ReplayScannerApi {
* * `template` - Template
* * `scratch` - From scratch */
creation_method?: ScannerCreationMethodEnumApi | null
+ /** Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`. */
+ take_over_as_creator?: boolean
/** Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`. */
scanner_config: unknown
/** The current prompt condensed by AI into the one question the scanner answers about a session. Falls back to the prompt's first line when no question matches the current prompt. */
@@ -1434,6 +1436,8 @@ export interface PatchedReplayScannerApi {
* * `template` - Template
* * `scratch` - From scratch */
creation_method?: ScannerCreationMethodEnumApi | null
+ /** Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`. */
+ take_over_as_creator?: boolean
/** Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`. */
scanner_config?: unknown
/** The current prompt condensed by AI into the one question the scanner answers about a session. Falls back to the prompt's first line when no question matches the current prompt. */
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index 44c724181a75..1e4faa789c21 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -656,6 +656,12 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod
.describe(
'How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.\n\n\* `ai` - AI draft\n\* `template` - Template\n\* `scratch` - From scratch'
),
+ take_over_as_creator: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`."
+ ),
scanner_config: zod
.unknown()
.describe(
@@ -813,6 +819,12 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod
.describe(
'How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.\n\n\* `ai` - AI draft\n\* `template` - Template\n\* `scratch` - From scratch'
),
+ take_over_as_creator: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`."
+ ),
scanner_config: zod
.unknown()
.optional()
diff --git a/products/replay_vision/frontend/replay_scanners/TurnOnScannerDialogs.stories.tsx b/products/replay_vision/frontend/replay_scanners/TurnOnScannerDialogs.stories.tsx
new file mode 100644
index 000000000000..2f9d78fca566
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/TurnOnScannerDialogs.stories.tsx
@@ -0,0 +1,25 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { LemonDialog, LemonDialogProps } from 'lib/lemon-ui/LemonDialog'
+
+import {
+ ALLOW_AI_ANALYSIS_DIALOG,
+ TAKE_OVER_DIALOG,
+ aiAnalysisOffDialogProps,
+ confirmDialogProps,
+} from './saveScannerEnabled'
+
+// The dialogs `saveScannerEnabled` opens before a scanner can turn on, rendered inline with the same props.
+const meta: Meta<LemonDialogProps> = {
+ title: 'Scenes-App/Replay Vision/TurnOnScannerDialogs',
+ render: (props) => <LemonDialog {...props} inline />,
+}
+export default meta
+
+type Story = StoryObj<LemonDialogProps>
+
+export const AllowAIAnalysis: Story = { args: confirmDialogProps(ALLOW_AI_ANALYSIS_DIALOG) }
+
+export const AIAnalysisOffForMember: Story = { args: aiAnalysisOffDialogProps() }
+
+export const TakeOverScanner: Story = { args: confirmDialogProps(TAKE_OVER_DIALOG) }
diff --git a/products/replay_vision/frontend/replay_scanners/highlightPicksStaleLogic.ts b/products/replay_vision/frontend/replay_scanners/highlightPicksStaleLogic.ts
index 9872684646e0..7446e4b56ba4 100644
--- a/products/replay_vision/frontend/replay_scanners/highlightPicksStaleLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/highlightPicksStaleLogic.ts
@@ -39,6 +39,7 @@ import { visionScannersListLogic } from '../logics/visionScannersListLogic'
import { HighlightFeedEmptyReason, resolveHighlightFeedEmptyReason } from './highlightFeedEmptyState'
import { highlightPicksLogic } from './highlightPicksLogic'
import { HighlightPicksStaleReason, resolveHighlightPicksStaleReason } from './highlightPicksStaleState'
+import { saveScannerEnabled } from './saveScannerEnabled'
import { scanDrought } from './scanDrought'
const DROUGHT_SCANNER_CAP = 10
@@ -562,8 +563,10 @@ export const highlightPicksStaleLogic: LogicWrapper<highlightPicksStaleLogicType
}
act(enabled ? 'enable' : 'disable', scannerId)
try {
- await visionScannersPartialUpdate(String(teamId), scannerId, { enabled })
- refresh()
+ const saved = await saveScannerEnabled(String(teamId), scannerId, enabled)
+ if (saved) {
+ refresh()
+ }
} finally {
actions.scannerActionDone(scannerId)
}
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 43c2279385e9..17fc73087e9f 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -85,6 +85,7 @@ import {
} from './experimentTargeting'
import { newScanner } from './newScanner'
import { ReplayScannerTab } from './replayScannerSceneLogic'
+import { saveScannerEnabled } from './saveScannerEnabled'
import { clearScannerDraft, readScannerDraft, writeScannerDraft } from './scannerDraft'
import {
ScannerEditorStep,
@@ -1233,7 +1234,13 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
},
})
} else {
- await visionScannersPartialUpdate(String(teamId), props.id, scannerToPatchedApiBody(body))
+ // The toggles own `enabled`, and the sweep may have turned the scanner off while the form was open.
+ const { enabled: _enabled, ...editedFields } = body
+ await visionScannersPartialUpdate(
+ String(teamId),
+ props.id,
+ scannerToPatchedApiBody(editedFields)
+ )
actions.scannerSaved(scanner)
lemonToast.success('Scanner saved')
leaveScannerEditor(props.id, urls.replayVision(props.id))
@@ -2608,7 +2615,12 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
const next = !scanner.enabled
actions.setScannerValue('enabled', next)
try {
- await visionScannersPartialUpdate(String(teamId), props.id, { enabled: next })
+ const saved = await saveScannerEnabled(String(teamId), props.id, next)
+ if (!saved) {
+ actions.setScannerValue('enabled', false)
+ actions.toggleEnabledFailure()
+ return
+ }
actions.toggleEnabledSuccess(next)
refreshVisionQuota()
lemonToast.success(`Scanner ${next ? 'enabled' : 'disabled'}`)
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts
index 5e1c95b4a842..b56807a2a43c 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts
@@ -1,6 +1,7 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { addProductIntent } from 'lib/utils/product-intents'
import { urls } from 'scenes/urls'
@@ -401,6 +402,28 @@ describe('replayScannersLogic', () => {
expect(errorToast).toHaveBeenCalledWith(expect.stringContaining('Failed to disable scanner'))
})
+ it('a turn-on the person declines reverts the row without an error toast', async () => {
+ useMocks({
+ patch: {
+ '/api/projects/:team/vision/scanners/:id/': () => [
+ 400,
+ { type: 'validation_error', code: 'scanner_creator_lost_access', detail: 'x' },
+ ],
+ },
+ })
+ const open = jest.spyOn(LemonDialog, 'open').mockImplementation((props) => props.onAfterClose?.())
+ const errorToast = jest.spyOn(lemonToast, 'error')
+ logic.actions.loadScannersSuccess([makeScanner({ id: 'a', enabled: false })], 1)
+
+ await expectLogic(logic, () => logic.actions.toggleScannerEnabled('a')).toDispatchActions([
+ 'revertScannerEnabled',
+ ])
+
+ expect(logic.values.scanners.find((s) => s.id === 'a')?.enabled).toBe(false)
+ expect(errorToast).not.toHaveBeenCalled()
+ open.mockRestore()
+ })
+
it('revertScannerEnabled flips the row back and clears the in-flight id', async () => {
await expectLogic(logic, () => {
logic.actions.loadScannersSuccess(scanners, scanners.length)
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
index ac23a3013efc..1cdc9bd060d0 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
@@ -28,13 +28,13 @@ import {
visionScannersDestroy,
visionScannersDuplicateCreate,
visionScannersList,
- visionScannersPartialUpdate,
visionScannersStatsRetrieve,
} from '../generated/api'
import type { ScannerStatsResponseApi, UserBasicApi, VisionScannersListParams } from '../generated/api.schemas'
import type { ScannerTypeEnumApi } from '../generated/api.schemas'
import { refreshVisionQuota, visionQuotaLogic } from '../logics/visionQuotaLogic'
import { csvParam, parseCsvParam, parseSortParam, serializeSortParam } from '../utils/urlParams'
+import { saveScannerEnabled } from './saveScannerEnabled'
import {
ENABLED_OPTIONS,
EnabledFilter,
@@ -611,8 +611,17 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
const delta = enabled ? estimate : -estimate
visionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(delta)
try {
- await visionScannersPartialUpdate(String(teamId), id, { enabled })
+ const saved = await saveScannerEnabled(String(teamId), id, enabled)
+ if (!saved) {
+ visionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(-delta)
+ actions.revertScannerEnabled(id)
+ return
+ }
actions.toggleScannerEnabledDone(id)
+ if (enabled && (saved.created_by?.id ?? null) !== (scanner.created_by?.id ?? null)) {
+ // A take-over moved the scanner to the current user, which the creator column shows.
+ actions.loadScanners()
+ }
} catch (error: any) {
const verb = enabled ? 'enable' : 'disable'
lemonToast.error(`Failed to ${verb} scanner${error.detail ? `: ${error.detail}` : ''}`)
diff --git a/products/replay_vision/frontend/replay_scanners/saveScannerEnabled.test.ts b/products/replay_vision/frontend/replay_scanners/saveScannerEnabled.test.ts
new file mode 100644
index 000000000000..ceaf91eda3c8
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/saveScannerEnabled.test.ts
@@ -0,0 +1,98 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
+import { LemonDialog, LemonDialogProps } from 'lib/lemon-ui/LemonDialog'
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { saveScannerEnabled } from './saveScannerEnabled'
+
+const LOST_ACCESS = [400, { type: 'validation_error', code: 'scanner_creator_lost_access', detail: 'x' }]
+const SAVED = [200, { id: 's1', enabled: true }]
+
+describe('saveScannerEnabled', () => {
+ let patches: Record<string, unknown>[]
+ let dialogTitles: string[]
+
+ function useScenario({
+ consented,
+ responses,
+ answers,
+ }: {
+ consented: boolean
+ responses: unknown[][]
+ answers: boolean[]
+ }): void {
+ patches = []
+ dialogTitles = []
+ useMocks({
+ patch: {
+ '/api/projects/:team/vision/scanners/:id/': async ({ request }: { request: Request }) => {
+ patches.push(await request.json())
+ return responses[patches.length - 1] as any
+ },
+ '/api/organizations/:id/': () => [
+ 200,
+ { ...MOCK_DEFAULT_ORGANIZATION, is_ai_data_processing_approved: true },
+ ],
+ },
+ })
+ organizationLogic.mount()
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: consented,
+ })
+ // Each dialog takes the next answer: confirm runs the primary button, then the dialog closes.
+ jest.spyOn(LemonDialog, 'open').mockImplementation(async (props: LemonDialogProps) => {
+ dialogTitles.push(String(props.title))
+ if (answers.shift()) {
+ await (props.primaryButton?.onClick as (() => unknown) | undefined)?.()
+ }
+ props.onAfterClose?.()
+ })
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('turns on without asking when nothing is in the way', async () => {
+ useScenario({ consented: true, responses: [SAVED], answers: [] })
+
+ expect(await saveScannerEnabled('1', 's1', true)).toMatchObject({ enabled: true })
+ expect(patches).toEqual([{ enabled: true }])
+ expect(dialogTitles).toEqual([])
+ })
+
+ it.each([
+ ['approved', true, [{ enabled: true }, { enabled: true, take_over_as_creator: true }], true],
+ ['declined', false, [{ enabled: true }], false],
+ ])('takes the scanner over only once the take-over is %s', async (_name, confirm, expectedPatches, turnedOn) => {
+ useScenario({ consented: true, responses: [LOST_ACCESS, SAVED], answers: [confirm] })
+
+ const saved = await saveScannerEnabled('1', 's1', true)
+
+ expect(saved !== null).toBe(turnedOn)
+ expect(patches).toEqual(expectedPatches)
+ expect(dialogTitles).toEqual(['Take over this scanner?'])
+ })
+
+ it.each([
+ ['declines the prompt', [false], 0, false],
+ ['cancels the legal terms', [true, false], 0, false],
+ ['approves both', [true, true], 1, true],
+ ])('without consent, a person who %s', async (_name, answers, scannerPatches, turnedOn) => {
+ useScenario({ consented: false, responses: [SAVED], answers: [...answers] })
+
+ const saved = await saveScannerEnabled('1', 's1', true)
+
+ expect(saved !== null).toBe(turnedOn)
+ expect(patches).toHaveLength(scannerPatches)
+ expect(organizationLogic.values.currentOrganization?.is_ai_data_processing_approved).toBe(turnedOn)
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/saveScannerEnabled.tsx b/products/replay_vision/frontend/replay_scanners/saveScannerEnabled.tsx
new file mode 100644
index 000000000000..d90d728718f8
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/saveScannerEnabled.tsx
@@ -0,0 +1,154 @@
+import { LemonDialog, LemonDialogProps } from 'lib/lemon-ui/LemonDialog'
+import { organizationLogic } from 'scenes/organizationLogic'
+import { AIAccessRequest } from 'scenes/settings/organization/AIAccessRequest'
+import { aiConsentLegalDialogProps } from 'scenes/settings/organization/aiConsentCopy'
+
+import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'
+
+import { visionScannersPartialUpdate } from '../generated/api'
+import type { ReplayScannerApi } from '../generated/api.schemas'
+
+// The server's error codes for a turn-on that needs the person's decision first.
+const AI_CONSENT_REQUIRED_CODE = 'ai_data_processing_not_approved'
+const CREATOR_LOST_ACCESS_CODE = 'scanner_creator_lost_access'
+
+interface ConfirmDialog {
+ title: string
+ description: string
+ confirmLabel: string
+ confirmDataAttr: string
+}
+
+export const ALLOW_AI_ANALYSIS_DIALOG: ConfirmDialog = {
+ title: 'Allow AI analysis to turn this scanner on?',
+ description:
+ "Scanners send recordings to external AI providers for analysis. Your organization hasn't allowed this yet, so the scanner can't run until it does.",
+ confirmLabel: 'Allow AI analysis',
+ confirmDataAttr: 'vision-scanner-turn-on-allow-ai',
+}
+
+export const TAKE_OVER_DIALOG: ConfirmDialog = {
+ title: 'Take over this scanner?',
+ description:
+ "The person who created this scanner can no longer view recordings, so it can't run as them. Turning it on makes you its creator, and it will scan recordings as you.",
+ confirmLabel: 'Take over and turn on',
+ confirmDataAttr: 'vision-scanner-turn-on-take-over',
+}
+
+export function confirmDialogProps(dialog: ConfirmDialog): LemonDialogProps {
+ return {
+ title: dialog.title,
+ description: dialog.description,
+ primaryButton: { children: dialog.confirmLabel, 'data-attr': dialog.confirmDataAttr },
+ secondaryButton: { children: 'Keep it off' },
+ }
+}
+
+/** Shown to a member who can't allow AI analysis themselves. */
+export function aiAnalysisOffDialogProps(): LemonDialogProps {
+ return {
+ title: 'AI analysis is off for this organization',
+ description:
+ 'Scanners need AI analysis to run. An organization admin or owner can allow it, and then you can turn this scanner on.',
+ content: <AIAccessRequest size="small" />,
+ primaryButton: { children: 'Close', type: 'secondary' },
+ }
+}
+
+/** Opens a dialog and resolves whether its primary action completed before it closed. */
+function openForDecision(props: LemonDialogProps): Promise<boolean> {
+ return new Promise((resolve) => {
+ let confirmed = false
+ const primary = props.primaryButton
+ LemonDialog.open({
+ ...props,
+ primaryButton: primary && {
+ ...primary,
+ onClick: (event) => {
+ const result: unknown = primary.onClick?.(event)
+ if (!(result instanceof Promise)) {
+ confirmed = true
+ return
+ }
+ // An awaited submit that throws keeps the dialog open, so only success counts.
+ return result.then(() => {
+ confirmed = true
+ })
+ },
+ },
+ onAfterClose: () => resolve(confirmed),
+ })
+ })
+}
+
+async function acceptAIConsent(): Promise<void> {
+ const organization = organizationLogic.values.currentOrganization
+ if (organization) {
+ // Approving can trigger an SSO reauthentication redirect, so aiConsentLogic finishes it on return.
+ const { pathname, search, hash } = window.location
+ aiConsentLogic.actions.setPendingApprovalRedirect({
+ url: `${pathname}${search}${hash}`,
+ organizationId: organization.id,
+ setAt: Date.now(),
+ })
+ }
+ await aiConsentLogic.asyncActions.acceptDataProcessing()
+}
+
+async function allowAIAnalysis(): Promise<boolean> {
+ const unmount = aiConsentLogic.mount()
+ try {
+ if (aiConsentLogic.values.dataProcessingApprovalDisabledReason) {
+ LemonDialog.open(aiAnalysisOffDialogProps())
+ return false
+ }
+ return (
+ (await openForDecision(confirmDialogProps(ALLOW_AI_ANALYSIS_DIALOG))) &&
+ (await openForDecision(aiConsentLegalDialogProps({ onConfirm: acceptAIConsent })))
+ )
+ } finally {
+ unmount()
+ }
+}
+
+async function enable(teamId: string, scannerId: string, takeOver: boolean): Promise<ReplayScannerApi | null> {
+ try {
+ return await visionScannersPartialUpdate(teamId, scannerId, {
+ enabled: true,
+ ...(takeOver && { take_over_as_creator: true }),
+ })
+ } catch (error: any) {
+ if (error?.code === AI_CONSENT_REQUIRED_CODE) {
+ return (await allowAIAnalysis()) ? enable(teamId, scannerId, takeOver) : null
+ }
+ if (error?.code === CREATOR_LOST_ACCESS_CODE && !takeOver) {
+ return (await openForDecision(confirmDialogProps(TAKE_OVER_DIALOG)))
+ ? enable(teamId, scannerId, true)
+ : null
+ }
+ throw error
+ }
+}
+
+async function turnOnScanner(teamId: string, scannerId: string): Promise<ReplayScannerApi | null> {
+ const organization = organizationLogic.values.currentOrganization
+ // Unknown consent is left to the server, which answers with the code `enable` handles.
+ if (organization && !organization.is_ai_data_processing_approved && !(await allowAIAnalysis())) {
+ return null
+ }
+ return enable(teamId, scannerId, false)
+}
+
+/**
+ * Turns a scanner on or off. Turning on first asks the person to allow AI analysis or take the
+ * scanner over when it can't run otherwise, and resolves null when they decline.
+ */
+export function saveScannerEnabled(
+ teamId: string,
+ scannerId: string,
+ enabled: boolean
+): Promise<ReplayScannerApi | null> {
+ return enabled
+ ? turnOnScanner(teamId, scannerId)
+ : visionScannersPartialUpdate(teamId, scannerId, { enabled: false })
+}
diff --git a/products/replay_vision/frontend/replay_scanners/visionUsageLogic.ts b/products/replay_vision/frontend/replay_scanners/visionUsageLogic.ts
index ed9acfc59151..80b7334a6137 100644
--- a/products/replay_vision/frontend/replay_scanners/visionUsageLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/visionUsageLogic.ts
@@ -5,16 +5,13 @@ import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
-import {
- environmentVisionQuotaSpendSeriesRetrieve,
- visionScannersList,
- visionScannersPartialUpdate,
-} from '../generated/api'
+import { environmentVisionQuotaSpendSeriesRetrieve, visionScannersList } from '../generated/api'
import type { VisionQuotaApi, VisionSpendSeriesApi } from '../generated/api.schemas'
import { refreshVisionQuota, visionQuotaLogic } from '../logics/visionQuotaLogic'
import { fleetContributions } from '../utils/quotaContributions'
import { hasCreditLimit } from '../utils/quotaProjection'
import { type SpendVerdict, spendVerdict } from '../utils/spendVerdict'
+import { saveScannerEnabled } from './saveScannerEnabled'
import type { ReplayScanner } from './types'
/** Settled credit spend per UTC day of the current billing period, oldest first, zero-filled through today. */
@@ -206,7 +203,11 @@ export const visionUsageLogic = kea<visionUsageLogicType>([
}
actions.setScannerEnabled(scanner.id, next)
try {
- await visionScannersPartialUpdate(String(teamId), scanner.id, { enabled: next })
+ const saved = await saveScannerEnabled(String(teamId), scanner.id, next)
+ if (!saved) {
+ actions.setScannerEnabled(scanner.id, scanner.enabled)
+ return
+ }
refreshVisionQuota()
lemonToast.success(`Scanner ${next ? 'enabled' : 'disabled'}`)
} catch (error: any) {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 28c2b1fd044a..f5a6a51f7d26 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -79577,6 +79577,8 @@ export namespace Schemas {
* * `template` - Template
* * `scratch` - From scratch */
creation_method?: ScannerCreationMethodEnum | null;
+ /** Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`. */
+ take_over_as_creator?: boolean;
/** Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`. */
scanner_config: unknown;
/** The current prompt condensed by AI into the one question the scanner answers about a session. Falls back to the prompt's first line when no question matches the current prompt. */
@@ -92486,6 +92488,8 @@ export namespace Schemas {
* * `template` - Template
* * `scratch` - From scratch */
creation_method?: ScannerCreationMethodEnum | null;
+ /** Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`. */
+ take_over_as_creator?: boolean;
/** Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`. */
scanner_config?: unknown;
/** The current prompt condensed by AI into the one question the scanner answers about a session. Falls back to the prompt's first line when no question matches the current prompt. */
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 191ad38cdc07..eb894c46addf 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -913,6 +913,12 @@ export const VisionScannersCreateBody = () => zod
.describe(
'How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.\n\n\* `ai` - AI draft\n\* `template` - Template\n\* `scratch` - From scratch'
),
+ take_over_as_creator: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`."
+ ),
scanner_config: zod
.unknown()
.describe(
@@ -1091,6 +1097,12 @@ export const VisionScannersPartialUpdateBody = () => zod
.describe(
'How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.\n\n\* `ai` - AI draft\n\* `template` - Template\n\* `scratch` - From scratch'
),
+ take_over_as_creator: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`."
+ ),
scanner_config: zod
.unknown()
.optional()
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index e5e148d72377..92d703d374d7 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -921,6 +921,9 @@ const visionScannersCreate = (): ToolBase<
if (params.creation_method !== undefined) {
body['creation_method'] = params.creation_method
}
+ if (params.take_over_as_creator !== undefined) {
+ body['take_over_as_creator'] = params.take_over_as_creator
+ }
if (params.scanner_config !== undefined) {
body['scanner_config'] = params.scanner_config
}
@@ -1623,6 +1626,9 @@ const visionScannersUpdate = (): ToolBase<ReturnType<typeof VisionScannersUpdate
if (params.creation_method !== undefined) {
body['creation_method'] = params.creation_method
}
+ if (params.take_over_as_creator !== undefined) {
+ body['take_over_as_creator'] = params.take_over_as_creator
+ }
if (params.scanner_config !== undefined) {
body['scanner_config'] = params.scanner_config
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
index 197766d5b015..c3ce5ae708ef 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
@@ -137,6 +137,10 @@
},
"maxItems": 32,
"type": "array"
+ },
+ "take_over_as_creator": {
+ "description": "Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`.",
+ "type": "boolean"
}
},
"required": ["name", "scanner_type", "scanner_config", "model"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
index 5520343c8ec1..a2b5ffe0ff73 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
@@ -140,6 +140,10 @@
},
"maxItems": 32,
"type": "array"
+ },
+ "take_over_as_creator": {
+ "description": "Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`.",
+ "type": "boolean"
}
},
"required": ["id"],