: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(web-analytics): explain the empty Search & AI tab instead of showing zeros (#89740)
Lucas Ricoy6c57ce151a55
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex dac2fa6410f5..cf0ff96411a2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8713,9 +8713,13 @@ snapshots:scenes-app-web-analytics-pageperformancemetriccard--without-sparkline--light:hash: v1.k794b7964.27bbdd01e4451fe0fe7cfbf693975714907972cdef4cc9b74ab13f99c28f5c34.9VZtUj_jx6H9AXXqTTKz1uomaF3X9e8cENkeIs8iJ_Iscenes-app-web-analytics-search-ai--web-analytics-page-performance--dark:- hash: v1.k794b7964.1fc5749cb466dec1443223b49ec2c2e8e6a03b2ee3a763d55b9fd1d62e9e6be4.RF6AyylJtgQpmv_VRLTZUlF-ly66l2wnmF9lUKC_cRA+ hash: v1.k794b7964.60c001e801c861bd1b9a0dbfa7c3b87d6d5b8ed03af7cd145e88ce2dafa9df81.7dliypqCJeOXP_wCTJMeIxEW4urr1TjnnfKmp9T-fMMscenes-app-web-analytics-search-ai--web-analytics-page-performance--light:- hash: v1.k794b7964.b5e83a15484dc4055944c77db7a46fdeb5141ab6c12219450ce97f015e696d34.8SUEwt3vz-P5JebG1RpmgWsh5aLng4coLv2TbD8r5ZA+ hash: v1.k794b7964.6139f596e3f9ff7ba00323248dedc923bf4020b1c6f0ee4948628ed41228dfb3.gf2_OMHy67IGdywFrlPSzb1yjFe_Zc-550tBFTCqSJE+ scenes-app-web-analytics-search-ai--web-analytics-page-performance-no-ai-traffic--dark:+ hash: v1.k794b7964.ff693d29af19c34091c70dc0e5a22853d7f35b01ab3459f6a2bf1f2b06c57536.rM7sS7EbyqrDzgeTX1Nz6Xu63xYhT9KbpNi97rJzsmQ+ scenes-app-web-analytics-search-ai--web-analytics-page-performance-no-ai-traffic--light:+ hash: v1.k794b7964.d28c10ae27c8ddbee128184c1555e0aa6aefc81ac5c6702a0721d84ca9811c46.TEn8Vcq05e1uAqQ_zoQfOvYYsE9BXU9Y0ev2W5QDSroscenes-inbox-scout-tags--editor-and-filter--dark:hash: v1.k794b7964.b76b173ee1dc78112e700af267b53d59959164f8ebbc814df2b5f4a3811bcd49.2hfIhAW_k3BdFlo9jtUoJhOyZhS1uQmgafcdvh_CGmgscenes-inbox-scout-tags--editor-and-filter--light:diff --git a/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx b/frontend/src/scenes/web-analytics/PagePerformance.stories.tsxindex ea9e2f981baf..d473408de46d 100644--- a/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx+++ b/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx@@ -30,17 +30,29 @@ const OVERVIEW_HUMAN = {}const OVERVIEW_CRAWLER = {- columns: ['bucket', 'crawls', 'crawls_previous'],+ columns: ['bucket', 'crawls', 'crawls_previous', 'server_logs'],results: [- ['1970-01-01 00:00:00', 88100, 78600],+ ['1970-01-01 00:00:00', 88100, 78600, 214000],...[9800, 11200, 10400, 14100, 13600, 15200, 13800].map((crawls, index) => [`${BUCKETS[index]} 00:00:00`,crawls,0,+ 0,]),],}+// A site with real traffic but no forwarded access logs and no AI referrals: the common shape today.+const OVERVIEW_HUMAN_NO_AI = {+ columns: OVERVIEW_HUMAN.columns,+ results: [['1970-01-01 00:00:00', 1430, 1210, 384, 361, 0, 0, 128]],+}++const OVERVIEW_CRAWLER_NONE = {+ columns: OVERVIEW_CRAWLER.columns,+ results: [['1970-01-01 00:00:00', 0, 0, 0]],+}+// Every metric tuple is [current, previous], except agent crawls, which is [crawls, distinct agents].const PAGE_ROWS = [['hedgebox.net/pricing', [172, 141], [50, 44], [121, 19], [900, 60], [16, 12], 94],@@ -66,6 +78,11 @@ const LEADERBOARD = {results: PAGE_ROWS,}+const LEADERBOARD_NO_AI = {+ columns: LEADERBOARD.columns,+ results: PAGE_ROWS.map((row) => [row[0], row[1], row[2], [0, 0], [0, 0], row[5], row[6]]),+}+const CANDIDATES = {columns: ['context.columns.breakdown_value'],results: PAGE_ROWS.map((row) => [row[0]]),@@ -89,6 +106,74 @@ const breakdownTable = (rows: (string | number)[][]): Record<string, unknown> =>results: rows,})+const handlers = (+ overviewHuman: Record<string, unknown>,+ overviewCrawler: Record<string, unknown>,+ leaderboard: Record<string, unknown> = LEADERBOARD,+ // The AI sections read their own queries, so an empty overview has to empty those too.+ hasAiData: boolean = true+): Parameters<typeof mswDecorator>[0] => ({+ get: {+ '/stats': () => [200, { users_on_product: 2387 }],+ '/api/projects/:team_id/event_definitions': () => [200, { count: 5 }],+ },+ post: {+ '/api/environments/:team_id/query/:kind': async ({ request }) => {+ const query = ((await request.json()) as any).query+ const source = query.source ?? query+ const kind = source.kind++ if (kind === 'DatabaseSchemaQuery') {+ return [200, { tables: {}, joins: [] }]+ }+ if (kind === 'TrendsQuery') {+ return [200, hasAiData ? trend('Visitors', [180, 220, 190, 260, 240, 310, 295]) : { results: [] }]+ }+ if (kind === 'WebBotsTableQuery') {+ return [+ 200,+ breakdownTable(+ hasAiData+ ? [+ ['GPTBot', 31200],+ ['ClaudeBot', 24800],+ ['PerplexityBot', 16400],+ ['Google-Extended', 9700],+ ]+ : []+ ),+ ]+ }+ if (kind === 'WebStatsTableQuery') {+ if (source.breakdownBy === 'InitialReferringDomain') {+ return [+ 200,+ breakdownTable(+ hasAiData+ ? [+ ['chatgpt.com', 640],+ ['perplexity.ai', 410],+ ['claude.ai', 220],+ ]+ : []+ ),+ ]+ }+ return [200, CANDIDATES]+ }+ if (kind === 'HogQLQuery') {+ if (source.query?.includes('AS crawls')) {+ return [200, overviewCrawler]+ }+ if (source.query?.includes('AS visitors')) {+ return [200, overviewHuman]+ }+ return [200, leaderboard]+ }+ },+ },+})+const meta: Meta = {component: App,title: 'Scenes-App/Web Analytics/Search & AI',@@ -103,64 +188,17 @@ const meta: Meta = {waitForLoadersToDisappear: true,},},- decorators: [- mswDecorator({- get: {- '/stats': () => [200, { users_on_product: 2387 }],- '/api/projects/:team_id/event_definitions': () => [200, { count: 5 }],- },- post: {- '/api/environments/:team_id/query/:kind': async ({ request }) => {- const query = ((await request.json()) as any).query- const source = query.source ?? query- const kind = source.kind-- if (kind === 'DatabaseSchemaQuery') {- return [200, { tables: {}, joins: [] }]- }- if (kind === 'TrendsQuery') {- return [200, trend('Visitors', [180, 220, 190, 260, 240, 310, 295])]- }- if (kind === 'WebBotsTableQuery') {- return [- 200,- breakdownTable([- ['GPTBot', 31200],- ['ClaudeBot', 24800],- ['PerplexityBot', 16400],- ['Google-Extended', 9700],- ]),- ]- }- if (kind === 'WebStatsTableQuery') {- if (source.breakdownBy === 'InitialReferringDomain') {- return [- 200,- breakdownTable([- ['chatgpt.com', 640],- ['perplexity.ai', 410],- ['claude.ai', 220],- ]),- ]- }- return [200, CANDIDATES]- }- if (kind === 'HogQLQuery') {- if (source.query?.includes('AS crawls')) {- return [200, OVERVIEW_CRAWLER]- }- if (source.query?.includes('AS visitors')) {- return [200, OVERVIEW_HUMAN]- }- return [200, LEADERBOARD]- }- },- },- }),- ],+ decorators: [mswDecorator(handlers(OVERVIEW_HUMAN, OVERVIEW_CRAWLER))],}export default meta+WebAnalyticsPagePerformanceNoAiTraffic.decorators = [+ mswDecorator(handlers(OVERVIEW_HUMAN_NO_AI, OVERVIEW_CRAWLER_NONE, LEADERBOARD_NO_AI, false)),+]+export function WebAnalyticsPagePerformanceNoAiTraffic(): JSX.Element {+ return <App />+}+export function WebAnalyticsPagePerformance(): JSX.Element {const { setConversionGoal } = useActions(webAnalyticsLogic)diff --git a/frontend/src/scenes/web-analytics/PagePerformance.tsx b/frontend/src/scenes/web-analytics/PagePerformance.tsxindex 5e4bb62f59f1..cb1aed25b21a 100644--- a/frontend/src/scenes/web-analytics/PagePerformance.tsx+++ b/frontend/src/scenes/web-analytics/PagePerformance.tsx@@ -2,8 +2,8 @@ import clsx from 'clsx'import { useActions, useMountedLogic, useValues } from 'kea'import { forwardRef, useMemo } from 'react'-import { IconTrending } from '@posthog/icons'-import { LemonBanner, LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'+import { IconInfo, IconTrending } from '@posthog/icons'+import { LemonBanner, LemonButton, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { useChartTheme } from 'lib/charts/hooks'import { seriesColor } from 'lib/charts/utils/theme'@@ -12,17 +12,22 @@ import { humanFriendlyDuration } from 'lib/utils/durations'import { percentage } from 'lib/utils/numbers'import { pluralize } from 'lib/utils/strings'import { tryDecodeURIComponent } from 'lib/utils/url'+import { urls } from 'scenes/urls'import { Query } from '~/queries/Query/Query'-import { DataTableNode } from '~/queries/schema/schema-general'+import { DataTableNode, ProductKey } from '~/queries/schema/schema-general'import { QueryContext, QueryContextColumnComponent, QueryContextColumnTitleComponent } from '~/queries/types'+import { OnboardingStepKey } from '~/types'import { TileId } from './common'import { PagePerformanceBreakdownModal } from './PagePerformanceBreakdownModal'import { PagePerformanceCard } from './PagePerformanceCard'import { PagePerformanceCardHeader } from './PagePerformanceCardHeader'+import { PagePerformanceEmptyState } from './PagePerformanceEmptyState'import {+ PagePerformanceCrawlerState,PagePerformanceMetric,+ PagePerformanceTabState,changeVsPrevious,createPagePerformanceInsightProps,formatShare,@@ -277,10 +282,116 @@ const sortableTitle = (label: string, column: string): QueryContextColumnTitleCo)}-const SectionHeading = ({ children }: { children: React.ReactNode }): JSX.Element => (- <h2 className="mb-4 text-xl font-semibold text-primary">{children}</h2>+const CRAWLER_CAVEAT =+ "AI crawlers don't run JavaScript, so the browser SDK never sees them. Forward your server access logs to count them."++const AgentCrawlsSortableTitle = sortableTitle('Agent crawls', 'agent_crawls')++/** An empty crawler feed still renders as a hard zero, so the header says when that zero means "not measured". */+const AgentCrawlsTitle: QueryContextColumnTitleComponent = (props) => {+ const { dataState } = useValues(pagePerformanceLogic)+ if (dataState.crawlers !== 'needs-server-logs') {+ return <AgentCrawlsSortableTitle {...props} />+ }+ return (+ <span className="inline-flex items-center gap-1">+ <AgentCrawlsSortableTitle {...props} />+ <Tooltip title={CRAWLER_CAVEAT}>+ <IconInfo className="shrink-0" />+ </Tooltip>+ </span>+ )+}++const SectionHeading = ({+ children,+ description,+}: {+ children: React.ReactNode+ description?: string+}): JSX.Element => (+ <div className="mb-4">+ <h2 className="mb-0 text-xl font-semibold text-primary">{children}</h2>+ {description ? <p className="m-0 text-sm text-secondary">{description}</p> : null}+ </div>+)++const SERVER_LOGS_DOCS = 'https://posthog.com/docs/web-analytics/sending-http-logs'++const CHANNEL_TYPE_DOCS = 'https://posthog.com/docs/data/channel-type'++const TabEmptyState = ({ state }: { state: PagePerformanceTabState }): JSX.Element =>+ state === 'no-events' ? (+ <PagePerformanceEmptyState+ title="Nothing to measure yet"+ action={+ <LemonButton+ type="primary"+ to={urls.onboarding({+ productKey: ProductKey.WEB_ANALYTICS,+ stepKey: OnboardingStepKey.INSTALL,+ })}+ data-attr="page-performance-onboarding"+ >+ Open installation guide+ </LemonButton>+ }+ >+ <p className="m-0">+ Install PostHog on your site to see how search engines, AI assistants, and AI crawlers reach your pages.+ </p>+ </PagePerformanceEmptyState>+ ) : (+ <PagePerformanceEmptyState title="No pageviews in this date range">+ <p className="m-0">Pick a wider range to see how search and AI bring people to your pages.</p>+ </PagePerformanceEmptyState>+ )++const AiTrafficEmptyState = (): JSX.Element => (+ <PagePerformanceEmptyState+ title="No AI referrals in this range"+ action={+ <Link to={CHANNEL_TYPE_DOCS} target="_blank">+ How PostHog works out where a visit came from+ </Link>+ }+ >+ <p className="m-0">Nobody arrived from an AI assistant that PostHog could attribute.</p>+ <p className="m-0">+ This is a lower bound. Some assistants strip the referrer, and those visits land in Direct instead.+ </p>+ </PagePerformanceEmptyState>)+const CrawlersEmptyState = ({ state }: { state: PagePerformanceCrawlerState }): JSX.Element =>+ state === 'needs-server-logs' ? (+ <PagePerformanceEmptyState+ title="PostHog can't see your AI crawlers yet"+ action={+ <LemonButton+ type="primary"+ to={SERVER_LOGS_DOCS}+ targetBlank+ data-attr="page-performance-server-logs-docs"+ >+ Read the setup guide+ </LemonButton>+ }+ >+ <p className="m-0">+ Crawlers like GPTBot and ClaudeBot never run JavaScript, so the browser SDK never sees them. Forward+ your server or CDN access logs as <code>$http_log</code> events to count them here.+ </p>+ <p className="m-0">Already sending them? Try a wider date range.</p>+ </PagePerformanceEmptyState>+ ) : (+ <PagePerformanceEmptyState title="No AI crawlers in this range">+ <p className="m-0">+ Your server logs are reaching PostHog, but no AI crawler read these pages. Try a wider date range.+ </p>+ </PagePerformanceEmptyState>+ )+const AiTableCard = ({title,query,@@ -317,6 +428,7 @@ export const PagePerformance = (): JSX.Element => {overviewLoading,footerText,aiSectionQueries,+ dataState,} = useValues(pagePerformanceLogic)const { loadOverview, loadCandidates } = useActions(pagePerformanceLogic)const theme = useChartTheme()@@ -338,7 +450,7 @@ export const PagePerformance = (): JSX.Element => {align: 'center',},agent_crawls: {- renderTitle: sortableTitle('Agent crawls', 'agent_crawls'),+ renderTitle: AgentCrawlsTitle,render: AgentCrawlsCell,align: 'center',},@@ -357,15 +469,28 @@ export const PagePerformance = (): JSX.Element => {[])+ const feedbackBanner = (+ <LemonBanner+ type="info"+ dismissKey="web-analytics-search-and-ai-feedback-banner"+ action={{ children: 'Send feedback', id: 'web-analytics-search-and-ai-feedback-button' }}+ >+ We'd love to hear what you think about search and AI.+ </LemonBanner>+ )++ if (dataState.tab === 'no-events' || dataState.tab === 'no-traffic-in-range') {+ return (+ <div className="flex flex-col gap-4">+ {feedbackBanner}+ <TabEmptyState state={dataState.tab} />+ </div>+ )+ }+return (<div className="flex flex-col gap-4">- <LemonBanner- type="info"- dismissKey="web-analytics-search-and-ai-feedback-banner"- action={{ children: 'Send feedback', id: 'web-analytics-search-and-ai-feedback-button' }}- >- We'd love to hear what you think about search and AI.- </LemonBanner>+ {feedbackBanner}<section><SectionHeading>Key metrics</SectionHeading>{overviewError ? (@@ -386,6 +511,11 @@ export const PagePerformance = (): JSX.Element => {color={seriesColor(theme, index)}theme={theme}loading={overviewLoading}+ caveat={+ key === 'agent_crawls' && dataState.crawlers === 'needs-server-logs'+ ? CRAWLER_CAVEAT+ : undefined+ }/>))}</div>@@ -393,7 +523,9 @@ export const PagePerformance = (): JSX.Element => {)}</section><section>- <SectionHeading>Pages</SectionHeading>+ <SectionHeading description="How each page earns its traffic, from search engines through to AI crawlers.">+ Pages+ </SectionHeading><PagePerformanceCard footer={footerText}>{candidatesError ? (<LemonBanner@@ -419,52 +551,68 @@ export const PagePerformance = (): JSX.Element => {</PagePerformanceCard></section><section>- <SectionHeading>Traffic from AI</SectionHeading>- <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={<PagePerformanceCardHeader title="Referrals over time" />}+ <SectionHeading description="People who landed on your site from an AI assistant such as ChatGPT, Claude, or Perplexity.">+ Traffic from AI+ </SectionHeading>+ {dataState.aiTraffic === 'empty' ? (+ <AiTrafficEmptyState />+ ) : (+ <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={<PagePerformanceCardHeader title="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>- <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>+ )}</section><section>- <SectionHeading>AI crawlers</SectionHeading>- <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={<PagePerformanceCardHeader title="Crawler activity over time" />}+ <SectionHeading description="Bots that read your pages to train a model or to answer someone's question about you.">+ AI crawlers+ </SectionHeading>+ {dataState.crawlers === 'empty' || dataState.crawlers === 'needs-server-logs' ? (+ <CrawlersEmptyState state={dataState.crawlers} />+ ) : (+ <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={<PagePerformanceCardHeader title="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>- <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>+ )}</section><PagePerformanceBreakdownModal /></div>diff --git a/frontend/src/scenes/web-analytics/PagePerformanceEmptyState.tsx b/frontend/src/scenes/web-analytics/PagePerformanceEmptyState.tsxnew file mode 100644index 000000000000..b71c98f629c0--- /dev/null+++ b/frontend/src/scenes/web-analytics/PagePerformanceEmptyState.tsx@@ -0,0 +1,29 @@+import clsx from 'clsx'++export interface PagePerformanceEmptyStateProps {+ title: string+ /** One or two short lines saying why this is empty and what to do next. */+ children: React.ReactNode+ action?: React.ReactNode+ className?: string+}++export function PagePerformanceEmptyState({+ title,+ children,+ action,+ className,+}: PagePerformanceEmptyStateProps): JSX.Element {+ return (+ <div+ className={clsx(+ 'border rounded bg-surface-primary flex flex-col items-center gap-2 px-6 py-10 text-center',+ className+ )}+ >+ <h3 className="m-0 text-base font-semibold">{title}</h3>+ <div className="flex flex-col gap-1 max-w-140 text-sm text-secondary">{children}</div>+ {action ? <div className="mt-2 flex items-center gap-2">{action}</div> : null}+ </div>+ )+}diff --git a/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx b/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsxindex a4b5a3e8ef63..a9353dd4af18 100644--- a/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx+++ b/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx@@ -1,6 +1,6 @@import { memo } from 'react'-import { IconTrending } from '@posthog/icons'+import { IconInfo, IconTrending } from '@posthog/icons'import { LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'import { Sparkline } from '@posthog/quill-charts'import type { ChartTheme } from '@posthog/quill-charts'@@ -20,6 +20,8 @@ export interface PagePerformanceMetricCardProps {color: stringtheme: ChartThemeloading: boolean+ /** Says why this number can't be trusted at face value, shown as an icon beside the label. */+ caveat?: string'data-attr'?: string}@@ -55,6 +57,7 @@ export const PagePerformanceMetricCard = memo(function PagePerformanceMetricCardcolor,theme,loading,+ caveat,'data-attr': dataAttr,}: PagePerformanceMetricCardProps): JSX.Element {const hasSparkline = sparkline.some((point) => point > 0)@@ -63,7 +66,14 @@ export const PagePerformanceMetricCard = memo(function PagePerformanceMetricCard<div className="border rounded bg-surface-primary flex flex-col overflow-hidden" data-attr={dataAttr}><div className="flex flex-col gap-1 px-3 pt-3"><div className="flex items-center justify-between gap-2">- <span className="text-xs font-medium text-secondary truncate">{label}</span>+ <span className="flex items-center gap-1 text-xs font-medium text-secondary truncate">+ {label}+ {caveat ? (+ <Tooltip title={caveat}>+ <IconInfo className="shrink-0 text-base" />+ </Tooltip>+ ) : null}+ </span>{!loading && changeFromPreviousPct !== null && (<DeltaTag changeFromPreviousPct={changeFromPreviousPct} previous={previous} />)}diff --git a/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts b/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.tsindex 33eb5077d501..7cc04eac699e 100644--- a/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts+++ b/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts@@ -3,6 +3,7 @@ import { dayjs } from 'lib/dayjs'import { CompareFilter } from '~/queries/schema/schema-general'import {+ OverviewTotals,PagePerformanceWindow,buildGoogleSearchConsoleQuery,buildPagePerformanceTableQuery,@@ -10,6 +11,7 @@ import {mergePagePerformanceSeries,parsePagePerformanceOverviewResponse,resolvePagePerformanceBucket,+ resolvePagePerformanceDataState,resolvePagePerformanceWindow,} from './pagePerformanceLogic'import { DateFilterState } from './webAnalyticsLogic'@@ -220,4 +222,69 @@ describe('pagePerformanceLogic', () => {expect(resolvePagePerformanceBucket(window)).toBe('week')})})++ describe('data state', () => {+ const totals = (overrides: Partial<OverviewTotals>): OverviewTotals => ({+ visitors: 0,+ visitorsPrevious: 0,+ google: 0,+ googlePrevious: 0,+ llm: 0,+ llmPrevious: 0,+ crawls: 0,+ crawlsPrevious: 0,+ pages: 0,+ serverLogs: 0,+ ...overrides,+ })++ it('holds every section on loading until the overview answers', () => {+ expect(resolvePagePerformanceDataState(null, true)).toEqual({+ tab: 'loading',+ aiTraffic: 'loading',+ crawlers: 'loading',+ })+ })++ it.each([+ {+ name: 'sends a team that has never ingested to the installation guide',+ totals: totals({}),+ hasIngestedEvents: false,+ expected: { tab: 'no-events', aiTraffic: 'empty', crawlers: 'empty' },+ },+ {+ name: 'blames the date range when the team has ingested before',+ totals: totals({}),+ hasIngestedEvents: true,+ expected: { tab: 'no-traffic-in-range', aiTraffic: 'empty', crawlers: 'needs-server-logs' },+ },+ {+ name: 'reads zero crawls as a missing feed when no access logs arrive',+ totals: totals({ visitors: 1430, pages: 128, llm: 812 }),+ hasIngestedEvents: true,+ expected: { tab: 'ready', aiTraffic: 'ready', crawlers: 'needs-server-logs' },+ },+ {+ name: 'reads zero crawls as a real zero once access logs arrive',+ totals: totals({ visitors: 1430, pages: 128, llm: 812, serverLogs: 4200 }),+ hasIngestedEvents: true,+ expected: { tab: 'ready', aiTraffic: 'ready', crawlers: 'empty' },+ },+ {+ name: 'empties only the AI section when nobody arrived from an assistant',+ totals: totals({ visitors: 1430, pages: 128, crawls: 88100, serverLogs: 4200 }),+ hasIngestedEvents: true,+ expected: { tab: 'ready', aiTraffic: 'empty', crawlers: 'ready' },+ },+ {+ name: 'keeps the tab alive for a site that only shows up in access logs',+ totals: totals({ serverLogs: 4200, crawls: 88100 }),+ hasIngestedEvents: true,+ expected: { tab: 'ready', aiTraffic: 'empty', crawlers: 'ready' },+ },+ ])('$name', ({ totals: overviewTotals, hasIngestedEvents, expected }) => {+ expect(resolvePagePerformanceDataState(overviewTotals, hasIngestedEvents)).toEqual(expected)+ })+ })})diff --git a/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts b/frontend/src/scenes/web-analytics/pagePerformanceLogic.tsindex 8d97ebc8ae2f..3a151d371198 100644--- a/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts+++ b/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts@@ -112,6 +112,8 @@ export interface OverviewTotals {crawls: numbercrawlsPrevious: numberpages: number+ /** Forwarded access-log events. Without them the crawler numbers can only ever be zero. */+ serverLogs: number}export type PagePerformanceBucket = 'hour' | 'day' | 'week'@@ -192,6 +194,46 @@ const EMPTY_OVERVIEW_TOTALS: OverviewTotals = {crawls: 0,crawlsPrevious: 0,pages: 0,+ serverLogs: 0,+}++export type PagePerformanceTabState = 'loading' | 'ready' | 'no-events' | 'no-traffic-in-range'+export type PagePerformanceAiTrafficState = 'loading' | 'ready' | 'empty'+export type PagePerformanceCrawlerState = 'loading' | 'ready' | 'empty' | 'needs-server-logs'++export interface PagePerformanceDataState {+ tab: PagePerformanceTabState+ aiTraffic: PagePerformanceAiTrafficState+ crawlers: PagePerformanceCrawlerState+}++const READY_DATA_STATE: PagePerformanceDataState = { tab: 'ready', aiTraffic: 'ready', crawlers: 'ready' }++/**+ * Which of the tab's three stories can actually be told from the data at hand. A zero here is+ * ambiguous: crawlers never run JavaScript, so no forwarded access logs means no crawler rows are+ * possible, whatever the site's real crawler traffic is. Separating that from a genuine zero keeps+ * the tab from reporting an instrumentation gap as a fact about the world.+ */+export const resolvePagePerformanceDataState = (+ totals: OverviewTotals | null,+ hasIngestedEvents: boolean+): PagePerformanceDataState => {+ if (!totals) {+ return { tab: 'loading', aiTraffic: 'loading', crawlers: 'loading' }+ }+ if (totals.visitors === 0 && totals.pages === 0 && totals.crawls === 0 && totals.serverLogs === 0) {+ return {+ tab: hasIngestedEvents ? 'no-traffic-in-range' : 'no-events',+ aiTraffic: 'empty',+ crawlers: hasIngestedEvents ? 'needs-server-logs' : 'empty',+ }+ }+ return {+ tab: 'ready',+ aiTraffic: totals.llm > 0 ? 'ready' : 'empty',+ crawlers: totals.crawls > 0 ? 'ready' : totals.serverLogs > 0 ? 'empty' : 'needs-server-logs',+ }}const tsLiteral = (date: dayjs.Dayjs, timezone: string): string => date.tz(timezone).format("'YYYY-MM-DD HH:mm:ss'")@@ -565,7 +607,8 @@ const buildOverviewCrawlerQuery = (window: PagePerformanceWindow, bucketSize: PaSELECT${BUCKET_HOGQL_FN[bucketSize]}(timestamp) AS bucket,countIf((${CRAWLER}) AND ${cur}) AS crawls,- countIf((${CRAWLER}) AND ${prev}) AS crawls_previous+ countIf((${CRAWLER}) AND ${prev}) AS crawls_previous,+ countIf(event = '$http_log' AND ${cur}) AS server_logsFROM eventsWHERE and(event IN ${PAGE_PERFORMANCE_EVENTS},@@ -654,6 +697,7 @@ export interface pagePerformanceLogicValues {candidatesError: string | nullcandidatesInput: stringcandidatesLoading: boolean+ dataState: PagePerformanceDataStatefooterText: stringgoalLabel: string | nullorderBy: PagePerformanceOrderBy@@ -769,6 +813,11 @@ export interface pagePerformanceLogicMeta {) => DataTableNode | nullcomparePeriods: (compareFilter: CompareFilter) => booleansiteVisitors: (overviewTotals: OverviewTotals | null) => number+ dataState: (+ overviewTotals: OverviewTotals | null,+ overviewError: string | null,+ currentTeam: TeamPublicType | TeamType | null+ ) => PagePerformanceDataStateoverviewMetrics: (overviewTotals: OverviewTotals | null,overviewSeries: OverviewSeriesPoint[],@@ -1144,6 +1193,18 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([(s) => [s.compareFilter],(compareFilter: CompareFilter): boolean => compareFilter.compare !== false,],+ dataState: [+ (s) => [s.overviewTotals, s.overviewError, s.currentTeam],+ (+ overviewTotals: OverviewTotals | null,+ overviewError: string | null,+ currentTeam: TeamPublicType | TeamType | null+ ): PagePerformanceDataState =>+ // A failed overview says nothing about the sections, so let their own queries speak instead.+ overviewError+ ? READY_DATA_STATE+ : resolvePagePerformanceDataState(overviewTotals, !!currentTeam?.ingested_event),+ ],// A number rather than the totals object, so a reload doesn't re-render every row on identity alone.siteVisitors: [(s) => [s.overviewTotals],@@ -1307,6 +1368,7 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([crawls: crawler.totals.crawls ?? 0,crawlsPrevious: crawler.totals.crawls_previous ?? 0,pages: human.totals.pages ?? 0,+ serverLogs: crawler.totals.server_logs ?? 0,},mergePagePerformanceSeries(human, crawler, bucketSize))