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.

fix(product-analytics): reuse home dashboard query results (#113344)

Daniel Parker3aff4b92f010
diff --git a/frontend/src/scenes/saved-insights/HomeTabChartCard.tsx b/frontend/src/scenes/saved-insights/HomeTabChartCard.tsx
index 1327485e496d..53e5d7e69cd7 100644
--- a/frontend/src/scenes/saved-insights/HomeTabChartCard.tsx
+++ b/frontend/src/scenes/saved-insights/HomeTabChartCard.tsx
@@ -1,14 +1,22 @@
import './HomeTabChartCard.scss'
+import { useValues } from 'kea'
import type { ReactNode } from 'react'
import { IconInfo } from '@posthog/icons'
import { LemonButton, LemonCard } from '@posthog/lemon-ui'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { teamLogic } from 'scenes/teamLogic'
import { Query } from '~/queries/Query/Query'
+import {
+ homeTabChartInsightId,
+ homeTabDataCollectionId,
+} from 'products/product_analytics/frontend/insights/home/homeTabQueryKeys'
+
+import { homeTabDefaultLogic } from './homeTabDefaultLogic'
import { getHomeTabExploreUrl, type HomeTabChartOption } from './homeTabDefaultTiles'
interface HomeTabChartCardProps {
@@ -19,6 +27,7 @@ interface HomeTabChartCardProps {
}
export function HomeTabChartCard({ option, size, control, source }: HomeTabChartCardProps): JSX.Element {
+ const { currentTeamId } = useValues(teamLogic)
return (
<LemonCard hoverEffect={false} className="HomeTabChartCard flex min-w-0 flex-col overflow-hidden p-0">
<div className="HomeTabChartCard__header border-b border-primary px-4 py-2.5">
@@ -50,7 +59,20 @@ export function HomeTabChartCard({ option, size, control, source }: HomeTabChart
<div
className={`HomeTabDefaultChart HomeTabChartCard__visualization HomeTabChartCard__visualization--${size}`}
>
- <Query query={option.query} readOnly uniqueKey={option.key} />
+ <Query
+ key={currentTeamId}
+ query={option.query}
+ readOnly
+ uniqueKey={`HomeTab.${currentTeamId}.${option.key}`}
+ context={{
+ insightProps: {
+ dashboardItemId: homeTabChartInsightId(currentTeamId, option.key),
+ dataNodeCollectionId: homeTabDataCollectionId(currentTeamId),
+ query: option.query,
+ },
+ }}
+ attachTo={homeTabDefaultLogic}
+ />
</div>
</LemonCard>
)
diff --git a/frontend/src/scenes/saved-insights/HomeTabDefault.tsx b/frontend/src/scenes/saved-insights/HomeTabDefault.tsx
index 91c6bcbec386..9e282cc7f8a1 100644
--- a/frontend/src/scenes/saved-insights/HomeTabDefault.tsx
+++ b/frontend/src/scenes/saved-insights/HomeTabDefault.tsx
@@ -1,4 +1,4 @@
-import { useActions, useValues } from 'kea'
+import { useActions, useMountedLogic, useValues } from 'kea'
import type { ReactNode } from 'react'
import { IconCalendar } from '@posthog/icons'
@@ -7,20 +7,37 @@ import { LemonSelect } from '@posthog/lemon-ui'
import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
+import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { dateMapping } from 'lib/utils/dateFilters'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'
import { HomeTabExplore } from 'products/product_analytics/frontend/insights/home/HomeTabExplore'
+import { homeTabLoadTimeLogic } from 'products/product_analytics/frontend/insights/home/homeTabLoadTimeLogic'
+import {
+ homeTabChartInsightId,
+ homeTabStatKey,
+} from 'products/product_analytics/frontend/insights/home/homeTabQueryKeys'
import { HomeTabChartCard } from './HomeTabChartCard'
import { homeTabDefaultLogic } from './homeTabDefaultLogic'
-import { getHomeTabAudienceOptions, getHomeTabBreakdownOptions, getHomeTabChartOptions } from './homeTabDefaultTiles'
+import {
+ getHomeTabAudienceOptions,
+ getHomeTabBreakdownOptions,
+ getHomeTabChartOptions,
+ getHomeTabStatQueries,
+} from './homeTabDefaultTiles'
import { HomeTabStatTiles } from './HomeTabStatTiles'
+import { savedInsightsLogic } from './savedInsightsLogic'
const HOME_DATE_OPTIONS = dateMapping.filter((option) => option.key !== CUSTOM_OPTION_KEY)
export function HomeTabDefault({ dashboardActions }: { dashboardActions?: ReactNode }): JSX.Element {
+ useAttachedLogic(homeTabDefaultLogic(), savedInsightsLogic)
const { dateRange, compare, selectedMetric, selectedContentKey } = useValues(homeTabDefaultLogic)
const { setDates, setCompare, setSelectedMetric, setSelectedContentKey } = useActions(homeTabDefaultLogic)
+ const { currentTeamId } = useValues(teamLogic)
const metricCharts = getHomeTabChartOptions(dateRange, compare)
const audienceCharts = getHomeTabAudienceOptions(dateRange)
@@ -32,6 +49,20 @@ export function HomeTabDefault({ dashboardActions }: { dashboardActions?: ReactN
const eventsChart =
breakdownCharts.find((option) => option.key === 'top_events') ?? breakdownCharts[breakdownCharts.length - 1]
+ useMountedLogic(
+ homeTabLoadTimeLogic({
+ teamId: currentTeamId,
+ tileIds: [
+ ...getHomeTabStatQueries(dateRange, compare).map((stat) => homeTabStatKey(currentTeamId, stat.key)),
+ ...[primaryChart, contentChart, eventsChart, ...audienceCharts, retentionChart].map((chart) =>
+ insightVizDataNodeKey({ dashboardItemId: homeTabChartInsightId(currentTeamId, chart.key) })
+ ),
+ ],
+ defaultDateRange: dateRange.date_from === '-7d' && !dateRange.date_to,
+ compare,
+ })
+ )
+
return (
<div className="@container/home-overview flex flex-col gap-4 @max-[32rem]/saved-insights:gap-3">
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-primary pb-2 @min-[32rem]/home-overview:pb-3">
diff --git a/frontend/src/scenes/saved-insights/HomeTabStatTile.tsx b/frontend/src/scenes/saved-insights/HomeTabStatTile.tsx
index ab2169584e1c..5fcc26339748 100644
--- a/frontend/src/scenes/saved-insights/HomeTabStatTile.tsx
+++ b/frontend/src/scenes/saved-insights/HomeTabStatTile.tsx
@@ -2,12 +2,20 @@ import { useValues } from 'kea'
import { AnalyticsMetricCard } from 'lib/components/AnalyticsMetricCard/AnalyticsMetricCard'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { formatItem } from '~/queries/nodes/OverviewGrid/OverviewGrid'
import type { TrendsQueryResponse } from '~/queries/schema/schema-general'
import type { TrendResult } from '~/types'
+import {
+ homeTabDataCollectionId,
+ homeTabStatKey,
+} from 'products/product_analytics/frontend/insights/home/homeTabQueryKeys'
+
+import { homeTabDefaultLogic } from './homeTabDefaultLogic'
import { getHomeTabStatValue, type HomeTabStatQuery } from './homeTabDefaultTiles'
interface HomeTabStatTileProps {
@@ -18,10 +26,15 @@ interface HomeTabStatTileProps {
}
export function HomeTabStatTile({ stat, compare, selected, onSelect }: HomeTabStatTileProps): JSX.Element {
- const key = `HomeTabStatTile.${stat.key}`
- const { response, responseError, responseLoading } = useValues(
- dataNodeLogic({ query: stat.query, key, dataNodeCollectionId: key })
- )
+ const { currentTeamId } = useValues(teamLogic)
+ const key = homeTabStatKey(currentTeamId, stat.key)
+ const logic = dataNodeLogic({
+ query: stat.query,
+ key,
+ dataNodeCollectionId: homeTabDataCollectionId(currentTeamId),
+ })
+ useAttachedLogic(logic, homeTabDefaultLogic)
+ const { response, responseError, responseLoading } = useValues(logic)
const loading = responseLoading || (!response && !responseError)
const results = (response as TrendsQueryResponse | undefined)?.results ?? (response as { result?: unknown })?.result
diff --git a/frontend/src/scenes/saved-insights/homeTabDefaultLogic.ts b/frontend/src/scenes/saved-insights/homeTabDefaultLogic.ts
index f74b80221956..3c06df252f62 100644
--- a/frontend/src/scenes/saved-insights/homeTabDefaultLogic.ts
+++ b/frontend/src/scenes/saved-insights/homeTabDefaultLogic.ts
@@ -2,7 +2,7 @@ import { MakeLogicType, actions, kea, path, reducers } from 'kea'
import { DateRange } from '~/queries/schema/schema-general'
-export const HOME_TAB_DEFAULT_DATE_RANGE: DateRange = { date_from: '-30d', date_to: null }
+export const HOME_TAB_DEFAULT_DATE_RANGE: DateRange = { date_from: '-7d', date_to: null }
export type HomeTabMetricKey = 'active_users' | 'sessions' | 'new_users' | 'session_duration' | 'daily_active_users'
export type HomeTabContentKey = 'top_pages' | 'top_screens'
@@ -56,7 +56,7 @@ export const homeTabDefaultLogic = kea<homeTabDefaultLogicType>([
HOME_TAB_DEFAULT_DATE_RANGE,
{
setDates: (_, { dateFrom, dateTo, explicitDate }) => ({
- date_from: dateFrom ?? '-30d',
+ date_from: dateFrom ?? HOME_TAB_DEFAULT_DATE_RANGE.date_from,
date_to: dateTo,
explicitDate,
}),
diff --git a/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx b/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx
new file mode 100644
index 000000000000..9b5588e44a50
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx
@@ -0,0 +1,79 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'
+
+import { HomeTabDefault } from 'scenes/saved-insights/HomeTabDefault'
+import { homeTabDefaultLogic } from 'scenes/saved-insights/homeTabDefaultLogic'
+import { savedInsightsLogic } from 'scenes/saved-insights/savedInsightsLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import trendsNumber from '~/mocks/fixtures/api/projects/team_id/insights/trendsNumber.json'
+import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+import { performQuery } from '~/queries/query'
+import { isInsightQueryNode } from '~/queries/utils'
+import { initKeaTests } from '~/test/init'
+
+import { homeTabDataCollectionId } from './homeTabQueryKeys'
+
+jest.mock('~/queries/query', () => ({
+ ...jest.requireActual('~/queries/query'),
+ performQuery: jest.fn(),
+}))
+jest.mock('~/queries/nodes/InsightViz/InsightVizDisplay', () => ({
+ InsightVizDisplay: () => <div />,
+}))
+
+const mockedQuery = jest.mocked(performQuery)
+
+describe('HomeTabDefault query reuse', () => {
+ beforeEach(() => {
+ initKeaTests()
+ savedInsightsLogic.mount()
+ mockedQuery.mockImplementation(async (query) => ({
+ results: [
+ {
+ ...trendsNumber.result[0],
+ aggregated_value: isInsightQueryNode(query) && query.dateRange?.date_from === '-30d' ? 20 : 10,
+ },
+ ],
+ }))
+ })
+
+ afterEach(() => {
+ cleanup()
+ savedInsightsLogic.unmount()
+ })
+
+ it('reuses loaded queries on return and fetches new results when the range changes', async () => {
+ const { rerender } = render(<HomeTabDefault />)
+ const collection = dataNodeCollectionLogic({ key: homeTabDataCollectionId(teamLogic.values.currentTeamId) })
+
+ await waitFor(() => expect(mockedQuery).toHaveBeenCalledTimes(11))
+ await waitFor(() => expect(collection.values.areAnyLoading).toBe(false))
+ expect(
+ within(screen.getByLabelText('Active users', { selector: 'button' })).getByText('10')
+ ).toBeInTheDocument()
+
+ await act(async () => rerender(<div>Another tab</div>))
+ expect(savedInsightsLogic.isMounted()).toBe(true)
+ await act(async () => rerender(<HomeTabDefault />))
+
+ expect(mockedQuery).toHaveBeenCalledTimes(11)
+ expect(
+ within(screen.getByLabelText('Active users', { selector: 'button' })).getByText('10')
+ ).toBeInTheDocument()
+
+ await act(async () => homeTabDefaultLogic.actions.setDates('-30d', null))
+ await waitFor(() => expect(mockedQuery).toHaveBeenCalledTimes(22))
+ await waitFor(() => expect(collection.values.areAnyLoading).toBe(false))
+
+ expect(
+ mockedQuery.mock.calls
+ .slice(11)
+ .every(([query]) => isInsightQueryNode(query) && query.dateRange?.date_from === '-30d')
+ ).toBe(true)
+ expect(
+ within(screen.getByLabelText('Active users', { selector: 'button' })).getByText('20')
+ ).toBeInTheDocument()
+ })
+})
diff --git a/products/product_analytics/frontend/insights/home/homeTabLoadTimeLogic.test.ts b/products/product_analytics/frontend/insights/home/homeTabLoadTimeLogic.test.ts
new file mode 100644
index 000000000000..259b6107236d
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/homeTabLoadTimeLogic.test.ts
@@ -0,0 +1,152 @@
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+import { initKeaTests } from '~/test/init'
+
+import { homeTabLoadTimeLogic } from './homeTabLoadTimeLogic'
+import { homeTabDataCollectionId } from './homeTabQueryKeys'
+
+jest.mock('posthog-js')
+
+describe('homeTabLoadTimeLogic', () => {
+ let logic: ReturnType<typeof homeTabLoadTimeLogic.build>
+ let collection: ReturnType<typeof dataNodeCollectionLogic.build>
+ let now: number
+
+ const loadEvents = (): Record<string, unknown>[] =>
+ (posthog.capture as jest.Mock).mock.calls
+ .filter(([event]) => event === 'product_analytics_home_load')
+ .map(([, properties]) => properties)
+
+ beforeEach(() => {
+ initKeaTests()
+ ;(posthog.capture as jest.Mock).mockClear()
+ now = 100
+ jest.spyOn(performance, 'now').mockImplementation(() => now)
+ collection = dataNodeCollectionLogic({ key: homeTabDataCollectionId(123) })
+ collection.mount()
+ logic = homeTabLoadTimeLogic({ teamId: 123, tileIds: ['a', 'b'], defaultDateRange: true, compare: true })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ if (logic.isMounted()) {
+ logic.unmount()
+ }
+ collection.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it.each(['success', 'failure'] as const)('waits for all visible tiles and reports %s once', async (status) => {
+ collection.actions.collectionNodeLoadData('a')
+ collection.actions.collectionNodeLoadData('b')
+ collection.actions.collectionNodeLoadData('hidden-chart')
+ collection.actions.collectionNodeLoadDataSuccess('a')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(loadEvents()).toHaveLength(0)
+
+ now = 350
+ if (status === 'success') {
+ collection.actions.collectionNodeLoadDataSuccess('b', { isCached: true })
+ } else {
+ collection.actions.collectionNodeLoadDataFailure('b')
+ }
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(loadEvents()).toEqual([
+ expect.objectContaining({
+ team_id: 123,
+ duration_ms: 250,
+ status,
+ load_type: 'query',
+ tile_count: 2,
+ failed_tile_count: status === 'failure' ? 1 : 0,
+ was_hidden: false,
+ default_date_range: true,
+ compare: true,
+ }),
+ ])
+ const [, mounted] = (posthog.capture as jest.Mock).mock.calls.find(
+ ([event]) => event === 'product_analytics_home_mounted'
+ )
+ expect(loadEvents()[0].visit_id).toBe(mounted.visit_id)
+
+ collection.actions.collectionNodeLoadDataSuccess('hidden-chart')
+ collection.actions.collectionNodeLoadData('a')
+ collection.actions.collectionNodeLoadDataSuccess('a')
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+ expect(loadEvents()).toHaveLength(1)
+ })
+
+ it('measures a new cached visit without waiting for a query', async () => {
+ collection.actions.collectionNodeLoadData('a')
+ collection.actions.collectionNodeLoadData('b')
+ collection.actions.collectionNodeLoadDataSuccess('a')
+ collection.actions.collectionNodeLoadDataSuccess('b')
+ await expectLogic(logic).toFinishAllListeners()
+ const initialVisit = loadEvents()[0].visit_id
+ logic.unmount()
+ ;(posthog.capture as jest.Mock).mockClear()
+
+ now = 500
+ logic.mount()
+ now = 510
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(loadEvents()).toEqual([
+ expect.objectContaining({ status: 'success', load_type: 'cached', duration_ms: 10 }),
+ ])
+ expect(loadEvents()[0].visit_id).not.toBe(initialVisit)
+ })
+
+ it.each(['navigation', 'pagehide'] as const)('reports an unfinished visit on %s', async (exit) => {
+ collection.actions.collectionNodeLoadData('a')
+ await expectLogic(logic).toFinishAllListeners()
+ now = 600
+ if (exit === 'pagehide') {
+ collection.actions.pageHidden()
+ }
+ logic.unmount()
+
+ expect(loadEvents()).toEqual([
+ expect.objectContaining({ status: 'cancelled', load_type: 'query', duration_ms: 500 }),
+ ])
+ })
+
+ it('waits for queries that still run when the tab opens again', async () => {
+ collection.actions.collectionNodeLoadData('a')
+ collection.actions.collectionNodeLoadData('b')
+ logic.unmount()
+ ;(posthog.capture as jest.Mock).mockClear()
+ logic.mount()
+ collection.actions.collectionNodeLoadDataSuccess('a')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(loadEvents()).toHaveLength(0)
+ collection.actions.collectionNodeLoadDataSuccess('b')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(loadEvents()).toEqual([expect.objectContaining({ status: 'success', load_type: 'query' })])
+ })
+
+ it('marks hidden visits and ignores load results from another project', async () => {
+ const other = dataNodeCollectionLogic({ key: homeTabDataCollectionId(456) })
+ other.mount()
+ other.actions.collectionNodeLoadData('a')
+ other.actions.collectionNodeLoadDataSuccess('a')
+ other.actions.collectionNodeLoadData('b')
+ other.actions.collectionNodeLoadDataSuccess('b')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(loadEvents()).toHaveLength(0)
+ other.unmount()
+
+ collection.actions.collectionNodeLoadData('a')
+ collection.actions.collectionNodeLoadData('b')
+ collection.actions.visibilityChanged(true)
+ collection.actions.visibilityChanged(false)
+ collection.actions.collectionNodeLoadDataSuccess('a')
+ collection.actions.collectionNodeLoadDataSuccess('b')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(loadEvents()).toEqual([expect.objectContaining({ team_id: 123, was_hidden: true })])
+ })
+})
diff --git a/products/product_analytics/frontend/insights/home/homeTabLoadTimeLogic.ts b/products/product_analytics/frontend/insights/home/homeTabLoadTimeLogic.ts
new file mode 100644
index 000000000000..c7991293f2c7
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/homeTabLoadTimeLogic.ts
@@ -0,0 +1,169 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ beforeUnmount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+} from 'kea'
+import posthog, { CaptureOptions } from 'posthog-js'
+
+import { uuid } from 'lib/utils/dom'
+
+import { DataNodeStatusMap, dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+
+import { homeTabDataCollectionId } from './homeTabQueryKeys'
+
+export interface HomeTabLoadTimeLogicProps {
+ teamId: number | null
+ tileIds: string[]
+ defaultDateRange: boolean
+ compare: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface homeTabLoadTimeLogicValues {
+ collectionNodeStatus: DataNodeStatusMap // dataNodeCollectionLogic
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface homeTabLoadTimeLogicActions {
+ collectionNodeLoadData: (
+ id: string,
+ kind?: string | undefined
+ ) => {
+ id: string
+ kind: string | undefined
+ } // dataNodeCollectionLogic
+ collectionNodeLoadDataFailure: (id: string) => {
+ id: string
+ } // dataNodeCollectionLogic
+ collectionNodeLoadDataSuccess: (
+ id: string,
+ meta?: import('~/queries/nodes/DataNode/dataNodeCollectionLogic').CollectionNodeLoadMeta | undefined
+ ) => {
+ id: string
+ meta: import('~/queries/nodes/DataNode/dataNodeCollectionLogic').CollectionNodeLoadMeta | undefined
+ } // dataNodeCollectionLogic
+ endPageVisit: () => {
+ value: true
+ } // dataNodeCollectionLogic
+ pageHidden: () => {
+ value: true
+ } // dataNodeCollectionLogic
+ startPageVisit: (visitId: string) => {
+ visitId: string
+ } // dataNodeCollectionLogic
+ visibilityChanged: (hidden: boolean) => {
+ hidden: boolean
+ } // dataNodeCollectionLogic
+ checkLoaded: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface homeTabLoadTimeLogicMeta {
+ key: number | 'none'
+}
+
+export type homeTabLoadTimeLogicType = MakeLogicType<
+ homeTabLoadTimeLogicValues,
+ homeTabLoadTimeLogicActions,
+ HomeTabLoadTimeLogicProps,
+ homeTabLoadTimeLogicMeta
+>
+
+export const homeTabLoadTimeLogic: LogicWrapper<homeTabLoadTimeLogicType> = kea<homeTabLoadTimeLogicType>([
+ props({} as HomeTabLoadTimeLogicProps),
+ key(({ teamId }) => teamId ?? 'none'),
+ path((key) => ['products', 'product_analytics', 'home', 'homeTabLoadTimeLogic', key]),
+ connect(({ teamId }: HomeTabLoadTimeLogicProps) => ({
+ values: [dataNodeCollectionLogic({ key: homeTabDataCollectionId(teamId) }), ['collectionNodeStatus']],
+ actions: [
+ dataNodeCollectionLogic({ key: homeTabDataCollectionId(teamId) }),
+ [
+ 'collectionNodeLoadData',
+ 'collectionNodeLoadDataSuccess',
+ 'collectionNodeLoadDataFailure',
+ 'visibilityChanged',
+ 'pageHidden',
+ 'startPageVisit',
+ 'endPageVisit',
+ ],
+ ],
+ })),
+ actions({
+ checkLoaded: true,
+ }),
+ listeners(({ actions, values, props, cache }) => {
+ const reportLoad = (status: 'success' | 'failure' | 'cancelled', options?: CaptureOptions): void => {
+ if (cache.hasReported) {
+ return
+ }
+ cache.hasReported = true
+ posthog.capture(
+ 'product_analytics_home_load',
+ {
+ team_id: props.teamId,
+ visit_id: cache.visitId,
+ duration_ms: Math.round(performance.now() - cache.mountStart),
+ status,
+ load_type: cache.hasObservedLoading ? 'query' : 'cached',
+ tile_count: props.tileIds.length,
+ failed_tile_count: props.tileIds.filter((id) => values.collectionNodeStatus[id]?.hasError).length,
+ was_hidden: cache.wasHidden,
+ default_date_range: props.defaultDateRange,
+ compare: props.compare,
+ },
+ options
+ )
+ }
+ cache.reportLoad = reportLoad
+ return {
+ collectionNodeLoadData: ({ id }) => {
+ if (props.tileIds.includes(id)) {
+ cache.hasObservedLoading = true
+ }
+ },
+ collectionNodeLoadDataSuccess: () => actions.checkLoaded(),
+ collectionNodeLoadDataFailure: () => actions.checkLoaded(),
+ visibilityChanged: ({ hidden }) => {
+ cache.wasHidden ||= hidden
+ },
+ pageHidden: () => reportLoad('cancelled', { transport: 'sendBeacon' }),
+ checkLoaded: async (_, breakpoint) => {
+ await breakpoint(0)
+ if (cache.hasReported || !props.tileIds.length) {
+ return
+ }
+ const statuses = props.tileIds.map((id) => values.collectionNodeStatus[id])
+ cache.hasObservedLoading ||= statuses.some((status) => status?.isLoading)
+ if (statuses.every((status) => status && !status.isLoading)) {
+ reportLoad(statuses.some((status) => status?.hasError) ? 'failure' : 'success')
+ }
+ },
+ }
+ }),
+ afterMount(({ actions, values, props, cache }) => {
+ cache.mountStart = performance.now()
+ cache.visitId = uuid()
+ cache.hasReported = false
+ cache.hasObservedLoading = props.tileIds.some((id) => values.collectionNodeStatus[id]?.isLoading)
+ cache.wasHidden = document.visibilityState === 'hidden'
+ actions.startPageVisit(cache.visitId)
+ posthog.capture('product_analytics_home_mounted', { team_id: props.teamId, visit_id: cache.visitId })
+ actions.checkLoaded()
+ }),
+ propsChanged(({ actions }) => actions.checkLoaded()),
+ beforeUnmount(({ actions, cache }) => {
+ cache.reportLoad('cancelled')
+ actions.endPageVisit()
+ }),
+])
diff --git a/products/product_analytics/frontend/insights/home/homeTabQueryKeys.ts b/products/product_analytics/frontend/insights/home/homeTabQueryKeys.ts
new file mode 100644
index 000000000000..68b91cfc4b7a
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/homeTabQueryKeys.ts
@@ -0,0 +1,13 @@
+import { pageCollectionId } from '~/queries/nodes/DataNode/pageCollections'
+
+export function homeTabDataCollectionId(teamId: number | null): string {
+ return pageCollectionId(`product-analytics-home.${teamId}`)
+}
+
+export function homeTabStatKey(teamId: number | null, metric: string): string {
+ return `HomeTabStatTile.${teamId}.${metric}`
+}
+
+export function homeTabChartInsightId(teamId: number | null, chart: string): `new-${string}` {
+ return `new-AdHoc.InsightViz.HomeTab.${teamId}.${chart}`
+}