: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): run variant analysis now and keep it from inventing differences (#113569)
Kim Svatos Dugan78e684445b09
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1f258613b535..ca0a7e52a03d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -13079,25 +13079,25 @@ snapshots:scenes-app-replay-vision--classifier-overview--light:hash: v1.k794b7964.d783f97810e725be92a984582c6b85339167bdeacf4dbdfe05c47212aa9c9c75.RMVo1BoCfKz55txBT9FgJ2pldYxWqQlqT-zmXPop2KEscenes-app-replay-vision--experiment-variants--dark:- hash: v1.k794b7964.72b706db719241e2c0d28e2a02a6fcb4a7be5dcdab09f88c3598aa70e6cb9e91.xoEYSou4heBzLBWHqzVcv9A9WlleZhQxpRiOwU4JL7s+ hash: v1.k794b7964.fdd4adf30d177da572195bd1b9e9d0c14e352c6673851f25f8a020270c50e08f.6WesLWYfxfVHjS8EmBHUzdkoSYACQdRj1VauuiONc6oscenes-app-replay-vision--experiment-variants--light:- hash: v1.k794b7964.265a587c624797e974a38dbabf74ba7dbedbe533d952b484a63f0ee6c0218a59.brxtW69oKk1UOscm5yTMwu2t4XqcQYp_M5cAp21mdVU+ hash: v1.k794b7964.54f70409e31c258b7b5c87762d95e48305fb2c9eedb53cb66f66638954ed3d37.D8C7Mv45o4G6oMAP1ie7XL5VyrSZS-Rp5HAttMyctCkscenes-app-replay-vision--experiment-variants-first-run-pending--dark:hash: v1.k794b7964.c57caf08e3df0e866dd24940b2cf9daeeb5aa5b70b1db79823f51c355a79b7b3.-lpN27ZP_-tT5GMGL4CHm5kOTiPOPBJHIjbgLWDhMyoscenes-app-replay-vision--experiment-variants-first-run-pending--light:hash: v1.k794b7964.35370afc30dde56a3bd42b3bd7867fafa4b40d1333ee5616cfb6c5787e1ab9f9.26leUuMz__caJ78lI3xaZRh5ZY1QIHQ1WvLsgxJEplgscenes-app-replay-vision--experiment-variants-narrow--dark:- hash: v1.k794b7964.13c49e60bc6cc79445eef7be2e5ea8ef314402274a6a291337226c15e40552ed.HAC77bIjaOMOoLMRN6YWf5q3wU7dDl6V3aDmgAZcTYU+ hash: v1.k794b7964.79774af2f046ec2ad24af9dc84de51e0d974f47a6c7b3cf652e9d6efde5d41a0.KEIv1cO8XYVKJJC1x5HKej3lsiobYR9VSfgQ4ukH1qcscenes-app-replay-vision--experiment-variants-narrow--light:- hash: v1.k794b7964.d9b0d4963eec714e16f057dfce9da13967974d4f900a882c4514c0f0c4053300.cGii9EDM-C2IiXcOO7y6aWPa4ey12Fe-DopaDhYsnMs+ hash: v1.k794b7964.6cc4ae50773b2d621e7661da3369384a1b654a7910e3fa79c5fc997297458689.8ingz1F0pMoykzXNWNcM34U2krZP0tSu_dXyv8GU8hEscenes-app-replay-vision--experiment-variants-no-scout--dark:hash: v1.k794b7964.a8f0a51439fee34a91831b134240afc0d9839254d83c8fea9757f1b6c7c12a36.DX9DFGPNfnL6HGYWKpcHKP8TTYuLTpP4QWhhKUhiF0Uscenes-app-replay-vision--experiment-variants-no-scout--light:hash: v1.k794b7964.5a89953d1d09a9ecefa4138a8bdb3e1a39944849b6280eec875391963d2ab0d4.AGZHAbYj7jJB7zQutEqrFxOntxz5fyOlnDeVKCI76mIscenes-app-replay-vision--experiment-variants-three-variants--dark:- hash: v1.k794b7964.3a46d1be73932a767101335f2aa8962256f0209e7d4f20ac040e5d37e3f1e757.4XaHTLpO3eNIe6PbsJU89RNYNIPpel0Hx3OxP0k7lpc+ hash: v1.k794b7964.cc5fe44c667cf4abd075c85ffd4abb30fe1cbe25fb864d0d911adf38eb5454a4.JwgI3f2PycZRTynYIENc5_2YGd3H0C25Ae041eMSSBMscenes-app-replay-vision--experiment-variants-three-variants--light:- hash: v1.k794b7964.ba095eb635c4246983dbbc471b0973fbd042f9daad6a970f4d66d78bb6dc020d.UxdaUdzmSBJrAOH1g5VQmT1HOxLt6b8cvMaSdx2CSZc+ hash: v1.k794b7964.8cbb752b1138dfb4cf524efd77ab70d6e1eb880520afa3b48676094a035bffb6.l4XCzOvaamzOeRJD7SHa_nYTY1U0jKPHjBI3-beG6Icscenes-app-replay-vision--experiment-variants-waiting-for-observations--dark:hash: v1.k794b7964.0056b7d379418048419e1af4fe26b3dedb57db977d907a994c35dfbb961c85c6.LZbOuzh4Jc8rJ_fNBfvGocKs0Cx7bOqjXlQ8F_XFJa8scenes-app-replay-vision--experiment-variants-waiting-for-observations--light:diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex 2437d557a9b4..536f30b5b7f8 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -2115,12 +2115,29 @@ export const ObservationDetailTimeline: StoryObj = {},}+// The experiment scanner's variant analysis scout, so the Variants tab offers Run now.+const variantAnalysisScoutMocks = mswDecorator({+ get: {+ '/api/projects/:team_id/signals/scout/configs/': [+ {+ ...digestScoutConfig,+ id: '00000000-0000-0000-0000-0000000000c9',+ skill_name: 'signals-scout-post-exposure-friction-variant-analysis',+ display_name: 'Post-exposure friction / variant analysis',+ description: 'Compares what users in each experiment variant do.',+ source_id: experimentScanner.id,+ tags: ['replay-vision-variant-analysis'],+ },+ ],+ },+})+export const ExperimentVariants: StoryObj = {parameters: {pageUrl: urls.replayVision(experimentScanner.id),featureFlags: { [FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]: true },},- decorators: [variantsDecorator(variantsReadout())],+ decorators: [variantsDecorator(variantsReadout()), variantAnalysisScoutMocks],}// No variant analysis scout yet: the counts show, and the comparison offers to set one up.@@ -2139,6 +2156,7 @@ export const ExperimentVariantsFirstRunPending: StoryObj = {},decorators: [variantsDecorator(withoutAnalysis(variantsReadout({ analysis: { ...readyAnalysis, recorded_at: null } }))),+ variantAnalysisScoutMocks,],}diff --git a/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsx b/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsxindex b05ce4c9e696..d0689a10b97f 100644--- a/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsx@@ -5,6 +5,14 @@ import { TZLabel } from 'lib/components/TZLabel'import type { ExperimentVariantsReadoutApi } from '../../../generated/api.schemas'import type { VariantComparisonState } from '../../scannerVariantsLogic'+export interface VariantAnalysisRunNow {+ onClick: () => void+ /** The request to start a run is in flight. */+ loading: boolean+ running: boolean+ disabledReason: string | null+}+export interface VariantDifferencesCardProps {readout: ExperimentVariantsReadoutApicomparisonState: VariantComparisonState@@ -13,6 +21,8 @@ export interface VariantDifferencesCardProps {onSetUp: () => void/** Opens the existing variant analysis scout; undefined when it isn't loaded. */onOpenScout?: () => void+ /** Starts the variant analysis scout now; undefined when there is no scout. */+ runNow?: VariantAnalysisRunNow}/** The comparison between variants, which the variant analysis scout records once a day. */@@ -22,6 +32,7 @@ export function VariantDifferencesCard({setupDisabledReason,onSetUp,onOpenScout,+ runNow,}: VariantDifferencesCardProps): JSX.Element {const scoutPaused = readout.analysis?.scout_enabled === falseconst openScoutButton = onOpenScout ? (@@ -29,6 +40,19 @@ export function VariantDifferencesCard({Open scout</LemonButton>) : null+ const runNowButton = runNow ? (+ <LemonButton+ type="secondary"+ size="small"+ onClick={runNow.onClick}+ loading={runNow.loading}+ disabledReason={runNow.disabledReason ?? undefined}+ tooltip="Run variant analysis now instead of waiting for its next scheduled run. You can run it once an hour."+ data-attr="vision-variants-run-analysis"+ >+ {runNow.running ? 'Running…' : 'Run now'}+ </LemonButton>+ ) : nullif (comparisonState === 'no_scout') {return (@@ -63,7 +87,10 @@ export function VariantDifferencesCard({: 'The scanner changed since the last analysis, so the comparison updates after the next run.'}</p></div>- {openScoutButton}+ <div className="flex items-center gap-2">+ {runNowButton}+ {openScoutButton}+ </div></LemonCard>)}@@ -82,13 +109,16 @@ export function VariantDifferencesCard({Variant analysis is paused, so this comparison doesn't update.</LemonBanner>)}- <div className="flex flex-wrap items-baseline justify-between gap-2">+ <div className="flex flex-wrap items-center 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 className="flex items-center gap-2">+ {readout.analysis?.recorded_at && (+ <span className="text-xs text-muted">+ Updated <TZLabel time={readout.analysis.recorded_at} />+ </span>+ )}+ {runNowButton}+ </div></div><div className="flex flex-col gap-4 @3xl:flex-row">{differences.length > 0 ? (diff --git a/products/replay_vision/frontend/replay_scanners/components/variants/VariantsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/variants/VariantsTab.tsxindex d1a697f24776..a0d2ec8dfffa 100644--- a/products/replay_vision/frontend/replay_scanners/components/variants/VariantsTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/variants/VariantsTab.tsx@@ -13,6 +13,7 @@ import { scannerScoutLogic } from '../../scannerScoutLogic'import {UNATTRIBUTED_VARIANT,scannerVariantsLogic,+ variantAnalysisRunDisabledReason,variantComparisonState,variantObservationsUrl,} from '../../scannerVariantsLogic'@@ -30,11 +31,12 @@ 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 { scoutConfigsForScanner, createTemplateKey, settingsSkillName, rollups } = useValues(scoutLogic)const { openCreateModal, openScoutSettings } = useActions(scoutLogic)const logic = scannerVariantsLogic({ scannerId })- const { readout, readoutLoading, readoutFailed, variantColors } = useValues(logic)- const { loadReadout, setupAnalysisClicked, variantObservationsOpened } = useActions(logic)+ const { readout, readoutLoading, readoutFailed, variantColors, analysisRunStarting, analysisRunInFlight, now } =+ useValues(logic)+ const { loadReadout, setupAnalysisClicked, variantObservationsOpened, runAnalysisNow } = useActions(logic)if (!readout) {if (readoutFailed && !readoutLoading) {@@ -63,6 +65,22 @@ export function VariantsTab({ scannerId }: VariantsTabProps): JSX.Element {: readout.analysis?.scout_enabled === false || existingScout?.enabled === false? 'Variant analysis is paused. Turn it on in the scout settings above to see themes here.': null+ const analysisRollup = existingScout ? rollups.get(existingScout.skill_name) : undefined+ const runNow = existingScout+ ? {+ onClick: () => runAnalysisNow(existingScout.id, existingScout.skill_name),+ loading: analysisRunStarting,+ running: analysisRunInFlight,+ disabledReason:+ getReplayVisionEditDisabledReason(scanner?.user_access_level) ??+ variantAnalysisRunDisabledReason({+ running: analysisRunInFlight,+ lastRunStartedAt: analysisRollup?.latestRun?.started_at ?? null,+ hasObservations: readout.window.total_observations > 0,+ now,+ }),+ }+ : undefinedreturn (<div className="@container flex flex-col gap-4" data-attr="vision-variants-tab">@@ -76,6 +94,7 @@ export function VariantsTab({ scannerId }: VariantsTabProps): JSX.Element {openCreateModal('variant-analysis')}}onOpenScout={existingScout ? () => openScoutSettings(existingScout.skill_name) : undefined}+ runNow={runNow}/>{/* Each watched variant gets a card from the start; the readout lists none only when theexperiment can't be read, for example after it was deleted. */}diff --git a/products/replay_vision/frontend/replay_scanners/scannerScout.ts b/products/replay_vision/frontend/replay_scanners/scannerScout.tsindex c69a14fa19e3..934cc65ca96b 100644--- a/products/replay_vision/frontend/replay_scanners/scannerScout.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerScout.ts@@ -413,24 +413,29 @@ function variantAnalysisTemplate(scannerId: string, scannerName: string): Scannecron: SCANNER_SCOUT_CRON,body: buildScoutBody(scannerId, {heading: 'Replay Vision variant analysis',- role: 'You compare the variants of the experiment one Replay Vision experiment scanner watches. Read its session summaries variant by variant, name the behaviors they share, and report what users in each variant do differently.',- reads: `- \`vision-scanners-get\` with id \`${scannerId}\` gives \`scanner_version\`. Read only observations of that version: a prompt edit changes what a summary looks at, so mixing versions compares two different questions.+ role: 'You compare the variants of the experiment one Replay Vision experiment scanner watches. Read its session summaries variant by variant, name the behaviors they share, and report whether users in each variant behave differently. Many experiments change behavior too little to see in a few dozen sessions, so "no clear difference" is an acceptable and expected outcome, not a failed run.',+ reads: `- \`vision-scanners-get\` with id \`${scannerId}\` gives \`scanner_version\`, and \`scanner_config.experiment_id\`. Read only observations of that version: a prompt edit changes what a summary looks at, so mixing versions compares two different questions.+- \`experiment-get\` with that \`experiment_id\` gives the experiment's hypothesis (its \`description\`) and the definitions of its \`metrics\`, \`metrics_secondary\` and \`saved_metrics\`. Use them only to learn which behaviors the team cares about. Do not read the experiment's results with \`experiment-results\` or any other results tool, and ignore \`conclusion\` and \`conclusion_comment\`. A metric can move for reasons no replay shows, and knowing a result makes it easy to find a story that fits it.- \`vision-scanners-variants-list\` (scanner_id \`${scannerId}\`) gives the variant keys, each variant's observation and people counts, and its sampling rate. Those live counts are the trusted numbers: never restate them from your own reading.- \`vision-scanners-observations-list\` (scanner_id \`${scannerId}\`) with \`variant\` set to each key, \`status=succeeded\` and \`order_by=-completed_at\`: up to the 40 most recent summaries per variant. Read the same number from each variant where you can, so their shares compare. \`vision-observations-get\` reads one in full when its summary line is not enough.`,- notable: `Name the themes first, across all variants at once, so a theme means the same thing in every variant: one observable behavior each ("Reopens the pricing page before checking out"). Then count, per variant, how many of the summaries you read show each theme.+ notable: `Name the themes first, across all variants at once, so a theme means the same thing in every variant: one observable behavior each ("Reopens the pricing page before checking out"). Prefer behaviors that the hypothesis and the metrics point at. Then count, per variant, how many of the summaries you read show each theme.-A difference is a theme whose share differs between variants by enough to matter on the summaries you read. With 40 summaries a variant, a gap of a few sessions is noise.`,- quiet: 'Variants that behave the same is a real result. Say so in the report, and record no differences.',+A difference is a theme whose share differs between variants by at least 20 percentage points (for example 14 of 40 against 6 of 40), and that you can see in the summaries themselves. A smaller gap on a few dozen summaries is noise. Your counts come from model-written summaries, so they are approximate: when you are not sure a difference is real, leave it out. Finding no difference is an acceptable result.`,+ quiet: 'Variants that behave the same is a real and expected result. Say so in the report, describe the themes all variants share, and record no differences.',+ quietVerdict:+ 'When no theme clears the bar, still file the report: open with the verdict `No clear difference between variants`, then one line with how many summaries you read per variant, then the main themes all variants share.',skip: `- Restating the variants counts as findings: the variants view already shows them.-- A difference resting on fewer than 5 sessions in either variant.-- Claims about which variant wins. The experiment's metrics decide that; you describe what users do.`,+- A difference resting on fewer than 5 sessions in the variant where the theme is more common. A theme seen in 7 sessions of one variant and none of another can still be a difference.+- Effects too small to see in a few dozen sessions, such as a 1 to 2% change in watch time or conversion. Only the experiment's metrics can show those, across thousands of sessions.+- Claims about which variant wins. The experiment's metrics decide that; you describe what users do.+- Explaining, confirming, or predicting a metric result.`,priority: 'Priority P3 by default.',record: `Every run also records exactly one structured record with \`scout-record-output\`: the whole comparison, matching the schema in your instructions. It fills in the experiment's variants view in Replay Vision, so record it even when nothing differs.- \`scanner_version\`: the version you read from \`vision-scanners-get\`. A record for an older version is not shown.- \`observations_read\`: per variant key, how many summaries you read. Every count below is out of this number.- \`variants\`: per variant key, up to 5 themes, most common first. \`count\` is how many of that variant's summaries you read show the theme. Cite up to 2 observation ids of that variant that show it in \`example_observation_ids\`.-- \`differences\`: up to 5, most meaningful first, each resting on one theme, with \`counts\` per variant key. Empty when the variants behave the same.+- \`differences\`: up to 5, most meaningful first, each resting on one theme, with \`counts\` per variant key. Empty when no theme clears the bar.- Use the same \`theme\` label in every variant and in \`differences\`, so the view can line them up.- Submit once per run. The newest record replaces the previous one in the view.`,}),diff --git a/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.test.tsindex 38f131773446..c9397c9b76a7 100644--- a/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.test.ts@@ -4,10 +4,14 @@ import posthog from 'posthog-js'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { scoutFleetLogic } from 'products/signals/frontend/inbox/logics/scoutFleetLogic'+import type { SignalScoutRunSummary } from 'products/signals/frontend/inbox/types'+import type { ExperimentVariantsReadoutApi, VariantsAnalysisStateApi } from '../generated/api.schemas'import {UNATTRIBUTED_VARIANT,scannerVariantsLogic,+ variantAnalysisRunDisabledReason,variantComparisonState,variantFilterOptions,variantObservationsUrl,@@ -31,6 +35,47 @@ const readout: ExperimentVariantsReadoutApi = {analysis: null,}+const ANALYSIS_SKILL = 'signals-scout-checkout-variant-analysis'++const analysisRun = (status: string): SignalScoutRunSummary =>+ ({+ run_id: 'run-1',+ skill_name: ANALYSIS_SKILL,+ status,+ created_at: new Date().toISOString(),+ started_at: new Date().toISOString(),+ completed_at: null,+ }) as SignalScoutRunSummary++const analysisScoutConfig = {+ id: 'config-1',+ skill_name: ANALYSIS_SKILL,+ tags: ['replay-vision-variant-analysis'],+ source_product: 'replay_vision',+ source_id: 'scanner-1',+ enabled: true,+}++const refreshedReadout: ExperimentVariantsReadoutApi = {+ ...readout,+ window: { ...readout.window, total_observations: 9 },+}++const runNowMocks = (runResponse: [number, Record<string, unknown>]): Parameters<typeof useMocks>[0] => {+ let readoutLoads = 0+ return {+ get: {+ '/api/projects/:team/vision/scanners/:id/variants/': () => [+ 200,+ readoutLoads++ === 0 ? readout : refreshedReadout,+ ],+ '/api/projects/:team/signals/scout/configs/': () => [200, [analysisScoutConfig]],+ '/api/projects/:team/signals/scout/runs/recent-per-scout/': () => [200, []],+ },+ post: { '/api/projects/:team/signals/scout/configs/:id/run/': () => runResponse },+ }+}+describe('scannerVariantsLogic', () => {it.each([['no scout', null, false, 'no_scout'],@@ -66,6 +111,77 @@ describe('scannerVariantsLogic', () => {expect(variantFilterOptions(['control', 'test'], current).map((option) => option.value)).toEqual(expected)})+ // Run now must stay off for an hour after any run starts, scheduled or manual, so repeated clicks+ // can't stack runs, and must open again once the hour has passed.+ it.each([+ ['a run in progress', { running: true }, /^Variant analysis is running/],+ ['no observations yet', { hasObservations: false }, /^There are no observations to compare yet\.$/],+ ['a run 10 minutes ago', { lastRunStartedAt: '2026-10-07T11:50:00Z' }, /run it again in 50\s+minutes\.$/],+ ['a run just under an hour ago', { lastRunStartedAt: '2026-10-07T11:00:30Z' }, /run it again in 1\s+minute\.$/],+ ['a run over an hour ago', { lastRunStartedAt: '2026-10-07T10:59:00Z' }, /^enabled$/],+ ['no earlier run', {}, /^enabled$/],+ ])('with %s, Run now is disabled for the right reason', (_name, overrides, expected) => {+ const reason = variantAnalysisRunDisabledReason({+ running: false,+ lastRunStartedAt: null,+ hasObservations: true,+ now: new Date('2026-10-07T12:00:00Z').getTime(),+ ...overrides,+ })++ expect(reason ?? 'enabled').toMatch(expected)+ })++ // The comparison must refresh once the scout's run is done, and not while it is queued or running,+ // whether this tab or the schedule started it. Otherwise the tab keeps showing the old analysis.+ it.each([+ [+ 'a run this tab started',+ async (logic: ReturnType<typeof scannerVariantsLogic>): Promise<void> => {+ await expectLogic(logic, () => logic.actions.runAnalysisNow('config-1', ANALYSIS_SKILL))+ .toDispatchActions(['analysisRunStarted'])+ .toFinishAllListeners()+ },+ ],+ ['a run started elsewhere', async (): Promise<void> => {}],+ ])('reloads the comparison when %s finishes', async (_name, startRun) => {+ useMocks(runNowMocks([202, { skill_name: ANALYSIS_SKILL, workflow_id: 'wf-1', started: true }]))+ initKeaTests()+ const logic = scannerVariantsLogic({ scannerId: 'scanner-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadReadoutSuccess']).toFinishAllListeners()+ await expectLogic(scoutFleetLogic).toDispatchActions(['loadScoutConfigsSuccess']).toFinishAllListeners()+ await startRun(logic)++ for (const status of ['queued', 'in_progress']) {+ await expectLogic(logic, () => scoutFleetLogic.actions.loadScoutRunsSuccess([analysisRun(status)]))+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['loadReadout'])+ }+ await expectLogic(logic, () =>+ scoutFleetLogic.actions.loadScoutRunsSuccess([analysisRun('completed')])+ ).toDispatchActions(['loadReadout', 'loadReadoutSuccess'])++ expect(logic.values).toMatchObject({ readout: refreshedReadout, analysisRunInFlight: false })+ logic.unmount()+ })++ // A refused start (a run in progress, a limit reached) must not leave the button on "Running…".+ it('stops waiting when the run start is refused', async () => {+ useMocks(runNowMocks([409, { detail: 'A run for this scout is already in progress.' }]))+ initKeaTests()+ const logic = scannerVariantsLogic({ scannerId: 'scanner-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadReadoutSuccess']).toFinishAllListeners()++ await expectLogic(logic, () => logic.actions.runAnalysisNow('config-1', ANALYSIS_SKILL))+ .toDispatchActions(['analysisRunSettled'])+ .toNotHaveDispatchedActions(['analysisRunStarted'])++ expect(logic.values).toMatchObject({ analysisRunRequest: null, analysisRunStarting: false })+ logic.unmount()+ })+it('reports one tab view per mount, not one per reload', async () => {useMocks({ get: { '/api/projects/:team/vision/scanners/:id/variants/': () => [200, readout] } })initKeaTests()diff --git a/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.tsindex 9caf499eed52..44474910d503 100644--- a/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerVariantsLogic.ts@@ -1,12 +1,19 @@-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, 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 { lemonToast } from 'lib/lemon-ui/LemonToast'+import { pluralize } from 'lib/utils/strings'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { signalsScoutConfigRun } from 'products/signals/frontend/generated/api'+import { scoutFleetLogic } from 'products/signals/frontend/inbox/logics/scoutFleetLogic'+import { type ScoutRollup, normalizeRunStatus } from 'products/signals/frontend/inbox/utils/scoutRunsWindow'++import type { SignalScoutConfig } from '../../../signals/frontend/inbox/logics/scoutFleetLogic'import { visionScannersVariantsList } from '../generated/api'import {type ExperimentVariantsReadoutApi,@@ -14,6 +21,7 @@ import {type VariantsAnalysisStateApi,} from '../generated/api.schemas'import { ReplayScannerTab } from './replayScannerSceneLogic'+import { isScannerScoutConfig, variantAnalysisScout } from './scannerScout'/** The observations list's value for observations with no resolved variant. */export const UNATTRIBUTED_VARIANT = '__unattributed__'@@ -69,12 +77,62 @@ export function variantFilterOptions(]}+/** The shortest time between two variant analysis runs that the Variants tab starts. */+export const VARIANT_ANALYSIS_RUN_COOLDOWN_MS = 60 * 60 * 1000+const ANALYSIS_RUN_POLL_MS = 30 * 1000+// Moves the Run now cooldown forward while the tab stays open with nothing else re-rendering it.+const CLOCK_TICK_MS = 30 * 1000+// A scout run stops at about 16 minutes, so a run still going after this is not watched any longer.+const ANALYSIS_RUN_WATCH_MS = 30 * 60 * 1000+// The run's start time comes from the server clock.+const CLOCK_SKEW_MS = 60 * 1000++/** Why the Variants tab can't start a variant analysis run now, or null when it can. */+export function variantAnalysisRunDisabledReason({+ running,+ lastRunStartedAt,+ hasObservations,+ now,+}: {+ running: boolean+ lastRunStartedAt: string | null+ hasObservations: boolean+ now: number+}): string | null {+ if (running) {+ return 'Variant analysis is running. The comparison updates when it finishes.'+ }+ if (!hasObservations) {+ return 'There are no observations to compare yet.'+ }+ if (lastRunStartedAt) {+ const elapsed = now - new Date(lastRunStartedAt).getTime()+ if (elapsed < VARIANT_ANALYSIS_RUN_COOLDOWN_MS) {+ const minutesLeft = Math.ceil((VARIANT_ANALYSIS_RUN_COOLDOWN_MS - elapsed) / 60_000)+ return `Variant analysis ran in the last hour. You can run it again in ${pluralize(minutesLeft, 'minute')}.`+ }+ }+ return null+}++export interface VariantAnalysisRunRequest {+ skillName: string+ requestedAt: number+}+export interface ScannerVariantsLogicProps {scannerId: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scannerVariantsLogicValues {+ rollups: Map<string, ScoutRollup> // scoutFleetLogic+ scoutConfigs: SignalScoutConfig[] | null // scoutFleetLogic+ analysisRunInFlight: boolean+ analysisRunRequest: VariantAnalysisRunRequest | null+ analysisRunStarting: boolean+ analysisSkillName: string | null+ now: numberreadout: ExperimentVariantsReadoutApi | nullreadoutFailed: booleanreadoutLoading: boolean@@ -83,6 +141,33 @@ export interface scannerVariantsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scannerVariantsLogicActions {+ loadScoutConfigsSuccess: (+ scoutConfigs: import('products/signals/frontend/generated/api.schemas').SignalScoutConfigApi[] | null,+ payload?: void | undefined+ ) => {+ payload?: void | undefined+ scoutConfigs: import('products/signals/frontend/generated/api.schemas').SignalScoutConfigApi[] | null+ } // scoutFleetLogic+ loadScoutRuns: (_?: void | undefined) => void // scoutFleetLogic+ loadScoutRunsSuccess: (+ scoutRuns: import('products/signals/frontend/inbox/types').SignalScoutRunSummary[],+ payload?: void | undefined+ ) => {+ payload?: void | undefined+ scoutRuns: import('products/signals/frontend/inbox/types').SignalScoutRunSummary[]+ } // scoutFleetLogic+ analysisRunSettled: () => {+ value: true+ }+ analysisRunStarted: (request: VariantAnalysisRunRequest) => {+ request: VariantAnalysisRunRequest+ }+ checkAnalysisRun: () => {+ value: true+ }+ clockTick: () => {+ value: true+ }loadReadout: () => anyloadReadoutFailure: (error: string,@@ -98,6 +183,14 @@ export interface scannerVariantsLogicActions {readout: ExperimentVariantsReadoutApipayload?: any}+ runAnalysisNow: (+ configId: string,+ skillName: string+ ) => {+ configId: string+ requestedAt: number+ skillName: string+ }setupAnalysisClicked: () => {value: true}@@ -110,6 +203,14 @@ export interface scannerVariantsLogicActions {export interface scannerVariantsLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ analysisSkillName: (+ scoutConfigs: import('products/signals/frontend/generated/api.schemas').SignalScoutConfigApi[] | null+ ) => string | null+ analysisRunInFlight: (+ rollups: Map<string, ScoutRollup>,+ analysisSkillName: string | null,+ analysisRunRequest: VariantAnalysisRunRequest | null+ ) => booleanvariantColors: (readout: ExperimentVariantsReadoutApi | null) => Record<string, string>}}@@ -127,9 +228,19 @@ export const scannerVariantsLogic = kea<scannerVariantsLogicType>([props({} as ScannerVariantsLogicProps),key((props) => props.scannerId),+ connect(() => ({+ values: [scoutFleetLogic, ['rollups', 'scoutConfigs']],+ actions: [scoutFleetLogic, ['loadScoutRuns', 'loadScoutRunsSuccess', 'loadScoutConfigsSuccess']],+ })),+actions({setupAnalysisClicked: true,variantObservationsOpened: (variantKey: string) => ({ variantKey }),+ runAnalysisNow: (configId: string, skillName: string) => ({ configId, skillName, requestedAt: Date.now() }),+ analysisRunStarted: (request: VariantAnalysisRunRequest) => ({ request }),+ analysisRunSettled: true,+ checkAnalysisRun: true,+ clockTick: true,}),loaders(({ props }) => ({@@ -142,11 +253,46 @@ export const scannerVariantsLogic = kea<scannerVariantsLogicType>([],})),- reducers({+ reducers(() => ({+ now: [Date.now(), { clockTick: () => Date.now() }],readoutFailed: [false, { loadReadout: () => false, loadReadoutFailure: () => true }],- }),+ analysisRunStarting: [+ false,+ { runAnalysisNow: () => true, analysisRunStarted: () => false, analysisRunSettled: () => false },+ ],+ // The run this tab started and still waits for. Its run row only appears once the run begins.+ analysisRunRequest: [+ null as VariantAnalysisRunRequest | null,+ { analysisRunStarted: (_, { request }) => request, analysisRunSettled: () => null },+ ],+ })),- selectors({+ selectors(({ props }) => ({+ analysisSkillName: [+ (s) => [s.scoutConfigs],+ (+ scoutConfigs: import('products/signals/frontend/generated/api.schemas').SignalScoutConfigApi[] | null+ ): string | null =>+ variantAnalysisScout(+ (scoutConfigs ?? []).filter((config) => isScannerScoutConfig(config, props.scannerId))+ )?.skill_name ?? null,+ ],+ // A run this tab asked for, or a run of the scout queued or in progress, wherever it was started.+ analysisRunInFlight: [+ (s) => [s.rollups, s.analysisSkillName, s.analysisRunRequest],+ (+ rollups: Map<string, ScoutRollup>,+ analysisSkillName: string | null,+ analysisRunRequest: VariantAnalysisRunRequest | null+ ): boolean => {+ if (analysisRunRequest) {+ return true+ }+ const run = analysisSkillName ? rollups.get(analysisSkillName)?.latestRun : null+ const status = run ? normalizeRunStatus(run.status) : null+ return status === 'running' || status === 'queued'+ },+ ],// Series colors in the readout's variant order, the same palette the experiment results use.variantColors: [(s) => [s.readout],@@ -155,34 +301,116 @@ export const scannerVariantsLogic = kea<scannerVariantsLogicType>([(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', {+ listeners(({ props, cache, actions, values }) => {+ const pollAnalysisRuns = (): void => {+ cache.disposables.add(() => {+ const interval = window.setInterval(() => actions.loadScoutRuns(), ANALYSIS_RUN_POLL_MS)+ return () => window.clearInterval(interval)+ }, 'analysisRunPoll')+ }+ // Settling also clears the starting state, so only a request this tab made is settled.+ const stopWatching = (): void => {+ if (values.analysisRunRequest) {+ actions.analysisRunSettled()+ } else {+ cache.disposables.dispose('analysisRunPoll')+ }+ }+ return {+ runAnalysisNow: async ({ configId, skillName, requestedAt }) => {+ posthog.capture('replay_vision_variant_analysis_run_now_clicked', { scanner_id: props.scannerId })+ try {+ await signalsScoutConfigRun(String(teamLogic.values.currentTeamId), configId)+ } catch (error: any) {+ // The endpoint refuses on purpose when a run is in progress or a limit is reached, and says why.+ lemonToast.error(error?.detail || 'Could not start variant analysis. Try again later.')+ actions.analysisRunSettled()+ return+ }+ actions.analysisRunStarted({ skillName, requestedAt })+ lemonToast.success('Variant analysis started. The comparison updates when it finishes.')+ actions.loadScoutRuns()+ pollAnalysisRuns()+ },+ loadScoutRunsSuccess: () => actions.checkAnalysisRun(),+ loadScoutConfigsSuccess: () => actions.checkAnalysisRun(),+ // Watches the scout's latest run, whether this tab or the schedule started it, and reloads the+ // comparison when a run it saw in flight finishes.+ checkAnalysisRun: () => {+ const request = values.analysisRunRequest+ const skillName = request?.skillName ?? values.analysisSkillName+ if (!skillName) {+ return+ }+ const run = values.rollups.get(skillName)?.latestRun ?? null+ const status = run ? normalizeRunStatus(run.status) : null+ const inFlight = status === 'running' || status === 'queued'+ const isRequestedRun =+ !!request &&+ !!run?.started_at &&+ new Date(run.started_at).getTime() >= request.requestedAt - CLOCK_SKEW_MS+ const waiting = inFlight || (!!request && !isRequestedRun)+ if (waiting) {+ const since =+ inFlight && run?.started_at ? new Date(run.started_at).getTime() : request?.requestedAt+ if (since !== undefined && Date.now() - since > ANALYSIS_RUN_WATCH_MS) {+ stopWatching()+ return+ }+ if (inFlight && run) {+ cache.watchedRunId = run.run_id+ }+ pollAnalysisRuns()+ return+ }+ const finishedWatchedRun = !!run && run.run_id === cache.watchedRunId+ cache.watchedRunId = null+ stopWatching()+ if (isRequestedRun && status === 'failed') {+ lemonToast.error("Variant analysis didn't finish. Open the scout to see what happened.")+ }+ if (isRequestedRun || finishedWatchedRun) {+ actions.loadReadout()+ }+ },+ analysisRunSettled: () => {+ cache.disposables.dispose('analysisRunPoll')+ },+ // 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,- 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,+ variant: variantKey === UNATTRIBUTED_VARIANT ? 'unattributed' : 'variant',})- }- },- 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 }) => {+ afterMount(({ actions, cache }) => {actions.loadReadout()+ actions.clockTick()+ cache.disposables.add(() => {+ const interval = window.setInterval(() => actions.clockTick(), CLOCK_TICK_MS)+ return () => window.clearInterval(interval)+ }, 'clockTick')+ // The scout's runs may have loaded before this tab opened, with a run already in progress.+ actions.checkAnalysisRun()}),])