: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
perf(frontend): mount the product setup preload in the authenticated shell (#115070)
Paul D'Ambrad193381aa48c
diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex def6cf7cf2c9..cec4dece8c11 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -95,6 +95,8 @@ const ROOTS = [// purchase UI. A hit means a module on the App path imports billingLogic. Read billing values// from a logic or component that only logged-in pages load.'src/scenes/billing/billingLogic.tsx',+ // Product setup statuses need a logged-in team, so AuthenticatedShell mounts the preload.+ 'src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts',],},{diff --git a/frontend/src/lib/components/ProductEmptyState/README.md b/frontend/src/lib/components/ProductEmptyState/README.mdindex f780e037e374..face0a5e7ff2 100644--- a/frontend/src/lib/components/ProductEmptyState/README.md+++ b/frontend/src/lib/components/ProductEmptyState/README.md@@ -8,7 +8,7 @@ Scenes opt in declaratively: set `emptyState` on the scene's `SceneExport` and tMost detection logics are one call to `createSetupDetectionLogic` (`setupDetectionLogic.ts`): the product supplies a `detect` function resolving its status, and the factory owns the shared contract — detect on mount, optionally poll until data lands (stopping for good on `has-data`), and fail open on errors so a broken query never strands the gate on its spinner. With `cacheHasData`, a has-data answer is remembered per team and product, so a returning user's scene opens without waiting for the probe; `revalidateCachedHasData` adds one background check for products whose data can go away. A no-data answer clears the cache so the next visit shows the empty state, and never replaces the mounted scene. Products whose detection drives more than the gate (extra selectors, staged dashboards like MCP analytics) keep a bespoke logic that pushes into `productSetupStatusLogic` directly.-Products detectable from event definitions also declare a `setupProbe` in their manifest, which `productSetupPreloadLogic` answers at app boot with one batched request — so the status is usually known before the scene is ever opened. Probes support a `staleAfterDays` window for products where old, abandoned data shouldn't count as set up.+Products detectable from event definitions also declare a `setupProbe` in their manifest, which `productSetupPreloadLogic` answers after login with one batched request — so the status is usually known before the scene is ever opened. Probes support a `staleAfterDays` window for products where old, abandoned data shouldn't count as set up.To review an empty state on a project that already has data, add `?empty_state=1` to the scene URL. It forces the `needs-setup` screen past detection and past a local skip, `?empty_state=waiting-for-data` forces the other mode, and dropping the param gives the real scene back. Use it for design review and screenshots instead of clearing a project.diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.test.ts b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.test.tsnew file mode 100644index 000000000000..aa6bbe2faf7a--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.test.ts@@ -0,0 +1,41 @@+import { initKeaTests } from '~/test/init'++import { eventDefinitionsList } from 'products/event_definitions/frontend/generated/api'++import { productSetupPreloadLogic } from './productSetupPreloadLogic'++jest.mock('products/event_definitions/frontend/generated/api', () => ({+ eventDefinitionsList: jest.fn().mockResolvedValue({ results: [] }),+}))++describe('productSetupPreloadLogic', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ jest.useFakeTimers()+ initKeaTests()+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ // The authenticated shell mounts after the team has loaded, so no team listener fires. Waiting+ // for idle there lets a gated scene open on its own spinner before the preload answers.+ it('preloads at mount when the team is already known, without waiting for idle', () => {+ productSetupPreloadLogic.mount()++ expect(eventDefinitionsList).toHaveBeenCalledTimes(1)+ })++ it.each([+ ['is still running', (): Promise<never> => new Promise(() => {}), 1],+ ['failed', (): Promise<never> => Promise.reject(new Error('offline')), 2],+ ])('sends the idle retry only if the mount request failed, not when it %s', async (_, response, calls) => {+ jest.mocked(eventDefinitionsList).mockImplementationOnce(response)++ productSetupPreloadLogic.mount()+ await jest.runOnlyPendingTimersAsync()++ expect(eventDefinitionsList).toHaveBeenCalledTimes(calls)+ })+})diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.tsindex 9f75ad1fce01..3d6ed61de9bb 100644--- a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts+++ b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts@@ -75,6 +75,7 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([]let existingDefinitions: ProbeEventDefinition[]+ cache.requestsInFlight = (cache.requestsInFlight ?? 0) + 1try {const response = await api.eventDefinitionsList(String(teamId), {names: eventNames,@@ -88,6 +89,8 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([// Nothing was marked seeded, so the next trigger retries; until then the// in-scene detection logic answers on its own.return+ } finally {+ cache.requestsInFlight -= 1}breakpoint()if (values.currentTeamId !== teamId) {@@ -113,9 +116,16 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([},})),afterMount(({ actions, cache }) => {+ // The authenticated shell mounts after the team has loaded, so the team listener has already fired.+ actions.preloadStatuses()// Defer to idle so boot-critical work (scene chunk, first queries) wins.cache.disposables.add(() => {- const run = (): void => actions.preloadStatuses()+ // A retry for a failed mount run. A second request while one is running would cancel it.+ const run = (): void => {+ if (!cache.requestsInFlight) {+ actions.preloadStatuses()+ }+ }if (typeof window.requestIdleCallback === 'function') {const id = window.requestIdleCallback(run, { timeout: 5000 })return () => window.cancelIdleCallback(id)diff --git a/frontend/src/lib/components/ProductEmptyState/setupProbes.ts b/frontend/src/lib/components/ProductEmptyState/setupProbes.tsindex e2336c326382..225b751ef6d9 100644--- a/frontend/src/lib/components/ProductEmptyState/setupProbes.ts+++ b/frontend/src/lib/components/ProductEmptyState/setupProbes.ts@@ -6,8 +6,8 @@ import { ProductKey } from '~/queries/schema/schema-general'import type { ProductSetupStatus } from './types'/**- * A cheap, declarative approximation of a product's setup status, resolvable at- * app boot from event definitions. A product declares its probe as `setupProbe`+ * A cheap, declarative approximation of a product's setup status, resolvable+ * after login from event definitions. A product declares its probe as `setupProbe`* in its manifest; `build-products.mjs` aggregates them into `productSetupProbes`* (see `~/products`), and each one is answered by a Postgres-backed API call* (see `productSetupPreloadLogic`), so statuses are known before thediff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsxindex 3d909674993d..792c3650f295 100644--- a/frontend/src/scenes/App.tsx+++ b/frontend/src/scenes/App.tsx@@ -6,7 +6,6 @@ import { Slide, ToastContainer } from 'react-toastify'import { PostHogProvider } from '@posthog/react'-import { productSetupPreloadLogic } from 'lib/components/ProductEmptyState/productSetupPreloadLogic'import { MOCK_NODE_PROCESS } from 'lib/constants'import { useCancelAnimationsOnUnmount } from 'lib/hooks/useCancelAnimationsOnUnmount'import { useThemedHtml } from 'lib/hooks/useThemedHtml'@@ -81,9 +80,6 @@ export function App(): JSX.Element | null {useMountedLogic(sceneLogic({ scenes: appScenes }))useMountedLogic(autofillReleaseLogic)- // Resolves product setup statuses on idle, so gated scenes open without a spinner.- useMountedLogic(productSetupPreloadLogic)-// Unconditional so /oauth/callback's urlToAction is registered before routing. Inert in prod// (OAuth UI gated on preflight.is_debug); no timers/listeners, so cheap to always mount.useMountedLogic(oauthLogic)diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxindex 942a2f75f5ca..69f3eba85abc 100644--- a/frontend/src/scenes/AuthenticatedShell.tsx+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -3,6 +3,7 @@ import { Suspense } from 'react'import { Slide, ToastContainer } from 'react-toastify'import { Command } from 'lib/components/Command/Command'+import { productSetupPreloadLogic } from 'lib/components/ProductEmptyState/productSetupPreloadLogic'import { globalSetupLogic, useSetupHighlight } from 'lib/components/ProductSetup'import { FEATURE_FLAGS } from 'lib/constants'import { ToastCloseButton } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -47,6 +48,8 @@ export default function AuthenticatedShell({ children }: { children: React.ReactuseMountedLogic(globalSetupLogic)useMountedLogic(webmcpLogic)useMountedLogic(billingLogic)+ // Resolves product setup statuses on idle, so gated scenes open without a spinner.+ useMountedLogic(productSetupPreloadLogic)useSetupHighlight()const { sceneConfig } = useValues(sceneLogic)diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 0c3b4f0e7f55..e52b5cb338f3 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7954,9 +7954,9 @@ export interface ProductManifest {treeItemsGames?: FileSystemImport[]treeItemsMetadata?: FileSystemImport[]/**- * Boot-time setup-status probe for this product's empty state. Aggregated across+ * Setup-status probe for this product's empty state. Aggregated across* manifests into `productSetupProbes` and answered by one property-definition- * request at app boot (see `productSetupPreloadLogic`).+ * request after login (see `productSetupPreloadLogic`).*/setupProbe?: ProductSetupProbe}