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.

feat(replay-vision): create and edit experiment scanners in the scanner editor (#112019)

Kim Svatos Dugan0246fbceb71d
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 7b054733dc03..e949292b68da 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -575,6 +575,7 @@ export const FEATURE_FLAGS = {
UX_REMOVE_SIDEPANEL: 'ux-remove-sidepanel', // owner: #team-surveys
VISION_ENTRYPOINT_EXPERIMENTS: 'vision-entrypoint-experiments', // owner: #team-replay, cross-sell entry points from experiments
VISION_ENTRYPOINT_REPLAY_FILTERS: 'vision-entrypoint-replay-filters', // owner: #team-replay, cross-sell entry point from the replay filters panel
+ VISION_EXPERIMENT_SCANNER: 'experiment-scanner', // owner: #team-replay, experiment scanners overall: the type in the scanner editor, creating one from experiments, and the variants tab
VISION_GOAL_FLOW_V2: 'vision-goal-flow-v2', // owner: #team-replay multivariate=control,test — gate on === 'test'; a truthy check turns on for control too
VISUAL_REVIEW: 'visual-review', // owner: #team-devex
WAREHOUSE_MULTI_DESTINATION: 'warehouse-multi-destination', // owner: #team-warehouse-sources
diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsx
index 247f1fc92a17..113b5a781625 100644
--- a/products/replay_vision/frontend/components/ObservationCard.tsx
+++ b/products/replay_vision/frontend/components/ObservationCard.tsx
@@ -17,7 +17,7 @@ import {
} from '../replay_scanners/types'
import { markSimilarSearchIntent, similarSearchUrl } from '../search/observationQueries'
import { citedTextToPlainText, parseCitedSegments } from '../utils/citations'
-import { VERDICT_LABEL, confidenceLevel, readReasoning, scannerLabel } from '../utils/observation'
+import { VERDICT_LABEL, confidenceLevel, isSummaryScannerType, readReasoning, scannerLabel } from '../utils/observation'
import { CitedMarkdown } from './CitedMarkdown'
import { LabeledRow } from './LabeledRow'
import { ObservationProgressBar } from './ObservationProgressBar'
@@ -181,7 +181,7 @@ export function ObservationPrimaryOutput({
)
}
- if (scannerType === 'summarizer') {
+ if (isSummaryScannerType(scannerType)) {
const title = typeof result.title === 'string' ? result.title : null
const summary = typeof result.summary === 'string' ? result.summary : null
const showCopy = copyable && summary !== null
@@ -410,7 +410,7 @@ export function ObservationDockCard({
const similarUrl = observation.status === 'succeeded' ? similarSearchUrl(observation) : null
// Summarizers excluded: their primary output already is the full text
const reasoning =
- observation.status === 'succeeded' && scannerType !== 'summarizer' ? readReasoning(observation) : null
+ observation.status === 'succeeded' && !isSummaryScannerType(scannerType) ? readReasoning(observation) : null
return (
<div className="border rounded p-3 bg-surface-primary space-y-2">
@@ -490,7 +490,7 @@ export function ObservationDockCard({
copyable
/>
</LabeledRow>
- {prompt && scannerType !== 'summarizer' && (
+ {prompt && !isSummaryScannerType(scannerType) && (
<ObservationPrompt prompt={prompt} question={observation.prompt_question} />
)}
{reasoning && (
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
index 3eddf03964a0..2369aaf6ec10 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
@@ -50,17 +50,12 @@ import { LIMIT_REACHED_TOOLTIP } from './scannerCopy'
import {
ENABLED_OPTIONS,
EnabledFilter,
- SCANNER_TYPE_OPTIONS,
+ scannerTypeOptions,
ScannerType,
ReplayScanner,
homeRedesignVariant,
} from './types'
-const TYPE_OPTIONS: { value: ScannerType; label: string }[] = SCANNER_TYPE_OPTIONS.map(({ value, label }) => ({
- value,
- label,
-}))
-
function ScannerRowActions({ scanner }: { scanner: ReplayScanner }): JSX.Element {
const { deletingIds } = useValues(replayScannersLogic)
const { deleteScanner, duplicateScanner } = useActions(replayScannersLogic)
@@ -349,7 +344,10 @@ export function ReplayScannersScene(): JSX.Element {
<FilterPill<ScannerType>
label="Type"
dataAttr="vision-scanners-type-filter"
- options={TYPE_OPTIONS}
+ options={scannerTypeOptions(
+ !!featureFlags[FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER] ||
+ !!scannerStats?.by_type?.experiment?.total
+ ).map(({ value, label }) => ({ value, label }))}
value={scannerTypeFilter}
onChange={(v) => setScannersFilters({ scannerTypeFilter: v })}
/>
diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
index 49a03679d03d..3c266a34a33f 100644
--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
@@ -26,6 +26,7 @@ import { pngHoggie } from 'lib/brand/hoggies'
import { GuidedWizardStepper } from 'lib/components/GuidedWizard/GuidedWizardStepper'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { FEATURE_FLAGS } from 'lib/constants'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -64,7 +65,7 @@ import {
scannerStepUrlWithParams,
} from './scannerEditorSceneLogic'
import { scannerSelfDrivingStatsLogic } from './scannerSelfDrivingStatsLogic'
-import { MODEL_OPTIONS, SCANNER_TYPE_OPTIONS } from './types'
+import { MODEL_OPTIONS, SCANNER_TYPE_OPTIONS, scannerTypeOptions } from './types'
const HedgehogConstruction2 = pngHoggie(construction2Png)
const HedgehogImTheDriver = pngHoggie(imTheDriverPng)
@@ -352,6 +353,7 @@ function ConfigureStep(): JSX.Element {
const { setScannerType } = useActions(replayScannerLogic({ id: scannerId }))
const { searchParams } = useValues(router)
const isTypeSelectable = isNew && !searchParams.template
+ const experimentScanners = useFeatureFlag('VISION_EXPERIMENT_SCANNER')
if (!scanner) {
return <></>
@@ -392,16 +394,18 @@ function ConfigureStep(): JSX.Element {
}
setScannerType(next)
}}
- options={SCANNER_TYPE_OPTIONS.map((opt) => ({
- value: opt.value,
- label: opt.label,
- labelInMenu: (
- <div className="flex flex-col">
- <span className="font-medium">{opt.label}</span>
- <span className="text-xs text-muted">{opt.description}</span>
- </div>
- ),
- }))}
+ options={scannerTypeOptions(experimentScanners || scanner.scanner_type === 'experiment').map(
+ (opt) => ({
+ value: opt.value,
+ label: opt.label,
+ labelInMenu: (
+ <div className="flex flex-col">
+ <span className="font-medium">{opt.label}</span>
+ <span className="text-xs text-muted">{opt.description}</span>
+ </div>
+ ),
+ })
+ )}
/>
</LemonField>
) : (
diff --git a/products/replay_vision/frontend/replay_scanners/components/EnabledScannersCard.tsx b/products/replay_vision/frontend/replay_scanners/components/EnabledScannersCard.tsx
index fb3a620fa000..e4b76442b006 100644
--- a/products/replay_vision/frontend/replay_scanners/components/EnabledScannersCard.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/EnabledScannersCard.tsx
@@ -1,13 +1,15 @@
import { useValues } from 'kea'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { cn } from 'lib/utils/css-classes'
import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'
import { replayScannersLogic } from '../replayScannersLogic'
-import { SCANNER_TYPE_OPTIONS } from '../types'
+import { scannerTypeOptions } from '../types'
export function EnabledScannersCard({ className }: { className?: string }): JSX.Element {
const { scannerStats } = useValues(replayScannersLogic)
+ const experimentScanners = useFeatureFlag('VISION_EXPERIMENT_SCANNER')
return (
<div className={cn('bg-bg-light border rounded p-4 flex flex-col', className)}>
@@ -20,17 +22,19 @@ export function EnabledScannersCard({ className }: { className?: string }): JSX.
</span>
</div>
<div className="flex flex-wrap gap-1.5 mt-3">
- {SCANNER_TYPE_OPTIONS.map(({ value }) => {
- const { enabled = 0, total = 0 } = scannerStats?.by_type?.[value] ?? {}
- return (
- <ScannerTypeBadge
- key={value}
- scannerType={value}
- variant={total > 0 ? 'default' : 'muted'}
- suffix={`${enabled}/${total}`}
- />
- )
- })}
+ {scannerTypeOptions(experimentScanners || !!scannerStats?.by_type?.experiment?.total).map(
+ ({ value }) => {
+ const { enabled = 0, total = 0 } = scannerStats?.by_type?.[value] ?? {}
+ return (
+ <ScannerTypeBadge
+ key={value}
+ scannerType={value}
+ variant={total > 0 ? 'default' : 'muted'}
+ suffix={`${enabled}/${total}`}
+ />
+ )
+ }
+ )}
</div>
</div>
)
diff --git a/products/replay_vision/frontend/replay_scanners/components/ExperimentScannerConfigFields.tsx b/products/replay_vision/frontend/replay_scanners/components/ExperimentScannerConfigFields.tsx
new file mode 100644
index 000000000000..13f384d44274
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ExperimentScannerConfigFields.tsx
@@ -0,0 +1,143 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { LemonBanner, LemonSwitch } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInputSelect, type LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+import { Link } from 'lib/lemon-ui/Link'
+import { getExperimentVariants } from 'scenes/experiments/utils'
+import { urls } from 'scenes/urls'
+
+import { experimentScannerPickerLogic } from '../experimentScannerPickerLogic'
+import { replayScannerLogic } from '../replayScannerLogic'
+import type { ExperimentScannerConfig } from '../types'
+
+export interface ExperimentScannerConfigFieldsProps {
+ scannerId: string
+}
+
+/** The experiment type's scope: which experiment and variants it watches, and how it samples them. */
+export function ExperimentScannerConfigFields({ scannerId }: ExperimentScannerConfigFieldsProps): JSX.Element | null {
+ const logic = replayScannerLogic({ id: scannerId })
+ const { scanner, isNew, experimentContext, originalScanner } = useValues(logic)
+ const { setScannerExperiment } = useActions(logic)
+ const { experimentOptions, experimentOptionsLoading, search } = useValues(experimentScannerPickerLogic)
+ const { ensureOptionsLoaded, setSearch } = useActions(experimentScannerPickerLogic)
+
+ const config = scanner?.scanner_type === 'experiment' ? scanner.scanner_config : null
+ const experiment = experimentContext?.experiment.id === config?.experiment_id ? experimentContext?.experiment : null
+
+ const experimentSelectOptions = useMemo((): LemonInputSelectOption[] => {
+ const options = experimentOptions.map((option) => ({ key: String(option.id), label: option.name }))
+ if (experiment && !options.some((option) => option.key === String(experiment.id))) {
+ options.unshift({ key: String(experiment.id), label: experiment.name })
+ }
+ return options
+ }, [experimentOptions, experiment])
+
+ if (!config) {
+ return null
+ }
+ const variantOptions = getExperimentVariants(experiment).map((variant) => ({
+ key: variant.key,
+ label: variant.key,
+ }))
+ const originalConfig =
+ originalScanner?.scanner_type === 'experiment'
+ ? (originalScanner.scanner_config as ExperimentScannerConfig)
+ : null
+ const balanceChanged =
+ !isNew &&
+ originalConfig !== null &&
+ (originalConfig.balance_variants ?? true) !== (config.balance_variants ?? true)
+
+ return (
+ <div className="space-y-4">
+ <LemonField
+ name="scanner_config.experiment_id"
+ label="Experiment"
+ help={
+ experiment ? (
+ <>
+ Watches sessions of people exposed to{' '}
+ <Link to={urls.experiment(experiment.id)}>{experiment.name}</Link>. Each summary gets the
+ person's variant from exposure data.
+ </>
+ ) : (
+ "Watches sessions of people exposed to this experiment. Each summary gets the person's variant from exposure data."
+ )
+ }
+ >
+ {() => (
+ <LemonInputSelect
+ mode="single"
+ placeholder="Select a running experiment"
+ loading={experimentOptionsLoading}
+ disabled={!isNew}
+ disabledReason={
+ isNew
+ ? undefined
+ : 'The experiment is fixed after creation. Create a new scanner to watch another experiment.'
+ }
+ disableFiltering
+ value={config.experiment_id ? [String(config.experiment_id)] : []}
+ options={experimentSelectOptions}
+ emptyStateComponent={
+ <p className="text-secondary italic p-1">
+ {search ? `No running experiments match "${search}"` : 'No running experiments'}
+ </p>
+ }
+ onFocus={() => ensureOptionsLoaded()}
+ onInputChange={(text) => setSearch(text)}
+ onChange={(values) => setScannerExperiment(values.length > 0 ? Number(values[0]) : null)}
+ data-attr="vision-experiment-scanner-picker"
+ />
+ )}
+ </LemonField>
+ {experiment && !experiment.start_date && (
+ <LemonBanner type="info">
+ This experiment hasn't launched. The scanner stays off and turns on when the experiment launches.
+ </LemonBanner>
+ )}
+ <LemonField name="scanner_config.variants" label="Variants" help="Leave empty to watch every variant.">
+ {({ value, onChange }) => (
+ <LemonInputSelect
+ mode="multiple"
+ placeholder="All variants"
+ disabledReason={experiment ? undefined : 'Select an experiment first'}
+ value={(value as string[] | null) ?? []}
+ onChange={(keys) => onChange(keys.length > 0 ? keys : null)}
+ options={variantOptions}
+ data-attr="vision-experiment-scanner-variants"
+ />
+ )}
+ </LemonField>
+ <LemonField name="scanner_config.balance_variants">
+ {({ value, onChange }) => (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <LemonSwitch
+ checked={value !== false}
+ onChange={onChange}
+ data-attr="vision-experiment-scanner-balance-variants"
+ />
+ <div>
+ <div className="text-sm font-medium">Sample variants evenly</div>
+ <div className="text-xs text-muted">
+ Each variant gets enough sessions, even with an uneven split. Turn off to follow
+ traffic.
+ </div>
+ </div>
+ </div>
+ {balanceChanged && (
+ <LemonBanner type="warning">
+ This change starts a new scanner version. Earlier observations keep the old sampling.
+ </LemonBanner>
+ )}
+ </div>
+ )}
+ </LemonField>
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx
index a11bc64f26dd..d37c8e1cf751 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx
@@ -18,6 +18,7 @@ import { AnyPropertyFilter, PropertyFilterType } from '~/types'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import { creditsToUsd, formatCreditCount } from '../../utils/credits'
+import { scannerExperimentScope, scopeVariantsLabel } from '../experimentTargeting'
import { replayScannerLogic } from '../replayScannerLogic'
import { ScannerEditorStep, scannerStepUrlWithParams } from '../scannerEditorSceneLogic'
import {
@@ -119,12 +120,12 @@ export interface EligibleFilterGroup {
/** The targeted experiment and variant, named so the row stands alone before the experiment loads. */
function experimentValues(scanner: ReplayScanner, experimentName?: string): string[] {
- const targeting = scanner.experiment_targeting
- if (!targeting?.experiment_id) {
+ const scope = scannerExperimentScope(scanner)
+ if (!scope) {
return []
}
- const variant = targeting.variant ? `${targeting.variant} variant` : 'all variants'
- return [`${experimentName ?? `Experiment ${targeting.experiment_id}`} (${variant})`]
+ const variant = scopeVariantsLabel(scope, 'all variants')
+ return [`${experimentName ?? `Experiment ${scope.experimentId}`} (${variant})`]
}
/** The pages a session must have visited.
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx
index 95a562c43f26..ebc4ca1dae89 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx
@@ -10,6 +10,7 @@ import { urls } from 'scenes/urls'
import { LabeledRow } from '../../components/LabeledRow'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import { formatCreditCount } from '../../utils/credits'
+import { scannerExperimentScope, scopeVariantsLabel } from '../experimentTargeting'
import { replayScannerLogic } from '../replayScannerLogic'
import { SCANNER_TYPE_OPTIONS, modelName, scannerTypeLabel } from '../types'
import { PromptPreview } from './PromptPreview'
@@ -25,7 +26,7 @@ export function ScannerSetupCard({ scannerId }: { scannerId: string }): JSX.Elem
return null
}
const config = scanner.scanner_config
- const targeting = scanner.experiment_targeting
+ const scope = scannerExperimentScope(scanner)
return (
<div
@@ -110,26 +111,35 @@ export function ScannerSetupCard({ scannerId }: { scannerId: string }): JSX.Elem
{scanner.scanner_config.scale.label ? ` (${scanner.scanner_config.scale.label})` : ''}
</LabeledRow>
)}
- {scanner.scanner_type === 'summarizer' && scanner.scanner_config.length && (
- <LabeledRow label="Summary length">
- <span className="capitalize">{scanner.scanner_config.length}</span>
+ {scanner.scanner_type === 'experiment' && (
+ <LabeledRow
+ label="Sample variants evenly"
+ tooltip="When enabled, each variant gets enough sessions even with an uneven split, so counts follow sampling, not traffic."
+ >
+ <EnabledText enabled={scanner.scanner_config.balance_variants !== false} />
</LabeledRow>
)}
+ {(scanner.scanner_type === 'summarizer' || scanner.scanner_type === 'experiment') &&
+ scanner.scanner_config.length && (
+ <LabeledRow label="Summary length">
+ <span className="capitalize">{scanner.scanner_config.length}</span>
+ </LabeledRow>
+ )}
<LabeledRow label="Recordings">
Scans {percentage(scanner.sampling_rate ?? 0, 1)} of matching recordings
</LabeledRow>
- {targeting && (
+ {scope && (
<LabeledRow label="Experiment">
{/* The name loads with the scanner; until then, or for an experiment the viewer can't open, the ID stands in. */}
- <Link to={urls.experiment(targeting.experiment_id)}>
- {experimentContext?.experiment.id === targeting.experiment_id
+ <Link to={urls.experiment(scope.experimentId)}>
+ {experimentContext?.experiment.id === scope.experimentId
? experimentContext.experiment.name
- : `Experiment ${targeting.experiment_id}`}
+ : `Experiment ${scope.experimentId}`}
</Link>
<span className="text-muted">
{' · '}
- {targeting.variant ? `${targeting.variant} variant` : 'every variant'}
+ {scopeVariantsLabel(scope, 'every variant')}
</span>
</LabeledRow>
)}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
index 8f0dbb3f30dc..450a522891b4 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
@@ -117,35 +117,82 @@ function ScannerFilterGroup(): JSX.Element {
)
}
-// Variant selection for a scanner targeting an experiment. The choice is stored as the scanner's
-// experiment targeting; the backend derives the person-scoped exposure filter from it at scan
-// time, so there is no filter in the card below to hand-edit.
+// The experiment population, which the backend derives from exposure data at scan time, so there is
+// no filter in the card below to hand-edit. The experiment type picks it in its configuration step.
+// Legacy targeting on other types is read-only: the API refuses a new target but accepts a clear.
function ExperimentTargeting({ scannerId }: { scannerId: string }): JSX.Element | null {
- const { experimentContext } = useValues(replayScannerLogic({ id: scannerId }))
+ const { scanner, experimentContext } = useValues(replayScannerLogic({ id: scannerId }))
const { setExperimentVariant, detachExperimentContext } = useActions(replayScannerLogic({ id: scannerId }))
+ // Until experiment scanners ship, legacy targeting keeps its variant picker.
+ const experimentScanners = useFeatureFlag('VISION_EXPERIMENT_SCANNER')
- if (!experimentContext) {
+ if (!experimentContext || !scanner) {
return null
}
const { experiment, variantKey } = experimentContext
- // A null value targets every variant; each experiment variant is a single-select option.
- const variantOptions: { value: string | null; label: string }[] = [
- { value: null, label: 'All variants' },
- ...getExperimentVariants(experiment).map((variant) => ({
- value: variant.key,
- label: variant.key,
- })),
- ]
+ const experimentLink = <Link to={urls.experiment(experiment.id)}>{experiment.name}</Link>
+
+ if (scanner.scanner_type === 'experiment') {
+ const variants = scanner.scanner_config.variants
+ return (
+ <LemonCard hoverEffect={false} className="p-3 space-y-1" data-attr="vision-experiment-targeting">
+ <LemonLabel>Experiment</LemonLabel>
+ <div className="text-xs text-muted">
+ This scanner watches sessions of people exposed to {experimentLink}
+ {variants?.length ? <span> in {variants.join(', ')}</span> : null}. Filters you add here narrow it
+ further.
+ </div>
+ </LemonCard>
+ )
+ }
+
+ if (!experimentScanners) {
+ // A null value targets every variant; each experiment variant is a single-select option.
+ const variantOptions: { value: string | null; label: string }[] = [
+ { value: null, label: 'All variants' },
+ ...getExperimentVariants(experiment).map((variant) => ({ value: variant.key, label: variant.key })),
+ ]
+ return (
+ <LemonCard hoverEffect={false} className="p-3 space-y-3" data-attr="vision-experiment-targeting">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div className="min-w-0 flex-1 space-y-1">
+ <LemonLabel>Experiment targeting</LemonLabel>
+ <div className="text-xs text-muted">
+ This scanner watches sessions of people exposed to {experimentLink}. Pick a variant to
+ narrow it, or watch every variant. Filters you add yourself are kept.
+ </div>
+ </div>
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={() => detachExperimentContext()}
+ tooltip="Stop limiting this scanner to people exposed to this experiment. Filters you added yourself are kept."
+ data-attr="vision-experiment-targeting-detach"
+ >
+ Remove targeting
+ </LemonButton>
+ </div>
+ <div className="max-w-160">
+ <LemonSelect
+ value={variantKey}
+ onChange={(key) => setExperimentVariant(key)}
+ options={variantOptions}
+ data-attr="vision-experiment-targeting-variants"
+ />
+ </div>
+ </LemonCard>
+ )
+ }
return (
- <LemonCard hoverEffect={false} className="p-3 space-y-3" data-attr="vision-experiment-targeting">
- <div className="flex items-start justify-between gap-2">
- <div className="space-y-1">
+ <LemonCard hoverEffect={false} className="p-3" data-attr="vision-experiment-targeting">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div className="min-w-0 flex-1 space-y-1">
<LemonLabel>Experiment targeting</LemonLabel>
<div className="text-xs text-muted">
- This scanner watches sessions of people exposed to{' '}
- <Link to={urls.experiment(experiment.id)}>{experiment.name}</Link>. Pick a variant to narrow it,
- or watch every variant. Filters you add yourself are kept.
+ This scanner watches sessions of people exposed to {experimentLink}
+ <span>{variantKey ? ` in ${variantKey}` : ', every variant'}</span>. To compare variants, create
+ an experiment scanner.
</div>
</div>
<LemonButton
@@ -158,14 +205,6 @@ function ExperimentTargeting({ scannerId }: { scannerId: string }): JSX.Element
Remove targeting
</LemonButton>
</div>
- <div className="max-w-160">
- <LemonSelect
- value={variantKey}
- onChange={(key) => setExperimentVariant(key)}
- options={variantOptions}
- data-attr="vision-experiment-targeting-variants"
- />
- </div>
</LemonCard>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx
index 684aa59de9fb..03d8ef14a77c 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx
@@ -25,6 +25,7 @@ import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
import { replayScannerLogic } from '../replayScannerLogic'
import { ClassifierScannerConfig, SummarizerScannerConfig, scannerTypeLabel } from '../types'
+import { ExperimentScannerConfigFields } from './ExperimentScannerConfigFields'
/** Whether this form should offer no AI help at all.
*
@@ -287,6 +288,23 @@ export function ScannerTypeConfigEditor({ scannerId }: { scannerId: string }): J
)
}
+ if (scanner.scanner_type === 'experiment') {
+ return (
+ <div className="space-y-4">
+ <ExperimentScannerConfigFields scannerId={scannerId} />
+ <ScannerPromptField
+ scannerId={scannerId}
+ label="What to focus on"
+ caption="Each session gets a summary. Say what the summaries should cover, for example the step the experiment changes and where people get stuck."
+ placeholder="Summarize what people do after they reach the checkout. Call out hesitation, errors, and where they leave."
+ />
+ <LemonField name="scanner_config.length" label="Summary length">
+ <LemonSegmentedButton className="max-w-full overflow-x-auto" options={SUMMARIZER_LENGTH_OPTIONS} />
+ </LemonField>
+ </div>
+ )
+ }
+
if (scanner.scanner_type === 'monitor') {
return (
<div className="space-y-4">
diff --git a/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.ts b/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.ts
new file mode 100644
index 000000000000..60670f08bf41
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.ts
@@ -0,0 +1,111 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { experimentsList } from 'products/experiments/frontend/generated/api'
+import type { ExperimentBasicApi } from 'products/experiments/frontend/generated/api.schemas'
+
+/** One page is enough: search narrows the rest on the server, so the dropdown never paginates. */
+const EXPERIMENT_OPTIONS_LIMIT = 50
+const SEARCH_DEBOUNCE_MS = 300
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface experimentScannerPickerLogicValues {
+ currentProjectId: number | string // teamLogic
+ experimentOptions: ExperimentBasicApi[]
+ experimentOptionsLoading: boolean
+ hasLoadedOptions: boolean
+ search: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface experimentScannerPickerLogicActions {
+ ensureOptionsLoaded: () => {
+ value: true
+ }
+ loadOptions: ({ debounce }?: { debounce: boolean }) => {
+ debounce: boolean
+ }
+ loadOptionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadOptionsSuccess: (
+ experimentOptions: ExperimentBasicApi[],
+ payload?: {
+ debounce: boolean
+ }
+ ) => {
+ experimentOptions: ExperimentBasicApi[]
+ payload?: {
+ debounce: boolean
+ }
+ }
+ setSearch: (search: string) => {
+ search: string
+ }
+}
+
+export type experimentScannerPickerLogicType = MakeLogicType<
+ experimentScannerPickerLogicValues,
+ experimentScannerPickerLogicActions
+>
+
+/** Running experiments for the experiment scanner's picker. A draft gets its scanner from the
+ * experiment wizard instead, and the API refuses a stopped one. */
+export const experimentScannerPickerLogic = kea<experimentScannerPickerLogicType>([
+ path(['products', 'replay_vision', 'replay_scanners', 'experimentScannerPickerLogic']),
+
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ })),
+
+ actions({
+ setSearch: (search: string) => ({ search }),
+ ensureOptionsLoaded: true,
+ }),
+
+ reducers({
+ search: ['', { setSearch: (_: string, { search }: { search: string }) => search }],
+ hasLoadedOptions: [false, { loadOptionsSuccess: () => true }],
+ }),
+
+ loaders(({ values }) => ({
+ experimentOptions: [
+ [] as ExperimentBasicApi[],
+ {
+ loadOptions: async (
+ { debounce }: { debounce: boolean } = { debounce: false },
+ breakpoint
+ ): Promise<ExperimentBasicApi[]> => {
+ if (debounce) {
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ }
+ const response = await experimentsList(String(values.currentProjectId), {
+ limit: EXPERIMENT_OPTIONS_LIMIT,
+ order: '-start_date',
+ status: 'running',
+ search: values.search || undefined,
+ })
+ breakpoint()
+ return response.results ?? []
+ },
+ },
+ ],
+ })),
+
+ listeners(({ actions, values }) => ({
+ setSearch: () => {
+ actions.loadOptions({ debounce: true })
+ },
+ ensureOptionsLoaded: () => {
+ if (!values.hasLoadedOptions && !values.experimentOptionsLoading) {
+ actions.loadOptions({ debounce: false })
+ }
+ },
+ })),
+])
diff --git a/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts b/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts
index a4360365df4b..84f6136a977c 100644
--- a/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts
+++ b/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts
@@ -64,6 +64,39 @@ export function buildExperimentTargeting(context: ExperimentScannerContext): Sca
}
}
+export interface ScannerExperimentScope {
+ experimentId: number
+ /** Null watches every variant. */
+ variants: string[] | null
+}
+
+/**
+ * The experiment a scanner watches, wherever it is stored. The experiment type keeps it in
+ * `scanner_config`; older types use `experiment_targeting`. Mirrors the backend's `experiment_scope()`.
+ */
+export function scannerExperimentScope(scanner: ReplayScanner | null | undefined): ScannerExperimentScope | null {
+ if (!scanner) {
+ return null
+ }
+ if (scanner.scanner_type === 'experiment') {
+ const { experiment_id, variants } = scanner.scanner_config
+ return experiment_id ? { experimentId: experiment_id, variants: variants ?? null } : null
+ }
+ const targeting = scanner.experiment_targeting
+ if (!targeting?.experiment_id) {
+ return null
+ }
+ return { experimentId: targeting.experiment_id, variants: targeting.variant ? [targeting.variant] : null }
+}
+
+/** The variants a scope watches, as a short phrase: "test variant", "a, b variants", or the fallback. */
+export function scopeVariantsLabel(scope: ScannerExperimentScope, everyVariant: string): string {
+ if (!scope.variants?.length) {
+ return everyVariant
+ }
+ return `${scope.variants.join(', ')} ${scope.variants.length === 1 ? 'variant' : 'variants'}`
+}
+
/**
* The query keys an experiment-scoped scanner takes from its experiment. The population is never
* one of them: it lives in `experiment_targeting`, and the API rejects an exposure filter set here.
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index 92b87937f511..c30761fc27e6 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -1689,6 +1689,34 @@ describe('replayScannerLogic', () => {
expect(logic.values.scanner?.experiment_targeting).toBeFalsy()
expect(logic.values.experimentContext).toBeNull()
})
+
+ it('an experiment scanner loads its experiment from the config and estimates its scope', async () => {
+ const estimateSpy = jest.fn(() => [200, {}])
+ useMocks({
+ get: {
+ '/api/projects/:team/experiments/:id/': () => [
+ 200,
+ { id: 7, name: 'Checkout redesign', start_date: '2026-09-20T00:00:00Z' },
+ ],
+ },
+ post: { '/api/projects/:team/vision/scanners/estimate/': estimateSpy },
+ })
+ logic.actions.setScannerType('experiment')
+
+ await expectLogic(logic, () => logic.actions.loadScannerEstimate()).toFinishAllListeners()
+ expect(estimateSpy).not.toHaveBeenCalled()
+
+ await expectLogic(logic, () => logic.actions.setScannerExperiment(7)).toFinishAllListeners()
+ expect(logic.values.experimentContext).toMatchObject({ experiment: { id: 7 }, variantKey: null })
+
+ logic.actions.setScannerValue(['scanner_config', 'variants'], ['test'])
+ await expectLogic(logic, () => logic.actions.loadScannerEstimate()).toFinishAllListeners()
+ const body = await (estimateSpy.mock.calls.at(-1) as any)[0].request.json()
+ expect(body).toMatchObject({
+ experiment: { experiment_id: 7, variants: ['test'] },
+ experiment_targeting: null,
+ })
+ })
})
describe('team refresh on tab visibility', () => {
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 60b5ae07d129..bd0abd13c359 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -74,6 +74,7 @@ import {
parseExperimentScannerParams,
prefillScannerForExperiment,
reconcileVariantKey,
+ scannerExperimentScope,
} from './experimentTargeting'
import { ReplayScannerTab } from './replayScannerSceneLogic'
import { clearScannerDraft, readScannerDraft, writeScannerDraft } from './scannerDraft'
@@ -185,6 +186,9 @@ function defaultConfigForType(scannerType: ScannerType): ScannerConfig {
if (scannerType === 'scorer') {
return { prompt: '', scale: { min: 0, max: 10 } }
}
+ if (scannerType === 'experiment') {
+ return { prompt: '', length: 'medium', experiment_id: null, variants: null, balance_variants: true }
+ }
return { prompt: '' }
}
@@ -698,6 +702,9 @@ export interface replayScannerLogicActions {
setScannerDraftSavedAt: (savedAt: number | null) => {
savedAt: number | null
}
+ setScannerExperiment: (experimentId: number | null) => {
+ experimentId: number | null
+ }
setScannerManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -842,6 +849,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
scannerWatermarkRefreshed: (scanner: ReplayScanner) => ({ scanner }),
setExperimentContext: (context: ExperimentScannerContext | null) => ({ context }),
setExperimentVariant: (variantKey: string | null) => ({ variantKey }),
+ setScannerExperiment: (experimentId: number | null) => ({ experimentId }),
detachExperimentContext: true,
rebuildExperimentContext: true,
saveAffectedCohort: (windowDays: number, qualifier: AffectedCohortQualifier = {}) => ({
@@ -943,6 +951,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
configErrors.tags = 'Categories must be unique'
}
}
+ if (scanner.scanner_type === 'experiment' && !scanner.scanner_config.experiment_id) {
+ configErrors.experiment_id = 'Pick an experiment'
+ }
if (scanner.scanner_type === 'scorer') {
const { min, max } = scanner.scanner_config.scale
if (
@@ -1896,8 +1907,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// fetches an experiment the viewer can't see. Fails soft: without the card the scanner
// still edits normally.
rebuildExperimentContext: async () => {
- const targeting = values.scanner?.experiment_targeting
- if (!targeting?.experiment_id) {
+ const scope = scannerExperimentScope(values.scanner)
+ if (!scope) {
// A card left over from earlier targeting would keep offering variants of an
// experiment this scanner no longer watches, and the picker would re-persist it.
if (values.experimentContext) {
@@ -1905,23 +1916,27 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
return
}
- if (values.experimentContext?.experiment.id === targeting.experiment_id) {
+ if (values.experimentContext?.experiment.id === scope.experimentId) {
return
}
try {
- const experiment = await api.experiments.get(targeting.experiment_id)
+ const experiment = await api.experiments.get(scope.experimentId)
// The form's targeting can change while this request is in flight (a template pick or
// draft discard resets it), so re-check before installing the card. Otherwise a late
// response restores a card for targeting the scanner no longer carries, which a later
// variant change would then re-persist.
- const current = values.scanner?.experiment_targeting
+ const current = scannerExperimentScope(values.scanner)
if (
- current?.experiment_id !== targeting.experiment_id ||
- values.experimentContext?.experiment.id === targeting.experiment_id
+ current?.experimentId !== scope.experimentId ||
+ values.experimentContext?.experiment.id === scope.experimentId
) {
return
}
- actions.setExperimentContext({ experiment, variantKey: current.variant ?? null })
+ // The experiment type picks variants in its own config; only legacy targeting
+ // narrows to one variant through the card.
+ const variantKey =
+ values.scanner?.scanner_type === 'experiment' ? null : (current.variants?.[0] ?? null)
+ actions.setExperimentContext({ experiment, variantKey })
} catch {
// The card simply doesn't render; targeting stays intact on the scanner.
}
@@ -1937,6 +1952,13 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
actions.setScannerValue('experiment_targeting', buildExperimentTargeting(context))
},
+ // The variants belong to the old experiment, so they reset with it. Only an unsaved scanner
+ // gets here: the API fixes the experiment after creation.
+ setScannerExperiment: ({ experimentId }) => {
+ actions.setScannerValues({ scanner_config: { experiment_id: experimentId, variants: null } })
+ actions.rebuildExperimentContext()
+ },
+
// Clearing the context alone would leave the persisted targeting silently filtering to
// exposed persons with nothing in the Triggers UI able to show or remove it.
detachExperimentContext: () => {
@@ -2176,11 +2198,27 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
const version = values.estimateRequestVersion
try {
+ const scope = scannerExperimentScope(scanner)
+ const isExperimentType = scanner.scanner_type === 'experiment'
+ const context = values.experimentContext
+ const waitsForLaunch =
+ context?.experiment.id === scope?.experimentId && !context?.experiment.start_date
+ if (isExperimentType && (!scope || waitsForLaunch)) {
+ // No population to count yet: without an experiment the preview would count
+ // every session, and a draft has no exposed sessions.
+ actions.loadScannerEstimateFailure(null)
+ return
+ }
const response = await visionScannersEstimateCreate(String(teamId), {
query: scanner.query ?? undefined,
// Sent alongside the query so the preview counts the same exposed-person
- // population the scan will, instead of every eligible session.
- experiment_targeting: scanner.experiment_targeting ?? null,
+ // population the scan will, instead of every eligible session. The API
+ // refuses a request that sends both fields.
+ experiment_targeting: isExperimentType ? null : (scanner.experiment_targeting ?? null),
+ experiment:
+ isExperimentType && scope
+ ? { experiment_id: scope.experimentId, variants: scope.variants }
+ : null,
sampling_rate: scanner.sampling_rate,
// The proposed model prices the credit estimate.
model: scanner.model,
diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.ts
index 106f1179b8e4..0cc9d1e830ce 100644
--- a/products/replay_vision/frontend/replay_scanners/types.ts
+++ b/products/replay_vision/frontend/replay_scanners/types.ts
@@ -410,8 +410,19 @@ export const SCANNER_TYPE_OPTIONS: { value: ScannerType; label: string; descript
label: 'Scorer',
description: 'Scores the session on a configurable numeric scale.',
},
+ {
+ value: 'experiment',
+ label: 'Experiment',
+ description: 'Summarizes sessions for each variant of an A/B test.',
+ },
]
+/** The type options to offer. The experiment type is behind a flag until it ships, but a scanner that already
+ * has it, or a team that already has one, still sees it. */
+export function scannerTypeOptions(includeExperiment: boolean): typeof SCANNER_TYPE_OPTIONS {
+ return includeExperiment ? SCANNER_TYPE_OPTIONS : SCANNER_TYPE_OPTIONS.filter(({ value }) => value !== 'experiment')
+}
+
export interface MonitorScannerConfig {
prompt: string
allow_inconclusive?: boolean
@@ -437,10 +448,13 @@ export interface ScorerScannerConfig {
export interface ExperimentScannerConfig {
prompt: string
length?: 'short' | 'medium' | 'long'
- experiment_id: number
+ /** Null only on an unsaved form, before an experiment is picked. */
+ experiment_id: number | null
/** Variant keys to watch; null or absent means every variant. */
variants?: string[] | null
balance_variants?: boolean
+ /** Saved off on a draft experiment; the backend turns the scanner on at launch. */
+ start_on_launch?: boolean
}
export type ScannerConfig =
diff --git a/products/replay_vision/frontend/utils/observation.ts b/products/replay_vision/frontend/utils/observation.ts
index fb8ad8916f3e..4a1f329560f2 100644
--- a/products/replay_vision/frontend/utils/observation.ts
+++ b/products/replay_vision/frontend/utils/observation.ts
@@ -61,9 +61,14 @@ export function readReasoning(obs: ReplayObservationApi): string | null {
return typeof raw === 'string' && raw ? raw : null
}
-/** Summarizer output, which is the dock's primary content. */
+/** The experiment type stores the summarizer's output shape, so both read as summaries. */
+export function isSummaryScannerType(scannerType: string | null | undefined): boolean {
+ return scannerType === 'summarizer' || scannerType === 'experiment'
+}
+
+/** Summary output, which is the dock's primary content. */
export function isSummaryObservation(obs: ReplayObservationApi): boolean {
- return obs.scanner_snapshot?.scanner_type === 'summarizer'
+ return isSummaryScannerType(obs.scanner_snapshot?.scanner_type)
}
/** A scan that settled without a result: the scanner failed, or the recording did not qualify. */