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(frontend): pause disposables added while page is hidden (#58691)

Paul D'Ambracc1bc508565e
diff --git a/frontend/src/kea-disposables.test.ts b/frontend/src/kea-disposables.test.ts
new file mode 100644
index 000000000000..4b2e87c4fe74
--- /dev/null
+++ b/frontend/src/kea-disposables.test.ts
@@ -0,0 +1,213 @@
+import { kea, path } from 'kea'
+
+import { initKeaTests } from '~/test/init'
+
+import type { logicType } from './kea-disposables.testType'
+
+// 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'))
+}
+
+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)
+ })
+})
diff --git a/frontend/src/kea-disposables.ts b/frontend/src/kea-disposables.ts
index 633d7afa0dd4..4b932b01263f 100644
--- a/frontend/src/kea-disposables.ts
+++ b/frontend/src/kea-disposables.ts
@@ -127,6 +127,22 @@ const initializeDisposablesManager = (logic: LogicWithCache): void => {
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) {
diff --git a/products/conversations/frontend/supportTicketCounterLogic.ts b/products/conversations/frontend/supportTicketCounterLogic.ts
index 01f12f3d24ab..0a5958e8887f 100644
--- a/products/conversations/frontend/supportTicketCounterLogic.ts
+++ b/products/conversations/frontend/supportTicketCounterLogic.ts
@@ -1,4 +1,4 @@
-import { actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
@@ -22,12 +22,12 @@ export const supportTicketCounterLogic = kea<supportTicketCounterLogicType>([
actions: [browserNotificationLogic, ['showNotification']],
})),
actions({
- togglePolling: (pageIsVisible: boolean) => ({ pageIsVisible }),
incrementErrorCount: true,
clearErrorCount: true,
resetCount: true, // Reset count when team changes or user logs out
refreshCount: true, // Public action for other logics to trigger immediate refresh
loadUnreadCount: true, // Explicit parameterless action (loader will use this)
+ schedulePoll: true, // Re-schedule the next poll via disposables
}),
reducers({
errorCounter: [
@@ -35,49 +35,29 @@ export const supportTicketCounterLogic = kea<supportTicketCounterLogicType>([
{
incrementErrorCount: (state) => (state >= 5 ? 5 : state + 1),
clearErrorCount: () => 0,
- resetCount: () => 0, // Reset error counter on team change
+ resetCount: () => 0,
},
],
}),
- loaders(({ actions, values, cache }) => ({
+ loaders(({ actions, values }) => ({
unreadCount: [
0,
{
loadUnreadCount: async (_, breakpoint) => {
- // Don't poll if support is not enabled
if (!values.isSupportEnabled) {
return 0
}
await breakpoint(1)
- // Track error state locally to avoid race condition with async action dispatch
- let hadError = false
- const currentErrorCount = values.errorCounter
-
try {
const response = await api.conversationsTickets.unreadCount()
actions.clearErrorCount()
return response.count
} catch {
// Swallow errors - increment counter for backoff
- hadError = true
actions.incrementErrorCount()
return values.unreadCount // Keep previous value on error
- } finally {
- // Schedule next poll
- if (values.isSupportEnabled) {
- // Calculate backoff using local state to avoid race condition
- const effectiveErrorCount = hadError ? Math.min(currentErrorCount + 1, 5) : 0
- const pollInterval = effectiveErrorCount
- ? POLL_INTERVAL * (effectiveErrorCount + 1) // Backoff on errors
- : POLL_INTERVAL
-
- cache.disposables.add(() => {
- const timerId = window.setTimeout(actions.loadUnreadCount, pollInterval)
- return () => clearTimeout(timerId)
- }, 'pollTimeout')
- }
}
},
resetCount: () => 0, // Immediately set count to 0 on team change/logout
@@ -88,15 +68,29 @@ export const supportTicketCounterLogic = kea<supportTicketCounterLogicType>([
isSupportEnabled: [(s) => [s.currentTeam], (currentTeam): boolean => !!currentTeam?.conversations_enabled],
}),
listeners(({ actions, values, cache }) => ({
- togglePolling: ({ pageIsVisible }) => {
- if (pageIsVisible && values.isSupportEnabled) {
- actions.loadUnreadCount()
- } else {
- cache.disposables.dispose('pollTimeout')
+ // Re-schedule after each load completes. The loader catches API errors
+ // and returns a value, so the failure action never actually dispatches —
+ // a single success listener covers both the happy path and the swallowed
+ // error path. The disposables plugin auto-pauses the scheduled timer
+ // when the tab is hidden and resumes it when visible.
+ loadUnreadCountSuccess: () => actions.schedulePoll(),
+ schedulePoll: () => {
+ if (!values.isSupportEnabled) {
+ return
}
+ const interval = values.errorCounter
+ ? POLL_INTERVAL * (values.errorCounter + 1) // Backoff on errors
+ : POLL_INTERVAL
+ cache.disposables.add(() => {
+ const id = window.setTimeout(actions.loadUnreadCount, interval)
+ return () => clearTimeout(id)
+ }, 'pollTimeout')
},
refreshCount: () => {
- // Public action for other logics to trigger immediate refresh (e.g., after viewing a ticket)
+ // Intentionally visibility-agnostic: callers (e.g. ticket-viewed events)
+ // want an immediate count refresh regardless of tab focus. The follow-up
+ // polling resumes through schedulePoll, which IS gated by visibility
+ // via the disposables plugin's pause/resume.
cache.disposables.dispose('pollTimeout')
actions.loadUnreadCount()
},
@@ -109,48 +103,29 @@ export const supportTicketCounterLogic = kea<supportTicketCounterLogicType>([
return
}
- // Team changed or user logged out
cache.disposables.dispose('pollTimeout')
actions.resetCount()
- // If new team has support enabled, start polling
if (currentTeam?.conversations_enabled) {
actions.loadUnreadCount()
}
},
// Notify tickets scene when unread count changes
unreadCount: (unreadCount, oldUnreadCount) => {
- // Skip initial subscription
if (oldUnreadCount === undefined) {
return
}
- // Refresh tickets list if scene is mounted
if (unreadCount !== oldUnreadCount) {
supportTicketsSceneLogic.findMounted()?.actions.loadTickets()
}
- // Show browser notification when count increases
if (unreadCount > oldUnreadCount && values.canShowNotifications) {
actions.showNotification(unreadCount)
}
},
})),
- afterMount(({ actions, values, cache }) => {
- // Set up visibility change listener
- cache.disposables.add(() => {
- const onVisibilityChange = (): void => {
- actions.togglePolling(document.visibilityState === 'visible')
- }
- document.addEventListener('visibilitychange', onVisibilityChange)
- return () => document.removeEventListener('visibilitychange', onVisibilityChange)
- }, 'visibilityListener')
-
- // Start polling if support is enabled
+ afterMount(({ actions, values }) => {
if (values.isSupportEnabled) {
actions.loadUnreadCount()
}
}),
- beforeUnmount(({ cache }) => {
- // Clean up all disposables (timers, event listeners)
- cache.disposables.disposeAll()
- }),
])