: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
fix(experiments): Gate Replay Vision on AI-consent and show its price (#84598)
posthog[bot]60b712f569d4
diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.tsindex 0c263a351771..697cadc895c0 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts@@ -2,6 +2,7 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'import { router } from 'kea-router'import { expectLogic, partial } from 'kea-test-utils'+import posthog from 'posthog-js'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -281,8 +282,22 @@ describe('createExperimentLogic', () => {})- it('keeps the created experiment when scanner creation fails', async () => {- scannerCreateSpy.mockResolvedValueOnce([500, { detail: 'Scanner unavailable' }])+ it.each([+ {+ name: 'a generic failure is reported to error tracking',+ response: [500, { detail: 'Scanner unavailable' }] as [number, Record<string, unknown>],+ shouldCapture: true,+ },+ {+ // Missing org AI consent is user-correctable config, not a defect: keep it out of error+ // tracking so it stops reopening the issue that flagged this path.+ name: 'a missing AI consent 400 is not reported to error tracking',+ response: [400, { code: 'ai_data_processing_not_approved' }] as [number, Record<string, unknown>],+ shouldCapture: false,+ },+ ])('keeps the created experiment when scanner creation fails: $name', async ({ response, shouldCapture }) => {+ const captureExceptionSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined)+ scannerCreateSpy.mockResolvedValueOnce(response)await expectLogic(logic, () => {logic.actions.setCreateReplayVisionScanner(true)logic.actions.setExperiment({@@ -303,6 +318,8 @@ describe('createExperimentLogic', () => {button: expect.objectContaining({ label: 'Set up scanner' }),}))+ expect(captureExceptionSpy).toHaveBeenCalledTimes(shouldCapture ? 1 : 0)+ captureExceptionSpy.mockRestore()})it('refreshes tree items for experiment and feature flag after creation', async () => {diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.tsindex 21513e176ec9..0e774ce6017c 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts@@ -2,6 +2,7 @@ import { MakeLogicType, actions, connect, events, kea, key, listeners, path, proimport { router } from 'kea-router'import posthog from 'posthog-js'+import { ApiError } from 'lib/api-error'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -542,9 +543,18 @@ export const createExperimentLogic = kea<createExperimentLogicType>([intent_context: ProductIntentContext.EXPERIMENT_REPLAY_VISION_SCANNER_CREATED,})} catch (scannerError) {- // Captured rather than swallowed: a systematically failing create (quota, access)- // is otherwise invisible, since the experiment itself still succeeds.- posthog.captureException(scannerError)+ // A missing org AI consent is a user-correctable config state, not a defect, so it+ // stays out of error tracking. The checkbox gates on consent, but a stale client can+ // still reach here. Other failures (quota, access) are still captured. Without that,+ // a systematic break is invisible, because the experiment itself still succeeds.+ if (+ !(+ scannerError instanceof ApiError &&+ scannerError.code === 'ai_data_processing_not_approved'+ )+ ) {+ posthog.captureException(scannerError)+ }replayScannerCreationFailed = true}}diff --git a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsxindex b6949660b95a..a8b5d0112c6b 100644--- a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx+++ b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx@@ -11,7 +11,7 @@ import { featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import type { FeatureFlagType } from '~/types'+import { AccessControlLevel, AccessControlResourceType, type AppContext, type FeatureFlagType } from '~/types'import { NEW_EXPERIMENT } from 'products/experiments/frontend/constants'@@ -20,6 +20,7 @@ import { createExperimentLogic } from '../ExperimentForm/createExperimentLogic'import { variantsPanelLogic } from '../ExperimentForm/variantsPanelLogic'import { experimentWizardLogic, stepStorageKey } from './experimentWizardLogic'import { AboutStep } from './steps/AboutStep'+import { AnalyticsStep } from './steps/AnalyticsStep'import { VariantsStep } from './steps/VariantsStep'jest.mock('scenes/feature-flags/JSONEditorInput', () => ({@@ -34,6 +35,26 @@ jest.mock('scenes/feature-flags/JSONEditorInput', () => ({),}))+// The consent gate reads a single selector; stubbing the logic lets each case pick the org's+// consent state without standing up organizationLogic's loaders.+jest.mock('scenes/settings/organization/aiConsentLogic', () => {+ const { kea, selectors } = jest.requireActual('kea')+ return {+ aiConsentLogic: kea([+ selectors({+ dataProcessingAccepted: [() => [], () => (global as any).__consentAccepted ?? false],+ dataProcessingDismissed: [() => [], () => false],+ dataProcessingApprovalDisabledReason: [() => [], () => null],+ }),+ ]),+ }+})++// The metric panels pull in the metric modals and their logics, which the consent-gate tests+// don't exercise; stubbing them keeps the AnalyticsStep render scoped to the checkbox.+jest.mock('../ExperimentForm/MetricsPanel', () => ({ MetricsPanel: () => null }))+jest.mock('../ExperimentForm/ExposureCriteriaPanel', () => ({ ExposureCriteriaPanel: () => null }))+beforeAll(() => {const modalRoot = document.createElement('div')modalRoot.setAttribute('id', 'root')@@ -853,4 +874,93 @@ describe('experimentWizardLogic', () => {})})})++ describe('AnalyticsStep Replay Vision scanner consent gate', () => {+ let logic: ReturnType<typeof experimentWizardLogic.build>+ let createLogic: ReturnType<typeof createExperimentLogic.build>+ let appContextBeforeGrant: AppContext | undefined++ beforeEach(() => {+ localStorage.clear()+ sessionStorage.clear()+ useMocks(apiMocks)+ initKeaTests()+ // The checkbox's disabledReason fails closed when the app context carries no access+ // levels, which would swallow every click; grant what the backend grants an editor.+ appContextBeforeGrant = window.POSTHOG_APP_CONTEXT+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: {+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,+ [AccessControlResourceType.ReplayScanner]: AccessControlLevel.Editor,+ [AccessControlResourceType.SessionRecording]: AccessControlLevel.Viewer,+ },+ } as AppContext++ featureFlagsLogic.mount()+ experimentsLogic.mount()++ createLogic = createExperimentLogic()+ createLogic.mount()++ logic = experimentWizardLogic()+ logic.mount()+ })++ afterEach(() => {+ cleanup()+ logic?.unmount()+ createLogic?.unmount()+ experimentsLogic.unmount()+ featureFlagsLogic.unmount()+ delete (global as any).__consentAccepted+ // initKeaTests spreads the existing context, so the grant would otherwise leak into+ // every later test in this file.+ window.POSTHOG_APP_CONTEXT = appContextBeforeGrant+ })++ const renderAnalyticsStep = (): void => {+ render(+ <BindLogic logic={experimentWizardLogic} props={{}}>+ <AnalyticsStep />+ </BindLogic>+ )+ }++ it.each([+ {+ desc: 'a tick without org AI consent opens the consent popover instead of arming the scanner',+ accepted: false,+ expectedArmed: false,+ },+ {+ desc: 'a tick with org AI consent arms the scanner without the popover',+ accepted: true,+ expectedArmed: true,+ },+ ])('$desc', async ({ accepted, expectedArmed }) => {+ ;(global as any).__consentAccepted = accepted++ renderAnalyticsStep()+ await userEvent.click(screen.getByText('Watch participant behavior with Replay Vision'))++ // Without the gate the unconsented tick lands in the logic, and the save path then+ // creates a scanner the backend refuses with the consent 400.+ expect(logic.values.createReplayVisionScanner).toBe(expectedArmed)+ const popoverPrompt = screen.queryByText(/needs your approval/)+ if (accepted) {+ expect(popoverPrompt).not.toBeInTheDocument()+ } else {+ expect(popoverPrompt).toBeInTheDocument()+ }+ })++ it('shows the per-session price next to the checkbox', () => {+ ;(global as any).__consentAccepted = true++ renderAnalyticsStep()++ expect(screen.getByText(/Each scanned session costs/)).toBeInTheDocument()+ })+ })})diff --git a/frontend/src/scenes/experiments/ExperimentWizard/steps/AnalyticsStep.tsx b/frontend/src/scenes/experiments/ExperimentWizard/steps/AnalyticsStep.tsxindex edfb84094008..2a7e7d345e72 100644--- a/frontend/src/scenes/experiments/ExperimentWizard/steps/AnalyticsStep.tsx+++ b/frontend/src/scenes/experiments/ExperimentWizard/steps/AnalyticsStep.tsx@@ -1,17 +1,22 @@import { useActions, useValues } from 'kea'+import { useState } from 'react'import { LemonBanner, LemonCheckbox } from '@posthog/lemon-ui'+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'++import { DEFAULT_MODEL, OBSERVATION_CREDITS_BY_MODEL } from 'products/replay_vision/frontend/replay_scanners/types'import { getReplayVisionEditDisabledReason } from 'products/replay_vision/frontend/utils/accessControl'+import { formatCredits } from 'products/replay_vision/frontend/utils/credits'import { ExposureCriteriaPanel } from '../../ExperimentForm/ExposureCriteriaPanel'import { MetricsPanel } from '../../ExperimentForm/MetricsPanel'import { experimentWizardLogic } from '../experimentWizardLogic'export function AnalyticsStep(): JSX.Element {- const { createReplayVisionScanner, experiment, sharedMetrics } = useValues(experimentWizardLogic)- const { setCreateReplayVisionScanner, setExperiment, setExposureCriteria, setSharedMetrics } =- useActions(experimentWizardLogic)+ const { experiment, sharedMetrics } = useValues(experimentWizardLogic)+ const { setExperiment, setExposureCriteria, setSharedMetrics } = useActions(experimentWizardLogic)return (<div className="space-y-6">@@ -75,25 +80,7 @@ export function AnalyticsStep(): JSX.Element {</div></div>- <LemonCheckbox- bordered- fullWidth- checked={createReplayVisionScanner}- onChange={setCreateReplayVisionScanner}- disabledReason={getReplayVisionEditDisabledReason() ?? undefined}- data-attr="experiment-create-replay-vision-scanner"- label={- <div className="py-3">- <div className="font-semibold">Watch participant behavior with Replay Vision</div>- <div className="mt-1 font-normal text-sm text-muted">- Set up a scanner that classifies what participants do after experiment exposure. It is- created turned off, so nothing is scanned and no credits are used until you turn it on. You- can adjust its prompt, filters, and sampling first. A scanner keeps running after the- experiment ends, so turn it off when you are done.- </div>- </div>- }- />+ <ReplayVisionScannerCheckbox /><LemonBanner type="info">You can always refine your analytics configuration and metrics after saving.@@ -101,3 +88,71 @@ export function AnalyticsStep(): JSX.Element {</div>)}++/** Ticking this opts the experiment into a Replay Vision scanner, created at save. The scanner+ * endpoint refuses without org AI approval, so an unconsented tick opens the consent popover+ * instead of letting the experiment save and the scanner fail after the fact. */+function ReplayVisionScannerCheckbox(): JSX.Element {+ const { createReplayVisionScanner } = useValues(experimentWizardLogic)+ const { setCreateReplayVisionScanner } = useActions(experimentWizardLogic)+ const { dataProcessingAccepted } = useValues(aiConsentLogic)+ const [consentRequested, setConsentRequested] = useState(false)++ const checkbox = (+ <LemonCheckbox+ bordered+ fullWidth+ checked={createReplayVisionScanner}+ onChange={(checked) => {+ if (checked && !dataProcessingAccepted) {+ setConsentRequested(true)+ } else {+ setCreateReplayVisionScanner(checked)+ }+ }}+ disabledReason={getReplayVisionEditDisabledReason() ?? undefined}+ data-attr="experiment-create-replay-vision-scanner"+ label={+ <div className="py-3">+ <div className="font-semibold">Watch participant behavior with Replay Vision</div>+ <div className="mt-1 font-normal text-sm text-muted">+ Set up a scanner that classifies what participants do after experiment exposure. It is created+ turned off, so nothing is scanned and no credits are used until you turn it on. You can adjust+ its prompt, filters, and sampling first. A scanner keeps running after the experiment ends, so+ turn it off when you are done.+ </div>+ {/* Per-session price only: a monthly projection needs the 30-day recording history the+ * estimate endpoint reads, and an unstarted experiment has no exposed sessions yet, so+ * any monthly figure computed here would be a misleading zero. The scanner page shows+ * the projection once participant sessions exist. Priced at the model+ * experimentScannerBody pins, so this matches the scanner the save path creates. */}+ <div className="font-normal text-sm text-muted mt-1">+ Each scanned session costs {formatCredits(OBSERVATION_CREDITS_BY_MODEL[DEFAULT_MODEL])}. The+ scanner shows a projected monthly cost once the experiment has participants.+ </div>+ </div>+ }+ />+ )++ if (dataProcessingAccepted) {+ return checkbox+ }++ return (+ <AIConsentPopoverWrapper+ placement="top"+ showArrow+ ignoreDismissal+ hideTrainingDisclaimer+ hidden={!consentRequested}+ onApprove={() => {+ setConsentRequested(false)+ setCreateReplayVisionScanner(true)+ }}+ onDismiss={() => setConsentRequested(false)}+ >+ {checkbox}+ </AIConsentPopoverWrapper>+ )+}diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 0e9c3777dc25..4a7be0735938 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -684,7 +684,8 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerialuser = acting_user(self.context)if not team.organization.is_ai_data_processing_approved:raise serializers.ValidationError(- "Your organization needs to allow AI analysis before you can create a Replay Vision scanner."+ "Your organization needs to allow AI analysis before you can create a Replay Vision scanner.",+ code="ai_data_processing_not_approved",)# Tags become TaggedItem rows below, not a scanner column.tags = validated_data.pop("tags", None)diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 6efdea3de584..25561ba75f43 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -189,6 +189,24 @@ 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:+ # 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.+ 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_7_FLASH,+ },+ format="json",+ )+ self.assertEqual(resp.status_code, 400, resp.json())+ self.assertEqual(resp.json()["code"], "ai_data_processing_not_approved")+def test_create_duplicate_name_rejected(self) -> None:self._create_scanner(name="dup")resp = self.client.post(diff --git a/products/replay_vision/frontend/utils/credits.ts b/products/replay_vision/frontend/utils/credits.tsindex fdab15c36b9d..42731c533223 100644--- a/products/replay_vision/frontend/utils/credits.ts+++ b/products/replay_vision/frontend/utils/credits.ts@@ -1,10 +1,10 @@import { humanFriendlyCurrency } from 'lib/utils/numbers'/** 1 credit = $0.01. Amounts arrive from the API as integer credits. Credits are the unit we bill, so credits are- * what we show. The dollar anchor is reserved for the three spend surfaces (the spend meter, the scanner list's- * spend column, and the cost estimate) — repeating it in every tooltip, banner, and dropdown option is noise.- * Those three pair `formatCreditCount` with `creditsToUsd` when the dollar gets its own line, or use the inline- * `formatCredits`. Everywhere else is `formatCreditCount` alone. */+ * what we show. The dollar anchor is reserved for the spend surfaces (the spend meter, the scanner list's+ * spend column, the cost estimate, and the experiment wizard's scanner opt-in) — repeating it in every tooltip,+ * banner, and dropdown option is noise. Those pair `formatCreditCount` with `creditsToUsd` when the dollar gets+ * its own line, or use the inline `formatCredits`. Everywhere else is `formatCreditCount` alone. */export const CREDITS_PER_DOLLAR = 100/** e.g. 1200 -> "$12.00". */