: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(surveys): show URL reach estimate in the full survey editor (#71790)
Ben Lea80985fe0ff9d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex eaf84d3a7cbe..6874012b15b1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7027,9 +7027,9 @@ snapshots:scenes-app-surveys--new-survey-customisation-section--light:hash: v1.k794b7964.bc016f559e76a957263be186aa2ef2c4f8866349984c8c42848ee37a8e454185.5BzY7jlNP0TRSi4knqU3u-_VZX-GvO5vnVk2XT5okFYscenes-app-surveys--new-survey-targeting-section--dark:- hash: v1.k794b7964.803c80bab7d9bd09df849e296bb779910d40fdf464b7cab74223ff6dfbb55df1.YD6wa5xeVCNyO0HAY1jdpdPFVaqlUmSxQH42N67gsF0+ hash: v1.k794b7964.613ab3e01bf3425c96ce0b13ff28e300776d92e155da5f899165d93c70571c36.My2MvTdYRum7fY0L1VNbic1nMMQn7k2aIjcQIesqCUwscenes-app-surveys--new-survey-targeting-section--light:- hash: v1.k794b7964.2492600bd176d2c008ca5085c32710a0e6a28795a9ceda1cb0fa31cca68d5f25.cwr3dHGwYkvQCrwx4LH18GXXfctZnp7Xd3BT37whOUM+ hash: v1.k794b7964.ca8af865f7a041b0ff718a36edd0d86c2fb03c5ec43b8f36316de571367f5bf6.6Qo_9HWNOUfRlhPYMcbunu8THHG9lDRdEef2eujDhRkscenes-app-surveys--new-survey-with-html-question-description--dark:hash: v1.k794b7964.54111bee2334eccdc99f6c9212d4a8c71bcd53e608ddec9a92fb31898f3082b8.DRc8wJwLM863SeYFi_zH6JuZDSseEB9fvftMC_XeB1Escenes-app-surveys--new-survey-with-html-question-description--light:diff --git a/frontend/src/scenes/surveys/SurveyEdit.tsx b/frontend/src/scenes/surveys/SurveyEdit.tsxindex 25852b5ff703..18090d271546 100644--- a/frontend/src/scenes/surveys/SurveyEdit.tsx+++ b/frontend/src/scenes/surveys/SurveyEdit.tsx@@ -65,6 +65,7 @@ import {} from '~/types'import { SurveyBranchingFlowModal } from './branching-flow/SurveyBranchingFlowModal'+import { SurveyUrlAudienceEstimate } from './components/SurveyUrlAudienceEstimate'import { SURVEY_TYPE_LABEL_MAP, SurveyMatchTypeLabels, defaultSurveyFieldValues } from './constants'import { COMMON_LANGUAGES, getBaseLanguage, getSurveyLanguageName } from './language'import { SurveyAPIEditor } from './SurveyAPIEditor'@@ -1581,6 +1582,7 @@ export default function SurveyEdit({ id }: { id: string }): JSX.Element {fullWidth/></div>+ <SurveyUrlAudienceEstimate /></LemonField.Pure><LemonField.Purelabel="Device types"@@ -1752,7 +1754,10 @@ export default function SurveyEdit({ id }: { id: string }): JSX.Element {</>)}</LemonField>- <LemonField.Pure label="Audience filters">+ <LemonField.Pure+ label="Audience filters"+ info="User counts shown here estimate how many people match these filters across your project. The survey's actual reach is usually smaller, because display conditions like URL and device targeting still control where it appears."+ ><BindLogiclogic={featureFlagLogic}props={{diff --git a/frontend/src/scenes/surveys/components/SurveyUrlAudienceEstimate.test.ts b/frontend/src/scenes/surveys/components/SurveyUrlAudienceEstimate.test.tsnew file mode 100644index 000000000000..e5c449d8bfee--- /dev/null+++ b/frontend/src/scenes/surveys/components/SurveyUrlAudienceEstimate.test.ts@@ -0,0 +1,68 @@+import { PropertyOperator, SurveyMatchType } from '~/types'++import { getUrlAudienceEstimateParams } from './SurveyUrlAudienceEstimate'++describe('getUrlAudienceEstimateParams', () => {+ it.each([+ { name: 'no conditions', conditions: null, expected: null },+ { name: 'empty url', conditions: { url: '' }, expected: null },+ { name: 'whitespace url', conditions: { url: ' ' }, expected: null },+ {+ name: 'default match type falls back to icontains',+ conditions: { url: '/pricing' },+ expected: { url: '/pricing', operator: PropertyOperator.IContains },+ },+ {+ name: 'contains',+ conditions: { url: '/pricing', urlMatchType: SurveyMatchType.Contains },+ expected: { url: '/pricing', operator: PropertyOperator.IContains },+ },+ {+ name: 'exact with a full URL',+ conditions: { url: 'https://example.com/pricing', urlMatchType: SurveyMatchType.Exact },+ expected: { url: 'https://example.com/pricing', operator: PropertyOperator.Exact },+ },+ {+ name: 'exact with a bare path never matches, so no estimate',+ conditions: { url: '/pricing', urlMatchType: SurveyMatchType.Exact },+ expected: null,+ },+ {+ name: 'valid regex',+ conditions: { url: '^https://example.com/docs/.*', urlMatchType: SurveyMatchType.Regex },+ expected: { url: '^https://example.com/docs/.*', operator: PropertyOperator.Regex },+ },+ {+ name: 'regex invalid everywhere',+ conditions: { url: '(unclosed', urlMatchType: SurveyMatchType.Regex },+ expected: null,+ },+ {+ name: 'regex valid in JS but not in RE2 (lookahead) never queries',+ conditions: { url: '^https://example\\.com/(?!admin)', urlMatchType: SurveyMatchType.Regex },+ expected: null,+ },+ {+ name: 'url is trimmed',+ conditions: { url: ' /pricing ', urlMatchType: SurveyMatchType.Contains },+ expected: { url: '/pricing', operator: PropertyOperator.IContains },+ },+ {+ name: 'negative operators show no estimate: is not',+ conditions: { url: 'https://example.com/admin', urlMatchType: SurveyMatchType.IsNot },+ expected: null,+ },+ {+ name: 'negative operators show no estimate: not contains',+ conditions: { url: '/pricing', urlMatchType: SurveyMatchType.NotIContains },+ expected: null,+ },+ {+ name: 'negative operators show no estimate: not regex',+ conditions: { url: '^https://example.com/docs/.*', urlMatchType: SurveyMatchType.NotRegex },+ expected: null,+ },+ ])('$name', ({ conditions, expected }) => {+ expect(getUrlAudienceEstimateParams(conditions)).toEqual(expected)+ })+})diff --git a/frontend/src/scenes/surveys/components/SurveyUrlAudienceEstimate.tsx b/frontend/src/scenes/surveys/components/SurveyUrlAudienceEstimate.tsxnew file mode 100644index 000000000000..63afd6dc8275--- /dev/null+++ b/frontend/src/scenes/surveys/components/SurveyUrlAudienceEstimate.tsx@@ -0,0 +1,174 @@+import { useValues } from 'kea'+import { RE2JS } from 're2js'+import { useEffect, useState } from 'react'++import { Spinner } from '@posthog/lemon-ui'++import api from 'lib/api'+import { cn } from 'lib/utils/css-classes'+import { uuid } from 'lib/utils/dom'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import type { HogQLQueryString } from '~/queries/utils'+import { PropertyFilterType, PropertyOperator, SurveyDisplayConditions, SurveyMatchType } from '~/types'++import { surveyLogic } from '../surveyLogic'++export const URL_AUDIENCE_ESTIMATE_DAYS = 30+const URL_AUDIENCE_ESTIMATE_DEBOUNCE_MS = 500+const URL_AUDIENCE_ESTIMATE_TAGS = {+ scene: 'Survey' as const,+ productKey: 'surveys' as const,+ name: 'survey_url_audience_estimate' as const,+}++// Positive match types only: an estimate for a negative condition ("doesn't contain ...") counts+// nearly everyone, which costs a full scan for a number that misleads more than it informs.+// SurveyMatchType members alias PropertyOperator values, but the enums are distinct to TypeScript.+const SURVEY_MATCH_TYPE_TO_PROPERTY_OPERATOR: Partial<Record<SurveyMatchType, PropertyOperator>> = {+ [SurveyMatchType.Exact]: PropertyOperator.Exact,+ [SurveyMatchType.Contains]: PropertyOperator.IContains,+ [SurveyMatchType.Regex]: PropertyOperator.Regex,+}++type UrlAudienceEstimate =+ | { status: 'idle' }+ | { status: 'loading' }+ | { status: 'loaded'; count: number }+ | { status: 'error' }++export function getUrlAudienceEstimateParams(+ conditions: Pick<SurveyDisplayConditions, 'url' | 'urlMatchType'> | null | undefined+): { url: string; operator: PropertyOperator } | null {+ const url = conditions?.url?.trim()+ if (!url) {+ return null+ }+ const matchType = conditions?.urlMatchType || SurveyMatchType.Contains+ const operator = SURVEY_MATCH_TYPE_TO_PROPERTY_OPERATOR[matchType]+ if (!operator) {+ return null+ }+ // $current_url always includes protocol and host, so an exact match against a bare path never matches+ if (matchType === SurveyMatchType.Exact && url.startsWith('/')) {+ return null+ }+ if (matchType === SurveyMatchType.Regex) {+ // The estimate runs in ClickHouse, which evaluates RE2 — JS-only syntax (e.g. lookaheads)+ // can be a valid survey condition yet would only ever produce a failing query here+ try {+ RE2JS.compile(url)+ } catch {+ return null+ }+ }+ return { url, operator }+}++/** Estimated unique users who viewed pages matching the survey's URL condition in the last+ * {@link URL_AUDIENCE_ESTIMATE_DAYS} days. Render it only on editing surfaces, within a `BindLogic`+ * for `surveyLogic` — rendering it is what triggers the estimate queries. */+export function SurveyUrlAudienceEstimate({ className }: { className?: string }): JSX.Element | null {+ const { survey } = useValues(surveyLogic)+ const [estimate, setEstimate] = useState<UrlAudienceEstimate>({ status: 'idle' })++ const params = getUrlAudienceEstimateParams(survey.conditions)+ const url = params?.url+ const operator = params?.operator++ useEffect(() => {+ if (!url || !operator) {+ setEstimate({ status: 'idle' })+ return+ }++ // Show progress immediately so a stale count never lingers through the debounce window+ setEstimate({ status: 'loading' })++ const abortController = new AbortController()+ const clientQueryId = uuid()+ let queryInFlight = false+ const timeout = window.setTimeout(async () => {+ try {+ const query = `+ SELECT uniq(person_id)+ FROM events+ WHERE event = '$pageview'+ AND timestamp >= now() - INTERVAL ${URL_AUDIENCE_ESTIMATE_DAYS} DAY+ AND {filters}+ ` as HogQLQueryString++ queryInFlight = true+ const response = await api.queryHogQL<[[number]]>(query, URL_AUDIENCE_ESTIMATE_TAGS, {+ clientQueryId,+ requestOptions: { signal: abortController.signal },+ queryParams: {+ filters: {+ properties: [+ {+ key: '$current_url',+ operator,+ type: PropertyFilterType.Event,+ value: url,+ },+ ],+ },+ },+ })+ queryInFlight = false++ const count = response.results?.[0]?.[0]+ setEstimate(typeof count === 'number' ? { status: 'loaded', count } : { status: 'error' })+ } catch (error) {+ queryInFlight = false+ if ((error as { name?: string }).name !== 'AbortError') {+ setEstimate({ status: 'error' })+ }+ }+ }, URL_AUDIENCE_ESTIMATE_DEBOUNCE_MS)++ return () => {+ window.clearTimeout(timeout)+ abortController.abort()+ if (queryInFlight) {+ // Aborting only drops the connection — also cancel the ClickHouse query server-side+ void api.insights.cancelQuery(clientQueryId)+ }+ }+ }, [url, operator])++ if (estimate.status === 'idle') {+ return null+ }++ let content: JSX.Element+ if (estimate.status === 'loading') {+ content = (+ <p className={cn('text-xs text-muted flex items-center gap-1', className)}>+ <Spinner className="text-xs" /> Estimating matching users...+ </p>+ )+ } else if (estimate.status === 'error') {+ content = (+ <p className={cn('text-xs text-muted', className)}>+ Unable to estimate matching users for this URL condition.+ </p>+ )+ } else if (estimate.count === 0) {+ content = (+ <p className={cn('text-xs text-muted', className)}>+ No pageviews matched this URL condition in the last {URL_AUDIENCE_ESTIMATE_DAYS} days. Double-check the+ pattern if you expected matches.+ </p>+ )+ } else {+ content = (+ <p className={cn('text-xs text-muted', className)}>+ About {humanFriendlyNumber(estimate.count)} unique {estimate.count === 1 ? 'user' : 'users'} viewed+ matching URLs in the last {URL_AUDIENCE_ESTIMATE_DAYS} days.+ </p>+ )+ }++ return <div aria-live="polite">{content}</div>+}diff --git a/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx b/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsxindex e933e6a4c586..5032559ca074 100644--- a/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx+++ b/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx@@ -1,53 +1,27 @@import { useActions, useValues } from 'kea'import { RE2JS } from 're2js'-import { useEffect, useState } from 'react'+import { useEffect } from 'react'import { IconTrash } from '@posthog/icons'-import { LemonButton, LemonInputSelect, LemonSegmentedButton, Spinner } from '@posthog/lemon-ui'+import { LemonButton, LemonInputSelect, LemonSegmentedButton } from '@posthog/lemon-ui'-import api from 'lib/api'import { FlagSelector } from 'lib/components/FlagSelector'import { ANY_VARIANT, variantOptions } from 'lib/components/IngestionControls/triggers/FlagTrigger/VariantSelector'import { LemonRadio } from 'lib/lemon-ui/LemonRadio'-import { humanFriendlyNumber } from 'lib/utils/numbers'import { formatRE2Error } from 'lib/utils/regexp'import { featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'-import { teamLogic } from 'scenes/teamLogic'import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'-import type { HogQLQueryString } from '~/queries/utils'-import {- PropertyDefinitionType,- PropertyFilterType,- PropertyOperator,- SurveyDisplayConditions,- SurveyMatchType,-} from '~/types'+import { PropertyDefinitionType, SurveyDisplayConditions, SurveyMatchType } from '~/types'+import { SurveyUrlAudienceEstimate } from '../../components/SurveyUrlAudienceEstimate'import { surveyLogic } from '../../surveyLogic'import { SurveyAudienceFilters } from '../SurveyAudienceFilters'import { WizardSection, WizardStepLayout } from '../WizardLayout'const DEVICE_OPTIONS = ['Desktop', 'Mobile', 'Tablet']-const URL_AUDIENCE_ESTIMATE_DAYS = 30-const URL_AUDIENCE_ESTIMATE_TAGS = {- scene: 'Survey' as const,- productKey: 'surveys' as const,- name: 'survey_url_audience_estimate' as const,-}type UrlMatchMode = SurveyMatchType.Contains | SurveyMatchType.Exact | SurveyMatchType.Regex-type UrlAudienceEstimate =- | { status: 'idle' }- | { status: 'loading' }- | { status: 'loaded'; count: number }- | { status: 'error' }--const URL_MATCH_MODE_PROPERTY_OPERATORS: Record<UrlMatchMode, PropertyOperator> = {- [SurveyMatchType.Contains]: PropertyOperator.IContains,- [SurveyMatchType.Exact]: PropertyOperator.Exact,- [SurveyMatchType.Regex]: PropertyOperator.Regex,-}function getRegexValidationError(pattern: string, matchType: UrlMatchMode): string | null {if (matchType !== SurveyMatchType.Regex || !pattern) {@@ -67,12 +41,10 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => voidconst { survey } = useValues(surveyLogic)const { setSurveyValue } = useActions(surveyLogic)const { featureFlag } = useValues(featureFlagLogic({ id: survey.linked_flag_id || 'link' }))- const { currentTeamId } = useValues(teamLogic)const { options } = useValues(propertyDefinitionsModel)const { loadPropertyValues } = useActions(propertyDefinitionsModel)const urlOptions = options['$current_url']- const [urlAudienceEstimate, setUrlAudienceEstimate] = useState<UrlAudienceEstimate>({ status: 'idle' })const conditions: Partial<SurveyDisplayConditions> = survey.conditions || {}const targetingMode = conditions.urlMatchType ? 'specific' : 'all'@@ -145,64 +117,6 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => void}}, [targetingMode, urlMatchMode, urlOptions?.status, loadPropertyValues])- useEffect(() => {- const trimmedPattern = urlPattern.trim()-- if (- targetingMode !== 'specific' ||- !currentTeamId ||- !trimmedPattern ||- isPathInputInExactMode ||- regexValidationError- ) {- setUrlAudienceEstimate({ status: 'idle' })- return- }-- const abortController = new AbortController()- const timeout = window.setTimeout(async () => {- setUrlAudienceEstimate({ status: 'loading' })-- try {- const query = `- SELECT uniq(person_id)- FROM events- WHERE team_id = ${currentTeamId}- AND event = '$pageview'- AND timestamp >= now() - INTERVAL ${URL_AUDIENCE_ESTIMATE_DAYS} DAY- AND {filters}- ` as HogQLQueryString-- const response = await api.queryHogQL<[[number]]>(query, URL_AUDIENCE_ESTIMATE_TAGS, {- requestOptions: { signal: abortController.signal },- queryParams: {- filters: {- properties: [- {- key: '$current_url',- operator: URL_MATCH_MODE_PROPERTY_OPERATORS[urlMatchMode],- type: PropertyFilterType.Event,- value: trimmedPattern,- },- ],- },- },- })-- setUrlAudienceEstimate({ status: 'loaded', count: response.results?.[0]?.[0] ?? 0 })- } catch (error) {- if ((error as { name?: string }).name !== 'AbortError') {- setUrlAudienceEstimate({ status: 'error' })- }- }- }, 500)-- return () => {- window.clearTimeout(timeout)- abortController.abort()- }- }, [currentTeamId, isPathInputInExactMode, regexValidationError, targetingMode, urlMatchMode, urlPattern])-const setTargetingMode = (mode: 'all' | 'specific'): void => {if (mode === 'all') {setSurveyValue('conditions', { ...conditions, url: '', urlMatchType: undefined })@@ -315,22 +229,8 @@ export function WhereStep({ onOpenFullEditor }: { onOpenFullEditor?: () => void: 'Select from your most visited pages or type a path like /pricing.'}</p>)}- {urlAudienceEstimate.status === 'loading' && (- <p className="text-xs text-muted mt-1.5 flex items-center gap-1">- <Spinner className="text-xs" /> Estimating matching users...- </p>- )}- {urlAudienceEstimate.status === 'loaded' && (- <p className="text-xs text-muted mt-1.5">- About {humanFriendlyNumber(urlAudienceEstimate.count)} unique{' '}- {urlAudienceEstimate.count === 1 ? 'user' : 'users'} viewed matching URLs in the last{' '}- {URL_AUDIENCE_ESTIMATE_DAYS} days.- </p>- )}- {urlAudienceEstimate.status === 'error' && (- <p className="text-xs text-muted mt-1.5">- Unable to estimate matching users for this URL condition.- </p>+ {!isPathInputInExactMode && !regexValidationError && (+ <SurveyUrlAudienceEstimate className="mt-1.5" />)}</div>)}