: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(experiments): create replay scanner during setup (#75108)
Arno Hillen793906f5388c
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex e4768f4bf2e5..5617bca35ad4 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -36951,6 +36951,7 @@"experiment created","experiment analyzed","experiment view recordings",+ "experiment replay vision scanner created","feature flag created","session_replay_set_filters","session_replay_experiment_link_clicked",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 62e3931d91eb..6eae9f16df09 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -9332,6 +9332,7 @@ export enum ProductIntentContext {EXPERIMENT_CREATED = 'experiment created',EXPERIMENT_ANALYZED = 'experiment analyzed',EXPERIMENT_VIEW_RECORDINGS = 'experiment view recordings',+ EXPERIMENT_REPLAY_VISION_SCANNER_CREATED = 'experiment replay vision scanner created',// Feature FlagsFEATURE_FLAG_CREATED = 'feature flag created',diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.tsindex b68e5a5befc0..8fd438190af5 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts@@ -3,13 +3,18 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'import { router } from 'kea-router'import { expectLogic, partial } from 'kea-test-utils'+import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'import { useMocks } from '~/mocks/jest'+import { type ExperimentExposureCriteria, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import type { Experiment } from '~/types'+import { DEFAULT_MODEL, DEFAULT_PROVIDER } from 'products/replay_vision/frontend/replay_scanners/types'+import { NEW_EXPERIMENT } from '../constants'import { createExperimentLogic, DRAFT_STORAGE_KEY } from './createExperimentLogic'@@ -27,17 +32,30 @@ jest.mock('~/layout/panel-layout/ProjectTree/projectTreeLogic', () => ({describe('createExperimentLogic', () => {let logic: ReturnType<typeof createExperimentLogic.build>let routerPushSpy: jest.SpyInstance+ let scannerCreateSpy: jest.Mock+ let scannerRequestBody: Record<string, unknown> | null+ let exposureEventSeenWithSessionId: booleanbeforeEach(() => {// Clear persisted state to prevent it from affecting testslocalStorage.clear()sessionStorage.clear()+ scannerRequestBody = null+ exposureEventSeenWithSessionId = true+ scannerCreateSpy = jest.fn(async ({ request }: { request: Request }) => {+ scannerRequestBody = (await request.json()) as Record<string, unknown>+ return [200, { id: 'scanner-123' }]+ })useMocks({get: {// saveExperiment verifies flag-key availability before building the payload'/api/projects/:team_id/feature_flags/': () => [200, { results: [], count: 0 }],'/api/projects/:team_id/experiments': () => [200, { results: [], count: 0 }],+ '/api/projects/:team_id/property_definitions/seen_together': ({ request }) => {+ const eventNames = new URL(request.url).searchParams.getAll('event_names')+ return [200, Object.fromEntries(eventNames.map((name) => [name, exposureEventSeenWithSessionId]))]+ },},post: {[`/api/projects/${MOCK_TEAM_ID}/experiments`]: async ({ request }) => {@@ -48,16 +66,20 @@ describe('createExperimentLogic', () => {return [200,{+ ...body,id: 123,name: body.name,description: body.description,type: body.type || 'product',feature_flag: {+ ...body.feature_flag,id: 456,+ key: body.feature_flag_key,},},]},+ '/api/projects/:team_id/vision/scanners/': scannerCreateSpy,},patch: {'/api/environments/:team_id/add_product_intent/': () => [200, {}],@@ -124,6 +146,154 @@ describe('createExperimentLogic', () => {.toMatchValues({experimentErrors: {},})++ expect(scannerCreateSpy).not.toHaveBeenCalled()+ })++ it('creates a scanner scoped to enrolled experiment sessions when selected', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.REPLAY_VISION], {+ [FEATURE_FLAGS.REPLAY_VISION]: true,+ })++ await expectLogic(logic, () => {+ logic.actions.setCreateReplayVisionScanner(true)+ logic.actions.setExperiment({+ ...NEW_EXPERIMENT,+ name: 'Checkout flow',+ description: 'Test hypothesis',+ feature_flag_key: 'checkout-flow',+ feature_flag_config: {+ filters: {+ multivariate: {+ variants: [+ { key: 'control', rollout_percentage: 50 },+ { key: 'new-checkout', rollout_percentage: 50 },+ ],+ },+ },+ },+ exposure_criteria: {+ filterTestAccounts: true,+ },+ })+ logic.actions.saveExperiment()+ })+ .toDispatchActions(['saveExperiment', 'createExperimentSuccess'])+ .toFinishAllListeners()++ expect(scannerCreateSpy).toHaveBeenCalledTimes(1)+ expect(scannerRequestBody).toMatchObject({+ name: 'Checkout flow (#123)',+ scanner_type: 'classifier',+ // Enabling starts credit spend, so a created scanner must never arrive switched on+ enabled: false,+ // `model` is required by the create serializer — omitting it 400s every create+ provider: DEFAULT_PROVIDER,+ model: DEFAULT_MODEL,+ query: {+ filter_test_accounts: true,+ events: [+ {+ id: '$feature_flag_called',+ properties: expect.arrayContaining([+ expect.objectContaining({+ key: '$feature_flag_response',+ value: ['control', 'new-checkout'],+ }),+ expect.objectContaining({+ key: '$feature_flag',+ value: ['checkout-flow'],+ }),+ ]),+ },+ ],+ },+ })+ expect(lemonToast.success).toHaveBeenCalledWith(+ 'Experiment created. The Replay Vision scanner is off until you turn it on.',+ expect.objectContaining({+ button: expect.objectContaining({ label: 'View scanner' }),+ })+ )+ })++ it.each([+ {+ name: 'falls back to the flag-value filter for a default exposure event',+ exposure_criteria: undefined,+ expectedQuery: {+ properties: [expect.objectContaining({ key: '$feature/server-side-exposure', type: 'event' })],+ },+ },+ {+ name: 'keeps the custom exposure filter, never an unfiltered query',+ exposure_criteria: {+ exposure_config: {+ kind: NodeKind.ExperimentEventExposureConfig,+ event: 'backend_assigned',+ properties: [],+ },+ } satisfies ExperimentExposureCriteria as ExperimentExposureCriteria,+ expectedQuery: {+ events: [expect.objectContaining({ id: 'backend_assigned' })],+ },+ },+ ])(+ // The check reports "never seen with a session ID", which for a minutes-old flag is+ // mostly "never seen at all" — so it must never refuse, and must never leave the query+ // empty, which would scan every recording in the project.+ 'creates a scoped scanner anyway when the exposure event looks unlinkable: $name',+ async ({ exposure_criteria, expectedQuery }) => {+ exposureEventSeenWithSessionId = false+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.REPLAY_VISION], {+ [FEATURE_FLAGS.REPLAY_VISION]: true,+ })++ await expectLogic(logic, () => {+ logic.actions.setCreateReplayVisionScanner(true)+ logic.actions.setExperiment({+ ...NEW_EXPERIMENT,+ name: 'Server-side exposure',+ description: 'Test hypothesis',+ feature_flag_key: 'server-side-exposure',+ ...(exposure_criteria ? { exposure_criteria } : {}),+ })+ logic.actions.saveExperiment()+ })+ .toDispatchActions(['saveExperiment', 'createExperimentSuccess', 'saveExperimentSuccess'])+ .toFinishAllListeners()++ expect(scannerCreateSpy).toHaveBeenCalledTimes(1)+ expect(scannerRequestBody).toMatchObject({ query: expect.objectContaining(expectedQuery) })+ }+ )++ it('keeps the created experiment when scanner creation fails', async () => {+ scannerCreateSpy.mockResolvedValueOnce([500, { detail: 'Scanner unavailable' }])+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.REPLAY_VISION], {+ [FEATURE_FLAGS.REPLAY_VISION]: true,+ })++ await expectLogic(logic, () => {+ logic.actions.setCreateReplayVisionScanner(true)+ logic.actions.setExperiment({+ ...NEW_EXPERIMENT,+ name: 'Test Experiment',+ description: 'Test hypothesis',+ feature_flag_key: 'test-experiment',+ })+ logic.actions.saveExperiment()+ })+ .toDispatchActions(['saveExperiment', 'createExperimentSuccess', 'saveExperimentSuccess'])+ .toFinishAllListeners()++ expect(routerPushSpy).toHaveBeenCalledWith('/experiments/123')+ expect(lemonToast.error).toHaveBeenCalledWith(+ "Experiment created, but the Replay Vision scanner wasn't.",+ expect.objectContaining({+ button: expect.objectContaining({ label: 'Set up scanner' }),+ })+ )})it('refreshes tree items for experiment and feature flag after creation', async () => {@@ -412,9 +582,11 @@ describe('createExperimentLogic', () => {firstNew.actions.setExperimentValue('name', 'Work In Progress')firstNew.actions.setExperimentValue('feature_flag_key', 'wip-flag')+ firstNew.actions.setCreateReplayVisionScanner(true)await expectLogic(firstNew).toMatchValues({experiment: partial({ name: 'Work In Progress', feature_flag_key: 'wip-flag' }),+ createReplayVisionScanner: true,})// Navigating away without saving writes the draft to sessionStorage@@ -425,6 +597,7 @@ describe('createExperimentLogic', () => {await expectLogic(secondNew).toMatchValues({experiment: partial({ id: 'new', name: 'Work In Progress', feature_flag_key: 'wip-flag' }),+ createReplayVisionScanner: true,})secondNew.unmount()diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.tsindex 4af7f00b80aa..533eba68115d 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts@@ -1,10 +1,12 @@import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { router } from 'kea-router'+import posthog from 'posthog-js'-import api from 'lib/api'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'+import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'import { projectLogic } from 'scenes/projectLogic'@@ -21,15 +23,29 @@ import {} from '~/queries/schema/schema-general'import type { Experiment, FeatureFlagFilters, MultivariateFlagVariant } from '~/types'-import type { ExperimentFeatureFlagFiltersApi } from 'products/experiments/frontend/generated/api.schemas'+import { experimentsCreate } from 'products/experiments/frontend/generated/api'+import type {+ ExperimentApi,+ ExperimentFeatureFlagFiltersApi,+ ExperimentTypeEnumApi,+} from 'products/experiments/frontend/generated/api.schemas'+import { visionScannersCreate } from 'products/replay_vision/frontend/generated/api'+import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'import type { ProductIntentProperties } from '../../../lib/utils/product-intents'import type { ExperimentMetricUnion } from '../../../queries/schema/schema-general'import type { FeatureFlagType } from '../../../types'import { NEW_EXPERIMENT } from '../constants'import { FORM_MODES, experimentLogic } from '../experimentLogic'import { experimentSceneLogic } from '../experimentSceneLogic'-import { getExperimentVariants, toExperimentWritePayload, toFlagVariantsInput } from '../utils'+import { experimentScannerBody, experimentScannerFilters } from '../replayVisionScanner'+import {+ type ExperimentWritePayload,+ getExperimentVariants,+ toExperimentWritePayload,+ toFlagVariantsInput,+} from '../utils'+import { loadUnlinkableEventNames } from '../viewRecordingsLinkabilityLogic'import { validateExperimentSubmission } from './experimentSubmissionValidation'import type { FeatureFlagKeyValidation } from './variantsPanelLogic'import { variantsPanelLogic } from './variantsPanelLogic'@@ -37,15 +53,38 @@ import { validateVariants } from './variantsPanelValidation'const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000+function experimentFromApi(experiment: ExperimentApi): Experiment {+ return experiment as unknown as Experiment+}++function experimentTypeForApi(type: Experiment['type']): ExperimentTypeEnumApi | undefined {+ return type === 'web' || type === 'product' ? type : undefined+}++function experimentWritePayloadForApi(+ experiment: ExperimentWritePayload<Experiment>+): Parameters<typeof experimentsCreate>[1] {+ return {+ ...experiment,+ type: experimentTypeForApi(experiment.type),+ } as unknown as Parameters<typeof experimentsCreate>[1]+}+// Scope the draft key per project so a draft started in one project can't prefill or be submitted in another within the same browser session.export const DRAFT_STORAGE_KEY = `experiment-draft-${window.POSTHOG_APP_CONTEXT?.current_team?.id ?? 'unknown'}`type ExperimentDraft = {experiment: Experiment+ createReplayVisionScanner?: booleantimestamp: number}-const readDraftFromStorage = (): Experiment | null => {+type RestoredDraft = {+ experiment: Experiment+ createReplayVisionScanner: boolean+}++const readDraftFromStorage = (): RestoredDraft | null => {if (typeof sessionStorage === 'undefined') {return null}@@ -56,24 +95,24 @@ const readDraftFromStorage = (): Experiment | null => {try {const parsed = JSON.parse(raw) as ExperimentDraft | Experimentif (parsed && typeof parsed === 'object' && 'experiment' in parsed && 'timestamp' in parsed) {- const { experiment, timestamp } = parsed as ExperimentDraft+ const { experiment, createReplayVisionScanner, timestamp } = parsed as ExperimentDraftif (Date.now() - timestamp > DRAFT_TTL_MS) {sessionStorage.removeItem(DRAFT_STORAGE_KEY)return null}- return experiment+ return { experiment, createReplayVisionScanner: createReplayVisionScanner ?? false }}- return parsed as Experiment+ return { experiment: parsed as Experiment, createReplayVisionScanner: false }} catch {return null}}-const writeDraftToStorage = (experiment: Experiment): void => {+const writeDraftToStorage = (experiment: Experiment, createReplayVisionScanner: boolean): void => {if (typeof sessionStorage === 'undefined') {return}- const draft: ExperimentDraft = { experiment, timestamp: Date.now() }+ const draft: ExperimentDraft = { experiment, createReplayVisionScanner, timestamp: Date.now() }sessionStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(draft))}@@ -88,10 +127,12 @@ export interface CreateExperimentLogicProps {}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface createExperimentLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogiccurrentProjectId: number | null // projectLogicfeatureFlagKeyValidation: FeatureFlagKeyValidation | null // variantsPanelLogicfeatureFlagKeyValidationLoading: boolean // variantsPanelLogiccanSubmitExperiment: boolean+ createReplayVisionScanner: booleanexperiment: Experiment & {feature_flag_filters?: FeatureFlagFilters}@@ -100,6 +141,7 @@ export interface createExperimentLogicValues {formCanceled: booleanisExperimentSubmitting: booleanmode: 'create' | 'link'+ replayVisionEnabled: booleansharedMetrics: {primary: ExperimentMetric[]secondary: ExperimentMetric[]@@ -150,6 +192,9 @@ export interface createExperimentLogicActions {saveExperimentSuccess: () => {value: true}+ setCreateReplayVisionScanner: (enabled: boolean) => {+ enabled: boolean+ }setExperiment: (experiment: Experiment) => {experiment: Experiment}@@ -215,6 +260,7 @@ export interface createExperimentLogicMeta {feature_flag_filters?: FeatureFlagFilters}) => 'create' | 'link'+ replayVisionEnabled: (featureFlags: FeatureFlagsSet) => boolean}}@@ -235,6 +281,8 @@ export const createExperimentLogic = kea<createExperimentLogicType>([['featureFlagKeyValidation', 'featureFlagKeyValidationLoading'],projectLogic,['currentProjectId'],+ featureFlagLogic,+ ['featureFlags'],],actions: [eventUsageLogic,@@ -251,6 +299,7 @@ export const createExperimentLogic = kea<createExperimentLogicType>([resetExperiment: true,cancelForm: true,setExposureCriteria: (criteria: ExperimentExposureCriteria) => ({ criteria }),+ setCreateReplayVisionScanner: (enabled: boolean) => ({ enabled }),setFeatureFlagConfig: (config: {feature_flag_key?: stringvariants?: MultivariateFlagVariant[]@@ -308,6 +357,14 @@ export const createExperimentLogic = kea<createExperimentLogicType>([resetExperiment: () => ({ ...NEW_EXPERIMENT }),},],+ createReplayVisionScanner: [+ false,+ {+ setCreateReplayVisionScanner: (_, { enabled }) => enabled,+ resetExperiment: () => false,+ saveExperimentSuccess: () => false,+ },+ ],sharedMetrics: [{ primary: [], secondary: [] } as { primary: ExperimentMetric[]; secondary: ExperimentMetric[] },{@@ -379,6 +436,11 @@ export const createExperimentLogic = kea<createExperimentLogicType>([return variantsPanelLogic({ experiment: { ...NEW_EXPERIMENT }, disabled: false }).values.mode},],+ replayVisionEnabled: [+ (s) => [s.featureFlags],+ (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean =>+ featureFlags[FEATURE_FLAGS.REPLAY_VISION] === true,+ ],})),events(({ actions, values }) => ({afterMount: () => {@@ -411,7 +473,8 @@ export const createExperimentLogic = kea<createExperimentLogicType>([const draft = readDraftFromStorage()if (draft) {- actions.setExperiment(draft)+ actions.setExperiment(draft.experiment)+ actions.setCreateReplayVisionScanner(draft.createReplayVisionScanner)}},beforeUnmount: () => {@@ -420,7 +483,7 @@ export const createExperimentLogic = kea<createExperimentLogicType>([}// Use cases covered:// - navigating away from the form without saving- writeDraftToStorage(values.experiment)+ writeDraftToStorage(values.experiment, values.createReplayVisionScanner)},})),listeners(({ values, actions }) => ({@@ -534,10 +597,12 @@ export const createExperimentLogic = kea<createExperimentLogicType>([saved_metrics_ids: savedMetrics,}- const response = (await api.create(- `api/projects/${values.currentProjectId}/experiments`,- experimentPayload- )) as Experiment+ const response = experimentFromApi(+ await experimentsCreate(+ String(values.currentProjectId),+ experimentWritePayloadForApi(experimentPayload)+ )+ )if (response.id) {// Refresh tree navigation@@ -556,7 +621,52 @@ export const createExperimentLogic = kea<createExperimentLogicType>([})actions.createExperimentSuccess()globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.CreateExperiment)- lemonToast.success('Experiment created successfully!')++ let replayScannerId: string | null = null+ let replayScannerCreationFailed = false+ if (values.createReplayVisionScanner && values.replayVisionEnabled) {+ const { filters, usedExposureFallback } = experimentScannerFilters(+ response,+ await loadUnlinkableEventNames(response)+ )+ try {+ const replayScanner = await visionScannersCreate(+ String(values.currentProjectId),+ experimentScannerBody(response, filters, usedExposureFallback)+ )+ replayScannerId = replayScanner.id+ actions.addProductIntent({+ product_type: ProductKey.REPLAY_VISION,+ 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)+ replayScannerCreationFailed = true+ }+ }++ if (replayScannerCreationFailed) {+ lemonToast.error("Experiment created, but the Replay Vision scanner wasn't.", {+ button: {+ label: 'Set up scanner',+ action: () => router.actions.push(urls.replayVisionTemplates()),+ },+ })+ } else if (replayScannerId) {+ lemonToast.success(+ 'Experiment created. The Replay Vision scanner is off until you turn it on.',+ {+ button: {+ label: 'View scanner',+ action: () => router.actions.push(urls.replayVision(replayScannerId)),+ },+ }+ )+ } else {+ lemonToast.success('Experiment created successfully!')+ }tryShowMCPHint('experiments.create', {derivedPrompt: response.name ? `Create an A/B experiment called ${response.name}` : undefined,})diff --git a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.tsindex dec4c981478c..dd2156da85f8 100644--- a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts@@ -50,12 +50,14 @@ export interface ExperimentWizardLogicProps {}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentWizardLogicValues {+ createReplayVisionScanner: boolean // createExperimentLogicexperiment: Experiment & {feature_flag_filters?: FeatureFlagFilters} // createExperimentLogicfeatureFlagKeyValidation: FeatureFlagKeyValidation | null // createExperimentLogicfeatureFlagKeyValidationLoading: boolean // createExperimentLogicisExperimentSubmitting: boolean // createExperimentLogic+ replayVisionEnabled: boolean // createExperimentLogicsharedMetrics: {primary: ExperimentMetric[]secondary: ExperimentMetric[]@@ -81,6 +83,9 @@ export interface experimentWizardLogicActions {saveExperimentSuccess: () => {value: true} // createExperimentLogic+ setCreateReplayVisionScanner: (enabled: boolean) => {+ enabled: boolean+ } // createExperimentLogicsetExperiment: (experiment: Experiment) => {experiment: Experiment} // createExperimentLogic@@ -217,6 +222,8 @@ export const experimentWizardLogic = kea<experimentWizardLogicType>(['isExperimentSubmitting','featureFlagKeyValidation','featureFlagKeyValidationLoading',+ 'createReplayVisionScanner',+ 'replayVisionEnabled',],],actions: [@@ -226,6 +233,7 @@ export const experimentWizardLogic = kea<experimentWizardLogicType>(['setExperimentValue','setFeatureFlagConfig','setExposureCriteria',+ 'setCreateReplayVisionScanner','setSharedMetrics','saveExperiment','saveExperimentSuccess',diff --git a/frontend/src/scenes/experiments/ExperimentWizard/steps/AnalyticsStep.tsx b/frontend/src/scenes/experiments/ExperimentWizard/steps/AnalyticsStep.tsxindex 28a01199d1da..66ac7302866b 100644--- a/frontend/src/scenes/experiments/ExperimentWizard/steps/AnalyticsStep.tsx+++ b/frontend/src/scenes/experiments/ExperimentWizard/steps/AnalyticsStep.tsx@@ -1,14 +1,18 @@import { useActions, useValues } from 'kea'-import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonBanner, LemonCheckbox } from '@posthog/lemon-ui'++import { getReplayVisionEditDisabledReason } from 'products/replay_vision/frontend/utils/accessControl'import { ExposureCriteriaPanel } from '../../ExperimentForm/ExposureCriteriaPanel'import { MetricsPanel } from '../../ExperimentForm/MetricsPanel'import { experimentWizardLogic } from '../experimentWizardLogic'export function AnalyticsStep(): JSX.Element {- const { experiment, sharedMetrics } = useValues(experimentWizardLogic)- const { setExperiment, setExposureCriteria, setSharedMetrics } = useActions(experimentWizardLogic)+ const { createReplayVisionScanner, experiment, replayVisionEnabled, sharedMetrics } =+ useValues(experimentWizardLogic)+ const { setCreateReplayVisionScanner, setExperiment, setExposureCriteria, setSharedMetrics } =+ useActions(experimentWizardLogic)return (<div className="space-y-6">@@ -72,6 +76,28 @@ export function AnalyticsStep(): JSX.Element {</div></div>+ {replayVisionEnabled && (+ <LemonCheckbox+ bordered+ fullWidth+ checked={createReplayVisionScanner}+ onChange={setCreateReplayVisionScanner}+ disabledReason={getReplayVisionEditDisabledReason() ?? undefined}+ data-attr="experiment-create-replay-vision-scanner"+ label={+ <div className="py-1">+ <div className="font-semibold">Watch participant behavior with Replay Vision</div>+ <div className="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>+ }+ />+ )}+<LemonBanner type="info">You can always refine your analytics configuration and metrics after saving.</LemonBanner>diff --git a/frontend/src/scenes/experiments/replayVisionScanner.test.ts b/frontend/src/scenes/experiments/replayVisionScanner.test.tsnew file mode 100644index 000000000000..fb0abff41e43--- /dev/null+++ b/frontend/src/scenes/experiments/replayVisionScanner.test.ts@@ -0,0 +1,27 @@+import type { Experiment } from '~/types'++import { NEW_EXPERIMENT } from './constants'+import { experimentScannerPrompt } from './replayVisionScanner'++describe('experimentScannerPrompt', () => {+ it.each([+ {+ name: 'uses the hypothesis as the changed-surface grounding',+ description: 'New one-page checkout',+ expected: 'What the experiment changes: New one-page checkout',+ },+ {+ name: 'falls back to the experiment name when the hypothesis is blank',+ description: '',+ expected: 'Its name is "Checkout redesign"',+ },+ {+ name: 'treats a whitespace-only hypothesis as blank',+ description: ' ',+ expected: 'Its name is "Checkout redesign"',+ },+ ])('$name', ({ description, expected }) => {+ const experiment: Experiment = { ...NEW_EXPERIMENT, name: 'Checkout redesign', description }+ expect(experimentScannerPrompt(experiment)).toContain(expected)+ })+})diff --git a/frontend/src/scenes/experiments/replayVisionScanner.ts b/frontend/src/scenes/experiments/replayVisionScanner.tsnew file mode 100644index 000000000000..ff5c3d10099d--- /dev/null+++ b/frontend/src/scenes/experiments/replayVisionScanner.ts@@ -0,0 +1,117 @@+import { convertUniversalFiltersToRecordingsQuery } from 'scenes/session-recordings/filters/recordingsQueryConversions'++import {+ FilterLogicalOperator,+ type Experiment,+ type RecordingUniversalFilters,+ type UniversalFiltersGroupValue,+} from '~/types'++import type { ReplayScannerApi } from 'products/replay_vision/frontend/generated/api.schemas'+import {+ DEFAULT_MODEL,+ DEFAULT_PROVIDER,+ scannerToApiBody,+} from 'products/replay_vision/frontend/replay_scanners/types'++import { applySessionLinkability, getExposureFallbackFilter, getViewRecordingFiltersForVariant } from './utils'++const SCANNER_NAME_MAX_LENGTH = 255++/**+ * A classifier, not a summarizer: a fixed tag set is what makes two variants comparable, and free+ * text does not aggregate into a per-variant delta. `never-reached` is the escape tag — most+ * exposed sessions never touch the changed surface, and without somewhere to put them the model is+ * forced to invent friction on irrelevant sessions, which shows up as a fake delta between variants.+ */+export const EXPERIMENT_SCANNER_TAGS = [+ 'never-reached',+ 'smooth',+ 'hesitation',+ 'confusion',+ 'error-or-dead-end',+] as const++/**+ * The variant keys are deliberately absent: the scanner cannot know which variant a session belongs+ * to, and a prompt that names them gets confident, wrong variant labels attached to observations.+ * Attribution comes from joining observations back to the exposure event at readout instead.+ */+export function experimentScannerPrompt(experiment: Experiment): string {+ const hypothesis = experiment.description?.trim()+ return [+ 'Classify what this participant did after the point where the experiment change would first be visible to them. Ignore anything earlier in the session.',+ // The hypothesis is optional at creation, so the required name is the fallback grounding:+ // without any hint at the changed surface, the tags have nothing to distinguish sessions on.+ hypothesis+ ? `What the experiment changes: ${hypothesis}`+ : `The experiment has no written hypothesis. Its name is "${experiment.name.trim()}", so infer the changed surface from that name.`,+ 'Pick one tag:',+ '- never-reached: they never got to the part of the product the experiment changes.',+ '- smooth: they reached it and moved on without visible trouble.',+ '- hesitation: they reached it and paused, re-read, or went back and forth before acting.',+ '- confusion: they reached it and acted as if they misread it, for example wrong clicks, repeated attempts, or wandering.',+ '- error-or-dead-end: they hit an error, an empty state, or a point with no way forward.',+ 'Do not guess which variant of the experiment this session was in, and do not mention variants. Describe only what the participant did.',+ ].join('\n\n')+}++/**+ * The scanner's population: the experiment's exposed sessions, with the same session-linkability+ * handling the recordings surfaces use. A server-side exposure event carries no `$session_id`, so+ * without this the query matches zero sessions forever while the scanner looks healthy.+ *+ * Advisory only here, unlike on the recordings surfaces: the check reports "never seen with a+ * session id", which at creation time is mostly "never seen at all" — the flag is minutes old. So+ * an unlinkable exposure downgrades to the fallback filter where one exists, and otherwise keeps+ * the exposure filter. It must never fall through to the empty filter list `applySessionLinkability`+ * returns for that case, which would scan every recording in the project.+ */+export function experimentScannerFilters(+ experiment: Experiment,+ unlinkableEventNames: Set<string>+): { filters: UniversalFiltersGroupValue[]; usedExposureFallback: boolean } {+ const exposureFilters = getViewRecordingFiltersForVariant(experiment)+ const { filters, usedExposureFallback, exposureUnlinkable } = applySessionLinkability(+ exposureFilters,+ unlinkableEventNames,+ getExposureFallbackFilter(experiment)+ )+ return { filters: exposureUnlinkable ? exposureFilters : filters, usedExposureFallback }+}++export function experimentScannerBody(+ experiment: Experiment,+ filters: UniversalFiltersGroupValue[],+ usedExposureFallback: boolean+): ReplayScannerApi {+ const nameSuffix = ` (#${experiment.id})`+ const name = `${experiment.name.slice(0, SCANNER_NAME_MAX_LENGTH - nameSuffix.length)}${nameSuffix}`+ const universalFilters: RecordingUniversalFilters = {+ filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,+ duration: [],+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [{ type: FilterLogicalOperator.And, values: filters }],+ },+ }++ return scannerToApiBody({+ name,+ description: usedExposureFallback+ ? "Classifies what participants do in sessions where this experiment's feature flag was active."+ : 'Classifies what participants do after they are exposed to this experiment.',+ scanner_type: 'classifier',+ scanner_config: {+ prompt: experimentScannerPrompt(experiment),+ tags: [...EXPERIMENT_SCANNER_TAGS],+ multi_label: false,+ },+ // `model` is required by the create serializer; the rest of the product picks the same defaults.+ provider: DEFAULT_PROVIDER,+ model: DEFAULT_MODEL,+ query: convertUniversalFiltersToRecordingsQuery(universalFilters),+ // Enabling starts real credit spend, so that stays a human decision on the scanner itself.+ enabled: false,+ })+}diff --git a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.tsindex 0176cdb1f56c..c92fb3e87738 100644--- a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts+++ b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts@@ -1,5 +1,6 @@import { MakeLogicType, afterMount, kea, key, path, props, propsChanged, selectors } from 'kea'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'import api from 'lib/api'import { objectsEqual } from 'lib/utils/objects'@@ -28,6 +29,38 @@ export const RETENTION_UNLINKABLE_REASON =export const DATA_WAREHOUSE_UNLINKABLE_REASON ='This metric is measured entirely in the data warehouse, which has no session events to match recordings on.'+/** Only an explicit `false` marks an event unlinkable; absent keys stay linkable (fail open). */+export function unlinkableEventNamesFromSeenTogether(+ seenTogetherMap: Record<string, boolean> | null | undefined+): Set<string> {+ return new Set(+ Object.entries(seenTogetherMap ?? {})+ .filter(([, seen]) => seen === false)+ .map(([eventName]) => eventName)+ )+}++/**+ * One-shot version of the check below, for surfaces that need the answer once rather than as+ * mounted state. Fails open on error, the same way the logic's selector does, but captures the+ * error first: callers bake the result into objects they create, so a systemic failure here is+ * otherwise indistinguishable from "no unlinkable events".+ */+export async function loadUnlinkableEventNames(experiment: Experiment): Promise<Set<string>> {+ const eventNames = getSessionLinkabilityEventNames(experiment)+ if (eventNames.length === 0) {+ return new Set()+ }+ try {+ return unlinkableEventNamesFromSeenTogether(+ await api.propertyDefinitions.seenTogether({ eventNames, propertyDefinitionName: '$session_id' })+ )+ } catch (error) {+ posthog.captureException(error)+ return new Set()+ }+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface viewRecordingsLinkabilityLogicValues {linkabilityLoaded: boolean@@ -104,15 +137,10 @@ export const viewRecordingsLinkabilityLogic = kea<viewRecordingsLinkabilityLogic(s) => [s.seenTogetherMap],(seenTogetherMap: Record<string, boolean> | null): boolean => seenTogetherMap !== null,],- /** Only an explicit `false` marks an event unlinkable; absent keys stay linkable (fail open). */unlinkableEventNames: [(s) => [s.seenTogetherMap],(seenTogetherMap: Record<string, boolean> | null): Set<string> =>- new Set(- Object.entries(seenTogetherMap ?? {})- .filter(([, seen]) => seen === false)- .map(([eventName]) => eventName)- ),+ unlinkableEventNamesFromSeenTogether(seenTogetherMap),],}),afterMount(({ actions }) => {diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex d6dc7fc8a11a..d6c86ae31ebd 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3353,6 +3353,7 @@ class ProductIntentContext(StrEnum):EXPERIMENT_CREATED = "experiment created"EXPERIMENT_ANALYZED = "experiment analyzed"EXPERIMENT_VIEW_RECORDINGS = "experiment view recordings"+ EXPERIMENT_REPLAY_VISION_SCANNER_CREATED = "experiment replay vision scanner created"FEATURE_FLAG_CREATED = "feature flag created"SESSION_REPLAY_SET_FILTERS = "session_replay_set_filters"SESSION_REPLAY_EXPERIMENT_LINK_CLICKED = "session_replay_experiment_link_clicked"diff --git a/products/experiments/skills/scanning-experiments-with-replay-vision/SKILL.md b/products/experiments/skills/scanning-experiments-with-replay-vision/SKILL.mdindex 2933cd6f2331..b55de9e1d14e 100644--- a/products/experiments/skills/scanning-experiments-with-replay-vision/SKILL.md+++ b/products/experiments/skills/scanning-experiments-with-replay-vision/SKILL.md@@ -133,6 +133,8 @@ Template hygiene, learned the hard way: name the changed surface concretely (notEvery prompt needs the **post-exposure framing** sentence: tell the model to focus on behavior after the point where the experiment's change would first be visible and ignore earlier activity. Be honest with the user that this is a request to the model, not an enforced window — scanners view the whole recording (see Limits).+**The experiment creation wizard offers the same scanner from a checkbox**, built from `frontend/src/scenes/experiments/replayVisionScanner.ts` — the post-exposure friction template below, with the query derived the same way as Step 2. That module is the canonical version of the template, so change it and this section together, and prefer matching it over inventing a new prompt when a user already has a wizard-created scanner.+Starter templates:1. **"Did anyone notice?"** — `classifier`, tags `reached-and-interacted`, `reached-not-interacted`, `never-reached`. When an experiment lands flat, the numbers can't distinguish "the change did nothing" from "nobody encountered the change"; this can. Needs the user to describe the changed surface. Often the right first scanner.diff --git a/products/replay_vision/README.md b/products/replay_vision/README.mdindex 8b5ff06a8601..dcd426268897 100644--- a/products/replay_vision/README.md+++ b/products/replay_vision/README.md@@ -12,6 +12,12 @@ A sub-product of Session Replay. Users configure named **scanners** that PostHog**Quota** — succeeded observations write an immutable usage receipt; usage (receipts + in-flight rows) is counted against a monthly per-organization quota, with per-scanner volume estimates summed into a projected-usage prognosis shown at configuration time.+## Experiment-created scanners++The experiment creation wizard offers an opt-in Replay Vision scanner when the `replay-vision` feature flag is enabled. The scanner is a **disabled** classifier — enabling it, and the credit spend that follows, stays a human decision on the scanner itself. Its `RecordingsQuery` uses the experiment's exposure event, enrolled variant filters, custom exposure properties, and test-account setting, with the session-linkability check the experiment recordings surfaces use, applied as advice rather than a veto: an exposure event never seen with a `$session_id` falls back to the `$feature/<key>` property where one applies, and otherwise keeps the exposure filter. The check can't distinguish "captured server-side" from "not emitted yet", which at creation time is the common case, so it must never refuse and never widen the query. Scanner creation runs after the experiment has been persisted and cannot roll back a successfully created experiment.++The template lives in `frontend/src/scenes/experiments/replayVisionScanner.ts` and mirrors the one in the `scanning-experiments-with-replay-vision` skill: a fixed tag set (so variants stay comparable), an escape tag for sessions that never reached the changed surface, and no variant names in the prompt.+## Layout- `backend/models/` — `ReplayScanner`, `ReplayObservation`, usage receipts, quota grants.