: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): nudge frequent replay watchers to create an AI scanner (#83418)
Arno Hillen778518d68b72
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5bef6f5caf13..0a273c46169c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5424,6 +5424,10 @@ snapshots:hash: v1.k794b7964.2ba8b5789dc4e6732085d5c3e9b4434011dfd0f50c9b9bf20101273d65e6ee7d.vbjff-vvIJ5OC55myq8StIReDxV12WsR2hkQyMFeHmkreplay-tabs-home-success--second-recording-in-list--light:hash: v1.k794b7964.3a8372e58168132be7cc904fd0b41f6758930206eb5c51fb50f3a067f19398fc.HToJJ6kF0cytmkWxhkwCEtjSN0YxsJV7p8OtC9qShv0+ replay-vision-analysis-nudge--default--dark:+ hash: v1.k794b7964.e21450a1b2054a36fab2a183fd4485190e7161c07830a04008b734f83ecabb1c.Hj2ygumZlfd2zAIz7tC6m7XoM-G15hY_amDmI_m-cJo+ replay-vision-analysis-nudge--default--light:+ hash: v1.k794b7964.7eff340ad050dbd7cf07813207e989e33fccb29ef9767e38f89d16b1d567017c.Kr8YaJd8YlDg3tPWTMYWt4vAxTb_HKQuhGUe4IKACDUscenes-app-ai-observability-clustercard--default--dark:hash: v1.k794b7964.745c8ac41b251f329b890d56d7b07fb31b4939a440a40eea7932f1081d3de702.ESnQVAOfySBfRJWfJsURYu-prgU3EUvQZCD62MyLlX4scenes-app-ai-observability-clustercard--default--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 0020c686dcc8..162173d330dd 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -475,6 +475,7 @@ export const FEATURE_FLAGS = {REPLAY_PLAYLIST_SURFACING_SCORE: 'replay-playlist-surfacing-score', // owner: #team-replayREPLAY_TRIGGERS_V2: 'replay-triggers-v2', // owner: #team-replayREPLAY_UI_REDESIGN_2026: 'replay-ui-redesign-2026', // owner: #team-replay, New UI layout for replay+ REPLAY_VISION_ANALYSIS_NUDGE: 'replay-vision-analysis-nudge', // owner: #team-replay, in-player nudge offering an AI-drafted scanner after analyzing several recordingsREPLAY_VISION_EMPTY_STATE_EXPERIMENT: 'replay-vision-empty-state-experiment', // owner: #team-replay multivariate=control,templates,example-observationsREPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT: 'replay-vision-model-tier-naming-experiment', // owner: #team-replay multivariate=control,test,lite-standard-proREPLAY_VISION_SEND_REASONING: 'replay-vision-send-reasoning', // owner: #team-replay, gates the "include reasoning" checkbox on scanner alertsdiff --git a/frontend/src/lib/posthog-typed.ts b/frontend/src/lib/posthog-typed.tsindex a0764d472910..18ff52bbcd95 100644--- a/frontend/src/lib/posthog-typed.ts+++ b/frontend/src/lib/posthog-typed.ts@@ -3212,6 +3212,16 @@ interface EventSchemas {'renewal pipeline closed won': Record<string, any>'renewal pipeline onboarding': Record<string, any>'renewal pipeline onboarding complete': Record<string, any>+ 'replay vision analysis nudge dismissed': {+ analyzed_count?: number+ }+ 'replay vision analysis nudge shown': {+ analyzed_count?: number+ }+ 'replay vision analysis nudge submitted': {+ analyzed_count?: number+ goal_length?: number+ }'replayer error swallowed': Record<string, any>'report ingestion third party plugin installed': Record<string, any>'resource access level updated': Record<string, any>diff --git a/frontend/src/scenes/session-recordings/player/SessionRecordingPlayer.tsx b/frontend/src/scenes/session-recordings/player/SessionRecordingPlayer.tsxindex d872c4ef261a..b3c593fc6293 100644--- a/frontend/src/scenes/session-recordings/player/SessionRecordingPlayer.tsx+++ b/frontend/src/scenes/session-recordings/player/SessionRecordingPlayer.tsx@@ -6,6 +6,7 @@ import { useRef } from 'react'import { MatchingEventsMatchType } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'+import { AnalysisNudge } from 'products/replay_vision/frontend/components/AnalysisNudge'import { ObservationsDock } from 'products/replay_vision/frontend/components/ObservationsDock'import { visionSurfaceShown } from 'products/replay_vision/frontend/utils/visionSurface'@@ -103,9 +104,14 @@ function SessionRecordingPlayerInternal({'SessionRecordingPlayerWrapper--stacked-vertically': withSidebar && sidebarOpen && isVerticallyStacked,})}>- <div className="flex flex-col flex-1 min-w-0 min-h-0">+ <div className="relative flex flex-col flex-1 min-w-0 min-h-0"><PurePlayer noMeta={noMeta} noBorder={noBorder} />- {visionSurfaceShown(logicProps) && <ObservationsDock />}+ {visionSurfaceShown(logicProps) && (+ <>+ <ObservationsDock />+ <AnalysisNudge />+ </>+ )}</div>{withSidebar && <PlayerSidebar />}</div>diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.tsindex 54eb33e2cd81..5667038fe251 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts@@ -17,6 +17,8 @@ import { urls } from 'scenes/urls'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { ExporterFormat, RecordingSegment, RecordingSnapshot } from '~/types'+import { analysisNudgeLogic } from 'products/replay_vision/frontend/logics/analysisNudgeLogic'+import { deletedRecordingsLogic } from '../deletedRecordingsLogic'import { sessionRecordingEventUsageLogic } from '../sessionRecordingEventUsageLogic'import {@@ -334,11 +336,18 @@ describe('sessionRecordingPlayerLogic', () => {logic.unmount()logic = sessionRecordingPlayerLogic({ sessionRecordingId: '2', playerKey: 'test', autoPlay: true })logic.mount()+ const nudgeLogic = analysisNudgeLogic.build()+ nudgeLogic.mount()silenceKeaLoadersErrors()await expectLogic(logic).toDispatchActions([logic.actionTypes.setPlay, logic.actionTypes.markViewed])+ // The analyzed mark also feeds the replay vision analysis nudge counter.+ await expectLogic(nudgeLogic).toDispatchActions(['recordingAnalyzed'])+ expect(nudgeLogic.values.analyzedRecordingIds).toContain('2')++ nudgeLogic.unmount()resumeKeaLoadersErrors()})diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex 9016f023e103..3657c87deaaa 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -55,6 +55,7 @@ import { userLogic } from 'scenes/userLogic'import { AvailableFeature, ExporterFormat, RecordingSegment, SessionPlayerData, SessionPlayerState } from '~/types'+import { analysisNudgeLogic } from 'products/replay_vision/frontend/logics/analysisNudgeLogic'import {MAX_REPLAY_IFRAME_HTML_CHARS,ReplayIframeData,@@ -2629,6 +2630,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(analyzed: true,player_metadata: values.sessionPlayerMetaData,})+ analysisNudgeLogic.findMounted()?.actions.recordingAnalyzed(props.sessionRecordingId)},setPause: () => {actions.stopAnimation()diff --git a/products/replay_vision/frontend/components/AnalysisNudge.stories.tsx b/products/replay_vision/frontend/components/AnalysisNudge.stories.tsxnew file mode 100644index 000000000000..f84362232b7d--- /dev/null+++ b/products/replay_vision/frontend/components/AnalysisNudge.stories.tsx@@ -0,0 +1,77 @@+import type { Decorator, Meta, StoryObj } from '@storybook/react'+import { useMountedLogic } from 'kea'+import { useEffect, useRef } from 'react'++import { FEATURE_FLAGS } from 'lib/constants'++import { mswDecorator } from '~/mocks/browser'+import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { ANALYSIS_NUDGE_THRESHOLD, analysisNudgeLogic } from '../logics/analysisNudgeLogic'+import { AnalysisNudge } from './AnalysisNudge'++// The nudge hides without scanner editor access; grant it on the storybook app context before+// the story mounts and restore the original on unmount so story order can't leak. Persisted+// suppressions are cleared here too, before the logic's persisted reducers read them on mount.+const grantScannerAccess: Decorator = function GrantScannerAccess(Story): JSX.Element {+ const appContext = (window as any).POSTHOG_APP_CONTEXT+ const original = useRef<{ value: unknown }>()+ if (appContext && !original.current) {+ original.current = { value: appContext.resource_access_control }+ appContext.resource_access_control = {+ ...appContext.resource_access_control,+ [AccessControlResourceType.ReplayScanner]: AccessControlLevel.Editor,+ [AccessControlResourceType.SessionRecording]: AccessControlLevel.Editor,+ }+ localStorage.removeItem('products.replay_vision.frontend.logics.analysisNudgeLogic.suppressed')+ localStorage.removeItem('products.replay_vision.frontend.logics.analysisNudgeLogic.lastShownAt')+ }+ useEffect(+ () => () => {+ if (appContext && original.current) {+ appContext.resource_access_control = original.current.value+ }+ },+ [appContext]+ )+ return <Story />+}++const meta: Meta<typeof AnalysisNudge> = {+ title: 'Replay Vision/Analysis nudge',+ component: AnalysisNudge,+ decorators: [+ grantScannerAccess,+ // The nudge only shows for teams without scanners, checked against this endpoint.+ mswDecorator({+ get: {+ '/api/projects/:team_id/vision/scanners/': { count: 0, next: null, previous: null, results: [] },+ },+ }),+ ],+ parameters: {+ featureFlags: { [FEATURE_FLAGS.REPLAY_VISION_ANALYSIS_NUDGE]: true },+ },+}+export default meta++function PrimedNudge(): JSX.Element {+ const logic = useMountedLogic(analysisNudgeLogic)+ useEffect(() => {+ for (let i = 0; i < ANALYSIS_NUDGE_THRESHOLD; i++) {+ logic.actions.recordingAnalyzed(`story-recording-${i}`)+ }+ }, [logic])+ return (+ // Stands in for the player area the card overlays in the app. An explicit width matters:+ // the card is absolutely positioned, so without one the wrapper collapses to its borders+ // and the visual-regression snapshot captures a 2px sliver instead of the card.+ <div className="relative h-80 w-160 border rounded">+ <AnalysisNudge />+ </div>+ )+}++export const Default: StoryObj = {+ render: () => <PrimedNudge />,+}diff --git a/products/replay_vision/frontend/components/AnalysisNudge.tsx b/products/replay_vision/frontend/components/AnalysisNudge.tsxnew file mode 100644index 000000000000..78e5e04bcd57--- /dev/null+++ b/products/replay_vision/frontend/components/AnalysisNudge.tsx@@ -0,0 +1,109 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconSparkles, IconX } from '@posthog/icons'+import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'++import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'+import { urls } from 'scenes/urls'++import { analysisNudgeLogic } from '../logics/analysisNudgeLogic'+import { consumeGoalDraftIntent, markGoalDraftIntent } from '../replay_scanners/goalDraftIntent'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'++/** Card overlaying the player once the user has analyzed a few recordings this session:+ * collects what they're looking for and hands it to the scanner creation wizard's AI draft. */+export function AnalysisNudge(): JSX.Element | null {+ const { nudgeVisible, goalInput } = useValues(analysisNudgeLogic)+ const { dismissNudge, setGoalInput, submitGoal } = useActions(analysisNudgeLogic)+ const { dataProcessingAccepted } = useValues(aiConsentLogic)+ // The exact goal that initiated the consent ask; approving submits this, not the live input,+ // so edits made while the popover is open can't be sent unvalidated (or blank).+ const [pendingConsentGoal, setPendingConsentGoal] = useState<string | null>(null)++ // Creating a scanner needs editor access, so users who couldn't finish the flow never see it.+ if (!nudgeVisible || getReplayVisionEditDisabledReason()) {+ return null+ }++ const handleSubmit = (): void => {+ const goal = goalInput.trim()+ if (!goal) {+ return+ }+ if (dataProcessingAccepted) {+ submitGoal(goal)+ } else {+ // Stored before the consent ask: approving can trigger a full-page SSO reauth that+ // unloads before onApprove runs, and on return the wizard (pendingRedirectUrl below)+ // picks the goal up from the hand-off instead of losing it.+ markGoalDraftIntent(goal)+ setPendingConsentGoal(goal)+ }+ }++ return (+ <div+ className="absolute bottom-16 right-4 z-10 w-80 rounded-lg border bg-bg-light shadow-md p-3 flex flex-col gap-2"+ data-attr="vision-analysis-nudge"+ >+ <div className="flex items-center gap-1.5">+ <IconSparkles className="text-ai size-4" />+ <span className="font-semibold text-sm flex-1">Looking for something specific?</span>+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ onClick={dismissNudge}+ tooltip="Dismiss"+ data-attr="vision-analysis-nudge-dismiss"+ />+ </div>+ <p className="text-xs text-secondary mb-0">+ Tell PostHog AI what you're looking for and it'll set up a scanner that watches every new recording for+ it.+ </p>+ <LemonTextArea+ value={goalInput}+ onChange={setGoalInput}+ onPressEnter={handleSubmit}+ placeholder="e.g., Find sessions where users get stuck during onboarding"+ minRows={2}+ maxRows={4}+ data-attr="vision-analysis-nudge-input"+ />+ <AIConsentPopoverWrapper+ placement="top"+ showArrow+ ignoreDismissal+ hideTrainingDisclaimer+ hidden={pendingConsentGoal === null}+ pendingRedirectUrl={urls.replayVisionTemplates()}+ onApprove={() => {+ if (pendingConsentGoal) {+ submitGoal(pendingConsentGoal)+ }+ setPendingConsentGoal(null)+ }}+ onDismiss={() => {+ // Disarm the hand-off so a later wizard visit can't auto-start a draft the+ // user backed out of.+ consumeGoalDraftIntent()+ setPendingConsentGoal(null)+ }}+ >+ <LemonButton+ type="primary"+ size="small"+ fullWidth+ center+ onClick={handleSubmit}+ disabledReason={!goalInput.trim() ? 'Describe what the scanner should look for' : undefined}+ data-attr="vision-analysis-nudge-submit"+ >+ Create a scanner with AI+ </LemonButton>+ </AIConsentPopoverWrapper>+ </div>+ )+}diff --git a/products/replay_vision/frontend/logics/analysisNudgeLogic.test.ts b/products/replay_vision/frontend/logics/analysisNudgeLogic.test.tsnew file mode 100644index 000000000000..49200d15a0c6--- /dev/null+++ b/products/replay_vision/frontend/logics/analysisNudgeLogic.test.ts@@ -0,0 +1,131 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { consumeGoalDraftIntent } from '../replay_scanners/goalDraftIntent'+import { ANALYSIS_NUDGE_THRESHOLD, analysisNudgeLogic } from './analysisNudgeLogic'++describe('analysisNudgeLogic', () => {+ let logic: ReturnType<typeof analysisNudgeLogic.build>+ let scannersSpy: jest.Mock++ const setFlagEnabled = (enabled: boolean): void => {+ featureFlagLogic.actions.setFeatureFlags(+ enabled ? [FEATURE_FLAGS.REPLAY_VISION_ANALYSIS_NUDGE] : [],+ enabled ? { [FEATURE_FLAGS.REPLAY_VISION_ANALYSIS_NUDGE]: true } : {}+ )+ }++ beforeEach(() => {+ // The suppression reducers persist to localStorage and the goal hand-off to+ // sessionStorage; isolate tests from each other.+ localStorage.clear()+ sessionStorage.clear()+ // Access control fails closed, and the shown capture is gated on scanner editor access.+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: {+ [AccessControlResourceType.ReplayScanner]: AccessControlLevel.Editor,+ [AccessControlResourceType.SessionRecording]: AccessControlLevel.Editor,+ },+ } as any+ scannersSpy = jest.fn(() => [200, { count: 0, next: null, previous: null, results: [] }])+ useMocks({ get: { '/api/projects/:team/vision/scanners/': scannersSpy } })+ initKeaTests()+ teamLogic.mount()+ featureFlagLogic.mount()+ setFlagEnabled(true)+ logic = analysisNudgeLogic.build()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ const analyzeUpToThreshold = (): void => {+ for (let i = 0; i < ANALYSIS_NUDGE_THRESHOLD; i++) {+ logic.actions.recordingAnalyzed(`recording-${i}`)+ }+ }++ it('shows only after enough unique recordings, so re-watching one never triggers it', async () => {+ logic.actions.recordingAnalyzed('recording-0')+ logic.actions.recordingAnalyzed('recording-0')+ for (let i = 1; i < ANALYSIS_NUDGE_THRESHOLD - 1; i++) {+ logic.actions.recordingAnalyzed(`recording-${i}`)+ }+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.nudgeVisible).toBe(false)+ expect(scannersSpy).not.toHaveBeenCalled()++ await expectLogic(logic, () =>+ logic.actions.recordingAnalyzed(`recording-${ANALYSIS_NUDGE_THRESHOLD - 1}`)+ ).toDispatchActions(['checkTeamScannersSuccess'])+ expect(logic.values.nudgeVisible).toBe(true)+ })++ it('stays hidden past the threshold when the feature flag is off', async () => {+ setFlagEnabled(false)+ analyzeUpToThreshold()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.nudgeVisible).toBe(false)+ })++ it('stays hidden for a team already running scanners', async () => {+ scannersSpy.mockReturnValue([200, { count: 1, next: null, previous: null, results: [{ id: 'existing' }] }])+ await expectLogic(logic, analyzeUpToThreshold).toDispatchActions(['checkTeamScannersSuccess'])+ expect(logic.values.teamHasScanners).toBe(true)+ expect(logic.values.nudgeVisible).toBe(false)+ })++ it('captures shown once, not again for every further analyzed recording', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ await expectLogic(logic, analyzeUpToThreshold).toDispatchActions(['checkTeamScannersSuccess'])+ logic.actions.recordingAnalyzed('recording-extra')+ await expectLogic(logic).toFinishAllListeners()+ const shownCalls = captureSpy.mock.calls.filter((call) => call[0] === 'replay vision analysis nudge shown')+ expect(shownCalls).toHaveLength(1)+ })++ it('a shown-but-ignored nudge stays hidden on the next mount, so ignoring is not re-pitched every session', async () => {+ await expectLogic(logic, analyzeUpToThreshold).toDispatchActions(['nudgeShown'])+ expect(logic.values.nudgeVisible).toBe(true)++ logic.unmount()+ logic = analysisNudgeLogic.build()+ logic.mount()+ analyzeUpToThreshold()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.nudgeVisible).toBe(false)+ })++ it.each([+ ['dismissing', () => logic.actions.dismissNudge()],+ ['submitting', () => logic.actions.submitGoal('find rage clicks')],+ ])('%s suppresses the nudge even as more recordings are analyzed', async (_name, act) => {+ analyzeUpToThreshold()+ act()+ logic.actions.recordingAnalyzed('recording-after')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.suppressed).toBe(true)+ expect(logic.values.nudgeVisible).toBe(false)+ })++ it('submitting hands the goal to the creation wizard via sessionStorage, never the URL', () => {+ analyzeUpToThreshold()+ logic.actions.submitGoal('find rage clicks in checkout')+ expect(router.values.location.pathname).toContain(urls.replayVisionTemplates())+ expect(router.values.searchParams.goal).toBeUndefined()+ expect(consumeGoalDraftIntent()).toEqual('find rage clicks in checkout')+ })+})diff --git a/products/replay_vision/frontend/logics/analysisNudgeLogic.ts b/products/replay_vision/frontend/logics/analysisNudgeLogic.tsnew file mode 100644index 000000000000..7821068b35d6--- /dev/null+++ b/products/replay_vision/frontend/logics/analysisNudgeLogic.ts@@ -0,0 +1,265 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ connect,+ kea,+ listeners,+ path,+ reducers,+ selectors,+ sharedListeners,+} from 'kea'+import type { BreakPointFunction } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import posthog from 'lib/posthog-typed'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'+import { visionScannersList } from '../generated/api'+import { markGoalDraftIntent } from '../replay_scanners/goalDraftIntent'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'++export const ANALYSIS_NUDGE_THRESHOLD = 5++/** How long a shown-but-ignored nudge stays quiet. Dismissal and submission suppress forever;+ * ignoring is softer, so it re-pitches eventually rather than every qualifying session. */+export const IGNORED_NUDGE_COOLDOWN_MS = 30 * 24 * 60 * 60 * 1000++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface analysisNudgeLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ analyzedRecordingIds: string[]+ cooldownActive: boolean+ goalInput: string+ lastShownAt: number | null+ nudgeVisible: boolean+ suppressed: boolean+ teamHasScanners: boolean | null+ teamHasScannersLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface analysisNudgeLogicActions {+ checkTeamScanners: () => any+ checkTeamScannersFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ checkTeamScannersSuccess: (+ teamHasScanners: boolean | null,+ payload?: any+ ) => {+ teamHasScanners: boolean | null+ payload?: any+ }+ dismissNudge: () => {+ value: true+ }+ nudgeShown: () => {+ shownAt: number+ }+ recordingAnalyzed: (sessionRecordingId: string) => {+ sessionRecordingId: string+ }+ setCooldownActive: (active: boolean) => {+ active: boolean+ }+ setGoalInput: (goal: string) => {+ goal: string+ }+ submitGoal: (goal: string) => {+ goal: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface analysisNudgeLogicMeta {+ sharedListeners: {+ reportShownIfVisible: (+ payload: any,+ breakpoint: BreakPointFunction,+ action: {+ type: string+ payload: any+ },+ previousState: any+ ) => void | Promise<void>+ }+ __keaTypeGenInternalSelectorTypes: {+ nudgeVisible: (+ analyzedRecordingIds: string[],+ suppressed: boolean,+ cooldownActive: boolean,+ teamHasScanners: boolean | null,+ featureFlags: FeatureFlagsSet+ ) => boolean+ }+}++export type analysisNudgeLogicType = MakeLogicType<+ analysisNudgeLogicValues,+ analysisNudgeLogicActions,+ Record<string, any>,+ analysisNudgeLogicMeta+>++/** After a user analyzes a few recordings in one browser session, offers to turn what they're+ * looking for into a Replay Vision scanner via the AI goal-draft flow on the creation wizard. */+export const analysisNudgeLogic = kea<analysisNudgeLogicType>([+ path(['products', 'replay_vision', 'frontend', 'logics', 'analysisNudgeLogic']),+ connect(() => ({ values: [featureFlagLogic, ['featureFlags']] })),+ actions({+ recordingAnalyzed: (sessionRecordingId: string) => ({ sessionRecordingId }),+ dismissNudge: true,+ nudgeShown: () => ({ shownAt: Date.now() }),+ setCooldownActive: (active: boolean) => ({ active }),+ setGoalInput: (goal: string) => ({ goal }),+ submitGoal: (goal: string) => ({ goal }),+ }),+ loaders({+ // A team already running scanners doesn't need the pitch. Null means "not checked yet"+ // and keeps the nudge hidden, so an API failure can never pitch such a team.+ teamHasScanners: [+ null as boolean | null,+ {+ checkTeamScanners: async () => {+ const teamId = teamLogic.findMounted()?.values.currentTeamId+ if (!teamId) {+ return null+ }+ try {+ const response = await visionScannersList(String(teamId), { limit: 1 })+ return (response.results ?? []).length > 0+ } catch {+ return null+ }+ },+ },+ ],+ }),+ reducers({+ // Unique ids so re-watching one recording doesn't count as hunting through several.+ analyzedRecordingIds: [+ [] as string[],+ {+ recordingAnalyzed: (state, { sessionRecordingId }) =>+ state.includes(sessionRecordingId) ? state : [...state, sessionRecordingId],+ },+ ],+ // Persisted so neither a dismissal nor a submission ever nags the same browser again.+ suppressed: [+ false,+ { persist: true },+ {+ dismissNudge: () => true,+ submitGoal: () => true,+ },+ ],+ // Persisted so a shown-but-ignored nudge counts against the cooldown across sessions.+ lastShownAt: [+ null as number | null,+ { persist: true },+ {+ nudgeShown: (_, { shownAt }) => shownAt,+ },+ ],+ // The cooldown is evaluated once at mount: recording a sighting mid-session must not+ // hide the card the user is currently reading.+ cooldownActive: [+ false,+ {+ setCooldownActive: (_, { active }) => active,+ },+ ],+ goalInput: ['', { setGoalInput: (_, { goal }) => goal }],+ }),+ selectors({+ nudgeVisible: [+ (s) => [s.analyzedRecordingIds, s.suppressed, s.cooldownActive, s.teamHasScanners, s.featureFlags],+ (+ analyzedRecordingIds: string[],+ suppressed: boolean,+ cooldownActive: boolean,+ teamHasScanners: boolean | null,+ featureFlags: Record<string, boolean | string | undefined>+ ): boolean => {+ // Reading the flags proxy reports exposure, so the read stays behind the other+ // guards: exposure has to cover exactly the users who qualified for the nudge.+ if (suppressed || cooldownActive || analyzedRecordingIds.length < ANALYSIS_NUDGE_THRESHOLD) {+ return false+ }+ // Strict false so both "team already runs scanners" and "not known yet" hide it.+ if (teamHasScanners !== false) {+ return false+ }+ return !!featureFlags[FEATURE_FLAGS.REPLAY_VISION_ANALYSIS_NUDGE]+ },+ ],+ }),+ sharedListeners(({ actions, cache, values }) => ({+ // Fires from both paths that can flip nudgeVisible to true: the analyzed count crossing+ // the threshold, and the async scanners check resolving after it.+ reportShownIfVisible: () => {+ // Mirrors the component's render guards so "shown" only fires when the card rendered.+ if (!values.nudgeVisible || cache.shownReported || getReplayVisionEditDisabledReason()) {+ return+ }+ cache.shownReported = true+ actions.nudgeShown()+ posthog.capture('replay vision analysis nudge shown', {+ analyzed_count: values.analyzedRecordingIds.length,+ })+ },+ })),+ listeners(({ actions, values, sharedListeners }) => ({+ recordingAnalyzed: [+ () => {+ // Checked lazily, only once a viewer qualifies, so plain replay watching never+ // fetches the scanner list.+ if (+ values.teamHasScanners === null &&+ !values.teamHasScannersLoading &&+ !values.suppressed &&+ !values.cooldownActive &&+ values.analyzedRecordingIds.length >= ANALYSIS_NUDGE_THRESHOLD+ ) {+ actions.checkTeamScanners()+ }+ },+ sharedListeners.reportShownIfVisible,+ ],+ checkTeamScannersSuccess: sharedListeners.reportShownIfVisible,+ dismissNudge: () => {+ posthog.capture('replay vision analysis nudge dismissed', {+ analyzed_count: values.analyzedRecordingIds.length,+ })+ },+ submitGoal: ({ goal }) => {+ posthog.capture('replay vision analysis nudge submitted', {+ analyzed_count: values.analyzedRecordingIds.length,+ goal_length: goal.length,+ })+ // The goal travels via the sessionStorage hand-off, never the URL: it is free text+ // that can contain customer emails or names, and a query param would land in+ // autocapture's $current_url, our own replay, and browser history. The wizard+ // consumes it on mount, prefills the AI box, and starts the draft, so all creation+ // gates (consent, estimate, quota) stay in force.+ markGoalDraftIntent(goal)+ router.actions.push(urls.replayVisionTemplates())+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.lastShownAt !== null && Date.now() - values.lastShownAt < IGNORED_NUDGE_COOLDOWN_MS) {+ actions.setCooldownActive(true)+ }+ }),+])diff --git a/products/replay_vision/frontend/replay_scanners/goalDraftIntent.ts b/products/replay_vision/frontend/replay_scanners/goalDraftIntent.tsnew file mode 100644index 000000000000..f76c765886bb--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/goalDraftIntent.ts@@ -0,0 +1,27 @@+const GOAL_DRAFT_INTENT_KEY = 'replay-vision.goal-draft-intent'++/** One-shot hand-off of the in-player analysis nudge's goal to the creation wizard. The goal is+ * free text that can contain customer emails or names, so it travels via sessionStorage rather+ * than the URL, keeping it out of autocapture's $current_url, our own replay of our app, and+ * browser history. Only this channel auto-starts the AI draft, so a crafted external ?goal= link+ * can prefill the goal box but never spend the user's AI allowance on its own. */+export function markGoalDraftIntent(goal: string): void {+ try {+ sessionStorage.setItem(GOAL_DRAFT_INTENT_KEY, goal)+ } catch {+ // Storage can be unavailable (private mode); the nudge then just opens the wizard blank.+ }+}++/** Reads and clears the hand-off. The wizard must call this on every entry, whichever prefill+ * path wins, so a hand-off can never stay armed for the rest of the tab session and auto-start+ * a draft from a later, unrelated wizard visit. */+export function consumeGoalDraftIntent(): string | null {+ try {+ const goal = sessionStorage.getItem(GOAL_DRAFT_INTENT_KEY)+ sessionStorage.removeItem(GOAL_DRAFT_INTENT_KEY)+ return goal+ } catch {+ return null+ }+}diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex fb593ed0bef8..2e0a4c85720c 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -1,3 +1,5 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'@@ -10,6 +12,7 @@ import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { parseCsvParam, parseNumericParam, parseSortParam } from '../utils/urlParams'+import { consumeGoalDraftIntent, markGoalDraftIntent } from './goalDraftIntent'import {buildObservationListParams,ObservationStatusValue,@@ -18,7 +21,7 @@ import {replayScannerLogic,shouldGuardScannerNavigation,} from './replayScannerLogic'-import { readScannerDraft } from './scannerDraft'+import { readScannerDraft, writeScannerDraft } from './scannerDraft'import { scannerEditorSceneLogic } from './scannerEditorSceneLogic'import { observationsDrilldownSearchParams } from './scannerOverviewLogic'import { defaultScannerTemplates } from './scannerTemplates'@@ -60,9 +63,10 @@ describe('replayScannerLogic', () => {'/api/projects/:team/vision/scanners/draft/': draftSpy,},})- // The draft layer persists form edits to localStorage; without a reset, one test's edits- // restore into the next test's freshly mounted wizard.+ // The draft layer persists form edits to localStorage and the nudge hand-off marker to+ // sessionStorage; without a reset, one test's state bleeds into the next.localStorage.clear()+ sessionStorage.clear()initKeaTests()logic = replayScannerLogic({ id: 'new' })logic.mount()@@ -178,6 +182,94 @@ describe('replayScannerLogic', () => {})expect(router.values.location.pathname).toEqual(pathBefore)})++ // The in-player analysis nudge hands the goal to the wizard via a one-shot sessionStorage+ // hand-off that authorizes the auto-start; the free text never travels in the URL.+ it('consumes the nudge hand-off: prefills the box and starts the draft with the goal never in the URL', async () => {+ draftSpy.mockReturnValue([+ 200,+ { name: 'Rage clicks', description: '', scanner_type: 'monitor', scanner_config: { prompt: 'x' } },+ ])+ markGoalDraftIntent('find rage clicks in checkout')+ router.actions.push(urls.replayVisionScannerTemplate('new'))++ await expectLogic(logic, () => logic.actions.loadScanner())+ .toDispatchActions([+ logic.actionCreators.setGoalDraftInput('find rage clicks in checkout'),+ 'draftScannerFromGoal',+ ])+ .toFinishAllListeners()++ expect(draftSpy).toHaveBeenCalled()+ expect(router.values.searchParams.goal).toBeUndefined()+ expect(logic.values.scanner).toMatchObject({ name: 'Rage clicks' })+ expect(router.values.location.pathname).toContain(urls.replayVisionScannerDetails('new'))+ // One-shot: the entry consumed the hand-off, so a reload cannot re-fire the draft.+ expect(consumeGoalDraftIntent()).toBeNull()+ })++ // The hand-off is consumed on every wizard entry, even when another prefill path wins,+ // so it can't stay armed for the tab session and auto-start from a later ?goal= link.+ it('an entry that takes the experiment path still consumes the hand-off, so a later ?goal= link cannot auto-start', async () => {+ useMocks({+ get: {+ '/api/projects/:team/experiments/:id/': () => [200, { id: 7, name: 'Checkout redesign' }],+ },+ })+ markGoalDraftIntent('find rage clicks in checkout')+ router.actions.push(urls.replayVisionScannerTemplate('new'), { experiment: '7' })+ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()++ router.actions.push(urls.replayVisionScannerTemplate('new'), { goal: 'find rage clicks in checkout' })+ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()++ expect(logic.values.goalDraftInput).toEqual('find rage clicks in checkout')+ expect(draftSpy).not.toHaveBeenCalled()+ })++ // Documented precedence with the ?filters= deep link (a fully built query): filters win,+ // the free-text goal is dropped, regardless of which entry point built the URL.+ it('an explicit ?filters= param outranks the goal prefill and drops it', async () => {+ markGoalDraftIntent('find rage clicks in checkout')+ router.actions.push(urls.replayVisionScannerTemplate('new'), {+ filters: JSON.stringify({ kind: 'RecordingsQuery' }),+ goal: 'find rage clicks in checkout',+ })++ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()++ expect(logic.values.goalDraftInput).toEqual('')+ expect(draftSpy).not.toHaveBeenCalled()+ })++ // A ?goal= link without the nudge's marker (e.g. crafted or shared) must not spend the+ // user's AI allowance on its own; it only prefills the box for an explicit click.+ it('a bare ?goal= param prefills the input without auto-starting the draft', async () => {+ router.actions.push(urls.replayVisionScannerTemplate('new'), { goal: 'find rage clicks in checkout' })++ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()++ expect(logic.values.goalDraftInput).toEqual('find rage clicks in checkout')+ expect(draftSpy).not.toHaveBeenCalled()+ expect(router.values.searchParams.goal).toBeUndefined()+ })++ // The drafted scanner persists over the sole saved-draft slot, so auto-starting on top of+ // a restored draft would destroy the user's saved work without any action of theirs.+ it('a nudge hand-off over a saved draft restores the draft and does not auto-start', async () => {+ writeScannerDraft(MOCK_TEAM_ID, {+ ...logic.values.scanner!,+ name: 'My saved work',+ })+ markGoalDraftIntent('find rage clicks in checkout')+ router.actions.push(urls.replayVisionScannerTemplate('new'))++ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()++ expect(logic.values.scanner).toMatchObject({ name: 'My saved work' })+ expect(logic.values.goalDraftInput).toEqual('find rage clicks in checkout')+ expect(draftSpy).not.toHaveBeenCalled()+ })})describe('setScannerType', () => {diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex c73b447184da..51577635bebe 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -72,6 +72,7 @@ import {reconcileVariantKeys,replaceExperimentExposureFilter,} from './experimentTargeting'+import { consumeGoalDraftIntent } from './goalDraftIntent'import { clearScannerDraft, readScannerDraft, writeScannerDraft } from './scannerDraft'import {SCANNER_EDITOR_STEPS,@@ -1492,10 +1493,25 @@ export const replayScannerLogic = kea<replayScannerLogicType>([!draft && urlTemplateKey && findScannerTemplate(urlTemplateKey) ? urlTemplateKey : nullconst teamName = teamLogic.findMounted()?.values.currentTeam?.nameconst experimentParams = parseExperimentScannerParams(router.values.searchParams)+ const goalParam =+ typeof router.values.searchParams.goal === 'string'+ ? router.values.searchParams.goal.trim()+ : ''+ // Consumed unconditionally on every wizard entry: whichever prefill path wins+ // below, a hand-off armed by the nudge must not stay usable for the rest of+ // the tab session, where a later ?goal= link would auto-start a draft and+ // spend the user's AI allowance without fresh intent.+ const handedOffGoal = consumeGoalDraftIntent()?.trim() ?? ''+ // Prefill precedence: an experiment deep link, then an explicit ?filters=+ // query (both carry fully built state), then a saved draft, then the+ // free-text goal. A URL carrying both ?filters= and ?goal= deterministically+ // takes the filters and drops the goal.+ const hasFiltersPrefill = 'filters' in router.values.searchParams// Strip the params the wizard has now consumed so a reload doesn't re-run the prefill// over the user's edits: an unknown template that fell back to from-scratch (a valid- // template stays), and the experiment deep-link params. One replace covers both and- // preserves the URL hash, which a second back-to-back replace would drop.+ // template stays), the experiment deep-link params, and the goal param. One replace+ // covers all of them and preserves the URL hash, which a second back-to-back replace+ // would drop.const nextParams = { ...router.values.searchParams }if (urlTemplateKey && !templateKey) {delete nextParams.template@@ -1505,6 +1521,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([delete nextParams.variantsdelete nextParams.exposure}+ if (nextParams.goal !== undefined) {+ delete nextParams.goal+ }if (Object.keys(nextParams).length !== Object.keys(router.values.searchParams).length) {router.actions.replace(router.values.location.pathname, nextParams, router.values.hashParams)}@@ -1545,6 +1564,18 @@ export const replayScannerLogic = kea<replayScannerLogicType>([} finally {cache.restoringDraft = false}+ // The goal prefills the AI box; the draft only auto-starts for the in-player+ // nudge's sessionStorage hand-off (which carries the goal so the free text+ // never enters the URL), and never over a saved draft. A crafted external+ // ?goal= link can therefore neither spend the user's AI allowance nor+ // overwrite saved work without an explicit click.+ const goal = handedOffGoal || goalParam+ if (goal && !hasFiltersPrefill) {+ actions.setGoalDraftInput(goal)+ if (handedOffGoal && !draft) {+ actions.draftScannerFromGoal(handedOffGoal)+ }+ }return}const teamId = teamLogic.values.currentTeamId