:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(error-tracking): add replay vision scanner cross-sell button (#99492)
Kim Svatos Duganedfd9631ce99
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex bb884442fe47..d768a2b441d6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7444,6 +7444,10 @@ snapshots:hash: v1.k794b7964.361c63d8098b60ca1bbf69206dc8f6711320146663aaf32dbd6651168a0b600b.dMsSmC7-kkmsg2uY_UCUtBk-2KP8U8EC-CgTQBwgCkEscenes-app-errortracking--group-page-with-self-driving--light:hash: v1.k794b7964.4c24d565a6a126a64761040eb44a64d5a689fc04a8b566ccc5410147c19451fc.wuQskHSi8SlMXfFZuza565EKQMIw1RhLM-1UCclFPJ8+ scenes-app-errortracking--group-page-with-vision-cross-sell--dark:+ hash: v1.k794b7964.84a773b4bbffa53723bd2d81dec3a213688635074715adcce52c0d60e9cace91.QoTzJjfl11h7SEPNyPxaVVpJjPPoKIu1fs2SmOCTlwI+ scenes-app-errortracking--group-page-with-vision-cross-sell--light:+ hash: v1.k794b7964.c8919d61e8bc3abb40cbadc55b5fa92b234cda3008c026d151f8f76f6a663150.7ahPDYahlm5Dxq8Rgxciz4yNliVI31j_IQsMLBMYNhMscenes-app-errortracking--insights-page--dark:hash: v1.k794b7964.547ba7d50edff3d4fd57c33937b1536edb9837c5c34fd57543b29a5fb257e848.V99ai7csLzzA-J4mPePBh5GIyIie_ulJCWMMU7bfioEscenes-app-errortracking--insights-page--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 5ac971d32e74..d4df06403a21 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -533,6 +533,7 @@ export const FEATURE_FLAGS = {USER_INTERVIEWS: 'user-interviews', // owner: @Twixes @jurajmajerikUX_HIDE_PROJECT_NOTICE: 'ux-hide-project-notice', // owner: #team-platform-ux, hides the project notice banner across all scenesUX_REMOVE_SIDEPANEL: 'ux-remove-sidepanel', // owner: #team-surveys+ VISION_ENTRYPOINT_ERROR_TRACKING: 'vision-entrypoint-error-tracking', // owner: #team-replay, cross-sell entry point from the error tracking issue recording tabVISION_ENTRYPOINT_EXPERIMENTS: 'vision-entrypoint-experiments', // owner: #team-replay, cross-sell entry points from experimentsVISION_ENTRYPOINT_REPLAY_FILTERS: 'vision-entrypoint-replay-filters', // owner: #team-replay, cross-sell entry point from the replay filters panelVISION_GOAL_BASED_CREATION_FLOW: 'vision-goal-based-creation-flow', // owner: #team-replay multivariate=control,test — gate on === 'test'; a truthy check turns on for control toodiff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 2a46ba00a8a5..d669cb9598c1 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -39942,6 +39942,7 @@"error_tracking_issue_sorting","error_tracking_docs_viewed","error_tracking_issue_explained",+ "error_tracking_scan_with_vision","llm_analytics_viewed","llm_analytics_trace_viewed","llm_analytics_docs_viewed",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex d8521febca36..6b79d2eeb4be 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -10213,6 +10213,7 @@ export enum ProductIntentContext {ERROR_TRACKING_ISSUE_SORTING = 'error_tracking_issue_sorting',ERROR_TRACKING_DOCS_VIEWED = 'error_tracking_docs_viewed',ERROR_TRACKING_ISSUE_EXPLAINED = 'error_tracking_issue_explained',+ ERROR_TRACKING_SCAN_WITH_VISION = 'error_tracking_scan_with_vision',// LLM AnalyticsLLM_ANALYTICS_VIEWED = 'llm_analytics_viewed',diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 3513c23f50b8..f022836fb8bd 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3603,6 +3603,7 @@ class ProductIntentContext(StrEnum):ERROR_TRACKING_ISSUE_SORTING = "error_tracking_issue_sorting"ERROR_TRACKING_DOCS_VIEWED = "error_tracking_docs_viewed"ERROR_TRACKING_ISSUE_EXPLAINED = "error_tracking_issue_explained"+ ERROR_TRACKING_SCAN_WITH_VISION = "error_tracking_scan_with_vision"LLM_ANALYTICS_VIEWED = "llm_analytics_viewed"LLM_ANALYTICS_TRACE_VIEWED = "llm_analytics_trace_viewed"LLM_ANALYTICS_DOCS_VIEWED = "llm_analytics_docs_viewed"diff --git a/products/error_tracking/frontend/ErrorTracking.stories.tsx b/products/error_tracking/frontend/ErrorTracking.stories.tsxindex 2d485aaf85ab..00098e0a38fb 100644--- a/products/error_tracking/frontend/ErrorTracking.stories.tsx+++ b/products/error_tracking/frontend/ErrorTracking.stories.tsx@@ -743,6 +743,14 @@ export const GroupPage: Story = {parameters: { pageUrl: urls.errorTrackingIssue(ISSUE_ID) },}+export const GroupPageWithVisionCrossSell: Story = {+ name: 'Issue scene with Replay vision cross-sell',+ parameters: {+ pageUrl: urls.errorTrackingIssue(ISSUE_ID),+ featureFlags: [FEATURE_FLAGS.VISION_ENTRYPOINT_ERROR_TRACKING],+ },+}+export const GroupPageManyAssignees: Story = {name: 'Issue scene with many assignees',parameters: { pageUrl: urls.errorTrackingIssue(ISSUE_ID) },diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene.tsxindex 842d8b2b4380..9c25b313fdd5 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene.tsx@@ -2,10 +2,11 @@ import '../ErrorTrackingIssueScene/ErrorTrackingIssueScene.scss'import clsx from 'clsx'import { BindLogic, useActions, useValues } from 'kea'+import { router } from 'kea-router'import posthog from 'posthog-js'-import { useEffect, useRef } from 'react'+import { useCallback, useEffect, useRef } from 'react'-import { IconRewindPlay, IconX } from '@posthog/icons'+import { IconChevronDown, IconRewindPlay, IconSparkles, IconX } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'@@ -14,16 +15,26 @@ import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLimport { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { useWindowSize } from 'lib/hooks/useWindowSize'-import { Button, ButtonGroup } from 'lib/ui/quill'+import {+ Button,+ ButtonGroup,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from 'lib/ui/quill'import { newInternalTab } from 'lib/utils/newInternalTab'+import { addProductIntentForCrossSell } from 'lib/utils/product-intents'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { SceneMenuBar, SceneMenuBarItem, SceneMenuBarMenu } from '~/layout/scenes/components/SceneMenuBar'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { ReplayTabs } from '~/types'import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { markScannerHandoffIntent } from 'products/replay_vision/frontend/replay_scanners/scannerHandoffIntent'import { PostHogSDKIssueBanner } from '../../components/Banners/PostHogSDKIssueBanner'import { miniBreakdownsLogic } from '../../components/Breakdowns/miniBreakdownsLogic'@@ -41,7 +52,7 @@ import { IssueStatusSelect } from '../../components/IssueStatusSelect'import { ErrorTrackingSetupPrompt } from '../../components/SetupPrompt/SetupPrompt'import { StyleVariables } from '../../components/StyleVariables'import { useErrorTagRenderer } from '../../hooks/use-error-tag-renderer'-import { getIssueReplayDateRange, getIssueReplayFilterGroup } from '../../utils'+import { getIssueReplayDateRange, getIssueReplayFilterGroup, issueVisionScannerHandoff } from '../../utils'import { ErrorTrackingIssueSceneLogicProps, errorTrackingIssueSceneLogic } from './errorTrackingIssueSceneLogic'import { IssueEventsPanel } from './IssueEventsPanel'import { LinkedReports } from './LinkedReports'@@ -64,6 +75,50 @@ export function ErrorTrackingIssueScene(): JSX.Element {const isMobile = isWindowLessThan('md')const sceneMenuBarEnabled = useFeatureFlag('SCENE_MENU_BAR')const hasIssueSplitting = useFeatureFlag('ERROR_TRACKING_ISSUE_SPLITTING')+ const visionCrossSellEnabled = useFeatureFlag('VISION_ENTRYPOINT_ERROR_TRACKING')++ // Jump to the session replay list filtered to this issue. Captured so we can measure how often+ // people watch recordings themselves, the baseline the Replay vision cross-sell is weighed against.+ // Named to match the sibling 'viewed recordings from experiment' / 'from feature flag' events, so+ // all three cross-product entry points compare in one breakdown.+ const openRecordings = useCallback(+ (source: 'header' | 'menubar'): void => {+ posthog.capture('viewed recordings from error tracking', { issue_id: issueId, source })+ newInternalTab(+ urls.replay(ReplayTabs.Home, {+ ...getIssueReplayDateRange(+ issue?.first_seen,+ lastSeen,+ selectedEvent?.timestamp ?? initialEventTimestamp+ ),+ filter_group: getIssueReplayFilterGroup(issueId),+ })+ )+ },+ [issueId, issue?.first_seen, lastSeen, selectedEvent?.timestamp, initialEventTimestamp]+ )++ // Prefill a Replay vision scanner scoped to this issue and open the wizard on its review-and-create+ // overview. The overview blocks creation when no recordings match, so a sessionless issue can't+ // launch a scanner that never runs.+ const setUpVisionScanner = useCallback((): void => {+ if (!issue?.name) {+ return+ }+ markScannerHandoffIntent(+ issueVisionScannerHandoff(+ issueId,+ issue.name,+ getIssueReplayDateRange(issue.first_seen, lastSeen, selectedEvent?.timestamp ?? initialEventTimestamp)+ )+ )+ void addProductIntentForCrossSell({+ from: ProductKey.ERROR_TRACKING,+ to: ProductKey.REPLAY_VISION,+ intent_context: ProductIntentContext.ERROR_TRACKING_SCAN_WITH_VISION,+ })+ router.actions.push(urls.replayVisionScannerOverview('new'))+ }, [issueId, issue?.name, issue?.first_seen, lastSeen, selectedEvent?.timestamp, initialEventTimestamp])useAttachedContext(issueIdValid ? [{ type: 'error_tracking_issue', key: issueId, label: issue?.name ?? undefined }] : null@@ -111,22 +166,21 @@ export function ErrorTrackingIssueScene(): JSX.Element {</SceneMenuBarMenu><SceneMenuBarMenu label="View" dataAttr="issue-menubar-view"><SceneMenuBarItem- onClick={() => {- const url = urls.replay(ReplayTabs.Home, {- ...getIssueReplayDateRange(- issue.first_seen,- lastSeen,- selectedEvent?.timestamp ?? initialEventTimestamp- ),- filter_group: getIssueReplayFilterGroup(issue.id),- })- newInternalTab(url)- }}+ onClick={() => openRecordings('menubar')}data-attr="issue-menubar-view-recordings"><IconRewindPlay />View recordings</SceneMenuBarItem>+ {visionCrossSellEnabled && (+ <SceneMenuBarItem+ onClick={setUpVisionScanner}+ data-attr="issue-menubar-scan-with-vision"+ >+ <IconSparkles className="text-ai" />+ Set up a scanner to watch these+ </SceneMenuBarItem>+ )}</SceneMenuBarMenu></SceneMenuBar>)}@@ -163,24 +217,52 @@ export function ErrorTrackingIssueScene(): JSX.Element {disabled={issue.status != 'active'}/></ButtonGroup>- <Button- variant="outline"- onClick={() => {- const url = urls.replay(ReplayTabs.Home, {- ...getIssueReplayDateRange(- issue.first_seen,- lastSeen,- selectedEvent?.timestamp ?? initialEventTimestamp- ),- filter_group: getIssueReplayFilterGroup(issue.id),- })- newInternalTab(url)- }}- data-attr="error-tracking-issue-view-recordings"- >- View recordings- <IconRewindPlay />- </Button>+ {visionCrossSellEnabled ? (+ <ButtonGroup>+ <Button+ variant="outline"+ onClick={() => openRecordings('header')}+ data-attr="error-tracking-issue-view-recordings"+ >+ View recordings+ <IconRewindPlay />+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ size="icon"+ aria-label="More recording options"+ />+ }+ >+ <IconChevronDown />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="w-auto min-w-56"+ >+ <DropdownMenuItem+ onClick={setUpVisionScanner}+ data-attr="error-tracking-scan-with-vision"+ >+ <IconSparkles className="text-ai" />+ Set up a scanner to watch these+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </ButtonGroup>+ ) : (+ <Button+ variant="outline"+ onClick={() => openRecordings('header')}+ data-attr="error-tracking-issue-view-recordings"+ >+ View recordings+ <IconRewindPlay />+ </Button>+ )}<IssueStatusButton status={issue.status} onChange={updateStatus} /></div>)diff --git a/products/error_tracking/frontend/utils.test.ts b/products/error_tracking/frontend/utils.test.tsindex 4dcda97f1c10..2d84e770d426 100644--- a/products/error_tracking/frontend/utils.test.ts+++ b/products/error_tracking/frontend/utils.test.ts@@ -7,6 +7,7 @@ import {generateDateRangeLabel,getIssueReplayDateRange,getIssueReplayFilterGroup,+ issueVisionScannerHandoff,mergeIssues,sourceDisplay,} from './utils'@@ -261,6 +262,54 @@ describe('getIssueReplayFilterGroup', () => {],})})++ // The label rides in a HogQL `-- comment`, which ends at a line terminator. The issue name is+ // attacker-influenced, so a newline in it must not break out of the comment and inject a live+ // condition that widens the scanner beyond this issue.+ it('strips line terminators from the label so it cannot break out of the HogQL comment', () => {+ const group = getIssueReplayFilterGroup('issue-uuid', 'TypeError\n OR 1 = 1')+ const key = (group.values[0] as any).values[0].properties[0].key as string++ expect(key).not.toMatch(/[\r\n]/)+ expect(key).toEqual("issue_id = 'issue-uuid' -- TypeError OR 1 = 1")+ })+})++describe('issueVisionScannerHandoff', () => {+ it('builds a summarizer whose query keeps the issue scoping', () => {+ const handoff = issueVisionScannerHandoff('issue-uuid', 'TypeError: x is not a function', {+ date_from: '2024-01-01T00:00:00.000Z',+ date_to: '2024-01-02T00:00:00.000Z',+ })++ expect(handoff.source).toEqual('error_tracking')+ expect(handoff.scanner).toMatchObject({+ name: 'Error tracking: TypeError: x is not a function',+ scanner_type: 'summarizer',+ sampling_rate: 1.0,+ credit_limit: 5000,+ credit_limit_enabled: true,+ })+ expect(handoff.scanner.scanner_config?.prompt).toContain('"TypeError: x is not a function"')+ // Without the issue_id filter on $exception events the scanner silently watches every session.+ // The HogQL `-- comment` carries the error name so the scanner preview renders the condition+ // as the error rather than an opaque `issue_id = '<uuid>'`; it's stripped before the query runs.+ expect(handoff.scanner.query).toMatchObject({+ kind: 'RecordingsQuery',+ date_from: '2024-01-01T00:00:00.000Z',+ events: [+ expect.objectContaining({+ id: '$exception',+ properties: [+ {+ key: "issue_id = 'issue-uuid' -- TypeError: x is not a function",+ type: PropertyFilterType.HogQL,+ },+ ],+ }),+ ],+ })+ })})describe('sourceDisplay', () => {diff --git a/products/error_tracking/frontend/utils.ts b/products/error_tracking/frontend/utils.tsindex a43bc324d7fb..c2c7dd5d8230 100644--- a/products/error_tracking/frontend/utils.ts+++ b/products/error_tracking/frontend/utils.ts@@ -8,6 +8,7 @@ import { Dayjs, dayjs } from 'lib/dayjs'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { componentsToDayJs, dateStringToComponents, dateStringToDayJs, isStringDateRegex } from 'lib/utils/dateFilters'import { Params } from 'scenes/sceneTypes'+import { convertUniversalFiltersToRecordingsQuery } from 'scenes/session-recordings/filters/recordingsQueryConversions'import { DateRange, ErrorTrackingIssue } from '~/queries/schema/schema-general'import { escapeHogQLString } from '~/queries/utils'@@ -19,6 +20,8 @@ import {type UniversalFiltersGroup,} from '~/types'+import type { ScannerHandoffIntent } from 'products/replay_vision/frontend/replay_scanners/scannerHandoffIntent'+/** Reason error tracking write actions are disabled, or null when the user has editor access. */export function errorTrackingEditAccessDisabledReason(): string | null {return getAccessControlDisabledReason(AccessControlResourceType.ErrorTracking, AccessControlLevel.Editor)@@ -139,7 +142,16 @@ export function getIssueReplayDateRange(}}-export function getIssueReplayFilterGroup(issueId: string): UniversalFiltersGroup {+export function getIssueReplayFilterGroup(issueId: string, issueLabel?: string): UniversalFiltersGroup {+ // A HogQL `-- comment` is stripped before the query runs, so it never changes matching, but the+ // filter UI renders the condition by its comment. Pass the error name so a preview shows+ // "$exception where <error>" instead of a raw, opaque `issue_id = '<uuid>'`.+ //+ // The name is attacker-influenced (an app can throw an exception with any name), and a HogQL line+ // comment runs only to the next CR/LF. A line terminator in the name would end the comment and let+ // the rest run as a live condition, widening the scanner past this issue, so strip line terminators+ // before embedding. The label is display-only, so collapsing them to a space loses nothing.+ const comment = issueLabel ? ` -- ${issueLabel.replace(/[\r\n]/g, ' ')}` : ''return {type: FilterLogicalOperator.And,values: [@@ -152,7 +164,7 @@ export function getIssueReplayFilterGroup(issueId: string): UniversalFiltersGroutype: 'events',properties: [{- key: `issue_id = ${escapeHogQLString(issueId)}`,+ key: `issue_id = ${escapeHogQLString(issueId)}${comment}`,type: PropertyFilterType.HogQL,},],@@ -163,6 +175,50 @@ export function getIssueReplayFilterGroup(issueId: string): UniversalFiltersGrou}}+function issueVisionScannerPrompt(issueName: string): string {+ return [+ `Watch each recording to understand what the user experienced around the error "${issueName}". For each session, describe:`,+ '- What the user was trying to do right before the error',+ '- What they saw when it happened: a broken screen, an error message, or nothing visible',+ '- How they reacted: retried, refreshed, rage-clicked, or left',+ '- Whether they recovered and finished, or gave up',+ ].join('\n')+}++/** The "scan this error's recordings" cross-sell: a Replay vision scanner prefilled to watch+ * sessions that hit this issue and summarize what users experienced around the error. */+export function issueVisionScannerHandoff(+ issueId: string,+ issueName: string,+ dateRange: DateRange+): ScannerHandoffIntent {+ return {+ source: 'error_tracking',+ scanner: {+ name: `Error tracking: ${issueName}`,+ description: 'Summarizes what users experienced in sessions that hit this error.',+ scanner_type: 'summarizer',+ scanner_config: { prompt: issueVisionScannerPrompt(issueName), length: 'medium' },+ // The date range rides along like the replay filters entry point's does; the backend+ // drops it on save because the scanner's schedule owns time. The error name is passed as+ // the issue filter's label so the scanner's eligible-recordings preview reads+ // "$exception where <error>" instead of matching every exception session.+ query: convertUniversalFiltersToRecordingsQuery({+ ...dateRange,+ duration: [],+ filter_group: getIssueReplayFilterGroup(issueId, issueName),+ }),+ // Error-scoped queries match few sessions, so scan them all rather than starting at+ // the wizard's narrow default rate.+ sampling_rate: 1.0,+ sampling_mode: 'balanced',+ // 5,000 credits is $50 (1 credit = $0.01), the anchor the goal-based flow suggests.+ credit_limit: 5000,+ credit_limit_enabled: true,+ },+ }+}+const customOptions: Record<string, string> = {dStart: 'Today', // todaymStart: 'Month',diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.ts b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.tsindex 29e39e7ca187..f4bf7d62fe54 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.ts+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.ts@@ -35,6 +35,12 @@ describe('eligibleFilterGroups', () => {operator: PropertyOperator.Regex,},{ type: PropertyFilterType.Cohort, key: 'id', value: 7, operator: PropertyOperator.In },+ {+ type: PropertyFilterType.Session,+ key: '$entry_current_url',+ value: ['/pricing'],+ operator: PropertyOperator.Exact,+ },],events: [{ id: 'billing_limit_set', name: 'billing_limit_set', type: 'events', order: 0 }],actions: [{ id: 42, name: 'Completed checkout', type: 'actions', order: 0 }],@@ -43,12 +49,15 @@ describe('eligibleFilterGroups', () => {{ experimentName: 'Checkout CTA copy', cohortNames: { 7: 'Power users' } })+ // 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'] },])})@@ -72,6 +81,92 @@ describe('eligibleFilterGroups', () => {])})+ it("appends an event's property conditions so a scoped event doesn't read as every occurrence", () => {+ // A bare "checkout_clicked" chip reads as every click; the country filter has to show or the+ // preview overstates the match.+ const groups = eligibleFilterGroups(+ scanner({+ query: {+ kind: NodeKind.RecordingsQuery,+ events: [+ {+ id: 'checkout_clicked',+ name: 'checkout_clicked',+ type: 'events',+ order: 0,+ properties: [+ {+ type: PropertyFilterType.Event,+ key: '$geoip_country_code',+ value: ['US'],+ operator: PropertyOperator.Exact,+ },+ ],+ },+ ],+ },+ })+ )++ expect(groups).toEqual([{ 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', () => {+ // Error tracking pins $exception to one issue with `issue_id = '...' -- <error>`; the comment+ // is what makes the condition legible instead of an opaque id.+ const groups = eligibleFilterGroups(+ scanner({+ query: {+ kind: NodeKind.RecordingsQuery,+ events: [+ {+ id: '$exception',+ name: '$exception',+ type: 'events',+ order: 0,+ properties: [+ {+ type: PropertyFilterType.HogQL,+ key: "issue_id = 'abc' -- TypeError: x is not a function",+ },+ ],+ },+ ],+ },+ })+ )++ expect(groups).toEqual([{ 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', () => {+ // A recording-level person filter would otherwise be invisible, making the scan look like it+ // watches everyone. A known key humanizes; a custom key with no taxonomy entry keeps its name.+ const groups = eligibleFilterGroups(+ scanner({+ query: {+ kind: NodeKind.RecordingsQuery,+ properties: [+ {+ type: PropertyFilterType.Person,+ key: '$browser',+ value: ['Chrome'],+ operator: PropertyOperator.Exact,+ },+ {+ type: PropertyFilterType.Person,+ key: 'plan',+ value: ['enterprise'],+ operator: PropertyOperator.Exact,+ },+ ],+ },+ })+ )++ expect(groups).toEqual([{ label: 'Person', values: ['Latest browser = Chrome', 'plan = enterprise'] }])+ })+it('has no groups when the draft watches every recording', () => {expect(eligibleFilterGroups(scanner({ query: { kind: NodeKind.RecordingsQuery } }))).toEqual([])})diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsxindex 80713a985fd5..b5f7bdbf34de 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx@@ -6,13 +6,14 @@ import { TextMorph } from 'torph/react'import { IconInfo } from '@posthog/icons'import { LemonBanner, LemonButton, LemonSkeleton, LemonSnack, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'+import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'import { LoadingBar } from 'lib/lemon-ui/LoadingBar'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'import { cohortsModel } from '~/models/cohortsModel'-import { PropertyFilterType } from '~/types'+import { AnyPropertyFilter, PropertyFilterType } from '~/types'import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { creditsToUsd, formatCreditCount } from '../../utils/credits'@@ -140,11 +141,26 @@ function pageValues(scanner: ReplayScanner): string[] {return property.value.map(String)}-/** The names of the query's events or actions, whichever list is asked for. */+/** Each event or action the scan watches, with its own property conditions appended.+ *+ * A bare event name reads as "every time this event fires", so an event carrying a sub-filter (for+ * example "checkout clicked where country = US", or an `$exception` pinned to one issue) has to show+ * that filter or the preview overstates what the scan matches. A HogQL condition renders by its+ * trailing `-- comment` when it has one, which is how the issue filter shows the error name rather+ * than a raw `issue_id = '...'`.+ */function namedQueryEntities(scanner: ReplayScanner, key: 'events' | 'actions'): string[] {const query = scanner.queryconst entities = (query && key in query ? query[key] : null) ?? []- return entities.map((entity) => String(entity.name ?? entity.id)).filter(Boolean)+ return entities+ .map((entity) => {+ const name = String(entity.name ?? entity.id)+ const conditions = ((entity.properties ?? []) as AnyPropertyFilter[])+ .map((property) => formatPropertyLabel(property, {}).trim())+ .filter(Boolean)+ return conditions.length > 0 ? `${name} where ${conditions.join(', ')}` : name+ })+ .filter(Boolean)}/** The cohorts the scan is limited to. The query carries only ids, so the name is looked up. */@@ -154,12 +170,63 @@ function cohortValues(scanner: ReplayScanner, cohortNames?: Record<string, strin.map((property) => String(cohortNames?.[String(property.value)] ?? `Cohort ${property.value}`))}+/** The row label for a top-level property filter, by the thing it narrows on: [singular, plural].+ * A missing type falls through to a generic "Filter" so an unrecognized kind still shows rather+ * than vanishing from the preview. */+const TOP_LEVEL_PROPERTY_KIND: Partial<Record<PropertyFilterType, [singular: string, plural: string]>> = {+ [PropertyFilterType.Person]: ['Person', 'Person'],+ [PropertyFilterType.PersonMetadata]: ['Person', 'Person'],+ [PropertyFilterType.DataWarehousePersonProperty]: ['Person', 'Person'],+ [PropertyFilterType.Session]: ['Session', 'Session'],+ [PropertyFilterType.Recording]: ['Recording', 'Recording'],+ [PropertyFilterType.Group]: ['Group', 'Group'],+ [PropertyFilterType.Element]: ['Element', 'Elements'],+ [PropertyFilterType.DataWarehouse]: ['Warehouse', 'Warehouse'],+ [PropertyFilterType.Event]: ['Event property', 'Event properties'],+ [PropertyFilterType.EventMetadata]: ['Event property', 'Event properties'],+ [PropertyFilterType.Feature]: ['Feature', 'Features'],+ [PropertyFilterType.HogQL]: ['SQL', 'SQL'],+}++/** Top-level filters on the recording query itself — the session, person, and recording conditions+ * that aren't attached to a specific event. Without these a scan narrowed by, say, "session browser+ * is Chrome" would read as watching every recording. Pages and cohorts are excluded here because+ * they have their own rows with their own value formatting; everything else is grouped by the kind+ * it narrows on and rendered with the shared property formatter. */+function topLevelPropertyGroups(scanner: ReplayScanner): EligibleFilterGroup[] {+ const properties = (scanner.query?.properties ?? []) as AnyPropertyFilter[]+ // Insertion-ordered so the rows appear in the order the filters were added.+ const byKind = new Map<string, { singular: string; plural: string; values: string[] }>()+ for (const property of properties) {+ if (property.type === PropertyFilterType.Cohort) {+ continue+ }+ if ('key' in property && property.key === 'visited_page') {+ continue+ }+ const value = formatPropertyLabel(property, {}).trim()+ if (!value) {+ continue+ }+ const [singular, plural] = TOP_LEVEL_PROPERTY_KIND[property.type as PropertyFilterType] ?? ['Filter', 'Filters']+ const group = byKind.get(singular) ?? { singular, plural, values: [] }+ group.values.push(value)+ byKind.set(singular, group)+ }+ return [...byKind.values()].map(({ singular, plural, values }) => ({+ label: pluralize(values.length, singular, plural, false),+ values,+ }))+}+/** What the drafted scanner watches, grouped by the kind of filter each value came from.** Each kind narrows differently. An experiment picks the people, a page picks where they went, an- * event or an action picks what they did, and a cohort picks who they are. They also combine, so a- * flat row of values leaves the reader to guess which value is which kind. The label is also the- * only thing that makes an action or a cohort readable: neither value says what it is.+ * event or an action picks what they did, a cohort picks who they are, and a session, person, or+ * recording property narrows the recordings themselves. They also combine, so a flat row of values+ * leaves the reader to guess which value is which kind. The label is also the only thing that makes+ * an action or a cohort readable: neither value says what it is. Any filter that narrows the scan+ * has to appear here, or the preview overstates what the scan matches.*/export function eligibleFilterGroups(scanner: ReplayScanner,@@ -172,12 +239,15 @@ export function eligibleFilterGroups(['Action', 'Actions', namedQueryEntities(scanner, 'actions')],['Cohort', 'Cohorts', cohortValues(scanner, cohortNames)],]- return kinds- .filter(([, , values]) => values.length > 0)- .map(([singular, plural, values]) => ({- label: pluralize(values.length, singular, plural, false),- values,- }))+ return [+ ...kinds+ .filter(([, , values]) => values.length > 0)+ .map(([singular, plural, values]) => ({+ label: pluralize(values.length, singular, plural, false),+ values,+ })),+ ...topLevelPropertyGroups(scanner),+ ]}/** The landing step after a goal-based draft: the whole drafted config, ordered by comprehension,diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 2bf7d2eeedd9..fab5fed1fa65 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -9,6 +9,7 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { parseCsvParam, parseNumericParam, parseSortParam } from '../utils/urlParams'@@ -23,6 +24,7 @@ import {} from './replayScannerLogic'import { readScannerDraft, writeScannerDraft } from './scannerDraft'import { scannerEditorSceneLogic } from './scannerEditorSceneLogic'+import { consumeScannerHandoffIntent, markScannerHandoffIntent } from './scannerHandoffIntent'import { observationsDrilldownSearchParams } from './scannerOverviewLogic'import { defaultScannerTemplates, newScanner } from './scannerTemplates'import { ClassifierScanner, ReplayScanner, ScorerScanner } from './types'@@ -414,6 +416,44 @@ describe('replayScannerLogic', () => {expect(logic.values.goalDraftInput).toEqual('find rage clicks in checkout')expect(draftSpy).not.toHaveBeenCalled()})++ // A cross-product entry point (e.g. "scan this error's recordings" in error tracking)+ // hands over a whole prefilled scanner via one-shot sessionStorage, so customer text in+ // the name and prompt never enters the URL. It expresses fresh intent like the experiment+ // deep link, so it outranks a saved draft, but must not delete that draft.+ it('consumes a scanner hand-off: seeds the wizard over a saved draft, one-shot, draft intact', async () => {+ writeScannerDraft(MOCK_TEAM_ID, { ...logic.values.scanner!, name: 'My saved work' })+ markScannerHandoffIntent({+ source: 'error_tracking',+ scanner: {+ name: 'Error tracking: TypeError',+ scanner_type: 'summarizer',+ scanner_config: { prompt: 'Watch each recording around the error.', length: 'medium' },+ query: {+ kind: NodeKind.RecordingsQuery,+ events: [{ id: '$exception', name: '$exception', type: 'events' }],+ },+ sampling_rate: 1.0,+ credit_limit: 5000,+ credit_limit_enabled: true,+ },+ })+ router.actions.push(urls.replayVisionScannerOverview('new'))++ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()++ expect(logic.values.scanner).toMatchObject({+ name: 'Error tracking: TypeError',+ scanner_type: 'summarizer',+ scanner_config: { prompt: 'Watch each recording around the error.', length: 'medium' },+ query: expect.objectContaining({ events: [expect.objectContaining({ id: '$exception' })] }),+ sampling_rate: 1.0,+ credit_limit: 5000,+ credit_limit_enabled: true,+ })+ expect(consumeScannerHandoffIntent()).toBeNull()+ expect(readScannerDraft(MOCK_TEAM_ID)?.scanner.name).toEqual('My saved work')+ })})describe('setScannerType', () => {diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex e86043d6fb91..89c390b29408 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -84,6 +84,7 @@ import {scannerStepUrlWithParams,UNVALIDATED_SCANNER_STEPS,} from './scannerEditorSceneLogic'+import { consumeScannerHandoffIntent } from './scannerHandoffIntent'import type { ObservationStatusStats } from './scannerStats'import { availableTagsFromStats, daysFromDateRange, deriveObservationStatusStats } from './scannerStats'import { findScannerTemplate, newScanner } from './scannerTemplates'@@ -1642,10 +1643,15 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// the tab session, where a later ?goal= link would auto-start a draft and// spend the user's AI allowance without fresh intent.const handedOffGoal = consumeGoalDraftIntent()?.trim() ?? ''- // Prefill precedence: an experiment deep link, then an explicit ?filters=- // query (both carry fully built state), then a saved draft, then the- // free-text goal. A URL carrying both ?filters= and ?goal= deterministically- // takes the filters and drops the goal.+ // Consumed unconditionally for the same reason: a cross-product hand-off must+ // not stay armed for the rest of the tab session and prefill a later,+ // unrelated wizard visit.+ const handoff = consumeScannerHandoffIntent()+ // 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+ // draft, then the free-text goal. A URL carrying both ?filters= and ?goal=+ // deterministically takes the filters and drops the goal.const hasFiltersPrefill = 'filters' in router.values.searchParamsconst prefillQuery = prefillQueryFromUrl()// Strip the params the wizard has now consumed so a reload doesn't re-run the prefill@@ -1671,6 +1677,25 @@ export const replayScannerLogic = kea<replayScannerLogicType>([if (Object.keys(nextParams).length !== Object.keys(router.values.searchParams).length) {router.actions.replace(router.values.location.pathname, nextParams, router.values.hashParams)}+ if (handoff) {+ posthog.capture('replay_vision_scanner_creation_started', {+ creation_method: 'handoff',+ template_key: null,+ source: handoff.source,+ })+ // 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+ // draft; restoringDraft guards persistDraft so the prefill can't clobber+ // that draft.+ cache.restoringDraft = true+ try {+ actions.loadScannerSuccess(newScanner(null, teamName))+ actions.setScannerValues(handoff.scanner)+ } finally {+ cache.restoringDraft = false+ }+ return+ }if (experimentParams) {// The two deep links combine rather than compete: the replay filters entry// point sends targeting and filters together, because exposure can't ridediff --git a/products/replay_vision/frontend/replay_scanners/scannerHandoffIntent.ts b/products/replay_vision/frontend/replay_scanners/scannerHandoffIntent.tsnew file mode 100644index 000000000000..cebd20f8c17a--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerHandoffIntent.ts@@ -0,0 +1,52 @@+import type { ScannerFormValues } from './types'++const SCANNER_HANDOFF_INTENT_KEY = 'replay-vision.scanner-handoff-intent'+// Bump when the payload shape changes, so an entry written by an older tab is dropped instead of applied.+const SCANNER_HANDOFF_INTENT_VERSION = 1++/** One-shot hand-off of a prefilled scanner from another product's entry point (for example+ * "scan this error's recordings" in error tracking) to the creation wizard. The prefill can carry+ * customer text, such as an exception message inside the scanner name and prompt, so it travels+ * via sessionStorage rather than the URL, keeping it out of autocapture's $current_url, our own+ * replay of our app, and browser history. */+export interface ScannerHandoffIntent {+ /** Entry point that armed the hand-off, recorded on the creation-started event. */+ source: string+ scanner: Partial<ScannerFormValues>+}++export function markScannerHandoffIntent(intent: ScannerHandoffIntent): void {+ try {+ sessionStorage.setItem(+ SCANNER_HANDOFF_INTENT_KEY,+ JSON.stringify({ version: SCANNER_HANDOFF_INTENT_VERSION, ...intent })+ )+ } catch {+ // Storage can be unavailable (private mode); the entry point then just opens the wizard blank.+ }+}++/** Reads and clears the hand-off. The wizard must call this on every entry, whichever prefill+ * path wins, so a hand-off can never stay armed for the rest of the tab session and prefill a+ * later, unrelated wizard visit. */+export function consumeScannerHandoffIntent(): ScannerHandoffIntent | null {+ try {+ const raw = sessionStorage.getItem(SCANNER_HANDOFF_INTENT_KEY)+ sessionStorage.removeItem(SCANNER_HANDOFF_INTENT_KEY)+ if (!raw) {+ return null+ }+ const parsed = JSON.parse(raw)+ if (+ parsed?.version !== SCANNER_HANDOFF_INTENT_VERSION ||+ typeof parsed.source !== 'string' ||+ typeof parsed.scanner !== 'object' ||+ parsed.scanner === null+ ) {+ return null+ }+ return { source: parsed.source, scanner: parsed.scanner }+ } catch {+ return null+ }+}