: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(toolbar): don't remount on repeat ph_load_toolbar calls (#73332)
jake sciotto775ec0e89173
diff --git a/frontend/src/toolbar/index.test.ts b/frontend/src/toolbar/index.test.tsindex 3162b93d09c8..0f93c5db5c89 100644--- a/frontend/src/toolbar/index.test.ts+++ b/frontend/src/toolbar/index.test.ts@@ -204,6 +204,95 @@ describe('Toolbar flag loading', () => {expect(mockPostHog.featureFlags.overrideFeatureFlags).not.toHaveBeenCalled()})+ it('is idempotent — a repeat ph_load_toolbar keeps the live toolbar instead of remounting it', async () => {+ // On an SPA, posthog-js calls ph_load_toolbar again on client-side route changes.+ // Remounting resets the Kea context out from under the mounted React tree, so the toolbar+ // the user is interacting with disappears (and a duplicate shadow root is stacked). A+ // repeat call must leave the existing instance untouched.+ await import('./index')++ const mockPostHog = {+ featureFlags: { overrideFeatureFlags: jest.fn(), reloadFeatureFlags: jest.fn() },+ }+ const toolbarParams: ToolbarParams = {+ apiURL: 'http://localhost:8010',+ token: 'test-token',+ // no toolbarFlagsKey → skips the flags preload, straight to mount+ }++ await (window as any).ph_load_toolbar(toolbarParams, mockPostHog)+ const container = document.body.firstElementChild+ const childCountAfterFirstLoad = document.body.childElementCount+ expect(container).toBeTruthy()++ await (window as any).ph_load_toolbar(toolbarParams, mockPostHog)+ // Nothing added, same node still first: the second call was a no-op, not a fresh mount+ // (which would append another container) or a teardown + remount (which would swap it).+ expect(document.body.childElementCount).toBe(childCountAfterFirstLoad)+ expect(document.body.firstElementChild).toBe(container)+ })++ it('dedupes overlapping ph_load_toolbar calls onto a single mount', async () => {+ // posthog-js can fire ph_load_toolbar calls that overlap (e.g. two SPA route changes in+ // quick succession). The mounted-state flag is only set at the end of the async mount, so+ // without an in-flight guard the second call races past the mounted check and mounts a+ // second toolbar. Here the flags preload provides the async gap the race needs.+ await import('./index')++ const mockPostHog = {+ featureFlags: { overrideFeatureFlags: jest.fn(), reloadFeatureFlags: jest.fn() },+ }+ const toolbarParams: ToolbarParams = {+ apiURL: 'http://localhost:8010',+ token: 'test-token',+ toolbarFlagsKey: 'test-key-123',+ }+ // Resolve every fetch (flags preload + uiHost reachability check) so the mount completes.+ mockFetch.mockResolvedValue({ ok: true, json: async () => ({ featureFlags: {} }) })++ const childCountBeforeLoad = document.body.childElementCount++ // Fire the second call before awaiting the first, so it arrives mid-mount.+ const first = (window as any).ph_load_toolbar(toolbarParams, mockPostHog)+ const second = (window as any).ph_load_toolbar(toolbarParams, mockPostHog)+ await Promise.all([first, second])++ // Exactly one container was appended: the two calls shared a single mount.+ expect(document.body.childElementCount - childCountBeforeLoad).toBe(1)+ })++ it('remounts a fresh toolbar when the host page has detached the old container', async () => {+ // The mounted check also requires the container to still be attached, so a stale loaded+ // flag — the host page ripped our node out of the DOM — must not turn a repeat call into a+ // no-op, or the toolbar would be gone for good. The repeat call should tear the stale+ // instance down and mount a fresh, attached one.+ await import('./index')++ const mockPostHog = {+ featureFlags: { overrideFeatureFlags: jest.fn(), reloadFeatureFlags: jest.fn() },+ }+ const toolbarParams: ToolbarParams = {+ apiURL: 'http://localhost:8010',+ token: 'test-token',+ // no toolbarFlagsKey → skips the flags preload, straight to mount+ }++ await (window as any).ph_load_toolbar(toolbarParams, mockPostHog)+ const firstContainer = document.body.firstElementChild+ expect(firstContainer).toBeTruthy()++ // The host page removes our node (e.g. an SPA wiping document.body on a route change).+ firstContainer?.remove()+ expect(document.body.firstElementChild).toBeNull()++ await (window as any).ph_load_toolbar(toolbarParams, mockPostHog)+ // Recovered: a fresh container is mounted — not a no-op that leaves the toolbar gone, and+ // a new node rather than the stale detached one.+ const recovered = document.body.firstElementChild+ expect(recovered).toBeTruthy()+ expect(recovered).not.toBe(firstContainer)+ })+it('should still load toolbar even if flag fetching fails', async () => {// The failed flags fetch is reported through toolbarLogger's console.warn by designconst consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation()diff --git a/frontend/src/toolbar/index.tsx b/frontend/src/toolbar/index.tsxindex 9c50329ccbf3..674ee13e9643 100644--- a/frontend/src/toolbar/index.tsx+++ b/frontend/src/toolbar/index.tsx@@ -15,7 +15,7 @@ import { createRoot } from 'react-dom/client'import { disposablesPlugin } from '~/kea-disposables'import { ToolbarApp } from '~/toolbar/ToolbarApp'import { canonicalizeApiHost } from '~/toolbar/toolbarConfigLogic'-import { posthogToolbarController, setToolbarRefs } from '~/toolbar/toolbarController'+import { isToolbarMounted, posthogToolbarController, setToolbarRefs } from '~/toolbar/toolbarController'import { toolbarLogger } from '~/toolbar/toolbarLogger'import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'import { isToolbarRequestError } from '~/toolbar/toolbarRequestError'@@ -92,7 +92,38 @@ win['posthogToolbarController'] = posthogToolbarController// Re-exported for the loader script (loader.ts), which forwards its controller stub here.export { posthogToolbarController }+// Tracks an in-flight mount. The mounted-state flag isn't set until the very end of the async+// mount, so without this two overlapping ph_load_toolbar calls would both pass the guard below+// and mount twice. Concurrent calls dedupe onto this promise instead.+let loadPromise: Promise<void> | null = null+export async function loadToolbar(toolbarParams: ToolbarParams, posthog?: PostHog): Promise<void> {+ // ph_load_toolbar is not called once per page — posthog-js re-invokes it during a page's+ // lifetime, most notably on SPA client-side route changes. Mounting is destructive+ // (initKeaInToolbar() calls resetContext()), so a naive re-run tears the Kea logics out from+ // under the already-mounted React tree: the toolbar the user is interacting with vanishes and+ // a duplicate shadow root is appended. Keep a healthy live instance instead of remounting.+ if (isToolbarMounted()) {+ return+ }+ // A mount is already in flight. Calls can overlap before the first finishes its async setup+ // and records itself as mounted, so join the existing mount rather than starting a second.+ if (loadPromise) {+ return loadPromise+ }+ // Flagged as loaded but the container was detached (the host page removed our node): tear the+ // stale React root / Kea context down before mounting a fresh one so we don't leak or stack.+ if (posthogToolbarController.isLoaded) {+ posthogToolbarController.destroy()+ }++ loadPromise = mountToolbar(toolbarParams, posthog).finally(() => {+ loadPromise = null+ })+ return loadPromise+}++async function mountToolbar(toolbarParams: ToolbarParams, posthog?: PostHog): Promise<void> {// Store the start time so we can measure total load duration in initInstrumentation.// The loader script already stamps this before fetching the app module, so the measured// duration includes the chunk fetch — keep the earliest timestamp.diff --git a/frontend/src/toolbar/toolbarController.ts b/frontend/src/toolbar/toolbarController.tsindex 2bd2cb33b731..5177c3b3df71 100644--- a/frontend/src/toolbar/toolbarController.ts+++ b/frontend/src/toolbar/toolbarController.ts@@ -23,6 +23,20 @@ export function clearToolbarRefs(): void {_loaded = false}+/**+ * True when the toolbar is loaded AND its container is still attached to the page.+ *+ * `loadToolbar()` uses this to stay idempotent: posthog-js calls `ph_load_toolbar` more than+ * once in a page's lifetime (notably on SPA client-side route changes), and re-running the mount+ * path would `resetContext()` — tearing the Kea logics out from under the already-mounted React+ * tree, so the visible toolbar vanishes and a duplicate shadow root is left behind. The+ * `_container.isConnected` check means a stale flag (host page detached our node) still returns+ * false so the caller can tear down and remount.+ */+export function isToolbarMounted(): boolean {+ return _loaded && !!_container?.isConnected+}+/*** Public API for third-party code to programmatically control the toolbar.* Exposed on the host page as `window.posthogToolbarController`.