:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): add the variants tab to experiment scanners (#112021)
Kim Svatos Dugan9c73c1944ee4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4b03eaa18548..e6a3f6b7c142 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -12706,6 +12706,26 @@ snapshots:hash: v1.k794b7964.b1f7357f9a6076f86d189fd22d033515a5dfaffdc153848343e8d5584280d78b.cQu30e3nNVxIifwcxe8DF3BuWKB6wTW4JQHKEhyVpRYscenes-app-replay-vision--classifier-overview--light:hash: v1.k794b7964.d783f97810e725be92a984582c6b85339167bdeacf4dbdfe05c47212aa9c9c75.RMVo1BoCfKz55txBT9FgJ2pldYxWqQlqT-zmXPop2KE+ scenes-app-replay-vision--experiment-variants--dark:+ hash: v1.k794b7964.72b706db719241e2c0d28e2a02a6fcb4a7be5dcdab09f88c3598aa70e6cb9e91.xoEYSou4heBzLBWHqzVcv9A9WlleZhQxpRiOwU4JL7s+ scenes-app-replay-vision--experiment-variants--light:+ hash: v1.k794b7964.265a587c624797e974a38dbabf74ba7dbedbe533d952b484a63f0ee6c0218a59.brxtW69oKk1UOscm5yTMwu2t4XqcQYp_M5cAp21mdVU+ scenes-app-replay-vision--experiment-variants-first-run-pending--dark:+ hash: v1.k794b7964.c57caf08e3df0e866dd24940b2cf9daeeb5aa5b70b1db79823f51c355a79b7b3.-lpN27ZP_-tT5GMGL4CHm5kOTiPOPBJHIjbgLWDhMyo+ scenes-app-replay-vision--experiment-variants-first-run-pending--light:+ hash: v1.k794b7964.35370afc30dde56a3bd42b3bd7867fafa4b40d1333ee5616cfb6c5787e1ab9f9.26leUuMz__caJ78lI3xaZRh5ZY1QIHQ1WvLsgxJEplg+ scenes-app-replay-vision--experiment-variants-narrow--dark:+ hash: v1.k794b7964.13c49e60bc6cc79445eef7be2e5ea8ef314402274a6a291337226c15e40552ed.HAC77bIjaOMOoLMRN6YWf5q3wU7dDl6V3aDmgAZcTYU+ scenes-app-replay-vision--experiment-variants-narrow--light:+ hash: v1.k794b7964.d9b0d4963eec714e16f057dfce9da13967974d4f900a882c4514c0f0c4053300.cGii9EDM-C2IiXcOO7y6aWPa4ey12Fe-DopaDhYsnMs+ scenes-app-replay-vision--experiment-variants-no-scout--dark:+ hash: v1.k794b7964.a2043e06f871b55bb7eac56ce3ed2aa40decfeef870b556e669c4ce9cd3e498f.zzQwT1srKV5UWr86OsGcTjd5MIeCD37Ev6dTw1Te1-Y+ scenes-app-replay-vision--experiment-variants-no-scout--light:+ hash: v1.k794b7964.9cb9742e367806b211fd126e3107c16fcd94308ce294a7d18b0accd5192c787f.j8RY_0ieCIyQWiTz1HjFEysl1gglkbRMgvymaB_kfUw+ scenes-app-replay-vision--experiment-variants-three-variants--dark:+ hash: v1.k794b7964.3a46d1be73932a767101335f2aa8962256f0209e7d4f20ac040e5d37e3f1e757.4XaHTLpO3eNIe6PbsJU89RNYNIPpel0Hx3OxP0k7lpc+ scenes-app-replay-vision--experiment-variants-three-variants--light:+ hash: v1.k794b7964.ba095eb635c4246983dbbc471b0973fbd042f9daad6a970f4d66d78bb6dc020d.UxdaUdzmSBJrAOH1g5VQmT1HOxLt6b8cvMaSdx2CSZcscenes-app-replay-vision--home-watch-feed--dark:hash: v1.k794b7964.4e49c04cab295c8244570e27b42dd6d08712914dfb46c071e8d58cf97e05ca22.j0LdxNaQxcSLZggc0YaC6ZMGaRSWCAHeIz8Pu4EN9e0scenes-app-replay-vision--home-watch-feed--light:diff --git a/products/replay_vision/backend/api/variants.py b/products/replay_vision/backend/api/variants.pyindex 2bd41011f274..ea43c44c3f20 100644--- a/products/replay_vision/backend/api/variants.py+++ b/products/replay_vision/backend/api/variants.py@@ -6,6 +6,7 @@ from rest_framework.exceptions import ValidationErrorfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.api.documentation import PostHogAutoSchemafrom posthog.api.routing import TeamAndOrgViewSetMixinfrom products.replay_vision.backend.api.observations import ReplayObservationSerializer@@ -130,6 +131,13 @@ class ExperimentVariantsReadoutSerializer(serializers.Serializer):)+class _ReadoutSchema(PostHogAutoSchema):+ """Keeps drf-spectacular from wrapping the ``list`` response in an array: the readout is one object."""++ def _is_list_view(self, serializer: object = None) -> bool:+ return False++class ReplayScannerVariantsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"""What users in each variant of an experiment scanner's experiment do, side by side."""@@ -137,10 +145,14 @@ class ReplayScannerVariantsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# against that team and not just the environment in the URL.# Appended to the standard stack by `TeamAndOrgViewSetMixin.get_permissions`.permission_classes = [ScoutCanonicalTeamAccessPermission]+ schema = _ReadoutSchema()scope_object = "replay_scanner"required_scopes = ["replay_scanner:read", "session_recording:read"]@extend_schema(+ # Pinned: the schema override renames the operation to `_retrieve`, and the MCP tool and its+ # callers use the `_list` name.+ operation_id="vision_scanners_variants_list",responses={200: ExperimentVariantsReadoutSerializer,400: OpenApiResponse(description="The scanner is not an experiment scanner."),diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex b5bf0531dcc9..71e18316d6ca 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -1381,8 +1381,8 @@ export const visionScannersVariantsList = async (projectId: string,scannerId: string,options?: RequestInit-): Promise<ExperimentVariantsReadoutApi[]> => {- return apiMutator<ExperimentVariantsReadoutApi[]>(getVisionScannersVariantsListUrl(projectId, scannerId), {+): Promise<ExperimentVariantsReadoutApi> => {+ return apiMutator<ExperimentVariantsReadoutApi>(getVisionScannersVariantsListUrl(projectId, scannerId), {...options,method: 'GET',})diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsxindex 506d7d6c91ef..c1a298290ce6 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx@@ -1,8 +1,9 @@import { useActions, useValues } from 'kea'-import { Suspense } from 'react'+import { Suspense, useEffect } from 'react'import { LemonBanner, LemonButton, LemonTag, Spinner } from '@posthog/lemon-ui'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { lazyWithRetry } from 'lib/utils/retryImport'@@ -30,6 +31,9 @@ const ScannerAlertsTab = lazyWithRetry(() =>const ScannerScanTab = lazyWithRetry(() =>import('./components/ScannerScanTab').then((module) => ({ default: module.ScannerScanTab })))+const VariantsTab = lazyWithRetry(() =>+ import('./components/variants/VariantsTab').then((module) => ({ default: module.VariantsTab }))+)const ScannerScoutsTab = lazyWithRetry(() =>import('./components/ScannerScoutsTab').then((module) => ({ default: module.ScannerScoutsTab })))@@ -42,12 +46,22 @@ export const scene: SceneExport = {export function ReplayScannerSceneComponent(): JSX.Element {const { scannerId, activeTab } = useValues(replayScannerSceneLogic)- const { setActiveTab } = useActions(replayScannerSceneLogic)+ const { setActiveTab, setDefaultTab } = useActions(replayScannerSceneLogic)const scannerLogic = replayScannerLogic({ id: scannerId })useAttachedLogic(scannerLogic, replayScannerSceneLogic)const { scanner, scannerLoading } = useValues(scannerLogic)+ const experimentScanners = useFeatureFlag('VISION_EXPERIMENT_SCANNER')+ const isExperimentScanner = experimentScanners && scanner?.scanner_type === 'experiment'+ const loadedScannerId = scanner?.id ?? null++ // The scene logic can't see the scanner's type, so the page tells it which tab this scanner lands on.+ useEffect(() => {+ if (loadedScannerId) {+ setDefaultTab(isExperimentScanner ? ReplayScannerTab.Variants : ReplayScannerTab.Overview)+ }+ }, [loadedScannerId, isExperimentScanner, setDefaultTab])if (scannerLoading || !scanner) {return (@@ -84,7 +98,12 @@ export function ReplayScannerSceneComponent(): JSX.Element {<QuotaBanner /><LemonTabs- activeKey={activeTab}+ // Only an experiment scanner has a Variants tab, so a stale ?tab=variants falls back.+ activeKey={+ activeTab === ReplayScannerTab.Variants && !isExperimentScanner+ ? ReplayScannerTab.Overview+ : activeTab+ }onChange={setActiveTab}data-attr="vision-scanner-tabs"tabs={[@@ -93,6 +112,15 @@ export function ReplayScannerSceneComponent(): JSX.Element {label: 'Overview',content: <ScannerOverview scannerId={scannerId} />,},+ ...(isExperimentScanner+ ? [+ {+ key: ReplayScannerTab.Variants,+ label: 'Variants',+ content: <VariantsTab scannerId={scannerId} />,+ },+ ]+ : []),{key: ReplayScannerTab.Observations,label: 'Observations',diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex ea284e2e5749..c2692aea6a1f 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -21,6 +21,7 @@ import { LONG, LONG_INACTIVE, summary as timelineSummary } from '../__mocks__/reimport type {BackfillEstimateResponseApi,DraftScannerResponseApi,+ ExperimentVariantsReadoutApi,ObservationStatsApi,ReplayObservationApi,ReplayScannerApi,@@ -697,6 +698,184 @@ const paginated = (names: string[]): Record<string, any> => ({results: names.map((name) => ({ id: name, name, property_type: 'String' })),})+// The Variants tab of an experiment scanner. The data is invented: a checkout experiment with+// balanced sampling, so the smaller variant shows a higher sampling rate.+const experimentScanner: ReplayScannerApi = scanner({+ id: '00000000-0000-0000-0000-0000000000e1',+ name: 'Post-exposure friction: New checkout flow',+ scanner_type: 'experiment',+ scanner_config: {+ prompt: 'Summarize what this participant did after they reached the checkout.',+ length: 'medium',+ experiment_id: 11,+ variants: null,+ balance_variants: true,+ },+ observations_this_month: 71,+})++const experimentObservation = (+ id: string,+ variant: string,+ title: string,+ email: string,+ createdAt: string+): ReplayObservationApi =>+ observation({+ id,+ scanner_id: experimentScanner.id,+ recording_subject_email: email,+ created_at: createdAt,+ scanner_snapshot: {+ ...observation().scanner_snapshot!,+ name: experimentScanner.name,+ scanner_type: 'experiment',+ },+ scanner_result: {+ model_output: {+ scanner_type: 'experiment',+ confidence: 0.9,+ title,+ summary: `${title} The session ends on the order confirmation page.`,+ },+ signals_count: 0,+ experiment_variant: variant,+ } as ReplayObservationApi['scanner_result'],+ })++const readyAnalysis = {+ scout_config_id: '00000000-0000-0000-0000-0000000000s1',+ scout_enabled: true,+ recorded_at: '2026-05-11T09:00:00Z',+ scanner_version: 1,+ current: true,+}++const variantsReadout = (overrides: Partial<ExperimentVariantsReadoutApi> = {}): ExperimentVariantsReadoutApi => ({+ experiment: {+ id: 11,+ name: 'New checkout flow',+ status: 'running',+ start_date: '2026-05-03T00:00:00Z',+ end_date: null,+ planned_duration_days: 21,+ current_day: 9,+ },+ window: {+ total_observations: 71,+ first_observation_at: '2026-05-03T10:00:00Z',+ last_observation_at: '2026-05-11T20:48:00Z',+ },+ variants: [+ {+ key: 'control',+ observations: 34,+ distinct_people: 31,+ median_session_duration_s: 250,+ sampling_rate: 0.12,+ analysis_observations: 34,+ digest: [+ {+ theme: 'first-try-payment',+ statement: 'Most people complete payment on the first try.',+ count: 21,+ example_observation_ids: ['00000000-0000-0000-0000-0000000000c1'],+ },+ {+ theme: 'summary-rereads',+ statement: 'Some people scroll the order summary twice before they pay.',+ count: 8,+ example_observation_ids: [],+ },+ ],+ latest_observations: [+ experimentObservation(+ '00000000-0000-0000-0000-0000000000c1',+ 'control',+ 'Adds two items, opens the cart, and completes payment in one pass.',+ '[email protected]',+ '2026-05-11T20:34:00Z'+ ),+ experimentObservation(+ '00000000-0000-0000-0000-0000000000c2',+ 'control',+ 'Reviews the order summary twice, edits the quantity, then pays.',+ '[email protected]',+ '2026-05-11T19:50:00Z'+ ),+ ],+ },+ {+ key: 'test',+ observations: 31,+ distinct_people: 29,+ median_session_duration_s: 340,+ sampling_rate: 0.4,+ analysis_observations: 31,+ digest: [+ {+ theme: 'payment-method-pause',+ statement: 'Many people pause at the payment method step before they select an option.',+ count: 11,+ example_observation_ids: ['00000000-0000-0000-0000-0000000000t1'],+ },+ {+ theme: 'promo-field',+ statement: 'Several people open and close the promo code field without entering a code.',+ count: 7,+ example_observation_ids: [],+ },+ ],+ latest_observations: [+ experimentObservation(+ '00000000-0000-0000-0000-0000000000t1',+ 'test',+ 'Reaches the payment method step and moves between two options for about 40 seconds before selecting a card.',+ '[email protected]',+ '2026-05-11T20:48:00Z'+ ),+ ],+ },+ ],+ differences: [+ {+ theme: 'payment-method-pause',+ statement: 'Pauses at the payment method step appear far more often in test.',+ counts: { test: 11, control: 2 },+ },+ {+ theme: 'promo-field',+ statement: 'Promo code interactions appear only in test.',+ counts: { test: 7, control: 0 },+ },+ ],+ unattributed_count: 6,+ analysis: readyAnalysis,+ ...overrides,+})++const withoutAnalysis = (readout: ExperimentVariantsReadoutApi): ExperimentVariantsReadoutApi => ({+ ...readout,+ variants: readout.variants.map((variant) => ({ ...variant, digest: null, analysis_observations: null })),+ differences: null,+})++const variantsDecorator = (readout: ExperimentVariantsReadoutApi): ReturnType<typeof mswDecorator> =>+ mswDecorator({+ get: {+ '/api/projects/:team_id/vision/scanners/:id/': experimentScanner,+ '/api/projects/:team_id/vision/scanners/:id/variants/': readout,+ '/api/projects/:team_id/vision/scanners/:id/observations/stats/': summarizerStats,+ '/api/projects/:team_id/vision/scanners/:id/self_driving_stats/': noSelfDrivingStats,+ '/api/projects/:team_id/experiments/:id/': {+ id: 11,+ name: 'New checkout flow',+ feature_flag_key: 'new-checkout-flow',+ start_date: '2026-05-03T00:00:00Z',+ },+ },+ })+const meta: Meta = {component: App,title: 'Scenes-App/Replay Vision',@@ -1934,3 +2113,67 @@ export const ObservationDetailTimeline: StoryObj = {await within(canvasElement).findByText('Session start')},}++export const ExperimentVariants: StoryObj = {+ parameters: {+ pageUrl: urls.replayVision(experimentScanner.id),+ featureFlags: { [FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]: true },+ },+ decorators: [variantsDecorator(variantsReadout())],+}++// No variant analysis scout yet: the counts show, and the comparison offers to set one up.+export const ExperimentVariantsNoScout: StoryObj = {+ parameters: {+ pageUrl: urls.replayVision(experimentScanner.id),+ featureFlags: { [FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]: true },+ },+ decorators: [variantsDecorator(withoutAnalysis(variantsReadout({ analysis: null })))],+}++export const ExperimentVariantsFirstRunPending: StoryObj = {+ parameters: {+ pageUrl: urls.replayVision(experimentScanner.id),+ featureFlags: { [FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]: true },+ },+ decorators: [+ variantsDecorator(withoutAnalysis(variantsReadout({ analysis: { ...readyAnalysis, recorded_at: null } }))),+ ],+}++export const ExperimentVariantsThreeVariants: StoryObj = {+ parameters: {+ pageUrl: urls.replayVision(experimentScanner.id),+ featureFlags: { [FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]: true },+ },+ decorators: [+ variantsDecorator(+ variantsReadout({+ window: { ...variantsReadout().window, total_observations: 99 },+ variants: [+ ...variantsReadout().variants,+ {+ ...variantsReadout().variants[1],+ key: 'test-compact',+ observations: 28,+ distinct_people: 27,+ sampling_rate: 0.45,+ digest: null,+ latest_observations: [],+ },+ ],+ })+ ),+ ],+}++// About 520px of scene, the width a laptop leaves with the side panel open. The nav collapses at+// this viewport, so the scene takes the whole window less its padding.+export const ExperimentVariantsNarrow: StoryObj = {+ parameters: {+ pageUrl: urls.replayVision(experimentScanner.id),+ featureFlags: { [FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]: true },+ testOptions: { viewport: { width: 560, height: 1800 } },+ },+ decorators: [variantsDecorator(variantsReadout())],+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex 8ebeca6073e6..9abd0977c160 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -32,6 +32,7 @@ import {ObservationVerdictValue,replayScannerLogic,} from '../replayScannerLogic'+import { UNATTRIBUTED_VARIANT } from '../scannerVariantsLogic'import { OBSERVATION_TRIGGER_TAG, unsuccessfulScanReason } from '../types'import { ObservationRowResult } from './ObservationRowResult'@@ -106,6 +107,7 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):observationDateFrom,observationDateTo,observationBackfillFilter,+ observationVariantFilter,hasActiveObservationFilters,observationDetailLinkParams,availableTags,@@ -129,6 +131,7 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):setObservationSubjectFilter,setObservationDateRange,setObservationBackfillFilter,+ setObservationVariantFilter,clearObservationFilters,copyAllObservations,} = useActions(logic)@@ -408,6 +411,23 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):Backfill {shortBackfillId(observationBackfillFilter)}</LemonButton>)}+ {observationVariantFilter && (+ // Arrives from the Variants tab, so like the backfill filter it only clears.+ <LemonButton+ type="secondary"+ size="small"+ sideAction={{+ icon: <IconX />,+ onClick: () => setObservationVariantFilter(null),+ tooltip: 'Clear variant filter',+ }}+ data-attr="vision-observations-variant-filter"+ >+ {observationVariantFilter === UNATTRIBUTED_VARIANT+ ? 'No variant'+ : `Variant: ${observationVariantFilter}`}+ </LemonButton>+ )}<LemonButtontype="tertiary"size="small"diff --git a/products/replay_vision/frontend/replay_scanners/components/variants/VariantCard.tsx b/products/replay_vision/frontend/replay_scanners/components/variants/VariantCard.tsxnew file mode 100644index 000000000000..bc8c471c7046--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/variants/VariantCard.tsx@@ -0,0 +1,124 @@+import { LemonCard } from '@posthog/lemon-ui'++import { Link } from 'lib/lemon-ui/Link'+import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { percentage } from 'lib/utils/numbers'+import { pluralize } from 'lib/utils/strings'++import type { VariantReadoutApi } from '../../../generated/api.schemas'+import { observationDetailUrl } from '../../../observations/replayObservationLogic'+import { VariantObservationRow } from './VariantObservationRow'++export interface VariantCardProps {+ variant: VariantReadoutApi+ color: string+ /** Whether the scanner samples variants evenly, which makes counts follow sampling, not traffic. */+ balanced: boolean+ observationsUrl: string+ onOpenObservations: () => void+}++/** One variant: live counts, its sampling rate, the analysis themes, and its newest observations. */+export function VariantCard({+ variant,+ color,+ balanced,+ observationsUrl,+ onOpenObservations,+}: VariantCardProps): JSX.Element {+ const stats = [+ pluralize(variant.observations, 'observation'),+ pluralize(variant.distinct_people, 'person', 'people'),+ variant.median_session_duration_s != null+ ? `median session ${humanFriendlyDuration(variant.median_session_duration_s)}`+ : null,+ ].filter(Boolean)++ return (+ <LemonCard hoverEffect={false} className="p-0 flex flex-col" data-attr="vision-variant-card">+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 border-b px-4 py-3">+ <span className="flex min-w-0 items-center gap-2">+ {/* The color comes from the variant's series index, so it can't be a Tailwind class. */}+ <span className="inline-block size-2.5 shrink-0 rounded-sm" style={{ backgroundColor: color }} />+ <span className="truncate font-semibold">{variant.key}</span>+ </span>+ <span className="text-xs text-muted">{stats.join(' · ')}</span>+ </div>++ {variant.sampling_rate != null && (+ <div className="px-4 pt-3 text-xs text-muted">+ <Tooltip+ title={+ balanced+ ? 'The scanner samples each variant to about the same number of sessions, so a small variant gets a higher rate. Counts follow sampling, not traffic.'+ : 'The scanner samples every variant at the same rate, so counts follow traffic.'+ }+ >+ <span className="cursor-help underline decoration-dotted underline-offset-2">+ {`Sampled at ${percentage(variant.sampling_rate, 1)} of sessions`}+ </span>+ </Tooltip>+ </div>+ )}++ {variant.digest && variant.digest.length > 0 && (+ <div className="px-4 pt-3 space-y-1.5">+ <div className="text-xs font-semibold uppercase text-muted">Themes</div>+ <ul className="m-0 list-disc space-y-1 pl-5">+ {variant.digest.map((line) => (+ <li key={line.theme} className="text-sm">+ <span>{line.statement}</span>{' '}+ <span className="text-muted">+ {variant.analysis_observations != null+ ? `(${line.count} of ${variant.analysis_observations})`+ : `(${line.count})`}+ </span>+ {line.example_observation_ids.length > 0 && (+ <span className="ml-1 text-xs">+ {line.example_observation_ids.map((id, index) => (+ <Link+ key={id}+ to={observationDetailUrl(id, {})}+ className="ml-1"+ data-attr="vision-variant-theme-example"+ >+ {`Example ${index + 1}`}+ </Link>+ ))}+ </span>+ )}+ </li>+ ))}+ </ul>+ </div>+ )}++ <div className="flex-1 px-4 py-3 space-y-2">+ <div className="text-xs font-semibold uppercase text-muted">Latest observations</div>+ {variant.latest_observations.length > 0 ? (+ <div className="flex flex-col gap-3">+ {variant.latest_observations.map((observation) => (+ <VariantObservationRow key={observation.id} observation={observation} />+ ))}+ </div>+ ) : (+ <p className="m-0 text-sm text-muted">No observations for this variant yet.</p>+ )}+ </div>++ {variant.observations > 0 && (+ <div className="border-t px-4 py-2">+ <Link+ to={observationsUrl}+ onClick={onOpenObservations}+ className="text-sm"+ data-attr="vision-variant-view-observations"+ >+ {`View all ${pluralize(variant.observations, 'observation')}`}+ </Link>+ </div>+ )}+ </LemonCard>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsx b/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsxnew file mode 100644index 000000000000..b05ce4c9e696--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsx@@ -0,0 +1,122 @@+import { LemonBanner, LemonButton, LemonCard } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'++import type { ExperimentVariantsReadoutApi } from '../../../generated/api.schemas'+import type { VariantComparisonState } from '../../scannerVariantsLogic'++export interface VariantDifferencesCardProps {+ readout: ExperimentVariantsReadoutApi+ comparisonState: VariantComparisonState+ /** Why the person can't set up the scout, or undefined when they can. */+ setupDisabledReason?: string | null+ onSetUp: () => void+ /** Opens the existing variant analysis scout; undefined when it isn't loaded. */+ onOpenScout?: () => void+}++/** The comparison between variants, which the variant analysis scout records once a day. */+export function VariantDifferencesCard({+ readout,+ comparisonState,+ setupDisabledReason,+ onSetUp,+ onOpenScout,+}: VariantDifferencesCardProps): JSX.Element {+ const scoutPaused = readout.analysis?.scout_enabled === false+ const openScoutButton = onOpenScout ? (+ <LemonButton type="secondary" size="small" onClick={onOpenScout} data-attr="vision-variants-open-scout">+ Open scout+ </LemonButton>+ ) : null++ if (comparisonState === 'no_scout') {+ return (+ <LemonCard hoverEffect={false} className="p-4 flex flex-wrap items-center justify-between gap-3">+ <div className="min-w-0 flex-1 space-y-1">+ <h3 className="m-0 text-base font-semibold">Compare what people do in each variant</h3>+ <p className="m-0 text-sm text-muted">+ Variant analysis is a scout that reads each variant's summaries once a day and records what+ differs between them. Each run uses credits.+ </p>+ </div>+ <LemonButton+ type="primary"+ onClick={onSetUp}+ disabledReason={setupDisabledReason ?? undefined}+ data-attr="vision-variants-set-up-analysis"+ >+ Set up variant analysis+ </LemonButton>+ </LemonCard>+ )+ }++ if (comparisonState === 'pending' || comparisonState === 'updating') {+ return (+ <LemonCard hoverEffect={false} className="p-4 flex flex-wrap items-center justify-between gap-3">+ <div className="min-w-0 flex-1 space-y-1">+ <h3 className="m-0 text-base font-semibold">What differs between variants</h3>+ <p className="m-0 text-sm text-muted">+ {comparisonState === 'pending'+ ? 'The first analysis arrives after the next run. The scout runs once a day, at 9:00 by default.'+ : 'The scanner changed since the last analysis, so the comparison updates after the next run.'}+ </p>+ </div>+ {openScoutButton}+ </LemonCard>+ )+ }++ const differences = readout.differences ?? []+ const analysisCount = (key: string): number | null =>+ readout.variants.find((variant) => variant.key === key)?.analysis_observations ?? null++ return (+ <LemonCard hoverEffect={false} className="p-4 space-y-3" data-attr="vision-variants-differences">+ {scoutPaused && (+ <LemonBanner+ type="warning"+ action={onOpenScout ? { children: 'Open scout', onClick: onOpenScout } : undefined}+ >+ Variant analysis is paused, so this comparison doesn't update.+ </LemonBanner>+ )}+ <div className="flex flex-wrap items-baseline justify-between gap-2">+ <h3 className="m-0 text-base font-semibold">What differs between variants</h3>+ {readout.analysis?.recorded_at && (+ <span className="text-xs text-muted">+ Updated <TZLabel time={readout.analysis.recorded_at} />+ </span>+ )}+ </div>+ <div className="flex flex-col gap-4 @3xl:flex-row">+ {differences.length > 0 ? (+ <ul className="m-0 min-w-0 flex-1 list-disc space-y-2 pl-5">+ {differences.map((difference) => (+ <li key={difference.theme} className="text-sm">+ <span>{difference.statement}</span>{' '}+ <span className="text-muted">+ {`(${Object.entries(difference.counts)+ .map(([key, count]) => {+ const outOf = analysisCount(key)+ return outOf != null ? `${key} ${count} of ${outOf}` : `${key} ${count}`+ })+ .join(', ')})`}+ </span>+ </li>+ ))}+ </ul>+ ) : (+ <p className="m-0 min-w-0 flex-1 text-sm text-muted">+ The latest analysis found no clear difference between variants.+ </p>+ )}+ <p className="m-0 text-xs text-muted @3xl:max-w-64 @3xl:border-l @3xl:pl-4">+ Counts come from the model's summaries, not from tracked events. Samples are small, so treat a+ difference under about 10 observations as a lead to check, not a result.+ </p>+ </div>+ </LemonCard>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/variants/VariantObservationRow.tsx b/products/replay_vision/frontend/replay_scanners/components/variants/VariantObservationRow.tsxnew file mode 100644index 000000000000..4146eb298332--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/variants/VariantObservationRow.tsx@@ -0,0 +1,38 @@+import { TZLabel } from 'lib/components/TZLabel'+import { Link } from 'lib/lemon-ui/Link'++import { ObservationResultSummary } from '../../../components/ObservationCard'+import { ObservationThumbnail } from '../../../components/ObservationThumbnail'+import type { ReplayObservationApi } from '../../../generated/api.schemas'+import { observationDetailUrl } from '../../../observations/replayObservationLogic'++export interface VariantObservationRowProps {+ observation: ReplayObservationApi+}++/** One recent observation of a variant: its summary, who it was, and when. */+export function VariantObservationRow({ observation }: VariantObservationRowProps): JSX.Element {+ const person = observation.recording_subject_email || observation.distinct_id+ return (+ <Link+ to={observationDetailUrl(observation.id, {})}+ subtle+ className="flex gap-3 rounded p-1 -m-1 hover:bg-fill-highlight-50"+ data-attr="vision-variant-latest-observation"+ >+ <div className="hidden @md:block w-24 shrink-0">+ <ObservationThumbnail observation={observation} className="rounded" />+ </div>+ <div className="min-w-0 flex-1 space-y-0.5">+ <div className="text-sm line-clamp-3">+ <ObservationResultSummary observation={observation} />+ </div>+ <div className="flex flex-wrap items-center gap-1 text-xs text-muted">+ {person && <span className="truncate min-w-0">{person}</span>}+ {person && <span aria-hidden>·</span>}+ <TZLabel time={observation.created_at} className="shrink-0" />+ </div>+ </div>+ </Link>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/variants/VariantsExperimentStrip.tsx b/products/replay_vision/frontend/replay_scanners/components/variants/VariantsExperimentStrip.tsxnew file mode 100644index 000000000000..5292ce2dca9a--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/variants/VariantsExperimentStrip.tsx@@ -0,0 +1,91 @@+import { LemonCard, LemonTag, type LemonTagType } from '@posthog/lemon-ui'++import { Link } from 'lib/lemon-ui/Link'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import type { ExperimentVariantsReadoutApi } from '../../../generated/api.schemas'++const STATUS_TAG_TYPE: Record<string, LemonTagType> = {+ running: 'success',+ paused: 'warning',+ draft: 'default',+}++// The same gray the experiment pages use for a variant without a series color.+const UNATTRIBUTED_COLOR = 'var(--muted)'++export interface VariantsExperimentStripProps {+ readout: ExperimentVariantsReadoutApi+ variantColors: Record<string, string>+}++/** The watched experiment, where it is in its run, and how the observations split across variants. */+export function VariantsExperimentStrip({ readout, variantColors }: VariantsExperimentStripProps): JSX.Element {+ const { experiment, window: observationWindow, variants, unattributed_count } = readout+ const total = observationWindow.total_observations+ const segments = [+ ...variants.map((variant) => ({+ key: variant.key,+ label: variant.key,+ count: variant.observations,+ color: variantColors[variant.key],+ })),+ { key: 'unattributed', label: 'No variant', count: unattributed_count, color: UNATTRIBUTED_COLOR },+ ].filter((segment) => segment.count > 0)++ return (+ <LemonCard hoverEffect={false} className="p-3 flex flex-wrap items-center justify-between gap-x-6 gap-y-3">+ <div className="min-w-0 flex flex-wrap items-center gap-2">+ {experiment ? (+ <>+ <Link to={urls.experiment(experiment.id)} className="font-semibold truncate">+ {experiment.name}+ </Link>+ <LemonTag type={STATUS_TAG_TYPE[experiment.status] ?? 'default'} className="capitalize">+ {experiment.status}+ </LemonTag>+ {experiment.current_day != null && (+ <span className="text-sm text-muted">+ {experiment.planned_duration_days+ ? `Day ${experiment.current_day} of ${Math.round(experiment.planned_duration_days)}`+ : `Day ${experiment.current_day}`}+ </span>+ )}+ </>+ ) : (+ <span className="text-sm text-muted">+ The experiment was deleted. These counts cover what the scanner saw before.+ </span>+ )}+ </div>+ <div className="w-full @3xl:w-auto @3xl:min-w-80 space-y-1.5">+ {total > 0 && (+ <div className="flex h-2 w-full overflow-hidden rounded-full bg-fill-secondary">+ {segments.map((segment) => (+ <div+ key={segment.key}+ // Widths and colors come from the data, so they can't be Tailwind classes.+ style={{ width: `${(segment.count / total) * 100}%`, backgroundColor: segment.color }}+ />+ ))}+ </div>+ )}+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">+ {segments.map((segment) => (+ <span key={segment.key} className="inline-flex items-center gap-1">+ <span+ className="inline-block size-2 rounded-sm"+ style={{ backgroundColor: segment.color }}+ aria-hidden+ />+ <span className="text-muted">{segment.label}</span>+ <span className="font-semibold tabular-nums">{segment.count}</span>+ </span>+ ))}+ <span className="text-muted">{pluralize(total, 'observation')} in total</span>+ </div>+ </div>+ </LemonCard>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/variants/VariantsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/variants/VariantsTab.tsxnew file mode 100644index 000000000000..8a3254ed9ecc--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/variants/VariantsTab.tsx@@ -0,0 +1,127 @@+import clsx from 'clsx'+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonCard, LemonSkeleton } from '@posthog/lemon-ui'++import { Link } from 'lib/lemon-ui/Link'+import { pluralize } from 'lib/utils/strings'++import { getReplayVisionEditDisabledReason } from '../../../utils/accessControl'+import { replayScannerLogic } from '../../replayScannerLogic'+import { variantAnalysisScout } from '../../scannerScout'+import { scannerScoutLogic } from '../../scannerScoutLogic'+import {+ UNATTRIBUTED_VARIANT,+ scannerVariantsLogic,+ variantComparisonState,+ variantObservationsUrl,+} from '../../scannerVariantsLogic'+import { ScannerScoutFormModal } from '../ScannerScoutFormModal'+import { VariantCard } from './VariantCard'+import { VariantDifferencesCard } from './VariantDifferencesCard'+import { VariantsExperimentStrip } from './VariantsExperimentStrip'++export interface VariantsTabProps {+ scannerId: string+}++/** An experiment scanner's readout: what differs between variants first, then each variant side by side. */+export function VariantsTab({ scannerId }: VariantsTabProps): JSX.Element {+ const { scanner } = useValues(replayScannerLogic({ id: scannerId }))+ const scannerName = scanner?.name || ''+ const scoutLogic = scannerScoutLogic({ scannerId, scannerName })+ const { scoutConfigsForScanner, createTemplateKey, settingsSkillName } = useValues(scoutLogic)+ const { openCreateModal, openScoutSettings } = useActions(scoutLogic)+ const logic = scannerVariantsLogic({ scannerId })+ const { readout, readoutLoading, readoutFailed, variantColors } = useValues(logic)+ const { loadReadout, setupAnalysisClicked, variantObservationsOpened } = useActions(logic)++ if (!readout) {+ if (readoutFailed && !readoutLoading) {+ return (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: () => loadReadout() }}>+ Couldn't load the variants. Try again, or open the observations list.+ </LemonBanner>+ )+ }+ return (+ <div className="flex flex-col gap-4">+ <LemonSkeleton className="h-14 w-full" />+ <LemonSkeleton className="h-24 w-full" />+ <LemonSkeleton className="h-64 w-full" />+ </div>+ )+ }++ const existingScout = variantAnalysisScout(scoutConfigsForScanner)+ const comparisonState = variantComparisonState(readout.analysis, !!existingScout)+ const balanced = scanner?.scanner_type !== 'experiment' || scanner.scanner_config.balance_variants !== false++ return (+ <div className="@container flex flex-col gap-4" data-attr="vision-variants-tab">+ <VariantsExperimentStrip readout={readout} variantColors={variantColors} />+ <VariantDifferencesCard+ readout={readout}+ comparisonState={comparisonState}+ setupDisabledReason={getReplayVisionEditDisabledReason(scanner?.user_access_level)}+ onSetUp={() => {+ setupAnalysisClicked()+ openCreateModal('variant-analysis')+ }}+ onOpenScout={existingScout ? () => openScoutSettings(existingScout.skill_name) : undefined}+ />+ {readout.window.total_observations === 0 ? (+ <LemonCard hoverEffect={false} className="p-4 text-sm text-muted">+ No observations yet. The scanner summarizes sessions of exposed people as they arrive, and each+ variant shows here once it has some.+ </LemonCard>+ ) : (+ <div+ className={clsx(+ 'grid grid-cols-1 gap-4 @3xl:grid-cols-2',+ // A third column only when there is a third variant, so two variants share the width.+ readout.variants.length > 2 && '@6xl:grid-cols-3'+ )}+ >+ {readout.variants.map((variant) => (+ <VariantCard+ key={variant.key}+ variant={variant}+ color={variantColors[variant.key]}+ balanced={balanced}+ observationsUrl={variantObservationsUrl(scannerId, variant.key)}+ onOpenObservations={() => variantObservationsOpened(variant.key)}+ />+ ))}+ </div>+ )}+ {readout.unattributed_count > 0 && (+ <LemonCard hoverEffect={false} className="p-3 flex flex-wrap items-center justify-between gap-2">+ <span className="min-w-0 flex-1 text-sm text-muted">+ <span className="font-semibold text-default">+ {pluralize(readout.unattributed_count, 'observation')}+ </span>{' '}+ <span>{readout.unattributed_count === 1 ? 'has no variant.' : 'have no variant.'}</span>{' '}+ <span>+ The person was exposed in an earlier session, or has no recorded flag value, so these stay+ out of the per-variant counts.+ </span>+ </span>+ <Link+ to={variantObservationsUrl(scannerId, UNATTRIBUTED_VARIANT)}+ onClick={() => variantObservationsOpened(UNATTRIBUTED_VARIANT)}+ className="text-sm"+ data-attr="vision-variants-view-unattributed"+ >+ View them+ </Link>+ </LemonCard>+ )}+ <ScannerScoutFormModal+ key={createTemplateKey ?? settingsSkillName ?? 'closed'}+ scannerId={scannerId}+ scannerName={scannerName}+ />+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 9a49640ddaf9..1eb4ca44ade8 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -1182,6 +1182,7 @@ describe('replayScannerLogic', () => {observationDateFrom: null as string | null,observationDateTo: null as string | null,observationBackfillFilter: null as string | null,+ observationVariantFilter: null as string | null,observationsSort: null,scanner: null,}@@ -1657,6 +1658,25 @@ describe('replayScannerLogic', () => {sidLogic.unmount()}})++ // The Variants tab links each variant, and the unattributed row, into the list this way.+ it('restores a variant link and sends the variant to the list endpoint', async () => {+ const listSpy = jest.fn(() => [200, { results: [] }])+ useMocks({ get: { '/api/projects/:team/vision/scanners/:id/observations/': listSpy } })+ const sidLogic = replayScannerLogic({ id: 'sid' })+ sidLogic.mount()+ try {+ router.actions.push(urls.replayVision('sid'), { tab: 'observations', variant: '__unattributed__' })+ await expectLogic(sidLogic).toFinishAllListeners()+ expect(sidLogic.values.observationVariantFilter).toBe('__unattributed__')++ await expectLogic(sidLogic, () => sidLogic.actions.loadObservations()).toFinishAllListeners()+ const url = new URL((listSpy.mock.calls.at(-1) as any)[0].request.url)+ expect(url.searchParams.get('variant')).toBe('__unattributed__')+ } finally {+ sidLogic.unmount()+ }+ })})describe('creation path telemetry', () => {diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex a5c2196c700a..7841abd05bf0 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -263,6 +263,7 @@ interface ObservationListParams {status?: stringtriggered_by?: stringbackfill_id?: string+ variant?: stringverdict?: stringtags?: stringmin_score?: number@@ -305,6 +306,7 @@ interface ObservationFilterValues {observationDateFrom: string | nullobservationDateTo: string | nullobservationBackfillFilter: string | null+ observationVariantFilter: string | null}type ObservationFilterParamKeys =@@ -318,6 +320,7 @@ type ObservationFilterParamKeys =| 'date_from'| 'date_to'| 'backfill_id'+ | 'variant'/** The filter (non-pagination, non-sort) params shared by the list/stats endpoints and the URL query string. */function observationFilterParams(@@ -354,6 +357,9 @@ function observationFilterParams(if (values.observationBackfillFilter) {params.backfill_id = values.observationBackfillFilter}+ if (values.observationVariantFilter) {+ params.variant = values.observationVariantFilter+ }return params}@@ -455,6 +461,7 @@ export interface replayScannerLogicValues {observationSubjectFilter: stringobservationTagFilter: string[]observationTriggeredByFilter: ObservationTriggeredByValue[]+ observationVariantFilter: string | nullobservationVerdictFilter: ObservationVerdictValue[]observations: ReplayObservationApi[]observationsActive: boolean@@ -633,6 +640,7 @@ export interface replayScannerLogicActions {subject: stringtags: string[]triggeredBy: ObservationTriggeredByValue[]+ variant: string | nullverdict: ObservationVerdictValue[]}) => {backfillId: string | null@@ -646,6 +654,7 @@ export interface replayScannerLogicActions {subject: stringtags: string[]triggeredBy: ObservationTriggerEnumApi[]+ variant: string | nullverdict: ObservationVerdictValue[]}retryObservation: (observationId: string) => {@@ -742,6 +751,9 @@ export interface replayScannerLogicActions {setObservationTriggeredByFilter: (values: ObservationTriggeredByValue[]) => {values: ObservationTriggerEnumApi[]}+ setObservationVariantFilter: (value: string | null) => {+ value: string | null+ }setObservationVerdictFilter: (values: ObservationVerdictValue[]) => {values: ObservationVerdictValue[]}@@ -858,7 +870,8 @@ export interface replayScannerLogicMeta {observationSubjectFilter: string,observationDateFrom: string | null,observationDateTo: string | null,- observationBackfillFilter: string | null+ observationBackfillFilter: string | null,+ observationVariantFilter: string | null) => booleanobservationDetailLinkParams: (observationsPage: number,@@ -872,6 +885,7 @@ export interface replayScannerLogicMeta {observationDateFrom: string | null,observationDateTo: string | null,observationBackfillFilter: string | null,+ observationVariantFilter: string | null,observationsSort: ObservationsSorting | null,scanner: ScannerFormValues) => Record<string, number | string>@@ -951,6 +965,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([setObservationSubjectFilter: (value: string) => ({ value }),setObservationDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),setObservationBackfillFilter: (value: string | null) => ({ value }),+ setObservationVariantFilter: (value: string | null) => ({ value }),clearObservationFilters: true,restoreObservationsTableState: (state: {page: number@@ -965,6 +980,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([dateFrom: string | nulldateTo: string | nullbackfillId: string | null+ variant: string | null}) => state,setChartDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),requestScannerEstimate: true,@@ -1517,6 +1533,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([restoreObservationsTableState: (_, { backfillId }) => backfillId,},],+ observationVariantFilter: [+ null as string | null,+ {+ setObservationVariantFilter: (_, { value }) => value,+ clearObservationFilters: () => null,+ restoreObservationsTableState: (_, { variant }) => variant,+ },+ ],chartDateFrom: ['-14d' as string | null, { setChartDateRange: (_, { dateFrom }) => dateFrom }],chartDateTo: [null as string | null, { setChartDateRange: (_, { dateTo }) => dateTo }],}),@@ -1572,6 +1596,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([s.observationDateFrom,s.observationDateTo,s.observationBackfillFilter,+ s.observationVariantFilter,],(statusFilter: ObservationStatusValue[],@@ -1583,7 +1608,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([subjectFilter: string,dateFrom: string | null,dateTo: string | null,- backfillFilter: string | null+ backfillFilter: string | null,+ variantFilter: string | null): boolean =>statusFilter.length > 0 ||triggeredByFilter.length > 0 ||@@ -1594,7 +1620,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([subjectFilter.trim().length > 0 ||dateFrom !== null ||dateTo !== null ||- backfillFilter !== null,+ backfillFilter !== null ||+ variantFilter !== null,],// Carried into observation detail links so server-computed prev/next neighbors honor the table's// filters + sort, and so the observation page can send the reader back to this exact view.@@ -1611,6 +1638,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([s.observationDateFrom,s.observationDateTo,s.observationBackfillFilter,+ s.observationVariantFilter,s.observationsSort,s.scanner,],@@ -1626,6 +1654,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([observationDateFrom: string | null,observationDateTo: string | null,observationBackfillFilter: string | null,+ observationVariantFilter: string | null,observationsSort: ObservationsSorting | null,scanner: ReplayScanner | null): Record<string, string | number> => {@@ -1640,6 +1669,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([observationDateFrom,observationDateTo,observationBackfillFilter,+ observationVariantFilter,observationsSort,observationsPage,scanner,@@ -2491,6 +2521,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([reloadObservationsAndStats()},setObservationBackfillFilter: () => reloadObservationsAndStats(),+ setObservationVariantFilter: () => reloadObservationsAndStats(),setObservationDateRange: () => reloadObservationsAndStats(),setObservationSubjectFilter: async (_, breakpoint) => {// Free-text search — debounce so typing doesn't fire a request per keystroke.@@ -2570,6 +2601,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([setObservationScoreRange: writeUrlReplace,setObservationDateRange: writeUrl,setObservationBackfillFilter: writeUrl,+ setObservationVariantFilter: writeUrl,setObservationSubjectFilter: writeUrlReplace,clearObservationFilters: writeUrl,}@@ -2597,6 +2629,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([const dateFrom = typeof searchParams.date_from === 'string' ? searchParams.date_from : nullconst dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : nullconst backfillId = typeof searchParams.backfill_id === 'string' ? searchParams.backfill_id : null+ // The new-scanner wizard reads its own `?variant=` for an experiment deep link; this list+ // filter only runs on a saved scanner's page. String() so a numeric key survives the router.+ const variantRaw = searchParams.variant+ const variant =+ typeof variantRaw === 'string' || typeof variantRaw === 'number' ? String(variantRaw) || null : nullconst sameAsCurrent =page === values.observationsPage &&sort.columnKey === values.observationsSort?.columnKey &&@@ -2610,7 +2647,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([subject === values.observationSubjectFilter &&dateFrom === values.observationDateFrom &&dateTo === values.observationDateTo &&- backfillId === values.observationBackfillFilter+ backfillId === values.observationBackfillFilter &&+ variant === values.observationVariantFilterif (!sameAsCurrent) {actions.restoreObservationsTableState({page,@@ -2625,6 +2663,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([dateFrom,dateTo,backfillId,+ variant,})}},diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.tsindex 304e1b20dce8..72739c09e6bf 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.ts@@ -45,4 +45,20 @@ describe('replayScannerSceneLogic', () => {expect(logic.values.activeTab).toBe(expected)logic.unmount()})++ it.each([+ ['no tab in the URL lands on the new default', {}, ReplayScannerTab.Variants, undefined],+ ['an explicit tab stays', { tab: 'alerts' }, ReplayScannerTab.Alerts, 'alerts'],+ ])('an experiment scanner with %s', (_name, params, expectedTab, expectedParam) => {+ const logic = replayScannerSceneLogic()+ logic.mount()+ router.actions.push(urls.replayVision('scanner-9'), params)++ logic.actions.setDefaultTab(ReplayScannerTab.Variants)++ expect(logic.values.activeTab).toBe(expectedTab)+ // The default tab keeps a clean URL, so a shared link follows the scanner's own default.+ expect(router.values.searchParams.tab).toBe(expectedParam)+ logic.unmount()+ })})diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.tsindex 3b9f672510f5..240eb2afd359 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'import { actionToUrl, router, urlToAction } from 'kea-router'import { urls } from 'scenes/urls'@@ -9,6 +9,7 @@ import { VISION_ROOT_BREADCRUMB } from '../utils/breadcrumbs'export enum ReplayScannerTab {Overview = 'overview',+ Variants = 'variants',Observations = 'observations',Search = 'search',Run = 'run',@@ -18,6 +19,7 @@ export enum ReplayScannerTab {const SCANNER_TABS: ReplayScannerTab[] = Object.values(ReplayScannerTab)// The at-a-glance Overview (charts + stat panels) is the landing tab; Observations is the drill-down list.+// An experiment scanner lands on Variants instead, through `setDefaultTab`.const DEFAULT_TAB: ReplayScannerTab = ReplayScannerTab.Overview// Keys of tabs that were merged into others, so links and bookmarks made before still open the right place.@@ -38,6 +40,7 @@ function parseTab(tab: unknown): ReplayScannerTab {export interface replayScannerSceneLogicValues {activeTab: ReplayScannerTabbreadcrumbs: Breadcrumb[]+ defaultTab: ReplayScannerTabscannerId: string}@@ -46,6 +49,9 @@ export interface replayScannerSceneLogicActions {setActiveTab: (tab: ReplayScannerTab) => {tab: ReplayScannerTab}+ setDefaultTab: (tab: ReplayScannerTab) => {+ tab: ReplayScannerTab+ }setScannerId: (scannerId: string) => {scannerId: string}@@ -71,6 +77,7 @@ export const replayScannerSceneLogic = kea<replayScannerSceneLogicType>([actions({setScannerId: (scannerId: string) => ({ scannerId }),setActiveTab: (tab: ReplayScannerTab) => ({ tab }),+ setDefaultTab: (tab: ReplayScannerTab) => ({ tab }),}),reducers({@@ -87,7 +94,21 @@ export const replayScannerSceneLogic = kea<replayScannerSceneLogicType>([setActiveTab: (_, { tab }) => tab,},],+ defaultTab: [+ DEFAULT_TAB as ReplayScannerTab,+ {+ setDefaultTab: (_, { tab }) => tab,+ },+ ],}),+ listeners(({ actions, values }) => ({+ // Only a URL without a tab follows the default; an explicit ?tab= is the user's choice.+ setDefaultTab: ({ tab }) => {+ if (router.values.searchParams.tab === undefined && values.activeTab !== tab) {+ actions.setActiveTab(tab)+ }+ },+ })),selectors({breadcrumbs: [@@ -106,7 +127,7 @@ export const replayScannerSceneLogic = kea<replayScannerSceneLogicType>([actionToUrl(({ values }) => ({setActiveTab: () => {const searchParams = { ...router.values.searchParams }- if (values.activeTab === DEFAULT_TAB) {+ if (values.activeTab === values.defaultTab) {delete searchParams.tab} else {searchParams.tab = values.activeTab@@ -135,7 +156,7 @@ export const replayScannerSceneLogic = kea<replayScannerSceneLogicType>([if (scannerId !== values.scannerId) {actions.setScannerId(scannerId)}- const tab = parseTab(searchParams.tab)+ const tab = searchParams.tab === undefined ? values.defaultTab : parseTab(searchParams.tab)if (tab !== values.activeTab) {actions.setActiveTab(tab)}diff --git a/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.test.tsnew file mode 100644index 000000000000..f790d81d92d8--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.test.ts@@ -0,0 +1,76 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { ExperimentVariantsReadoutApi, VariantsAnalysisStateApi } from '../generated/api.schemas'+import {+ UNATTRIBUTED_VARIANT,+ scannerVariantsLogic,+ variantComparisonState,+ variantObservationsUrl,+} from './scannerVariantsLogic'++const analysis = (overrides: Partial<VariantsAnalysisStateApi>): VariantsAnalysisStateApi => ({+ scout_config_id: 'scout-1',+ scout_enabled: true,+ recorded_at: '2026-10-02T09:00:00Z',+ scanner_version: 2,+ current: true,+ ...overrides,+})++const readout: ExperimentVariantsReadoutApi = {+ experiment: null,+ window: { total_observations: 3, first_observation_at: null, last_observation_at: null },+ variants: [],+ differences: null,+ unattributed_count: 0,+ analysis: null,+}++describe('scannerVariantsLogic', () => {+ it.each([+ ['no scout', null, false, 'no_scout'],+ // The scout list can know about a scout the readout loaded before, and the CTA must not offer a second.+ ['a scout the readout has not seen yet', null, true, 'pending'],+ ['a scout that has not run', analysis({ recorded_at: null }), true, 'pending'],+ ['an analysis of an older scanner version', analysis({ current: false }), true, 'updating'],+ ['a current analysis', analysis({}), true, 'ready'],+ ] as const)('reads %s as %s', (_name, state, hasScout, expected) => {+ expect(variantComparisonState(state, hasScout)).toBe(expected)+ })++ // The readout counts only succeeded observations, but every observation that has not succeeded+ // also has no variant, so the "No variant" link must narrow to succeeded ones to match its count.+ it.each([+ ['a variant', 'control', null],+ ['no variant', UNATTRIBUTED_VARIANT, 'succeeded'],+ ])('links %s to the observations its count reads', (_name, variantKey, expectedStatus) => {+ const params = new URL(variantObservationsUrl('scanner-1', variantKey), 'http://localhost').searchParams++ expect(params.get('variant')).toBe(variantKey)+ expect(params.get('status')).toBe(expectedStatus)+ })++ it('reports one tab view per mount, not one per reload', async () => {+ useMocks({ get: { '/api/projects/:team/vision/scanners/:id/variants/': () => [200, readout] } })+ initKeaTests()+ const captureSpy = jest.spyOn(posthog, 'capture')+ const logic = scannerVariantsLogic({ scannerId: 'scanner-1' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadReadoutSuccess']).toFinishAllListeners()+ await expectLogic(logic, () => logic.actions.loadReadout()).toFinishAllListeners()++ const views = captureSpy.mock.calls.filter(([event]) => event === 'replay_vision_variants_tab_viewed')+ expect(views).toEqual([+ [+ 'replay_vision_variants_tab_viewed',+ expect.objectContaining({ scanner_id: 'scanner-1', comparison_state: 'no_scout', variant_count: 0 }),+ ],+ ])+ logic.unmount()+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.tsnew file mode 100644index 000000000000..f040de96ccb6--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.ts@@ -0,0 +1,169 @@+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { combineUrl } from 'kea-router'+import posthog from 'posthog-js'++import { getSeriesColor } from 'lib/colors'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { visionScannersVariantsList } from '../generated/api'+import {+ type ExperimentVariantsReadoutApi,+ ObservationStatusEnumApi,+ type VariantsAnalysisStateApi,+} from '../generated/api.schemas'+import { ReplayScannerTab } from './replayScannerSceneLogic'++/** The observations list's value for observations with no resolved variant. */+export const UNATTRIBUTED_VARIANT = '__unattributed__'++/**+ * Where the variant comparison stands:+ * - `no_scout`: no variant analysis scout is set up.+ * - `pending`: the scout exists but has not recorded an analysis yet.+ * - `updating`: the newest analysis covers an older scanner version, so the API hides it.+ * - `ready`: a current analysis is shown.+ */+export type VariantComparisonState = 'no_scout' | 'pending' | 'updating' | 'ready'++/** `hasScout` covers a scout created after the readout loaded, so the CTA does not offer a second one. */+export function variantComparisonState(+ analysis: VariantsAnalysisStateApi | null | undefined,+ hasScout: boolean+): VariantComparisonState {+ if (!analysis) {+ return hasScout ? 'pending' : 'no_scout'+ }+ if (!analysis.recorded_at) {+ return 'pending'+ }+ return analysis.current ? 'ready' : 'updating'+}++export function variantObservationsUrl(scannerId: string, variantKey: string): string {+ return combineUrl(urls.replayVision(scannerId), {+ tab: ReplayScannerTab.Observations,+ variant: variantKey,+ // The readout counts only succeeded observations, and an observation that has not succeeded has no variant yet.+ ...(variantKey === UNATTRIBUTED_VARIANT ? { status: ObservationStatusEnumApi.Succeeded } : {}),+ }).url+}++export interface ScannerVariantsLogicProps {+ scannerId: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scannerVariantsLogicValues {+ readout: ExperimentVariantsReadoutApi | null+ readoutFailed: boolean+ readoutLoading: boolean+ variantColors: Record<string, string>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scannerVariantsLogicActions {+ loadReadout: () => any+ loadReadoutFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadReadoutSuccess: (+ readout: ExperimentVariantsReadoutApi,+ payload?: any+ ) => {+ readout: ExperimentVariantsReadoutApi+ payload?: any+ }+ setupAnalysisClicked: () => {+ value: true+ }+ variantObservationsOpened: (variantKey: string) => {+ variantKey: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scannerVariantsLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ variantColors: (readout: ExperimentVariantsReadoutApi | null) => Record<string, string>+ }+}++export type scannerVariantsLogicType = MakeLogicType<+ scannerVariantsLogicValues,+ scannerVariantsLogicActions,+ ScannerVariantsLogicProps,+ scannerVariantsLogicMeta+>++/** The Variants tab of an experiment scanner: the per-variant readout and its comparison. */+export const scannerVariantsLogic = kea<scannerVariantsLogicType>([+ path((key) => ['products', 'replay_vision', 'replay_scanners', 'scannerVariantsLogic', key]),+ props({} as ScannerVariantsLogicProps),+ key((props) => props.scannerId),++ actions({+ setupAnalysisClicked: true,+ variantObservationsOpened: (variantKey: string) => ({ variantKey }),+ }),++ loaders(({ props }) => ({+ readout: [+ null as ExperimentVariantsReadoutApi | null,+ {+ loadReadout: async () =>+ visionScannersVariantsList(String(teamLogic.values.currentTeamId), props.scannerId),+ },+ ],+ })),++ reducers({+ readoutFailed: [false, { loadReadout: () => false, loadReadoutFailure: () => true }],+ }),++ selectors({+ // Series colors in the readout's variant order, the same palette the experiment results use.+ variantColors: [+ (s) => [s.readout],+ (readout: ExperimentVariantsReadoutApi | null): Record<string, string> =>+ Object.fromEntries(+ (readout?.variants ?? []).map((variant, index) => [variant.key, getSeriesColor(index)])+ ),+ ],+ }),++ listeners(({ props, cache }) => ({+ // Once per mount: a reload after a scout is set up is not a second view.+ loadReadoutSuccess: ({ readout }) => {+ if (!cache.viewReported && readout) {+ cache.viewReported = true+ posthog.capture('replay_vision_variants_tab_viewed', {+ scanner_id: props.scannerId,+ comparison_state: variantComparisonState(readout.analysis, false),+ variant_count: readout.variants.length,+ total_observations: readout.window.total_observations,+ scout_paused: readout.analysis ? !readout.analysis.scout_enabled : null,+ })+ }+ },+ setupAnalysisClicked: () => {+ posthog.capture('replay_vision_variant_analysis_cta_clicked', { scanner_id: props.scannerId })+ },+ variantObservationsOpened: ({ variantKey }) => {+ posthog.capture('replay_vision_variant_observations_opened', {+ scanner_id: props.scannerId,+ variant: variantKey === UNATTRIBUTED_VARIANT ? 'unattributed' : 'variant',+ })+ },+ })),++ afterMount(({ actions }) => {+ actions.loadReadout()+ }),+])diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex 0cc9d1e830ce..31029386d54a 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -66,6 +66,7 @@ export const OBSERVATION_LIST_URL_PARAM_KEYS = ['date_from','date_to','backfill_id',+ 'variant',] as constexport type ObservationsUrlParams = Partial<Record<(typeof OBSERVATION_LIST_URL_PARAM_KEYS)[number], string>>diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.tsindex ca7a5ccc61b7..5a207465e9fe 100644--- a/services/mcp/src/tools/generated/replay_vision.ts+++ b/services/mcp/src/tools/generated/replay_vision.ts@@ -1748,13 +1748,13 @@ const VisionScannersVariantsListSchema = () => {const visionScannersVariantsList = (): ToolBase<ReturnType<typeof VisionScannersVariantsListSchema>,- WithAgentNote<Schemas.ExperimentVariantsReadout[]>+ WithAgentNote<Schemas.ExperimentVariantsReadout>> => ({name: 'vision-scanners-variants-list',schema: VisionScannersVariantsListSchema(),handler: async (context: Context, params: z.infer<ReturnType<typeof VisionScannersVariantsListSchema>>) => {const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.ExperimentVariantsReadout[]>({+ const result = await context.api.request<Schemas.ExperimentVariantsReadout>({method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.scanner_id))}/variants/`,})