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): draft a scanner with AI from the replay filters (#124521)

Kim Svatos Dugandff71910c702
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1342fef0c0a8..aedd0750b841 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8819,9 +8819,9 @@ snapshots:
replay-tabs-home-filters-banner--product-analytics-under-limit--light:
hash: v1.k794b7964.bc227a614a4387183844d3f52df818b273b31d8d0a8d3b0e40fdf0a31488fb03.xFHUQD9ILXWiU9zR3XymL0E5VNOqa0jRvXiL5_FTiIs
replay-tabs-home-filters-banner--scanner-cross-sell--dark:
- hash: v1.k794b7964.cdda062e13754aeb37e3982382846ef836705498f6bbea45bb44a461945d43e2.8rtPhnDj48obOBCmP9Gzsmi6GQZwxWOvqT79lwYouDE
+ hash: v1.k794b7964.bc64e8d178e529d893d7bb7cf3b41acbc2f03932226becc2c3ab1122dfd2dcfd.VWUxbIzF0TqTKWX7VtcV_b1sxsM7WCMkHEaT9c0s2uQ
replay-tabs-home-filters-banner--scanner-cross-sell--light:
- hash: v1.k794b7964.a96216b5edb663a43474a80662c186bcdbf2c28ed8b5102d628fefa68b50ed98.vgbb2qohMFpIa0AX9WIcn8fgG6mxvygJDNu10McdBoU
+ hash: v1.k794b7964.4ed70ddb8a2d3543d370f0bb7ef593c8ea519dc2d0f76211b3036803f76535b8.PKjFroml7V0bPXDpdHO4s52Xxxb--3lQmjldubsJzr0
replay-tabs-home-filters-banner--templates-tab--dark:
hash: v1.k794b7964.d029de296a4c76b82cefbd0e68f9990c27a1b9692764a9b3ddc4317dd5d184d4.VGIKGjydwEuB3kz2DSDoMy-1QWQkGO6PPu44E4bBto0
replay-tabs-home-filters-banner--templates-tab--light:
@@ -15038,6 +15038,10 @@ snapshots:
hash: v1.k794b7964.c3c29df373cd8e663770b097f02a4772ffc2ba0c51e10a245fb5cf8ef7bdff68.rPAbWs7-3bfCc9X1HQcY30nfQscWET-stKmszLHV-fo
scenes-app-replay-vision--scanner-editor-goal-overview-free-only--light:
hash: v1.k794b7964.2abc94dc57d65cb6ecea210e7bdb23750f93dd5acdf32f1b0410b041bc0f3ed7.BSXIKK9m6yVzc_yZ5pmgl39D3y6ZaYmJpnULVOEULsM
+ scenes-app-replay-vision--scanner-editor-goal-overview-from-replay-filters--dark:
+ hash: v1.k794b7964.13e722e362e56337bc6d11e02bec026d9a923c2eca2bc995dbfd0451491d151d.xcQ8xU__yVwqmJJpFWHisDdT4fqdjvgr4Omv6mCW-yw
+ scenes-app-replay-vision--scanner-editor-goal-overview-from-replay-filters--light:
+ hash: v1.k794b7964.55081ca056585110b46a8ab9cfee6f4225d299689b7422257ba19257d8147310.7ezOd4HBRfRWJvJ3DnU-hqfeSutiMghrPXDae9BYSUg
scenes-app-replay-vision--scanner-editor-goal-overview-loading--dark:
hash: v1.k794b7964.1a1ff16d7bba6dfd41b09cf0a1e2032457a96412d8bef532f15c3f65039d2b20.0LkpJTMQS5qYq0AW_krA6JrCtvR-si_EnxNAh4hMdfs
scenes-app-replay-vision--scanner-editor-goal-overview-loading--light:
@@ -15222,6 +15226,14 @@ snapshots:
hash: v1.k794b7964.628aadee0591ed32bec6030dad4acc732423c095d82a0f75930710736851fa28.3mh2R55GMgaCMNSdXOcUqECUPP4MmFCDYu_0jqs331E
scenes-app-replay-vision-recordingtimeline--very-long-recording--light:
hash: v1.k794b7964.a04715d7aa78cff8fcfb049420139f30f87ac31872679219f3ee7f4be8475cf2.RW9X9AswVQmbJBWPH6SLAV52RPjoUy5MIcCOXDIGeBM
+ scenes-app-replay-vision-replayfiltersscannerpopover--all-new-recordings--dark:
+ hash: v1.k794b7964.08cc8aa558a5de23f4ed1306ad96af14729761554fce4cb505c6bf77e4360174.UfBYc1JFK9vfM6_t3rnC6RKmG8K_EXmySNpk0Ka19sg
+ scenes-app-replay-vision-replayfiltersscannerpopover--all-new-recordings--light:
+ hash: v1.k794b7964.ad2fa34bb32b8f83ddd9dff95548bb82f9ea24b58c9502b620633e7ed1fd26fa.CItre1_4DH5y_Ewg62HwBoYBlJi4u49h7JGqvs5Deuw
+ scenes-app-replay-vision-replayfiltersscannerpopover--with-filters--dark:
+ hash: v1.k794b7964.2a6736d2a3ec4972e36d3d0a4b9b693cd6c1301c4542fcb35b2108c6ebe39ed2.KDhm67EpypyqZcTOqmy5izF4WJaVokAdhf2eYmRI0wY
+ scenes-app-replay-vision-replayfiltersscannerpopover--with-filters--light:
+ hash: v1.k794b7964.498913275afda254c5b42c2969da4f4b4521ef9850ee19fd666ca52595f6fde2.1fwBcq3d4CeG70mWC6BIPkQ-Zvvrn7NGtbV-g8JFO3k
scenes-app-replay-vision-spendtrajectorychart--hits-the-limit--dark:
hash: v1.k794b7964.cf96414912c6d8f0d73808db3f1d833c661d12b3b0449cdd49b95d4dc8059e80.3sA2mn18MksUWQQ4mq6wEPbkJhGP3O258Y6Q2fTWhgM
scenes-app-replay-vision-spendtrajectorychart--hits-the-limit--light:
diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
index 2bc6908dbf7d..85e2a51c7ac1 100644
--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
@@ -1,7 +1,6 @@
import clsx from 'clsx'
import { deepEqual as equal } from 'fast-equals'
import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
import { useEffect, useId, useMemo, useRef, useState } from 'react'
import {
@@ -12,7 +11,6 @@ import {
IconRefresh,
IconRevert,
IconSearch,
- IconSparkles,
IconTrash,
IconX,
} from '@posthog/icons'
@@ -42,18 +40,16 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getProjectEventExistence } from 'lib/utils/getAppContext'
-import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter'
import { MaxTool } from 'scenes/max/MaxTool'
import { RecordingEventMatchScopeSelect } from 'scenes/session-recordings/filters/RecordingEventMatchScopeSelect'
import { hasPageFilter } from 'scenes/session-recordings/utils'
-import { urls } from 'scenes/urls'
import { actionsModel } from '~/models/actionsModel'
import { cohortsModel } from '~/models/cohortsModel'
import { groupsModel } from '~/models/groupsModel'
import { AndOrFilterSelect } from '~/queries/nodes/InsightViz/PropertyGroupFilters/AndOrFilterSelect'
-import { NodeKind, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+import { NodeKind } from '~/queries/schema/schema-general'
import {
PropertyFilterType,
PropertyOperator,
@@ -62,6 +58,7 @@ import {
UniversalFiltersGroup,
} from '~/types'
+import { ReplayFiltersScannerButton } from 'products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerButton'
import { scannerHandoffFromFilters } from 'products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters'
import { sessionRecordingSavedFiltersLogic } from '../filters/sessionRecordingSavedFiltersLogic'
@@ -886,33 +883,7 @@ export const ReplayFiltersTab = ({
<div className="flex gap-2 ml-auto">
{scannerCrossSellEnabled && (
<>
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconSparkles className="text-ai" />}
- data-attr="replay-save-filters-as-scanner"
- tooltip={
- scannerHandoff.narrowsSessions
- ? 'Create a Replay vision scanner. It watches new session recordings that match these filters for you. The date range does not carry over, so it starts from now.'
- : 'Create a Replay vision scanner. It watches every new session recording for you. Add a filter to watch only some of them. A date range and pinned sessions do not carry over.'
- }
- onClick={() => {
- void addProductIntentForCrossSell({
- from: ProductKey.SESSION_REPLAY,
- to: ProductKey.REPLAY_VISION,
- intent_context:
- ProductIntentContext.SESSION_REPLAY_SAVE_FILTERS_AS_SCANNER,
- })
- router.actions.push(
- combineUrl(
- urls.replayVisionScannerConfigure('new'),
- scannerHandoff.searchParams
- ).url
- )
- }}
- >
- Create scanner
- </LemonButton>
+ <ReplayFiltersScannerButton handoff={scannerHandoff} />
{/* Grouped away from the buttons that act on the filters themselves:
this one leaves for another product. */}
<LemonDivider vertical className="mx-1 self-stretch" />
diff --git a/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx b/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx
index bdad5cbf7f88..7fae83f4bc7c 100644
--- a/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx
+++ b/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx
@@ -76,6 +76,7 @@ export function AIConsentPopoverWrapper({
children,
ignoreDismissal,
onApprove,
+ onBeforeApprove,
onDismiss,
hideTrainingDisclaimer,
pendingRedirectUrl,
@@ -86,6 +87,11 @@ export function AIConsentPopoverWrapper({
/** Always show popover regardless of prior dismissal. */
ignoreDismissal?: boolean
onApprove?: () => void
+ /**
+ * Runs once the person confirms, before the approval request. That request can trigger a
+ * full-page SSO reauthentication, so persist here anything `onApprove` would need after it.
+ */
+ onBeforeApprove?: () => void
onDismiss?: () => void
/** Passed through to AIConsentPopoverContent. */
hideTrainingDisclaimer?: boolean
@@ -125,6 +131,7 @@ export function AIConsentPopoverWrapper({
setAt: Date.now(),
})
}
+ onBeforeApprove?.()
await acceptDataProcessing()
onApprove?.()
}}
diff --git a/frontend/src/scenes/settings/organization/aiConsentLogic.ts b/frontend/src/scenes/settings/organization/aiConsentLogic.ts
index b12b780d745a..2cd7d29af30a 100644
--- a/frontend/src/scenes/settings/organization/aiConsentLogic.ts
+++ b/frontend/src/scenes/settings/organization/aiConsentLogic.ts
@@ -24,7 +24,7 @@ const AI_ACCESS_REQUESTED_STORAGE_KEY = 'posthog_ai_access_requested_by_org'
// request is sent, so the confirmed intent can be replayed on return.
const AI_CONSENT_PENDING_REDIRECT_STORAGE_KEY = 'posthog_ai_consent_pending_redirect'
-const AI_CONSENT_PENDING_REDIRECT_TTL_MS = 15 * 60 * 1000
+export const AI_CONSENT_PENDING_REDIRECT_TTL_MS = 15 * 60 * 1000
export interface PendingApprovalRedirect {
url: string
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index d59c8d6e18ae..296788868ec7 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -2057,6 +2057,41 @@ export const ScannerEditorGoalOverviewRecordingsFirst: StoryObj = {
decorators: [seedGoalOverviewDraft],
}
+const addedBillingEvent = { id: 'billing_limit_set', name: 'billing_limit_set', type: 'events', order: 0 }
+
+const goalDraftFromReplayFilters: DraftScannerResponseApi = {
+ ...goalDraft,
+ query: {
+ kind: 'RecordingsQuery',
+ properties: [{ type: 'recording', key: 'visited_page', value: ['/checkout'], operator: 'icontains' }],
+ events: [addedBillingEvent],
+ },
+ query_additions: { kind: 'RecordingsQuery', events: [addedBillingEvent] },
+}
+
+export const ScannerEditorGoalOverviewFromReplayFilters: StoryObj = {
+ parameters: {
+ pageUrl: urls.replayVisionScannerOverview('new'),
+ },
+ decorators: [
+ (StoryFn) => {
+ const logic = replayScannerLogic({ id: 'new' })
+ logic.mount()
+ logic.actions.draftScannerFromGoalSuccess(goalDraftFromReplayFilters)
+ logic.actions.setScannerValues({
+ name: goalDraftFromReplayFilters.name,
+ description: goalDraftFromReplayFilters.description,
+ scanner_type: goalDraftFromReplayFilters.scanner_type as ScannerType,
+ scanner_config: goalDraftFromReplayFilters.scanner_config as ScannerConfig,
+ query: goalDraftFromReplayFilters.query as RecordingsQuery,
+ sampling_mode: goalDraftFromReplayFilters.sampling_mode as SamplingMode,
+ sampling_rate: goalDraftFromReplayFilters.sampling_rate ?? 1,
+ })
+ return <StoryFn />
+ },
+ ],
+}
+
// The same landing step for a goal that named an experiment: the eligible-recordings section
// leads with the experiment and variant the scan watches, which no page filter can express.
export const ScannerEditorGoalOverviewExperiment: StoryObj = {
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStaleBanner.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStaleBanner.tsx
index 3a7bbb30b1da..838e6868333c 100644
--- a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStaleBanner.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStaleBanner.tsx
@@ -159,7 +159,7 @@ export function HighlightPicksStaleBanner(): JSX.Element | null {
disabledReason={editDisabledReason}
to={combineUrl(urls.replayVisionNewScanner(), { goal: starter.goal }).url}
onClick={() => {
- markScannerGoalDraftIntent(starter.goal)
+ markScannerGoalDraftIntent({ goal: starter.goal })
pickSharperGoal(starter.key)
}}
data-attr={`vision-highlight-picks-stale-goal-${starter.key}`}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerButton.tsx b/products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerButton.tsx
new file mode 100644
index 000000000000..cb902e754216
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerButton.tsx
@@ -0,0 +1,58 @@
+import { useActions, useValues } from 'kea'
+import { useRef } from 'react'
+
+import { IconSparkles } from '@posthog/icons'
+import { LemonButton, LemonTag } from '@posthog/lemon-ui'
+import { PostHogCaptureOnViewed } from '@posthog/react'
+
+import { Popover } from 'lib/lemon-ui/Popover/Popover'
+
+import { REPLAY_FILTERS_ENTRY_POINT, replayFiltersScannerLogic } from '../replayFiltersScannerLogic'
+import type { ScannerHandoffFromFilters } from '../scannerHandoffFromFilters'
+import { ReplayFiltersScannerPopover } from './ReplayFiltersScannerPopover'
+
+export function ReplayFiltersScannerButton({ handoff }: { handoff: ScannerHandoffFromFilters }): JSX.Element {
+ const { popoverOpen } = useValues(replayFiltersScannerLogic)
+ const { setPopoverOpen } = useActions(replayFiltersScannerLogic)
+ const buttonRef = useRef<HTMLButtonElement>(null)
+
+ return (
+ <PostHogCaptureOnViewed
+ // Pinned: shared with the other Replay vision upsells, so one funnel compares every placement.
+ name="replay_vision_upsell_shown"
+ properties={{ placement: REPLAY_FILTERS_ENTRY_POINT, narrows_sessions: handoff.narrowsSessions }}
+ >
+ <Popover
+ visible={popoverOpen}
+ // Otherwise a press on the button closes the popover and the button's own toggle reopens it.
+ onClickOutside={(event) => {
+ if (!buttonRef.current?.contains(event.target as Node)) {
+ setPopoverOpen(false)
+ }
+ }}
+ overlay={<ReplayFiltersScannerPopover handoff={handoff} />}
+ placement="top-end"
+ fallbackPlacements={['bottom-end']}
+ showArrow
+ >
+ <LemonButton
+ ref={buttonRef}
+ type="secondary"
+ size="small"
+ icon={<IconSparkles className="text-ai" />}
+ sideIcon={
+ <LemonTag type="completion" size="small">
+ NEW
+ </LemonTag>
+ }
+ active={popoverOpen}
+ // Frozen: autocapture and the filters story find the entry point by it.
+ data-attr="replay-save-filters-as-scanner"
+ onClick={() => setPopoverOpen(!popoverOpen)}
+ >
+ {handoff.narrowsSessions ? 'Have AI watch recordings like these' : 'Have AI watch new recordings'}
+ </LemonButton>
+ </Popover>
+ </PostHogCaptureOnViewed>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerPopover.stories.tsx b/products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerPopover.stories.tsx
new file mode 100644
index 000000000000..47286df51603
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerPopover.stories.tsx
@@ -0,0 +1,85 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { mswDecorator } from '~/mocks/browser'
+import { NodeKind, type RecordingsQuery } from '~/queries/schema/schema-general'
+import { PropertyFilterType, PropertyOperator } from '~/types'
+
+import type { ScannerHandoffFromFilters } from '../scannerHandoffFromFilters'
+import { ReplayFiltersScannerPopover } from './ReplayFiltersScannerPopover'
+
+const quota = {
+ credit_limit: 10000,
+ credits_used: 100,
+ remaining: 9900,
+ exhausted: false,
+ projected_monthly_credits: 0,
+ scanners_monthly_credits: 0,
+ backfills_committed_credits: 0,
+ free_monthly_credits: 2500,
+ credits_settled: 100,
+ credits_reserved: 0,
+ period_start: '2026-10-01T00:00:00Z',
+ period_end: '2026-11-01T00:00:00Z',
+}
+
+const withFiltersQuery: RecordingsQuery = {
+ kind: NodeKind.RecordingsQuery,
+ properties: [
+ {
+ type: PropertyFilterType.Recording,
+ key: 'visited_page',
+ value: ['/checkout'],
+ operator: PropertyOperator.Regex,
+ },
+ {
+ type: PropertyFilterType.Session,
+ key: '$entry_current_url',
+ value: ['https://example.com/pricing'],
+ operator: PropertyOperator.Exact,
+ },
+ ],
+}
+
+const meta: Meta<typeof ReplayFiltersScannerPopover> = {
+ title: 'Scenes-App/Replay Vision/ReplayFiltersScannerPopover',
+ component: ReplayFiltersScannerPopover,
+ decorators: [
+ mswDecorator({ get: { '/api/projects/:team_id/vision/quota/': quota } }),
+ (Story) => (
+ <div className="inline-block rounded border bg-surface-primary p-2">
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof ReplayFiltersScannerPopover>
+
+export const WithFilters: Story = {
+ args: {
+ handoff: {
+ searchParams: {},
+ query: withFiltersQuery,
+ chosenQuery: withFiltersQuery,
+ experiment: null,
+ pinnedSessionCount: 0,
+ droppedCommentSearch: false,
+ narrowsSessions: true,
+ } satisfies ScannerHandoffFromFilters,
+ },
+}
+
+export const AllNewRecordings: Story = {
+ args: {
+ handoff: {
+ searchParams: {},
+ query: { kind: NodeKind.RecordingsQuery },
+ chosenQuery: { kind: NodeKind.RecordingsQuery },
+ experiment: null,
+ pinnedSessionCount: 3,
+ droppedCommentSearch: false,
+ narrowsSessions: false,
+ } satisfies ScannerHandoffFromFilters,
+ },
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerPopover.tsx b/products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerPopover.tsx
new file mode 100644
index 000000000000..bd7bb1c9e033
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ReplayFiltersScannerPopover.tsx
@@ -0,0 +1,199 @@
+import { useActions, useValues } from 'kea'
+
+import { IconSparkles } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonSegmentedButton, LemonTag, LemonTextArea } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
+import { urls } from 'scenes/urls'
+
+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
+import { formatCreditCount } from '../../utils/credits'
+import { type ReplayFiltersCreditCap, replayFiltersScannerLogic } from '../replayFiltersScannerLogic'
+import type { ScannerHandoffFromFilters } from '../scannerHandoffFromFilters'
+import type { ReplayScanner } from '../types'
+import { eligibleFilterGroups } from './ScannerGoalOverview'
+
+const GOAL_PLACEHOLDER =
+ 'For example: Where do people give up before they pay?\nOr: Watch for errors and buttons that do nothing on the payment step.'
+
+export function ReplayFiltersScannerPopover({ handoff }: { handoff: ScannerHandoffFromFilters }): JSX.Element {
+ const { goal, budget, spendChoice, freeCreditsLeft, draftInputDisabledReason, consentSpend } =
+ useValues(replayFiltersScannerLogic)
+ const {
+ setGoal,
+ setCreditCap,
+ setBudget,
+ draftWithAi,
+ setUpManually,
+ requestConsent,
+ confirmConsent,
+ cancelConsent,
+ } = useActions(replayFiltersScannerLogic)
+ const { dataProcessingAccepted } = useValues(aiConsentLogic)
+
+ const editDisabledReason = getReplayVisionEditDisabledReason()
+ const draftDisabledReason = editDisabledReason ?? draftInputDisabledReason
+
+ const filterGroups = handoff.narrowsSessions
+ ? eligibleFilterGroups({
+ query: handoff.query,
+ scanner_config: {},
+ experiment_targeting: handoff.experiment
+ ? { experiment_id: handoff.experiment.experimentId, variant: handoff.experiment.variantKey }
+ : null,
+ } as unknown as ReplayScanner)
+ : []
+ const notKept = [
+ 'the date range',
+ ...(handoff.pinnedSessionCount > 0 ? [pluralize(handoff.pinnedSessionCount, 'pinned recording')] : []),
+ ...(handoff.droppedCommentSearch ? ['the comment search'] : []),
+ ].join(', ')
+
+ const draft = (): void => {
+ if (dataProcessingAccepted) {
+ draftWithAi(handoff)
+ } else if (spendChoice.spend) {
+ requestConsent(spendChoice.spend)
+ }
+ }
+
+ return (
+ <div className="flex flex-col gap-3 p-1 w-[26rem] max-w-full">
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-1.5 font-semibold">
+ <IconSparkles className="text-ai" />
+ {handoff.narrowsSessions
+ ? 'Create a Replay vision scanner from these filters'
+ : 'Create a Replay vision scanner'}
+ </div>
+ <div className="text-xs text-secondary">
+ A Replay vision scanner watches new session recordings for you.{' '}
+ {handoff.narrowsSessions
+ ? 'It starts from these filters, and PostHog AI can narrow them to fit what you ask.'
+ : 'With no filters, it starts from every new recording, and PostHog AI can narrow that to fit what you ask.'}
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-1.5 rounded border border-dashed border-primary p-2">
+ <div className="text-xxs font-semibold uppercase text-secondary">Starts from these recordings</div>
+ <div className="flex flex-wrap gap-1">
+ {filterGroups.length > 0 ? (
+ filterGroups.flatMap((group) =>
+ group.values.map((value) => (
+ <LemonTag key={`${group.key}:${value}`} type="default">
+ {group.label}: {value}
+ </LemonTag>
+ ))
+ )
+ ) : (
+ // Some filters (custom durations, console logs) have no chip, so only claim "all" when nothing narrows.
+ <LemonTag type="default">
+ {handoff.narrowsSessions ? 'The replay filters you picked' : 'All new session recordings'}
+ </LemonTag>
+ )}
+ </div>
+ <div className="text-xs text-secondary">
+ Not kept: {notKept}. The Replay vision scanner starts from now.
+ </div>
+ {!handoff.narrowsSessions ? (
+ <div className="text-xs text-secondary">
+ To watch only some recordings, close this and add a filter.
+ </div>
+ ) : null}
+ </div>
+
+ <div className="flex flex-col gap-1">
+ <label htmlFor="replay-filters-scanner-goal" className="text-sm font-semibold">
+ What should it watch for or answer?
+ </label>
+ <LemonTextArea
+ id="replay-filters-scanner-goal"
+ value={goal}
+ onChange={setGoal}
+ placeholder={GOAL_PLACEHOLDER}
+ minRows={3}
+ maxRows={6}
+ autoFocus
+ data-attr="replay-filters-scanner-goal"
+ />
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ <span className="text-sm font-semibold">Do you want to set a credit cap for this scanner?</span>
+ <LemonSegmentedButton<ReplayFiltersCreditCap>
+ size="small"
+ value={spendChoice.mode === 'free' ? 'free' : 'cap'}
+ onChange={setCreditCap}
+ options={[
+ {
+ value: 'free',
+ label: 'No, use free credits only',
+ disabledReason: spendChoice.freeDisabledReason ?? undefined,
+ 'data-attr': 'replay-filters-scanner-spend-free',
+ },
+ { value: 'cap', label: 'Yes, set a cap', 'data-attr': 'replay-filters-scanner-spend-cap' },
+ ]}
+ />
+ {spendChoice.mode === 'free' ? (
+ <div className="text-xs text-secondary">
+ The Replay vision scanner only uses your free monthly credits
+ {/* Its own span, so page translation cannot strand the changing balance. */}
+ <span>{freeCreditsLeft != null ? ` (${formatCreditCount(freeCreditsLeft)} left)` : ''}</span>.
+ It pauses when they run out, so it never adds to your bill.
+ </div>
+ ) : (
+ <LemonInput
+ aria-label="Monthly credit cap"
+ type="number"
+ min={1}
+ value={budget ?? undefined}
+ onChange={(value) => setBudget(value ?? null)}
+ suffix={<span className="text-secondary">credits a month</span>}
+ size="small"
+ className="w-56"
+ data-attr="replay-filters-scanner-budget"
+ />
+ )}
+ </div>
+
+ <div className="flex items-center justify-between gap-2">
+ <LemonButton
+ type="tertiary"
+ size="small"
+ disabledReason={editDisabledReason}
+ onClick={() => setUpManually(handoff)}
+ data-attr="replay-filters-scanner-manual"
+ >
+ Set up manually
+ </LemonButton>
+ <AIConsentPopoverWrapper
+ placement="bottom-end"
+ showArrow
+ ignoreDismissal
+ hideTrainingDisclaimer
+ pendingRedirectUrl={urls.replayVisionNewScanner()}
+ hidden={!consentSpend}
+ onBeforeApprove={() => consentSpend && confirmConsent(handoff, consentSpend)}
+ onApprove={() => draftWithAi(handoff, consentSpend ?? undefined)}
+ onDismiss={cancelConsent}
+ >
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconSparkles />}
+ // Inside the consent popover's reference, so Lemon would add a dropdown chevron.
+ sideIcon={null}
+ disabledReason={draftDisabledReason}
+ onClick={draft}
+ data-attr="replay-filters-scanner-draft"
+ >
+ Draft with AI
+ </LemonButton>
+ </AIConsentPopoverWrapper>
+ </div>
+ <div className="text-xs font-semibold">You can review the draft before the scanner is created.</div>
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx
index c38db35b0c6a..6726fea2349d 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useState } from 'react'
import { IconPlus, IconSparkles } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonSegmentedButton, LemonTextArea } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonSegmentedButton, LemonTextArea, Link } from '@posthog/lemon-ui'
import { PopoverReferenceContext } from 'lib/lemon-ui/Popover/Popover'
import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
@@ -38,9 +38,16 @@ export function ScannerGoalFlow(): JSX.Element {
goalDraftLoading,
goalExperiment: experiment,
linkedExperimentContext,
+ goalDraftQuery,
} = useValues(logic)
- const { draftScannerFromGoal, setGoalDraftInput, setGoalBudgetInput, setGoalSpendMode, setGoalExperiment } =
- useActions(logic)
+ const {
+ draftScannerFromGoal,
+ setGoalDraftInput,
+ setGoalBudgetInput,
+ setGoalSpendMode,
+ setGoalExperiment,
+ setGoalDraftQuery,
+ } = useActions(logic)
const { dataProcessingAccepted } = useValues(aiConsentLogic)
const { freeCreditsLeft } = useValues(visionQuotaLogic)
// The spend choice is captured with the goal, so a quota that loads while consent is open cannot change it.
@@ -54,6 +61,10 @@ export function ScannerGoalFlow(): JSX.Element {
spendMode === 'free' ||
(goalBudgetInput != null && goalBudgetInput >= MIN_SCAN_BUDGET && goalBudgetInput <= MAX_SCAN_BUDGET)
const starterDisabledReason = editDisabledReason ?? (goalDraftLoading ? 'Drafting your scanner' : null)
+ // The server refuses an experiment other than the one the replay filters already scope to.
+ const experimentStarterDisabledReason =
+ starterDisabledReason ??
+ (goalDraftQuery?.experiment_exposure ? 'Your replay filters already pick an experiment' : null)
const submitDisabledReason =
starterDisabledReason ??
(!goalDraftInput.trim()
@@ -137,6 +148,18 @@ export function ScannerGoalFlow(): JSX.Element {
{linkedExperimentContext.experiment.name}. You don't have to mention the experiment.
</div>
) : null}
+ {goalDraftQuery ? (
+ <div className="text-xs text-muted">
+ This scanner starts from the replay filters you picked. The agent can narrow them,
+ but not widen them.{' '}
+ <Link
+ onClick={() => setGoalDraftQuery(null)}
+ data-attr="vision-goal-flow-clear-query"
+ >
+ Let the agent pick the recordings instead
+ </Link>
+ </div>
+ ) : null}
</div>
<div className="flex flex-col gap-2">
@@ -161,7 +184,7 @@ export function ScannerGoalFlow(): JSX.Element {
))}
<ScannerGoalExperimentStarter
experiment={experiment}
- disabledReason={starterDisabledReason}
+ disabledReason={experimentStarterDisabledReason}
onChange={changeExperiment}
/>
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.ts b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.ts
index 43ec2b8ac4d9..4d2ed4c04141 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.ts
@@ -1,5 +1,5 @@
import { NodeKind } from '~/queries/schema/schema-general'
-import { PropertyFilterType, PropertyOperator } from '~/types'
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
import type { ReplayScanner } from '../types'
import { eligibleFilterGroups, goalOverviewSectionLabels } from './ScannerGoalOverview'
@@ -52,12 +52,30 @@ describe('eligibleFilterGroups', () => {
// The session property gets its own row and is not double-counted as a page or cohort, which
// are pulled from the same top-level properties list but keep their dedicated rows.
expect(groups).toEqual([
- { label: 'Experiment', values: ['Checkout CTA copy (test variant)'] },
- { label: 'Pages', values: ['/billing', '/checkout'] },
- { label: 'Event', values: ['billing_limit_set'] },
- { label: 'Action', values: ['Completed checkout'] },
- { label: 'Cohort', values: ['Power users'] },
- { label: 'Session', values: ['Entry URL = /pricing'] },
+ { key: 'experiment', label: 'Experiment', values: ['Checkout CTA copy (test variant)'] },
+ { key: 'page:0', label: 'Pages', values: ['/billing', '/checkout'] },
+ { key: 'event', label: 'Event', values: ['billing_limit_set'] },
+ { key: 'action', label: 'Action', values: ['Completed checkout'] },
+ { key: 'cohort', label: 'Cohort', values: ['Power users'] },
+ { key: 'property:Session', label: 'Session', values: ['Entry URL = /pricing'] },
+ ])
+ })
+
+ it('gives each page filter its own row, so a page added to a chosen one does not merge into it', () => {
+ const page = (value: string): AnyPropertyFilter => ({
+ type: PropertyFilterType.Recording,
+ key: 'visited_page',
+ value: [value],
+ operator: PropertyOperator.Regex,
+ })
+
+ const groups = eligibleFilterGroups(
+ scanner({ query: { kind: NodeKind.RecordingsQuery, properties: [page('/checkout'), page('/billing')] } })
+ )
+
+ expect(groups).toEqual([
+ { key: 'page:0', label: 'Page', values: ['/checkout'] },
+ { key: 'page:1', label: 'Page', values: ['/billing'] },
])
})
@@ -76,8 +94,8 @@ describe('eligibleFilterGroups', () => {
)
expect(groups).toEqual([
- { label: 'Experiment', values: ['Experiment 11 (all variants)'] },
- { label: 'Cohort', values: ['Cohort 7'] },
+ { key: 'experiment', label: 'Experiment', values: ['Experiment 11 (all variants)'] },
+ { key: 'cohort', label: 'Cohort', values: ['Cohort 7'] },
])
})
@@ -108,7 +126,7 @@ describe('eligibleFilterGroups', () => {
})
)
- expect(groups).toEqual([{ label: 'Event', values: ['checkout_clicked where Country code = US'] }])
+ expect(groups).toEqual([{ key: 'event', label: 'Event', values: ['checkout_clicked where Country code = US'] }])
})
it('renders a HogQL condition by its comment, so a scoped $exception reads as the error', () => {
@@ -136,7 +154,9 @@ describe('eligibleFilterGroups', () => {
})
)
- expect(groups).toEqual([{ label: 'Event', values: ['$exception where TypeError: x is not a function'] }])
+ expect(groups).toEqual([
+ { key: 'event', label: 'Event', values: ['$exception where TypeError: x is not a function'] },
+ ])
})
it('merges top-level person filters into one row, humanizing known keys and keeping custom ones', () => {
@@ -164,7 +184,9 @@ describe('eligibleFilterGroups', () => {
})
)
- expect(groups).toEqual([{ label: 'Person', values: ['Latest browser = Chrome', 'plan = enterprise'] }])
+ expect(groups).toEqual([
+ { key: 'property:Person', label: 'Person', values: ['Latest browser = Chrome', 'plan = enterprise'] },
+ ])
})
it('has no groups when the draft watches every recording', () => {
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx
index fe1af7aa92ad..dbc52ef76973 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx
@@ -3,7 +3,7 @@ import { router } from 'kea-router'
import { useEffect, useState } from 'react'
import { TextMorph } from 'torph/react'
-import { IconInfo, IconWarning } from '@posthog/icons'
+import { IconInfo, IconSparkles, IconWarning } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonSkeleton, LemonSnack, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'
@@ -116,6 +116,8 @@ function OverviewSection({
/** One kind of filter on the drafted scanner, with the values it holds. */
export interface EligibleFilterGroup {
+ /** Unique within one scanner's groups, because two page filters share the label "Page". */
+ key: string
label: string
values: string[]
}
@@ -130,19 +132,17 @@ function experimentValues(scanner: ReplayScanner, experimentName?: string): stri
return [`${experimentName ?? `Experiment ${scope.experimentId}`} (${variant})`]
}
-/** The pages a session must have visited.
+/** The pages a session must have visited, one list per page filter.
*
* Read by key, not by position: the properties list can hold a cohort alongside the pages, and
- * taking whichever came first would render a cohort id as a page.
+ * taking whichever came first would render a cohort id as a page. A filter's pages are alternatives,
+ * but separate filters must all match, as when a draft narrows a chosen page with one of its own, so
+ * each filter keeps its own list.
*/
-function pageValues(scanner: ReplayScanner): string[] {
- const property = scanner.query?.properties?.find(
- (candidate) => 'key' in candidate && candidate.key === 'visited_page'
- )
- if (!property || !('value' in property) || !Array.isArray(property.value)) {
- return []
- }
- return property.value.map(String)
+function pageValueLists(scanner: ReplayScanner): string[][] {
+ return (scanner.query?.properties ?? [])
+ .filter((property) => 'key' in property && property.key === 'visited_page')
+ .map((property) => ('value' in property && Array.isArray(property.value) ? property.value.map(String) : []))
}
/** Each event or action the scan watches, with its own property conditions appended.
@@ -218,6 +218,7 @@ function topLevelPropertyGroups(scanner: ReplayScanner): EligibleFilterGroup[] {
byKind.set(singular, group)
}
return [...byKind.values()].map(({ singular, plural, values }) => ({
+ key: `property:${singular}`,
label: pluralize(values.length, singular, plural, false),
values,
}))
@@ -236,17 +237,23 @@ export function eligibleFilterGroups(
scanner: ReplayScanner,
{ experimentName, cohortNames }: { experimentName?: string; cohortNames?: Record<string, string> } = {}
): EligibleFilterGroup[] {
- const kinds: [singular: string, plural: string, values: string[]][] = [
- ['Experiment', 'Experiments', experimentValues(scanner, experimentName)],
- ['Page', 'Pages', pageValues(scanner)],
- ['Event', 'Events', namedQueryEntities(scanner, 'events')],
- ['Action', 'Actions', namedQueryEntities(scanner, 'actions')],
- ['Cohort', 'Cohorts', cohortValues(scanner, cohortNames)],
+ const kinds: [key: string, singular: string, plural: string, values: string[]][] = [
+ ['experiment', 'Experiment', 'Experiments', experimentValues(scanner, experimentName)],
+ ...pageValueLists(scanner).map((values, index): [string, string, string, string[]] => [
+ `page:${index}`,
+ 'Page',
+ 'Pages',
+ values,
+ ]),
+ ['event', 'Event', 'Events', namedQueryEntities(scanner, 'events')],
+ ['action', 'Action', 'Actions', namedQueryEntities(scanner, 'actions')],
+ ['cohort', 'Cohort', 'Cohorts', cohortValues(scanner, cohortNames)],
]
return [
...kinds
- .filter(([, , values]) => values.length > 0)
- .map(([singular, plural, values]) => ({
+ .filter(([, , , values]) => values.length > 0)
+ .map(([key, singular, plural, values]) => ({
+ key,
label: pluralize(values.length, singular, plural, false),
values,
})),
@@ -283,12 +290,20 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.E
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
+ const cohortNames = Object.fromEntries(
+ Object.entries(cohortsById).map(([id, cohort]) => [id, cohort?.name ?? `Cohort ${id}`])
+ )
const filterGroups = eligibleFilterGroups(scanner, {
experimentName: experimentContext?.experiment.name,
- cohortNames: Object.fromEntries(
- Object.entries(cohortsById).map(([id, cohort]) => [id, cohort?.name ?? `Cohort ${id}`])
- ),
+ cohortNames,
})
+ // Read against the form, so an addition the person removed by hand is not credited to the AI.
+ const currentFilterValues = new Set(filterGroups.flatMap((group) => group.values))
+ const aiAddedValues = goalDraft?.query_additions
+ ? eligibleFilterGroups({ query: goalDraft.query_additions } as ReplayScanner, { cohortNames })
+ .flatMap((group) => group.values)
+ .filter((value) => currentFilterValues.has(value))
+ : []
// The draft is still generating: show the page's shape so the wait reads as progress.
if (goalDraftLoading) {
@@ -362,7 +377,7 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.E
{filterGroups.length > 0 ? (
<div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3 gap-y-1 text-sm">
{filterGroups.map((group) => (
- <StatRow key={group.label} label={group.label}>
+ <StatRow key={group.key} label={group.label}>
<span className="flex flex-wrap gap-1">
{group.values.map((value) => (
<LemonSnack key={value} wrap>
@@ -376,6 +391,17 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.E
) : (
<div className="text-sm">Every recording (no filter)</div>
)}
+ {aiAddedValues.length > 0 ? (
+ <div className="flex flex-wrap items-center gap-1 text-xs text-secondary">
+ <IconSparkles className="text-ai" />
+ <span>PostHog AI added to your filters:</span>
+ {aiAddedValues.map((value) => (
+ <LemonSnack key={value} wrap>
+ {value}
+ </LemonSnack>
+ ))}
+ </div>
+ ) : null}
{scannerEstimateLoading ? (
<div className="flex items-center gap-2 text-sm text-muted">
<Spinner />
diff --git a/products/replay_vision/frontend/replay_scanners/replayFiltersScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayFiltersScannerLogic.ts
new file mode 100644
index 000000000000..b304582430ac
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/replayFiltersScannerLogic.ts
@@ -0,0 +1,243 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { combineUrl, router } from 'kea-router'
+import posthog from 'posthog-js'
+
+import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
+import { AI_CONSENT_PENDING_REDIRECT_TTL_MS } from 'scenes/settings/organization/aiConsentLogic'
+import { urls } from 'scenes/urls'
+
+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+
+import { visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { DEFAULT_GOAL_BUDGET, type GoalDraftSpend, type GoalSpendChoice, goalSpendChoice } from './replayScannerLogic'
+import type { ScannerHandoffFromFilters } from './scannerHandoffFromFilters'
+import { markScannerGoalDraftIntent } from './scannerHandoffIntent'
+
+export type ReplayFiltersCreditCap = 'free' | 'cap'
+
+// The draft API's limit for `monthly_credit_budget`.
+const MAX_CREDIT_CAP = 100_000_000
+
+// Pinned: the `placement` on the shared replay_vision_upsell_* events and the scanner's `entry_point`.
+export const REPLAY_FILTERS_ENTRY_POINT = 'replay_filters'
+
+function reportClicked(cta: 'open' | 'draft_with_ai' | 'set_up_manually', narrowsSessions?: boolean): void {
+ posthog.capture('replay_vision_upsell_clicked', {
+ placement: REPLAY_FILTERS_ENTRY_POINT,
+ cta,
+ narrows_sessions: narrowsSessions ?? null,
+ })
+}
+
+function manualWizardUrl(handoff: ScannerHandoffFromFilters): string {
+ return combineUrl(urls.replayVisionScannerConfigure('new'), {
+ ...handoff.searchParams,
+ entry_point: REPLAY_FILTERS_ENTRY_POINT,
+ }).url
+}
+
+function recordCrossSellIntent(): void {
+ void addProductIntentForCrossSell({
+ from: ProductKey.SESSION_REPLAY,
+ to: ProductKey.REPLAY_VISION,
+ intent_context: ProductIntentContext.SESSION_REPLAY_SAVE_FILTERS_AS_SCANNER,
+ })
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface replayFiltersScannerLogicValues {
+ freeCreditsLeft: number | null // visionQuotaLogic
+ budget: number | null
+ consentSpend: GoalDraftSpend | null
+ creditCap: ReplayFiltersCreditCap
+ draftInputDisabledReason: string | null
+ goal: string
+ popoverOpen: boolean
+ spendChoice: GoalSpendChoice
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface replayFiltersScannerLogicActions {
+ cancelConsent: () => {
+ value: true
+ }
+ confirmConsent: (
+ handoff: ScannerHandoffFromFilters,
+ spend: GoalDraftSpend
+ ) => {
+ handoff: ScannerHandoffFromFilters
+ spend: GoalDraftSpend
+ }
+ draftWithAi: (
+ handoff: ScannerHandoffFromFilters,
+ spend?: GoalDraftSpend
+ ) => {
+ handoff: ScannerHandoffFromFilters
+ spend: GoalDraftSpend | undefined
+ }
+ requestConsent: (spend: GoalDraftSpend) => {
+ spend: GoalDraftSpend
+ }
+ setBudget: (budget: number | null) => {
+ budget: number | null
+ }
+ setCreditCap: (cap: ReplayFiltersCreditCap) => {
+ cap: ReplayFiltersCreditCap
+ }
+ setGoal: (goal: string) => {
+ goal: string
+ }
+ setPopoverOpen: (open: boolean) => {
+ open: boolean
+ }
+ setUpManually: (handoff: ScannerHandoffFromFilters) => {
+ handoff: ScannerHandoffFromFilters
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface replayFiltersScannerLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ spendChoice: (
+ creditCap: ReplayFiltersCreditCap,
+ budget: number | null,
+ freeCreditsLeft: number | null
+ ) => GoalSpendChoice
+ draftInputDisabledReason: (goal: string, spendChoice: GoalSpendChoice, budget: number | null) => string | null
+ }
+}
+
+export type replayFiltersScannerLogicType = MakeLogicType<
+ replayFiltersScannerLogicValues,
+ replayFiltersScannerLogicActions,
+ Record<string, any>,
+ replayFiltersScannerLogicMeta
+>
+
+export const replayFiltersScannerLogic = kea<replayFiltersScannerLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'replayFiltersScannerLogic']),
+ connect(() => ({ values: [visionQuotaLogic, ['freeCreditsLeft']] })),
+
+ actions({
+ setPopoverOpen: (open: boolean) => ({ open }),
+ setGoal: (goal: string) => ({ goal }),
+ setCreditCap: (cap: ReplayFiltersCreditCap) => ({ cap }),
+ setBudget: (budget: number | null) => ({ budget }),
+ draftWithAi: (handoff: ScannerHandoffFromFilters, spend?: GoalDraftSpend) => ({ handoff, spend }),
+ setUpManually: (handoff: ScannerHandoffFromFilters) => ({ handoff }),
+ requestConsent: (spend: GoalDraftSpend) => ({ spend }),
+ confirmConsent: (handoff: ScannerHandoffFromFilters, spend: GoalDraftSpend) => ({ handoff, spend }),
+ cancelConsent: true,
+ }),
+
+ reducers({
+ popoverOpen: [
+ false,
+ {
+ setPopoverOpen: (_, { open }) => open,
+ draftWithAi: () => false,
+ setUpManually: () => false,
+ },
+ ],
+ goal: [
+ '',
+ {
+ setGoal: (_, { goal }) => goal,
+ },
+ ],
+ // The spend chosen when consent was asked for, so a quota that loads meanwhile cannot change it.
+ consentSpend: [
+ null as GoalDraftSpend | null,
+ {
+ requestConsent: (_, { spend }) => spend,
+ cancelConsent: () => null,
+ setPopoverOpen: () => null,
+ draftWithAi: () => null,
+ },
+ ],
+ creditCap: [
+ 'free' as ReplayFiltersCreditCap,
+ {
+ setCreditCap: (_, { cap }) => cap,
+ },
+ ],
+ budget: [
+ DEFAULT_GOAL_BUDGET as number | null,
+ {
+ // A cleared number input emits NaN, which would otherwise serialize to null in the hand-off.
+ setBudget: (_, { budget }) => (budget != null && Number.isFinite(budget) ? budget : null),
+ },
+ ],
+ }),
+
+ selectors({
+ spendChoice: [
+ (s) => [s.creditCap, s.budget, s.freeCreditsLeft],
+ (
+ creditCap: ReplayFiltersCreditCap,
+ budget: number | null,
+ freeCreditsLeft: number | null
+ ): GoalSpendChoice => goalSpendChoice(creditCap === 'free' ? 'free' : 'budget', budget, freeCreditsLeft),
+ ],
+ draftInputDisabledReason: [
+ (s) => [s.goal, s.spendChoice, s.budget],
+ (goal: string, spendChoice: GoalSpendChoice, budget: number | null): string | null => {
+ if (!goal.trim()) {
+ return 'Say what the scanner should watch for or answer'
+ }
+ const capInRange = budget != null && Number.isInteger(budget) && budget >= 1 && budget <= MAX_CREDIT_CAP
+ if (!spendChoice.spend || (spendChoice.mode === 'budget' && !capInRange)) {
+ return 'Enter a monthly credit cap from 1 to 100,000,000 credits'
+ }
+ return null
+ },
+ ],
+ }),
+
+ listeners(({ values, actions }) => ({
+ setPopoverOpen: ({ open }) => {
+ if (open) {
+ reportClicked('open')
+ }
+ },
+ // Approving consent can trigger a full-page SSO reauthentication, which unloads the page before
+ // the draft starts. So the draft is stored once the person confirms, for as long as the consent
+ // flow waits to resume. Not earlier: a click in the consent dialog closes both popovers.
+ confirmConsent: ({ handoff, spend }) => {
+ const goal = values.goal.trim()
+ if (goal) {
+ markScannerGoalDraftIntent(
+ { goal, query: handoff.chosenQuery, spend, source: REPLAY_FILTERS_ENTRY_POINT },
+ { ttlMs: AI_CONSENT_PENDING_REDIRECT_TTL_MS }
+ )
+ }
+ },
+ draftWithAi: ({ handoff, spend: capturedSpend }) => {
+ const goal = values.goal.trim()
+ const spend = capturedSpend ?? values.spendChoice.spend
+ if (!goal || !spend) {
+ return
+ }
+ reportClicked('draft_with_ai', handoff.narrowsSessions)
+ recordCrossSellIntent()
+ const armed = markScannerGoalDraftIntent({
+ goal,
+ query: handoff.chosenQuery,
+ spend,
+ source: REPLAY_FILTERS_ENTRY_POINT,
+ })
+ if (!armed) {
+ // Without storage the wizard cannot receive the filters, so open it with them in the URL instead.
+ router.actions.push(manualWizardUrl(handoff))
+ return
+ }
+ actions.setGoal('')
+ router.actions.push(urls.replayVisionNewScanner())
+ },
+ setUpManually: ({ handoff }) => {
+ reportClicked('set_up_manually', handoff.narrowsSessions)
+ recordCrossSellIntent()
+ router.actions.push(manualWizardUrl(handoff))
+ },
+ })),
+])
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index c720d6d5ae58..0746f82cb889 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -12,12 +12,13 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
-import { NodeKind } from '~/queries/schema/schema-general'
+import { NodeKind, type RecordingsQuery } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { ScannerModelEnumApi } from '../generated/api.schemas'
import { parseCsvParam, parseNumericParam, parseSortParam } from '../utils/urlParams'
import { newScanner } from './newScanner'
+import { replayFiltersScannerLogic } from './replayFiltersScannerLogic'
import {
buildObservationListParams,
goalSpendChoice,
@@ -30,6 +31,7 @@ import {
} from './replayScannerLogic'
import { readScannerDraft, writeScannerDraft } from './scannerDraft'
import { scannerEditorSceneLogic } from './scannerEditorSceneLogic'
+import type { ScannerHandoffFromFilters } from './scannerHandoffFromFilters'
import {
consumeScannerHandoffIntent,
markScannerGoalDraftIntent,
@@ -553,7 +555,7 @@ describe('replayScannerLogic', () => {
await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()
expect(draftSpy).not.toHaveBeenCalled()
- markScannerGoalDraftIntent('tell me what to watch')
+ markScannerGoalDraftIntent({ goal: 'tell me what to watch' })
router.actions.push(urls.replayVisionScannerGoal('new'))
await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()
expect(logic.values.goalDraftInput).toEqual('tell me what to watch')
@@ -563,10 +565,87 @@ describe('replayScannerLogic', () => {
expect(draftSpy).toHaveBeenCalledTimes(1)
})
+ it('a draft intent from the replay filters drafts against its query and spend, and a retry keeps the query', async () => {
+ const captureSpy = jest.spyOn(posthog, 'capture')
+ const query: RecordingsQuery = {
+ kind: NodeKind.RecordingsQuery,
+ filter_test_accounts: true,
+ experiment_exposure: { experiment_id: 11, variant: 'test' },
+ }
+ markScannerGoalDraftIntent({
+ goal: 'find rage clicks',
+ query,
+ spend: { monthlyCreditBudget: 900 },
+ source: 'replay_filters',
+ })
+ router.actions.push(urls.replayVisionScannerGoal('new'))
+ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()
+ await expectLogic(logic, () =>
+ logic.actions.draftScannerFromGoal({ goal: 'find rage clicks', spend: { monthlyCreditBudget: 900 } })
+ ).toFinishAllListeners()
+
+ const bodies = await Promise.all(
+ (draftSpy.mock.calls as unknown as [{ request: Request }][]).map(([{ request }]) => request.json())
+ )
+ expect(bodies).toEqual([
+ expect.objectContaining({ query, monthly_credit_budget: 900 }),
+ expect.objectContaining({ query }),
+ ])
+ expect(captureSpy).toHaveBeenCalledWith(
+ 'replay_vision_scanner_creation_started',
+ expect.objectContaining({ creation_method: 'ai', entry_point: 'replay_filters' })
+ )
+ })
+
+ // A click in the consent dialog closes both popovers before the confirm button's own click.
+ it.each([
+ ['once the person confirms, even after the dialog closes the popovers', true, 1],
+ ['never, when the person dismisses before confirming', false, 0],
+ ])('a filters draft that waits on AI consent starts %s', async (_, confirmed, drafts) => {
+ const popover = replayFiltersScannerLogic()
+ popover.mount()
+ const handoff = { chosenQuery: { kind: NodeKind.RecordingsQuery } } as ScannerHandoffFromFilters
+ popover.actions.setGoal('find rage clicks')
+ popover.actions.requestConsent({ freeOnly: true })
+ popover.actions.setPopoverOpen(false)
+ popover.actions.cancelConsent()
+ if (confirmed) {
+ popover.actions.confirmConsent(handoff, { freeOnly: true })
+ }
+ // Past the plain intent's lifetime, as after an SSO reauthentication round trip.
+ const clock = jest.spyOn(Date, 'now').mockReturnValue(Date.now() + 5 * 60 * 1000)
+ try {
+ router.actions.push(urls.replayVisionScannerGoal('new'))
+ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()
+ } finally {
+ clock.mockRestore()
+ }
+
+ expect(draftSpy).toHaveBeenCalledTimes(drafts)
+ popover.unmount()
+ })
+
+ // A value the create API rejects would block the save, so it is dropped rather than sent.
+ it.each([
+ ['a valid slug', 'replay_upsell_player', 'replay_upsell_player'],
+ ['an invalid value', 'Replay-Upsell', null],
+ ])('an ?entry_point= param with %s reaches the creation-started event', async (_, param, expected) => {
+ const captureSpy = jest.spyOn(posthog, 'capture')
+ router.actions.push(urls.replayVisionScannerGoal('new'), { entry_point: param })
+ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()
+ logic.actions.startFromScratch()
+
+ expect(captureSpy).toHaveBeenCalledWith(
+ 'replay_vision_scanner_creation_started',
+ expect.objectContaining({ creation_method: 'scratch', entry_point: expected })
+ )
+ expect(router.values.searchParams.entry_point).toBeUndefined()
+ })
+
it('a draft intent older than a minute is dropped', async () => {
const now = Date.now()
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(now)
- markScannerGoalDraftIntent('tell me what to watch')
+ markScannerGoalDraftIntent({ goal: 'tell me what to watch' })
nowSpy.mockReturnValue(now + 61_000)
router.actions.push(urls.replayVisionScannerGoal('new'))
await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()
@@ -1901,6 +1980,7 @@ describe('replayScannerLogic', () => {
expect(captureSpy).toHaveBeenCalledWith('replay_vision_scanner_creation_started', {
creation_method: 'scratch',
template_key: null,
+ entry_point: null,
})
})
@@ -1921,6 +2001,8 @@ describe('replayScannerLogic', () => {
expect(captureSpy).toHaveBeenCalledWith('replay_vision_scanner_creation_started', {
creation_method: 'ai',
template_key: reportedKey,
+ entry_point: null,
+ query_pinned: false,
spend_mode: spendMode,
goal_length: 'find users who get stuck'.length,
})
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index c36cf757d1b7..43c2279385e9 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -439,7 +439,7 @@ export type CreditLimitUnit = 'credits' | 'observations'
export type GoalSpendMode = 'free' | 'budget'
// Prefills the typed budget at the free monthly credits (FREE_TIER_MONTHLY_CREDITS in backend/billing.py).
-const DEFAULT_GOAL_BUDGET = 2500
+export const DEFAULT_GOAL_BUDGET = 2500
/** The spend a goal draft is sized to. The server sizes a free-only draft to the free credits it can spend. */
export type GoalDraftSpend = { freeOnly: true } | { monthlyCreditBudget: number }
@@ -451,6 +451,11 @@ export interface GoalDraftRequest {
experimentId?: number
}
+/** Kept only when it is a slug the create API accepts, so a telemetry value can never block a save. */
+function scannerEntryPoint(value: unknown): string | null {
+ return typeof value === 'string' && /^[a-z0-9_]{1,64}$/.test(value) ? value : null
+}
+
export interface GoalSpendChoice {
mode: GoalSpendMode
spend: GoalDraftSpend | null
@@ -530,6 +535,7 @@ export interface replayScannerLogicValues {
creditLimitState: CreditLimitState
creditLimitUnit: CreditLimitUnit
durationValidationError: string | null
+ entryPoint: string | null
estimateRequestVersion: number
experimentContext: ExperimentScannerContext | null
experimentContextLinked: boolean
@@ -537,6 +543,7 @@ export interface replayScannerLogicValues {
goalDraft: DraftScannerResponseApi | null
goalDraftInput: string
goalDraftLoading: boolean
+ goalDraftQuery: RecordingsQuery | null
goalExperiment: ExperimentBasicApi | null
goalSpendMode: GoalSpendMode
hasActiveObservationFilters: boolean
@@ -786,6 +793,9 @@ export interface replayScannerLogicActions {
setCreditLimitUnit: (unit: CreditLimitUnit) => {
unit: CreditLimitUnit
}
+ setEntryPoint: (entryPoint: string | null) => {
+ entryPoint: string | null
+ }
setExperimentContext: (context: ExperimentScannerContext | null) => {
context: ExperimentScannerContext | null
}
@@ -798,6 +808,9 @@ export interface replayScannerLogicActions {
setGoalDraftInput: (goal: string) => {
goal: string
}
+ setGoalDraftQuery: (query: RecordingsQuery | null) => {
+ query: RecordingsQuery | null
+ }
setGoalExperiment: (experiment: ExperimentBasicApi | null) => {
experiment: ExperimentBasicApi | null
}
@@ -1051,6 +1064,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
setGoalExperiment: (experiment: ExperimentBasicApi | null) => ({ experiment }),
setGoalBudgetInput: (budget: number | null) => ({ budget }),
setGoalSpendMode: (mode: GoalSpendMode) => ({ mode }),
+ setGoalDraftQuery: (query: RecordingsQuery | null) => ({ query }),
+ setEntryPoint: (entryPoint: string | null) => ({ entryPoint }),
loadObservations: (background = false) => ({ background }),
loadObservationsSuccess: (observations: ReplayObservationApi[], total: number) => ({ observations, total }),
loadObservationsFailure: true,
@@ -1200,7 +1215,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// about that, so the update payload below leaves it out.
const response = await visionScannersCreate(
String(teamId),
- scannerToApiBody({ ...body, creation_method: values.creationMethod })
+ scannerToApiBody({
+ ...body,
+ creation_method: values.creationMethod,
+ entry_point: values.entryPoint,
+ })
)
actions.scannerSaved(scanner)
leaveScannerEditor(props.id, urls.replayVision(response.id))
@@ -1292,6 +1311,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
? { free_only: true }
: { monthly_credit_budget: spend.monthlyCreditBudget }),
experiment_id: experimentId,
+ ...(values.goalDraftQuery ? { query: values.goalDraftQuery } : {}),
})
},
},
@@ -1349,6 +1369,25 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
setGoalSpendMode: (_, { mode }) => mode,
},
],
+ // Kept through a failed draft, so a retry from the goal page still watches the chosen recordings.
+ goalDraftQuery: [
+ null as RecordingsQuery | null,
+ {
+ setGoalDraftQuery: (_, { query }) => query,
+ startFromScratch: () => null,
+ discardScannerDraft: () => null,
+ scannerSaved: () => null,
+ },
+ ],
+ // Kept through a path switch, because a person who builds by hand after the AI flow still started there.
+ entryPoint: [
+ null as string | null,
+ {
+ setEntryPoint: (_, { entryPoint }) => entryPoint,
+ discardScannerDraft: () => null,
+ scannerSaved: () => null,
+ },
+ ],
// Starting from scratch replaces the drafted form, so its rationale no longer describes the config.
goalDraft: [
null as DraftScannerResponseApi | null,
@@ -2027,6 +2066,12 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// unrelated wizard visit.
const handoff = consumeScannerHandoffIntent()
const armedGoal = consumeScannerGoalDraftIntent()
+ const entryPoint = scannerEntryPoint(
+ handoff?.source ?? armedGoal?.source ?? router.values.searchParams.entry_point
+ )
+ if (entryPoint) {
+ actions.setEntryPoint(entryPoint)
+ }
// Prefill precedence: a cross-product hand-off (a whole scanner, armed by an
// in-tab click moments before navigation), then an experiment deep link, then
// an explicit ?filters= query (both carry fully built state), then a saved
@@ -2049,6 +2094,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
if ('filters' in nextParams) {
delete nextParams.filters
}
+ if ('entry_point' in nextParams) {
+ delete nextParams.entry_point
+ }
if (Object.keys(nextParams).length !== Object.keys(router.values.searchParams).length) {
router.actions.replace(router.values.location.pathname, nextParams, router.values.hashParams)
}
@@ -2057,6 +2105,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
creation_method: 'handoff',
template_key: null,
source: handoff.source,
+ entry_point: values.entryPoint,
})
// Same fresh-intent rule as the experiment deep link: the hand-off was
// armed by a click moments before navigation, so it outranks a saved
@@ -2148,15 +2197,30 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
const consented = !!organizationLogic.values.currentOrganization?.is_ai_data_processing_approved
if (armedGoal && !hasFiltersPrefill && consented && !values.goalDraftLoading) {
- actions.setGoalDraftInput(armedGoal)
- const { spend } = goalSpendChoice(
- values.goalSpendMode,
- values.goalBudgetInput,
- visionQuotaLogic.findMounted()?.values.freeCreditsLeft ?? null
- )
+ actions.setGoalDraftInput(armedGoal.goal)
+ if (armedGoal.query) {
+ actions.setGoalDraftQuery(armedGoal.query)
+ }
+ if (armedGoal.spend) {
+ // Mirrored into the goal page's controls, so a failed draft offers the same choice again.
+ actions.setGoalSpendMode('freeOnly' in armedGoal.spend ? 'free' : 'budget')
+ if ('monthlyCreditBudget' in armedGoal.spend) {
+ actions.setGoalBudgetInput(armedGoal.spend.monthlyCreditBudget)
+ }
+ }
+ const spend =
+ armedGoal.spend ??
+ goalSpendChoice(
+ values.goalSpendMode,
+ values.goalBudgetInput,
+ visionQuotaLogic.findMounted()?.values.freeCreditsLeft ?? null
+ ).spend
// With no budget to size it to, the goal stays in the box for the person to finish.
if (spend) {
- actions.draftScannerFromGoal({ goal: armedGoal, spend })
+ actions.draftScannerFromGoal({
+ goal: armedGoal.goal,
+ spend,
+ })
}
}
return
@@ -2301,6 +2365,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// Set when a starter wrote the goal and it was sent unedited, or when an experiment was picked,
// so the funnel can split typed goals from starter ones.
template_key: templateKey ?? null,
+ entry_point: values.entryPoint,
+ query_pinned: !!values.goalDraftQuery,
spend_mode: 'freeOnly' in spend ? 'free' : 'budget',
// The goal is customer text, so only its length is captured.
goal_length: goal.trim().length,
@@ -2426,6 +2492,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
posthog.capture('replay_vision_scanner_creation_started', {
creation_method: 'scratch',
template_key: null,
+ entry_point: values.entryPoint,
})
clearScannerDraft()
actions.setScannerDraftSavedAt(null)
diff --git a/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.test.ts b/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.test.ts
index 810fb5ca8d11..453752b122c8 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.test.ts
@@ -43,6 +43,13 @@ function handoffQuery(f: RecordingUniversalFilters): Record<string, any> {
return JSON.parse(scannerHandoffFromFilters(f).searchParams.filters)
}
+const COMMENT_SEARCH: UniversalFiltersGroupValue = {
+ type: PropertyFilterType.Recording,
+ key: 'comment_text',
+ value: 'checkout',
+ operator: PropertyOperator.IContains,
+}
+
describe('scannerHandoffFromFilters', () => {
// A scanner carrying session IDs is pinned to recordings that already exist, so it matches
// nothing ever while still looking healthy in the scanner list.
@@ -64,6 +71,15 @@ describe('scannerHandoffFromFilters', () => {
expect(JSON.parse(searchParams.filters)).not.toHaveProperty('experiment_exposure')
})
+ it('keeps experiment exposure in the query the AI draft gets', () => {
+ const handoff = scannerHandoffFromFilters(
+ filters({ values: [PAGEVIEW], experiment_exposure: { experiment_id: 42, variant: 'test' } })
+ )
+
+ expect(handoff.chosenQuery.experiment_exposure).toEqual({ experiment_id: 42, variant: 'test' })
+ expect(handoff.query).not.toHaveProperty('experiment_exposure')
+ })
+
it('omits the variant param when the filters cover every variant', () => {
const { searchParams } = scannerHandoffFromFilters(
filters({ values: [PAGEVIEW], experiment_exposure: { experiment_id: 42 } })
@@ -73,6 +89,15 @@ describe('scannerHandoffFromFilters', () => {
expect(searchParams).not.toHaveProperty('variant')
})
+ it('drops a comment search from the query and reports it', () => {
+ const handoff = scannerHandoffFromFilters(filters({ values: [PAGEVIEW, COMMENT_SEARCH] }))
+
+ expect(handoff.query.comment_text).toBeUndefined()
+ expect(JSON.parse(handoff.searchParams.filters).comment_text).toBeUndefined()
+ expect(handoff.droppedCommentSearch).toBe(true)
+ expect(handoff.narrowsSessions).toBe(true)
+ })
+
describe('narrowsSessions', () => {
// The replay list counts these as filters, but a scanner keeps none of them, so it watches every session.
it.each([
@@ -80,6 +105,7 @@ describe('scannerHandoffFromFilters', () => {
['only a date range', filters({ date_from: '-7d' })],
['only pinned session IDs', filters({ session_ids: ['abc-123'] })],
['only the default duration floor', filters({ duration: [defaultRecordingDurationFilter] })],
+ ['only a comment search', filters({ values: [COMMENT_SEARCH] })],
])('is false for %s', (_label, f) => {
expect(scannerHandoffFromFilters(f).narrowsSessions).toBe(false)
})
diff --git a/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.ts b/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.ts
index 5fbdddc07c04..15785bb67769 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.ts
@@ -1,17 +1,26 @@
+import { isCommentTextFilter } from 'lib/components/UniversalFilters/utils'
import { objectsEqual } from 'lib/utils/objects'
import { convertUniversalFiltersToRecordingsQuery } from 'scenes/session-recordings/filters/recordingsQueryConversions'
import { stripSessionIds } from 'scenes/session-recordings/playlist/playlistUtils'
import { defaultRecordingDurationFilter } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
import { filtersFromUniversalFilterGroups } from 'scenes/session-recordings/utils'
+import type { RecordingsQuery } from '~/queries/schema/schema-general'
import type { RecordingUniversalFilters } from '~/types'
-import { experimentScannerParams } from './experimentTargeting'
+import { type ExperimentScannerParams, experimentScannerParams } from './experimentTargeting'
/** The wizard hand-off for "create a scanner from these replay filters". */
export interface ScannerHandoffFromFilters {
/** Params for the new-scanner wizard URL: the encoded query, plus experiment targeting when the filters carry it. */
searchParams: Record<string, string>
+ query: RecordingsQuery
+ /** The filter as the person chose it, exposure included, which the AI draft turns into the scanner's experiment. */
+ chosenQuery: RecordingsQuery
+ /** Experiment exposure from the filters, which a scanner keeps as targeting rather than inside `query`. */
+ experiment: ExperimentScannerParams | null
+ pinnedSessionCount: number
+ droppedCommentSearch: boolean
/**
* Whether the resulting scanner would watch a subset of sessions rather than all of them.
*
@@ -38,24 +47,31 @@ export interface ScannerHandoffFromFilters {
* It becomes the wizard's experiment deep link instead, which builds the same experiment
* scanner the experiment's own entry point does.
* - The date range is dropped by the backend on save, because a scanner's schedule owns time.
+ * - Only the replay list API applies the comment search and "hide viewed recordings", so a scanner
+ * that kept them would watch more than the person chose. They are dropped here, where the person is told.
*/
export function scannerHandoffFromFilters(filters: RecordingUniversalFilters): ScannerHandoffFromFilters {
- const { experiment_exposure: exposure, ...query } = convertUniversalFiltersToRecordingsQuery(
- stripSessionIds(filters)
- )
+ const {
+ experiment_exposure: exposure,
+ comment_text: commentText,
+ hide_viewed_recordings: _hideViewedRecordings,
+ ...query
+ } = convertUniversalFiltersToRecordingsQuery(stripSessionIds(filters))
+
+ const experiment = exposure ? { experimentId: exposure.experiment_id, variantKey: exposure.variant ?? null } : null
return {
searchParams: {
filters: JSON.stringify(query),
- ...(exposure
- ? experimentScannerParams({
- experimentId: exposure.experiment_id,
- variantKey: exposure.variant ?? null,
- })
- : {}),
+ ...(experiment ? experimentScannerParams(experiment) : {}),
},
+ query,
+ chosenQuery: exposure ? { ...query, experiment_exposure: exposure } : query,
+ experiment,
+ pinnedSessionCount: filters.session_ids?.length ?? 0,
+ droppedCommentSearch: !!commentText,
narrowsSessions:
- filtersFromUniversalFilterGroups(filters).length > 0 ||
+ filtersFromUniversalFilterGroups(filters).some((filter) => !isCommentTextFilter(filter)) ||
// Every filter set carries a duration floor, so only one the user moved off the default
// counts as narrowing.
(filters.duration ?? []).some((predicate) => !objectsEqual(predicate, defaultRecordingDurationFilter)) ||
diff --git a/products/replay_vision/frontend/replay_scanners/scannerHandoffIntent.ts b/products/replay_vision/frontend/replay_scanners/scannerHandoffIntent.ts
index bb780c0f66d4..8ff1162485ef 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerHandoffIntent.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerHandoffIntent.ts
@@ -1,3 +1,6 @@
+import { NodeKind, type RecordingsQuery } from '~/queries/schema/schema-general'
+
+import type { GoalDraftSpend } from './replayScannerLogic'
import type { ScannerFormValues } from './types'
const SCANNER_HANDOFF_INTENT_KEY = 'replay-vision.scanner-handoff-intent'
@@ -54,18 +57,32 @@ export function consumeScannerHandoffIntent(): ScannerHandoffIntent | null {
const SCANNER_GOAL_DRAFT_INTENT_KEY = 'replay-vision.scanner-goal-draft-intent'
const SCANNER_GOAL_DRAFT_INTENT_TTL_MS = 60_000
+/** The query is the person's own filter, so the draft keeps it rather than picking its own sessions. */
+export interface ScannerGoalDraftIntent {
+ goal: string
+ query?: RecordingsQuery
+ spend?: GoalDraftSpend
+ source?: string
+}
+
/** One-shot "draft this goal now" from an in-app click, kept out of the URL so a link cannot
* start a draft on its own. Returns false when storage is unavailable. */
-export function markScannerGoalDraftIntent(goal: string): boolean {
+export function markScannerGoalDraftIntent(
+ intent: ScannerGoalDraftIntent,
+ { ttlMs = SCANNER_GOAL_DRAFT_INTENT_TTL_MS }: { ttlMs?: number } = {}
+): boolean {
try {
- sessionStorage.setItem(SCANNER_GOAL_DRAFT_INTENT_KEY, JSON.stringify({ goal, at: Date.now() }))
+ sessionStorage.setItem(
+ SCANNER_GOAL_DRAFT_INTENT_KEY,
+ JSON.stringify({ ...intent, expiresAt: Date.now() + ttlMs })
+ )
return true
} catch {
return false
}
}
-export function consumeScannerGoalDraftIntent(): string | null {
+export function consumeScannerGoalDraftIntent(): ScannerGoalDraftIntent | null {
try {
const raw = sessionStorage.getItem(SCANNER_GOAL_DRAFT_INTENT_KEY)
sessionStorage.removeItem(SCANNER_GOAL_DRAFT_INTENT_KEY)
@@ -73,14 +90,33 @@ export function consumeScannerGoalDraftIntent(): string | null {
return null
}
const parsed = JSON.parse(raw)
- if (typeof parsed?.goal !== 'string' || typeof parsed.at !== 'number') {
+ if (typeof parsed?.goal !== 'string' || typeof parsed.expiresAt !== 'number') {
+ return null
+ }
+ if (Date.now() > parsed.expiresAt) {
return null
}
- if (Date.now() - parsed.at > SCANNER_GOAL_DRAFT_INTENT_TTL_MS) {
+ const goal = parsed.goal.trim()
+ if (!goal) {
return null
}
- return parsed.goal.trim() || null
+ return {
+ goal,
+ query: parsed.query?.kind === NodeKind.RecordingsQuery ? parsed.query : undefined,
+ spend: isGoalDraftSpend(parsed.spend) ? parsed.spend : undefined,
+ source: typeof parsed.source === 'string' ? parsed.source : undefined,
+ }
} catch {
return null
}
}
+
+function isGoalDraftSpend(value: unknown): value is GoalDraftSpend {
+ if (typeof value !== 'object' || value === null) {
+ return false
+ }
+ return (
+ ('freeOnly' in value && value.freeOnly === true) ||
+ ('monthlyCreditBudget' in value && typeof value.monthlyCreditBudget === 'number')
+ )
+}