:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): gate scanner create and scan on AI consent (#73329)
Kim Svatos Dugan5c4291a873e1
diff --git a/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx b/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsxindex 1626a4a94dc4..a88720f4403e 100644--- a/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx+++ b/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx@@ -13,10 +13,13 @@ export function AIConsentPopoverContent({onApprove,onDismiss,approvalDisabledReason,+ hideTrainingDisclaimer,}: {onApprove: () => voidonDismiss: () => voidapprovalDisabledReason: string | null+ /** Omit the "won't be used for training third-party models" line where it doesn't apply. */+ hideTrainingDisclaimer?: boolean}): JSX.Element {const focusOnMount = useCallback((el: HTMLButtonElement | null) => {el?.focus()@@ -29,7 +32,7 @@ export function AIConsentPopoverContent({<Tooltip title={getExternalAIProvidersTooltipTitle()}><dfn>external AI providers</dfn></Tooltip>- . <i>Your data won't be used for training third-party models.</i>+ .{!hideTrainingDisclaimer && <i> Your data won't be used for training third-party models.</i>}</p><div className="flex gap-1.5 self-end"><LemonButton data-attr="ai-consent-cancel" type="secondary" size="xsmall" onClick={onDismiss}>@@ -86,6 +89,7 @@ export function AIConsentPopoverWrapper({ignoreDismissal,onApprove,onDismiss,+ hideTrainingDisclaimer,...popoverProps}: Pick<PopoverProps, 'placement' | 'fallbackPlacements' | 'middleware' | 'showArrow'> & {children: JSX.Element@@ -94,6 +98,8 @@ export function AIConsentPopoverWrapper({ignoreDismissal?: booleanonApprove?: () => voidonDismiss?: () => void+ /** Passed through to AIConsentPopoverContent. */+ hideTrainingDisclaimer?: boolean}): JSX.Element {const { acceptDataProcessing } = useAsyncActions(aiConsentLogic)const { dataProcessingApprovalDisabledReason, dataProcessingAccepted, dataProcessingDismissed } =@@ -114,6 +120,7 @@ export function AIConsentPopoverWrapper({isAdminOrOwner ? (<AIConsentPopoverContentapprovalDisabledReason={dataProcessingApprovalDisabledReason}+ hideTrainingDisclaimer={hideTrainingDisclaimer}onApprove={() =>void acceptDataProcessing().then(() => onApprove?.())diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 810d3cd36640..5a6cd4864ba5 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -461,6 +461,10 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Modedef create(self, validated_data: dict[str, Any]) -> ReplayScanner:team = self.context["get_team"]()user = cast(User, self.context["request"].user)+ if not team.organization.is_ai_data_processing_approved:+ raise serializers.ValidationError(+ "Your organization needs to allow AI analysis before you can create a Replay Vision scanner."+ )try:# last_swept_at is seeded a settle-interval back by the model default (initial_watermark) to avoid a cold start.scanner = ReplayScanner.objects.create(team=team, created_by=user, **validated_data)diff --git a/products/replay_vision/backend/consent.py b/products/replay_vision/backend/consent.pynew file mode 100644index 000000000000..3479849e0760--- /dev/null+++ b/products/replay_vision/backend/consent.py@@ -0,0 +1,8 @@+from posthog.models.team import Team+++def is_ai_data_processing_approved(team_id: int) -> bool:+ """Fresh read of the org's AI data-processing consent, fail-closed when the team or org is missing."""+ return bool(+ Team.objects.filter(id=team_id).values_list("organization__is_ai_data_processing_approved", flat=True).first()+ )diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex df0b77e39803..db5f64bbce50 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -26,11 +26,12 @@ from temporalio import activityfrom posthog.models import Teamfrom posthog.temporal.common.heartbeat import Heartbeater+from products.replay_vision.backend.consent import is_ai_data_processing_approvedfrom products.replay_vision.backend.models.replay_observation import ReplayObservationfrom products.replay_vision.backend.temporal.constants import replay_vision_distinct_idfrom products.replay_vision.backend.temporal.conversation import function_calls, run_tool_loopfrom products.replay_vision.backend.temporal.decorators import track_activity-from products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureError+from products.replay_vision.backend.temporal.errors import ConsentWithdrawnError, FailureKind, ScannerFailureErrorfrom products.replay_vision.backend.temporal.events_tool import build_events_index, dispatch_events_tool, events_toolfrom products.replay_vision.backend.temporal.gemini import gemini_api_keyfrom products.replay_vision.backend.temporal.metrics import record_provider_call@@ -72,6 +73,11 @@ async def call_scanner_provider_activity(inputs: CallScannerProviderInputs) -> Sasync def _call_scanner_provider(inputs: CallScannerProviderInputs) -> ScannerCallOutput:+ # Re-check consent right before the provider generation — a separate egress step from the upload, so revocation+ # in the window between them must still abort before any recording data reaches the model. Fail closed.+ if not await sync_to_async(is_ai_data_processing_approved)(inputs.team_id):+ raise ConsentWithdrawnError("AI data processing consent was withdrawn before this recording could be analyzed")+if inputs.snapshot_override is not None:snapshot = inputs.snapshot_overrideteam_name, llm_inputs = await asyncio.gather(diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.pyindex 9f848fbaa583..b1e58c951abc 100644--- a/products/replay_vision/backend/temporal/activities/create_observation.py+++ b/products/replay_vision/backend/temporal/activities/create_observation.py@@ -46,10 +46,27 @@ def create_observation_activity(inputs: CreateObservationInputs) -> CreateObservdef _create_observation(inputs: CreateObservationInputs) -> CreateObservationOutput:- scanner = ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id).select_related("team").first()+ # team__organization is prefetched for the AI-consent check below.+ scanner = (+ ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id)+ .select_related("team", "team__organization")+ .first()+ )if scanner is None:raise ValueError(f"ReplayScanner {inputs.scanner_id} not found for team {inputs.team_id}")+ # No AI processing of recordings without organization consent, even for scanners created earlier.+ if not scanner.team.organization.is_ai_data_processing_approved:+ activity.logger.info(+ "Skipping observation: AI data processing not approved for organization",+ extra={"scanner_id": str(inputs.scanner_id), "team_id": inputs.team_id, "session_id": inputs.session_id},+ )+ return CreateObservationOutput(+ observation_id=None,+ was_created=False,+ scanner_type=scanner.scanner_type,+ )+if inputs.triggered_by_user_id is not None:# The activity is the persistence boundary, so re-check team membership rather than trusting the trigger.is_member = OrganizationMembership.objects.filter(diff --git a/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py b/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.pyindex 342e8a08c0c0..9e32d1c47597 100644--- a/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py+++ b/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py@@ -17,8 +17,9 @@ from posthog.storage import object_storagefrom posthog.temporal.common.heartbeat import Heartbeaterfrom products.exports.backend.models.exported_asset import ExportedAsset+from products.replay_vision.backend.consent import is_ai_data_processing_approvedfrom products.replay_vision.backend.temporal.decorators import track_activity-from products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureError+from products.replay_vision.backend.temporal.errors import ConsentWithdrawnError, FailureKind, ScannerFailureErrorfrom products.replay_vision.backend.temporal.gemini import gemini_api_keyfrom products.replay_vision.backend.temporal.gemini_cleanup_sweep.tracking import track_uploaded_filefrom products.replay_vision.backend.temporal.types import UploadedVideo, UploadVideoToGeminiInputs@@ -44,6 +45,12 @@ async def _upload_video(inputs: UploadVideoToGeminiInputs) -> UploadedVideo:raise ScannerFailureError("upload_video_to_gemini_activity has no workflow_id", kind=FailureKind.INTERNAL_ERROR)asset = await ExportedAsset.objects.aget(id=inputs.asset_id)+ # Re-check consent at the egress boundary, keyed off the team that owns the bytes: an admin may have+ # revoked it after the observation was created but before these bytes leave for Gemini. Fail closed so+ # a withdrawn org can't have recordings processed.+ if not await sync_to_async(is_ai_data_processing_approved)(asset.team_id):+ raise ConsentWithdrawnError("AI data processing consent was withdrawn before this recording could be analyzed")+video_bytes: bytes | Noneif asset.content:video_bytes = bytes(asset.content)diff --git a/products/replay_vision/backend/temporal/errors.py b/products/replay_vision/backend/temporal/errors.pyindex a6567865a826..345109f47fc6 100644--- a/products/replay_vision/backend/temporal/errors.py+++ b/products/replay_vision/backend/temporal/errors.py@@ -7,6 +7,7 @@ from products.replay_vision.backend.error_kinds import FailureKind, IneligibleSe__all__ = ["INELIGIBLE_SESSION_ERROR_TYPE","SCANNER_FAILURE_ERROR_TYPE",+ "ConsentWithdrawnError","FailureKind","IneligibleSessionError","IneligibleSessionKind",@@ -43,3 +44,16 @@ class ScannerFailureError(_KindedApplicationError):def __init__(self, message: str, *, kind: FailureKind) -> None:super().__init__(message, kind=kind, type=SCANNER_FAILURE_ERROR_TYPE, non_retryable=not kind.is_retryable)+++class _ConsentKind(StrEnum):+ # Kept out of IneligibleSessionKind on purpose: this is a policy abort, not a session-eligibility reason,+ # so it stays off the DB `error_reason` help text / OpenAPI taxonomy. Surfaced as INELIGIBLE all the same.+ NO_AI_CONSENT = "no_ai_consent"+++class ConsentWithdrawnError(_KindedApplicationError):+ """Org AI data-processing consent was withdrawn before an egress step. Surfaced as INELIGIBLE, never retried."""++ def __init__(self, message: str) -> None:+ super().__init__(message, kind=_ConsentKind.NO_AI_CONSENT, type=INELIGIBLE_SESSION_ERROR_TYPE)diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 5cf4041a3c86..673c1ddbd44f 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -22,6 +22,7 @@ from temporalio.exceptions import (TimeoutError as TemporalTimeoutError,TimeoutType,)+from temporalio.testing import ActivityEnvironmentfrom posthog.models import Organization, Teamfrom posthog.models.user import User@@ -73,6 +74,7 @@ from products.replay_vision.backend.temporal.activities.upload_video_to_gemini ifrom products.replay_vision.backend.temporal.errors import (INELIGIBLE_SESSION_ERROR_TYPE,SCANNER_FAILURE_ERROR_TYPE,+ ConsentWithdrawnError,FailureKind,IneligibleSessionError,IneligibleSessionKind,@@ -96,6 +98,7 @@ from products.replay_vision.backend.temporal.state import (from products.replay_vision.backend.temporal.sweep_types import CountInFlightAppliesInputs, InFlightApplyCountsfrom products.replay_vision.backend.temporal.types import (ApplyScannerInputs,+ CallScannerProviderInputs,CleanupGeminiFileInputs,CreateObservationInputs,CreateObservationOutput,@@ -116,6 +119,7 @@ from products.replay_vision.backend.temporal.types import (ScannerSnapshot,SessionMetadata,UploadedVideo,+ UploadVideoToGeminiInputs,)from products.replay_vision.backend.temporal.workflow import (_activity_timeout_kind,@@ -456,6 +460,77 @@ class TestCreateObservationActivity:)assert not ReplayObservation.objects.filter(scanner=scanner, session_id="sess-quota").exists()+ def test_skips_insert_when_ai_data_processing_not_approved(self) -> None:+ scanner = _make_scanner()+ org = scanner.team.organization+ org.is_ai_data_processing_approved = False+ org.save()++ result = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id="sess-no-consent",+ triggered_by=ObservationTrigger.SCHEDULE,+ triggered_by_user_id=None,+ workflow_id="wf-no-consent",+ )+ )+ assert result == CreateObservationOutput(+ observation_id=None, was_created=False, scanner_type=scanner.scanner_type+ )+ assert not ReplayObservation.objects.filter(scanner=scanner, session_id="sess-no-consent").exists()++[email protected]_db(transaction=True)+class TestEgressConsentRecheck:+ """Consent is re-checked at each external-data egress step. Revoking it after an observation is created+ must still abort before any recording bytes reach Gemini — creation-time gating alone leaves in-flight scans."""++ @staticmethod+ def _team_without_consent() -> Team:+ org = Organization.objects.create(name="no-consent-org", is_ai_data_processing_approved=False)+ return Team.objects.create(organization=org, name="no-consent-team")++ @pytest.mark.asyncio+ async def test_upload_aborts_before_touching_gemini_when_consent_withdrawn(self) -> None:+ team = await sync_to_async(self._team_without_consent)()+ # The activity derives the team from the asset row (no team_id in the payload), so it must exist.+ asset = await ExportedAsset.objects.acreate(team=team, export_format="video/mp4")+ with patch(+ "products.replay_vision.backend.temporal.activities.upload_video_to_gemini.RawGenAIClient"+ ) as mock_client:+ with pytest.raises(ConsentWithdrawnError) as exc_info:+ await ActivityEnvironment().run(+ upload_video_to_gemini_activity,+ UploadVideoToGeminiInputs(asset_id=asset.id),+ )+ mock_client.assert_not_called()+ assert exc_info.value.non_retryable is True+ assert exc_info.value.type == INELIGIBLE_SESSION_ERROR_TYPE+ assert exc_info.value.details == ("no_ai_consent",)++ @pytest.mark.asyncio+ async def test_provider_aborts_before_generation_when_consent_withdrawn(self) -> None:+ team = await sync_to_async(self._team_without_consent)()+ with patch(+ "products.replay_vision.backend.temporal.activities.call_scanner_provider._run_mission"+ ) as mock_run_mission:+ with pytest.raises(ConsentWithdrawnError) as exc_info:+ await ActivityEnvironment().run(+ call_scanner_provider_activity,+ CallScannerProviderInputs(+ team_id=team.id,+ observation_id=uuid.uuid4(),+ file_uri="gemini://files/x",+ mime_type="video/mp4",+ ),+ )+ mock_run_mission.assert_not_called()+ assert exc_info.value.non_retryable is True+ assert exc_info.value.type == INELIGIBLE_SESSION_ERROR_TYPE+ assert exc_info.value.details == ("no_ai_consent",)+@pytest.mark.django_db(transaction=True)class TestObservationStateActivities:diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex bd8be6d1a1ef..6c9e9bd6cd9b 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -1,5 +1,6 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'+import { useState } from 'react'import * as xRayPng from '@posthog/brand/hoggies/png/x-ray'import { IconPencil, IconPlus, IconRefresh, IconSearch, IconTrash } from '@posthog/icons'@@ -15,6 +16,8 @@ import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { appLogic } from 'scenes/appLogic'import { SceneExport } from 'scenes/sceneTypes'+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'@@ -38,6 +41,60 @@ const TYPE_OPTIONS: { value: ScannerType; label: string }[] = SCANNER_TYPE_OPTIOlabel,}))+/**+ * "Create scanner" CTA that requires the organization to have approved AI data processing first.+ * When consent is missing, clicking surfaces the AI consent popover; approving flows straight into+ * the create-scanner journey, so the empty state stays the same whether or not consent is set.+ */+function CreateScannerButton({+ acceptedLabel,+ dataAttr,+ size = 'small',+}: {+ acceptedLabel: string+ dataAttr: string+ size?: 'small' | 'medium'+}): JSX.Element {+ const { dataProcessingAccepted } = useValues(aiConsentLogic)+ const { push } = useActions(router)+ const [consentRequested, setConsentRequested] = useState(false)+ const goToCreate = (): void => push(urls.replayVisionTemplates())++ const button = (+ <LemonButton+ type="primary"+ size={size}+ icon={<IconPlus />}+ disabledReason={getReplayVisionEditDisabledReason()}+ data-attr={dataAttr}+ onClick={() => (dataProcessingAccepted ? goToCreate() : setConsentRequested(true))}+ >+ {dataProcessingAccepted ? acceptedLabel : 'Allow AI analysis and create scanner'}+ </LemonButton>+ )++ if (dataProcessingAccepted) {+ return button+ }++ return (+ <AIConsentPopoverWrapper+ placement="bottom-end"+ showArrow+ ignoreDismissal+ hideTrainingDisclaimer+ hidden={!consentRequested}+ onApprove={() => {+ setConsentRequested(false)+ goToCreate()+ }}+ onDismiss={() => setConsentRequested(false)}+ >+ {button}+ </AIConsentPopoverWrapper>+ )+}+export const scene: SceneExport = {component: ReplayScannersScene,logic: replayScannersLogic,@@ -206,16 +263,7 @@ export function ReplayScannersScene(): JSX.Element {actions={<><ReplayVisionFeedbackButton />- <LemonButton- type="primary"- size="small"- icon={<IconPlus />}- to={urls.replayVisionTemplates()}- disabledReason={getReplayVisionEditDisabledReason()}- data-attr="vision-scanner-create"- >- New scanner- </LemonButton>+ <CreateScannerButton acceptedLabel="New scanner" dataAttr="vision-scanner-create" /></>}/>@@ -308,14 +356,11 @@ export function ReplayScannersScene(): JSX.Element {scannersTotal === 0 && !hasActiveFilters ? (<div className="flex flex-col items-center gap-3 p-8 text-center"><div className="text-muted">No scanners yet.</div>- <LemonButton- type="primary"- icon={<IconPlus />}- to={urls.replayVisionTemplates()}- data-attr="vision-scanner-create-empty"- >- Create your first scanner- </LemonButton>+ <CreateScannerButton+ acceptedLabel="Create your first scanner"+ dataAttr="vision-scanner-create-empty"+ size="medium"+ /></div>) : (<span className="text-muted">No scanners match your filters.</span>diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex cef63996ff7b..5a7175370722 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -46,7 +46,7 @@ export const OBSERVATION_LIST_FILTER_KEYS: readonly (keyof VisionObservationsRetexport type EnabledFilter = 'enabled' | 'disabled'-export type IneligibleKind = 'no_recording' | 'too_short' | 'too_inactive' | 'too_long' | 'no_events'+export type IneligibleKind = 'no_recording' | 'too_short' | 'too_inactive' | 'too_long' | 'no_events' | 'no_ai_consent'const INELIGIBLE_KINDS: Record<IneligibleKind, { label: string; description: string }> = {no_recording: { label: 'No recording', description: 'No recording was found for this session.' },@@ -54,6 +54,10 @@ const INELIGIBLE_KINDS: Record<IneligibleKind, { label: string; description: strtoo_inactive: { label: 'Too inactive', description: 'The session had too little active interaction to analyze.' },too_long: { label: 'Too long', description: 'The session was too long to analyze.' },no_events: { label: 'No events', description: 'The session had no events to analyze.' },+ no_ai_consent: {+ label: 'AI analysis not allowed',+ description: 'AI data processing is turned off for this organization, so this recording was not analyzed.',+ },}export type FailureKind =