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(web-analytics): Add SEO / AEO page performance to Web analytics (#82726)

Jordan Mryyan8ed5f32dd855
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b9d2567654c5..04bf2ce9bf23 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -542,6 +542,7 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_MARKETING: 'marketing-analytics', // owner: @jabahamondes #team-web-analytics
WEB_ANALYTICS_METRIC_CARDS: 'web-analytics-metric-cards', // owner: #team-web-analytics
WEB_ANALYTICS_OPEN_URL: 'web-analytics-open-url', // owner: @lricoy #team-web-analytics
+ WEB_ANALYTICS_PAGE_PERFORMANCE: 'web-analytics-page-performance', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_PRECOMPUTE_TOGGLE: 'web-analytics-precompute-toggle', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_RECAP: 'web-analytics-recap', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_REGIONS_MAP: 'web-analytics-regions-map', // owner: @jordanm-posthog #team-web-analytics
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index e938a85a0f05..20a49be43ef0 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -646,6 +646,7 @@ export const redirects: Record<
const params = new URLSearchParams(searchParams as Record<string, string>).toString()
return urls.marketingAnalyticsApp() + (params ? `?${params}` : '')
},
+ '/web/ai-search': urls.webAnalyticsPagePerformance(),
'/events': urls.activity(),
'/events/:id/*': ({ id, _ }) => {
@@ -755,6 +756,7 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.webAnalytics()]: [Scene.WebAnalytics, 'webAnalytics'],
[urls.webAnalyticsWebVitals()]: [Scene.WebAnalytics, 'webAnalyticsWebVitals'],
[urls.webAnalyticsBotAnalytics()]: [Scene.WebAnalytics, 'webAnalyticsBotAnalytics'],
+ [urls.webAnalyticsPagePerformance()]: [Scene.WebAnalytics, 'webAnalyticsPagePerformance'],
[urls.webAnalyticsHealth()]: [Scene.WebAnalyticsHealth, 'webAnalyticsHealth'],
[urls.webAnalyticsLive()]: [Scene.WebAnalyticsLive, 'webAnalyticsLive'],
[urls.webAnalyticsRecap()]: [Scene.WebAnalyticsRecap, 'webAnalyticsRecap'],
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 057003cee667..271815589075 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -316,6 +316,7 @@ export const urls = {
? `/health/alerts?preset_kinds=${encodeURIComponent(presetKinds.join(','))}`
: '/health/alerts',
webAnalyticsBotAnalytics: (): string => '/web/bots',
+ webAnalyticsPagePerformance: (): string => '/web/page-performance',
webAnalyticsHealth: (): string => '/web/health',
webAnalyticsRecap: (): string => '/web/recap',
pipelineStatus: (): string => '/health/pipeline-status',
diff --git a/frontend/src/scenes/web-analytics/PagePerformance.tsx b/frontend/src/scenes/web-analytics/PagePerformance.tsx
new file mode 100644
index 000000000000..72879e0d58d7
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/PagePerformance.tsx
@@ -0,0 +1,375 @@
+import clsx from 'clsx'
+import { useActions, useMountedLogic, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { IconTrending } from '@posthog/icons'
+import { LemonBanner, LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'
+
+import { getColorVar } from 'lib/colors'
+import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { percentage } from 'lib/utils/numbers'
+import { tryDecodeURIComponent } from 'lib/utils/url'
+
+import { OverviewGrid } from '~/queries/nodes/OverviewGrid/OverviewGrid'
+import { Query } from '~/queries/Query/Query'
+import { DataTableNode } from '~/queries/schema/schema-general'
+import { QueryContext, QueryContextColumnComponent, QueryContextColumnTitleComponent } from '~/queries/types'
+
+import { TileId } from './common'
+import { PagePerformanceBreakdownModal } from './PagePerformanceBreakdownModal'
+import {
+ OVERVIEW_CARD_LABELS,
+ PagePerformanceMetric,
+ createPagePerformanceInsightProps,
+ pagePerformanceLogic,
+} from './pagePerformanceLogic'
+import { WebQuery, webAnalyticsDataTableQueryContext } from './tiles/WebAnalyticsTile'
+import { webAnalyticsLogic } from './webAnalyticsLogic'
+
+const asTuple = (value: unknown): [number, number] | null => {
+ if (Array.isArray(value) && value.length >= 2) {
+ return [Number(value[0] ?? 0), Number(value[1] ?? 0)]
+ }
+ return null
+}
+
+const formatCount = (value: unknown): string =>
+ typeof value === 'number' ? value.toLocaleString() : String(value ?? 0)
+
+type TrendIndicator = {
+ Icon: typeof IconTrending | typeof IconTrendingDown | typeof IconTrendingFlat
+ color: string
+ className: string
+}
+
+const trendIndicator = (pctChange: number | null): TrendIndicator | null => {
+ if (pctChange === null) {
+ return null
+ }
+ if (pctChange === 0) {
+ return { Icon: IconTrendingFlat, color: getColorVar('muted'), className: 'text-secondary' }
+ }
+ if (pctChange > 0) {
+ return { Icon: IconTrending, color: getColorVar('success'), className: 'text-success' }
+ }
+ return { Icon: IconTrendingDown, color: getColorVar('danger'), className: 'text-danger' }
+}
+
+const DeltaValue = ({ value }: { value: unknown }): JSX.Element => {
+ const { compareFilter } = useValues(pagePerformanceLogic)
+ const tuple = asTuple(value)
+ if (!tuple) {
+ return <span>{formatCount(value)}</span>
+ }
+ const [current, previous] = tuple
+ const compareOn = compareFilter.compare !== false
+ const pctChange = !compareOn || previous === 0 ? null : current === previous ? 0 : current / previous - 1
+ const trend = trendIndicator(pctChange)
+ const tooltip =
+ pctChange !== null && pctChange !== 0
+ ? `${current >= previous ? 'Increased' : 'Decreased'} by ${percentage(Math.abs(pctChange), 0)} vs previous period`
+ : undefined
+ return (
+ <Tooltip title={tooltip}>
+ <span className="whitespace-nowrap">
+ {formatCount(current)}
+ {trend && (
+ <span className={clsx('ml-1 inline-flex items-center text-xs', trend.className)}>
+ <trend.Icon color={trend.color} />
+ {pctChange !== null && pctChange !== 0 ? percentage(Math.abs(pctChange), 0) : ''}
+ </span>
+ )}
+ </span>
+ </Tooltip>
+ )
+}
+
+const ValueWithSubtitle = ({ value, subtitle }: { value: string; subtitle: string }): JSX.Element => (
+ <div className="flex flex-col items-end leading-tight">
+ <span className="whitespace-nowrap">{value}</span>
+ <span className="text-secondary text-xs whitespace-nowrap">{subtitle}</span>
+ </div>
+)
+
+const BreakdownLink = ({
+ metric,
+ record,
+ children,
+}: {
+ metric: PagePerformanceMetric
+ record: unknown
+ children: React.ReactNode
+}): JSX.Element => {
+ const { openBreakdown } = useActions(pagePerformanceLogic)
+ const page = Array.isArray(record) ? String(record[0] ?? '') : ''
+ return (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ noPadding
+ className="underline decoration-dotted underline-offset-2 hover:decoration-solid"
+ onClick={() => openBreakdown({ page, metric })}
+ >
+ {children}
+ </LemonButton>
+ )
+}
+
+const PageCell: QueryContextColumnComponent = ({ value }) => {
+ if (typeof value !== 'string') {
+ return <span className="text-secondary italic">(none)</span>
+ }
+ const decoded = tryDecodeURIComponent(value)
+ return (
+ <Tooltip title={decoded}>
+ <span className="font-medium">{decoded}</span>
+ </Tooltip>
+ )
+}
+
+const VisitorsCell: QueryContextColumnComponent = ({ value }) => <DeltaValue value={value} />
+
+const GoogleSearchCell: QueryContextColumnComponent = ({ value, record }) => {
+ const tuple = asTuple(value)
+ const google = tuple?.[0] ?? 0
+ const visitors = tuple?.[1] ?? 0
+ const share = visitors > 0 ? percentage(google / visitors, 0) : '-'
+ return (
+ <BreakdownLink metric="google_search" record={record}>
+ <ValueWithSubtitle value={formatCount(google)} subtitle={`${share} of visitors`} />
+ </BreakdownLink>
+ )
+}
+
+const LlmReferralsCell: QueryContextColumnComponent = ({ value, record }) => (
+ <BreakdownLink metric="llm_referrals" record={record}>
+ <DeltaValue value={value} />
+ </BreakdownLink>
+)
+
+const AgentCrawlsCell: QueryContextColumnComponent = ({ value, record }) => {
+ const tuple = asTuple(value)
+ const crawls = tuple?.[0] ?? 0
+ const agents = tuple?.[1] ?? 0
+ return (
+ <BreakdownLink metric="agent_crawls" record={record}>
+ <ValueWithSubtitle
+ value={formatCount(crawls)}
+ subtitle={`${agents} ${agents === 1 ? 'agent' : 'agents'}`}
+ />
+ </BreakdownLink>
+ )
+}
+
+const ConversionsCell: QueryContextColumnComponent = ({ value }) => {
+ const { conversionGoal } = useValues(pagePerformanceLogic)
+ if (!conversionGoal) {
+ return <span className="text-secondary">-</span>
+ }
+ const tuple = asTuple(value)
+ const conversions = tuple?.[0] ?? 0
+ const visitors = tuple?.[1] ?? 0
+ const cvr = visitors > 0 ? percentage(conversions / visitors, 1) : '-'
+ return <ValueWithSubtitle value={formatCount(conversions)} subtitle={`${cvr} CVR`} />
+}
+
+const AvgTimeCell: QueryContextColumnComponent = ({ value }) => (
+ <span className="whitespace-nowrap">{value ? humanFriendlyDuration(Number(value)) : '-'}</span>
+)
+
+const sortableTitle = (label: string, column: string): QueryContextColumnTitleComponent =>
+ function SortableTitle() {
+ const { orderBy } = useValues(pagePerformanceLogic)
+ const { setOrderBy } = useActions(pagePerformanceLogic)
+ const active = orderBy.column === column
+ const ascending = active && orderBy.direction === 'ASC'
+ return (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ noPadding
+ className="group cursor-pointer inline-flex items-center"
+ onClick={() => setOrderBy(column, active && orderBy.direction === 'DESC' ? 'ASC' : 'DESC')}
+ aria-label={`Sort by ${label} ${active && orderBy.direction === 'DESC' ? 'ascending' : 'descending'}`}
+ >
+ {label}
+ <IconTrending
+ className={clsx('ml-1 opacity-0 group-hover:opacity-100', {
+ 'text-primary opacity-100': active,
+ 'rotate-180': ascending,
+ })}
+ />
+ </LemonButton>
+ )
+ }
+
+const cardHeading = (title: string): JSX.Element => (
+ <div className="flex items-baseline gap-2 px-3 pt-3">
+ <h3 className="font-semibold m-0">{title}</h3>
+ </div>
+)
+
+const AiTableCard = ({
+ title,
+ query,
+ tileId,
+}: {
+ title: string
+ query: DataTableNode
+ tileId: TileId
+}): JSX.Element => {
+ const context = useMemo(
+ (): QueryContext => ({
+ ...webAnalyticsDataTableQueryContext,
+ insightProps: createPagePerformanceInsightProps(tileId, 'table'),
+ showLoadNextButton: true,
+ }),
+ [tileId]
+ )
+ return (
+ <div className="border rounded bg-surface-primary flex flex-col flex-1">
+ {cardHeading(title)}
+ <Query uniqueKey={`page-performance-${tileId}`} query={query} readOnly context={context} />
+ </div>
+ )
+}
+
+export const PagePerformance = (): JSX.Element => {
+ useMountedLogic(pagePerformanceLogic)
+ const {
+ pageTableQuery,
+ pageCandidates,
+ pageDataError,
+ pageDataLoading,
+ overviewCards,
+ overviewLoading,
+ footerText,
+ aiSectionQueries,
+ } = useValues(pagePerformanceLogic)
+ const { loadPageData } = useActions(pagePerformanceLogic)
+
+ const context = useMemo(
+ (): QueryContext => ({
+ insightProps: createPagePerformanceInsightProps(TileId.PAGE_PERFORMANCE_TABLE, 'table'),
+ columns: {
+ breakdown_value: { title: 'Page', render: PageCell, width: '28%' },
+ visitors: { renderTitle: sortableTitle('Visitors', 'visitors'), render: VisitorsCell, align: 'right' },
+ google_search: {
+ renderTitle: sortableTitle('Google search', 'google_search'),
+ render: GoogleSearchCell,
+ align: 'right',
+ },
+ llm_referrals: {
+ renderTitle: sortableTitle('LLM referrals', 'llm_referrals'),
+ render: LlmReferralsCell,
+ align: 'right',
+ },
+ agent_crawls: {
+ renderTitle: sortableTitle('Agent crawls', 'agent_crawls'),
+ render: AgentCrawlsCell,
+ align: 'right',
+ },
+ conversions: {
+ renderTitle: sortableTitle('Conversions', 'conversions'),
+ render: ConversionsCell,
+ align: 'right',
+ },
+ avg_time: {
+ renderTitle: sortableTitle('Avg. time', 'avg_time'),
+ render: AvgTimeCell,
+ align: 'right',
+ },
+ },
+ }),
+ []
+ )
+
+ return (
+ <>
+ <LemonBanner type="info" dismissKey="page-performance-alpha-info" className="mb-4">
+ One leaderboard for how each page earns visits from Google, AI assistants, and the agents crawling your
+ site. AI referrals are a lower bound: some assistants strip the referrer, so those visits land in
+ Direct.
+ </LemonBanner>
+ <OverviewGrid
+ items={overviewCards}
+ loading={overviewLoading && overviewCards.length === 0}
+ numSkeletons={4}
+ labelFromKey={(key) => OVERVIEW_CARD_LABELS[key] ?? key}
+ />
+ <div className="border rounded bg-surface-primary flex flex-col mt-4">
+ <div className="flex items-baseline justify-between gap-2 px-3 pt-3">
+ <h3 className="font-semibold m-0">Pages ranked by visitors</h3>
+ </div>
+ {pageDataError ? (
+ <LemonBanner type="error" className="m-3" action={{ children: 'Try again', onClick: loadPageData }}>
+ Could not load page performance. Try again to reload the leaderboard.
+ </LemonBanner>
+ ) : pageDataLoading && pageCandidates === null ? (
+ <div className="flex items-center justify-center py-12">
+ <Spinner className="text-2xl" />
+ </div>
+ ) : (
+ <Query
+ uniqueKey="page-performance-table"
+ query={pageTableQuery}
+ readOnly
+ context={context}
+ dataAttr="page-performance-table"
+ />
+ )}
+ <div className="text-secondary text-xs px-3 pb-3">{footerText}</div>
+ </div>
+ <div className="mt-4">
+ <h2 className="text-lg font-semibold mb-4">Traffic from AI</h2>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div className="md:col-span-2 min-h-[350px] flex flex-col">
+ <WebQuery
+ attachTo={webAnalyticsLogic}
+ uniqueKey="page-performance-ai-referrals-trend"
+ query={aiSectionQueries.referralTrend}
+ insightProps={createPagePerformanceInsightProps(TileId.AI_REFERRALS_TREND)}
+ showIntervalSelect
+ tileId={TileId.AI_REFERRALS_TREND}
+ headerSlot={cardHeading('Referrals over time')}
+ />
+ </div>
+ <AiTableCard
+ title="By engine"
+ query={aiSectionQueries.byEngine}
+ tileId={TileId.AI_REFERRALS_BY_ENGINE}
+ />
+ <AiTableCard
+ title="Landing pages from AI"
+ query={aiSectionQueries.landingPages}
+ tileId={TileId.AI_LANDING_PAGES}
+ />
+ </div>
+ </div>
+ <div className="mt-4">
+ <h2 className="text-lg font-semibold mb-4">AI crawlers</h2>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div className="md:col-span-2 min-h-[350px] flex flex-col">
+ <WebQuery
+ attachTo={webAnalyticsLogic}
+ uniqueKey="page-performance-ai-crawler-trend"
+ query={aiSectionQueries.crawlerTrend}
+ insightProps={createPagePerformanceInsightProps(TileId.AI_CRAWLERS_TREND)}
+ showIntervalSelect
+ tileId={TileId.AI_CRAWLERS_TREND}
+ headerSlot={cardHeading('Crawler activity over time')}
+ />
+ </div>
+ <AiTableCard title="By crawler" query={aiSectionQueries.byCrawler} tileId={TileId.AI_CRAWLERS} />
+ <AiTableCard
+ title="Pages they read"
+ query={aiSectionQueries.crawledPages}
+ tileId={TileId.AI_CRAWLED_PAGES}
+ />
+ </div>
+ </div>
+ <PagePerformanceBreakdownModal />
+ </>
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceBreakdownModal.tsx b/frontend/src/scenes/web-analytics/PagePerformanceBreakdownModal.tsx
new file mode 100644
index 000000000000..76a5bc8a611a
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/PagePerformanceBreakdownModal.tsx
@@ -0,0 +1,139 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'
+
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { IconOpenInNew } from 'lib/lemon-ui/icons'
+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+
+import { Query } from '~/queries/Query/Query'
+import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'
+import { InsightLogicProps } from '~/types'
+
+import { TileId, WEB_ANALYTICS_DEFAULT_QUERY_TAGS } from './common'
+import {
+ PagePerformanceMetric,
+ buildGoogleSearchConsoleQuery,
+ createPagePerformanceInsightProps,
+ pagePerformanceLogic,
+} from './pagePerformanceLogic'
+
+const GSC_DOCS_URL = 'https://posthog.com/docs/cdp/sources/google-search-console'
+const GSC_TABLE_NAME = 'search_analytics_by_query_page'
+
+const MODAL_TITLE: Record<PagePerformanceMetric, string> = {
+ llm_referrals: 'LLM referrals',
+ agent_crawls: 'Agent crawls',
+ google_search: 'Google search',
+}
+
+const MODAL_SUBTITLE: Record<PagePerformanceMetric, string> = {
+ llm_referrals: 'Human visitors this page received from AI assistants, by referring engine.',
+ agent_crawls: 'AI agents that crawled this page. Crawls are excluded from visitor counts.',
+ google_search: 'Search queries this page ranks for, from Google Search Console.',
+}
+
+const GoogleBreakdown = ({ page, insightProps }: { page: string; insightProps: InsightLogicProps }): JSX.Element => {
+ const { dataWarehouseTables, database, databaseLoading, databaseLoadError } = useValues(databaseTableListLogic)
+ const { loadDatabase } = useActions(databaseTableListLogic)
+ const { currentTeam, isPathCleaningEnabled, window } = useValues(pagePerformanceLogic)
+
+ useOnMountEffect(() => {
+ if (!database) {
+ loadDatabase()
+ }
+ })
+
+ const gscTable = dataWarehouseTables.find((t) => t.name.includes(GSC_TABLE_NAME))
+
+ if (!gscTable) {
+ if (databaseLoadError) {
+ return (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: () => loadDatabase({ force: true }) }}
+ >
+ Could not load data warehouse tables. Try again to check for your Google Search Console source.
+ </LemonBanner>
+ )
+ }
+ if (databaseLoading || !database) {
+ return (
+ <div className="flex items-center justify-center py-8">
+ <Spinner className="text-2xl" />
+ </div>
+ )
+ }
+ return (
+ <div className="flex flex-col items-center gap-3 py-8 text-center">
+ <p className="text-secondary max-w-md m-0">
+ Google Search Console shows the search queries and average positions each page ranks for. Connect it
+ as a data warehouse source to unlock this breakdown.
+ </p>
+ <LemonButton type="primary" to={GSC_DOCS_URL} targetBlank sideIcon={<IconOpenInNew />}>
+ Connect Google Search Console
+ </LemonButton>
+ </div>
+ )
+ }
+
+ const query: DataTableNode = {
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: buildGoogleSearchConsoleQuery(
+ gscTable.name,
+ page,
+ window,
+ isPathCleaningEnabled,
+ currentTeam?.path_cleaning_filters
+ ),
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ embedded: true,
+ showActions: false,
+ }
+ return <Query uniqueKey="page-performance-gsc-breakdown" query={query} readOnly context={{ insightProps }} />
+}
+
+export const PagePerformanceBreakdownModal = (): JSX.Element => {
+ const { breakdownModal, breakdownQuery } = useValues(pagePerformanceLogic)
+ const { closeBreakdown } = useActions(pagePerformanceLogic)
+
+ const isOpen = !!breakdownModal
+ const metric = breakdownModal?.metric ?? 'llm_referrals'
+ const page = breakdownModal?.page ?? ''
+ const insightProps = createPagePerformanceInsightProps(TileId.PAGE_PERFORMANCE_TABLE, 'modal')
+
+ let body: JSX.Element | null = null
+ if (metric === 'google_search' && isOpen) {
+ body = <GoogleBreakdown page={page} insightProps={insightProps} />
+ } else if (breakdownQuery) {
+ body = (
+ <Query
+ uniqueKey={`page-performance-${metric}-breakdown`}
+ query={breakdownQuery}
+ readOnly
+ context={{ insightProps }}
+ />
+ )
+ }
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={closeBreakdown}
+ title={`${MODAL_TITLE[metric]}: ${page || 'this page'}`}
+ description={MODAL_SUBTITLE[metric]}
+ width={640}
+ >
+ {metric === 'llm_referrals' && (
+ <LemonBanner type="info" className="mb-3">
+ These are people who arrived from an AI assistant, not the assistants' crawlers. Open{' '}
+ <strong>Agent crawls</strong> for the machines reading this page.
+ </LemonBanner>
+ )}
+ {body}
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceFilters.tsx b/frontend/src/scenes/web-analytics/PagePerformanceFilters.tsx
new file mode 100644
index 000000000000..375e076f7c1c
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/PagePerformanceFilters.tsx
@@ -0,0 +1,59 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh } from '@posthog/icons'
+import { LemonButton, Spinner } from '@posthog/lemon-ui'
+
+import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { FilterBar } from 'lib/components/FilterBar'
+
+import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+
+import { WEB_ANALYTICS_DATA_COLLECTION_NODE_ID } from './common'
+import { webAnalyticsDateMapping } from './constants'
+import { pagePerformanceLogic } from './pagePerformanceLogic'
+import { PathCleaningToggle } from './PathCleaningToggle'
+import { webAnalyticsLogic } from './webAnalyticsLogic'
+import { WebConversionGoal } from './WebConversionGoal'
+
+export const PagePerformanceFilters = ({ tabs }: { tabs: JSX.Element }): JSX.Element => {
+ const {
+ dateFilter: { dateTo, dateFrom },
+ compareFilter,
+ conversionGoal,
+ isPathCleaningEnabled,
+ } = useValues(webAnalyticsLogic)
+ const { setDates, setCompareFilter, setConversionGoal, setIsPathCleaningEnabled } = useActions(webAnalyticsLogic)
+ const { areAnyLoading } = useValues(dataNodeCollectionLogic({ key: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID }))
+ const { reloadAll } = useActions(dataNodeCollectionLogic({ key: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID }))
+ const { pageDataLoading } = useValues(pagePerformanceLogic)
+ const isReloading = areAnyLoading || pageDataLoading
+
+ return (
+ <FilterBar
+ top={tabs}
+ left={
+ <>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={reloadAll}
+ icon={isReloading ? <Spinner textColored /> : <IconRefresh />}
+ disabledReason={isReloading ? 'Loading' : undefined}
+ aria-label="Reload page performance"
+ />
+ <DateFilter
+ dateOptions={webAnalyticsDateMapping}
+ allowTimePrecision
+ dateFrom={dateFrom}
+ dateTo={dateTo}
+ onChange={setDates}
+ />
+ <CompareFilter compareFilter={compareFilter} updateCompareFilter={setCompareFilter} />
+ <PathCleaningToggle value={isPathCleaningEnabled} onChange={setIsPathCleaningEnabled} />
+ </>
+ }
+ right={<WebConversionGoal value={conversionGoal} onChange={setConversionGoal} />}
+ />
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
index ccbf02320150..0314cda99ce7 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
@@ -63,6 +63,8 @@ import { botAnalyticsLogic } from './botAnalyticsLogic'
import { HealthStatusTab, webAnalyticsHealthLogic } from './health'
import { LiveBotTiles } from './LiveMetricsDashboard/LiveBotTiles'
import { LiveWebAnalyticsMetrics } from './LiveMetricsDashboard/LiveWebAnalyticsMetrics'
+import { PagePerformance } from './PagePerformance'
+import { PagePerformanceFilters } from './PagePerformanceFilters'
import { WebAnalyticsExport } from './WebAnalyticsExport'
import { WebAnalyticsFilters } from './WebAnalyticsFilters'
import { webAnalyticsModalLogic } from './webAnalyticsModalLogic'
@@ -643,6 +645,8 @@ const Filters = ({ tabs }: { tabs: JSX.Element }): JSX.Element | null => {
return null
case ProductTab.BOT_ANALYTICS:
return <BotAnalyticsFilters tabs={tabs} />
+ case ProductTab.PAGE_PERFORMANCE:
+ return <PagePerformanceFilters tabs={tabs} />
default:
return <WebAnalyticsFilters tabs={tabs} />
}
@@ -667,6 +671,10 @@ const MainContent = (): JSX.Element => {
return <BotAnalyticsTiles />
}
+ if (productTab === ProductTab.PAGE_PERFORMANCE) {
+ return <PagePerformance />
+ }
+
return <Tiles />
}
@@ -746,6 +754,29 @@ const botAnalyticsTab = (
]
}
+const pagePerformanceTab = (
+ featureFlags: FeatureFlagsSet
+): { key: ProductTab; label: string | JSX.Element; link: string }[] => {
+ if (!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]) {
+ return []
+ }
+
+ return [
+ {
+ key: ProductTab.PAGE_PERFORMANCE,
+ label: (
+ <div className="flex items-center gap-1">
+ Page performance
+ <LemonTag type="completion" className="uppercase">
+ Alpha
+ </LemonTag>
+ </div>
+ ),
+ link: urls.webAnalyticsPagePerformance(),
+ },
+ ]
+}
+
const WebAnalyticsSurveyModal = (): JSX.Element | null => {
const { surveyModalPath } = useValues(webAnalyticsLogic)
const { closeSurveyModal } = useActions(webAnalyticsLogic)
@@ -859,6 +890,7 @@ const WebAnalyticsTabs = (): JSX.Element => {
{ key: ProductTab.PAGE_REPORTS, label: 'Page reports', link: '/web/page-reports' },
...liveTab(),
...botAnalyticsTab(featureFlags),
+ ...pagePerformanceTab(featureFlags),
...healthTab(),
]}
sceneInset
diff --git a/frontend/src/scenes/web-analytics/common.ts b/frontend/src/scenes/web-analytics/common.ts
index ae33f6464de0..1228722a0591 100644
--- a/frontend/src/scenes/web-analytics/common.ts
+++ b/frontend/src/scenes/web-analytics/common.ts
@@ -98,6 +98,15 @@ export enum TileId {
BOT_AI_REFERRALS = 'BOT_AI_REFERRALS',
BOT_AI_ENGAGEMENT = 'BOT_AI_ENGAGEMENT',
BOT_CRAWLERS = 'BOT_CRAWLERS',
+
+ AI_REFERRALS_TREND = 'AI_REFERRALS_TREND',
+ AI_REFERRALS_BY_ENGINE = 'AI_REFERRALS_BY_ENGINE',
+ AI_LANDING_PAGES = 'AI_LANDING_PAGES',
+ AI_CRAWLERS_TREND = 'AI_CRAWLERS_TREND',
+ AI_CRAWLERS = 'AI_CRAWLERS',
+ AI_CRAWLED_PAGES = 'AI_CRAWLED_PAGES',
+
+ PAGE_PERFORMANCE_TABLE = 'PAGE_PERFORMANCE_TABLE',
}
export enum ProductTab {
@@ -109,6 +118,7 @@ export enum ProductTab {
HEALTH = 'health',
LIVE = 'live',
BOT_ANALYTICS = 'bots',
+ PAGE_PERFORMANCE = 'page-performance',
}
export type DeviceType = 'Desktop' | 'Mobile'
@@ -181,6 +191,15 @@ export const loadPriorityMap: Record<TileId, number> = {
[TileId.BOT_AI_REFERRALS]: 5,
[TileId.BOT_AI_ENGAGEMENT]: 6,
[TileId.BOT_CRAWLERS]: 7,
+
+ [TileId.AI_REFERRALS_TREND]: 3,
+ [TileId.AI_REFERRALS_BY_ENGINE]: 4,
+ [TileId.AI_LANDING_PAGES]: 5,
+ [TileId.AI_CRAWLERS_TREND]: 7,
+ [TileId.AI_CRAWLERS]: 8,
+ [TileId.AI_CRAWLED_PAGES]: 9,
+
+ [TileId.PAGE_PERFORMANCE_TABLE]: 1,
}
// To enable a tile here, you must update the QueryRunner to support it
@@ -253,6 +272,13 @@ export const TILE_LABELS: Record<TileId, string> = {
[TileId.BOT_AI_REFERRALS]: 'AI referral traffic',
[TileId.BOT_AI_ENGAGEMENT]: 'AI referral engagement',
[TileId.BOT_CRAWLERS]: 'Crawlers',
+ [TileId.AI_REFERRALS_TREND]: 'AI referrals over time',
+ [TileId.AI_REFERRALS_BY_ENGINE]: 'AI referrals by engine',
+ [TileId.AI_LANDING_PAGES]: 'Landing pages from AI',
+ [TileId.AI_CRAWLERS_TREND]: 'AI crawler activity over time',
+ [TileId.AI_CRAWLERS]: 'AI crawlers',
+ [TileId.AI_CRAWLED_PAGES]: 'Pages AI crawlers read',
+ [TileId.PAGE_PERFORMANCE_TABLE]: 'Page performance',
}
export interface BaseTile {
diff --git a/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts b/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts
new file mode 100644
index 000000000000..939cb1ca562b
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts
@@ -0,0 +1,111 @@
+import { dayjs } from 'lib/dayjs'
+
+import { CompareFilter } from '~/queries/schema/schema-general'
+
+import {
+ PagePerformanceWindow,
+ buildGoogleSearchConsoleQuery,
+ buildPagePerformanceTableQuery,
+ resolvePagePerformanceWindow,
+} from './pagePerformanceLogic'
+import { DateFilterState } from './webAnalyticsLogic'
+
+const dateFilter = (dateFrom: string | null, dateTo: string | null): DateFilterState => ({
+ dateFrom,
+ dateTo,
+ interval: 'day',
+ isIntervalManuallySet: false,
+})
+
+describe('pagePerformanceLogic', () => {
+ const timezone = 'America/Chicago'
+ const now = dayjs.tz('2026-08-13 12:00:00', timezone)
+
+ it.each([
+ {
+ name: 'keeps all-time ranges unbounded and disables comparison',
+ dates: dateFilter('all', null),
+ compare: { compare: true } as CompareFilter,
+ expectedCurrentFrom: null,
+ expectedCurrentTo: '2026-08-13 12:00:00',
+ expectedPreviousFrom: null,
+ expectedPreviousTo: null,
+ },
+ {
+ name: 'includes the full explicit end date in the team timezone',
+ dates: dateFilter('2026-08-01', '2026-08-05'),
+ compare: { compare: false } as CompareFilter,
+ expectedCurrentFrom: '2026-08-01 00:00:00',
+ expectedCurrentTo: '2026-08-05 23:59:59',
+ expectedPreviousFrom: null,
+ expectedPreviousTo: null,
+ },
+ {
+ name: 'anchors a custom comparison range at the current start',
+ dates: dateFilter('2026-08-01', '2026-08-05'),
+ compare: { compare: true, compare_to: '-1y' } as CompareFilter,
+ expectedCurrentFrom: '2026-08-01 00:00:00',
+ expectedCurrentTo: '2026-08-05 23:59:59',
+ expectedPreviousFrom: '2025-08-01 00:00:00',
+ expectedPreviousTo: '2025-08-05 23:59:59',
+ },
+ ])(
+ '$name',
+ ({ dates, compare, expectedCurrentFrom, expectedCurrentTo, expectedPreviousFrom, expectedPreviousTo }) => {
+ const window = resolvePagePerformanceWindow(dates, compare, timezone, now)
+
+ expect(window.currentFrom?.format('YYYY-MM-DD HH:mm:ss') ?? null).toBe(expectedCurrentFrom)
+ expect(window.currentTo.format('YYYY-MM-DD HH:mm:ss')).toBe(expectedCurrentTo)
+ expect(window.previousFrom?.format('YYYY-MM-DD HH:mm:ss') ?? null).toBe(expectedPreviousFrom)
+ expect(window.previousTo?.format('YYYY-MM-DD HH:mm:ss') ?? null).toBe(expectedPreviousTo)
+ }
+ )
+
+ it('bounds the leaderboard query and attributes duration to the previous page', () => {
+ const window: PagePerformanceWindow = {
+ currentFrom: dayjs.tz('2026-08-01', timezone),
+ currentTo: dayjs.tz('2026-08-05', timezone).endOf('day'),
+ previousFrom: null,
+ previousTo: null,
+ timezone,
+ }
+ const query = buildPagePerformanceTableQuery(
+ window,
+ { column: 'visitors', direction: 'DESC' },
+ null,
+ 'properties.$pathname',
+ 'properties.$prev_pageview_pathname',
+ ['one.example/pricing', 'two.example/pricing']
+ )
+
+ expect(query).toContain(
+ "concat(coalesce(properties.$host, ''), properties.$pathname) IN ('one.example/pricing', 'two.example/pricing')"
+ )
+ expect(query).toContain("event IN ('$pageview', '$screen', '$pageleave')")
+ expect(query).toContain('properties.$prev_pageview_pathname')
+ expect(query).toContain('LEFT JOIN')
+ expect(query).toContain('HAVING uniqIf')
+ expect(query).not.toContain('OR countIf')
+ })
+
+ it('builds an exact, date-bounded Search Console query with escaped identifiers', () => {
+ const window: PagePerformanceWindow = {
+ currentFrom: dayjs.tz('2026-08-01', timezone),
+ currentTo: dayjs.tz('2026-08-05', timezone).endOf('day'),
+ previousFrom: null,
+ previousTo: null,
+ timezone,
+ }
+ const query = buildGoogleSearchConsoleQuery('gsc_demo.search table', 'example.com/docs/:id', window, true, [
+ { regex: '/docs/[0-9]+', alias: '/docs/:id' },
+ ])
+
+ expect(query).toContain('FROM gsc_demo."search table"')
+ expect(query).toContain(
+ "concat(domain(page), replaceRegexpAll(path(page), '/docs/[0-9]+', '/docs/:id')) = 'example.com/docs/:id'"
+ )
+ expect(query).toContain("toDate(date) >= toDate('2026-08-01 00:00:00')")
+ expect(query).toContain("toDate(date) <= toDate('2026-08-05 23:59:59')")
+ expect(query).not.toContain('ILIKE')
+ })
+})
diff --git a/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts b/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
new file mode 100644
index 000000000000..7dfd0c08d1ef
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
@@ -0,0 +1,970 @@
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ isBreakpoint,
+ kea,
+ listeners,
+ path,
+ reducers,
+ selectors,
+} from 'kea'
+import { subscriptions } from 'kea-subscriptions'
+
+import { dayjs } from 'lib/dayjs'
+import { componentsToDayJs, dateStringToComponents, dateStringToDayJs } from 'lib/utils/dateFilters'
+import { isAbortedRequest } from 'lib/utils/requests'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { actionsModel } from '~/models/actionsModel'
+import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+import { OverviewItem } from '~/queries/nodes/OverviewGrid/OverviewGrid'
+import { performQuery } from '~/queries/query'
+import {
+ ActionConversionGoal,
+ CompareFilter,
+ CustomEventConversionGoal,
+ DataTableNode,
+ EventsNode,
+ GroupNode,
+ HogQLQuery,
+ InsightVizNode,
+ NodeKind,
+ TrendsFilter,
+ WebAnalyticsConversionGoal,
+ WebAnalyticsOrderByFields,
+ WebAnalyticsPropertyFilters,
+ WebBotsBreakdown,
+ WebStatsBreakdown,
+ WebStatsTableQuery,
+} from '~/queries/schema/schema-general'
+import { escapeDottedHogQLIdentifier, escapeHogQLString } from '~/queries/utils'
+import {
+ ActionType,
+ BaseMathType,
+ ChartDisplayType,
+ FilterLogicalOperator,
+ InsightLogicProps,
+ PropertyFilterType,
+ PropertyOperator,
+ TeamType,
+} from '~/types'
+
+import type { TeamPublicType } from '../../types'
+import {
+ BOT_ANALYTICS_EVENTS,
+ TileId,
+ WEB_ANALYTICS_DATA_COLLECTION_NODE_ID,
+ WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ getWebAnalyticsBreakdownFilter,
+ loadPriorityMap,
+} from './common'
+import { getDashboardItemId } from './insightsUtils'
+import { webAnalyticsLogic } from './webAnalyticsLogic'
+import type { DateFilterState } from './webAnalyticsLogic'
+
+const PAGE_PERFORMANCE_EVENTS = "('$pageview', '$screen', '$http_log')"
+
+const PAGE_TABLE_LIMIT = 20
+
+const PAGE_CANDIDATE_LIMIT = 200
+
+const HUMAN_VIEW = "(event = '$pageview' OR event = '$screen') AND NOT `$virt_is_bot`"
+
+const GOOGLE_VIEW = `${HUMAN_VIEW} AND session.$channel_type = 'Organic Search' AND session.$entry_referring_domain ILIKE '%google%'`
+
+const AI_VIEW = `${HUMAN_VIEW} AND session.$channel_type = 'AI'`
+
+const CRAWLER =
+ "`$virt_is_bot` = true AND `$virt_bot_name` != '' AND `$virt_traffic_category` IN ('ai_crawler', 'ai_assistant', 'ai_search')"
+
+export type PagePerformanceMetric = 'llm_referrals' | 'agent_crawls' | 'google_search'
+
+export interface PagePerformanceBreakdownState {
+ page: string
+ metric: PagePerformanceMetric
+}
+
+export interface PagePerformanceOrderBy {
+ column: string
+ direction: 'ASC' | 'DESC'
+}
+
+export interface PagePerformanceWindow {
+ currentFrom: dayjs.Dayjs | null
+ currentTo: dayjs.Dayjs
+ previousFrom: dayjs.Dayjs | null
+ previousTo: dayjs.Dayjs | null
+ timezone: string
+}
+
+export interface OverviewTotals {
+ visitors: number
+ visitorsPrevious: number
+ google: number
+ googlePrevious: number
+ llm: number
+ llmPrevious: number
+ crawls: number
+ crawlsPrevious: number
+ pages: number
+}
+
+export interface AiSectionQueries {
+ referralTrend: InsightVizNode
+ byEngine: DataTableNode
+ landingPages: DataTableNode
+ crawlerTrend: InsightVizNode
+ byCrawler: DataTableNode
+ crawledPages: DataTableNode
+}
+
+export const OVERVIEW_CARD_LABELS: Record<string, string> = {
+ visitors: 'Visitors',
+ google_search: 'Google search',
+ llm_referrals: 'LLM referrals',
+ agent_crawls: 'Agent crawls',
+}
+
+const tsLiteral = (date: dayjs.Dayjs, timezone: string): string => date.tz(timezone).format("'YYYY-MM-DD HH:mm:ss'")
+
+const conversionMatch = (conversionGoal: WebAnalyticsConversionGoal | null): string | null => {
+ if (conversionGoal && 'actionId' in conversionGoal) {
+ return `matchesAction(${(conversionGoal as ActionConversionGoal).actionId})`
+ }
+ if (conversionGoal && 'customEventName' in conversionGoal) {
+ return `event = ${escapeHogQLString((conversionGoal as CustomEventConversionGoal).customEventName)}`
+ }
+ return null
+}
+
+const RAW_PATH = 'properties.$pathname'
+
+export const buildPagePerformancePathExpr = (
+ source: string,
+ enabled: boolean,
+ filters: { regex?: string; alias?: string }[] | undefined
+): string => {
+ if (!enabled || !filters?.length) {
+ return source
+ }
+ let expr = source
+ for (const f of filters) {
+ if (f.regex && f.alias != null) {
+ expr = `replaceRegexpAll(${expr}, ${escapeHogQLString(f.regex)}, ${escapeHogQLString(f.alias)})`
+ }
+ }
+ return expr
+}
+
+export const resolvePagePerformanceWindow = (
+ dateFilter: DateFilterState,
+ compareFilter: CompareFilter,
+ timezone: string,
+ now: dayjs.Dayjs = dayjs().tz(timezone)
+): PagePerformanceWindow => {
+ const currentFrom =
+ dateFilter.dateFrom === 'all'
+ ? null
+ : (dateStringToDayJs(dateFilter.dateFrom, timezone) ?? now.subtract(7, 'day'))
+ const parsedCurrentTo = dateFilter.dateTo ? dateStringToDayJs(dateFilter.dateTo, timezone) : null
+ const currentTo =
+ parsedCurrentTo && /^\d{4}-\d{2}-\d{2}$/.test(dateFilter.dateTo ?? '')
+ ? parsedCurrentTo.endOf('day')
+ : (parsedCurrentTo ?? now)
+
+ if (!compareFilter.compare || !currentFrom) {
+ return { currentFrom, currentTo, previousFrom: null, previousTo: null, timezone }
+ }
+
+ const spanMs = Math.max(currentTo.diff(currentFrom), 1)
+ const compareToComponents = dateStringToComponents(compareFilter.compare_to ?? null)
+ const previousFrom = compareToComponents
+ ? componentsToDayJs(compareToComponents, currentFrom, timezone)
+ : currentFrom.subtract(spanMs, 'millisecond')
+ const previousTo = compareToComponents ? previousFrom.add(spanMs, 'millisecond') : currentFrom
+
+ return { currentFrom, currentTo, previousFrom, previousTo, timezone }
+}
+
+const SORTABLE_COLUMNS = new Set([
+ 'breakdown_value',
+ 'visitors',
+ 'google_search',
+ 'llm_referrals',
+ 'agent_crawls',
+ 'conversions',
+ 'avg_time',
+])
+const orderByExpr = (column: string): string =>
+ `"context.columns.${SORTABLE_COLUMNS.has(column) ? column : 'visitors'}"`
+
+const windowPredicates = (window: PagePerformanceWindow): { cur: string; prev: string; full: string } => {
+ const upperBound = `timestamp <= ${tsLiteral(window.currentTo, window.timezone)}`
+ const cur = window.currentFrom
+ ? `timestamp >= ${tsLiteral(window.currentFrom, window.timezone)} AND ${upperBound}`
+ : upperBound
+ const prev =
+ window.previousFrom && window.previousTo
+ ? `timestamp >= ${tsLiteral(window.previousFrom, window.timezone)} AND timestamp < ${tsLiteral(window.previousTo, window.timezone)}`
+ : 'false'
+ return { cur, prev, full: `(${cur}) OR (${prev})` }
+}
+
+const pageKeyExpr = (pathExpr: string): string => `concat(coalesce(properties.$host, ''), ${pathExpr})`
+
+const pageCandidatesPredicate = (pageKey: string, candidates: string[]): string =>
+ candidates.length > 0 ? `${pageKey} IN (${candidates.map(escapeHogQLString).join(', ')})` : 'false'
+
+export const buildPagePerformanceTableQuery = (
+ window: PagePerformanceWindow,
+ orderBy: PagePerformanceOrderBy,
+ conversionGoal: WebAnalyticsConversionGoal | null,
+ pathExpr: string,
+ previousPathExpr: string,
+ candidates: string[]
+): string => {
+ const { cur, prev, full } = windowPredicates(window)
+ const pageKey = pageKeyExpr(pathExpr)
+ const previousPageKey = pageKeyExpr(previousPathExpr)
+ const candidatePredicate = pageCandidatesPredicate(pageKeyExpr(RAW_PATH), candidates)
+ const previousCandidatePredicate = pageCandidatesPredicate(
+ pageKeyExpr('properties.$prev_pageview_pathname'),
+ candidates
+ )
+
+ const match = conversionMatch(conversionGoal)
+ const conversions = match
+ ? `tuple(countIf((${match}) AND ${cur}), uniqIf(person_id, (${HUMAN_VIEW}) AND ${cur}))`
+ : 'tuple(0, 0)'
+
+ const orderExpr = orderByExpr(orderBy.column)
+
+ return `
+SELECT
+ ${pageKey} AS "context.columns.breakdown_value",
+ tuple(
+ uniqIf(person_id, (${HUMAN_VIEW}) AND ${cur}),
+ uniqIf(person_id, (${HUMAN_VIEW}) AND ${prev})
+ ) AS "context.columns.visitors",
+ tuple(
+ uniqIf(person_id, (${GOOGLE_VIEW}) AND ${cur}),
+ uniqIf(person_id, (${HUMAN_VIEW}) AND ${cur})
+ ) AS "context.columns.google_search",
+ tuple(
+ uniqIf(person_id, (${AI_VIEW}) AND ${cur}),
+ uniqIf(person_id, (${AI_VIEW}) AND ${prev})
+ ) AS "context.columns.llm_referrals",
+ tuple(
+ countIf((${CRAWLER}) AND ${cur}),
+ uniqIf(\`$virt_bot_name\`, (${CRAWLER}) AND ${cur})
+ ) AS "context.columns.agent_crawls",
+ ${conversions} AS "context.columns.conversions",
+ any(page_durations.avg_time) AS "context.columns.avg_time"
+FROM events
+LEFT JOIN (
+ SELECT
+ ${previousPageKey} AS page_key,
+ quantile(0.90)(least(toFloat(properties.$prev_pageview_duration), 86400)) AS avg_time
+ FROM events
+ WHERE and(
+ event IN ('$pageview', '$screen', '$pageleave'),
+ properties.$prev_pageview_pathname IS NOT NULL,
+ properties.$prev_pageview_duration IS NOT NULL,
+ (${previousCandidatePredicate}),
+ (${cur}),
+ {filters}
+ )
+ GROUP BY page_key
+) AS page_durations ON page_durations.page_key = ${pageKey}
+WHERE and(
+ (event IN ${PAGE_PERFORMANCE_EVENTS}${match ? ` OR (${match})` : ''}),
+ properties.$pathname IS NOT NULL,
+ properties.$pathname != '',
+ (${candidatePredicate}),
+ (${full}),
+ {filters}
+)
+GROUP BY "context.columns.breakdown_value"
+HAVING uniqIf(person_id, (${HUMAN_VIEW}) AND ${cur}) > 0
+ORDER BY ${orderExpr} ${orderBy.direction}
+LIMIT ${PAGE_TABLE_LIMIT}
+`
+}
+
+const buildOverviewQuery = (window: PagePerformanceWindow, pathExpr: string): string => {
+ const { cur, prev, full } = windowPredicates(window)
+ const pageKey = pageKeyExpr(pathExpr)
+
+ return `
+SELECT
+ uniqIf(person_id, (${HUMAN_VIEW}) AND ${cur}) AS visitors,
+ uniqIf(person_id, (${HUMAN_VIEW}) AND ${prev}) AS visitors_previous,
+ uniqIf(person_id, (${GOOGLE_VIEW}) AND ${cur}) AS google,
+ uniqIf(person_id, (${GOOGLE_VIEW}) AND ${prev}) AS google_previous,
+ uniqIf(person_id, (${AI_VIEW}) AND ${cur}) AS llm,
+ uniqIf(person_id, (${AI_VIEW}) AND ${prev}) AS llm_previous,
+ countIf((${CRAWLER}) AND ${cur}) AS crawls,
+ countIf((${CRAWLER}) AND ${prev}) AS crawls_previous,
+ uniqIf(${pageKey}, (${HUMAN_VIEW}) AND ${cur}) AS pages
+FROM events
+WHERE and(
+ event IN ${PAGE_PERFORMANCE_EVENTS},
+ properties.$pathname IS NOT NULL,
+ properties.$pathname != '',
+ (${full}),
+ {filters}
+)
+`
+}
+
+const buildBreakdownQuery = (
+ metric: PagePerformanceMetric,
+ page: string,
+ window: PagePerformanceWindow,
+ pathExpr: string
+): string | null => {
+ const { cur } = windowPredicates(window)
+ const pageMatch = `${pageKeyExpr(pathExpr)} = ${escapeHogQLString(page)}`
+
+ if (metric === 'llm_referrals') {
+ return `
+SELECT
+ coalesce(nullIf(session.$entry_referring_domain, ''), '(direct)') AS "Assistant",
+ uniq(person_id) AS "Visitors"
+FROM events
+WHERE and(${AI_VIEW}, ${pageMatch}, (${cur}), {filters})
+GROUP BY "Assistant"
+ORDER BY "Visitors" DESC
+LIMIT 10
+`
+ }
+ if (metric === 'agent_crawls') {
+ return `
+SELECT
+ \`$virt_bot_name\` AS "Crawler",
+ \`$virt_traffic_category\` AS "Category",
+ count() AS "Requests",
+ max(timestamp) AS "Last seen"
+FROM events
+WHERE and(${CRAWLER}, event IN ${PAGE_PERFORMANCE_EVENTS}, ${pageMatch}, (${cur}), {filters})
+GROUP BY "Crawler", "Category"
+ORDER BY "Requests" DESC
+LIMIT 50
+`
+ }
+ return null
+}
+
+export const buildGoogleSearchConsoleQuery = (
+ tableName: string,
+ page: string,
+ window: PagePerformanceWindow,
+ isPathCleaningEnabled: boolean,
+ pathCleaningFilters: { regex?: string; alias?: string }[] | undefined
+): string => {
+ const gscPath = buildPagePerformancePathExpr('path(page)', isPathCleaningEnabled, pathCleaningFilters)
+ const gscPageKey = `concat(domain(page), ${gscPath})`
+ const dateField = 'toDate(date)'
+ const dateUpperBound = `${dateField} <= toDate(${tsLiteral(window.currentTo, window.timezone)})`
+ const datePredicate = window.currentFrom
+ ? `${dateField} >= toDate(${tsLiteral(window.currentFrom, window.timezone)}) AND ${dateUpperBound}`
+ : dateUpperBound
+
+ return `SELECT query AS "Query", sum(clicks) AS "Clicks", round(avg(position), 1) AS "Avg. position"
+FROM ${escapeDottedHogQLIdentifier(tableName)}
+WHERE ${gscPageKey} = ${escapeHogQLString(page)} AND (${datePredicate})
+GROUP BY query
+ORDER BY sum(clicks) DESC
+LIMIT 20`
+}
+
+export interface pagePerformanceLogicValues {
+ allActions: ActionType[]
+ currentTeam: TeamPublicType | TeamType | null
+ compareFilter: CompareFilter
+ conversionGoal: WebAnalyticsConversionGoal | null
+ dateFilter: DateFilterState
+ filterTestAccounts: boolean
+ isPathCleaningEnabled: boolean
+ aiSectionQueries: AiSectionQueries
+ breakdownModal: PagePerformanceBreakdownState | null
+ breakdownQuery: DataTableNode | null
+ footerText: string
+ goalLabel: string | null
+ orderBy: PagePerformanceOrderBy
+ overviewCards: OverviewItem[]
+ overviewLoading: boolean
+ overviewQuery: string
+ overviewTotals: OverviewTotals | null
+ pageCandidateQuery: WebStatsTableQuery
+ pageCandidates: string[] | null
+ pageDataError: string | null
+ pageDataInput: string
+ pageDataLoading: boolean
+ pageTableQuery: DataTableNode
+ pathExpr: string
+ previousPathExpr: string
+ window: PagePerformanceWindow
+}
+
+export interface pagePerformanceLogicActions {
+ reloadAll: () => {}
+ closeBreakdown: () => {
+ value: true
+ }
+ loadPageData: () => {
+ value: true
+ }
+ loadPageDataFailure: (error: string) => {
+ error: string
+ }
+ loadPageDataSuccess: (
+ overviewTotals: OverviewTotals,
+ pageCandidates: string[]
+ ) => {
+ overviewTotals: OverviewTotals
+ pageCandidates: string[]
+ }
+ openBreakdown: (breakdown: PagePerformanceBreakdownState) => {
+ breakdown: PagePerformanceBreakdownState
+ }
+ setOrderBy: (
+ column: string,
+ direction: 'ASC' | 'DESC'
+ ) => {
+ column: string
+ direction: 'ASC' | 'DESC'
+ }
+}
+
+export interface pagePerformanceLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ window: (
+ dateFilter: DateFilterState,
+ compareFilter: CompareFilter,
+ currentTeam: TeamPublicType | TeamType | null
+ ) => PagePerformanceWindow
+ pathExpr: (isPathCleaningEnabled: boolean, currentTeam: TeamPublicType | TeamType | null) => string
+ previousPathExpr: (isPathCleaningEnabled: boolean, currentTeam: TeamPublicType | TeamType | null) => string
+ pageCandidateQuery: (dateFilter: DateFilterState, filterTestAccounts: boolean) => WebStatsTableQuery
+ pageTableQuery: (
+ window: PagePerformanceWindow,
+ orderBy: PagePerformanceOrderBy,
+ conversionGoal: WebAnalyticsConversionGoal | null,
+ filterTestAccounts: boolean,
+ pathExpr: string,
+ previousPathExpr: string,
+ pageCandidates: string[] | null
+ ) => DataTableNode
+ aiSectionQueries: (
+ dateFilter: DateFilterState,
+ filterTestAccounts: boolean,
+ conversionGoal: WebAnalyticsConversionGoal | null,
+ compareFilter: CompareFilter
+ ) => AiSectionQueries
+ overviewQuery: (window: PagePerformanceWindow, pathExpr: string) => string
+ pageDataInput: (overviewQuery: string, pageCandidateQuery: WebStatsTableQuery) => string
+ breakdownQuery: (
+ breakdownModal: PagePerformanceBreakdownState | null,
+ window: PagePerformanceWindow,
+ filterTestAccounts: boolean,
+ pathExpr: string
+ ) => DataTableNode | null
+ overviewCards: (overviewTotals: OverviewTotals | null, compareFilter: CompareFilter) => OverviewItem[]
+ goalLabel: (conversionGoal: WebAnalyticsConversionGoal | null, allActions: ActionType[]) => string | null
+ footerText: (
+ overviewTotals: OverviewTotals | null,
+ goalLabel: string | null,
+ isPathCleaningEnabled: boolean
+ ) => string
+ }
+}
+
+export type pagePerformanceLogicType = MakeLogicType<
+ pagePerformanceLogicValues,
+ pagePerformanceLogicActions,
+ Record<string, any>,
+ pagePerformanceLogicMeta
+>
+
+export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
+ path(['scenes', 'webAnalytics', 'pagePerformanceLogic']),
+ connect(() => ({
+ actions: [dataNodeCollectionLogic({ key: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID }), ['reloadAll']],
+ values: [
+ webAnalyticsLogic,
+ [
+ 'dateFilter',
+ 'shouldFilterTestAccounts as filterTestAccounts',
+ 'compareFilter',
+ 'conversionGoal',
+ 'isPathCleaningEnabled',
+ ],
+ teamLogic,
+ ['currentTeam'],
+ actionsModel,
+ ['actions as allActions'],
+ ],
+ })),
+ actions({
+ setOrderBy: (column: string, direction: 'ASC' | 'DESC') => ({ column, direction }),
+ openBreakdown: (breakdown: PagePerformanceBreakdownState) => ({ breakdown }),
+ closeBreakdown: true,
+ loadPageData: true,
+ loadPageDataFailure: (error: string) => ({ error }),
+ loadPageDataSuccess: (overviewTotals: OverviewTotals, pageCandidates: string[]) => ({
+ overviewTotals,
+ pageCandidates,
+ }),
+ }),
+ reducers({
+ orderBy: [
+ { column: 'visitors', direction: 'DESC' } as PagePerformanceOrderBy,
+ {
+ setOrderBy: (_, { column, direction }) => ({ column, direction }),
+ },
+ ],
+ breakdownModal: [
+ null as PagePerformanceBreakdownState | null,
+ {
+ openBreakdown: (_, { breakdown }) => breakdown,
+ closeBreakdown: () => null,
+ },
+ ],
+ overviewTotals: [
+ null as OverviewTotals | null,
+ {
+ loadPageData: () => null,
+ loadPageDataSuccess: (_, { overviewTotals }) => overviewTotals,
+ },
+ ],
+ pageCandidates: [
+ null as string[] | null,
+ {
+ loadPageData: () => null,
+ loadPageDataSuccess: (_, { pageCandidates }) => pageCandidates,
+ },
+ ],
+ pageDataError: [
+ null as string | null,
+ {
+ loadPageData: () => null,
+ loadPageDataFailure: (_, { error }) => error,
+ },
+ ],
+ pageDataLoading: [
+ false,
+ {
+ loadPageData: () => true,
+ loadPageDataSuccess: () => false,
+ loadPageDataFailure: () => false,
+ },
+ ],
+ overviewLoading: [
+ false,
+ {
+ loadPageData: () => true,
+ loadPageDataSuccess: () => false,
+ loadPageDataFailure: () => false,
+ },
+ ],
+ }),
+ selectors(() => ({
+ window: [
+ (s) => [s.dateFilter, s.compareFilter, s.currentTeam],
+ (
+ dateFilter: DateFilterState,
+ compareFilter: CompareFilter,
+ currentTeam: TeamPublicType | TeamType | null
+ ): PagePerformanceWindow =>
+ resolvePagePerformanceWindow(dateFilter, compareFilter, currentTeam?.timezone ?? 'UTC'),
+ ],
+ pathExpr: [
+ (s) => [s.isPathCleaningEnabled, s.currentTeam],
+ (isPathCleaningEnabled: boolean, currentTeam: TeamType | null): string =>
+ buildPagePerformancePathExpr(RAW_PATH, isPathCleaningEnabled, currentTeam?.path_cleaning_filters),
+ ],
+ previousPathExpr: [
+ (s) => [s.isPathCleaningEnabled, s.currentTeam],
+ (isPathCleaningEnabled: boolean, currentTeam: TeamType | null): string =>
+ buildPagePerformancePathExpr(
+ 'properties.$prev_pageview_pathname',
+ isPathCleaningEnabled,
+ currentTeam?.path_cleaning_filters
+ ),
+ ],
+ pageCandidateQuery: [
+ (s) => [s.dateFilter, s.filterTestAccounts],
+ (dateFilter: DateFilterState, filterTestAccounts: boolean): WebStatsTableQuery => ({
+ kind: NodeKind.WebStatsTableQuery,
+ breakdownBy: WebStatsBreakdown.Page,
+ dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },
+ properties: [],
+ compareFilter: { compare: false },
+ doPathCleaning: false,
+ filterTestAccounts,
+ includeHost: true,
+ limit: PAGE_CANDIDATE_LIMIT,
+ orderBy: [WebAnalyticsOrderByFields.Visitors, 'DESC'],
+ useWebAnalyticsPrecompute: true,
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ }),
+ ],
+ pageTableQuery: [
+ (s) => [
+ s.window,
+ s.orderBy,
+ s.conversionGoal,
+ s.filterTestAccounts,
+ s.pathExpr,
+ s.previousPathExpr,
+ s.pageCandidates,
+ ],
+ (
+ window: PagePerformanceWindow,
+ orderBy: PagePerformanceOrderBy,
+ conversionGoal: WebAnalyticsConversionGoal | null,
+ filterTestAccounts: boolean,
+ pathExpr: string,
+ previousPathExpr: string,
+ pageCandidates: string[] | null
+ ): DataTableNode => ({
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: buildPagePerformanceTableQuery(
+ window,
+ orderBy,
+ conversionGoal,
+ pathExpr,
+ previousPathExpr,
+ pageCandidates ?? []
+ ),
+ filters: { filterTestAccounts },
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ embedded: true,
+ showActions: false,
+ columns: [
+ 'context.columns.breakdown_value',
+ 'context.columns.visitors',
+ 'context.columns.google_search',
+ 'context.columns.llm_referrals',
+ 'context.columns.agent_crawls',
+ 'context.columns.conversions',
+ 'context.columns.avg_time',
+ ],
+ }),
+ ],
+ aiSectionQueries: [
+ (s) => [s.dateFilter, s.filterTestAccounts, s.conversionGoal, s.compareFilter],
+ (
+ dateFilter: DateFilterState,
+ filterTestAccounts: boolean,
+ conversionGoal: WebAnalyticsConversionGoal | null,
+ compareFilter: CompareFilter
+ ): AiSectionQueries => {
+ const dateRange = { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo }
+ const interval = dateFilter.interval
+
+ const referralFilters: WebAnalyticsPropertyFilters = [
+ {
+ key: '$channel_type',
+ value: ['AI'],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Session,
+ },
+ ]
+ const crawlerFilters: WebAnalyticsPropertyFilters = [
+ {
+ key: '$virt_is_bot',
+ value: ['true'],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ {
+ key: '$virt_bot_name',
+ value: [''],
+ operator: PropertyOperator.IsNot,
+ type: PropertyFilterType.Event,
+ },
+ {
+ key: '$virt_traffic_category',
+ value: ['ai_crawler', 'ai_assistant', 'ai_search'],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ ]
+
+ const referralColumns = [
+ 'breakdown_value',
+ 'visitors',
+ 'views',
+ ...(conversionGoal ? ['total_conversions', 'conversion_rate'] : []),
+ 'cross_sell',
+ ]
+
+ const referralTable = (breakdownBy: WebStatsBreakdown): DataTableNode => ({
+ full: true,
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.WebStatsTableQuery,
+ properties: referralFilters,
+ breakdownBy,
+ dateRange,
+ compareFilter,
+ conversionGoal,
+ limit: 10,
+ filterTestAccounts,
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ embedded: false,
+ showActions: true,
+ columns: referralColumns,
+ })
+
+ const crawlerTable = (breakdownBy: WebBotsBreakdown): DataTableNode => ({
+ full: true,
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.WebBotsTableQuery,
+ breakdownBy,
+ dateRange,
+ properties: crawlerFilters,
+ limit: 10,
+ filterTestAccounts,
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ showActions: false,
+ embedded: false,
+ })
+
+ const crawlerRequestSeries: GroupNode[] = [
+ {
+ kind: NodeKind.GroupNode,
+ name: BOT_ANALYTICS_EVENTS.join(', '),
+ custom_name: 'Requests',
+ operator: FilterLogicalOperator.Or,
+ nodes: BOT_ANALYTICS_EVENTS.map(
+ (event): EventsNode => ({
+ event,
+ kind: NodeKind.EventsNode as const,
+ math: BaseMathType.TotalCount,
+ name: event,
+ })
+ ),
+ math: BaseMathType.TotalCount,
+ },
+ ]
+
+ return {
+ referralTrend: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ dateRange,
+ interval,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: '$pageview',
+ name: '$pageview',
+ math: BaseMathType.UniqueSessions,
+ },
+ ],
+ trendsFilter: {
+ display: ChartDisplayType.ActionsLineGraph,
+ showLegend: true,
+ } as TrendsFilter,
+ breakdownFilter: getWebAnalyticsBreakdownFilter(WebStatsBreakdown.InitialReferringDomain),
+ properties: referralFilters,
+ filterTestAccounts,
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ hidePersonsModal: true,
+ embedded: true,
+ },
+ byEngine: referralTable(WebStatsBreakdown.InitialReferringDomain),
+ landingPages: referralTable(WebStatsBreakdown.InitialPage),
+ crawlerTrend: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ dateRange,
+ interval,
+ series: crawlerRequestSeries,
+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph } as TrendsFilter,
+ properties: crawlerFilters,
+ filterTestAccounts,
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ hidePersonsModal: true,
+ embedded: true,
+ },
+ byCrawler: crawlerTable(WebBotsBreakdown.Crawler),
+ crawledPages: crawlerTable(WebBotsBreakdown.Path),
+ }
+ },
+ ],
+ overviewQuery: [
+ (s) => [s.window, s.pathExpr],
+ (window: PagePerformanceWindow, pathExpr: string): string => buildOverviewQuery(window, pathExpr),
+ ],
+ pageDataInput: [
+ (s) => [s.overviewQuery, s.pageCandidateQuery],
+ (overviewQuery: string, pageCandidateQuery: WebStatsTableQuery): string =>
+ JSON.stringify([overviewQuery, pageCandidateQuery]),
+ ],
+ breakdownQuery: [
+ (s) => [s.breakdownModal, s.window, s.filterTestAccounts, s.pathExpr],
+ (
+ breakdownModal: PagePerformanceBreakdownState | null,
+ window: PagePerformanceWindow,
+ filterTestAccounts: boolean,
+ pathExpr: string
+ ): DataTableNode | null => {
+ if (!breakdownModal) {
+ return null
+ }
+ const query = buildBreakdownQuery(breakdownModal.metric, breakdownModal.page, window, pathExpr)
+ if (!query) {
+ return null
+ }
+ return {
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query,
+ filters: { filterTestAccounts },
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ embedded: true,
+ showActions: false,
+ }
+ },
+ ],
+ overviewCards: [
+ (s) => [s.overviewTotals, s.compareFilter],
+ (overviewTotals: OverviewTotals | null, compareFilter: CompareFilter): OverviewItem[] => {
+ const compare = compareFilter.compare !== false
+ const card = (key: string, value: number, previous: number): OverviewItem => ({
+ key,
+ value,
+ previous: compare ? previous : undefined,
+ changeFromPreviousPct:
+ compare && previous > 0 ? Math.round(((value - previous) / previous) * 100) : undefined,
+ kind: 'unit',
+ })
+ const t = overviewTotals
+ if (!t) {
+ return []
+ }
+ return [
+ card('visitors', t.visitors, t.visitorsPrevious),
+ card('google_search', t.google, t.googlePrevious),
+ card('llm_referrals', t.llm, t.llmPrevious),
+ card('agent_crawls', t.crawls, t.crawlsPrevious),
+ ]
+ },
+ ],
+ goalLabel: [
+ (s) => [s.conversionGoal, s.allActions],
+ (conversionGoal: WebAnalyticsConversionGoal | null, allActions: ActionType[]): string | null => {
+ if (!conversionGoal) {
+ return null
+ }
+ if ('actionId' in conversionGoal) {
+ return allActions.find((a) => a.id === conversionGoal.actionId)?.name ?? 'Conversion goal'
+ }
+ return conversionGoal.customEventName
+ },
+ ],
+ footerText: [
+ (s) => [s.overviewTotals, s.goalLabel, s.isPathCleaningEnabled],
+ (
+ overviewTotals: OverviewTotals | null,
+ goalLabel: string | null,
+ isPathCleaningEnabled: boolean
+ ): string => {
+ const pages = overviewTotals?.pages ?? 0
+ return [
+ `${pages} ${pages === 1 ? 'page' : 'pages'}`,
+ `conversion goal: ${goalLabel ?? 'not set'}`,
+ `path cleaning ${isPathCleaningEnabled ? 'on' : 'off'}`,
+ ].join(' · ')
+ },
+ ],
+ })),
+ listeners(({ values, actions, cache }) => ({
+ loadPageData: async (_, breakpoint) => {
+ await breakpoint(300)
+ cache.disposables.dispose('pageDataRequest')
+ const abortController = new AbortController()
+ cache.disposables.add(() => abortController.abort(), 'pageDataRequest')
+
+ const overviewNode: HogQLQuery = {
+ kind: NodeKind.HogQLQuery,
+ query: values.overviewQuery,
+ filters: { filterTestAccounts: values.filterTestAccounts },
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ }
+ try {
+ const [overviewResponse, candidatesResponse] = await Promise.all([
+ performQuery(overviewNode, { signal: abortController.signal }),
+ performQuery(values.pageCandidateQuery, { signal: abortController.signal }),
+ ])
+ breakpoint()
+ const row = overviewResponse.results?.[0] ?? []
+ const columns: string[] = overviewResponse.columns ?? []
+ const at = (name: string): number => {
+ const idx = columns.indexOf(name)
+ return idx >= 0 ? Number(row[idx] ?? 0) : 0
+ }
+ const pageCandidates = (candidatesResponse.results ?? []).flatMap((candidate) => {
+ if (!Array.isArray(candidate) || typeof candidate[0] !== 'string' || candidate[0] === '') {
+ return []
+ }
+ return [candidate[0]]
+ })
+ actions.loadPageDataSuccess(
+ {
+ visitors: at('visitors'),
+ visitorsPrevious: at('visitors_previous'),
+ google: at('google'),
+ googlePrevious: at('google_previous'),
+ llm: at('llm'),
+ llmPrevious: at('llm_previous'),
+ crawls: at('crawls'),
+ crawlsPrevious: at('crawls_previous'),
+ pages: at('pages'),
+ },
+ pageCandidates
+ )
+ } catch (error) {
+ if ((error instanceof Error && isBreakpoint(error)) || isAbortedRequest(error)) {
+ return
+ }
+ actions.loadPageDataFailure(error instanceof Error ? error.message : 'Could not load page performance')
+ }
+ },
+ reloadAll: () => {
+ actions.loadPageData()
+ },
+ })),
+ subscriptions(({ actions }) => ({
+ pageDataInput: () => {
+ actions.loadPageData()
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadPageData()
+ }),
+])
+
+export const createPagePerformanceInsightProps = (tile: TileId, tab?: string): InsightLogicProps => ({
+ dashboardItemId: getDashboardItemId(tile, tab, false),
+ loadPriority: loadPriorityMap[tile],
+ dataNodeCollectionId: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID,
+})
diff --git a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx
index 4414f6d98a16..aa711fbcc7ac 100644
--- a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx
+++ b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx
@@ -68,6 +68,7 @@ import {
ProductKey,
QuerySchema,
WebAnalyticsOrderByFields,
+ WebAnalyticsPropertyFilters,
WebStatsBreakdown,
WebVitalsPathBreakdownQuery,
} from '~/queries/schema/schema-general'
@@ -1408,19 +1409,23 @@ interface HogQLTableTileProps {
headerSlot?: React.ReactNode
}
-// Bot tiles get their own variant so botAnalyticsLogic only mounts on the Bot Analytics tab —
-// `HogQLTableTile` is reused for any HogQLQuery DataTableNode and shouldn't depend on bot state.
-const BOT_HOGQL_TILES = new Set<TileId>([TileId.BOT_CRAWLERS, TileId.BOT_PATHS])
-
-const BotHogQLTableTile = ({ uniqueKey, attachTo, query, insightProps, tileId }: HogQLTableTileProps): JSX.Element => {
- const { setBotAnalyticsFilters } = useActions(botAnalyticsLogic)
- const { rawBotAnalyticsFilters } = useValues(botAnalyticsLogic)
-
- const context = useMemo((): QueryContext => {
- // Single-select toggle: clicking the same value clears it, any other click replaces.
+const useSingleSelectDrilldownContext = ({
+ insightProps,
+ filters,
+ setFilters,
+ filterKey,
+ filterType,
+}: {
+ insightProps: InsightLogicProps
+ filters: WebAnalyticsPropertyFilters
+ setFilters: (filters: WebAnalyticsPropertyFilters) => void
+ filterKey: string | undefined
+ filterType: PropertyFilterType.Event | PropertyFilterType.Session
+}): QueryContext =>
+ useMemo((): QueryContext => {
const toggleFilter = (key: string, value: string): void => {
- const existing = rawBotAnalyticsFilters.find((f) => 'key' in f && f.key === key)
- const otherFilters = rawBotAnalyticsFilters.filter((f) => !('key' in f && f.key === key))
+ const existing = filters.find((f) => 'key' in f && f.key === key)
+ const otherFilters = filters.filter((f) => !('key' in f && f.key === key))
const existingValues =
existing && 'value' in existing
? Array.isArray(existing.value)
@@ -1428,28 +1433,19 @@ const BotHogQLTableTile = ({ uniqueKey, attachTo, query, insightProps, tileId }:
: [existing.value]
: []
if (existingValues.length === 1 && existingValues[0] === value) {
- setBotAnalyticsFilters(otherFilters)
+ setFilters(otherFilters)
return
}
- setBotAnalyticsFilters([
- ...otherFilters,
- {
- key,
- value: [value],
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- },
- ])
+ setFilters([...otherFilters, { key, value: [value], operator: PropertyOperator.Exact, type: filterType }])
}
- const filterKey = tileId === TileId.BOT_CRAWLERS ? '$virt_bot_name' : '$pathname'
return {
...webAnalyticsDataTableQueryContext,
insightProps,
rowProps: (record: unknown) => {
const result = (record as { result?: unknown[] })?.result
const value = Array.isArray(result) ? (result[0] as string) : null
- if (!value) {
+ if (!value || !filterKey) {
return {}
}
return {
@@ -1458,7 +1454,21 @@ const BotHogQLTableTile = ({ uniqueKey, attachTo, query, insightProps, tileId }:
}
},
}
- }, [insightProps, tileId, rawBotAnalyticsFilters, setBotAnalyticsFilters])
+ }, [insightProps, filters, setFilters, filterKey, filterType])
+
+const BOT_HOGQL_TILES = new Set<TileId>([TileId.BOT_CRAWLERS, TileId.BOT_PATHS])
+
+const BotHogQLTableTile = ({ uniqueKey, attachTo, query, insightProps, tileId }: HogQLTableTileProps): JSX.Element => {
+ const { setBotAnalyticsFilters } = useActions(botAnalyticsLogic)
+ const { rawBotAnalyticsFilters } = useValues(botAnalyticsLogic)
+
+ const context = useSingleSelectDrilldownContext({
+ insightProps,
+ filters: rawBotAnalyticsFilters,
+ setFilters: setBotAnalyticsFilters,
+ filterKey: tileId === TileId.BOT_CRAWLERS ? '$virt_bot_name' : '$pathname',
+ filterType: PropertyFilterType.Event,
+ })
const dataNodeLogicProps = buildDataTableTileDataNodeLogicProps({ query, insightProps, context, uniqueKey })
return (
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
index 6ce7e8e77d82..d61a03cc26f9 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
@@ -476,6 +476,29 @@ describe('webAnalyticsLogic URL restoration', () => {
expect(router.values.searchParams[key]).toBe(expected)
})
+ it('keeps all page performance controls in the shareable URL', async () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE], {
+ [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]: true,
+ })
+ logic.actions.setProductTab(ProductTab.PAGE_PERFORMANCE)
+ logic.actions.setDates('-30d', '2026-08-05')
+ logic.actions.setConversionGoal({ actionId: 42 })
+ logic.actions.setCompareFilter({ compare: true, compare_to: '-1y' })
+ logic.actions.setIsPathCleaningEnabled(false)
+ logic.actions.setShouldFilterTestAccounts(true)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.location.pathname.endsWith('/web/page-performance')).toBe(true)
+ expect(router.values.searchParams).toMatchObject({
+ date_from: '-30d',
+ date_to: '2026-08-05',
+ 'conversionGoal.actionId': 42,
+ compare_filter: { compare: true, compare_to: '-1y' },
+ path_cleaning: false,
+ filter_test_accounts: true,
+ })
+ })
+
const enableBackNavReset = (): void => {
featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WEB_ANALYTICS_BACK_NAVIGATION_RESET], {
[FEATURE_FLAGS.WEB_ANALYTICS_BACK_NAVIGATION_RESET]: true,
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index 465a056ec095..c1bd97441cbb 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -3045,6 +3045,10 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
return []
}
+ if (productTab === ProductTab.PAGE_PERFORMANCE) {
+ return []
+ }
+
return allTiles
.filter(isNotNil)
.filter((tile) =>
@@ -3104,6 +3108,33 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
urlParams.set('interval', interval ?? '')
}
return `/web/bots${urlParams.toString() ? '?' + urlParams.toString() : ''}`
+ } else if (productTab === ProductTab.PAGE_PERFORMANCE) {
+ urlParams.delete('filters')
+ if (conversionGoal) {
+ if ('actionId' in conversionGoal) {
+ urlParams.set('conversionGoal.actionId', conversionGoal.actionId.toString())
+ urlParams.delete('conversionGoal.customEventName')
+ } else {
+ urlParams.set('conversionGoal.customEventName', conversionGoal.customEventName)
+ urlParams.delete('conversionGoal.actionId')
+ }
+ } else {
+ urlParams.delete('conversionGoal.actionId')
+ urlParams.delete('conversionGoal.customEventName')
+ }
+ if (dateFrom !== INITIAL_DATE_FROM || dateTo !== INITIAL_DATE_TO || interval !== INITIAL_INTERVAL) {
+ urlParams.set('date_from', dateFrom ?? '')
+ urlParams.set('date_to', dateTo ?? '')
+ urlParams.set('interval', interval ?? '')
+ } else {
+ urlParams.delete('date_from')
+ urlParams.delete('date_to')
+ urlParams.delete('interval')
+ }
+ urlParams.set('path_cleaning', isPathCleaningEnabled.toString())
+ urlParams.set('filter_test_accounts', shouldFilterTestAccounts.toString())
+ urlParams.set('compare_filter', JSON.stringify(rawCompareFilter))
+ return `/web/page-performance${urlParams.toString() ? '?' + urlParams.toString() : ''}`
}
// Make sure we're storing the raw filters only, or else we'll have issues with the domain/device type filters
@@ -3219,6 +3250,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
setProductTab: stateToUrl,
setWebVitalsPercentile: stateToUrl,
setIsPathCleaningEnabled: stateToUrl,
+ setShouldFilterTestAccounts: stateToUrl,
setDomainFilter: stateToUrl,
setDeviceTypeFilter: stateToUrl,
setTileVisualization: stateToUrl,
@@ -3261,6 +3293,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
ProductTab.HEALTH,
ProductTab.LIVE,
ProductTab.BOT_ANALYTICS,
+ ProductTab.PAGE_PERFORMANCE,
].includes(productTab)
) {
return
@@ -3275,6 +3308,14 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
return
}
+ if (
+ productTab === ProductTab.PAGE_PERFORMANCE &&
+ !values.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]
+ ) {
+ router.actions.replace(urls.webAnalytics())
+ return
+ }
+
cache.hasRestoredWebUrl = true
// Stamp the last-used timestamp for feature flag targeting (throttled to once per day per browser).
@@ -3292,7 +3333,10 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
if (botLogic && !objectsEqual(nextFilters, botLogic.values.rawBotAnalyticsFilters)) {
botLogic.actions.setBotAnalyticsFilters(nextFilters)
}
- } else if (!objectsEqual(nextFilters, values.rawWebAnalyticsFilters)) {
+ } else if (
+ productTab !== ProductTab.PAGE_PERFORMANCE &&
+ !objectsEqual(nextFilters, values.rawWebAnalyticsFilters)
+ ) {
actions.setWebAnalyticsFilters(nextFilters)
}
}