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.

feat(toolbar): lazy-load feature menus and tour step HTML generation (#69113)

Rafael Audibert1d2e4940dc58
diff --git a/.agents/toolbar-migration.md b/.agents/toolbar-migration.md
index 37ce63f94bc4..4f63ad26ab66 100644
--- a/.agents/toolbar-migration.md
+++ b/.agents/toolbar-migration.md
@@ -111,11 +111,13 @@ Approach (revised on review): rather than restructuring the generated products m
- [x] `HeatmapEventsPanel` → `PersonDisplay`: replaced with a plain span (PersonDisplay renders exactly that for a distinct_id-only person with `noPopover`); `TZLabel` → teamLogic edge now shimmed at resolve time (`~/scenes/teamLogic` matching)
- [ ] `TZLabel` → urls; `eventUsageLogic` → preflight/web-analytics edges; move `KeyboardShortcut` out of `layout/navigation-3000` into `lib/`
-### Step 7 — lazy boundaries in toolbar source
+### Step 7 — lazy boundaries in toolbar source (in review: `rafa/toolbar-migration-6-lazy-menus`)
-- [ ] Convert the nine `visibleMenu` bodies in `frontend/src/toolbar/bar/Toolbar.tsx` + `SurveySidebar`/`ProductToursSidebar`/modals to `React.lazy(() => retryImport(() => import(...)))` with `Spinner` fallback. Largest first: actions/TaxonomicFilter, experiments, surveys, heatmaps, web-vitals, debugger (react-json-view), product tours
-- [ ] Audit eagerly-mounted per-tab logics (e.g. `webVitalsToolbarLogic.mount()` in `ToolbarApp.tsx`) — keep a slim eager core where background collection is deliberate
-- [ ] Ratchet the eager budget down
+- [x] The nine `visibleMenu` bodies + `ProductToursSidebar`/`SurveySidebar`/`FieldNotesOverlay` are `React.lazy(() => retryImport(() => import(...)))` behind `Suspense` (Spinner fallback in the menu container, null for sidebars). `eventDebugMenuLogic` (and its 225KB taxonomy JSON) is component-only so it defers with the debugger menu
+- [x] `productToursLogic` imports `generateStepHtml` (tiptap/prosemirror/highlight.js, ~500KB) dynamically via a memoized `retryImport` — only fetched when a tour is edited/previewed; the two draft-compare subscriptions became async (module-cache awaits preserve call order after first load)
+- [x] Eager budget ratcheted 3.05 MB → 2.1 MB (measured 1,905,558 — eager JS down 31%, deferred now 1.93 MB ≈ 50% of app JS)
+- [x] New guard in `check-toolbar-size.mjs`: every CSS input in any chunk stylesheet must also be in the entry stylesheet (the only one the shadow root loads) — fails the build if a lazy feature's styles would silently never render. Watch out: with splitting, every dynamic-import target carries `entryPoint` in the metafile; use `findEntryOutput`
+- [ ] Audit eagerly-mounted per-tab logics (e.g. `webVitalsToolbarLogic.mount()` in `ToolbarApp.tsx`, `actionsLogic` via toolbarLogic dragging fuse.js) — keep a slim eager core where background collection is deliberate
### Step 8 — tree-shaking enablers + cleanup (highest breakage risk; last)
diff --git a/frontend/bin/check-toolbar-size.mjs b/frontend/bin/check-toolbar-size.mjs
index e4f964982b42..8db96d68ce10 100644
--- a/frontend/bin/check-toolbar-size.mjs
+++ b/frontend/bin/check-toolbar-size.mjs
@@ -1,7 +1,7 @@
import fs from 'fs'
import path from 'path'
-import { eagerOutputs, jsOutputs, readToolbarMetafile } from './toolbar-metafile.mjs'
+import { eagerOutputs, findEntryOutput, jsOutputs, readToolbarMetafile } from './toolbar-metafile.mjs'
// Size guards for the split toolbar build (dist/toolbar.js loader + dist/toolbar/ ESM app).
//
@@ -17,8 +17,8 @@ const MAX_FILE_BYTES = 10_000_000
// toolbar load fetches before any feature runs. Ratchet policy: when a cut lands, lower the
// budget to lock it in; raise it only as a conscious, reviewed decision in the PR that needs it.
// 2026-07-07: 2,967,721 bytes measured when splitting landed; 2,764,847 after the
-// replay-shared cut; ~10% headroom.
-const MAX_EAGER_BYTES = 3_050_000
+// replay-shared cut; 1,905,558 after the lazy menu boundaries; ~10% headroom.
+const MAX_EAGER_BYTES = 2_100_000
// 3. The loader is injected on every customer page that enables the toolbar and must stay tiny.
// 2026-07-07: 1,153 bytes minified.
@@ -69,6 +69,29 @@ function main() {
}
}
+ // CSS completeness: only the entry stylesheet is loaded into the toolbar's shadow root, so
+ // styles reachable solely through a lazy chunk would silently never render. Every CSS input
+ // that lands in any chunk stylesheet must also land in the entry stylesheet — if this fails,
+ // make the owning feature import its styles statically (or hoist the style import).
+ // Note: with code splitting, every dynamically-imported module also carries an entryPoint
+ // in the metafile — findEntryOutput matches the real toolbar entry specifically.
+ const entryCss = outputs[findEntryOutput(outputs)]?.cssBundle
+ if (entryCss) {
+ const entryCssInputs = new Set(Object.keys(outputs[entryCss].inputs || {}))
+ for (const [file, output] of Object.entries(outputs)) {
+ if (!file.endsWith('.css') || file.endsWith('.map') || file === entryCss) {
+ continue
+ }
+ const missing = Object.keys(output.inputs || {}).filter((inp) => !entryCssInputs.has(inp))
+ if (missing.length) {
+ fail(
+ `${file} contains styles missing from the entry stylesheet (${missing.join(', ')}) — ` +
+ 'they would never load into the shadow root. Import them statically.'
+ )
+ }
+ }
+ }
+
// Eager-set budget.
const eagerJs = [...eagerOutputs(outputs)].filter((o) => o.endsWith('.js'))
const eagerBytes = eagerJs.reduce((sum, o) => sum + outputs[o].bytes, 0)
diff --git a/frontend/src/toolbar/bar/Toolbar.tsx b/frontend/src/toolbar/bar/Toolbar.tsx
index 4454db1f596b..f125fd082d02 100644
--- a/frontend/src/toolbar/bar/Toolbar.tsx
+++ b/frontend/src/toolbar/bar/Toolbar.tsx
@@ -3,7 +3,7 @@ import './Toolbar.scss'
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { PostHog } from 'posthog-js'
-import { useEffect, useRef, useState } from 'react'
+import { Suspense, lazy, useEffect, useRef, useState } from 'react'
import {
IconApp,
@@ -35,34 +35,80 @@ import { IconFlare, IconMenu } from 'lib/lemon-ui/icons'
import { LemonMenu, LemonMenuItem, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
import { Link } from 'lib/lemon-ui/Link'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
+import { retryImport } from 'lib/utils/retryImport'
-import { ActionsToolbarMenu } from '~/toolbar/actions/ActionsToolbarMenu'
import { AnimatedLogomark } from '~/toolbar/bar/AnimatedLogomark'
import { AuthConfirmModal } from '~/toolbar/bar/AuthConfirmModal'
import { PII_MASKING_PRESET_COLORS } from '~/toolbar/bar/piiMaskingStyles'
import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'
import { UiHostConfigModal } from '~/toolbar/bar/UiHostConfigModal'
-import { EventDebugMenu } from '~/toolbar/debug/EventDebugMenu'
-import { ExperimentsToolbarMenu } from '~/toolbar/experiments/ExperimentsToolbarMenu'
import { fieldNotesLogic } from '~/toolbar/field-notes/fieldNotesLogic'
-import { FieldNotesOverlay } from '~/toolbar/field-notes/FieldNotesOverlay'
-import { FieldNotesToolbarMenu } from '~/toolbar/field-notes/FieldNotesToolbarMenu'
-import { FlagsToolbarMenu } from '~/toolbar/flags/FlagsToolbarMenu'
import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'
-import { ProductToursSidebar } from '~/toolbar/product-tours/ProductToursSidebar'
-import { ProductToursToolbarMenu } from '~/toolbar/product-tours/ProductToursToolbarMenu'
import { screenshotUploadLogic } from '~/toolbar/screenshot-upload/screenshotUploadLogic'
import { ScreenshotUploadModal } from '~/toolbar/screenshot-upload/ScreenshotUploadModal'
-import { HeatmapToolbarMenu } from '~/toolbar/stats/HeatmapToolbarMenu'
-import { SurveySidebar } from '~/toolbar/surveys/SurveySidebar'
import { surveysToolbarLogic } from '~/toolbar/surveys/surveysToolbarLogic'
-import { SurveysToolbarMenu } from '~/toolbar/surveys/SurveysToolbarMenu'
import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'
-import { WebVitalsToolbarMenu } from '~/toolbar/web-vitals/WebVitalsToolbarMenu'
import { ToolbarButton } from './ToolbarButton'
+// Each feature menu is a lazy split point: its component graph (and per-tab logics only it
+// mounts, like the event debugger's 200KB+ taxonomy) is fetched when the tab first opens, not
+// on toolbar boot. Styles are unaffected — the shadow root loads the entry stylesheet, and
+// bin/check-toolbar-size.mjs fails the build if a lazy chunk holds CSS the entry doesn't.
+const ActionsToolbarMenu = lazy(() =>
+ retryImport(() => import('~/toolbar/actions/ActionsToolbarMenu')).then((m) => ({
+ default: m.ActionsToolbarMenu,
+ }))
+)
+const EventDebugMenu = lazy(() =>
+ retryImport(() => import('~/toolbar/debug/EventDebugMenu')).then((m) => ({ default: m.EventDebugMenu }))
+)
+const ExperimentsToolbarMenu = lazy(() =>
+ retryImport(() => import('~/toolbar/experiments/ExperimentsToolbarMenu')).then((m) => ({
+ default: m.ExperimentsToolbarMenu,
+ }))
+)
+const FieldNotesOverlay = lazy(() =>
+ retryImport(() => import('~/toolbar/field-notes/FieldNotesOverlay')).then((m) => ({
+ default: m.FieldNotesOverlay,
+ }))
+)
+const FieldNotesToolbarMenu = lazy(() =>
+ retryImport(() => import('~/toolbar/field-notes/FieldNotesToolbarMenu')).then((m) => ({
+ default: m.FieldNotesToolbarMenu,
+ }))
+)
+const FlagsToolbarMenu = lazy(() =>
+ retryImport(() => import('~/toolbar/flags/FlagsToolbarMenu')).then((m) => ({ default: m.FlagsToolbarMenu }))
+)
+const ProductToursSidebar = lazy(() =>
+ retryImport(() => import('~/toolbar/product-tours/ProductToursSidebar')).then((m) => ({
+ default: m.ProductToursSidebar,
+ }))
+)
+const ProductToursToolbarMenu = lazy(() =>
+ retryImport(() => import('~/toolbar/product-tours/ProductToursToolbarMenu')).then((m) => ({
+ default: m.ProductToursToolbarMenu,
+ }))
+)
+const HeatmapToolbarMenu = lazy(() =>
+ retryImport(() => import('~/toolbar/stats/HeatmapToolbarMenu')).then((m) => ({ default: m.HeatmapToolbarMenu }))
+)
+const SurveySidebar = lazy(() =>
+ retryImport(() => import('~/toolbar/surveys/SurveySidebar')).then((m) => ({ default: m.SurveySidebar }))
+)
+const SurveysToolbarMenu = lazy(() =>
+ retryImport(() => import('~/toolbar/surveys/SurveysToolbarMenu')).then((m) => ({
+ default: m.SurveysToolbarMenu,
+ }))
+)
+const WebVitalsToolbarMenu = lazy(() =>
+ retryImport(() => import('~/toolbar/web-vitals/WebVitalsToolbarMenu')).then((m) => ({
+ default: m.WebVitalsToolbarMenu,
+ }))
+)
+
const HELP_URL = 'https://posthog.com/docs/toolbar?utm_medium=in-product&utm_campaign=toolbar-help-button'
function EnabledStatusItem({ label, value }: { label: string; value: boolean }): JSX.Element {
@@ -383,7 +429,15 @@ export function ToolbarInfoMenu(): JSX.Element | null {
maxHeight: menuProperties.maxHeight,
}}
>
- {content}
+ <Suspense
+ fallback={
+ <div className="flex items-center justify-center p-4">
+ <Spinner />
+ </div>
+ }
+ >
+ {content}
+ </Suspense>
</div>
</div>
)
@@ -450,9 +504,11 @@ export function Toolbar(): JSX.Element | null {
return (
<>
- {showToursSidebar && <ProductToursSidebar />}
- {showFieldNotes && <FieldNotesOverlay />}
- {isSurveyCreating && <SurveySidebar />}
+ <Suspense fallback={null}>
+ {showToursSidebar && <ProductToursSidebar />}
+ {showFieldNotes && <FieldNotesOverlay />}
+ {isSurveyCreating && <SurveySidebar />}
+ </Suspense>
<ToolbarInfoMenu />
<div
ref={ref}
diff --git a/frontend/src/toolbar/product-tours/productToursLogic.ts b/frontend/src/toolbar/product-tours/productToursLogic.ts
index c3e2bd89f472..625d6e66f029 100644
--- a/frontend/src/toolbar/product-tours/productToursLogic.ts
+++ b/frontend/src/toolbar/product-tours/productToursLogic.ts
@@ -7,9 +7,9 @@ import { findElement } from 'posthog-js/dist/element-inference'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { uuid } from 'lib/utils/dom'
+import { retryImport } from 'lib/utils/retryImport'
import { ProductTourEvent } from 'scenes/product-tours/constants'
import { DEFAULT_APPEARANCE } from 'scenes/product-tours/constants'
-import { prepareStepForRender, prepareStepsForRender } from 'scenes/product-tours/editor/generateStepHtml'
import {
createDefaultStep,
getDefaultStepContent,
@@ -124,7 +124,14 @@ export function getStepElement(step: TourStep): HTMLElement | null {
return findElement(step.inferenceData)
}
-function buildDraftPayload(form: TourForm, tours: ProductTour[]): Record<string, unknown> {
+// Step HTML generation drags tiptap/prosemirror/highlight.js (~500KB minified) — only needed
+// when a tour is edited or previewed, so load it on demand. Repeat awaits resolve from the
+// module cache in call order, so the draft-compare subscriptions below stay ordered.
+const importStepHtml = (): Promise<typeof import('scenes/product-tours/editor/generateStepHtml')> =>
+ retryImport(() => import('scenes/product-tours/editor/generateStepHtml'))
+
+async function buildDraftPayload(form: TourForm, tours: ProductTour[]): Promise<Record<string, unknown>> {
+ const { prepareStepForRender } = await importStepHtml()
const stepsForApi = form.steps.map(({ element: _, ...step }) => prepareStepForRender(step))
const existingTour = form.id ? tours.find((t) => t.id === form.id) : null
const stepOrderHistory = getUpdatedStepOrderHistory(stepsForApi, existingTour?.content?.step_order_history)
@@ -343,7 +350,7 @@ export const productToursLogic = kea<productToursLogicType>([
// draft-save status). toolbarApi already logged it, so don't double-report.
const result = await toolbarApi.productTours.updateDraft(
formValues.id,
- buildDraftPayload(formValues, values.tours),
+ await buildDraftPayload(formValues, values.tours),
{ context: 'save_product_tour_draft', captureOnError: false }
)
if (!result.ok) {
@@ -417,12 +424,12 @@ export const productToursLogic = kea<productToursLogicType>([
}),
subscriptions(({ actions, values, cache }) => ({
- selectedTour: (selectedTour: TourForm | null) => {
+ selectedTour: async (selectedTour: TourForm | null) => {
if (!selectedTour) {
actions.resetTourForm()
cache.lastDraftPayload = null
} else {
- const incomingPayload = buildDraftPayload(selectedTour, values.tours)
+ const incomingPayload = await buildDraftPayload(selectedTour, values.tours)
if (!equal(incomingPayload, cache.lastDraftPayload)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(actions.setTourFormValues as any)(selectedTour)
@@ -430,11 +437,11 @@ export const productToursLogic = kea<productToursLogicType>([
}
}
},
- tourForm: (tourForm: TourForm) => {
+ tourForm: async (tourForm: TourForm) => {
if (!values.selectedTourId || values.selectedTourId === 'new') {
return
}
- const payload = buildDraftPayload(tourForm, values.tours)
+ const payload = await buildDraftPayload(tourForm, values.tours)
if (equal(cache.lastDraftPayload, payload)) {
return
}
@@ -604,7 +611,7 @@ export const productToursLogic = kea<productToursLogicType>([
return
}
const isUpdate = !!tourForm.id
- const payload = { ...buildDraftPayload(tourForm, tours), creation_context: 'toolbar' }
+ const payload = { ...(await buildDraftPayload(tourForm, tours)), creation_context: 'toolbar' }
const result = tourForm.id
? await toolbarApi.productTours.updateDraft(tourForm.id, payload, {
context: 'save_product_tour',
@@ -639,7 +646,7 @@ export const productToursLogic = kea<productToursLogicType>([
}
actions.submitTourForm()
},
- previewTour: () => {
+ previewTour: async () => {
const { tourForm, posthog, selectedTourId, tours } = values
if (posthog?.version && !hasMinProductToursVersion(posthog.version)) {
lemonToast.error(`Requires posthog-js ${PRODUCT_TOURS_MIN_JS_VERSION}+`)
@@ -689,7 +696,7 @@ export const productToursLogic = kea<productToursLogicType>([
type: 'product_tour' as const,
start_date: null,
end_date: null,
- steps: prepareStepsForRender(tourForm.steps),
+ steps: (await importStepHtml()).prepareStepsForRender(tourForm.steps),
appearance: existingTour?.content?.appearance,
}