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.

fix(app): release autofill ref on SPA nav to free detached DOM (#61976)

Paul D'Ambra11310550e2f4
diff --git a/frontend/src/lib/memory/autofillReleaseLogic.test.ts b/frontend/src/lib/memory/autofillReleaseLogic.test.ts
new file mode 100644
index 000000000000..7ba41be1fd9f
--- /dev/null
+++ b/frontend/src/lib/memory/autofillReleaseLogic.test.ts
@@ -0,0 +1,57 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { autofillReleaseLogic } from './autofillReleaseLogic'
+
+const SINK_SELECTOR = '#autofill-release-sink'
+
+describe('autofillReleaseLogic', () => {
+ let logic: ReturnType<typeof autofillReleaseLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = autofillReleaseLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('mounts a sink input and removes it on unmount', () => {
+ expect(document.querySelectorAll(SINK_SELECTOR)).toHaveLength(1)
+ logic.unmount()
+ expect(document.querySelector(SINK_SELECTOR)).toBeNull()
+ })
+
+ it('evicts a stale sink left by a previous instance instead of duplicating it', () => {
+ logic.unmount()
+ const orphan = document.createElement('input')
+ orphan.id = 'autofill-release-sink'
+ document.body.appendChild(orphan)
+
+ logic.mount()
+
+ expect(document.querySelectorAll(SINK_SELECTOR)).toHaveLength(1)
+ })
+
+ it.each([
+ { change: 'a different pathname', navigate: (): void => router.actions.push('/dashboard'), shouldFocus: true },
+ {
+ change: 'a query-only change',
+ navigate: (): void => router.actions.push('/insights', { search: 'foo' }),
+ shouldFocus: false,
+ },
+ ])('focuses the sink on $change: $shouldFocus', async ({ navigate, shouldFocus }) => {
+ await expectLogic(logic, () => router.actions.push('/insights')).toDispatchActions(['locationChanged'])
+
+ const sink = document.querySelector(SINK_SELECTOR) as HTMLInputElement
+ const focusSpy = jest.spyOn(sink, 'focus')
+
+ await expectLogic(logic, () => navigate()).toDispatchActions(['locationChanged'])
+
+ expect(focusSpy).toHaveBeenCalledTimes(shouldFocus ? 1 : 0)
+ })
+})
diff --git a/frontend/src/lib/memory/autofillReleaseLogic.ts b/frontend/src/lib/memory/autofillReleaseLogic.ts
new file mode 100644
index 000000000000..bd31ba405792
--- /dev/null
+++ b/frontend/src/lib/memory/autofillReleaseLogic.ts
@@ -0,0 +1,94 @@
+import { afterMount, connect, kea, listeners, path } from 'kea'
+import { router } from 'kea-router'
+
+import type { autofillReleaseLogicType } from './autofillReleaseLogicType'
+
+const SINK_ID = 'autofill-release-sink'
+
+/**
+ * Workaround for a Chromium AutofillAgent retention bug.
+ *
+ * Blink's AutofillAgent keeps a strong (C++ Persistent) reference to the
+ * last-focused form control, and does not release it when that element is
+ * removed from the DOM. An `autoFocus`'d input inside a scene (e.g. the
+ * saved-insights search box) therefore pins its entire detached subtree —
+ * the whole results table, every row, cell and sparkline — across SPA
+ * navigation. Forced GC cannot reclaim it. Across navigations this is a
+ * large, steady source of detached-DOM growth.
+ *
+ * The agent only drops the reference when a *different* form control is
+ * focused (a new autofill query). Blurring alone does not release it. So on
+ * every scene change we momentarily focus a persistent off-screen sink
+ * input, moving the agent's reference onto a node that never detaches. The
+ * next scene's own `autoFocus` (if any) then takes the reference over from
+ * the sink. We blur the sink immediately so it never holds visible focus.
+ *
+ * Ordering holds because `locationChanged` fires on the router action, before
+ * React renders the next scene, so the sink's focus/blur runs first and the
+ * incoming scene's mount-time `autoFocus` reclaims focus afterwards — we never
+ * yank focus out of the scene we're navigating to.
+ *
+ * Sibling in spirit to `useCancelAnimationsOnUnmount`, which severs the
+ * DocumentTimeline -> animation -> element retention on the same SPA
+ * navigation boundary.
+ *
+ * Upstream Chromium bug: https://issues.chromium.org/issues/342247579
+ * Delete this file once it is fixed.
+ */
+export const autofillReleaseLogic = kea<autofillReleaseLogicType>([
+ path(['lib', 'memory', 'autofillReleaseLogic']),
+ connect(() => ({
+ actions: [router, ['locationChanged']],
+ })),
+ afterMount(({ cache }) => {
+ cache.lastPathname = router.values.location.pathname
+ // keep the sink for the whole app lifetime, including while the tab is
+ // hidden — pauseOnPageHidden would tear it down and recreate it on show
+ cache.disposables.add(
+ () => {
+ // evict any sink left behind by a previous instance whose
+ // cleanup was missed (e.g. an HMR module swap), so we never
+ // append a second element with the same id
+ document.getElementById(SINK_ID)?.remove()
+ const sink = document.createElement('input')
+ sink.id = SINK_ID
+ sink.type = 'text'
+ sink.tabIndex = -1
+ sink.setAttribute('aria-hidden', 'true')
+ // off-screen rather than `display:none`/`sr-only` clip: the
+ // element must stay focusable and "visible enough" for the
+ // autofill agent to re-query it, which releases the previous one
+ sink.style.position = 'fixed'
+ sink.style.left = '-9999px'
+ document.body.appendChild(sink)
+ cache.sink = sink
+ return () => {
+ sink.remove()
+ cache.sink = undefined
+ }
+ },
+ 'autofill-sink',
+ { pauseOnPageHidden: false }
+ )
+ }),
+ listeners(({ cache }) => ({
+ locationChanged: ({ pathname }) => {
+ // only release on an actual scene change. query/hash updates fire
+ // locationChanged too (scenes sync filters to the URL), and
+ // stealing focus on those would break a scene's own search box
+ // mid-keystroke
+ if (pathname === cache.lastPathname) {
+ return
+ }
+ cache.lastPathname = pathname
+ const sink = cache.sink as HTMLInputElement | undefined
+ if (!sink) {
+ return
+ }
+ // preventScroll: focusing must never scroll the (off-screen) sink
+ // into view
+ sink.focus({ preventScroll: true })
+ sink.blur()
+ },
+ })),
+])
diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsx
index d5cfd643578b..ded273c5cbb0 100644
--- a/frontend/src/scenes/App.tsx
+++ b/frontend/src/scenes/App.tsx
@@ -8,6 +8,7 @@ import { useThemedHtml } from 'lib/hooks/useThemedHtml'
import { KeaDevtools } from 'lib/KeaDevTools'
import { ToastCloseButton } from 'lib/lemon-ui/LemonToast/LemonToast'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
+import { autofillReleaseLogic } from 'lib/memory/autofillReleaseLogic'
import { appLogic } from 'scenes/appLogic'
import { appScenes } from 'scenes/appScenes'
import { sceneLogic } from 'scenes/sceneLogic'
@@ -49,6 +50,7 @@ export function App(): JSX.Element | null {
const { showApp, showingDelayedSpinner, showingDevTools } = useValues(appLogic)
useMountedLogic(sceneLogic({ scenes: appScenes }))
+ useMountedLogic(autofillReleaseLogic)
useThemedHtml()