: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(health): load the help menu health summary when the browser is idle (#117800)
Paul D'Ambraa6353beb4237
diff --git a/frontend/src/lib/components/HelpMenu/HelpMenu.stories.tsx b/frontend/src/lib/components/HelpMenu/HelpMenu.stories.tsxindex a6fbc80167f3..e51f25bd7308 100644--- a/frontend/src/lib/components/HelpMenu/HelpMenu.stories.tsx+++ b/frontend/src/lib/components/HelpMenu/HelpMenu.stories.tsx@@ -5,6 +5,7 @@ import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { mswDecorator } from '~/mocks/browser'+import { healthSummaryLogic } from './healthSummaryLogic'import { HelpMenu } from './HelpMenu'import { helpMenuLogic } from './helpMenuLogic'@@ -35,7 +36,13 @@ const meta: Meta<typeof HelpMenu> = {component: HelpMenu,render: () => {const { setHelpMenuOpen } = useActions(helpMenuLogic)- useOnMountEffect(() => setHelpMenuOpen(true))+ const { loadHealthSummary } = useActions(healthSummaryLogic)+ useOnMountEffect(() => {+ setHelpMenuOpen(true)+ // The app waits for the browser to go idle before it loads the summary. Load it now so+ // the snapshot does not depend on when that happens.+ loadHealthSummary()+ })return (<div className="flex h-[1400px] w-[600px]">diff --git a/frontend/src/lib/components/HelpMenu/HelpMenu.tsx b/frontend/src/lib/components/HelpMenu/HelpMenu.tsxindex bdbeb2784754..143d978256f0 100644--- a/frontend/src/lib/components/HelpMenu/HelpMenu.tsx+++ b/frontend/src/lib/components/HelpMenu/HelpMenu.tsx@@ -49,7 +49,7 @@ export function HelpMenu({ iconOnly = false }: { iconOnly?: boolean }): JSX.Elemconst { billing } = useValues(billingLogic)const { postHogStatusTooltip, postHogStatusBadgeStatus, postHogStatusBadgeContent, statusPageUrl } =useValues(posthogStatusLogic)- const { unsnoozedCount, snoozedCount } = useValues(healthSummaryLogic)+ const { healthSummary, unsnoozedCount, snoozedCount } = useValues(healthSummaryLogic)return (<Menu.Root open={isHelpMenuOpen} onOpenChange={setHelpMenuOpen}>@@ -183,17 +183,21 @@ export function HelpMenu({ iconOnly = false }: { iconOnly?: boolean }): JSX.Elem{...props}to={urls.health()}buttonProps={{ menuItem: true }}- tooltip={healthTooltip(unsnoozedCount, snoozedCount)}+ tooltip={+ healthSummary ? healthTooltip(unsnoozedCount, snoozedCount) : undefined+ }tooltipPlacement="right"tooltipCloseDelayMs={0}data-attr="more-menu-health-button">Health- <LemonBadge- size="small"- content={triggerBadgeContent}- status={triggerBadgeStatus}- />+ {healthSummary && (+ <LemonBadge+ size="small"+ content={triggerBadgeContent}+ status={triggerBadgeStatus}+ />+ )}</Link>)}/>diff --git a/frontend/src/lib/components/HelpMenu/healthSummaryLogic.test.ts b/frontend/src/lib/components/HelpMenu/healthSummaryLogic.test.tsnew file mode 100644index 000000000000..32ae770a5485--- /dev/null+++ b/frontend/src/lib/components/HelpMenu/healthSummaryLogic.test.ts@@ -0,0 +1,49 @@+import api from 'lib/api'++import { initKeaTests } from '~/test/init'++import { healthSummaryLogic } from './healthSummaryLogic'++describe('healthSummaryLogic', () => {+ let logic: ReturnType<typeof healthSummaryLogic.build>+ let getSpy: jest.SpyInstance++ beforeEach(() => {+ jest.useFakeTimers()+ initKeaTests()+ getSpy = jest.spyOn(api, 'get').mockResolvedValue({ unsnoozed: { total: 2 }, snoozed: { total: 0 } })+ logic = healthSummaryLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ jest.useRealTimers()+ jest.restoreAllMocks()+ })++ it('loads the summary after boot instead of on mount', async () => {+ expect(getSpy).not.toHaveBeenCalled()++ await jest.advanceTimersByTimeAsync(5000)++ expect(getSpy).toHaveBeenCalledTimes(1)+ expect(getSpy).toHaveBeenCalledWith(expect.stringContaining('/health_issues/summary/'))+ expect(logic.values.unsnoozedCount).toBe(2)+ })++ it('does not load the summary again when the tab is shown after the first load', async () => {+ const setDocumentHidden = (hidden: boolean): void => {+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })+ document.dispatchEvent(new Event('visibilitychange'))+ }+ await jest.advanceTimersByTimeAsync(5000)+ expect(getSpy).toHaveBeenCalledTimes(1)++ setDocumentHidden(true)+ setDocumentHidden(false)+ await jest.advanceTimersByTimeAsync(5000)++ expect(getSpy).toHaveBeenCalledTimes(1)+ })+})diff --git a/frontend/src/lib/components/HelpMenu/healthSummaryLogic.tsx b/frontend/src/lib/components/HelpMenu/healthSummaryLogic.tsxindex e6e4c2f7f75f..0f34303be6eb 100644--- a/frontend/src/lib/components/HelpMenu/healthSummaryLogic.tsx+++ b/frontend/src/lib/components/HelpMenu/healthSummaryLogic.tsx@@ -2,6 +2,7 @@ import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors } fimport { loaders } from 'kea-loaders'import api from 'lib/api'+import { runWhenIdle } from 'lib/utils/async'import type { HealthIssueSummary } from 'scenes/health/types'import { teamLogic } from 'scenes/teamLogic'@@ -100,7 +101,17 @@ export const healthSummaryLogic = kea<healthSummaryLogicType>([}, 'refreshTimeout')},})),- afterMount(({ actions }) => {- actions.loadHealthSummary()+ afterMount(({ actions, cache }) => {+ // Only the help menu reads this data, so wait for an idle browser and let the page's own requests go first.+ // Disposables re-run setup when the tab shows again, so drop this one once it fires.+ // The refresh timer handles every load after the first.+ cache.disposables.add(+ () =>+ runWhenIdle(() => {+ cache.disposables.dispose('idleLoad')+ actions.loadHealthSummary()+ }),+ 'idleLoad'+ )}),])diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.tsindex 3d6ed61de9bb..a0fbe655976a 100644--- a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts+++ b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts@@ -1,6 +1,7 @@import { MakeLogicType, actions, afterMount, connect, isBreakpoint, kea, listeners, path } from 'kea'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { runWhenIdle } from 'lib/utils/async'import { teamLogic } from 'scenes/teamLogic'import { productSetupProbes } from '~/products'@@ -126,12 +127,7 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([actions.preloadStatuses()}}- if (typeof window.requestIdleCallback === 'function') {- const id = window.requestIdleCallback(run, { timeout: 5000 })- return () => window.cancelIdleCallback(id)- }- const id = window.setTimeout(run, 1000)- return () => clearTimeout(id)+ return runWhenIdle(run)}, 'idle-preload')}),])diff --git a/frontend/src/lib/utils/async.ts b/frontend/src/lib/utils/async.tsindex 4cd49e36c532..0a89a8d6efcc 100644--- a/frontend/src/lib/utils/async.ts+++ b/frontend/src/lib/utils/async.ts@@ -212,6 +212,22 @@ export function yieldToMain(): Promise<void> {})}+const IDLE_FALLBACK_DELAY_MS = 1000++/**+ * Runs `callback` once the browser is idle, or after `timeoutMs` at the latest.+ * Where `requestIdleCallback` is missing, `timeoutMs` is ignored and `callback` runs after a short fixed delay.+ * Returns a cancel function.+ */+export function runWhenIdle(callback: () => void, timeoutMs: number = 5000): () => void {+ if (typeof window.requestIdleCallback === 'function') {+ const id = window.requestIdleCallback(callback, { timeout: timeoutMs })+ return () => window.cancelIdleCallback(id)+ }+ const id = window.setTimeout(callback, IDLE_FALLBACK_DELAY_MS)+ return () => clearTimeout(id)+}+export function createSliceYielder(budgetMs: number = 10): (beforeYield?: () => void) => Promise<boolean> {let sliceStart = performance.now()return async (beforeYield?: () => void): Promise<boolean> => {