: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
fix(frontend): mark scene_rendered when lazy scene content commits (#120096)
Paul D'Ambra80a25847c125
diff --git a/frontend/src/lib/utils/bootTiming.test.ts b/frontend/src/lib/utils/bootTiming.test.tsindex 1e423fff4019..eae4d1fc2e4f 100644--- a/frontend/src/lib/utils/bootTiming.test.ts+++ b/frontend/src/lib/utils/bootTiming.test.ts@@ -1,6 +1,9 @@import type posthogType from 'posthog-js'-import type { markBootPhase as markBootPhaseType } from './bootTiming'+import type {+ createSceneRenderedMark as createSceneRenderedMarkType,+ markBootPhase as markBootPhaseType,+} from './bootTiming'describe('bootTiming', () => {// Hash buckets 0 and 26 of 100, so one sits inside the 5% sample and one sits outside it.@@ -8,6 +11,7 @@ describe('bootTiming', () => {const OUT_OF_SAMPLE_ID = 'user-0'let markBootPhase: typeof markBootPhaseType+ let createSceneRenderedMark: typeof createSceneRenderedMarkTypelet capture: jest.SpyInstancelet getDistinctId: jest.SpyInstancelet now: number@@ -18,7 +22,7 @@ describe('bootTiming', () => {jest.resetModules()now = 0nowSpy = jest.spyOn(performance, 'now').mockImplementation(() => now)- markBootPhase = require('./bootTiming').markBootPhase+ ;({ markBootPhase, createSceneRenderedMark } = require('./bootTiming'))const posthog: typeof posthogType = require('posthog-js').defaultcapture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)getDistinctId = jest.spyOn(posthog, 'get_distinct_id').mockReturnValue(IN_SAMPLE_ID)@@ -65,6 +69,74 @@ describe('bootTiming', () => {)})+ it.each([+ { name: 'marks when the scene commits', fallbackGoneAt: [], expected: 900 },+ { name: 'waits for a lazy content fallback to go', fallbackGoneAt: [1150], expected: 1150 },+ { name: 'waits for the last of two fallbacks', fallbackGoneAt: [1100, 1300], expected: 1300 },+ ])(+ 'scene rendered mark $name',+ async ({ fallbackGoneAt, expected }: { fallbackGoneAt: number[]; expected: number }) => {+ markAt(50, 'entry')+ const sceneRendered = createSceneRenderedMark()+ // A child's layout effect runs before its parent's, so a fallback holds the mark before the scene commits.+ const releases = fallbackGoneAt.map(() => sceneRendered.holdUntilContent())+ now = 900+ sceneRendered.sceneCommitted()+ fallbackGoneAt.forEach((time, index) => {+ now = time+ releases[index]()+ })+ await flushSend()++ expect(capture).toHaveBeenCalledTimes(1)+ expect(capture).toHaveBeenCalledWith(+ 'app boot timing',+ expect.objectContaining({ scene_rendered_ms: expected })+ )+ }+ )++ it('does not mark a scene that unmounts before lazy content appears', async () => {+ markAt(50, 'entry')+ const sceneRendered = createSceneRenderedMark()+ const release = sceneRendered.holdUntilContent()+ sceneRendered.sceneCommitted()+ release()+ sceneRendered.sceneUncommitted()+ await flushSend()++ expect(capture).not.toHaveBeenCalled()+ })++ it('marks after the lazy content commit completes', async () => {+ markAt(50, 'entry')+ const sceneRendered = createSceneRenderedMark()+ const release = sceneRendered.holdUntilContent()+ sceneRendered.sceneCommitted()+ now = 1100+ release()+ now = 1110+ await flushSend()++ expect(capture).toHaveBeenCalledWith('app boot timing', expect.objectContaining({ scene_rendered_ms: 1110 }))+ })++ it('waits if lazy content starts loading after the scene commit', async () => {+ markAt(50, 'entry')+ const sceneRendered = createSceneRenderedMark()+ sceneRendered.sceneCommitted()+ const release = sceneRendered.holdUntilContent()+ await Promise.resolve()++ expect(capture).not.toHaveBeenCalled()++ now = 1200+ release()+ await flushSend()++ expect(capture).toHaveBeenCalledWith('app boot timing', expect.objectContaining({ scene_rendered_ms: 1200 }))+ })+it.each([{ distinctId: IN_SAMPLE_ID, sends: true },{ distinctId: OUT_OF_SAMPLE_ID, sends: false },diff --git a/frontend/src/lib/utils/bootTiming.ts b/frontend/src/lib/utils/bootTiming.tsindex 79870900e1ce..48da2fb3f9d2 100644--- a/frontend/src/lib/utils/bootTiming.ts+++ b/frontend/src/lib/utils/bootTiming.ts@@ -95,3 +95,48 @@ export function markBootPhase(phase: BootPhase, phaseContext?: BootContext): voivoid sendBootTiming().catch(() => {})}}++export interface SceneRenderedMark {+ /** Holds the mark while a Suspense fallback stands in for the scene's lazy content. Returns the release. */+ holdUntilContent: () => () => void+ sceneCommitted: () => void+ sceneUncommitted: () => void+}++/**+ * Marks `scene_rendered` when the scene has committed and no fallback for its lazy content is on screen.+ * Without this, a scene that wraps its content in its own Suspense marks the commit of its spinner.+ */+export function createSceneRenderedMark(): SceneRenderedMark {+ let committed = false+ let holds = 0+ const markIfReady = (): void => {+ if (committed && holds === 0) {+ queueMicrotask(() => {+ if (committed && holds === 0) {+ markBootPhase('scene_rendered')+ }+ })+ }+ }+ return {+ holdUntilContent: () => {+ holds+++ let released = false+ return () => {+ if (!released) {+ released = true+ holds--+ markIfReady()+ }+ }+ },+ sceneCommitted: () => {+ committed = true+ markIfReady()+ },+ sceneUncommitted: () => {+ committed = false+ },+ }+}diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsxindex ba62fce32cdf..1bb3a52c38f1 100644--- a/frontend/src/scenes/App.tsx+++ b/frontend/src/scenes/App.tsx@@ -1,7 +1,7 @@import { Tooltip as BaseTooltip } from '@base-ui/react/tooltip'import { BindLogic, useMountedLogic, useValues } from 'kea'import posthog from 'posthog-js'-import React, { Suspense, useEffect, useLayoutEffect } from 'react'+import React, { Suspense, useEffect, useLayoutEffect, useState } from 'react'import { Slide, ToastContainer } from 'react-toastify'import { PostHogProvider } from '@posthog/react'@@ -14,7 +14,7 @@ import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'import { autofillReleaseLogic } from 'lib/memory/autofillReleaseLogic'import { OAuthCallback } from 'lib/oauth/OAuthCallback'import { oauthLogic } from 'lib/oauth/oauthLogic'-import { markBootPhase } from 'lib/utils/bootTiming'+import { createSceneRenderedMark, markBootPhase } from 'lib/utils/bootTiming'import { lazyWithRetry, retryImport } from 'lib/utils/retryImport'import { appLogic } from 'scenes/appLogic'import { appScenes } from 'scenes/appScenes'@@ -28,6 +28,7 @@ import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { AuthenticatedShellFallback } from './AuthenticatedShellFallback'import { ChunkLoadErrorBoundary } from './ChunkLoadErrorBoundary'import { mountSupportRouter } from './mountSupportRouter'+import { SceneRenderedMarkContext } from './SceneContentFallback'const AuthenticatedShell = React.lazy(() => retryImport(() => import('./AuthenticatedShell')))@@ -54,10 +55,14 @@ window.process = MOCK_NODE_PROCESS*/function SceneAnimationRoot({ children }: { children: React.ReactNode }): JSX.Element {const ref = useCancelAnimationsOnUnmount<HTMLDivElement>()+ const [sceneRendered] = useState(createSceneRenderedMark)// For a logged-in user this sits inside the AuthenticatedShell Suspense boundary, so it runs when the scene// commits, not when the shell fallback does. A scene behind ProductEmptyStateGate can still commit the- // gate's fallback first.- useLayoutEffect(() => markBootPhase('scene_rendered'), [])+ // gate's fallback first. A scene whose own Suspense shows a SceneContentFallback marks when its content commits.+ useLayoutEffect(() => {+ sceneRendered.sceneCommitted()+ return () => sceneRendered.sceneUncommitted()+ }, [sceneRendered])return (// `className="contents"` is load-bearing: the wrapper must take a DOM// node so the ref has something to attach to (we need an element to@@ -65,7 +70,7 @@ function SceneAnimationRoot({ children }: { children: React.ReactNode }): JSX.El// transparent to layout. `display: contents` removes it from the box// tree so children render as if there's no wrapper.<div ref={ref} className="contents">- {children}+ <SceneRenderedMarkContext.Provider value={sceneRendered}>{children}</SceneRenderedMarkContext.Provider></div>)}diff --git a/frontend/src/scenes/SceneContentFallback.tsx b/frontend/src/scenes/SceneContentFallback.tsxnew file mode 100644index 000000000000..affc30e25063--- /dev/null+++ b/frontend/src/scenes/SceneContentFallback.tsx@@ -0,0 +1,16 @@+import { createContext, useContext, useLayoutEffect } from 'react'++import type { SceneRenderedMark } from 'lib/utils/bootTiming'++export const SceneRenderedMarkContext = createContext<SceneRenderedMark | null>(null)++/**+ * Use as the fallback of a scene's own Suspense boundary around its main lazy content, so the+ * `scene_rendered` boot mark waits for that content and not for the fallback.+ */+export function SceneContentFallback({ children }: { children: JSX.Element }): JSX.Element {+ const sceneRendered = useContext(SceneRenderedMarkContext)+ // The release runs as the cleanup, in the commit that replaces this fallback with the content.+ useLayoutEffect(() => sceneRendered?.holdUntilContent(), [sceneRendered])+ return children+}diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsxindex 8539ea5ea1b1..270b7a420aea 100644--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx@@ -39,6 +39,7 @@ import { Dashboard } from 'scenes/dashboard/Dashboard'import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'import { FeatureFlagPermissions } from 'scenes/FeatureFlagPermissions'import { NotebookNodeType } from 'scenes/notebooks/types'+import { SceneContentFallback } from 'scenes/SceneContentFallback'import { SceneExport } from 'scenes/sceneTypes'import { SURVEY_CREATED_SOURCE } from 'scenes/surveys/constants'import { QuickSurveyType } from 'scenes/surveys/quick-create/types'@@ -321,7 +322,13 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {}return (<ChunkLoadErrorBoundary>- <Suspense fallback={<FeatureFlagFormSkeleton />}>+ <Suspense+ fallback={+ <SceneContentFallback>+ <FeatureFlagFormSkeleton />+ </SceneContentFallback>+ }+ ><FeatureFlagForm id={id} /></Suspense></ChunkLoadErrorBoundary>diff --git a/frontend/src/scenes/project-homepage/ProjectHomepage.tsx b/frontend/src/scenes/project-homepage/ProjectHomepage.tsxindex 397d3b22cb13..48876de8b7a6 100644--- a/frontend/src/scenes/project-homepage/ProjectHomepage.tsx+++ b/frontend/src/scenes/project-homepage/ProjectHomepage.tsx@@ -6,6 +6,7 @@ import { Suspense } from 'react'import { SpinnerOverlay } from 'lib/lemon-ui/Spinner'import { lazyWithRetry } from 'lib/utils/retryImport'import { projectHomepageLogic } from 'scenes/project-homepage/projectHomepageLogic'+import { SceneContentFallback } from 'scenes/SceneContentFallback'import { SceneExport } from 'scenes/sceneTypes'const AiFirstHomepage = lazyWithRetry(() =>@@ -22,7 +23,13 @@ export function ProjectHomepage(): JSX.Element {const { todayHomeEnabled } = useValues(projectHomepageLogic)return (<div className="flex-1 min-h-0">- <Suspense fallback={<SpinnerOverlay sceneLevel />}>+ <Suspense+ fallback={+ <SceneContentFallback>+ <SpinnerOverlay sceneLevel />+ </SceneContentFallback>+ }+ >{todayHomeEnabled ? <TodayHome /> : <AiFirstHomepage />}</Suspense></div>diff --git a/products/alerts/frontend/views/Alerts.tsx b/products/alerts/frontend/views/Alerts.tsxindex c0939bf75b5b..a516794abce1 100644--- a/products/alerts/frontend/views/Alerts.tsx+++ b/products/alerts/frontend/views/Alerts.tsx@@ -6,6 +6,7 @@ import { LemonSkeleton, LemonTabs } from '@posthog/lemon-ui'import { AccessDenied } from 'lib/components/AccessDenied'import { lazyWithRetry } from 'lib/utils/retryImport'+import { SceneContentFallback } from 'scenes/SceneContentFallback'import { urls } from 'scenes/urls'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'@@ -84,7 +85,13 @@ export function Alerts({ alertId }: AlertsProps): JSX.Element {resourceType={{ type: 'inbox' }}/><LemonTabs<AlertsTab> activeKey={activeTab} onChange={switchTab} tabs={tabs} sceneInset />- <Suspense fallback={<AlertsPanelSkeleton />}>+ <Suspense+ fallback={+ <SceneContentFallback>+ <AlertsPanelSkeleton />+ </SceneContentFallback>+ }+ >{activeTab === AlertsTab.LOGS ? <LogsAlertingSection /> : <InsightAlerts alertId={alertId} />}</Suspense></>