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.

chore(frontend): use the kea-disposables package (#98764)

posthog[bot]a42a4773c37f
diff --git a/.agents/skills/using-kea-disposables/SKILL.md b/.agents/skills/using-kea-disposables/SKILL.md
index 8d3d4d03f048..f8f2432f684a 100644
--- a/.agents/skills/using-kea-disposables/SKILL.md
+++ b/.agents/skills/using-kea-disposables/SKILL.md
@@ -1,11 +1,13 @@
---
name: using-kea-disposables
-description: 'Use when adding timers (`setInterval`, `setTimeout`), event listeners (`window.addEventListener`, `document.addEventListener`, `MediaQueryList.addEventListener`), or any other resource that needs cleanup inside a kea logic. Every logic has `cache.disposables.add(setup, key?, options?)` and `cache.disposables.dispose(key)` available via the globally registered `disposablesPlugin` (`frontend/src/kea-disposables.ts`). Replaces the bare `cache.foo = setInterval(...)` + `beforeUnmount: clearInterval(cache.foo)` pattern and auto-pauses background work when the tab is hidden.'
+description: 'Use when adding timers (`setInterval`, `setTimeout`), event listeners (`window.addEventListener`, `document.addEventListener`, `MediaQueryList.addEventListener`), or any other resource that needs cleanup inside a kea logic. Every logic has `cache.disposables.add(setup, key?, options?)` and `cache.disposables.dispose(key)` available via the globally registered `disposablesPlugin` from the `kea-disposables` package. Replaces the bare `cache.foo = setInterval(...)` + `beforeUnmount: clearInterval(cache.foo)` pattern and auto-pauses background work when the tab is hidden.'
---
# Using kea disposables
-Every kea logic in this repo has `cache.disposables` injected by the local `disposablesPlugin` (`frontend/src/kea-disposables.ts`, registered globally in `frontend/src/initKea.ts`). Reach for it whenever you create a resource that needs explicit teardown — the plugin runs cleanup on unmount and automatically pauses background work when the tab is hidden.
+Every kea logic in this repo has `cache.disposables` injected by `disposablesPlugin` from the [`kea-disposables`](https://github.com/PostHog/kea-disposables) package, registered globally in `frontend/src/initKea.ts` and in `frontend/src/toolbar/index.tsx`. Reach for it whenever you create a resource that needs explicit teardown — the plugin runs cleanup on unmount and automatically pauses background work when the tab is hidden.
+
+The package is maintained outside this repo, so a change to the plugin itself belongs there, not here. Types come from the package too: `import type { DisposablesManager } from 'kea-disposables'`.
**Do not add a `beforeUnmount` for cleanup.** The plugin runs the cleanup function you return from `setup` automatically when the logic unmounts (and re-runs setup/cleanup around tab visibility changes). If you find yourself writing a `beforeUnmount` whose only job is to `clearInterval` / `clearTimeout` / `removeEventListener` something registered earlier in the same logic, register that resource through `cache.disposables.add(...)` instead and delete the `beforeUnmount`. Reserve `beforeUnmount` for teardown that _isn't_ a resource you control (e.g. flushing state, persisting to localStorage, calling a third-party `dispose()`).
@@ -40,6 +42,23 @@ afterMount(({ actions, cache }) => {
}),
```
+For a resource that lives exactly as long as the logic, the `disposables` builder replaces that `afterMount`:
+
+```ts
+import { disposables } from 'kea-disposables'
+
+disposables(({ actions }) => ({
+ pollTimer: () => {
+ const id = window.setInterval(() => actions.loadCurrentTeam(), POLL_INTERVAL_MS)
+ return () => clearInterval(id)
+ },
+})),
+```
+
+The object keys are ordinary disposable keys, so `dispose('pollTimer')` still stops it early.
+Pass `{ setup, options }` instead of a bare function to set `pauseOnPageHidden`.
+Anything conditional, or re-armed from a listener, still wants `cache.disposables.add(...)`.
+
## Choosing a key
- **No key** — fire-and-forget; cleaned up only on unmount. Fine for one-shot listeners registered in `afterMount`.
@@ -88,8 +107,9 @@ The next mount puts a fresh manager on the cache, so a continuation left over fr
Capture what the continuation needs while the logic is alive when that matters.
Do not guard a timer callback with `isDisposed` alone if it reads `values`.
-The flag only moves on unmount, and replacing the kea context (which storybook does on every story mount) drops the logic from the store without unmounting it, so the cleanup never runs.
-Compare `getContext()` against the context the resource was set up in — see `frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts`.
+The flag only moves on unmount, and replacing the kea context (which storybook does on every story mount) drops the logic from the store without unmounting it, so `isDisposed` stays `false` on a logic that no longer has a store.
+The plugin does run every cleanup when the old context closes, so the resource itself goes away.
+A callback that already fired, or one whose cleanup cannot stop it (an in-flight request resolving), still needs its own guard: compare `getContext()` against the context the resource was set up in — see `frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts`.
## Examples in the codebase
diff --git a/frontend/package.json b/frontend/package.json
index b9367dcb84b7..1f65a6c841f5 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -227,6 +227,7 @@
"husky": "catalog:",
"image-blob-reduce": "^4.1.0",
"kea": "catalog:",
+ "kea-disposables": "catalog:",
"kea-forms": "catalog:",
"kea-loaders": "catalog:",
"kea-localstorage": "catalog:",
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index 6e5ce7da0bb0..f34bb6125089 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -1,4 +1,5 @@
import { KeaPlugin, resetContext } from 'kea'
+import { disposablesPlugin } from 'kea-disposables'
import { formsPlugin } from 'kea-forms'
import { loadersPlugin } from 'kea-loaders'
import { localStoragePlugin } from 'kea-localstorage'
@@ -18,8 +19,6 @@ import {
} from 'lib/utils/kea-router'
import { identifierToHuman } from 'lib/utils/strings'
-import { disposablesPlugin } from '~/kea-disposables'
-
/*
Actions for which we don't want to show error alerts,
mostly to avoid user confusion.
diff --git a/frontend/src/kea-disposables.test.ts b/frontend/src/kea-disposables.test.ts
deleted file mode 100644
index a5784ada57be..000000000000
--- a/frontend/src/kea-disposables.test.ts
+++ /dev/null
@@ -1,251 +0,0 @@
-import { MakeLogicType, kea, path } from 'kea'
-
-import { initKeaTests } from '~/test/init'
-
-// Helper: trigger visibilitychange after mutating document.hidden
-const setHidden = (hidden: boolean): void => {
- Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })
- Object.defineProperty(document, 'visibilityState', {
- configurable: true,
- get: () => (hidden ? 'hidden' : 'visible'),
- })
- document.dispatchEvent(new Event('visibilitychange'))
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export type logicType = MakeLogicType<{}, {}>
-
-describe('disposablesPlugin', () => {
- let logic: ReturnType<typeof kea<logicType>>
- let setupCalls: number
- let cleanupCalls: number
-
- beforeEach(() => {
- initKeaTests()
- setupCalls = 0
- cleanupCalls = 0
- setHidden(false)
-
- logic = kea<logicType>([path(['test', 'disposablesPluginTest'])])
- logic.mount()
- })
-
- afterEach(() => {
- logic.unmount()
- setHidden(false)
- })
-
- const makeSetup = () => () => {
- setupCalls += 1
- return () => {
- cleanupCalls += 1
- }
- }
-
- describe.each<{
- label: string
- initialHidden: boolean
- options?: { pauseOnPageHidden?: boolean }
- expectedSetupCalls: number
- expectedRegistryHas: boolean
- }>([
- {
- label: 'visible, default options — runs setup immediately',
- initialHidden: false,
- expectedSetupCalls: 1,
- expectedRegistryHas: true,
- },
- {
- label: 'hidden, default options — defers setup, entry still registered',
- initialHidden: true,
- expectedSetupCalls: 0,
- expectedRegistryHas: true,
- },
- {
- label: 'hidden, pauseOnPageHidden=false — runs setup anyway',
- initialHidden: true,
- options: { pauseOnPageHidden: false },
- expectedSetupCalls: 1,
- expectedRegistryHas: true,
- },
- ])('add() — $label', ({ initialHidden, options, expectedSetupCalls, expectedRegistryHas }) => {
- it('matches expected setup/registry state', () => {
- setHidden(initialHidden)
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1', options)
- expect(setupCalls).toBe(expectedSetupCalls)
- expect(cleanupCalls).toBe(0)
- expect((logic as any).cache.disposables.registry.has('k1')).toBe(expectedRegistryHas)
- })
- })
-
- it('runs setup on next visibility-visible for paused-at-birth entries', () => {
- setHidden(true)
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1')
- expect(setupCalls).toBe(0)
-
- setHidden(false)
- expect(setupCalls).toBe(1)
- })
-
- describe.each<{
- label: string
- options?: { pauseOnPageHidden?: boolean }
- expectedCleanupCalls: number
- }>([
- {
- label: 'default — cleanup runs on hide',
- expectedCleanupCalls: 1,
- },
- {
- label: 'pauseOnPageHidden=false — cleanup does NOT run on hide',
- options: { pauseOnPageHidden: false },
- expectedCleanupCalls: 0,
- },
- ])('visibility-hidden cleanup — $label', ({ options, expectedCleanupCalls }) => {
- it('matches expected cleanup count', () => {
- setHidden(false)
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1', options)
- expect(setupCalls).toBe(1)
- setHidden(true)
- expect(cleanupCalls).toBe(expectedCleanupCalls)
- })
- })
-
- it('replacing a keyed disposable cleans up the previous one', () => {
- setHidden(false)
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1')
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1')
- // first setup ran, first cleanup ran (because replaced), second setup ran
- expect(setupCalls).toBe(2)
- expect(cleanupCalls).toBe(1)
- })
-
- it('replacing a keyed disposable while hidden cleans up the previous and stores paused', () => {
- setHidden(false)
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1')
- expect(setupCalls).toBe(1)
-
- setHidden(true)
- // visibility-hidden runs cleanup for the active entry
- expect(cleanupCalls).toBe(1)
-
- // replace while hidden — should not run setup
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1')
- expect(setupCalls).toBe(1) // unchanged
- // Plugin defensively re-runs the previous cleanup when replacing a key.
- // User-supplied cleanups must therefore be idempotent (clearTimeout on
- // an already-cleared id is fine). cleanupCalls bumps to 2 even though
- // the timer was already cleared on hide.
- expect(cleanupCalls).toBe(2)
-
- // Resume runs setup for the replaced entry
- setHidden(false)
- expect(setupCalls).toBe(2)
- })
-
- it('regression: re-adding a disposable while hidden (poll-rescheduling pattern) does not start a live timer', () => {
- // Simulates the bug: a fetch's `finally` block calls add('pollTimeout', ...)
- // while the page is hidden. Before the fix, this would create a live timer.
- // After the fix, the setup is deferred to next visibility-visible.
- setHidden(false)
- ;(logic as any).cache.disposables.add(makeSetup(), 'pollTimeout')
- expect(setupCalls).toBe(1)
-
- setHidden(true)
- expect(cleanupCalls).toBe(1)
-
- // Simulate fetch returning and `finally` re-scheduling the timer
- ;(logic as any).cache.disposables.add(makeSetup(), 'pollTimeout')
- // CRITICAL: setup must NOT run while hidden — that was the bug
- expect(setupCalls).toBe(1)
-
- // When the user returns to the tab, the timer should be set up
- setHidden(false)
- expect(setupCalls).toBe(2)
- })
-
- describe.each<{
- label: string
- initialHidden: boolean
- expectedSetupCalls: number
- expectedCleanupCalls: number
- }>([
- {
- label: 'active entry — cleanup runs',
- initialHidden: false,
- expectedSetupCalls: 1,
- expectedCleanupCalls: 1,
- },
- {
- label: 'paused-at-birth entry — no user cleanup runs',
- initialHidden: true,
- expectedSetupCalls: 0,
- expectedCleanupCalls: 0,
- },
- ])('dispose() — $label', ({ initialHidden, expectedSetupCalls, expectedCleanupCalls }) => {
- it('removes entry and runs cleanup as expected', () => {
- setHidden(initialHidden)
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1')
- expect(setupCalls).toBe(expectedSetupCalls)
- ;(logic as any).cache.disposables.dispose('k1')
- expect(cleanupCalls).toBe(expectedCleanupCalls)
- expect((logic as any).cache.disposables.registry.has('k1')).toBe(false)
-
- // Subsequent visibility changes should not affect anything
- setHidden(!initialHidden)
- setHidden(initialHidden)
- expect(setupCalls).toBe(expectedSetupCalls)
- expect(cleanupCalls).toBe(expectedCleanupCalls)
- })
- })
-
- it('logic.unmount() disposes all registered disposables (no leak when consumer omits beforeUnmount)', () => {
- // Pins the contract that supportTicketCounterLogic relies on after
- // dropping its explicit `beforeUnmount(() => disposables.disposeAll())`.
- setHidden(false)
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1')
- ;(logic as any).cache.disposables.add(makeSetup(), 'k2')
- expect(setupCalls).toBe(2)
- expect(cleanupCalls).toBe(0)
-
- logic.unmount()
- expect(cleanupCalls).toBe(2)
- })
-
- it('add() and dispose() are inert after unmount rather than throwing', () => {
- setHidden(false)
- ;(logic as any).cache.disposables.add(makeSetup(), 'k1')
- // A loader or listener closes over `cache`, then reaches `cache.disposables` when it
- // resumes. Read the manager the same way here, so nulling it on unmount fails this test.
- const cache = (logic as any).cache
-
- logic.unmount()
- expect(cleanupCalls).toBe(1)
- expect(cache.disposables.isDisposed).toBe(true)
-
- expect(cache.disposables.dispose('k1')).toBe(false)
-
- cache.disposables.add(makeSetup(), 'k2')
- expect(setupCalls).toBe(1)
- expect(cache.disposables.registry.has('k2')).toBe(false)
- })
-
- it('mounting a built logic again replaces its disposed manager', () => {
- // Remounting a retained built logic keeps its cache, the lifecycle
- // scratchpadLogic.test.ts exercises. A manager left disposed there makes every add() in
- // the next afterMount a no-op, so the logic loses its timers and listeners for good.
- setHidden(false)
- const remounted = kea<logicType>([path(['test', 'disposablesRemountTest'])]).build()
- remounted.mount()
- ;(remounted as any).cache.disposables.add(makeSetup(), 'k1')
- remounted.unmount()
- expect(cleanupCalls).toBe(1)
- expect((remounted as any).cache.disposables.isDisposed).toBe(true)
-
- remounted.mount()
- ;(remounted as any).cache.disposables.add(makeSetup(), 'k1')
- expect(setupCalls).toBe(2)
- expect((remounted as any).cache.disposables.registry.has('k1')).toBe(true)
- remounted.unmount()
- })
-})
diff --git a/frontend/src/kea-disposables.ts b/frontend/src/kea-disposables.ts
deleted file mode 100644
index d8ca3e72fc51..000000000000
--- a/frontend/src/kea-disposables.ts
+++ /dev/null
@@ -1,322 +0,0 @@
-import type { BuiltLogic, KeaPlugin } from 'kea'
-
-export type DisposableFunction = () => void
-export type SetupFunction = () => DisposableFunction
-
-export type DisposableOptions = {
- pauseOnPageHidden?: boolean
-}
-
-type DisposableEntry = {
- setup: SetupFunction
- cleanup: DisposableFunction
- options: DisposableOptions
-}
-
-export type DisposablesManager = {
- add: (setup: SetupFunction, key?: string, options?: DisposableOptions) => void
- dispose: (key: string) => boolean
- registry: Map<string, DisposableEntry>
- keyCounter: number
- logicPath: string
- /**
- * True once the logic has begun its final unmount. It is set before the registered cleanups
- * run, so a cleanup that wakes a continuation already sees an inert manager. `add` and
- * `dispose` do nothing from that point on, which is what lets async work that outlives the
- * unmount call them unconditionally. Read it when the continuation itself must stop early,
- * for instance before reading `values` on a logic whose reducers are already detached.
- *
- * A disposed manager stays inert for the rest of its own life, but the next mount of the same
- * logic puts a fresh manager on the cache. So a continuation that reaches `cache.disposables`
- * late can find a live manager belonging to the logic's next life, and disposing a shared key
- * from there tears down the new life's resource. Capture what the continuation needs while the
- * logic is alive when that matters.
- */
- isDisposed: boolean
-}
-
-// Type for logic with disposables added
-type LogicWithCache = BuiltLogic & {
- cache: { disposables?: DisposablesManager; [key: string]: any }
-}
-
-// Global state for visibility tracking
-const globalVisibilityState = {
- allManagers: new Set<DisposablesManager>(),
- listenerAttached: false,
- handler: null as (() => void) | null,
-}
-
-const safeCleanup = (cleanup: DisposableFunction, logicPath: string): void => {
- try {
- cleanup()
- } catch (error) {
- console.error(`[KEA] Disposable cleanup failed in logic ${logicPath}:`, error)
- }
-}
-
-const safeSetup = (setup: SetupFunction, logicPath: string): DisposableFunction | null => {
- try {
- return setup()
- } catch (error) {
- console.error(`[KEA] Disposable setup failed in logic ${logicPath}:`, error)
- return null
- }
-}
-
-const pauseAllDisposables = (): void => {
- globalVisibilityState.allManagers.forEach((manager) => {
- manager.registry.forEach((entry) => {
- if (entry.options.pauseOnPageHidden !== false && entry.cleanup) {
- safeCleanup(entry.cleanup, manager.logicPath)
- }
- })
- })
-}
-
-const resumeAllDisposables = (): void => {
- globalVisibilityState.allManagers.forEach((manager) => {
- manager.registry.forEach((entry) => {
- if (entry.options.pauseOnPageHidden !== false) {
- const cleanup = safeSetup(entry.setup, manager.logicPath)
- if (cleanup) {
- entry.cleanup = cleanup
- } else {
- // Setup failed - replace cleanup with no-op to prevent stale cleanup from running
- entry.cleanup = () => {}
- }
- }
- })
- })
-}
-
-const attachGlobalVisibilityListener = (): void => {
- if (globalVisibilityState.listenerAttached) {
- return
- }
-
- const handleVisibilityChange = (): void => {
- if (document.hidden) {
- pauseAllDisposables()
- } else {
- resumeAllDisposables()
- }
- }
-
- globalVisibilityState.handler = handleVisibilityChange
- document.addEventListener('visibilitychange', handleVisibilityChange)
- globalVisibilityState.listenerAttached = true
-}
-
-const detachGlobalVisibilityListener = (): void => {
- if (!globalVisibilityState.listenerAttached || !globalVisibilityState.handler) {
- return
- }
- if (globalVisibilityState.allManagers.size === 0) {
- document.removeEventListener('visibilitychange', globalVisibilityState.handler)
- globalVisibilityState.listenerAttached = false
- globalVisibilityState.handler = null
- }
-}
-
-const initializeDisposablesManager = (logic: LogicWithCache): void => {
- // A logic that mounts again keeps the same cache, so the disposed manager from its previous
- // life is still attached. Replace it, or every `add` in the new `afterMount` is a no-op and
- // the logic silently loses its timers and listeners for the rest of the session.
- if (logic.cache.disposables && !logic.cache.disposables.isDisposed) {
- return
- }
-
- const manager: DisposablesManager = {
- registry: new Map(),
- keyCounter: 0,
- logicPath: logic.pathString,
- isDisposed: false,
- add: (setup: SetupFunction, key?: string, options?: DisposableOptions) => {
- if (manager.isDisposed) {
- return
- }
- const disposableKey = key ?? `__auto_${manager.keyCounter++}`
- const disposableOptions: DisposableOptions = { pauseOnPageHidden: true, ...options }
-
- // If replacing a keyed disposable, clean up the previous one first
- if (key && manager.registry.has(disposableKey)) {
- const previousEntry = manager.registry.get(disposableKey)!
- safeCleanup(previousEntry.cleanup, manager.logicPath)
- }
-
- // If the page is currently hidden and this disposable opts into
- // pause/resume, register it without running setup. resumeAllDisposables
- // will run setup the next time the page becomes visible. Without this,
- // anything calling add() from a listener/loader while hidden (e.g.
- // re-scheduling a poll inside a fetch's `finally`) creates a live
- // timer/listener that should be paused — defeating the auto-pause.
- const startPaused = document.hidden && disposableOptions.pauseOnPageHidden !== false
- if (startPaused) {
- manager.registry.set(disposableKey, {
- setup,
- cleanup: () => {},
- options: disposableOptions,
- })
- return
- }
-
- // Run setup function to get cleanup function
- const cleanup = safeSetup(setup, manager.logicPath)
- if (cleanup) {
- manager.registry.set(disposableKey, {
- setup,
- cleanup,
- options: disposableOptions,
- })
- }
- },
- dispose: (key: string) => {
- if (manager.isDisposed) {
- return false
- }
- if (!manager.registry.has(key)) {
- return false
- }
-
- const entry = manager.registry.get(key)!
- safeCleanup(entry.cleanup, manager.logicPath)
- manager.registry.delete(key)
- return true
- },
- }
-
- logic.cache.disposables = manager
-
- // Register this manager for global visibility tracking
- globalVisibilityState.allManagers.add(manager)
- attachGlobalVisibilityListener()
-}
-
-/**
- * Kea plugin that provides automatic resource cleanup via disposables with smart pause/resume.
- *
- * ## Usage
- *
- * The disposables system is similar to React's useEffect cleanup pattern - you provide
- * a setup function that returns a cleanup function. The cleanup runs automatically when
- * the logic unmounts.
- *
- * ```typescript
- * listeners(({ actions, cache }) => ({
- * someAction: () => {
- * // Add a disposable - like useEffect(() => { ... return cleanup }, [])
- * cache.disposables.add(() => {
- * // Setup code runs immediately
- * const intervalId = setInterval(() => {
- * actions.pollData()
- * }, 5000)
- *
- * // Return cleanup function (like useEffect cleanup)
- * return () => clearInterval(intervalId)
- * }, 'pollingInterval') // Optional key for replacing/disposing specific disposables
- * }
- * }))
- * ```
- *
- * ## Key Features
- *
- * - **Automatic cleanup**: Cleanup functions run when the logic unmounts
- * - **Smart pause/resume**: Disposables automatically pause when page is hidden (NEW!)
- * - **Named disposables**: Use keys to replace or dispose specific resources
- * - **Safe execution**: Errors in cleanup are caught and logged
- * - **Similar to useEffect**: Setup returns cleanup, just like React hooks
- *
- * ## Automatic Pause on Page Hidden
- *
- * By default, all disposables pause when the page is hidden and resume when visible.
- * This dramatically reduces CPU and network usage in background tabs.
- *
- * ```typescript
- * // This automatically pauses when page is hidden
- * cache.disposables.add(() => {
- * const id = setInterval(() => actions.pollData(), 5000)
- * return () => clearInterval(id)
- * }, 'polling')
- * ```
- *
- * For critical resources that must remain active (e.g., navigation tracking),
- * opt-out with `pauseOnPageHidden: false`:
- *
- * ```typescript
- * // This keeps running even when page is hidden
- * cache.disposables.add(() => {
- * window.addEventListener('popstate', handler)
- * return () => window.removeEventListener('popstate', handler)
- * }, 'navigation', { pauseOnPageHidden: false })
- * ```
- *
- * ## Common Use Cases
- *
- * - Event listeners (window.addEventListener)
- * - Timers (setTimeout, setInterval) - auto-pauses!
- * - Subscriptions (WebSocket, EventSource) - auto-pauses!
- * - External library cleanup
- *
- * @example Replace a disposable
- * ```typescript
- * // Each call with the same key replaces the previous one
- * cache.disposables.add(() => {
- * const id = setTimeout(() => action(), 1000)
- * return () => clearTimeout(id)
- * }, 'myTimer')
- *
- * // Later, this replaces the previous timer
- * cache.disposables.add(() => {
- * const id = setTimeout(() => action(), 2000)
- * return () => clearTimeout(id)
- * }, 'myTimer')
- * ```
- *
- * @example Manually dispose
- * ```typescript
- * // Stop polling without unmounting
- * cache.disposables.dispose('pollingInterval')
- * ```
- *
- * ## Safe to call after unmount
- *
- * `add` and `dispose` become no-ops once the logic unmounts, so a listener or loader that resumes
- * after the unmount can call them without a null check. When such a continuation must also skip
- * work of its own (dispatching an action, reading `values`), branch on `cache.disposables.isDisposed`.
- */
-export const disposablesPlugin: KeaPlugin = {
- name: 'disposables',
- events: {
- afterMount(logic) {
- const typedLogic = logic as LogicWithCache
- initializeDisposablesManager(typedLogic)
- },
- beforeUnmount(logic) {
- const typedLogic = logic as LogicWithCache
- const manager = typedLogic.cache.disposables
- // Only dispose on final unmount when logic.isMounted() becomes false
- if (!typedLogic.isMounted() && manager && !manager.isDisposed) {
- // Unregister from global visibility tracking
- globalVisibilityState.allManagers.delete(manager)
-
- // Marked before the cleanups run, so that anything a cleanup wakes up (an aborted
- // request resuming inside a `finally`, for instance) sees an inert manager rather
- // than re-registering a resource on a logic that is going away.
- manager.isDisposed = true
-
- // Clean up all disposables. The manager itself stays on the cache instead of being
- // nulled, because async work that outlives the unmount still reaches for
- // `cache.disposables.dispose(...)`, and a null there throws a TypeError out of the
- // continuation rather than doing nothing.
- manager.registry.forEach((entry) => {
- safeCleanup(entry.cleanup, typedLogic.pathString)
- })
- manager.registry.clear()
-
- // Detach global listener if no more managers
- detachGlobalVisibilityListener()
- }
- },
- },
-}
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
index 3fd3274205ac..329b9cbb4afa 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
@@ -1,5 +1,6 @@
import { deepEqual as equal } from 'fast-equals'
import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
+import type { DisposablesManager } from 'kea-disposables'
import { subscriptions } from 'kea-subscriptions'
import { lemonToast } from '@posthog/lemon-ui'
@@ -21,7 +22,6 @@ import { ProductTab, WEB_ANALYTICS_DEFAULT_QUERY_TAGS } from 'scenes/web-analyti
import { isLiveStreamFilter, webAnalyticsFilterLogic } from 'scenes/web-analytics/webAnalyticsFilterLogic'
import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
-import type { DisposablesManager } from '~/kea-disposables'
import { performQuery } from '~/queries/query'
import {
HogQLQuery,
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx
index 37781edc48ae..e2dc44556bbc 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx
@@ -1,10 +1,9 @@
import { MakeLogicType, actions, events, kea, listeners, path, reducers, selectors } from 'kea'
+import type { DisposablesManager } from 'kea-disposables'
import { getSeriesColor } from 'lib/colors'
import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
-import type { DisposablesManager } from '~/kea-disposables'
-
import { CountryBreakdownItem } from './LiveWebAnalyticsMetricsTypes'
const HEAT_DECAY_MS = 3000
diff --git a/frontend/src/toolbar/index.tsx b/frontend/src/toolbar/index.tsx
index 0c78fc7bc31d..f4e17a4365cd 100644
--- a/frontend/src/toolbar/index.tsx
+++ b/frontend/src/toolbar/index.tsx
@@ -2,6 +2,7 @@ import '~/styles'
import './styles.scss'
import { KeaPlugin, resetContext } from 'kea'
+import { disposablesPlugin } from 'kea-disposables'
import { formsPlugin } from 'kea-forms'
import { loadersPlugin } from 'kea-loaders'
import { localStoragePlugin } from 'kea-localstorage'
@@ -12,7 +13,6 @@ import { windowValuesPlugin } from 'kea-window-values'
import type { PostHog } from 'posthog-js'
import { createRoot } from 'react-dom/client'
-import { disposablesPlugin } from '~/kea-disposables'
import { ToolbarApp } from '~/toolbar/ToolbarApp'
import { canonicalizeApiHost } from '~/toolbar/toolbarConfigLogic'
import { isToolbarMounted, posthogToolbarController, setToolbarRefs } from '~/toolbar/toolbarController'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 403388d94b09..3a2292023f5e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -66,6 +66,9 @@ catalogs:
kea:
specifier: ^4.0.0-pre.6
version: 4.0.0-pre.6
+ kea-disposables:
+ specifier: ^1.0.0
+ version: 1.0.0
kea-forms:
specifier: ^3.2.0
version: 3.2.0
@@ -1073,6 +1076,9 @@ importers:
kea:
specifier: 'catalog:'
version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
+ kea-disposables:
+ specifier: 'catalog:'
+ version: 1.0.0([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
kea-forms:
specifier: 'catalog:'
version: 3.2.0([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
@@ -4128,6 +4134,9 @@ importers:
kea:
specifier: 'catalog:'
version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
+ kea-disposables:
+ specifier: 'catalog:'
+ version: 1.0.0([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
kea-forms:
specifier: 'catalog:'
version: 3.2.0([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
@@ -18071,6 +18080,12 @@ packages:
resolution: {integrity: sha512-WbCVYJ27Sz8zi9Q7Q0xHC+05iwkm3Znipc2XTlrnJbsHMYktW4hPhXUE8Ys1engBrvffoSCqbil1JQAa7clRpA==}
+ resolution: {integrity: sha512-WFME7l3iT7jOCOicXiU6tzeeoQrOInCBBuPqBT9wkaoX6rSJlZgcOghLbAEgVl1BXi3Cl1UsbYJnuSAQ7rZEVg==}
+ engines: {node: '>=20'}
+ peerDependencies:
+ kea: '>= 3'
+
resolution: {integrity: sha512-R/ECGx6FxOZ2TEJv2GcFNLcQJePUK5Qd4Km81rN/7lBHd2hG4CAJglODVpcolWZ0RtcLcvMhHeTg/iqNz5pynw==}
peerDependencies:
@@ -39832,6 +39847,10 @@ snapshots:
+ [email protected]([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])):
+ dependencies:
+ kea: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
+
[email protected]([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])):
dependencies:
kea: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index c32ff2097ff2..0216c90076f3 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -134,6 +134,7 @@ onlyBuiltDependencies:
catalog:
# Kea ecosystem - state management
kea: ^4.0.0-pre.6
+ kea-disposables: ^1.0.0
kea-forms: ^3.2.0
kea-loaders: ^3.1.1
kea-localstorage: ^3.1.0
diff --git a/products/posthog_ai/frontend/utils/warmRunSubmission.test.ts b/products/posthog_ai/frontend/utils/warmRunSubmission.test.ts
index 042bc77856bf..c1cf38eade3d 100644
--- a/products/posthog_ai/frontend/utils/warmRunSubmission.test.ts
+++ b/products/posthog_ai/frontend/utils/warmRunSubmission.test.ts
@@ -1,9 +1,8 @@
import { kea, path, resetContext } from 'kea'
+import { type DisposablesManager, disposablesPlugin } from 'kea-disposables'
import { ApiError } from 'lib/api-error'
-import { DisposablesManager, disposablesPlugin } from '~/kea-disposables'
-
import { submitWithWarmRunRetry } from './warmRunSubmission'
const starting = (token = 'synthetic-retry-token'): ApiError =>
diff --git a/products/posthog_ai/frontend/utils/warmRunSubmission.ts b/products/posthog_ai/frontend/utils/warmRunSubmission.ts
index cbc473c04994..d371641dd9de 100644
--- a/products/posthog_ai/frontend/utils/warmRunSubmission.ts
+++ b/products/posthog_ai/frontend/utils/warmRunSubmission.ts
@@ -1,8 +1,8 @@
+import type { DisposablesManager } from 'kea-disposables'
+
import { ApiError } from 'lib/api-error'
import { uuid } from 'lib/utils/dom'
-import type { DisposablesManager } from '~/kea-disposables'
-
async function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
let abort = (): void => {}
try {
diff --git a/products/posthog_ai/package.json b/products/posthog_ai/package.json
index 2060215d1704..eefeaa837d67 100644
--- a/products/posthog_ai/package.json
+++ b/products/posthog_ai/package.json
@@ -27,6 +27,7 @@
"@types/react-dom": "*",
"clsx": "*",
"kea": "catalog:",
+ "kea-disposables": "catalog:",
"kea-forms": "catalog:",
"kea-loaders": "catalog:",
"kea-router": "catalog:",
diff --git a/tsconfig.kea-typegen.json b/tsconfig.kea-typegen.json
index a592ec7036ab..6d5e7c5c915e 100644
--- a/tsconfig.kea-typegen.json
+++ b/tsconfig.kea-typegen.json
@@ -4,7 +4,6 @@
"incremental": false
},
"files": [
- "frontend/src/kea-disposables.test.ts",
"frontend/src/lib/lemon-ui/LemonField/LemonField.stories.tsx",
"frontend/src/lib/lemon-ui/LemonField/LemonField.test.tsx",
"frontend/src/lib/logic/bindModalToUrl.test.ts",