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): speed up kea listener breakpoints (#95407)

Paul D'Ambra13a6b48bc908
diff --git a/.agents/skills/writing-kea-logics/references/testing.md b/.agents/skills/writing-kea-logics/references/testing.md
index 243176dedc98..f5d372783565 100644
--- a/.agents/skills/writing-kea-logics/references/testing.md
+++ b/.agents/skills/writing-kea-logics/references/testing.md
@@ -87,6 +87,23 @@ Common assertion methods from `kea-test-utils`:
| `.toFinishListener(actionName)` | Awaits a specific listener. |
| `partial({ ... })` / `truth(fn)` | Helpers for value matching. |
+## Breakpoint timing in Jest
+
+The frontend Jest setup keeps kea breakpoint cancellation but shortens
+`breakpoint(ms)` to a zero-delay timer task. A bare `breakpoint()` is unchanged. When
+Jest fake timers are active, delayed breakpoints keep their requested duration.
+
+- If the delay itself is behavior, call `jest.useFakeTimers()` before dispatching the
+ action, advance the exact duration, and restore real timers after the test.
+- If the test must observe an API request while it is pending, do not depend on the
+ breakpoint delay. Make the HTTP mock await a test-controlled promise, assert the
+ pending state, then resolve the promise and assert the settled state.
+- If only the settled result matters, await that result with `expectLogic`, `waitFor`,
+ or the matching loader action.
+
+See [writing-tests](../../writing-tests/SKILL.md) for the general async state-transition
+rule. Never add logic-path exceptions to the Jest breakpoint wrapper.
+
## Parameterise
Per repo convention ([CLAUDE.md](../../../../CLAUDE.md)), parameterise variations of the
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.md
index e0f22d5c4914..ae7c84536340 100644
--- a/.agents/skills/writing-tests/SKILL.md
+++ b/.agents/skills/writing-tests/SKILL.md
@@ -152,9 +152,18 @@ Escalating to the next rung is the last resort, not the default.
### Always — determinism and isolation
-- **No `time.sleep` / arbitrary waits.**
- Use fake timers, `wait_for` / `waitFor` on a real condition, or `freeze_time`.
- A sleep is a flake waiting to happen, and it slows every run.
+- **Control the state transition instead of racing it.** Choose the control that matches
+ the behavior under test:
+ - For elapsed-time behavior, enable fake timers before starting the work and advance
+ exactly the duration the behavior requires.
+ - For a final async result, use `wait_for` / `waitFor` on the observable result.
+ - For an in-flight state, make the mocked boundary await a promise controlled by the
+ test. Assert the pending state, release the promise, then assert the final state.
+ Do not assume a debounce, `setTimeout`, kea breakpoint, or fast mock will still be
+ pending on the next line. Test setup may shorten internal delays without changing
+ production behavior.
+- **No `time.sleep` / arbitrary waits.** A sleep is a flake waiting to happen, and it
+ slows every run. Replace it with the matching control above or `freeze_time`.
- **An absolute date in a test is a time bomb until you pin the clock.**
A fixture date keeps its meaning only while the real clock stays where you left it.
If anything under test measures that date against `now` — an age, a window, a "recent" flag, an expiry — the assertion holds today and fails some weeks later, on every open branch at once.
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index 85cf75a40d20..497c8acb52be 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -180,6 +180,7 @@ const config: Config = {
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: {
+ '^kea$': '<rootDir>/src/test/keaTestModule.js',
'^.+\\.(css|less|scss|svg|png)$': '<rootDir>/src/test/mocks/styleMock.js',
// @posthog/brand PNG subpaths resolve to .mjs modules that build a URL via
// `new URL("./x.png", import.meta.url)` — import.meta is unavailable under Sucrase/CJS,
diff --git a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx b/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
index b78262aefbd3..f6692a195a90 100644
--- a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
+++ b/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
@@ -67,18 +67,24 @@ async function dropASearch(container: HTMLElement): Promise<void> {
describe('SlackChannelPicker', () => {
let channelsRequestSearchQueries: (string | null)[] = []
let channelIdLookups: string[] = []
+ // A test that must observe the by-id lookup mid-flight sets this so the mock waits to respond.
+ let holdChannelIdLookup: Promise<void> | null = null
beforeEach(() => {
channelsRequestSearchQueries = []
channelIdLookups = []
+ holdChannelIdLookup = null
useMocks({
get: {
- '/api/environments/:team_id/integrations/:id/channels': ({ request }) => {
+ '/api/environments/:team_id/integrations/:id/channels': async ({ request }) => {
const url = new URL(request.url)
const search = url.searchParams.get('search')
const channelId = url.searchParams.get('channel_id')
if (channelId) {
channelIdLookups.push(channelId)
+ if (holdChannelIdLookup) {
+ await holdChannelIdLookup
+ }
const match =
CHANNELS.find((c) => c.id === channelId) ??
(OFF_PAGE_CHANNEL.id === channelId ? OFF_PAGE_CHANNEL : null)
@@ -321,6 +327,10 @@ describe('SlackChannelPicker', () => {
{ settles: 'a channel', pastedId: OFF_PAGE_CHANNEL.id, reportsDroppedSearch: false },
{ settles: 'nothing', pastedId: 'CNOSUCHCHAN', reportsDroppedSearch: true },
])('pasting an id that settles on $settles, then clicking away', async ({ pastedId, reportsDroppedSearch }) => {
+ let releaseChannelIdLookup: () => void = () => {}
+ holdChannelIdLookup = new Promise<void>((resolve) => {
+ releaseChannelIdLookup = resolve
+ })
const onChange = jest.fn()
const { container } = render(
<Provider>
@@ -333,8 +343,9 @@ describe('SlackChannelPicker', () => {
await userEvent.paste(pastedId)
await userEvent.click(document.body)
- // The lookup is still in flight here, so neither outcome may show the message yet.
+ // The lookup is held in flight here, so neither outcome may show the message yet.
expect(screen.queryByText('No channel selected. Pick one from the list.')).toBeNull()
+ releaseChannelIdLookup()
if (reportsDroppedSearch) {
expect(
diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.store.test.ts b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.store.test.ts
index de3d6413b36a..aed74b599d94 100644
--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.store.test.ts
+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.store.test.ts
@@ -65,6 +65,7 @@ describe('snapshotDataLogic (store-based loading)', () => {
afterEach(() => {
logic?.unmount()
+ jest.useRealTimers()
})
describe('initialization', () => {
@@ -304,6 +305,8 @@ describe('snapshotDataLogic (store-based loading)', () => {
})
it('re-arms the next poll after a poll returns unchanged sources', async () => {
+ jest.useFakeTimers()
+
// polling-enabled instance, unlike the shared harness
logic = snapshotDataLogic({ sessionRecordingId: 'store-test-polling' })
logic.mount()
@@ -313,14 +316,18 @@ describe('snapshotDataLogic (store-based loading)', () => {
store.setSources([SOURCE_A])
markLoaded(store, 0, [makeFullSnapshot(tsMs(0, 0))])
- await expectLogic(logic, () => {
+ const firstPoll = expectLogic(logic, () => {
logic.actions.loadSnapshotSourcesSuccess([SOURCE_A])
}).toDispatchActions(['maybeStartPolling', 'startPolling'])
+ await jest.advanceTimersByTimeAsync(1)
+ await firstPoll
// a poll response with the same source list must close this cycle and arm the next one
- await expectLogic(logic, () => {
+ const nextPoll = expectLogic(logic, () => {
logic.actions.loadSnapshotSourcesSuccess([SOURCE_A])
}).toDispatchActions(['stopPolling', 'maybeStartPolling', 'startPolling'])
+ await jest.advanceTimersByTimeAsync(1)
+ await nextPoll
})
})
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
index 439f42507a38..72c8b6c6bd3e 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
@@ -1089,7 +1089,7 @@ describe('sessionRecordingsPlaylistLogic', () => {
onRecordingSelected,
})
logic.mount()
- await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()
expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])
// A facet can match nothing: the player unloads into the empty state. When the next
@@ -1101,14 +1101,16 @@ describe('sessionRecordingsPlaylistLogic', () => {
ReturnType<typeof api.recordings.list>
>)
logic.actions.loadSessionRecordings()
- await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()
+ expect(logic.values.sessionRecordings).toEqual([])
+ expect(logic.values.activeSessionRecordingId).toBeUndefined()
expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])
listSpy.mockResolvedValueOnce({ results: listOfSessionRecordings, has_next: false } as Awaited<
ReturnType<typeof api.recordings.list>
>)
logic.actions.loadSessionRecordings()
- await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()
expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id], [aRecording.id]])
})
diff --git a/frontend/src/test/keaTestListeners.test.ts b/frontend/src/test/keaTestListeners.test.ts
new file mode 100644
index 000000000000..5ad52acdea7e
--- /dev/null
+++ b/frontend/src/test/keaTestListeners.test.ts
@@ -0,0 +1,78 @@
+import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
+
+import { initKeaTests } from '~/test/init'
+
+type breakpointTestLogicType = MakeLogicType<
+ { completedValue: string | null },
+ {
+ start: (value: string) => { value: string }
+ complete: (value: string) => { value: string }
+ }
+>
+
+const breakpointTestLogic = kea<breakpointTestLogicType>([
+ path(['test', 'keaTestListeners', 'breakpointTestLogic']),
+ actions({
+ start: (value: string) => ({ value }),
+ complete: (value: string) => ({ value }),
+ }),
+ reducers({
+ completedValue: [null as string | null, { complete: (_, { value }) => value }],
+ }),
+ listeners(({ actions }) => ({
+ start: async ({ value }, breakpoint) => {
+ await breakpoint(60_000)
+ actions.complete(value)
+ },
+ })),
+])
+
+const legacyBreakpointTestLogic = kea<breakpointTestLogicType>({
+ path: ['test', 'keaTestListeners', 'legacyBreakpointTestLogic'],
+ actions: {
+ start: (value: string) => ({ value }),
+ complete: (value: string) => ({ value }),
+ },
+ reducers: {
+ completedValue: [null as string | null, { complete: (_, { value }) => value }],
+ },
+ listeners: ({ actions }) => ({
+ start: async ({ value }, breakpoint) => {
+ await breakpoint(60_000)
+ actions.complete(value)
+ },
+ }),
+})
+
+describe('Kea test listeners', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it.each([
+ ['builder-form logic', breakpointTestLogic],
+ ['legacy object-form logic', legacyBreakpointTestLogic],
+ ])('runs delayed breakpoints on the next timer task and keeps cancellation for %s', async (_, logicBuilder) => {
+ const setTimeoutSpy = jest.spyOn(global, 'setTimeout').mockImplementation((callback, delay, ...args) => {
+ if (delay === 0) {
+ callback(...args)
+ }
+ return 0 as unknown as NodeJS.Timeout
+ })
+ const logic = logicBuilder()
+ logic.mount()
+
+ logic.actions.start('first')
+ logic.actions.start('second')
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(setTimeoutSpy).toHaveBeenCalledTimes(2)
+ expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 0)
+ expect(logic.values.completedValue).toBe('second')
+ })
+})
diff --git a/frontend/src/test/keaTestListeners.ts b/frontend/src/test/keaTestListeners.ts
new file mode 100644
index 000000000000..85c1811b51b6
--- /dev/null
+++ b/frontend/src/test/keaTestListeners.ts
@@ -0,0 +1,46 @@
+import type { BreakPointFunction, ListenerFunction, Logic, LogicBuilder, LogicInput } from 'kea'
+
+type ListenersBuilder = <L extends Logic = Logic>(input: LogicInput<L>['listeners']) => LogicBuilder<L>
+
+function hasFakeTimers(): boolean {
+ return 'clock' in setTimeout
+}
+
+function fastBreakpoint(breakpoint: BreakPointFunction): BreakPointFunction {
+ return ((ms?: number): Promise<void> | void => {
+ if (ms === undefined) {
+ return breakpoint()
+ }
+ return breakpoint(0)
+ }) as BreakPointFunction
+}
+
+function wrapListener(listener: ListenerFunction): ListenerFunction {
+ return (payload, breakpoint, action, previousState) =>
+ listener(payload, hasFakeTimers() ? breakpoint : fastBreakpoint(breakpoint), action, previousState)
+}
+
+export function testListenerDefinitions<L extends Logic = Logic>(
+ input: LogicInput<L>['listeners']
+): LogicInput<L>['listeners'] {
+ return ((logic: L) => {
+ const listeners = (typeof input === 'function' ? input(logic) : input) as Record<
+ string,
+ ListenerFunction | ListenerFunction[]
+ >
+ return Object.fromEntries(
+ Object.entries(listeners).map(([action, listener]) => [
+ action,
+ Array.isArray(listener) ? listener.map((item) => wrapListener(item)) : wrapListener(listener),
+ ])
+ )
+ }) as LogicInput<L>['listeners']
+}
+
+export function testListeners(listenersBuilder: ListenersBuilder): ListenersBuilder {
+ return function listenersWithoutDelays<L extends Logic = Logic>(
+ input: LogicInput<L>['listeners']
+ ): LogicBuilder<L> {
+ return listenersBuilder<L>(testListenerDefinitions(input))
+ }
+}
diff --git a/frontend/src/test/keaTestModule.js b/frontend/src/test/keaTestModule.js
new file mode 100644
index 000000000000..6b8b3de9e82a
--- /dev/null
+++ b/frontend/src/test/keaTestModule.js
@@ -0,0 +1,16 @@
+const kea = require('../../node_modules/kea')
+const { testListenerDefinitions, testListeners } = require('./keaTestListeners')
+
+function wrapLogicInput(input) {
+ if (!input || typeof input !== 'object' || input.listeners === undefined) {
+ return input
+ }
+ return { ...input, listeners: testListenerDefinitions(input.listeners) }
+}
+
+function testKea(input) {
+ return kea.kea(Array.isArray(input) ? input.map(wrapLogicInput) : wrapLogicInput(input))
+}
+
+/** @type {typeof kea & { __esModule: true }} */
+module.exports = { ...kea, __esModule: true, kea: testKea, listeners: testListeners(kea.listeners) }