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 page directory components (#123198)

Jordan Mryyan1771601fac53
diff --git a/frontend/src/scenes/web-analytics/pageReportsLogic.ts b/frontend/src/scenes/web-analytics/pageReportsLogic.ts
index 3d8e18b14c1b..d3cde0f70e62 100644
--- a/frontend/src/scenes/web-analytics/pageReportsLogic.ts
+++ b/frontend/src/scenes/web-analytics/pageReportsLogic.ts
@@ -1,5 +1,6 @@
import { MakeLogicType, kea } from 'kea'
import { router } from 'kea-router'
+import posthog from 'posthog-js'
import api from 'lib/api'
import { applyPathCleaning } from 'lib/components/PathCleanFilters/pathCleaningUtils'
@@ -40,6 +41,7 @@ import {
PathTab,
SectionTile,
SourceTab,
+ QueryTile,
TabsTile,
TileId,
TileVisualizationOption,
@@ -54,6 +56,152 @@ import { PROPERTY_PATHNAME } from './constants'
import { webAnalyticsLogic } from './webAnalyticsLogic'
import type { DateFilterState } from './webAnalyticsLogic'
+export enum PageReportTab {
+ Overview = 'overview',
+ Traffic = 'traffic',
+ Search = 'search',
+ AI = 'ai',
+ Audience = 'audience',
+}
+
+export type PageReportOpenSource = 'directory_row' | 'pasted_url'
+
+const PAGE_REPORT_TAB_PARAM = 'page_report_tab'
+
+const isPageReportTab = (value: unknown): value is PageReportTab =>
+ typeof value === 'string' && (Object.values(PageReportTab) as string[]).includes(value)
+
+const sentenceCaseTitle = (title: string): string =>
+ title
+ .split(' ')
+ .map((word, index) => (index === 0 || word === word.toUpperCase() ? word : word.toLowerCase()))
+ .join(' ')
+
+export type PageReportTileRowVariant = 'feature' | 'grid'
+
+export interface PageReportTileRow {
+ key: string
+ variant: PageReportTileRowVariant
+ tiles: QueryTile[]
+}
+
+export type PageReportTabRows = Partial<Record<PageReportTab, PageReportTileRow[]>>
+
+const CHART_TILE_LAYOUT = 'flex flex-col h-full min-h-72'
+const TABLE_TILE_LAYOUT = 'flex flex-col h-full'
+
+function groupPageReportTiles(tiles: SectionTile[]): PageReportTabRows {
+ const queryTiles = new Map<TileId, QueryTile>()
+ for (const section of tiles) {
+ for (const tile of section.tiles) {
+ if (tile.kind === 'query') {
+ queryTiles.set(tile.tileId, {
+ ...tile,
+ title: typeof tile.title === 'string' ? sentenceCaseTitle(tile.title) : tile.title,
+ docs:
+ tile.docs && typeof tile.title === 'string'
+ ? { ...tile.docs, title: sentenceCaseTitle(tile.title) }
+ : tile.docs,
+ layout: {
+ ...tile.layout,
+ className: tile.query.kind === NodeKind.InsightVizNode ? CHART_TILE_LAYOUT : TABLE_TILE_LAYOUT,
+ },
+ })
+ }
+ }
+ }
+
+ const row = (key: string, ids: TileId[], variant: PageReportTileRowVariant = 'grid'): PageReportTileRow | null => {
+ const rowTiles = ids.map((id) => queryTiles.get(id)).filter((tile): tile is QueryTile => !!tile)
+ return rowTiles.length > 0 ? { key, variant, tiles: rowTiles } : null
+ }
+ const rows = (...items: (PageReportTileRow | null)[]): PageReportTileRow[] =>
+ items.filter((item): item is PageReportTileRow => !!item)
+
+ const pathTileIds = [
+ TileId.PAGE_REPORTS_ENTRY_PATHS,
+ TileId.PAGE_REPORTS_PREVIOUS_PAGE,
+ TileId.PAGE_REPORTS_EXIT_PATHS,
+ ].filter((id) => queryTiles.has(id))
+
+ const topEvents = queryTiles.get(TileId.PAGE_REPORTS_TOP_EVENTS)
+ if (
+ topEvents &&
+ topEvents.query.kind === NodeKind.InsightVizNode &&
+ topEvents.query.source.kind === NodeKind.TrendsQuery
+ ) {
+ queryTiles.set(TileId.PAGE_REPORTS_TOP_EVENTS, {
+ ...topEvents,
+ layout: { className: 'flex flex-col h-full min-h-64' },
+ query: {
+ ...topEvents.query,
+ source: {
+ ...topEvents.query.source,
+ properties: Array.isArray(topEvents.query.source.properties)
+ ? topEvents.query.source.properties.map((filter) =>
+ filter.type === PropertyFilterType.EventMetadata &&
+ filter.key === 'event' &&
+ Array.isArray(filter.value)
+ ? { ...filter, value: [...filter.value, '$http_log'] }
+ : filter
+ )
+ : topEvents.query.source.properties,
+ trendsFilter: {
+ ...topEvents.query.source.trendsFilter,
+ display: ChartDisplayType.ActionsBarValue,
+ },
+ },
+ },
+ })
+ }
+
+ return {
+ [PageReportTab.Overview]:
+ pathTileIds.length === 3
+ ? rows(
+ row(
+ 'trends',
+ [TileId.PAGE_REPORTS_COMBINED_METRICS_CHART, TileId.PAGE_REPORTS_AVG_TIME_ON_PAGE_TREND],
+ 'feature'
+ ),
+ row('paths', pathTileIds)
+ )
+ : rows(
+ row('trends', [TileId.PAGE_REPORTS_COMBINED_METRICS_CHART]),
+ row('paths', [TileId.PAGE_REPORTS_AVG_TIME_ON_PAGE_TREND, ...pathTileIds])
+ ),
+ [PageReportTab.Traffic]: rows(
+ row('sources', [
+ TileId.PAGE_REPORTS_CHANNELS,
+ TileId.PAGE_REPORTS_REFERRERS,
+ TileId.PAGE_REPORTS_OUTBOUND_CLICKS,
+ ]),
+ row('utm', [
+ TileId.PAGE_REPORTS_UTM_SOURCE,
+ TileId.PAGE_REPORTS_UTM_MEDIUM,
+ TileId.PAGE_REPORTS_UTM_CAMPAIGN,
+ TileId.PAGE_REPORTS_UTM_CONTENT,
+ TileId.PAGE_REPORTS_UTM_TERM,
+ ])
+ ),
+ [PageReportTab.Audience]: rows(
+ row('devices', [
+ TileId.PAGE_REPORTS_DEVICE_TYPES,
+ TileId.PAGE_REPORTS_BROWSERS,
+ TileId.PAGE_REPORTS_OPERATING_SYSTEMS,
+ ]),
+ row('geography', [
+ TileId.PAGE_REPORTS_COUNTRIES,
+ TileId.PAGE_REPORTS_REGIONS,
+ TileId.PAGE_REPORTS_CITIES,
+ TileId.PAGE_REPORTS_TIMEZONES,
+ TileId.PAGE_REPORTS_LANGUAGES,
+ ]),
+ row('events', [TileId.PAGE_REPORTS_TOP_EVENTS])
+ ),
+ }
+}
+
/**
* Creates property filters for URL matching that handles query parameters consistently
* Always attempts to parse full URLs into host+pathname filters to enable backend optimizations
@@ -276,8 +424,10 @@ export interface pageReportsLogicValues {
combinedMetricsQuery: (dateFilter: DateFilterState) => InsightVizNode<TrendsQuery>
createInsightProps: (tileId: TileId, tabId?: string | undefined) => InsightLogicProps<QuerySchema>
hasPageUrl: boolean
+ isDirectoryEnabled: boolean
isInitialLoad: boolean
isLoading: boolean
+ pageReportTab: PageReportTab
pageUrl: string | null
pageUrlOptions: PageURLOption[]
pageUrlSearchTerm: string
@@ -353,6 +503,7 @@ export interface pageReportsLogicValues {
stripQueryParams: boolean
tileVisualizations: Record<TileId, TileVisualizationOption>
tiles: SectionTile[]
+ tilesByTab: PageReportTabRows
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -370,6 +521,9 @@ export interface pageReportsLogicActions {
setIsPathCleaningEnabled: (isPathCleaningEnabled: boolean) => {
isPathCleaningEnabled: boolean
} // webAnalyticsLogic
+ backToDirectory: () => {
+ value: true
+ }
loadPages: (searchTerm?: string) => {
searchTerm: string
}
@@ -394,6 +548,18 @@ export interface pageReportsLogicActions {
searchTerm: string
}
}
+ openPageReport: (
+ url: string,
+ source: PageReportOpenSource,
+ position?: number | null
+ ) => {
+ position: number | null
+ source: PageReportOpenSource
+ url: string
+ }
+ setPageReportTab: (tab: PageReportTab) => {
+ tab: PageReportTab
+ }
setPageUrl: (url: string | string[] | null) => {
url: string | string[] | null
}
@@ -407,12 +573,17 @@ export interface pageReportsLogicActions {
tileId: TileId
visualization: TileVisualizationOption
}
+ trackDirectoryCtaClicked: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface pageReportsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
hasPageUrl: (pageUrl: string | null) => boolean
+ isDirectoryEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ tilesByTab: (tiles: SectionTile[]) => PageReportTabRows
isLoading: (pagesUrlsLoading: boolean, isInitialLoad: boolean) => boolean
pathCleaningFilters: (currentTeam: TeamPublicType | TeamType | null) => PathCleaningFilter[]
pageUrlOptions: (
@@ -612,6 +783,14 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
actions: () => ({
setPageUrl: (url: string | string[] | null) => ({ url }),
+ openPageReport: (url: string, source: PageReportOpenSource, position: number | null = null) => ({
+ url,
+ source,
+ position,
+ }),
+ backToDirectory: true,
+ setPageReportTab: (tab: PageReportTab) => ({ tab }),
+ trackDirectoryCtaClicked: true,
setPageUrlSearchTerm: (searchTerm: string) => ({ searchTerm }),
loadPages: (searchTerm: string = '') => ({ searchTerm }),
setTileVisualization: (tileId: TileId, visualization: TileVisualizationOption) => ({
@@ -632,6 +811,16 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
}
return url
},
+ openPageReport: (_state, { url }) => url,
+ backToDirectory: () => null,
+ },
+ ],
+ pageReportTab: [
+ PageReportTab.Overview as PageReportTab,
+ {
+ setPageReportTab: (_state, { tab }) => tab,
+ openPageReport: () => PageReportTab.Overview,
+ backToDirectory: () => PageReportTab.Overview,
},
],
pageUrlSearchTerm: [
@@ -732,6 +921,12 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
selectors: {
hasPageUrl: [(selectors) => [selectors.pageUrl], (pageUrl: string | null) => !!pageUrl],
+ isDirectoryEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean =>
+ !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PAGE_REPORTS_DIRECTORY],
+ ],
+ tilesByTab: [(s) => [s.tiles], (tiles: SectionTile[]): PageReportTabRows => groupPageReportTiles(tiles)],
isLoading: [
(selectors) => [selectors.pagesUrlsLoading, selectors.isInitialLoad],
(pagesUrlsLoading: boolean, isInitialLoad: boolean) => pagesUrlsLoading || isInitialLoad,
@@ -1263,6 +1458,18 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
},
listeners: ({ actions, values }) => ({
+ openPageReport: ({ source, position }) => {
+ posthog.capture('web analytics page report opened', { source, row_position: position })
+ },
+ backToDirectory: () => {
+ posthog.capture('web analytics page report back to directory', { method: 'breadcrumb' })
+ },
+ setPageReportTab: ({ tab }) => {
+ posthog.capture('web analytics page report tab changed', { tab })
+ },
+ trackDirectoryCtaClicked: () => {
+ posthog.capture('web analytics page reports cta clicked', { location: 'search_and_ai' })
+ },
setPageUrlSearchTerm: ({ searchTerm }) => {
actions.loadPages(searchTerm)
},
@@ -1293,6 +1500,18 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
if (pageURL && pageURL !== values.pageUrl) {
actions.setPageUrl(pageURL)
}
+ if (!values.isDirectoryEnabled) {
+ return
+ }
+ if (!pageURL && values.pageUrl) {
+ actions.setPageUrl(null)
+ }
+ const tab = isPageReportTab(searchParams[PAGE_REPORT_TAB_PARAM])
+ ? searchParams[PAGE_REPORT_TAB_PARAM]
+ : PageReportTab.Overview
+ if (tab !== values.pageReportTab) {
+ actions.setPageReportTab(tab)
+ }
},
}),
@@ -1308,5 +1527,22 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
return ['/web/page-reports', searchParams, router.values.hashParams, { replace: true }]
},
+ openPageReport: () => {
+ const { [PAGE_REPORT_TAB_PARAM]: _tab, ...searchParams } = router.values.searchParams
+ return ['/web/page-reports', { ...searchParams, pageURL: values.pageUrl }, router.values.hashParams]
+ },
+ backToDirectory: () => {
+ const { [PAGE_REPORT_TAB_PARAM]: _tab, pageURL: _pageURL, ...searchParams } = router.values.searchParams
+ return ['/web/page-reports', searchParams, router.values.hashParams]
+ },
+ setPageReportTab: () => {
+ const searchParams = { ...router.values.searchParams }
+ if (values.pageReportTab === PageReportTab.Overview) {
+ delete searchParams[PAGE_REPORT_TAB_PARAM]
+ } else {
+ searchParams[PAGE_REPORT_TAB_PARAM] = values.pageReportTab
+ }
+ return ['/web/page-reports', searchParams, router.values.hashParams, { replace: true }]
+ },
}),
})
diff --git a/products/web_analytics/frontend/pageReports/CrawlerLogoStack.tsx b/products/web_analytics/frontend/pageReports/CrawlerLogoStack.tsx
new file mode 100644
index 000000000000..704df1f34f21
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/CrawlerLogoStack.tsx
@@ -0,0 +1,29 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import { AiBrandLogo, resolveAiBrand } from 'products/web_analytics/frontend/searchAndAi/AiBrandLogo'
+
+export function CrawlerLogoStack({ names, count }: { names: string[]; count: number }): JSX.Element {
+ const hidden = Math.max(count - names.length, 0)
+ const brandNames = [...new Map(names.map((name) => [resolveAiBrand(name)?.domain ?? name, name])).values()]
+ return (
+ <Tooltip title={names.length > 0 ? `Read by ${names.join(', ')}${hidden ? ` and ${hidden} more` : ''}` : null}>
+ <span className="inline-flex items-center gap-1.5" data-attr="page-directory-crawler-logos">
+ {brandNames.length > 0 ? (
+ <span className="flex items-center">
+ {brandNames.map((name) => (
+ <span
+ key={name}
+ className="-ml-0.5 first:ml-0 rounded-sm outline-2 outline-solid outline-[var(--color-bg-surface-primary)]"
+ >
+ <AiBrandLogo name={name} size="xs" />
+ </span>
+ ))}
+ </span>
+ ) : null}
+ <span className="text-xs text-secondary whitespace-nowrap">{pluralize(count, 'crawler')}</span>
+ </span>
+ </Tooltip>
+ )
+}
diff --git a/products/web_analytics/frontend/pageReports/PageDirectoryEmptyState.tsx b/products/web_analytics/frontend/pageReports/PageDirectoryEmptyState.tsx
new file mode 100644
index 000000000000..3ffd7a9ed451
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageDirectoryEmptyState.tsx
@@ -0,0 +1,56 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { WebPageDirectorySortBy } from '~/queries/schema/schema-general'
+
+import { pageDirectoryLogic } from './pageDirectoryLogic'
+
+export function PageDirectoryEmptyState(): JSX.Element | null {
+ const { directoryState, search } = useValues(pageDirectoryLogic)
+ const { setSort } = useActions(pageDirectoryLogic)
+
+ if (directoryState === 'no-matches') {
+ return (
+ <p className="text-secondary m-0 py-6 text-center">
+ No pages match "<span>{search.trim()}</span>" in this date range. Try a shorter search, or paste a full
+ URL to open its report.
+ </p>
+ )
+ }
+ if (directoryState === 'no-metric-rows') {
+ return (
+ <div className="flex flex-col items-center gap-2 py-6 text-center">
+ <p className="text-secondary m-0">No pages have data for this column in this date range.</p>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => setSort(WebPageDirectorySortBy.Visitors, 'DESC')}
+ data-attr="page-reports-directory-sort-by-visitors"
+ >
+ Sort by visitors
+ </LemonButton>
+ </div>
+ )
+ }
+ if (directoryState === 'no-traffic') {
+ return (
+ <p className="text-secondary m-0 py-6 text-center">
+ No pageviews in this date range. Pick a longer date range to see your pages.
+ </p>
+ )
+ }
+ if (directoryState === 'no-events') {
+ return (
+ <div className="flex flex-col items-center gap-2 py-6 text-center">
+ <p className="text-secondary m-0">No pageviews yet. Pages appear here once your site sends events.</p>
+ <LemonButton type="secondary" size="small" to={urls.webAnalyticsHealth()}>
+ Check your installation
+ </LemonButton>
+ </div>
+ )
+ }
+ return null
+}
diff --git a/products/web_analytics/frontend/pageReports/PageDirectoryMetricCell.tsx b/products/web_analytics/frontend/pageReports/PageDirectoryMetricCell.tsx
new file mode 100644
index 000000000000..4da3cdb43092
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageDirectoryMetricCell.tsx
@@ -0,0 +1,57 @@
+import clsx from 'clsx'
+
+import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import { percentage } from 'lib/utils/numbers'
+
+import { WebPageDirectoryValue } from '~/queries/schema/schema-general'
+
+import { valueChange } from './pageReportsUtils'
+import { TrendChange } from './TrendChange'
+
+export interface PageDirectoryMetricCellProps {
+ value: WebPageDirectoryValue | undefined
+ detail?: React.ReactNode
+ tooltip: string
+ loading: boolean
+}
+
+export function PageDirectoryMetricCell({
+ value,
+ detail,
+ tooltip,
+ loading,
+}: PageDirectoryMetricCellProps): JSX.Element {
+ if (!value) {
+ return loading ? <LemonSkeleton className="h-8 w-16 ml-auto" /> : <span className="text-secondary">-</span>
+ }
+ const current = value.current
+ const change = valueChange(value)
+
+ const title = [
+ tooltip,
+ change === null
+ ? null
+ : `${change > 0 ? 'Up' : change < 0 ? 'Down' : 'No change'}${change !== 0 ? ` ${percentage(Math.abs(change), 0)}` : ''} from the previous period`,
+ ]
+ .filter(Boolean)
+ .join('. ')
+
+ const changeNode = change !== null && change !== 0 ? <TrendChange change={change} /> : null
+
+ return (
+ <Tooltip title={title}>
+ <span className="inline-flex flex-col items-end gap-1 leading-tight tabular-nums" translate="no">
+ <span className={clsx('font-medium whitespace-nowrap', current === 0 && 'text-secondary font-normal')}>
+ {current.toLocaleString()}
+ </span>
+ {changeNode || detail ? (
+ <span className="inline-flex items-center gap-1.5 text-xs text-secondary whitespace-nowrap">
+ {changeNode}
+ {detail}
+ </span>
+ ) : null}
+ </span>
+ </Tooltip>
+ )
+}
diff --git a/products/web_analytics/frontend/pageReports/PageDirectorySummary.tsx b/products/web_analytics/frontend/pageReports/PageDirectorySummary.tsx
new file mode 100644
index 000000000000..86adc30291be
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageDirectorySummary.tsx
@@ -0,0 +1,128 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
+
+import { WebPageDirectoryValue } from '~/queries/schema/schema-general'
+
+import { pageDirectoryLogic } from './pageDirectoryLogic'
+import { valueChange } from './pageReportsUtils'
+import { TrendChange } from './TrendChange'
+
+function SummaryChange({ value }: { value: WebPageDirectoryValue | undefined }): JSX.Element | null {
+ const change = valueChange(value)
+ if (change === null) {
+ return null
+ }
+ return (
+ <Tooltip title={`${(value?.previous ?? 0).toLocaleString()} in the previous period`}>
+ <span>
+ <TrendChange change={change} className="gap-0.5 tabular-nums" />
+ </span>
+ </Tooltip>
+ )
+}
+
+function SummaryCell({
+ label,
+ value,
+ detail,
+ change,
+ loading,
+}: {
+ label: string
+ value: string
+ detail: string | null
+ change?: WebPageDirectoryValue
+ loading: boolean
+}): JSX.Element {
+ return (
+ <div className="flex flex-col gap-0.5 px-4 py-3 min-w-0">
+ <span className="text-xs font-semibold uppercase tracking-wide text-secondary truncate">{label}</span>
+ {loading ? (
+ <>
+ <LemonSkeleton className="h-7 w-20" />
+ <LemonSkeleton className="h-3 w-28 mt-1" />
+ </>
+ ) : (
+ <>
+ <span className="flex items-baseline gap-2 min-w-0">
+ <span className="text-xl font-semibold tabular-nums" translate="no">
+ {value}
+ </span>
+ <span className="text-xs">
+ <SummaryChange value={change} />
+ </span>
+ </span>
+ <span className="text-xs text-secondary truncate">{detail}</span>
+ </>
+ )}
+ </div>
+ )
+}
+
+export function PageDirectorySummary(): JSX.Element {
+ const { siteTotals, siteTotalsError, hasServerLogs } = useValues(pageDirectoryLogic)
+ const { loadSiteTotals } = useActions(pageDirectoryLogic)
+ const loading = !siteTotals
+
+ if (siteTotalsError) {
+ return (
+ <LemonBanner
+ type="error"
+ action={{
+ children: 'Try again',
+ onClick: () => loadSiteTotals(true),
+ 'data-attr': 'page-reports-directory-summary-retry',
+ }}
+ >
+ Couldn't load site totals.
+ </LemonBanner>
+ )
+ }
+ const visitors = siteTotals?.visitors?.current ?? 0
+ const google = siteTotals?.googleSearch?.current ?? 0
+ const ai = siteTotals?.aiReferrals?.current ?? 0
+
+ return (
+ <div
+ className="grid grid-cols-2 @min-[48rem]/main-content:grid-cols-4 border rounded-lg bg-surface-primary divide-x divide-y @min-[48rem]/main-content:divide-y-0"
+ data-attr="page-reports-directory-summary"
+ >
+ <SummaryCell
+ label="Visitors"
+ value={humanFriendlyLargeNumber(visitors)}
+ detail="across all pages"
+ change={siteTotals?.visitors}
+ loading={loading}
+ />
+ <SummaryCell
+ label="From Google"
+ value={humanFriendlyLargeNumber(google)}
+ detail="visitors from Google search"
+ change={siteTotals?.googleSearch}
+ loading={loading}
+ />
+ <SummaryCell
+ label="From AI assistants"
+ value={humanFriendlyLargeNumber(ai)}
+ detail="visitors from AI assistants"
+ change={siteTotals?.aiReferrals}
+ loading={loading}
+ />
+ <SummaryCell
+ label="AI crawls"
+ value={hasServerLogs === false ? '-' : humanFriendlyLargeNumber(siteTotals?.aiCrawls?.current ?? 0)}
+ detail={
+ hasServerLogs === false
+ ? 'Forward server logs to measure'
+ : `by ${pluralize(siteTotals?.aiCrawlers ?? 0, 'AI crawler')}`
+ }
+ change={hasServerLogs === false ? undefined : siteTotals?.aiCrawls}
+ loading={loading}
+ />
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/pageReports/TrendChange.tsx b/products/web_analytics/frontend/pageReports/TrendChange.tsx
new file mode 100644
index 000000000000..415855cfb081
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/TrendChange.tsx
@@ -0,0 +1,22 @@
+import clsx from 'clsx'
+
+import { IconTrending } from '@posthog/icons'
+
+import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
+import { percentage } from 'lib/utils/numbers'
+
+export function TrendChange({ change, className }: { change: number; className?: string }): JSX.Element {
+ const TrendIcon = change === 0 ? IconTrendingFlat : change > 0 ? IconTrending : IconTrendingDown
+ return (
+ <span
+ className={clsx(
+ 'inline-flex items-center',
+ change === 0 ? 'text-secondary' : change > 0 ? 'text-success' : 'text-danger',
+ className
+ )}
+ >
+ <TrendIcon />
+ <span>{percentage(Math.abs(change), 0)}</span>
+ </span>
+ )
+}
diff --git a/products/web_analytics/frontend/searchAndAi/AiBrandLogo.tsx b/products/web_analytics/frontend/searchAndAi/AiBrandLogo.tsx
new file mode 100644
index 000000000000..415dfba772ba
--- /dev/null
+++ b/products/web_analytics/frontend/searchAndAi/AiBrandLogo.tsx
@@ -0,0 +1,107 @@
+import clsx from 'clsx'
+import { useState } from 'react'
+
+import { claudeLogo, geminiLogo, openaiLogo } from 'lib/components/AgentPromptButton/AgentLogo'
+import { faviconUrl } from 'scenes/web-analytics/common'
+
+interface AiBrand {
+ pattern: RegExp
+ domain: string
+ colorClass: string
+ logo?: string
+ logoFillsTile?: boolean
+}
+
+const AI_BRANDS: AiBrand[] = [
+ {
+ pattern: /chatgpt|openai|gpt|oai-|codex/i,
+ domain: 'chatgpt.com',
+ colorClass: 'bg-[#10a37f]',
+ logo: openaiLogo,
+ logoFillsTile: true,
+ },
+ { pattern: /claude|anthropic/i, domain: 'claude.ai', colorClass: 'bg-[#d97757]', logo: claudeLogo },
+ { pattern: /gemini|bard/i, domain: 'gemini.google.com', colorClass: 'bg-[#4285f4]', logo: geminiLogo },
+ { pattern: /google|notebooklm/i, domain: 'google.com', colorClass: 'bg-[#4285f4]' },
+ {
+ pattern: /mistral/i,
+ domain: 'chat.mistral.ai',
+ colorClass: 'bg-[#fa520f]',
+ logo: '/static/services/mistral_ai.svg',
+ },
+ { pattern: /perplexity/i, domain: 'perplexity.ai', colorClass: 'bg-[#20808d]' },
+ { pattern: /copilot|bing|azure|microsoft/i, domain: 'copilot.microsoft.com', colorClass: 'bg-[#0078d4]' },
+ { pattern: /grok|xai/i, domain: 'grok.com', colorClass: 'bg-[#111111]' },
+ { pattern: /meta/i, domain: 'meta.ai', colorClass: 'bg-[#0866ff]' },
+ { pattern: /deepseek/i, domain: 'chat.deepseek.com', colorClass: 'bg-[#4d6bfe]' },
+ { pattern: /bytedance|bytespider|tiktok|doubao/i, domain: 'bytedance.com', colorClass: 'bg-[#325ab4]' },
+ { pattern: /common ?crawl|ccbot/i, domain: 'commoncrawl.org', colorClass: 'bg-[#2f4b7c]' },
+ { pattern: /cohere/i, domain: 'cohere.com', colorClass: 'bg-[#39594d]' },
+ { pattern: /diffbot/i, domain: 'diffbot.com', colorClass: 'bg-[#f26522]' },
+ { pattern: /amazon|alexa/i, domain: 'amazon.com', colorClass: 'bg-[#ff9900]' },
+ { pattern: /apple/i, domain: 'apple.com', colorClass: 'bg-[#555555]' },
+ { pattern: /duckassist|duckduck/i, domain: 'duckduckgo.com', colorClass: 'bg-[#de5833]' },
+ { pattern: /petal|huawei/i, domain: 'huawei.com', colorClass: 'bg-[#cf0a2c]' },
+ { pattern: /kagi/i, domain: 'kagi.com', colorClass: 'bg-[#ffb319]' },
+ { pattern: /you\.com|youbot/i, domain: 'you.com', colorClass: 'bg-[#7c3aed]' },
+ { pattern: /phind/i, domain: 'phind.com', colorClass: 'bg-[#5a4fcf]' },
+ { pattern: /manus/i, domain: 'manus.im', colorClass: 'bg-[#111111]' },
+ { pattern: /posthog/i, domain: 'posthog.com', colorClass: 'bg-[#f54e00]' },
+]
+
+const NEUTRAL_COLOR_CLASS = 'bg-[var(--color-text-secondary)]'
+
+export function resolveAiBrand(name: string): AiBrand | null {
+ return AI_BRANDS.find((brand) => brand.pattern.test(name)) ?? null
+}
+
+export type AiBrandLogoSize = 'xs' | 'sm' | 'md'
+
+const BOX_CLASS: Record<AiBrandLogoSize, string> = {
+ xs: 'size-4 rounded-sm',
+ sm: 'size-5 rounded',
+ md: 'size-6 rounded-md',
+}
+
+export function AiBrandLogo({ name, size = 'md' }: { name: string; size?: AiBrandLogoSize }): JSX.Element {
+ const brand = resolveAiBrand(name)
+ const [failed, setFailed] = useState(false)
+ const src = brand?.logo ?? (brand ? faviconUrl(brand.domain) : null)
+ const boxClass = BOX_CLASS[size]
+
+ if (src && !failed) {
+ return (
+ <span
+ className={clsx(
+ 'shrink-0 flex items-center justify-center overflow-hidden bg-white border border-primary',
+ boxClass
+ )}
+ aria-hidden
+ >
+ <img
+ src={src}
+ alt=""
+ className={clsx(
+ 'object-contain',
+ brand?.logoFillsTile ? 'size-full' : size === 'xs' ? 'size-2.5' : 'size-3.5'
+ )}
+ onError={() => setFailed(true)}
+ />
+ </span>
+ )
+ }
+
+ return (
+ <span
+ className={clsx(
+ 'shrink-0 flex items-center justify-center font-semibold text-white leading-none',
+ size === 'md' ? 'text-xs' : 'text-xxs',
+ boxClass,
+ brand?.colorClass ?? NEUTRAL_COLOR_CLASS
+ )}
+ aria-hidden
+ >
+ {name.trim().charAt(0).toUpperCase() || '?'}
+ </span>
+ )
+}
diff --git a/products/web_analytics/frontend/searchAndAi/SearchAndAiMetricCell.tsx b/products/web_analytics/frontend/searchAndAi/SearchAndAiMetricCell.tsx
index 6deb719a6eaf..e0de9c21e073 100644
--- a/products/web_analytics/frontend/searchAndAi/SearchAndAiMetricCell.tsx
+++ b/products/web_analytics/frontend/searchAndAi/SearchAndAiMetricCell.tsx
@@ -1,15 +1,14 @@
-import clsx from 'clsx'
import { useActions, useValues } from 'kea'
-import { IconTrending } from '@posthog/icons'
import { LemonButton, Tooltip } from '@posthog/lemon-ui'
-import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { percentage } from 'lib/utils/numbers'
import { pluralize } from 'lib/utils/strings'
import { pagePerformanceLogic, parseMetricCell } from 'scenes/web-analytics/pagePerformanceLogic'
+import { TrendChange } from 'products/web_analytics/frontend/pageReports/TrendChange'
+
import { PagePerformanceMetric, changeVsPrevious, formatShare } from './searchAndAiQueries'
export type SearchAndAiMetric =
@@ -67,7 +66,6 @@ export function SearchAndAiMetricCell({ metric, record }: { metric: SearchAndAiM
}
const change = comparePeriods && !isCrawler ? changeVsPrevious(current, previous) : null
- const TrendIcon = change === 0 ? IconTrendingFlat : (change ?? 0) > 0 ? IconTrending : IconTrendingDown
const tooltip = {
visitors: `${share ?? '0%'} of the ${siteVisitors.toLocaleString()} visitors to your site this period`,
@@ -81,17 +79,7 @@ export function SearchAndAiMetricCell({ metric, record }: { metric: SearchAndAiM
<span className="whitespace-nowrap">{current.toLocaleString()}</span>
<span className="inline-flex items-center gap-1 text-xs text-secondary whitespace-nowrap">
{isCrawler ? <span>{current > 0 ? pluralize(previous, 'agent') : null}</span> : <span>{share}</span>}
- {change !== null && (
- <span
- className={clsx(
- 'inline-flex items-center',
- change === 0 ? 'text-secondary' : change > 0 ? 'text-success' : 'text-danger'
- )}
- >
- <TrendIcon />
- <span>{percentage(Math.abs(change), 0)}</span>
- </span>
- )}
+ {change !== null && <TrendChange change={change} />}
</span>
</span>
)