: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(replay-vision): keep experiment context in the scanner cross-sell (#97013)
Kim Svatos Dugand2831cd98342
diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsxindex fa53bdc78b2b..6f5e6472c4ce 100644--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx@@ -11,6 +11,7 @@ import * as reporterPng from '@posthog/brand/hoggies/png/reporter'import * as xRayPng from '@posthog/brand/hoggies/png/x-ray'import { IconSparkles } from '@posthog/icons'import {+ LemonBanner,LemonButton,LemonCard,LemonInput,@@ -49,6 +50,7 @@ import { ScannerGoalOverview } from './components/ScannerGoalOverview'import { ScannerTemplatePicker } from './components/ScannerTemplatePicker'import { ScannerTriggers } from './components/ScannerTriggers'import { ScannerTypeConfigEditor } from './components/ScannerTypeConfigEditor'+import { parseExperimentScannerParams } from './experimentTargeting'import { replayScannerLogic } from './replayScannerLogic'import {SCANNER_EDITOR_STEPS,@@ -111,7 +113,8 @@ export function ScannerEditorSceneComponent(): JSX.Element {// Multivariate flag; a truthy check would turn the goal flow on for control too.const goalFlow = featureFlags[FEATURE_FLAGS.VISION_GOAL_BASED_CREATION_FLOW] === 'test'const [manualMode, setManualMode] = useState(false)- const showGoalEntry = step === 'template' && goalFlow && !manualMode+ // Read once on mount, because the wizard strips the deep-link params as soon as it consumes them.+ const [experimentDeepLink] = useState(() => parseExperimentScannerParams(router.values.searchParams) !== null)// Reached a form step by clicking Edit on the goal overview: the overview is home, not a wizard// stop, so the linear stepper is hidden and the footer returns there instead of marching on.const fromOverview = searchParams.from === 'overview'@@ -126,9 +129,17 @@ export function ScannerEditorSceneComponent(): JSX.Element {scannerValidationErrors,showScannerErrors,durationValidationError,+ experimentContext,} = useValues(scannerLogic)const { submitScanner } = useActions(scannerLogic)+ // An experiment cross-sell entry point has already said what to watch and deep-linked the+ // targeting. Asking for that goal again as free text loses the prefill from view and makes the+ // user restate it, so those entries get the template picker with the prefill already applied.+ // Only the deep link decides this. A context that arrives later (the experiment fetch, or a+ // restored draft that carries targeting) would swap the layout under someone already typing.+ const showGoalEntry = step === 'template' && goalFlow && !manualMode && !experimentDeepLink+if (step !== 'template' && (scannerLoading || !scanner)) {return (<SceneContent>@@ -220,10 +231,12 @@ export function ScannerEditorSceneComponent(): JSX.Element {scanner from scratch.</p></div>+ <ExperimentScopeNote experimentName={experimentContext?.experiment.name} /><ScannerTemplatePicker />{/* The goal flow supersedes this box, so someone who has already- turned it down to build by hand should not be offered it again. */}- {!goalFlow && <ScannerGoalDraft />}+ turned it down to build by hand should not be offered it again.+ An experiment entry never saw the goal flow, so it keeps the box. */}+ {(!goalFlow || experimentDeepLink) && <ScannerGoalDraft />}</>)) : step === 'overview' ? (@@ -272,6 +285,20 @@ export function ScannerEditorSceneComponent(): JSX.Element {)}+/** Tells an experiment entry that the targeting came with it, so the template step doesn't read as+ * a blank start that dropped the experiment. The variant picker itself lives on the Recordings step. */+function ExperimentScopeNote({ experimentName }: { experimentName?: string }): JSX.Element | null {+ if (!experimentName) {+ return null+ }+ return (+ <LemonBanner type="info">+ This scanner watches sessions of people exposed to {experimentName}. That holds whichever way you set it up+ below, and you can narrow it to one variant on the Recordings step.+ </LemonBanner>+ )+}+function DetailsStep(): JSX.Element {const { tags: allTags } = useValues(tagsModel)diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsxindex 60cb6d9b6609..32a6844bb5b2 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx@@ -15,7 +15,7 @@ import { replayScannerLogic } from '../replayScannerLogic'export function ScannerGoalDraft(): JSX.Element {const textAreaRef = useRef<HTMLTextAreaElement>(null)const logic = replayScannerLogic({ id: 'new' })- const { goalDraftInput, goalDraftLoading } = useValues(logic)+ const { goalDraftInput, goalDraftLoading, experimentContext } = useValues(logic)const { draftScannerFromGoal, setGoalDraftInput } = useActions(logic)// Drafting creates a scanner, so it needs the same editor access as the rest of the wizard.@@ -63,6 +63,14 @@ export function ScannerGoalDraft(): JSX.Element {hideFocusdata-attr="vision-goal-draft-input"/>+ {/* The page-level scope note sits above the template grid, so someone who+ scrolled down to this box has lost sight of it. */}+ {experimentContext ? (+ <div className="px-4 pb-2 text-xs text-muted">+ Whatever you describe, this scanner keeps watching people exposed to{' '}+ {experimentContext.experiment.name}. You don't have to mention the experiment.+ </div>+ ) : null}<div className="flex items-center justify-between px-4 pb-3"><div className="flex items-center gap-1.5 text-xs text-tertiary"><IconSparkles className="text-ai size-3.5" />diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsxindex 2ca664058220..3e6c3b15ab2a 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx@@ -20,7 +20,7 @@ const MAX_SCAN_BUDGET = 100000000* and lands the user on the overview step to review it. */export function ScannerGoalFlow({ onManual }: { onManual: () => void }): JSX.Element {const logic = replayScannerLogic({ id: 'new' })- const { goalDraftInput, goalBudgetInput, goalDraftLoading } = useValues(logic)+ const { goalDraftInput, goalBudgetInput, goalDraftLoading, experimentContext } = useValues(logic)const { draftScannerFromGoal, setGoalDraftInput, setGoalBudgetInput } = useActions(logic)// Drafting creates a scanner, so it needs the same editor access as the rest of the wizard.@@ -67,6 +67,14 @@ export function ScannerGoalFlow({ onManual }: { onManual: () => void }): JSX.EleSay what to learn and which part of the product to watch. The agent maps it onto your realpages.</div>+ {/* A draft restored from an earlier experiment-scoped session keeps its targeting+ through this flow, so say whose sessions the scanner ends up watching. */}+ {experimentContext ? (+ <div className="text-xs text-muted">+ This scanner keeps watching people exposed to {experimentContext.experiment.name}. You don't+ have to mention the experiment.+ </div>+ ) : null}</div><div className="flex flex-col gap-1">diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 194ff7f148b9..77b0ce494d0e 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -194,6 +194,39 @@ describe('replayScannerLogic', () => {expect(logic.values.scanner?.experiment_targeting).toEqual({ experiment_id: 11, variant: 'test' })})+ it('keeps an experiment prefill the AI draft did not name', async () => {+ // The experiment cross-sell deep-links targeting the goal text never mentions. Dropping it+ // here would save a scanner watching every visitor of the drafted pages, not the participants.+ useMocks({+ get: {+ '/api/projects/:team/experiments/:id/': () => [200, { id: 7, name: 'Checkout redesign' }],+ },+ })+ draftSpy.mockReturnValue([+ 200,+ {+ name: 'Billing drop-off',+ description: 'Watches where people give up.',+ scanner_type: 'monitor',+ scanner_config: { prompt: 'Watch for drop-off.' },+ rationale: '',+ query: { kind: 'RecordingsQuery' },+ },+ ])+ router.actions.push(urls.replayVisionScannerTemplate('new'), { experiment: '7' })+ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()+ expect(logic.values.experimentContext).toMatchObject({ experiment: { id: 7 }, variantKey: null })++ await expectLogic(logic, () =>+ logic.actions.draftScannerFromGoal('where do people give up in billing')+ ).toFinishAllListeners()++ expect(logic.values.scanner).toMatchObject({+ name: 'Billing drop-off: Checkout redesign',+ experiment_targeting: { experiment_id: 7, variant: null },+ })+ })+it('drops a stale draft when the user has left the template step mid-request', async () => {draftSpy.mockReturnValue([200,diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex 394261480b3c..790401aa7b13 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -68,6 +68,7 @@ import { clampDurationFilter, durationFilterError } from './durationBounds'import {ExperimentScannerContext,buildExperimentTargeting,+ experimentScannerName,parseExperimentScannerParams,prefillScannerForExperiment,reconcileVariantKey,@@ -1814,17 +1815,41 @@ export const replayScannerLogic = kea<replayScannerLogicType>([) {return}- actions.resetScanner(newScanner(null, teamLogic.values.currentTeam?.name))+ // An experiment prefill (targeting, scoped name, test-account setting) has to survive+ // the AI draft the same way it survives a template pick, or a scanner started from an+ // experiment would end up watching every visitor instead of the participants. A draft+ // that named an experiment itself is fresher intent, so it wins.+ const context = goalDraft.experiment_targeting ? null : values.experimentContext+ if (goalDraft.experiment_targeting && values.experimentContext) {+ // rebuildExperimentContext keeps a card whose experiment id already matches, so a+ // draft that renames the variant would leave the Recordings step showing the old+ // one while the scanner saves the new one. Drop the card and let it rebuild.+ actions.setExperimentContext(null)+ }+ const base = newScanner(null, teamLogic.values.currentTeam?.name)+ actions.resetScanner(context ? prefillScannerForExperiment(base, context) : base)+ const draftQuery = goalDraft.query as RecordingsQuery | undefined// Applied as form values (not baked into the reset) so the draft persists like hand-edited// input and survives a reload of the configure step.actions.setScannerValues({- name: goalDraft.name,+ name: context ? experimentScannerName(goalDraft.name, context.experiment.name) : goalDraft.name,description: goalDraft.description,scanner_type: goalDraft.scanner_type as ScannerType,scanner_config: goalDraft.scanner_config as ScannerConfig,// The drafted session filter (when the goal mapped to real screens or events); the- // triggers step shows it for review like any hand-picked filter.- ...(goalDraft.query ? { query: goalDraft.query as RecordingsQuery } : {}),+ // triggers step shows it for review like any hand-picked filter. Under an+ // experiment prefill it keeps that experiment's test-account setting.+ ...(draftQuery+ ? {+ query: context+ ? {+ ...draftQuery,+ filter_test_accounts:+ context.experiment.exposure_criteria?.filterTestAccounts ?? false,+ }+ : draftQuery,+ }+ : {}),// A goal-flow draft also solves the budget dials; legacy drafts keep the wizard defaults....(goalDraft.sampling_mode ? { sampling_mode: goalDraft.sampling_mode as SamplingMode } : {}),...(goalDraft.sampling_rate != null ? { sampling_rate: goalDraft.sampling_rate } : {}),@@ -1837,7 +1862,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// The experiment the goal named, if any. It watches that experiment's// participants, which the query itself can't express — the backend derives the// exposure filter from this field at scan time.- experiment_targeting: goalDraft.experiment_targeting ?? null,+ experiment_targeting:+ goalDraft.experiment_targeting ?? (context ? buildExperimentTargeting(context) : null),})// Loads the targeted experiment so the Triggers step shows its card and variant// picker, the same way it does for a scanner started from the experiment itself.