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): replace the scanner empty state and auto-run new scanners (#84191)

Tue Haulund7218dedd23c0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 943a1e53075d..c552f223aeca 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1776,6 +1776,10 @@ snapshots:
hash: v1.k794b7964.6fb2d5feff1fa62c3ed888268602b4eb017f75d33178538542ee4a6d28072fc3.tHRCmCQubhMPmffxXOGXE0jpd1kSvcnGMay-GOjl-J0
components-product-empty-state--product-introduction--light:
hash: v1.k794b7964.80a94ce3b72b30fc78f17c3df97f60b02513da190f16b10b785ddc6410e29610.4XhHHGq7prdUMyvvHE7cOA3EgP4Ia_lrdFQCDxvt470
+ components-product-empty-state--replay-vision-needs-setup--dark:
+ hash: v1.k794b7964.2366ea7dc8a7c9adbe708bd75456157833054f1d1687f3394c06f44bce0891d6.XZGK_PpPYxHJOetNVEYOvKYdG4WoZd8hWiXLZNwOgp4
+ components-product-empty-state--replay-vision-needs-setup--light:
+ hash: v1.k794b7964.251eee6169c98d22d57c361fdcf9747e16187d832d3ce775d93ce9418b67466a.QZzU0myILKJWAjynyGeUQybg5UwVqniqT1Q1TuT-jkE
components-product-empty-state--product-tours-needs-setup--dark:
hash: v1.k794b7964.ba387f94bf7380934a79b9a58f19d27dbe5561163315728c3a2d813a747757f0.XpF43f3StaHvZq-5TpAo3Uw5ABra8ikrJrLcMaCFqlM
components-product-empty-state--product-tours-needs-setup--light:
@@ -7561,33 +7565,25 @@ snapshots:
scenes-app-replay-vision--scanner-templates--light:
hash: v1.k794b7964.1f88a5eb5ce04ca6bea3009c62f23eb09af6e2540f21ef1e1e20fb53c3b38777.XnkQTLfdifTRzsriW4EbOkCXkWBJ1WLlBhE8dPsjcEc
scenes-app-replay-vision--scanners-list--dark:
- hash: v1.k794b7964.f26ddd49023d8bd519d1b7519683f9584214fad7c572a028ccbcc94350daf5e5.AFY_giJl1OgV7nY3jGw5xsTmZT-35VA66AKv6chsNZI
+ hash: v1.k794b7964.1fcb7458a86919bea9fd523028d7a131b786f0c22c628b0e5fcf9a0ef66b9e50.-oBeHYXd34jWxw0EBxFFekkwrJGZ-OcEtxFv_th0hFM
scenes-app-replay-vision--scanners-list--light:
- hash: v1.k794b7964.c1e59f579e1d037bd2c60f9a59d470f2411337f671c9e9cd39eaf2fa164b74e8.OlFHYmRW-vflJaDiD2nl8XG1nzeDyilQGXKNCxsik9U
+ hash: v1.k794b7964.8883df4a4cbcf7ef4b13bc2544f53889f7299a8b45042df3067ed055e73f1051.gc4HOiTmXIEjTbCcamzR1jioxy-yPDKvKjF8goSgZl0
scenes-app-replay-vision--scanners-list-empty--dark:
- hash: v1.k794b7964.caa178a1664602705ebf6fa8b39ec75575b4e7758eb4a9ff91508dd52cb529f8.039sZnGu8gSRPTpNbYNQcYPDufGfHXaHCStCeN2yxwk
+ hash: v1.k794b7964.39153526f0a9155a2f64f3ee6287b9a59f5a90d2bdc7cb81089b34a01a987034.niMr9U8Em5N9iMEXBiV3tqoxpnwLrGIe-yr-zU_041w
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
+ hash: v1.k794b7964.73ae7eb6a69efdfc1d7ccee798c452f608b209cd9abddfaa25fa72aa53abc6e8.XcekA1SUZ7lNVl302KAdsFT_iqAZbqt6PENT3IbqwLI
scenes-app-replay-vision--startup-program-cap--dark:
- hash: v1.k794b7964.99e74ef4a71dc6e8cf10969cc1f77399422c60a962fc05aa240653366fb8f48b.UadUr5iL4v6jiAz1MN-Pg27WbXsikXhNEq_GHX5pNKk
+ hash: v1.k794b7964.9b2986eac51ec18989ff0a0ca0054b2d0ed08715636a80dd5c309b65f902f696.4fToQ_pJan7lDaeKmLyQzaxXpaIRYMwLRq3nlRtoNzY
scenes-app-replay-vision--startup-program-cap--light:
- hash: v1.k794b7964.4f8607a7ad5d31f814e202a7446ef97eb6ccf74455147b068d08deecdd7b3136.vxVv8hYBIj7g6ps2cBMRTCP3vLTxQcmkkhnNBIU5JnA
+ hash: v1.k794b7964.10fed0a6b6c60bb696e0e0d3cd33bf515a0d7f29447fb7e2ba8697b52a177c9a.ATNAszHN_Jo0NJowz0TGFLh3VoQMbWd-h903WlwYYtc
scenes-app-replay-vision--summarizer-overview--dark:
hash: v1.k794b7964.977399e0f1a5cdd98967d020ed15d2aa08b47ec0dbb0d36c4287ccf4e16d6bc6.L1TFIxNhtYHGbq72h1LbR4v2KvenCDxpXaStGAA4J5Q
scenes-app-replay-vision--summarizer-overview--light:
hash: v1.k794b7964.c4c10f01522dae58cfa74b31763cc511792be4e089715c3a2dc368069709903a.oNfnCNLDZrnVpzs6I9cQGdG22Hrp5C3PQ3LukYHNIE0
scenes-app-replay-vision--usage-tab--dark:
- hash: v1.k794b7964.2cbe01468a4afb2779cd3ce13961c7f12f5de30b17ff2f1745d08aca2d90d6b1.h0UIDulO8w6XzMcfmA9URttOLJ9pT7XUKlPJpBwjwTY
+ hash: v1.k794b7964.7597963aa31229871d070717ba14ab862d3a449c34cda3a6daf955bb9ed3303e.C-QVr_MQvoR9HIQ4FucF431T-QkWUVYpf9KK7bSO4L0
scenes-app-replay-vision--usage-tab--light:
- hash: v1.k794b7964.5e63ef4530beaec03140fc557480037e2dc59c0251332ea0a0f28017dbb9d8af.UgdvVrSEaZBpwSwqp-Q5BRyQNSz7pVpxIO6-86L6Uu8
+ hash: v1.k794b7964.905ddad41ffd554979e273efe3fa22a592b2ed65cf1d96ce18fdf557817e6aae.c30xFjJse9ILNiHi07sdYEbyINvpBVlVwXT6Y2m-R1k
scenes-app-saved-insights--empty-state--dark:
hash: v1.k794b7964.43545664c9133c8afd354be6a6ed8f808c35b381101325d9605114632fcdc0c9.l8w9uEOEmrH6Xl1kNd9ueRtg_51cJUSjWLdjWDM0Fko
scenes-app-saved-insights--empty-state--light:
diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
index fe56b1da94b3..5a2b4387728b 100644
--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
@@ -13,6 +13,7 @@ import { featureFlagsEmptyState } from 'products/feature_flags/frontend/emptySta
import { linksEmptyState } from 'products/links/frontend/emptyState/linksEmptyState'
import { mcpAnalyticsEmptyState } from 'products/mcp_analytics/frontend/emptyState/mcpAnalyticsEmptyState'
import { productToursEmptyState } from 'products/product_tours/frontend/emptyState/productToursEmptyState'
+import { replayVisionEmptyState } from 'products/replay_vision/frontend/emptyState/replayVisionEmptyState'
import { llmSkillsEmptyState } from 'products/skills/frontend/emptyState/llmSkillsEmptyState'
import { userInterviewsEmptyState } from 'products/user_interviews/frontend/emptyState/userInterviewsEmptyState'
@@ -142,3 +143,26 @@ export const AIObservabilityNeedsSetup: ProductEmptyStateStory = productEmptySta
aiObservabilityEmptyState,
'needs-setup'
)
+
+// Replay vision detection is binary too (a scanner is the unit of setup); its
+// detection logic polls the scanner stats endpoint, so answer it with zeros.
+export const ReplayVisionNeedsSetup: ProductEmptyStateStory = productEmptyStateStory(
+ replayVisionEmptyState,
+ 'needs-setup',
+ {
+ mocks: {
+ get: {
+ '/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 },
+ },
+ },
+ },
+ },
+ }
+)
diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx
index 29ccf5fda38e..3cf499b1bef7 100644
--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx
+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx
@@ -6,6 +6,7 @@ import { IconBook, IconGear } from '@posthog/icons'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { TerminalCard } from 'lib/components/CommandBlock/TerminalCard'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { cn } from 'lib/utils/css-classes'
import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'
import { productSetupStatusLogic } from './productSetupStatusLogic'
@@ -43,6 +44,7 @@ export function ProductEmptyState({ config, mode }: ProductEmptyStateProps): JSX
const manualUrl = config.manualSetupUrl ?? config.docsUrl
const Hedgehog = config.hedgehog
const Preview = config.Preview
+ const hedgehogBeside = config.hedgehogPlacement === 'beside'
const { primaryAction } = config
const primaryActionButton = primaryAction ? (
@@ -82,82 +84,102 @@ export function ProductEmptyState({ config, mode }: ProductEmptyStateProps): JSX
} as React.CSSProperties
}
>
- <div className="mx-auto flex w-full min-w-0 max-w-[36rem] flex-col justify-center gap-4 px-6">
- <div className="flex flex-col items-start gap-3">
- {Hedgehog ? <Hedgehog className="w-32 shrink-0" /> : null}
- <div className="inline-flex items-center gap-2.5 text-4xl font-bold [&_svg]:text-[2.25rem]">
- <span className={ACCENT_TEXT}>{config.icon}</span>
- <span>{config.productName}</span>
+ <div
+ className={cn(
+ 'mx-auto flex w-full min-w-0 justify-center gap-8 px-6',
+ hedgehogBeside ? 'max-w-[56rem] items-center' : 'max-w-[36rem]'
+ )}
+ >
+ {Hedgehog && hedgehogBeside ? <Hedgehog className="hidden w-72 shrink-0 xl:block" /> : null}
+ <div className="flex min-w-0 max-w-[36rem] flex-col justify-center gap-4">
+ <div className="flex flex-col items-start gap-3">
+ {Hedgehog && !hedgehogBeside ? <Hedgehog className="w-32 shrink-0" /> : null}
+ <div className="inline-flex items-center gap-2.5 text-4xl font-bold [&_svg]:text-[2.25rem]">
+ <span className={ACCENT_TEXT}>{config.icon}</span>
+ <span>{config.productName}</span>
+ </div>
+ </div>
+ <div className="flex flex-col gap-1">
+ <h2 className="text-xl font-semibold m-0">{text.headline}</h2>
+ <p className="text-secondary text-sm m-0">{text.lead}</p>
</div>
- </div>
- <div className="flex flex-col gap-1">
- <h2 className="text-xl font-semibold m-0">{text.headline}</h2>
- <p className="text-secondary text-sm m-0">{text.lead}</p>
- </div>
-
- {text.hint ? <div className="text-xs text-tertiary mt-2">{text.hint}</div> : null}
- {showWizard ? (
- <TerminalCard
- command={wizardCommand}
- copyLabel={`${config.productName} wizard command`}
- onCopy={() => captureClick('wizard command copied')}
- />
- ) : config.PrimaryAction ? (
- <config.PrimaryAction />
- ) : guardedPrimaryAction ? (
- guardedPrimaryAction
- ) : manualUrl ? (
- <LemonButton
- type="primary"
- to={manualUrl}
- targetBlank
- className="self-start"
- onClick={() => captureClick('manual setup clicked')}
- data-attr="product-empty-state-manual-setup"
- >
- Set up {config.productName}
- </LemonButton>
- ) : null}
-
- {config.statusIndicator ? <div className="text-xs">{config.statusIndicator}</div> : null}
-
- <div className="flex items-center gap-4">
- {showWizard && manualUrl ? (
+ {text.hint ? <div className="text-xs text-tertiary mt-2">{text.hint}</div> : null}
+
+ {showWizard ? (
+ <>
+ <TerminalCard
+ command={wizardCommand}
+ copyLabel={`${config.productName} wizard command`}
+ onCopy={() => captureClick('wizard command copied')}
+ />
+ {guardedPrimaryAction ? (
+ <>
+ <div className="flex items-center gap-3">
+ <div className="h-px flex-1 bg-border-primary" />
+ <span className="text-xs text-tertiary uppercase tracking-wide">or</span>
+ <div className="h-px flex-1 bg-border-primary" />
+ </div>
+ {guardedPrimaryAction}
+ </>
+ ) : null}
+ </>
+ ) : config.PrimaryAction ? (
+ <config.PrimaryAction />
+ ) : guardedPrimaryAction ? (
+ guardedPrimaryAction
+ ) : manualUrl ? (
<LemonButton
- type="secondary"
- icon={<IconGear />}
+ type="primary"
to={manualUrl}
targetBlank
+ className="self-start"
onClick={() => captureClick('manual setup clicked')}
data-attr="product-empty-state-manual-setup"
>
- Configure manually
- </LemonButton>
- ) : null}
- {config.docsUrl ? (
- <LemonButton
- size="xsmall"
- type="tertiary"
- icon={<IconBook />}
- to={config.docsUrl}
- targetBlank
- onClick={() => captureClick('docs clicked')}
- data-attr="product-empty-state-docs"
- >
- Read the docs
- </LemonButton>
- ) : null}
- {config.skippable !== false ? (
- <LemonButton
- size="xsmall"
- type="tertiary"
- onClick={skipEmptyState}
- data-attr="product-empty-state-skip"
- >
- Skip for now
+ Set up {config.productName}
</LemonButton>
) : null}
+
+ {config.statusIndicator ? <div className="text-xs">{config.statusIndicator}</div> : null}
+
+ <div className="flex items-center gap-4">
+ {showWizard && !primaryActionButton && manualUrl ? (
+ <LemonButton
+ type="secondary"
+ icon={<IconGear />}
+ to={manualUrl}
+ targetBlank
+ onClick={() => captureClick('manual setup clicked')}
+ data-attr="product-empty-state-manual-setup"
+ >
+ Configure manually
+ </LemonButton>
+ ) : null}
+ {config.docsUrl ? (
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ icon={<IconBook />}
+ to={config.docsUrl}
+ targetBlank
+ onClick={() => captureClick('docs clicked')}
+ data-attr="product-empty-state-docs"
+ >
+ Read the docs
+ </LemonButton>
+ ) : null}
+ {config.skippable !== false ? (
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ onClick={skipEmptyState}
+ data-attr="product-empty-state-skip"
+ >
+ Skip for now
+ </LemonButton>
+ ) : null}
+ </div>
</div>
</div>
diff --git a/frontend/src/lib/components/ProductEmptyState/previewSparkline.ts b/frontend/src/lib/components/ProductEmptyState/previewSparkline.ts
new file mode 100644
index 000000000000..3209e83cbd05
--- /dev/null
+++ b/frontend/src/lib/components/ProductEmptyState/previewSparkline.ts
@@ -0,0 +1,18 @@
+/**
+ * SVG paths for an empty-state preview sparkline over a 100x40 viewBox: the stroked line and the
+ * filled area under it. Series are hand-authored constants, so call this once at module scope.
+ */
+export function sparkPaths(series: number[]): { line: string; area: string } {
+ const width = 100
+ const height = 40
+ const pad = 3
+ const min = Math.min(...series)
+ const max = Math.max(...series)
+ const points = series.map((value, i) => {
+ const x = (i / (series.length - 1)) * width
+ const y = height - pad - ((value - min) / (max - min || 1)) * (height - 2 * pad)
+ return `${x.toFixed(1)} ${y.toFixed(1)}`
+ })
+ const line = 'M ' + points.join(' L ')
+ return { line, area: `${line} L ${width} ${height} L 0 ${height} Z` }
+}
diff --git a/frontend/src/lib/components/ProductEmptyState/types.ts b/frontend/src/lib/components/ProductEmptyState/types.ts
index 6d600b0cfa0a..9358e74058a3 100644
--- a/frontend/src/lib/components/ProductEmptyState/types.ts
+++ b/frontend/src/lib/components/ProductEmptyState/types.ts
@@ -80,10 +80,20 @@ export interface ProductEmptyStateConfig {
accentColorDark?: string
/** A `pngHoggie(...)`-wrapped hedgehog, rendered above the product name */
hedgehog?: ComponentType<{ className?: string; style?: CSSProperties }>
+ /**
+ * Where the hedgehog sits: `above` (default) is a small illustration above the
+ * product name; `beside` renders it large next to the text and install command,
+ * for wide scene-setting illustrations.
+ */
+ hedgehogPlacement?: 'above' | 'beside'
text: ProductEmptyStateTextByMode
/** Install-command CTA. Omit for creation-first products (use `primaryAction`) or self-hosted-only flows */
wizard?: ProductEmptyStateWizard
- /** Primary CTA for products set up in the UI rather than via the wizard, e.g. "Create your first flag" */
+ /**
+ * Primary CTA for products set up in the UI rather than via the wizard, e.g. "Create your first flag".
+ * With `wizard` also set, the terminal card stays the hero and this renders as a secondary button
+ * (in place of the "Configure manually" link), for products with both a terminal and an in-app path.
+ */
primaryAction?: ProductEmptyStatePrimaryAction
/**
* Rendered in the primary-action slot instead of the `primaryAction` button, for
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 3b8db5d5a012..fa7de45fae45 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -474,7 +474,6 @@ export const FEATURE_FLAGS = {
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_ANALYSIS_NUDGE: 'replay-vision-analysis-nudge', // owner: #team-replay, in-player nudge offering an AI-drafted scanner after analyzing several recordings
- 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/ai_observability/frontend/emptyState/AIObservabilityTracePreview.tsx b/products/ai_observability/frontend/emptyState/AIObservabilityTracePreview.tsx
index d463bf5fbcf1..924ba2e441d3 100644
--- a/products/ai_observability/frontend/emptyState/AIObservabilityTracePreview.tsx
+++ b/products/ai_observability/frontend/emptyState/AIObservabilityTracePreview.tsx
@@ -1,3 +1,4 @@
+import { sparkPaths } from 'lib/components/ProductEmptyState/previewSparkline'
import type { ProductEmptyStateMode } from 'lib/components/ProductEmptyState/types'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Spinner } from 'lib/lemon-ui/Spinner'
@@ -25,21 +26,7 @@ const SESSIONS: PreviewSession[] = [
// A hand-authored series for the sparkline - flat baseline with a spike at the end,
// matching the "negative sentiment spiked" alert below it.
const SPARK = [3, 4, 3, 3, 4, 3, 4, 3, 4, 6, 10, 15]
-
-function sparkPaths(): { line: string; area: string } {
- const width = 100
- const height = 40
- const pad = 3
- const min = Math.min(...SPARK)
- const max = Math.max(...SPARK)
- const points = SPARK.map((value, i) => {
- const x = (i / (SPARK.length - 1)) * width
- const y = height - pad - ((value - min) / (max - min || 1)) * (height - 2 * pad)
- return `${x.toFixed(1)} ${y.toFixed(1)}`
- })
- const line = 'M ' + points.join(' L ')
- return { line, area: `${line} L ${width} ${height} L 0 ${height} Z` }
-}
+const { line, area } = sparkPaths(SPARK)
/**
* Example-data preview for the AI observability empty state: a sessions list plus
@@ -47,8 +34,6 @@ function sparkPaths(): { line: string; area: string } {
* preview rules in the `building-product-empty-states` skill.
*/
export function AIObservabilityTracePreview({ mode }: { mode: ProductEmptyStateMode }): JSX.Element {
- const { line, area } = sparkPaths()
-
return (
<div className="flex flex-col gap-3">
<div className="rounded-md border border-primary bg-surface-primary p-3">
diff --git a/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.tsx b/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.tsx
index b7b3df2af28e..fbb0d3fa03a4 100644
--- a/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.tsx
+++ b/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.tsx
@@ -1,5 +1,6 @@
import './MCPToolCallPreview.scss'
+import { sparkPaths } from 'lib/components/ProductEmptyState/previewSparkline'
import type { ProductEmptyStateMode } from 'lib/components/ProductEmptyState/types'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Link } from 'lib/lemon-ui/Link'
@@ -47,21 +48,7 @@ const CLIENT_LOGOS = [claudeLogo, openaiLogo, cursorLogo, windsurfLogo]
// A hand-authored series for the sparkline — abstract, just enough to read as a rising trend.
const SPARK = [4, 6, 5, 7, 6, 9, 8, 10, 9, 12, 11, 14]
-
-function sparkPaths(): { line: string; area: string } {
- const width = 100
- const height = 40
- const pad = 3
- const min = Math.min(...SPARK)
- const max = Math.max(...SPARK)
- const points = SPARK.map((value, i) => {
- const x = (i / (SPARK.length - 1)) * width
- const y = height - pad - ((value - min) / (max - min || 1)) * (height - 2 * pad)
- return `${x.toFixed(1)} ${y.toFixed(1)}`
- })
- const line = 'M ' + points.join(' L ')
- return { line, area: `${line} L ${width} ${height} L 0 ${height} Z` }
-}
+const { line, area } = sparkPaths(SPARK)
/**
* Example-data preview for the MCP analytics empty state. All interaction and motion
@@ -70,7 +57,6 @@ function sparkPaths(): { line: string; area: string } {
*/
export function MCPToolCallPreview({ mode }: { mode: ProductEmptyStateMode }): JSX.Element {
const isStatic = inStorybook() || inStorybookTestRunner()
- const { line, area } = sparkPaths()
return (
<div className="flex flex-col gap-3">
diff --git a/products/replay_vision/backend/migrations/0079_replayscanner_primed_at.py b/products/replay_vision/backend/migrations/0079_replayscanner_primed_at.py
new file mode 100644
index 000000000000..4bec9bb97891
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0079_replayscanner_primed_at.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.17 on 2026-08-18 11:37
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0078_migrate_deep_sweep_watermark"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayscanner",
+ name="primed_at",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="When the one-off priming pass over recent recordings ran; null until the first sweep primes the scanner.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0080_backfill_primed_at.py b/products/replay_vision/backend/migrations/0080_backfill_primed_at.py
new file mode 100644
index 000000000000..9640b28168da
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0080_backfill_primed_at.py
@@ -0,0 +1,18 @@
+from django.db import migrations
+from django.db.models import F
+
+
+def backfill_primed_at(apps, schema_editor):
+ # Existing scanners were created before priming existed and have been swept for real; marking
+ # them primed keeps the one-off pass strictly for scanners created after this deploy. The
+ # scanner table is small (thousands of rows), so a single UPDATE is fine.
+ ReplayScanner = apps.get_model("replay_vision", "ReplayScanner")
+ ReplayScanner.objects.filter(primed_at__isnull=True).update(primed_at=F("created_at"))
+
+
+class Migration(migrations.Migration):
+ dependencies = [("replay_vision", "0079_replayscanner_primed_at")]
+
+ operations = [
+ migrations.RunPython(backfill_primed_at, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 5c78554476f0..cab4f8018ce3 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0078_migrate_deep_sweep_watermark
+0080_backfill_primed_at
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index 5a016f357b2d..a723482f40ce 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -168,6 +168,11 @@ class ReplayScanner(UUIDModel):
blank=True,
help_text="When the deep pass last started; its cadence gates on this rather than on progress, so a cut-short pass still waits out its interval.",
)
+ primed_at = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text="When the one-off priming pass over recent recordings ran; null until the first sweep primes the scanner.",
+ )
sweep_read_bytes_by_hour = models.JSONField(
null=True,
blank=True,
diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
index 8b6e00dccb1c..ec0f96033369 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -30,6 +30,9 @@ from products.replay_vision.backend.temporal.constants import (
DEEP_SWEEP_MAX_EXECUTION_SECONDS,
DEEP_SWEEP_MAX_WINDOW,
FIND_SCANNER_CANDIDATES_TIMEOUT,
+ PRIMING_LOOKBACK,
+ PRIMING_MAX_EXECUTION_SECONDS,
+ PRIMING_SCAN_SESSIONS,
SCANNER_SCHEDULE_INTERVAL,
)
from products.replay_vision.backend.temporal.decorators import track_activity
@@ -149,20 +152,35 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
activity.logger.exception("replay_vision.deep_sweep_failed", extra={"scanner_id": str(scanner.id)})
record_deep_sweep_failure()
+ # A never-swept scanner gets a one-off priming pass over the recordings that already exist, so
+ # its page has observations without waiting for new sessions to land and settle. Strictly behind
+ # the fast walk's range (bounded by the pre-advance watermark), so the two can't overlap.
+ priming_candidates: list[CandidateSession] = []
+ priming_limit = min(PRIMING_SCAN_SESSIONS, limit - len(candidates) - len(deep_candidates))
+ if scanner.primed_at is None and priming_limit > 0:
+ priming_candidates = _priming_pass(scanner, query, priming_limit)
+ # Marked on the first tick that had headroom to try, whatever the outcome: priming is
+ # one-shot, and an empty or failed pass just means the regular sweep takes it from here.
+ # A tick whose batches spent the whole in-flight budget defers priming to a later tick.
+ ReplayScanner.objects.filter(pk=scanner.pk, primed_at__isnull=True).update(primed_at=timezone.now())
+
# Sessions that repeatedly exhausted the rasterizer's whole retry envelope (the Class B
# compositor wedge) get quarantined for the counter's TTL window; each dispatch would otherwise
# burn up to an hour of shared rasterizer capacity on a render that cannot finish. The watermark
# still advances past them, so they are skipped, not retried forever.
- stuck = read_stuck_session_ids(inputs.team_id, [c.session_id for c in [*candidates, *deep_candidates]])
+ stuck = read_stuck_session_ids(
+ inputs.team_id, [c.session_id for c in [*candidates, *deep_candidates, *priming_candidates]]
+ )
if stuck:
activity.logger.warning("replay_vision.stuck_sessions_skipped %d", len(stuck))
record_sweep_outcome("stuck_sessions_skipped")
candidates = [c for c in candidates if c.session_id not in stuck]
deep_candidates = [c for c in deep_candidates if c.session_id not in stuck]
+ priming_candidates = [c for c in priming_candidates if c.session_id not in stuck]
record_sweep_outcome(
- "candidates_found" if candidates or deep_candidates else "no_candidates",
- candidates=len(candidates) + len(deep_candidates),
+ "candidates_found" if candidates or deep_candidates or priming_candidates else "no_candidates",
+ candidates=len(candidates) + len(deep_candidates) + len(priming_candidates),
)
return FindScannerCandidatesOutput(
candidates=[CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in candidates],
@@ -175,6 +193,9 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
],
deep_swept_through=deep_progress.swept_through if deep_progress else None,
deep_keyset_session_id=deep_progress.seen_session_id if deep_progress else "",
+ priming_candidates=[
+ CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in priming_candidates
+ ],
)
@@ -200,6 +221,38 @@ def _throttled(scanner: ReplayScanner) -> bool:
return (now - SETTLE_INTERVAL) - scanner.last_swept_at < SCANNER_SCHEDULE_INTERVAL * factor
+def _priming_pass(scanner: ReplayScanner, query: RecordingsQuery, limit: int) -> list[CandidateSession]:
+ """A few of the freshest already-settled recordings from before the fast walk's range.
+
+ Ignores the scanner's sampling rate (priming exists to produce examples now) but keeps its
+ sampling mode, so a surfacing-scored scanner still primes on the sessions it would surface.
+ Never raises: priming is advisory and must not fail the tick that carries the real sweep.
+ """
+ window_start = timezone.now() - PRIMING_LOOKBACK
+ if window_start >= scanner.last_swept_at:
+ # The watermark already covers the whole priming window (a scanner that sat throttled or
+ # unswept for over a day); there is nothing behind the fast walk to prime from.
+ return []
+ try:
+ return WindowedCandidateQuery(
+ team=scanner.team,
+ query=query,
+ window_start=window_start,
+ window_end=scanner.last_swept_at,
+ query_type="ReplayVisionPrimingCandidateQuery",
+ sampling_rate=1.0,
+ sampling_salt=str(scanner.id),
+ sampling_mode=scanner.sampling_mode,
+ candidate_limit=limit,
+ max_execution_time_seconds=PRIMING_MAX_EXECUTION_SECONDS,
+ scanner_id=str(scanner.id),
+ ).run()
+ except Exception:
+ activity.logger.exception("replay_vision.priming_pass_failed")
+ record_sweep_outcome("priming_failed")
+ return []
+
+
def _buckets_or_pre_split(buckets: dict[str, int] | None, scanner: ReplayScanner) -> dict[str, int] | None:
"""`is None`, not truthiness: only a column the meter has never written falls back to the
pre-split total bucket, which keeps throttled scanners throttled across the deploy."""
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index f5779e5bbbb6..6ddeb4a1fc17 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -84,6 +84,12 @@ DEEP_SPEND_WINDOW_DAYS = 8
# would double the per-scanner ceiling this throttling exists to hold.
DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY = 100 * 1024**3
+# One-off priming pass for a scanner that has never been swept: a few recent recordings scanned on
+# the first sweep tick, so the scanner has observations to show without waiting for new sessions.
+PRIMING_LOOKBACK = dt.timedelta(hours=24)
+PRIMING_SCAN_SESSIONS = 3
+PRIMING_MAX_EXECUTION_SECONDS = 30
+
# Rolling 24h ClickHouse read budget per scanner. Above it, sweeps stretch their effective cadence
# proportionally (skipped ticks batch into the next executed one, so no sessions are missed).
# Sized an order of magnitude above the healthy post-optimization p95 so only pathological
diff --git a/products/replay_vision/backend/temporal/sweep_types.py b/products/replay_vision/backend/temporal/sweep_types.py
index 44e005858354..8919f944731d 100644
--- a/products/replay_vision/backend/temporal/sweep_types.py
+++ b/products/replay_vision/backend/temporal/sweep_types.py
@@ -48,6 +48,9 @@ class FindScannerCandidatesOutput(BaseModel, frozen=True):
deep_keyset_session_id: str = ""
# Horizon the deep pass covered; None when it didn't run.
deep_swept_through: dt.datetime | None = None
+ # One-off priming pass for a never-swept scanner; dispatch-only, never drives any watermark.
+ # The default keeps pre-deploy histories replaying deterministically.
+ priming_candidates: list[CandidateSessionPayload] = Field(default_factory=list)
# Last row of the fetched batch, before negative-filter exclusion dropped any of it. Dropping rows
# must not regress or stall the keyset. None on pre-deploy histories and on empty batches, where
# the workflow falls back to deriving the position from `candidates`/`swept_through`.
diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.py
index a8f7683c9c10..fe81bf962a90 100644
--- a/products/replay_vision/backend/temporal/sweep_workflow.py
+++ b/products/replay_vision/backend/temporal/sweep_workflow.py
@@ -179,7 +179,10 @@ class SweepScannerWorkflow(PostHogWorkflow):
# A no-op when both lists are empty. First failure aborts the gather and skips the advance;
# UNIQUE(scanner_id, session_id) dedups retries.
await asyncio.gather(
- *(self._start_child(inputs, c) for c in (*find_result.candidates, *find_result.deep_candidates))
+ *(
+ self._start_child(inputs, c)
+ for c in (*find_result.candidates, *find_result.deep_candidates, *find_result.priming_candidates)
+ )
)
if find_result.keyset_end is not None:
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index e06d76d286cc..8e6649188210 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -7,6 +7,8 @@ from typing import Any
import pytest
from unittest.mock import MagicMock, patch
+from django.utils import timezone
+
from parameterized import parameterized
from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
@@ -54,6 +56,8 @@ from products.replay_vision.backend.temporal.constants import (
MAX_IN_FLIGHT_APPLIES_PER_TEAM,
ON_DEMAND_RESERVED_SCANNER_SLOTS,
ON_DEMAND_RESERVED_TEAM_SLOTS,
+ PRIMING_LOOKBACK,
+ PRIMING_SCAN_SESSIONS,
SWEEP_READ_BUDGET_BYTES_24H,
build_process_vision_action_workflow_id,
)
@@ -105,6 +109,8 @@ def _make_scanner(**overrides) -> ReplayScanner:
"scanner_type": ScannerType.MONITOR,
"scanner_config": {"prompt": "p"},
"model": ScannerModel.GEMINI_3_7_FLASH,
+ # Primed by default so only the priming-specific tests exercise the one-off pass.
+ "primed_at": timezone.now(),
}
defaults.update(overrides)
return ReplayScanner.objects.create(**defaults)
@@ -763,6 +769,97 @@ class TestFindScannerCandidatesActivity:
)
assert exc_info.value.non_retryable is True
+ def test_priming_pass_runs_once_for_a_never_swept_scanner(self) -> None:
+ scanner = _make_scanner(primed_at=None)
+ primed = [
+ CandidateSession(session_id="prime-a", session_end=dt.datetime(2026, 5, 1, 9, 0, tzinfo=dt.UTC)),
+ CandidateSession(session_id="prime-b", session_end=dt.datetime(2026, 5, 1, 8, 0, tzinfo=dt.UTC)),
+ ]
+ with (
+ patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
+ ) as MockFast,
+ patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
+ ) as MockWindowed,
+ ):
+ MockFast.return_value.run.return_value = []
+ MockWindowed.return_value.run.return_value = primed
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert [c.session_id for c in result.priming_candidates] == ["prime-a", "prime-b"]
+ windowed_kwargs = MockWindowed.call_args.kwargs
+ # Priming ignores the scanner's sampling rate (examples now) and stays behind the fast walk.
+ assert windowed_kwargs["sampling_rate"] == 1.0
+ assert windowed_kwargs["candidate_limit"] == PRIMING_SCAN_SESSIONS
+ assert windowed_kwargs["window_end"] == scanner.last_swept_at
+ scanner.refresh_from_db()
+ assert scanner.primed_at is not None
+
+ # One-shot: the next tick must not prime again.
+ with (
+ patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
+ ) as MockFast,
+ patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
+ ) as MockWindowed,
+ ):
+ MockFast.return_value.run.return_value = []
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+ assert result.priming_candidates == []
+ MockWindowed.assert_not_called()
+
+ def test_priming_defers_when_the_fast_batch_spends_the_whole_headroom(self) -> None:
+ # Priming shares the tick's in-flight budget; without headroom it must wait for a later tick
+ # (and stay armed), never dispatch past the caps.
+ scanner = _make_scanner(primed_at=None)
+ fast = [
+ CandidateSession(session_id=f"sess-{i}", session_end=dt.datetime(2026, 5, 1, 10, i, tzinfo=dt.UTC))
+ for i in range(2)
+ ]
+ with (
+ patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
+ ) as MockFast,
+ patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
+ ) as MockWindowed,
+ ):
+ MockFast.return_value.run.return_value = fast
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=2)
+ )
+ assert result.priming_candidates == []
+ MockWindowed.assert_not_called()
+ scanner.refresh_from_db()
+ assert scanner.primed_at is None
+
+ def test_priming_skipped_but_marked_when_watermark_covers_the_window(self) -> None:
+ # A scanner that sat unswept for over the priming lookback has nothing behind the fast walk to
+ # prime from; the pass must still be marked done so it never re-arms.
+ scanner = _make_scanner(primed_at=None, last_swept_at=timezone.now() - PRIMING_LOOKBACK * 2)
+ with (
+ patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
+ ) as MockFast,
+ patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"
+ ) as MockWindowed,
+ ):
+ MockFast.return_value.run.return_value = []
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+ assert result.priming_candidates == []
+ MockWindowed.assert_not_called()
+ scanner.refresh_from_db()
+ assert scanner.primed_at is not None
+
# advance_scanner_watermark_activity
diff --git a/products/replay_vision/frontend/emptyState/ReplayVisionObservationPreview.scss b/products/replay_vision/frontend/emptyState/ReplayVisionObservationPreview.scss
new file mode 100644
index 000000000000..aced52cda09e
--- /dev/null
+++ b/products/replay_vision/frontend/emptyState/ReplayVisionObservationPreview.scss
@@ -0,0 +1,208 @@
+.VisionPreview {
+ --vision-preview-accent: var(--empty-state-accent, var(--color-primary-500));
+
+ overflow: hidden;
+ background: var(--color-bg-surface-primary);
+ border: 1px solid var(--color-border-primary);
+ border-radius: var(--radius);
+
+ // Hidden filter state. Direct children of .VisionPreview so `:checked ~` can reach the rest.
+ &__radio {
+ position: absolute;
+ width: 0;
+ height: 0;
+ pointer-events: none;
+ opacity: 0;
+ }
+
+ &__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0.5rem 0.75rem;
+ border-bottom: 1px solid var(--color-border-primary);
+ }
+
+ &__title {
+ font-size: 0.75rem;
+ font-weight: 600;
+ }
+
+ &__chips {
+ display: flex;
+ gap: 0.375rem;
+ padding: 0.625rem 0.75rem;
+ }
+
+ &__chip {
+ display: inline-flex;
+ gap: 0.25rem;
+ align-items: center;
+ padding: 0.125rem 0.5rem;
+ font-size: 0.6875rem;
+ font-weight: 600;
+ color: var(--color-text-secondary);
+ cursor: pointer;
+ user-select: none;
+ border: 1px solid var(--color-border-primary);
+ border-radius: 999px;
+ transition:
+ color 150ms ease,
+ background-color 150ms ease,
+ border-color 150ms ease;
+ }
+
+ &__chip:hover {
+ color: var(--color-text-primary);
+ }
+
+ &__rows {
+ display: flex;
+ flex-direction: column;
+ gap: 0.375rem;
+ padding: 0.25rem 0.625rem 0.625rem;
+ }
+
+ &__row {
+ display: flex;
+ flex-direction: column;
+ gap: 0.375rem;
+ padding: 0.5rem 0.625rem;
+ border: 1px solid var(--color-border-primary);
+ border-radius: var(--radius);
+ transition: opacity 150ms ease;
+ }
+
+ &__scanner {
+ font-size: 0.75rem;
+ font-weight: 600;
+ }
+
+ &__text {
+ margin: 0;
+ font-size: 0.6875rem;
+ line-height: 1.4;
+ color: var(--color-text-secondary);
+ }
+}
+
+// The radios stay keyboard-focusable even while visually hidden, so the active chip
+// label needs a visible focus indicator (WCAG 2.4.7).
+#vision-preview-all:focus-visible ~ .VisionPreview__chips .VisionPreview__chip--all,
+#vision-preview-monitor:focus-visible ~ .VisionPreview__chips .VisionPreview__chip--monitor,
+#vision-preview-scorer:focus-visible ~ .VisionPreview__chips .VisionPreview__chip--scorer,
+#vision-preview-classifier:focus-visible ~ .VisionPreview__chips .VisionPreview__chip--classifier,
+#vision-preview-summarizer:focus-visible ~ .VisionPreview__chips .VisionPreview__chip--summarizer {
+ outline: 2px solid var(--vision-preview-accent);
+ outline-offset: 1px;
+}
+
+// Active filter chip, driven purely by the hidden radios.
+#vision-preview-all:checked ~ .VisionPreview__chips .VisionPreview__chip--all,
+#vision-preview-monitor:checked ~ .VisionPreview__chips .VisionPreview__chip--monitor,
+#vision-preview-scorer:checked ~ .VisionPreview__chips .VisionPreview__chip--scorer,
+#vision-preview-classifier:checked ~ .VisionPreview__chips .VisionPreview__chip--classifier,
+#vision-preview-summarizer:checked ~ .VisionPreview__chips .VisionPreview__chip--summarizer {
+ color: var(--vision-preview-accent);
+ background: color-mix(in oklab, var(--vision-preview-accent) 12%, transparent);
+ border-color: color-mix(in oklab, var(--vision-preview-accent) 45%, transparent);
+}
+
+// Picking a scanner type dims the rows that don't belong to it.
+#vision-preview-monitor:checked ~ .VisionPreview__rows .VisionPreview__row:not([data-t='monitor']),
+#vision-preview-scorer:checked ~ .VisionPreview__rows .VisionPreview__row:not([data-t='scorer']),
+#vision-preview-classifier:checked ~ .VisionPreview__rows .VisionPreview__row:not([data-t='classifier']),
+#vision-preview-summarizer:checked ~ .VisionPreview__rows .VisionPreview__row:not([data-t='summarizer']) {
+ opacity: 0.25;
+}
+
+.VisionSpark {
+ --vision-spark-accent: var(--empty-state-accent, var(--color-primary-500));
+
+ padding: 0.625rem 0.75rem;
+ background: var(--color-bg-surface-primary);
+ border: 1px solid var(--color-border-primary);
+ border-radius: var(--radius);
+
+ &__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+
+ &__title {
+ font-size: 0.75rem;
+ font-weight: 600;
+ color: var(--color-text-secondary);
+ }
+
+ &__value {
+ display: flex;
+ gap: 0.5rem;
+ align-items: baseline;
+ margin-top: 0.375rem;
+ font-size: 1.25rem;
+ font-weight: 700;
+ line-height: 1.1;
+ }
+
+ &__delta {
+ font-size: 0.6875rem;
+ font-weight: 600;
+ color: var(--color-green-500);
+ }
+
+ &__chart {
+ margin-top: 0.5rem;
+ }
+
+ &__svg {
+ width: 100%;
+ height: 40px;
+ }
+
+ &__area {
+ fill: color-mix(in oklab, var(--vision-spark-accent) 13%, transparent);
+ }
+
+ &__line {
+ fill: none;
+ stroke: color-mix(in oklab, var(--vision-spark-accent) 32%, transparent);
+ stroke-width: 2;
+ }
+
+ &__trace {
+ fill: none;
+ stroke: var(--vision-spark-accent);
+ stroke-dasharray: 16 84;
+ stroke-linecap: round;
+ stroke-width: 2;
+ animation: VisionSpark__trace 4s linear infinite;
+ }
+
+ &__caption {
+ margin-top: 0.5rem;
+ font-size: 0.6875rem;
+ color: var(--color-text-tertiary);
+ }
+}
+
+@keyframes VisionSpark__trace {
+ from {
+ stroke-dashoffset: 100;
+ }
+
+ to {
+ stroke-dashoffset: -100;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .VisionSpark__trace {
+ animation: none;
+ }
+}
+
+.VisionSpark--static .VisionSpark__trace {
+ animation: none;
+}
diff --git a/products/replay_vision/frontend/emptyState/ReplayVisionObservationPreview.tsx b/products/replay_vision/frontend/emptyState/ReplayVisionObservationPreview.tsx
new file mode 100644
index 000000000000..f4afd3f3cce3
--- /dev/null
+++ b/products/replay_vision/frontend/emptyState/ReplayVisionObservationPreview.tsx
@@ -0,0 +1,155 @@
+import './ReplayVisionObservationPreview.scss'
+
+import { sparkPaths } from 'lib/components/ProductEmptyState/previewSparkline'
+import type { ProductEmptyStateMode } from 'lib/components/ProductEmptyState/types'
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
+import { cn } from 'lib/utils/css-classes'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
+
+import { ScannerTypeBadge } from '../components/ScannerTypeBadge'
+import { ScannerType } from '../replay_scanners/types'
+
+interface PreviewObservation {
+ scannerType: ScannerType
+ scannerName: string
+ tag: { label: string; type: 'warning' | 'danger' } | null
+ text: string
+}
+
+// Invented results covering the four scanner types, so the examples match what the
+// create flow offers next. Static by design: an illustration, not data.
+const OBSERVATIONS: PreviewObservation[] = [
+ {
+ scannerType: 'monitor',
+ scannerName: 'Dead-end pages',
+ tag: { label: 'yes', type: 'warning' },
+ text: 'Landed on the integrations page from a search result, scrolled to the bottom, and left without clicking anything.',
+ },
+ {
+ 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.',
+ },
+]
+
+const FILTERS: { id: string; label: string }[] = [
+ { id: 'all', label: 'All' },
+ { id: 'monitor', label: 'Monitor' },
+ { id: 'scorer', label: 'Scorer' },
+ { id: 'classifier', label: 'Classifier' },
+ { id: 'summarizer', label: 'Summarizer' },
+]
+
+// A hand-authored series for the sparkline: abstract, just enough to read as a rising trend.
+const SPARK = [3, 5, 4, 6, 7, 6, 9, 8, 11, 10, 13, 14]
+const { line, area } = sparkPaths(SPARK)
+
+/**
+ * Example-data preview for the Replay vision empty state. All interaction and motion
+ * are pure CSS (hidden radios drive the type filter) - no timers or state, per the
+ * preview rules in the `building-product-empty-states` skill.
+ */
+export function ReplayVisionObservationPreview(_: { mode: ProductEmptyStateMode }): JSX.Element {
+ const isStatic = inStorybook() || inStorybookTestRunner()
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="VisionPreview">
+ {/* Filter state, before the chips/rows so `:checked ~` can style them. */}
+ {FILTERS.map((filter) => (
+ <input
+ key={filter.id}
+ type="radio"
+ name="vision-preview-filter"
+ id={`vision-preview-${filter.id}`}
+ defaultChecked={filter.id === 'all'}
+ className="VisionPreview__radio"
+ />
+ ))}
+
+ <div className="VisionPreview__head">
+ <span className="VisionPreview__title">Observations</span>
+ <LemonTag size="small">example data</LemonTag>
+ </div>
+
+ <div className="VisionPreview__chips">
+ {FILTERS.map((filter) => (
+ <label
+ key={filter.id}
+ htmlFor={`vision-preview-${filter.id}`}
+ className={`VisionPreview__chip VisionPreview__chip--${filter.id}`}
+ >
+ {filter.label}
+ </label>
+ ))}
+ </div>
+
+ <div className="VisionPreview__rows">
+ {OBSERVATIONS.map((observation) => (
+ <div
+ key={observation.scannerName}
+ className="VisionPreview__row"
+ data-t={observation.scannerType}
+ >
+ <div className="flex items-center gap-2">
+ <ScannerTypeBadge scannerType={observation.scannerType} size="small" />
+ <span className="VisionPreview__scanner">{observation.scannerName}</span>
+ {observation.tag && (
+ <LemonTag type={observation.tag.type} size="small" className="ml-auto">
+ {observation.tag.label}
+ </LemonTag>
+ )}
+ </div>
+ <p className="VisionPreview__text">{observation.text}</p>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className={cn('VisionSpark', isStatic && 'VisionSpark--static')}>
+ <div className="VisionSpark__head">
+ <span className="VisionSpark__title">Sessions scanned · 7 days</span>
+ <LemonTag size="small">example data</LemonTag>
+ </div>
+
+ <div className="VisionSpark__value">
+ 412
+ <span className="VisionSpark__delta">▲ 23%</span>
+ </div>
+
+ <div className="VisionSpark__chart">
+ <svg
+ className="VisionSpark__svg"
+ viewBox="0 0 100 40"
+ preserveAspectRatio="none"
+ aria-hidden="true"
+ >
+ <path className="VisionSpark__area" d={area} />
+ <path className="VisionSpark__line" d={line} vectorEffect="non-scaling-stroke" />
+ <path
+ className="VisionSpark__trace"
+ d={line}
+ pathLength={100}
+ vectorEffect="non-scaling-stroke"
+ />
+ </svg>
+ </div>
+
+ <div className="VisionSpark__caption">Every result is an event you can query, graph, and alert on</div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/emptyState/replayVisionEmptyState.tsx b/products/replay_vision/frontend/emptyState/replayVisionEmptyState.tsx
new file mode 100644
index 000000000000..01f89d994d18
--- /dev/null
+++ b/products/replay_vision/frontend/emptyState/replayVisionEmptyState.tsx
@@ -0,0 +1,43 @@
+import * as noirDeskPng from '@posthog/brand/hoggies/png/noir-5'
+import { IconEye } from '@posthog/icons'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import type { SceneProductEmptyState } from 'lib/components/ProductEmptyState/types'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+
+import { visionDocsUrl } from '../components/DocsLink'
+import { replayVisionSetupLogic } from '../replayVisionSetupLogic'
+import { ReplayVisionObservationPreview } from './ReplayVisionObservationPreview'
+
+const HedgehogNoirDesk = pngHoggie(noirDeskPng)
+
+export const replayVisionEmptyState: SceneProductEmptyState = {
+ statusLogic: replayVisionSetupLogic,
+ config: {
+ productKey: ProductKey.REPLAY_VISION,
+ productName: 'Replay Vision',
+ icon: <IconEye />,
+ // Replay vision shares session replay's product color (see the manifest's iconColor).
+ accentColor: 'var(--color-product-session-replay-light)',
+ accentColorDark: 'var(--color-product-session-replay-dark)',
+ hedgehog: HedgehogNoirDesk,
+ hedgehogPlacement: 'beside',
+ text: {
+ 'needs-setup': {
+ headline: "AI watches your recordings so you don't have to",
+ lead: 'Describe what to look for in plain language. A scanner watches each new session recording for it. Every result is an event you can query, graph, and alert on.',
+ hint: 'Fastest way in: the setup agent turns on session replay if needed, then reads your codebase and creates scanners for your key flows:',
+ },
+ },
+ wizard: { slug: 'replay-vision', pinProjectId: true },
+ primaryAction: {
+ label: 'Create a scanner yourself',
+ to: urls.replayVisionTemplates(),
+ },
+ docsUrl: visionDocsUrl(),
+ previewLabel: 'Example scanner results',
+ Preview: ReplayVisionObservationPreview,
+ },
+}
diff --git a/products/replay_vision/frontend/replayVisionSetupLogic.test.ts b/products/replay_vision/frontend/replayVisionSetupLogic.test.ts
new file mode 100644
index 000000000000..e55e4b0bb72c
--- /dev/null
+++ b/products/replay_vision/frontend/replayVisionSetupLogic.test.ts
@@ -0,0 +1,74 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { visionScannersStatsRetrieve } from './generated/api'
+import { replayVisionSetupLogic } from './replayVisionSetupLogic'
+
+jest.mock('./generated/api')
+
+const mockStatsRetrieve = visionScannersStatsRetrieve as jest.MockedFunction<typeof visionScannersStatsRetrieve>
+
+function statsWithTotal(total: number): Awaited<ReturnType<typeof visionScannersStatsRetrieve>> {
+ return {
+ total,
+ enabled: total,
+ by_type: {
+ monitor: { enabled: 0, total: 0 },
+ classifier: { enabled: 0, total: 0 },
+ scorer: { enabled: 0, total: 0 },
+ summarizer: { enabled: total, total },
+ },
+ }
+}
+
+describe('replayVisionSetupLogic', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ initKeaTests()
+ })
+
+ function setupStatus(): string {
+ return productSetupStatusLogic({ productKey: ProductKey.REPLAY_VISION }).values.status
+ }
+
+ // Guards the connect + mapping into the app-wide setup-status layer: if either
+ // breaks, the scene empty-state gate stays on its loading spinner forever.
+ it.each([
+ [0, 'needs-setup'],
+ [1, 'has-data'],
+ [7, 'has-data'],
+ ])('pushes a %i-scanner team into productSetupStatusLogic as %s', async (total, expected) => {
+ mockStatsRetrieve.mockResolvedValue(statsWithTotal(total))
+ const logic = replayVisionSetupLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(setupStatus()).toBe(expected)
+ })
+
+ // Guards the fail-open path: a persistently failing stats call must publish
+ // `unknown` (gate renders the scene), not leave the gate on its spinner forever.
+ it('publishes unknown when the stats call fails before any answer exists', async () => {
+ mockStatsRetrieve.mockRejectedValue(new Error('network down'))
+ const logic = replayVisionSetupLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(setupStatus()).toBe('unknown')
+ })
+
+ it('does not downgrade an existing answer when a later poll fails', async () => {
+ mockStatsRetrieve.mockResolvedValue(statsWithTotal(0))
+ const logic = replayVisionSetupLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(setupStatus()).toBe('needs-setup')
+
+ mockStatsRetrieve.mockRejectedValue(new Error('network blip'))
+ logic.actions.loadSetupStats()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(setupStatus()).toBe('needs-setup')
+ })
+})
diff --git a/products/replay_vision/frontend/replayVisionSetupLogic.ts b/products/replay_vision/frontend/replayVisionSetupLogic.ts
new file mode 100644
index 000000000000..6bf8e5151926
--- /dev/null
+++ b/products/replay_vision/frontend/replayVisionSetupLogic.ts
@@ -0,0 +1,100 @@
+import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
+import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+
+import { visionScannersStatsRetrieve } from './generated/api'
+import type { ScannerStatsResponseApi } from './generated/api.schemas'
+
+// The wizard's self-driving run creates scanners from the terminal, so keep polling
+// while the empty state is up and flip to the real scene as soon as one lands.
+const POLL_INTERVAL_MS = 20000
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface replayVisionSetupLogicValues {
+ setupStatus: ProductSetupStatus // productSetupStatusLogic
+ setupStats: ScannerStatsResponseApi | null
+ setupStatsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface replayVisionSetupLogicActions {
+ setDetectedStatus: (status: ProductSetupStatus) => {
+ status: ProductSetupStatus
+ } // productSetupStatusLogic
+ loadSetupStats: (_: void) => void
+ loadSetupStatsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSetupStatsSuccess: (
+ setupStats: ScannerStatsResponseApi,
+ payload?: void
+ ) => {
+ setupStats: ScannerStatsResponseApi
+ payload?: void
+ }
+}
+
+export type replayVisionSetupLogicType = MakeLogicType<replayVisionSetupLogicValues, replayVisionSetupLogicActions>
+
+/**
+ * Setup detection for the Replay vision empty-state gate: a scanner is the unit of
+ * setup, so any scanner on the team means the product is in use. Pushes the
+ * normalized status into `productSetupStatusLogic({ productKey: REPLAY_VISION })`.
+ */
+export const replayVisionSetupLogic = kea<replayVisionSetupLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replayVisionSetupLogic']),
+ connect(() => ({
+ actions: [productSetupStatusLogic({ productKey: ProductKey.REPLAY_VISION }), ['setDetectedStatus']],
+ values: [productSetupStatusLogic({ productKey: ProductKey.REPLAY_VISION }), ['status as setupStatus']],
+ })),
+ loaders({
+ setupStats: {
+ __default: null as ScannerStatsResponseApi | null,
+ loadSetupStats: async (_: void, breakpoint): Promise<ScannerStatsResponseApi> => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ // Routed to loadSetupStatsFailure, which fails open like any other unanswerable probe.
+ throw new Error('no current team')
+ }
+ const response = await visionScannersStatsRetrieve(String(teamId))
+ breakpoint()
+ return response
+ },
+ },
+ }),
+ listeners(({ actions, values, cache }) => ({
+ loadSetupStatsSuccess: ({ setupStats }) => {
+ const detected = setupStats && setupStats.total > 0 ? 'has-data' : 'needs-setup'
+ // Poll ticks mostly re-detect the same status; don't re-render the gate subtree for those.
+ if (detected !== values.setupStatus) {
+ actions.setDetectedStatus(detected)
+ }
+ if (detected === 'has-data') {
+ cache.disposables.dispose('poll')
+ }
+ },
+ loadSetupStatsFailure: () => {
+ // Never strand the gate on its spinner: if nothing has answered yet, fail
+ // open to the real scene. Don't downgrade an existing answer on a poll blip.
+ if (values.setupStatus === 'loading') {
+ actions.setDetectedStatus('unknown')
+ }
+ },
+ })),
+ afterMount(({ actions, cache }) => {
+ actions.loadSetupStats()
+ cache.disposables.add(() => {
+ const id = window.setInterval(() => actions.loadSetupStats(), POLL_INTERVAL_MS)
+ return () => clearInterval(id)
+ }, 'poll')
+ }),
+])
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index 7f61294ca9dd..57e38de9a51e 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -515,26 +515,6 @@ export const ScannersListEmpty: StoryObj = {
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 = {
parameters: { pageUrl: `${urls.replayVision()}?tab=usage` },
}
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
index 1461dcb72b11..c2ec023cba83 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
@@ -1,7 +1,6 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import * as xRayPng from '@posthog/brand/hoggies/png/x-ray'
import { IconPencil, IconRefresh, IconSearch, IconTrash } from '@posthog/icons'
import {
LemonBanner,
@@ -16,13 +15,10 @@ import {
Tooltip,
} from '@posthog/lemon-ui'
-import { pngHoggie } from 'lib/brand/hoggies'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
-import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
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 { urls } from 'scenes/urls'
@@ -30,24 +26,22 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
-import { visionDocsUrl, VisionDocsLink } from '../components/DocsLink'
+import { VisionDocsLink } from '../components/DocsLink'
import { FilterPill } from '../components/FilterPill'
import { IngestionLimitBanner } from '../components/IngestionLimitBanner'
import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'
import { ScannerTypeBadge } from '../components/ScannerTypeBadge'
+import { replayVisionEmptyState } from '../emptyState/replayVisionEmptyState'
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'
import { LIMIT_REACHED_TOOLTIP } from './scannerCopy'
import { ENABLED_OPTIONS, EnabledFilter, SCANNER_TYPE_OPTIONS, ScannerType, ReplayScanner } from './types'
-const HedgehogXRay = pngHoggie(xRayPng)
-
const TYPE_OPTIONS: { value: ScannerType; label: string }[] = SCANNER_TYPE_OPTIONS.map(({ value, label }) => ({
value,
label,
@@ -57,6 +51,7 @@ export const scene: SceneExport = {
component: ReplayScannersScene,
logic: replayScannersLogic,
productKey: ProductKey.REPLAY_VISION,
+ emptyState: replayVisionEmptyState,
}
export function ReplayScannersScene(): JSX.Element {
@@ -84,15 +79,6 @@ 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> = [
{
@@ -265,19 +251,6 @@ export function ReplayScannersScene(): JSX.Element {
</LemonBanner>
)}
- {!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'}
onChange={(tab) => push(urls.replayVision(), tab === 'usage' ? { tab } : {})}
@@ -289,8 +262,6 @@ 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/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
index ca1cedbc6ae9..cf2b757b0a84 100644
--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
@@ -1,6 +1,7 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { router } from 'kea-router'
+import { useState } from 'react'
import * as construction2Png from '@posthog/brand/hoggies/png/construction-2'
import * as imTheDriverPng from '@posthog/brand/hoggies/png/im-the-driver'
@@ -29,6 +30,8 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { pluralize } from 'lib/utils/strings'
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'
@@ -442,6 +445,11 @@ function EditorFooter({
const { scanner, durationValidationError, hasUnsavedChanges } = useValues(replayScannerLogic({ id: scannerId }))
const { searchParams } = useValues(router)
const { discardScannerDraft } = useActions(replayScannerLogic({ id: scannerId }))
+ const { dataProcessingAccepted } = useValues(aiConsentLogic)
+ const [consentRequested, setConsentRequested] = useState(false)
+ // The backend rejects scanner creation without org AI consent, so the popover interposes at
+ // Save instead of letting the request 400.
+ const needsConsent = isNew && !dataProcessingAccepted
const stepIndex = SCANNER_EDITOR_STEPS.indexOf(step)
const previous = stepIndex > 0 ? SCANNER_EDITOR_STEPS[stepIndex - 1] : null
const prevStep = previous === 'template' && !isNew ? null : previous
@@ -507,16 +515,33 @@ function EditorFooter({
Next: {STEP_LABELS[nextStep]}
</LemonButton>
) : (
- <LemonButton
- type="primary"
- loading={isSubmitting}
- disabledReason={saveDisabledReason}
- onClick={onSave}
- data-attr="vision-editor-save"
- data-ph-capture-attribute-scanner-type={scanner?.scanner_type}
+ <AIConsentPopoverWrapper
+ placement="top-end"
+ showArrow
+ ignoreDismissal
+ hideTrainingDisclaimer
+ hidden={!consentRequested}
+ onApprove={() => {
+ setConsentRequested(false)
+ onSave()
+ }}
+ onDismiss={() => setConsentRequested(false)}
>
- {isNew ? 'Create scanner' : 'Save changes'}
- </LemonButton>
+ <LemonButton
+ type="primary"
+ loading={isSubmitting}
+ disabledReason={saveDisabledReason}
+ onClick={() => (needsConsent ? setConsentRequested(true) : onSave())}
+ data-attr="vision-editor-save"
+ data-ph-capture-attribute-scanner-type={scanner?.scanner_type}
+ >
+ {needsConsent
+ ? 'Allow AI analysis and create scanner'
+ : isNew
+ ? 'Create scanner'
+ : 'Save changes'}
+ </LemonButton>
+ </AIConsentPopoverWrapper>
)}
</div>
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/components/CreateScannerButton.tsx b/products/replay_vision/frontend/replay_scanners/components/CreateScannerButton.tsx
index 1954b9f53553..b797b4381863 100644
--- a/products/replay_vision/frontend/replay_scanners/components/CreateScannerButton.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/CreateScannerButton.tsx
@@ -20,21 +20,14 @@ 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 [consentRequested, setConsentRequested] = useState(false)
const goToCreate = (): void => push(urls.replayVisionTemplates())
const button = (
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx
index 22f83a4ac7fa..60cb6d9b6609 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalDraft.tsx
@@ -1,21 +1,18 @@
import { useActions, useValues } from 'kea'
-import { useRef } from 'react'
+import { useRef, useState } from 'react'
import { IconArrowRight, IconSparkles } 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 { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import { replayScannerLogic } from '../replayScannerLogic'
-/** "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 details
- * 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 {
+/** "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 details step to review it. */
+export function ScannerGoalDraft(): JSX.Element {
const textAreaRef = useRef<HTMLTextAreaElement>(null)
const logic = replayScannerLogic({ id: 'new' })
const { goalDraftInput, goalDraftLoading } = useValues(logic)
@@ -23,17 +20,20 @@ export function ScannerGoalDraft({
// Drafting creates a scanner, so it needs the same editor access as the rest of the wizard.
const editDisabledReason = getReplayVisionEditDisabledReason()
+ const { dataProcessingAccepted } = useValues(aiConsentLogic)
+ const [consentRequested, setConsentRequested] = useState(false)
const handleSubmit = (): void => {
if (editDisabledReason || !goalDraftInput.trim() || goalDraftLoading) {
return
}
- const proceed = (): void => draftScannerFromGoal(goalDraftInput.trim())
- if (gateSubmit) {
- gateSubmit(proceed)
- } else {
- proceed()
+ // Drafting calls an AI endpoint the backend rejects without org consent; interpose the
+ // popover instead of letting the request 400.
+ if (!dataProcessingAccepted) {
+ setConsentRequested(true)
+ return
}
+ draftScannerFromGoal(goalDraftInput.trim())
}
return (
@@ -68,20 +68,33 @@ export function ScannerGoalDraft({
<IconSparkles className="text-ai size-3.5" />
<span>PostHog AI</span>
</div>
- <LemonButton
- type="primary"
- size="small"
- icon={<IconArrowRight />}
- loading={goalDraftLoading}
- onClick={handleSubmit}
- disabledReason={
- editDisabledReason ??
- (!goalDraftInput.trim() ? 'Describe what the scanner should look for' : undefined)
- }
- data-attr="vision-goal-draft-submit"
+ <AIConsentPopoverWrapper
+ placement="bottom-end"
+ showArrow
+ ignoreDismissal
+ hideTrainingDisclaimer
+ hidden={!consentRequested}
+ onApprove={() => {
+ setConsentRequested(false)
+ draftScannerFromGoal(goalDraftInput.trim())
+ }}
+ onDismiss={() => setConsentRequested(false)}
>
- Set up with AI
- </LemonButton>
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconArrowRight />}
+ loading={goalDraftLoading}
+ onClick={handleSubmit}
+ disabledReason={
+ editDisabledReason ??
+ (!goalDraftInput.trim() ? 'Describe what the scanner should look for' : undefined)
+ }
+ data-attr="vision-goal-draft-submit"
+ >
+ Set up with AI
+ </LemonButton>
+ </AIConsentPopoverWrapper>
</div>
</label>
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.test.ts b/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.test.ts
deleted file mode 100644
index 43cfa6881c02..000000000000
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-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
deleted file mode 100644
index b853e7e9e5c5..000000000000
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerListEmptyState.tsx
+++ /dev/null
@@ -1,244 +0,0 @@
-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 0ae1c29d96ba..7da5bbcee45f 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx
@@ -30,18 +30,7 @@ const TEMPLATE_ICONS: Record<ScannerTemplateIcon, JSX.Element> = {
check: <IconCheckCircle />,
}
-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 {
+export function TemplateCard({ template }: { template: ScannerTemplate | 'blank' }): JSX.Element {
const isBlank = template === 'blank'
const { searchParams } = useValues(router)
const { scannerDraftSavedAt } = useValues(replayScannerLogic({ id: 'new' }))
@@ -54,23 +43,16 @@ export function TemplateCard({
}
const handleClick = (): void => {
- 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()
+ 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' },
+ })
}
return (