: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): Add person drill down to Web Analytics Live Dashboard (#58629)
Jordan Mryyanca3527ce56d6
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 83075bb10944..ae9d6d3ea7f9 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -497,6 +497,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_LIVE_FILTERS: 'web-analytics-live-filters', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_LIVE_MAP: 'web-analytics-live-map', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_LIVE_METRICS: 'web-analytics-live-metrics', // owner: @jordanm-posthog #team-web-analytics+ WEB_ANALYTICS_LIVE_PERSON_DRILLDOWN: 'web-analytics-live-person-drilldown', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_LIVE_REFERRERS: 'web-analytics-live-referrers', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_MARKETING: 'marketing-analytics', // owner: @jabahamondes #team-web-analyticsWEB_ANALYTICS_OPEN_URL: 'web-analytics-open-url', // owner: @lricoy #team-web-analyticsdiff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/BreakdownLiveCard.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/BreakdownLiveCard.tsxindex 67e4b49688bc..d1d408e940ff 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/BreakdownLiveCard.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/BreakdownLiveCard.tsx@@ -20,6 +20,7 @@ interface BreakdownLiveCardProps<T extends BreakdownItem> {statLabel: stringtotalCount?: numberisLoading?: boolean+ onItemClick?: (item: T) => void}const BreakdownLiveCardInner = <T extends BreakdownItem>({@@ -32,6 +33,7 @@ const BreakdownLiveCardInner = <T extends BreakdownItem>({statLabel,totalCount,isLoading,+ onItemClick,}: BreakdownLiveCardProps<T>): JSX.Element => {const colors = useMemo(() => getSeriesColorPalette(), [])@@ -89,38 +91,56 @@ const BreakdownLiveCardInner = <T extends BreakdownItem>({const isTop = index === 0const key = getKey(item)const label = getLabel(item)+ const tooltip = onItemClick+ ? `Click to see visitors · ${item.count.toLocaleString()} ${statLabel}`+ : `${item.count.toLocaleString()} ${statLabel} · ${label}`- return (- <Tooltip key={key} title={`${item.count.toLocaleString()} ${statLabel} · ${label}`}>- <div className="flex items-center gap-2 cursor-default">- {renderIcon && renderIcon(item)}- <div- className={clsx(- 'text-xs truncate',- renderIcon ? 'w-14' : 'w-16',- isTop ? 'text-default font-medium' : 'text-muted'- )}- >- {label}- </div>- <div className="flex-1 h-2 bg-border-light rounded-full overflow-hidden">- <div- className="h-full rounded-full transition-all duration-300 ease-out"- style={{- width: `${item.percentage}%`,- backgroundColor: color,- }}- />- </div>+ const rowContent = (+ <>+ {renderIcon && renderIcon(item)}+ <div+ className={clsx(+ 'text-xs truncate',+ renderIcon ? 'w-14' : 'w-16',+ isTop ? 'text-default font-medium' : 'text-muted'+ )}+ >+ {label}+ </div>+ <div className="flex-1 h-2 bg-border-light rounded-full overflow-hidden"><div- className={clsx(- 'w-10 text-xs text-right tabular-nums',- isTop ? 'text-default font-medium' : 'text-muted'- )}- >- {item.percentage.toFixed(0)}%- </div>+ className="h-full rounded-full transition-all duration-300 ease-out"+ style={{+ width: `${item.percentage}%`,+ backgroundColor: color,+ }}+ /></div>+ <div+ className={clsx(+ 'w-10 text-xs text-right tabular-nums',+ isTop ? 'text-default font-medium' : 'text-muted'+ )}+ >+ {item.percentage.toFixed(0)}%+ </div>+ </>+ )++ return (+ <Tooltip key={key} title={tooltip}>+ {onItemClick ? (+ <button+ type="button"+ onClick={() => onItemClick(item)}+ className="w-full flex items-center gap-2 cursor-pointer hover:bg-bg-3000 rounded -mx-1 px-1 py-0.5 text-left"+ data-attr="breakdown-live-card-row"+ >+ {rowContent}+ </button>+ ) : (+ <div className="flex items-center gap-2 cursor-default">{rowContent}</div>+ )}</Tooltip>)})}diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveLocationsCard.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveLocationsCard.tsxindex b63083bb80d1..5733934e1a1c 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveLocationsCard.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveLocationsCard.tsx@@ -14,6 +14,8 @@ interface LiveLocationsCardProps {countryData: CountryBreakdownItem[]cityData: CityBreakdownItem[]isLoading?: boolean+ onCountryClick?: (item: CountryBreakdownItem) => void+ onCityClick?: (item: CityBreakdownItem) => void}const renderFlagOrGlobe = (countryCode: string): JSX.Element => {@@ -45,7 +47,13 @@ const getCityLabel = (d: CityBreakdownItem): string => {const renderCityIcon = (d: CityBreakdownItem): JSX.Element =>renderFlagOrGlobe(d.cityName === 'Other' ? 'Other' : d.countryCode)-export const LiveLocationsCard = ({ countryData, cityData, isLoading }: LiveLocationsCardProps): JSX.Element => {+export const LiveLocationsCard = ({+ countryData,+ cityData,+ isLoading,+ onCountryClick,+ onCityClick,+}: LiveLocationsCardProps): JSX.Element => {const [activeTab, setActiveTab] = useState<LocationTab>('country')const tabs = (@@ -71,6 +79,7 @@ export const LiveLocationsCard = ({ countryData, cityData, isLoading }: LiveLocaemptyMessage="No city data"statLabel="unique visitors"isLoading={isLoading}+ onItemClick={onCityClick}/>)}@@ -85,6 +94,7 @@ export const LiveLocationsCard = ({ countryData, cityData, isLoading }: LiveLocaemptyMessage="No country data"statLabel="unique visitors"isLoading={isLoading}+ onItemClick={onCountryClick}/>)}diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveMetricsSlidingWindow.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveMetricsSlidingWindow.tsxindex 917a658818bb..4cf768a02a3f 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveMetricsSlidingWindow.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveMetricsSlidingWindow.tsx@@ -11,6 +11,8 @@ import {SlidingWindowBucket,} from './LiveWebAnalyticsMetricsTypes'+export type BreakdownDimension = 'country' | 'city' | 'device' | 'browser'+export class LiveMetricsSlidingWindow {private buckets = new Map<number, SlidingWindowBucket>()private windowSizeSeconds: number@@ -21,6 +23,12 @@ export class LiveMetricsSlidingWindow {private browserBucketCounts = new Map<string, Map<string, number>>()private countryBucketCounts = new Map<string, Map<string, number>>()private cityBucketCounts = new Map<string, Map<string, number>>()+ private bucketCountsByDimension: Record<BreakdownDimension, Map<string, Map<string, number>>> = {+ country: this.countryBucketCounts,+ city: this.cityBucketCounts,+ device: this.deviceBucketCounts,+ browser: this.browserBucketCounts,+ }// Incrementally-maintained aggregatesprivate _totalPageviews = 0@@ -554,6 +562,10 @@ export class LiveMetricsSlidingWindow {return this.userBucketCounts.size}+ getDistinctIdsFor(dimension: BreakdownDimension, value: string): string[] {+ return [...(this.bucketCountsByDimension[dimension].get(value)?.keys() ?? [])]+ }+getBotBreakdown(limit?: number): BotBreakdownItem[] {let total = 0for (const count of this._globalBotCounts.values()) {diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDown.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDown.tsxnew file mode 100644index 000000000000..cd6274a94a8d--- /dev/null+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDown.tsx@@ -0,0 +1,146 @@+import { useActions, useValues } from 'kea'++import { IconInfo, IconRefresh } from '@posthog/icons'+import { LemonButton, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'++import { LemonDrawer } from 'lib/lemon-ui/LemonDrawer/LemonDrawer'++import {+ LivePersonDrillDownBreakdownType,+ LivePersonDrillDownSelection,+ livePersonDrillDownDrawerLogic,+} from './livePersonDrillDownDrawerLogic'+import { livePersonDrillDownLogic } from './livePersonDrillDownLogic'+import { LivePersonDrillDownRow } from './LivePersonDrillDownRow'++const BREAKDOWN_TITLE_PREFIX: Record<LivePersonDrillDownBreakdownType, string> = {+ country: 'Visitors from',+ city: 'Visitors from',+ device: 'Visitors using',+ browser: 'Visitors using',+}++const LivePersonDrillDownInner = ({ selection }: { selection: LivePersonDrillDownSelection }): JSX.Element => {+ const { closeDrillDown } = useActions(livePersonDrillDownDrawerLogic)+ const logicProps = {+ breakdownType: selection.breakdownType,+ breakdownValue: selection.breakdownValue,+ }+ const { persons, personsLoading, totalCount, identifiedCount, anonymousCount, newVisitorCount, isTruncated } =+ useValues(livePersonDrillDownLogic(logicProps))+ const { refresh } = useActions(livePersonDrillDownLogic(logicProps))++ const title = `${BREAKDOWN_TITLE_PREFIX[selection.breakdownType]} ${selection.breakdownLabel}`++ return (+ <LemonDrawer+ isOpen+ onClose={closeDrillDown}+ title={+ <div className="flex items-center gap-2 min-w-0">+ <span className="truncate">{title}</span>+ <span className="text-sm font-normal text-muted tabular-nums shrink-0">+ {totalCount.toLocaleString()}+ </span>+ </div>+ }+ description={+ <div className="flex items-center gap-1 text-xs text-muted">+ Visitors in the last 30 minutes+ <Tooltip title="Lists persons seen for this segment within the live dashboard's 30-minute window. The count updates live as new visitors arrive.">+ <IconInfo className="text-sm" />+ </Tooltip>+ </div>+ }+ footer={+ <LemonButton type="secondary" size="small" icon={<IconRefresh />} onClick={refresh}>+ Refresh+ </LemonButton>+ }+ data-attr="live-person-drilldown"+ >+ <div className="flex flex-col gap-3">+ {newVisitorCount > 0 && (+ <LemonButton+ type="secondary"+ size="small"+ fullWidth+ center+ icon={<IconRefresh />}+ onClick={refresh}+ data-attr="live-person-drilldown-refresh-pill"+ >+ {newVisitorCount === 1+ ? '1 new visitor — refresh'+ : `${newVisitorCount.toLocaleString()} new visitors — refresh`}+ </LemonButton>+ )}++ {personsLoading && persons.length === 0 ? (+ <div className="flex flex-col gap-2">+ {Array.from({ length: 6 }).map((_, i) => (+ <LemonSkeleton key={i} className="h-10 w-full" />+ ))}+ </div>+ ) : identifiedCount === 0 && anonymousCount === 0 ? (+ <div className="text-sm text-muted text-center py-8">No visitors in this window</div>+ ) : (+ <>+ {persons.length > 0 && (+ <div className="flex flex-col">+ <div className="text-xs font-semibold text-muted uppercase mb-2">+ Identified ({persons.length.toLocaleString()}+ {isTruncated ? ` of ${identifiedCount.toLocaleString()}` : ''})+ </div>+ <div className="flex flex-col">+ {persons.map((person) => (+ <LivePersonDrillDownRow key={person.id ?? person.uuid} person={person} />+ ))}+ </div>+ {isTruncated && (+ <div className="text-xs text-muted mt-2">+ Showing the {persons.length.toLocaleString()} most recently seen — narrow+ filters to see more.+ </div>+ )}+ </div>+ )}++ {persons.length === 0 && identifiedCount > 0 && !personsLoading && (+ <div className="text-sm text-muted">+ No profiles found for these distinct IDs. They may not have person processing enabled.+ </div>+ )}++ {anonymousCount > 0 && (+ <div className="flex flex-col gap-1 pt-2 border-t border-border">+ <div className="text-xs font-semibold text-muted uppercase">Anonymous</div>+ <Tooltip title="Cookieless visitors are tracked anonymously by IP and user agent. They do not have a person profile and cannot be linked to.">+ <div className="text-sm text-muted">+ {anonymousCount === 1+ ? '1 anonymous visitor — no profile linked'+ : `${anonymousCount.toLocaleString()} anonymous visitors — no profile linked`}+ </div>+ </Tooltip>+ </div>+ )}+ </>+ )}+ </div>+ </LemonDrawer>+ )+}++export const LivePersonDrillDown = (): JSX.Element | null => {+ const { currentSelection } = useValues(livePersonDrillDownDrawerLogic)+ if (!currentSelection) {+ return null+ }+ return (+ <LivePersonDrillDownInner+ // Re-mount when the (type, value) tuple changes so the keyed logic instance switches cleanly.+ key={`${currentSelection.breakdownType}:${currentSelection.breakdownValue}`}+ selection={currentSelection}+ />+ )+}diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsxnew file mode 100644index 000000000000..096a246b321e--- /dev/null+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx@@ -0,0 +1,49 @@+import { Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { PersonDisplay } from 'scenes/persons/PersonDisplay'+import { urls } from 'scenes/urls'++import { PersonType } from '~/types'++interface LivePersonDrillDownRowProps {+ person: PersonType+}++const pickSecondaryProperty = (person: PersonType): { key: string; value: string } | null => {+ const candidates = ['email', '$browser', '$os', '$geoip_country_code']+ for (const key of candidates) {+ const raw = person.properties?.[key]+ if (typeof raw === 'string' && raw.length > 0) {+ return { key, value: raw }+ }+ }+ return null+}++export const LivePersonDrillDownRow = ({ person }: LivePersonDrillDownRowProps): JSX.Element => {+ const distinctId = person.distinct_ids?.[0]+ const secondary = pickSecondaryProperty(person)+ const href = distinctId ? urls.personByDistinctId(distinctId) : undefined++ return (+ <Link+ to={href}+ subtle+ className="flex items-center gap-3 px-2 py-2 -mx-2 rounded hover:bg-bg-3000"+ data-attr="live-person-drilldown-row"+ >+ <PersonDisplay person={person} withIcon noPopover noLink />+ {secondary && (+ <span className="flex-1 min-w-0 text-xs text-muted truncate ph-no-capture">+ {secondary.key === 'email' ? secondary.value : `${secondary.key}: ${secondary.value}`}+ </span>+ )}+ {person.last_seen_at && (+ <span className="text-xs text-muted shrink-0 ml-auto">+ <TZLabel time={person.last_seen_at} />+ </span>+ )}+ </Link>+ )+}diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsxindex 2fffe4ae10fc..620ce1fbabe5 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx@@ -38,13 +38,21 @@ import { LiveBotTrafficCard } from './LiveBotTrafficCard'import { CONTENT_CARD_SPAN, LiveContentCardId, LiveStatCardId } from './liveCards'import { LiveChartCard } from './LiveChartCard'import { LiveLocationsCard } from './LiveLocationsCard'+import { LivePersonDrillDown } from './LivePersonDrillDown'+import { LivePersonDrillDownSelection, livePersonDrillDownDrawerLogic } from './livePersonDrillDownDrawerLogic'import { LiveStatCard, LiveStatDivider } from './LiveStatCard'import { LiveTopPathsTable } from './LiveTopPathsTable'import { LiveTopReferrersTable } from './LiveTopReferrersTable'import { liveWebAnalyticsLayoutLogic } from './liveWebAnalyticsLayoutLogic'import { BotEventsPerMinuteChart, UsersPerMinuteChart } from './liveWebAnalyticsMetricsCharts'import { liveWebAnalyticsMetricsLogic } from './liveWebAnalyticsMetricsLogic'-import { BrowserBreakdownItem, CountryBreakdownItem, DeviceBreakdownItem } from './LiveWebAnalyticsMetricsTypes'+import {+ BrowserBreakdownItem,+ buildCityKey,+ CityBreakdownItem,+ CountryBreakdownItem,+ DeviceBreakdownItem,+} from './LiveWebAnalyticsMetricsTypes'import { LiveWorldMap } from './LiveWorldMap'const LIVE_FEED_COLUMNS: LiveEventsFeedColumn[] = ['event', 'person', 'url', 'timestamp']@@ -284,7 +292,51 @@ export const LiveWebAnalyticsMetrics = (): JSX.Element => {const { featureFlags } = useValues(featureFlagLogic)const canEditLayout = !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_LIVE_EDIT_LAYOUT]+ const drillDownEnabled = !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_LIVE_PERSON_DRILLDOWN]+ const { openDrillDown } = useActions(livePersonDrillDownDrawerLogic)const isEditing = canEditLayout && isEditingRaw++ const buildRowClickHandler = <T,>(+ isClickable: (item: T) => boolean,+ toSelection: (item: T) => LivePersonDrillDownSelection+ ): ((item: T) => void) | undefined =>+ drillDownEnabled+ ? (item: T): void => {+ if (isClickable(item)) {+ openDrillDown(toSelection(item))+ }+ }+ : undefined++ const countrySelection = (countryCode: string): LivePersonDrillDownSelection => ({+ breakdownType: 'country',+ breakdownValue: countryCode,+ breakdownLabel: COUNTRY_CODE_TO_LONG_NAME[countryCode] ?? countryCode,+ })++ const onCountryRowClick = buildRowClickHandler<CountryBreakdownItem>(+ (item) => item.country !== 'Other',+ (item) => countrySelection(item.country)+ )+ const onCityRowClick = buildRowClickHandler<CityBreakdownItem>(+ (item) => item.cityName !== 'Other',+ (item) => ({+ breakdownType: 'city',+ breakdownValue: buildCityKey(item.cityName, item.countryCode),+ breakdownLabel: item.countryCode ? `${item.cityName}, ${item.countryCode}` : item.cityName,+ })+ )+ const onDeviceRowClick = buildRowClickHandler<DeviceBreakdownItem>(+ (item) => item.device !== 'Other',+ (item) => ({ breakdownType: 'device', breakdownValue: item.device, breakdownLabel: item.device })+ )+ const onBrowserRowClick = buildRowClickHandler<BrowserBreakdownItem>(+ (item) => item.browser !== 'Other',+ (item) => ({ breakdownType: 'browser', breakdownValue: item.browser, breakdownLabel: item.browser })+ )+ const onMapCountryClick = drillDownEnabled+ ? (countryCode: string): void => openDrillDown(countrySelection(countryCode))+ : undefinedconst { isVisible } = usePageVisibility()useEffect(() => {if (isVisible) {@@ -355,6 +407,7 @@ export const LiveWebAnalyticsMetrics = (): JSX.Element => {emptyMessage="No device data"statLabel="unique devices"isLoading={isLoading}+ onItemClick={onDeviceRowClick}/>)case 'browsers':@@ -369,6 +422,7 @@ export const LiveWebAnalyticsMetrics = (): JSX.Element => {statLabel="unique browsers"totalCount={totalBrowsers}isLoading={isLoading}+ onItemClick={onBrowserRowClick}/>)case 'top_countries':@@ -383,6 +437,7 @@ export const LiveWebAnalyticsMetrics = (): JSX.Element => {emptyMessage="No country data"statLabel="unique visitors"isLoading={isLoading}+ onItemClick={onCountryRowClick}/>)}@@ -391,6 +446,8 @@ export const LiveWebAnalyticsMetrics = (): JSX.Element => {countryData={topCountryBreakdown}cityData={topCityBreakdown}isLoading={isLoading}+ onCountryClick={onCountryRowClick}+ onCityClick={onCityRowClick}/>)case 'bot_events_chart':@@ -429,6 +486,7 @@ export const LiveWebAnalyticsMetrics = (): JSX.Element => {<LiveWorldMapdata={countryBreakdown}totalEvents={countryBreakdown.reduce((sum, c) => sum + c.count, 0)}+ onCountryClick={onMapCountryClick}/></LiveChartCard>)@@ -514,6 +572,8 @@ export const LiveWebAnalyticsMetrics = (): JSX.Element => {</div></SortableContext></DndContext>++ {drillDownEnabled && <LivePersonDrillDown />}</div>)}diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWorldMap.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWorldMap.tsxindex 17b5116444b9..2e4e6bb6c9a6 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWorldMap.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWorldMap.tsx@@ -23,6 +23,7 @@ interface CountryPathProps {onMouseEnter: (countryCode: string, e: React.MouseEvent) => voidonMouseMove: (e: React.MouseEvent) => voidonMouseLeave: () => void+ onClick?: (countryCode: string) => void}const CountryPath = React.memo(@@ -35,13 +36,14 @@ const CountryPath = React.memo(onMouseEnter,onMouseMove,onMouseLeave,+ onClick,}: CountryPathProps): JSX.Element => {return React.cloneElement(countryElement, {key: countryCode,style: {color: fill,'--world-map-hover': mapColor,- cursor: fill ? 'pointer' : undefined,+ cursor: fill && onClick ? 'pointer' : undefined,filter:heat > 0? `brightness(${1 + heat * HEAT_BRIGHTNESS_FACTOR}) saturate(${1 + heat}) hue-rotate(${heat * HEAT_HUE_ROTATION_DEG}deg)`@@ -51,6 +53,7 @@ const CountryPath = React.memo(onMouseEnter: (e: React.MouseEvent) => onMouseEnter(countryCode, e),onMouseMove,onMouseLeave,+ onClick: onClick && fill ? () => onClick(countryCode) : undefined,})})@@ -59,9 +62,10 @@ CountryPath.displayName = 'CountryPath'interface LiveWorldMapProps {data: CountryBreakdownItem[]totalEvents: number+ onCountryClick?: (countryCode: string) => void}-export const LiveWorldMap = ({ data, totalEvents }: LiveWorldMapProps): JSX.Element => {+export const LiveWorldMap = ({ data, totalEvents, onCountryClick }: LiveWorldMapProps): JSX.Element => {const { countryCodeToCount, maxCount, tooltipData, countryHeat, mapColor, tooltipPosition } =useValues(liveWorldMapLogic)const { showTooltip, hideTooltip, updateTooltipCoordinates, updateCountryData } = useActions(liveWorldMapLogic)@@ -112,6 +116,7 @@ export const LiveWorldMap = ({ data, totalEvents }: LiveWorldMapProps): JSX.ElemonMouseEnter={handleMouseEnter}onMouseMove={handleMouseMove}onMouseLeave={hideTooltip}+ onClick={onCountryClick}/>)})}diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownDrawerLogic.ts b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownDrawerLogic.tsnew file mode 100644index 000000000000..b0cf71a11ef2--- /dev/null+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownDrawerLogic.ts@@ -0,0 +1,28 @@+import { actions, kea, path, reducers } from 'kea'++import type { livePersonDrillDownDrawerLogicType } from './livePersonDrillDownDrawerLogicType'++export type LivePersonDrillDownBreakdownType = 'country' | 'city' | 'device' | 'browser'++export interface LivePersonDrillDownSelection {+ breakdownType: LivePersonDrillDownBreakdownType+ breakdownValue: string+ breakdownLabel: string+}++export const livePersonDrillDownDrawerLogic = kea<livePersonDrillDownDrawerLogicType>([+ path(['scenes', 'webAnalytics', 'livePersonDrillDownDrawerLogic']),+ actions({+ openDrillDown: (selection: LivePersonDrillDownSelection) => selection,+ closeDrillDown: true,+ }),+ reducers({+ currentSelection: [+ null as LivePersonDrillDownSelection | null,+ {+ openDrillDown: (_, payload) => payload,+ closeDrillDown: () => null,+ },+ ],+ }),+])diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.test.ts b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.test.tsnew file mode 100644index 000000000000..6f21b372999d--- /dev/null+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.test.ts@@ -0,0 +1,105 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { livePersonDrillDownDrawerLogic, LivePersonDrillDownSelection } from './livePersonDrillDownDrawerLogic'+import { COOKIELESS_DISTINCT_ID_PREFIX, partitionDistinctIds } from './livePersonDrillDownLogic'++describe('partitionDistinctIds', () => {+ it('separates cookieless ids from identified ones', () => {+ const result = partitionDistinctIds([+ 'user-1',+ `${COOKIELESS_DISTINCT_ID_PREFIX}abc`,+ 'user-2',+ `${COOKIELESS_DISTINCT_ID_PREFIX}def`,+ ])+ expect(result).toEqual({+ identified: ['user-1', 'user-2'],+ anonymous: [`${COOKIELESS_DISTINCT_ID_PREFIX}abc`, `${COOKIELESS_DISTINCT_ID_PREFIX}def`],+ })+ })++ it('handles an empty input', () => {+ expect(partitionDistinctIds([])).toEqual({ identified: [], anonymous: [] })+ })++ it('handles all-cookieless input', () => {+ const result = partitionDistinctIds([`${COOKIELESS_DISTINCT_ID_PREFIX}a`, `${COOKIELESS_DISTINCT_ID_PREFIX}b`])+ expect(result.identified).toEqual([])+ expect(result.anonymous).toHaveLength(2)+ })++ it('preserves order within each partition', () => {+ const result = partitionDistinctIds([+ 'z',+ `${COOKIELESS_DISTINCT_ID_PREFIX}1`,+ 'a',+ `${COOKIELESS_DISTINCT_ID_PREFIX}2`,+ 'm',+ ])+ expect(result.identified).toEqual(['z', 'a', 'm'])+ expect(result.anonymous).toEqual([`${COOKIELESS_DISTINCT_ID_PREFIX}1`, `${COOKIELESS_DISTINCT_ID_PREFIX}2`])+ })++ it('does not treat ids that merely contain "cookieless" as anonymous', () => {+ const result = partitionDistinctIds(['user_with_cookieless_word', 'cookieless'])+ expect(result.identified).toEqual(['user_with_cookieless_word', 'cookieless'])+ expect(result.anonymous).toEqual([])+ })+})++describe('livePersonDrillDownDrawerLogic', () => {+ let logic: ReturnType<typeof livePersonDrillDownDrawerLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = livePersonDrillDownDrawerLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('starts with no current selection', async () => {+ await expectLogic(logic).toMatchValues({ currentSelection: null })+ })++ it('opens a drill-down with the given selection', async () => {+ const selection: LivePersonDrillDownSelection = {+ breakdownType: 'country',+ breakdownValue: 'US',+ breakdownLabel: 'United States',+ }+ await expectLogic(logic, () => {+ logic.actions.openDrillDown(selection)+ }).toMatchValues({ currentSelection: selection })+ })++ it('replaces the current selection when opening a different one', async () => {+ logic.actions.openDrillDown({+ breakdownType: 'country',+ breakdownValue: 'US',+ breakdownLabel: 'United States',+ })+ const next: LivePersonDrillDownSelection = {+ breakdownType: 'browser',+ breakdownValue: 'Chrome',+ breakdownLabel: 'Chrome',+ }+ await expectLogic(logic, () => {+ logic.actions.openDrillDown(next)+ }).toMatchValues({ currentSelection: next })+ })++ it('clears the selection on close', async () => {+ logic.actions.openDrillDown({+ breakdownType: 'country',+ breakdownValue: 'US',+ breakdownLabel: 'United States',+ })+ await expectLogic(logic, () => {+ logic.actions.closeDrillDown()+ }).toMatchValues({ currentSelection: null })+ })+})diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.ts b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.tsnew file mode 100644index 000000000000..4c61832e9cc3--- /dev/null+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.ts@@ -0,0 +1,177 @@+import equal from 'fast-deep-equal'+import { actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { parsePersonFromHogQLRow } from 'scenes/persons/person-utils'+import { WEB_ANALYTICS_DEFAULT_QUERY_TAGS } from 'scenes/web-analytics/common'++import { performQuery } from '~/queries/query'+import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'+import { hogql } from '~/queries/utils'+import { PersonType } from '~/types'++import { LiveMetricsSlidingWindow } from './LiveMetricsSlidingWindow'+import { LivePersonDrillDownBreakdownType, livePersonDrillDownDrawerLogic } from './livePersonDrillDownDrawerLogic'+import type { livePersonDrillDownLogicType } from './livePersonDrillDownLogicType'+import { liveWebAnalyticsMetricsLogic } from './liveWebAnalyticsMetricsLogic'++export const COOKIELESS_DISTINCT_ID_PREFIX = 'cookieless_'+export const PERSON_HYDRATION_LIMIT = 200++export interface LivePersonDrillDownLogicProps {+ breakdownType: LivePersonDrillDownBreakdownType+ breakdownValue: string+}++export const partitionDistinctIds = (distinctIds: string[]): { identified: string[]; anonymous: string[] } => {+ const identified: string[] = []+ const anonymous: string[] = []+ for (const id of distinctIds) {+ if (id.startsWith(COOKIELESS_DISTINCT_ID_PREFIX)) {+ anonymous.push(id)+ } else {+ identified.push(id)+ }+ }+ return { identified, anonymous }+}++export const livePersonDrillDownLogic = kea<livePersonDrillDownLogicType>([+ props({} as LivePersonDrillDownLogicProps),+ key((p) => `${p.breakdownType}:${p.breakdownValue}`),+ path((logicKey) => ['scenes', 'webAnalytics', 'livePersonDrillDownLogic', logicKey]),+ connect(() => ({+ values: [+ liveWebAnalyticsMetricsLogic,+ ['slidingWindow', 'eventsVersion', 'geoVersion'],+ livePersonDrillDownDrawerLogic,+ ['currentSelection'],+ ],+ })),+ actions({+ refresh: true,+ }),+ loaders(() => ({+ persons: [+ [] as PersonType[],+ {+ loadPersons: async ({ distinctIds }: { distinctIds: string[] }) => {+ const { identified } = partitionDistinctIds(distinctIds)+ if (identified.length === 0) {+ return []+ }+ const limitedIds = identified.slice(0, PERSON_HYDRATION_LIMIT)+ const query = hogql`SELECT+ id,+ groupArray(101)(pdi2.distinct_id) AS distinct_ids,+ properties,+ is_identified,+ created_at,+ last_seen_at+ FROM persons+ LEFT JOIN (+ SELECT+ pdi2.distinct_id,+ argMax(pdi2.person_id, pdi2.version) AS person_id+ FROM raw_person_distinct_ids pdi2+ WHERE pdi2.distinct_id IN (+ SELECT distinct_id+ FROM raw_person_distinct_ids+ WHERE person_id IN (+ SELECT argMax(person_id, version) AS person_id+ FROM raw_person_distinct_ids+ WHERE distinct_id IN ${limitedIds}+ GROUP BY distinct_id+ HAVING argMax(is_deleted, version) = 0+ )+ )+ GROUP BY pdi2.distinct_id+ HAVING argMax(pdi2.is_deleted, pdi2.version) = 0+ ) AS pdi2 ON pdi2.person_id = persons.id+ WHERE persons.id IN (+ SELECT argMax(person_id, version) AS person_id+ FROM raw_person_distinct_ids+ WHERE distinct_id IN ${limitedIds}+ GROUP BY distinct_id+ HAVING argMax(is_deleted, version) = 0+ )+ GROUP BY id, properties, is_identified, created_at, last_seen_at+ ORDER BY last_seen_at DESC+ LIMIT ${PERSON_HYDRATION_LIMIT}`++ const response = (await performQuery({+ kind: NodeKind.HogQLQuery,+ query,+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,+ })) as HogQLQueryResponse+ return (response.results ?? []).map(parsePersonFromHogQLRow)+ },+ },+ ],+ })),+ reducers({+ displayedDistinctIds: [+ [] as string[],+ {+ loadPersons: (_, { distinctIds }) => distinctIds,+ },+ ],+ }),+ selectors({+ currentDistinctIds: [+ (s) => [s.slidingWindow, s.eventsVersion, s.geoVersion, (_, p) => p],+ (+ slidingWindow: LiveMetricsSlidingWindow,+ _eventsVersion: number,+ _geoVersion: number,+ props: LivePersonDrillDownLogicProps+ ): string[] => slidingWindow.getDistinctIdsFor(props.breakdownType, props.breakdownValue),+ { resultEqualityCheck: equal },+ ],+ partitionedDistinctIds: [+ (s) => [s.currentDistinctIds],+ (distinctIds: string[]): { identified: string[]; anonymous: string[] } => partitionDistinctIds(distinctIds),+ { resultEqualityCheck: equal },+ ],+ identifiedDistinctIds: [+ (s) => [s.partitionedDistinctIds],+ (partitioned: { identified: string[] }): string[] => partitioned.identified,+ ],+ anonymousCount: [+ (s) => [s.partitionedDistinctIds],+ (partitioned: { anonymous: string[] }): number => partitioned.anonymous.length,+ ],+ totalCount: [(s) => [s.currentDistinctIds], (distinctIds: string[]): number => distinctIds.length],+ identifiedCount: [(s) => [s.identifiedDistinctIds], (identified: string[]): number => identified.length],+ newVisitorCount: [+ (s) => [s.identifiedDistinctIds, s.displayedDistinctIds],+ (current: string[], displayed: string[]): number => {+ if (displayed.length === 0) {+ return 0+ }+ const displayedSet = new Set(displayed)+ let n = 0+ for (const id of current) {+ if (!displayedSet.has(id)) {+ n+++ }+ }+ return n+ },+ ],+ isTruncated: [+ (s) => [s.identifiedCount],+ (identifiedCount: number): boolean => identifiedCount > PERSON_HYDRATION_LIMIT,+ ],+ }),+ listeners(({ actions, values }) => ({+ refresh: () => {+ actions.loadPersons({ distinctIds: values.identifiedDistinctIds })+ },+ })),+ events(({ actions, values }) => ({+ afterMount: () => {+ actions.loadPersons({ distinctIds: values.identifiedDistinctIds })+ },+ })),+])