Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-vision): add scanner list empty state experiment (#82176)

coryslater7f8db534f8c2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 270ab2506fbb..c66a63620713 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7332,6 +7332,14 @@ snapshots:
hash: v1.k794b7964.caa178a1664602705ebf6fa8b39ec75575b4e7758eb4a9ff91508dd52cb529f8.039sZnGu8gSRPTpNbYNQcYPDufGfHXaHCStCeN2yxwk
scenes-app-replay-vision--scanners-list-empty--light:
hash: v1.k794b7964.b75a243ab120376ac748771433615ee48f5685affd4204f432010064405111d2.Svp0qq0wiHROHRW6E3sfxSHlCiBO84meXZm3nQhcMtA
+ scenes-app-replay-vision--scanners-list-empty-example-observations--dark:
+ hash: v1.k794b7964.7677d40ce99e90a7b2dd6d12629097eae7c118c78c59740096c5b3700b388329.eM9tjhuy8FsHtwpLsciYVtFVsOr0oFuux81gMFe1xPc
+ scenes-app-replay-vision--scanners-list-empty-example-observations--light:
+ hash: v1.k794b7964.df915fa7114df5f106758480145b2b7572269024e17c7a97ecbd4c6baf751a50.eJDQRIO1pWPRg65mXVeIWhxPZmdnw5losNMDW5ZMZpk
+ scenes-app-replay-vision--scanners-list-empty-templates--dark:
+ hash: v1.k794b7964.460d8a05336e98cada4d8c82fd4f75f1d7efeab9d2529bd521a778c744de0ed1.cc28rpByy1_1Yk2sWtVHBXsWOY9PvVGGmdl6_WpGJ98
+ scenes-app-replay-vision--scanners-list-empty-templates--light:
+ hash: v1.k794b7964.57a50554032d53c4c59b238ad1987ff588a8e6cddbab3cd5ca1458ab5fda4d6d.cjZwOeq5V-l42SMoTn4wNBEOtTJ5tWLDp2hFJ3XQEdc
scenes-app-replay-vision--startup-program-cap--dark:
hash: v1.k794b7964.99e74ef4a71dc6e8cf10969cc1f77399422c60a962fc05aa240653366fb8f48b.UadUr5iL4v6jiAz1MN-Pg27WbXsikXhNEq_GHX5pNKk
scenes-app-replay-vision--startup-program-cap--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 913b6ac2aff8..87fd5dbac484 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-replay
REPLAY_TRIGGERS_V2: 'replay-triggers-v2', // owner: #team-replay
REPLAY_UI_REDESIGN_2026: 'replay-ui-redesign-2026', // owner: #team-replay, New UI layout for replay
+ REPLAY_VISION_EMPTY_STATE_EXPERIMENT: 'replay-vision-empty-state-experiment', // owner: #team-replay multivariate=control,templates,example-observations
REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT: 'replay-vision-model-tier-naming-experiment', // owner: #team-replay multivariate=control,test,lite-standard-pro
REPLAY_VISION_SEND_REASONING: 'replay-vision-send-reasoning', // owner: #team-replay, gates the "include reasoning" checkbox on scanner alerts
REVAMPED_PY_NOTEBOOKS: 'revamped-py-notebooks', // owner: #team-data-tools
diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.py
index d18afcb2b87c..2158539dac1b 100644
--- a/products/replay_vision/backend/scanner_draft.py
+++ b/products/replay_vision/backend/scanner_draft.py
@@ -270,10 +270,15 @@ def draft_scanner_from_goal(
then synthesize one scanner draft. Raises DraftError on model failure.
`include_business_context` must be False for scoped-token requests: core memory's own API is
- INTERNAL (session-only), so its content must not flow out through this endpoint's response.
+ INTERNAL (session-only), and the org/project names sit behind their own read scopes, so neither
+ may flow out through this endpoint's response (the model can echo them into the draft).
"""
taxonomy = _product_taxonomy(team)
- company = " / ".join(part for part in [team.organization.name, team.project.name if team.project else ""] if part)
+ company = (
+ " / ".join(part for part in [team.organization.name, team.project.name if team.project else ""] if part)
+ if include_business_context
+ else ""
+ )
user_content = _build_user_content(
goal,
taxonomy.events,
diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.py
index d8b7c7d8591c..3260520f8b3b 100644
--- a/products/replay_vision/backend/tests/test_scanner_draft.py
+++ b/products/replay_vision/backend/tests/test_scanner_draft.py
@@ -364,9 +364,12 @@ class TestDraftScannerEndpoint(_VisionAPITestCase):
@patch(_CORE_MEMORY_FLAG_PATH, return_value=False)
@patch(_GENERATE_PATH)
def test_scoped_token_requests_exclude_business_context(self, mock_generate, _flag):
- # Core memory's own API is INTERNAL (session-only); a scoped key must not read it through here.
+ # Core memory's own API is INTERNAL (session-only), and org/project names sit behind their
+ # own read scopes; a scoped key must not recover either through the model's output.
mock_generate.return_value = _draft()
CoreMemory.objects.create(team=self.team, text="Acme sells anvils to coyotes.")
+ self.organization.name = "Acme Corp"
+ self.organization.save()
value = self._personal_api_key(["replay_scanner:write", "session_recording:read"])
resp = self.client.post(
@@ -374,7 +377,9 @@ class TestDraftScannerEndpoint(_VisionAPITestCase):
)
assert resp.status_code == status.HTTP_200_OK, resp.json()
- assert "Acme sells anvils to coyotes." not in mock_generate.call_args.kwargs["user_content"]
+ user_content = mock_generate.call_args.kwargs["user_content"]
+ assert "Acme sells anvils to coyotes." not in user_content
+ assert "Acme Corp" not in user_content
@patch(_GENERATE_PATH)
def test_scope_enforcement_for_personal_api_keys(self, mock_generate):
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index f4c411d07d3d..33687995850d 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -491,25 +491,48 @@ export default meta
export const ScannersList: StoryObj = {}
-// Zero scanners: snapshot-covers the table empty state and its docs link, which no other story renders.
+// A project that has never created a scanner: the surface of the empty-state experiment.
+const emptyProjectDecorators = [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/vision/scanners/': { count: 0, next: null, previous: null, results: [] },
+ '/api/projects/:team_id/vision/scanners/stats/': {
+ total: 0,
+ enabled: 0,
+ by_type: {
+ monitor: { enabled: 0, total: 0 },
+ classifier: { enabled: 0, total: 0 },
+ scorer: { enabled: 0, total: 0 },
+ summarizer: { enabled: 0, total: 0 },
+ },
+ } satisfies ScannerStatsResponseApi,
+ '/api/projects/:team_id/vision/scanners/creators/': { creators: [] },
+ },
+ }),
+]
+
export const ScannersListEmpty: StoryObj = {
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/vision/scanners/': { count: 0, next: null, previous: null, results: [] },
- '/api/projects/:team_id/vision/scanners/stats/': {
- total: 0,
- enabled: 0,
- by_type: {
- monitor: { enabled: 0, total: 0 },
- classifier: { enabled: 0, total: 0 },
- scorer: { enabled: 0, total: 0 },
- summarizer: { enabled: 0, total: 0 },
- },
- } satisfies ScannerStatsResponseApi,
- },
- }),
- ],
+ decorators: emptyProjectDecorators,
+}
+
+// Both arm stories run with the goal-draft flag on, matching the launch state where each arm
+// also offers the "tell PostHog AI what you want to accomplish" box.
+export const ScannersListEmptyTemplates: StoryObj = {
+ decorators: emptyProjectDecorators,
+ parameters: {
+ featureFlags: {
+ [FEATURE_FLAGS.REPLAY_VISION_EMPTY_STATE_EXPERIMENT]: 'templates',
+ },
+ },
+}
+
+export const ScannersListEmptyExampleObservations: StoryObj = {
+ decorators: emptyProjectDecorators,
+ parameters: {
+ featureFlags: {
+ [FEATURE_FLAGS.REPLAY_VISION_EMPTY_STATE_EXPERIMENT]: 'example-observations',
+ },
+ },
}
export const UsageTab: StoryObj = {
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
index 923aca186e97..1461dcb72b11 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
@@ -1,9 +1,8 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { useState } from 'react'
import * as xRayPng from '@posthog/brand/hoggies/png/x-ray'
-import { IconPencil, IconPlus, IconRefresh, IconSearch, IconTrash } from '@posthog/icons'
+import { IconPencil, IconRefresh, IconSearch, IconTrash } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
@@ -23,9 +22,8 @@ import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductI
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { SceneExport } from 'scenes/sceneTypes'
-import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
-import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
@@ -40,6 +38,8 @@ import { ScannerTypeBadge } from '../components/ScannerTypeBadge'
import { visionQuotaLogic } from '../logics/visionQuotaLogic'
import { getReplayVisionDeleteDisabledReason, getReplayVisionEditDisabledReason } from '../utils/accessControl'
import { creditsToUsd, formatCreditCount } from '../utils/credits'
+import { CreateScannerButton } from './components/CreateScannerButton'
+import { ScannerListEmptyState, computeScannerListEmptyStateVariant } from './components/ScannerListEmptyState'
import { VisionMetrics } from './components/VisionMetrics'
import { VisionUsageTab } from './components/VisionUsageTab'
import { type ScannersSorting, SCANNERS_PAGE_SIZE, replayScannersLogic } from './replayScannersLogic'
@@ -53,61 +53,6 @@ const TYPE_OPTIONS: { value: ScannerType; label: string }[] = SCANNER_TYPE_OPTIO
label,
}))
-/**
- * "Create scanner" CTA that requires the organization to have approved AI data processing first.
- * When consent is missing, clicking surfaces the AI consent popover; approving flows straight into
- * the create-scanner journey, so the empty state stays the same whether or not consent is set.
- */
-function CreateScannerButton({
- acceptedLabel,
- dataAttr,
- size = 'small',
-}: {
- acceptedLabel: string
- dataAttr: string
- size?: 'small' | 'medium'
-}): JSX.Element {
- const { dataProcessingAccepted } = useValues(aiConsentLogic)
- const { push } = useActions(router)
- const [consentRequested, setConsentRequested] = useState(false)
- const goToCreate = (): void => push(urls.replayVisionTemplates())
-
- const button = (
- <LemonButton
- type="primary"
- size={size}
- icon={<IconPlus />}
- disabledReason={getReplayVisionEditDisabledReason()}
- data-attr={dataAttr}
- onClick={() => (dataProcessingAccepted ? goToCreate() : setConsentRequested(true))}
- >
- {dataProcessingAccepted ? acceptedLabel : 'Allow AI analysis and create scanner'}
- </LemonButton>
- )
-
- if (dataProcessingAccepted) {
- return button
- }
-
- return (
- <AIConsentPopoverWrapper
- placement="bottom-end"
- showArrow
- ignoreDismissal
- hideTrainingDisclaimer
- hidden={!consentRequested}
- pendingRedirectUrl={urls.replayVisionTemplates()}
- onApprove={() => {
- setConsentRequested(false)
- goToCreate()
- }}
- onDismiss={() => setConsentRequested(false)}
- >
- {button}
- </AIConsentPopoverWrapper>
- )
-}
-
export const scene: SceneExport = {
component: ReplayScannersScene,
logic: replayScannersLogic,
@@ -139,6 +84,15 @@ export function ReplayScannersScene(): JSX.Element {
const { push } = useActions(router)
const { searchParams } = useValues(router)
const { showUsd } = useValues(visionQuotaLogic)
+ const { featureFlags, receivedFeatureFlags } = useValues(featureFlagLogic)
+
+ const emptyStateVariant = computeScannerListEmptyStateVariant({
+ onScannersTab: searchParams.tab !== 'usage',
+ receivedFeatureFlags,
+ scannerStatsLoading,
+ scannerTotal: scannerStats?.total,
+ featureFlags,
+ })
const columns: LemonTableColumns<ReplayScanner> = [
{
@@ -311,16 +265,18 @@ export function ReplayScannersScene(): JSX.Element {
</LemonBanner>
)}
- <ProductIntroduction
- productName="Replay vision"
- productKey={ProductKey.REPLAY_VISION}
- thingName="scanner"
- description="Replay vision runs scanners over your completed sessions on a schedule or on demand. Describe what you want to look for and the model watches each recording for it — categorizing sessions, scoring intent, flagging bugs, or detecting any pattern you can put into a prompt. Each result lands as a queryable event you can build insights, alerts, and cohorts on."
- secondaryDescription="Start from a template or build a fully custom scanner."
- customHog={HedgehogXRay}
- action={() => push(urls.replayVisionTemplates())}
- docsURL={visionDocsUrl()}
- />
+ {!emptyStateVariant && (
+ <ProductIntroduction
+ productName="Replay vision"
+ productKey={ProductKey.REPLAY_VISION}
+ thingName="scanner"
+ description="Replay vision runs scanners over your completed sessions on a schedule or on demand. Describe what you want to look for and the model watches each recording for it — categorizing sessions, scoring intent, flagging bugs, or detecting any pattern you can put into a prompt. Each result lands as a queryable event you can build insights, alerts, and cohorts on."
+ secondaryDescription="Start from a template or build a fully custom scanner."
+ customHog={HedgehogXRay}
+ action={() => push(urls.replayVisionTemplates())}
+ docsURL={visionDocsUrl()}
+ />
+ )}
<LemonTabs
activeKey={searchParams.tab === 'usage' ? 'usage' : 'scanners'}
@@ -333,6 +289,8 @@ export function ReplayScannersScene(): JSX.Element {
{searchParams.tab === 'usage' ? (
<VisionUsageTab />
+ ) : emptyStateVariant ? (
+ <ScannerListEmptyState variant={emptyStateVariant} />
) : (
<>
{(scannerStats?.total ?? 0) > 0 ? (
diff --git a/products/replay_vision/frontend/replay_scanners/components/CreateScannerButton.tsx b/products/replay_vision/frontend/replay_scanners/components/CreateScannerButton.tsx
new file mode 100644
index 000000000000..1954b9f53553
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/CreateScannerButton.tsx
@@ -0,0 +1,74 @@
+import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+import { useState } from 'react'
+
+import { IconPlus } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
+import { urls } from 'scenes/urls'
+
+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
+
+/**
+ * "Create scanner" CTA that requires the organization to have approved AI data processing first.
+ * When consent is missing, clicking surfaces the AI consent popover; approving flows straight into
+ * the create-scanner journey, so the empty state stays the same whether or not consent is set.
+ */
+export function CreateScannerButton({
+ acceptedLabel,
+ dataAttr,
+ size = 'small',
+ consentRequested: controlledConsentRequested,
+ onConsentRequestedChange,
+}: {
+ acceptedLabel: string
+ dataAttr: string
+ size?: 'small' | 'medium'
+ // Controlled mode, for surfaces with several AI entry points that share one consent popover slot.
+ consentRequested?: boolean
+ onConsentRequestedChange?: (requested: boolean) => void
+}): JSX.Element {
+ const { dataProcessingAccepted } = useValues(aiConsentLogic)
+ const { push } = useActions(router)
+ const [internalConsentRequested, setInternalConsentRequested] = useState(false)
+ const consentRequested = controlledConsentRequested ?? internalConsentRequested
+ const setConsentRequested = onConsentRequestedChange ?? setInternalConsentRequested
+ const goToCreate = (): void => push(urls.replayVisionTemplates())
+
+ const button = (
+ <LemonButton
+ type="primary"
+ size={size}
+ icon={<IconPlus />}
+ disabledReason={getReplayVisionEditDisabledReason()}
+ data-attr={dataAttr}
+ onClick={() => (dataProcessingAccepted ? goToCreate() : setConsentRequested(true))}
+ >
+ {dataProcessingAccepted ? acceptedLabel : 'Allow AI analysis and create scanner'}
+ </LemonButton>
+ )
+
+ if (dataProcessingAccepted) {
+ return button
+ }
+
+ return (
+ <AIConsentPopoverWrapper
+ placement="bottom-end"
+ showArrow
+ ignoreDismissal
+ hideTrainingDisclaimer
+ pendingRedirectUrl={urls.replayVisionTemplates()}
+ hidden={!consentRequested}
+ onApprove={() => {
+ setConsentRequested(false)
+ goToCreate()
+ }}
+ onDismiss={() => setConsentRequested(false)}
+ >
+ {button}
+ </AIConsentPopoverWrapper>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx
index 4c999df2461e..ecbc5a41267f 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx
@@ -7,9 +7,15 @@ import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import { replayScannerLogic } from '../replayScannerLogic'
-/** "Tell PostHog AI what you want to accomplish" box on the template step: drafts a full scanner
- * from the stated goal and drops the user into the configure step to review it. */
-export function ScannerGoalDraft(): JSX.Element {
+/** "Tell PostHog AI what you want to accomplish" box on the template step and the zero-scanner
+ * empty state: drafts a full scanner from the stated goal and drops the user into the configure
+ * step to review it. */
+export function ScannerGoalDraft({
+ gateSubmit,
+}: {
+ // Lets pre-consent surfaces interpose the AI consent popover before the draft request fires.
+ gateSubmit?: (proceed: () => void) => void
+}): JSX.Element {
const textAreaRef = useRef<HTMLTextAreaElement>(null)
const logic = replayScannerLogic({ id: 'new' })
const { goalDraftInput, goalDraftLoading } = useValues(logic)
@@ -19,8 +25,14 @@ export function ScannerGoalDraft(): JSX.Element {
const editDisabledReason = getReplayVisionEditDisabledReason()
const handleSubmit = (): void => {
- if (!editDisabledReason && goalDraftInput.trim() && !goalDraftLoading) {
- draftScannerFromGoal(goalDraftInput.trim())
+ if (editDisabledReason || !goalDraftInput.trim() || goalDraftLoading) {
+ return
+ }
+ const proceed = (): void => draftScannerFromGoal(goalDraftInput.trim())
+ if (gateSubmit) {
+ gateSubmit(proceed)
+ } else {
+ proceed()
}
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.test.ts b/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.test.ts
new file mode 100644
index 000000000000..43cfa6881c02
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.test.ts
@@ -0,0 +1,65 @@
+import {
+ type ScannerListEmptyStateVariant,
+ computeScannerListEmptyStateVariant,
+ scannerListEmptyStateVariant,
+} from './ScannerListEmptyState'
+
+describe('scannerListEmptyStateVariant', () => {
+ // The flag can serve values this build doesn't know (a new arm added before the frontend
+ // deploys, control, or a plain boolean); all of them must degrade to the control empty state,
+ // or the control arm gets contaminated.
+ it.each<[unknown, ScannerListEmptyStateVariant | null]>([
+ ['templates', 'templates'],
+ ['example-observations', 'example-observations'],
+ ['control', null],
+ ['some-future-arm', null],
+ [true, null],
+ [false, null],
+ [undefined, null],
+ ])('narrows flag value %p to variant %p', (flagValue, expected) => {
+ expect(scannerListEmptyStateVariant(flagValue)).toBe(expected)
+ })
+
+ // Reading the flag is what reports exposure, so any guarded-out render must return null
+ // WITHOUT touching the flags object; a read here logs users who never saw the empty state.
+ describe('computeScannerListEmptyStateVariant', () => {
+ const eligible = {
+ onScannersTab: true,
+ receivedFeatureFlags: true,
+ scannerStatsLoading: false,
+ scannerTotal: 0,
+ }
+ const flagsServing = (value: unknown): Record<string, unknown> => ({
+ 'replay-vision-empty-state-experiment': value,
+ })
+
+ it('returns the variant when the empty state actually shows', () => {
+ expect(computeScannerListEmptyStateVariant({ ...eligible, featureFlags: flagsServing('templates') })).toBe(
+ 'templates'
+ )
+ })
+
+ it.each<[string, Partial<typeof eligible>]>([
+ ['on the usage tab', { onScannersTab: false }],
+ ['before flags load', { receivedFeatureFlags: false }],
+ ['while stats load', { scannerStatsLoading: true }],
+ ['with stats missing', { scannerTotal: undefined }],
+ ['with existing scanners', { scannerTotal: 3 }],
+ ])('returns null without reading the flag %s', (_label, overrides) => {
+ const flagReads: string[] = []
+ const trackedFlags = new Proxy(
+ {},
+ {
+ get: (_target, prop) => {
+ flagReads.push(String(prop))
+ return 'templates'
+ },
+ }
+ )
+ expect(
+ computeScannerListEmptyStateVariant({ ...eligible, ...overrides, featureFlags: trackedFlags })
+ ).toBeNull()
+ expect(flagReads).toEqual([])
+ })
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.tsx
new file mode 100644
index 000000000000..b853e7e9e5c5
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.tsx
@@ -0,0 +1,244 @@
+import { useValues } from 'kea'
+import { useRef, useState } from 'react'
+
+import { IconOpenSidebar } from '@posthog/icons'
+import { LemonTag, Link } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
+
+import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'
+import { ScannerTemplate, defaultScannerTemplates } from '../scannerTemplates'
+import { ScannerType } from '../types'
+import { CreateScannerButton } from './CreateScannerButton'
+import { ScannerGoalDraft } from './ScannerGoalDraft'
+import { TemplateCard } from './ScannerTemplatePicker'
+
+// Test arms of the replay-vision-empty-state-experiment flag, keyed by the flag's variant key.
+// The surface is the scanner list for a project that has never created a scanner; the goal metric
+// is the backend's replay_vision_scanner_created event.
+export type ScannerListEmptyStateVariant = 'templates' | 'example-observations'
+
+const EMPTY_STATE_VARIANTS: readonly ScannerListEmptyStateVariant[] = ['templates', 'example-observations']
+
+// Narrows a raw flag value to an empty-state variant. Control, booleans, and variant keys this
+// build doesn't know yet all resolve to null (the pre-experiment empty state), so a flag/frontend
+// version skew degrades to the control experience instead of rendering a broken arm.
+export function scannerListEmptyStateVariant(flagValue: unknown): ScannerListEmptyStateVariant | null {
+ return typeof flagValue === 'string' && (EMPTY_STATE_VARIANTS as readonly string[]).includes(flagValue)
+ ? (flagValue as ScannerListEmptyStateVariant)
+ : null
+}
+
+// Accessing the flag on kea's featureFlags proxy is what reports experiment exposure, so the read
+// must stay behind every guard: exposure has to cover exactly the users who saw the empty state.
+// Usage-tab visitors, renders before flags load (a stale read would log control and stick for the
+// page view), and projects with scanners all resolve to null without touching the flag.
+export function computeScannerListEmptyStateVariant({
+ onScannersTab,
+ receivedFeatureFlags,
+ scannerStatsLoading,
+ scannerTotal,
+ featureFlags,
+}: {
+ onScannersTab: boolean
+ receivedFeatureFlags: boolean
+ scannerStatsLoading: boolean
+ scannerTotal: number | undefined
+ featureFlags: Record<string, unknown>
+}): ScannerListEmptyStateVariant | null {
+ if (!onScannersTab || !receivedFeatureFlags || scannerStatsLoading || scannerTotal !== 0) {
+ return null
+ }
+ return scannerListEmptyStateVariant(featureFlags[FEATURE_FLAGS.REPLAY_VISION_EMPTY_STATE_EXPERIMENT])
+}
+
+const DOCS_LINK = (
+ <Link
+ to="https://posthog.com/docs/replay-vision?utm_medium=in-product&utm_campaign=empty-state-docs-link"
+ target="_blank"
+ className="inline-flex items-center gap-1"
+ >
+ How scanners work <IconOpenSidebar className="w-4 h-4" />
+ </Link>
+)
+
+// The consent popover doesn't close on outside click, so the arm tracks which single AI entry
+// point requested consent; opening one closes the rest instead of stacking popovers.
+interface ConsentSlot {
+ activeGate: string | null
+ setActiveGate: (gateId: string | null) => void
+}
+
+// Unlike the picker page, this surface is reachable before the organization has approved AI data
+// processing, so every AI entry point interposes the consent popover before its draft starts.
+function ConsentGate({
+ gateId,
+ slot,
+ children,
+}: {
+ gateId: string
+ slot: ConsentSlot
+ children: (gate: (proceed: () => void) => void) => JSX.Element
+}): JSX.Element {
+ const { dataProcessingAccepted } = useValues(aiConsentLogic)
+ const pendingStart = useRef<(() => void) | null>(null)
+
+ return (
+ <AIConsentPopoverWrapper
+ placement="bottom"
+ showArrow
+ ignoreDismissal
+ hideTrainingDisclaimer
+ hidden={slot.activeGate !== gateId}
+ onApprove={() => {
+ slot.setActiveGate(null)
+ pendingStart.current?.()
+ pendingStart.current = null
+ }}
+ onDismiss={() => slot.setActiveGate(null)}
+ >
+ {children((proceed) => {
+ if (dataProcessingAccepted) {
+ proceed()
+ return
+ }
+ pendingStart.current = proceed
+ slot.setActiveGate(gateId)
+ })}
+ </AIConsentPopoverWrapper>
+ )
+}
+
+function ConsentGatedTemplateCard({
+ template,
+ slot,
+}: {
+ template: ScannerTemplate | 'blank'
+ slot: ConsentSlot
+}): JSX.Element {
+ const gateId = template === 'blank' ? 'template-blank' : `template-${template.key}`
+ return (
+ <ConsentGate gateId={gateId} slot={slot}>
+ {(gate) => <TemplateCard template={template} gateStart={gate} />}
+ </ConsentGate>
+ )
+}
+
+function GatedGoalDraft({ className, slot }: { className?: string; slot: ConsentSlot }): JSX.Element {
+ return (
+ <div className={className}>
+ <ConsentGate gateId="goal-draft" slot={slot}>
+ {(gate) => <ScannerGoalDraft gateSubmit={gate} />}
+ </ConsentGate>
+ </div>
+ )
+}
+
+function TemplatesEmptyState({ slot }: { slot: ConsentSlot }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-6 pt-2" data-attr="vision-empty-state-templates">
+ <div className="flex flex-col gap-2 text-center max-w-160 mx-auto">
+ <h2 className="mb-0">Pick your first scanner</h2>
+ <p className="text-secondary mb-0">
+ A scanner watches each new session recording and reports what it finds. Start from a template, then
+ adjust the prompt to fit your product.
+ </p>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
+ {defaultScannerTemplates.map((template) => (
+ <ConsentGatedTemplateCard key={template.key} template={template} slot={slot} />
+ ))}
+ <ConsentGatedTemplateCard template="blank" slot={slot} />
+ </div>
+ <GatedGoalDraft className="w-full max-w-160 mx-auto" slot={slot} />
+ <div className="text-center">{DOCS_LINK}</div>
+ </div>
+ )
+}
+
+interface ExampleObservation {
+ scannerType: ScannerType
+ scannerName: string
+ tag: { label: string; type: 'warning' | 'danger' } | null
+ text: string
+}
+
+// Invented results covering three of the scanner types (a score, a tag, a summary), so the
+// examples match what the create flow offers next. Static by design: an illustration, not data.
+const EXAMPLE_OBSERVATIONS: ExampleObservation[] = [
+ {
+ scannerType: 'scorer',
+ scannerName: 'Frustration score',
+ tag: { label: '7/10', type: 'warning' },
+ text: 'Clicked a disabled save button four times, reloaded the page, and re-entered the form before finishing signup.',
+ },
+ {
+ scannerType: 'classifier',
+ scannerName: 'Session outcome',
+ tag: { label: 'blocked_by_error', type: 'danger' },
+ text: 'Checkout failed twice with a card validation error. The user retried once, then left from the payment step.',
+ },
+ {
+ scannerType: 'summarizer',
+ scannerName: 'Session summary',
+ tag: null,
+ text: 'Compared the two paid plans, read the SSO docs, invited a teammate, and started a trial from the billing page.',
+ },
+]
+
+function ExampleObservationsEmptyState({ slot }: { slot: ConsentSlot }): JSX.Element {
+ return (
+ <div
+ className="flex flex-col md:flex-row gap-8 md:gap-12 pt-2 max-w-320 items-start"
+ data-attr="vision-empty-state-example-observations"
+ >
+ <div className="flex flex-col gap-4 flex-1 max-w-140">
+ <h2 className="mb-0">Create your first scanner</h2>
+ <p className="mb-0">
+ Describe what to look for in plain language. A scanner watches each new session recording for it and
+ reports a score, a tag, or a summary.
+ </p>
+ <p className="mb-0">Every result is an event you can query, graph, and alert on.</p>
+ <div className="flex items-center gap-4 flex-wrap mt-2">
+ <CreateScannerButton
+ acceptedLabel="Create your first scanner"
+ dataAttr="vision-scanner-create-empty"
+ size="medium"
+ consentRequested={slot.activeGate === 'create-button'}
+ onConsentRequestedChange={(requested) => slot.setActiveGate(requested ? 'create-button' : null)}
+ />
+ {DOCS_LINK}
+ </div>
+ <GatedGoalDraft className="mt-2" slot={slot} />
+ </div>
+ <div className="flex flex-col gap-3 flex-1 w-full max-w-160">
+ <span className="text-muted text-xs font-semibold uppercase tracking-wide">Example results</span>
+ {EXAMPLE_OBSERVATIONS.map((example) => (
+ <div
+ key={example.scannerName}
+ className="flex flex-col gap-2 bg-bg-light border border-border rounded p-4"
+ >
+ <div className="flex items-center gap-2">
+ <ScannerTypeBadge scannerType={example.scannerType} />
+ <span className="font-semibold text-sm">{example.scannerName}</span>
+ {example.tag && (
+ <LemonTag type={example.tag.type} className="ml-auto">
+ {example.tag.label}
+ </LemonTag>
+ )}
+ </div>
+ <p className="text-sm text-secondary mb-0">{example.text}</p>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
+
+export function ScannerListEmptyState({ variant }: { variant: ScannerListEmptyStateVariant }): JSX.Element {
+ const [activeGate, setActiveGate] = useState<string | null>(null)
+ const slot: ConsentSlot = { activeGate, setActiveGate }
+ return variant === 'templates' ? <TemplatesEmptyState slot={slot} /> : <ExampleObservationsEmptyState slot={slot} />
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx
index 14d0c34680bf..ecdba545cb04 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx
@@ -30,7 +30,18 @@ const TEMPLATE_ICONS: Record<ScannerTemplateIcon, JSX.Element> = {
check: <IconCheckCircle />,
}
-function TemplateCard({ template }: { template: ScannerTemplate | 'blank' }): JSX.Element {
+export function TemplateCard({
+ template,
+ gateStart,
+}: {
+ template: ScannerTemplate | 'blank'
+ /**
+ * The picker page sits behind a consent-gated entry button, but cards rendered elsewhere (the
+ * scanner list empty state) are the entry point themselves. When set, clicks hand the start
+ * flow to this gate so it can interpose the AI consent popover before any draft is touched.
+ */
+ gateStart?: (proceed: () => void) => void
+}): JSX.Element {
const isBlank = template === 'blank'
const { searchParams } = useValues(router)
const { scannerDraftSavedAt } = useValues(replayScannerLogic({ id: 'new' }))
@@ -43,16 +54,23 @@ function TemplateCard({ template }: { template: ScannerTemplate | 'blank' }): JS
}
const handleClick = (): void => {
- if (scannerDraftSavedAt === null) {
- start()
- return
+ const proceed = (): void => {
+ if (scannerDraftSavedAt === null) {
+ start()
+ return
+ }
+ LemonDialog.open({
+ title: 'Start over and lose your draft?',
+ description: 'The scanner you have in progress will be replaced by this template.',
+ primaryButton: { children: 'Start over', status: 'danger', onClick: start },
+ secondaryButton: { children: 'Keep my draft' },
+ })
+ }
+ if (gateStart) {
+ gateStart(proceed)
+ } else {
+ proceed()
}
- LemonDialog.open({
- title: 'Start over and lose your draft?',
- description: 'The scanner you have in progress will be replaced by this template.',
- primaryButton: { children: 'Start over', status: 'danger', onClick: start },
- secondaryButton: { children: 'Keep my draft' },
- })
}
return (
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index 35361e8cb50f..df30db5b9d02 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -101,7 +101,11 @@ describe('replayScannerLogic', () => {
})
describe('draftScannerFromGoal', () => {
- it('seeds the form from the AI draft and routes to the configure step', async () => {
+ // The box renders on the editor's template step and on the zero-scanner empty state.
+ it.each([
+ ['the template step', urls.replayVisionScannerTemplate('new')],
+ ['the empty scanner list', urls.replayVision()],
+ ])('seeds the form from the AI draft and routes to the configure step from %s', async (_origin, path) => {
const draft = {
name: 'User intent',
description: 'Tags each session by intent.',
@@ -110,7 +114,7 @@ describe('replayScannerLogic', () => {
rationale: 'A classifier fits because you want the mix of visit intents.',
}
draftSpy.mockReturnValue([200, draft])
- router.actions.push(urls.replayVisionScannerTemplate('new'))
+ router.actions.push(path)
logic.actions.setGoalDraftInput('understand what users come here to do')
await expectLogic(logic, () =>
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 8c40a06c16d1..d7f5dedc667e 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -1589,8 +1589,13 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
return
}
// The model call can take a while; if the user picked a template or navigated away
- // meanwhile, their newer state wins and the stale draft is dropped.
- if (!router.values.location.pathname.endsWith(urls.replayVisionScannerTemplate('new'))) {
+ // meanwhile, their newer state wins and the stale draft is dropped. The box lives on
+ // the template step and the zero-scanner empty state, so both count as still there.
+ const pathname = router.values.location.pathname
+ if (
+ !pathname.endsWith(urls.replayVisionScannerTemplate('new')) &&
+ !pathname.endsWith(urls.replayVision())
+ ) {
return
}
actions.resetScanner(newScanner())