: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
chore(skills): add writing-kea-logics skill (#58707)
Paul D'Ambra1358f6712b58
diff --git a/.agents/skills/writing-kea-logics/SKILL.md b/.agents/skills/writing-kea-logics/SKILL.mdnew file mode 100644index 000000000000..e4a61dd5d4f8--- /dev/null+++ b/.agents/skills/writing-kea-logics/SKILL.md@@ -0,0 +1,177 @@+---+name: writing-kea-logics+description: Guide for writing or reviewing PostHog kea logic files (`*Logic.ts` / `*Logic.tsx`). Use when creating a new logic, adding actions/reducers/selectors/listeners/loaders/forms/router bindings, choosing between reducer vs selector vs cache, deciding between listeners and `kea-subscriptions`, wiring React with `useValues`/`useActions`/`BindLogic`, or onboarding to kea conventions. Read keajs.org for upstream API; this skill captures PostHog-specific conventions and idioms.+---++# Writing kea logics++PostHog uses [kea](https://keajs.org) as the state container for the frontend. Almost+all non-trivial business logic lives in a `*Logic.ts` / `*Logic.tsx` file, not in+React. We may be on a kea pre-release ahead of the version the keajs.org docs+cover — when in doubt, check `pnpm-workspace.yaml` for the pinned version.++This skill captures the PostHog-specific conventions on top of the upstream+[kea docs](https://keajs.org). When in doubt about a builder's signature, go upstream.+When in doubt about whether to use it, read here.++## Use this skill when++- Creating a new `*Logic.ts` / `*Logic.tsx` file+- Adding builders to an existing logic (actions, reducers, selectors, listeners, loaders, forms)+- Choosing between `reducer` vs `selector` vs `cache` vs `loader` for a piece of state+- Wiring a React component to a logic+- Reviewing a PR that introduces or modifies a kea logic+- Reviewing code that uses React hooks where a logic would be more idiomatic++## Companion skills (do not duplicate)++- [using-kea-disposables](../using-kea-disposables/SKILL.md) — `setInterval`, `addEventListener`,+ and any other resource that needs cleanup.+- [making-scenes-tab-aware](../making-scenes-tab-aware/SKILL.md) — scene root logics keyed by+ `tabId`, `tabAwareUrlToAction`/`tabAwareActionToUrl`, `useAttachedLogic`.++If your work overlaps either of those, read the companion skill first.++## Core principles++1. **Business logic lives in a logic, not in a component.**+ [CLAUDE.md](../../../CLAUDE.md) is explicit: "If there is a kea logic file, write all+ business logic there, avoid React hooks at all costs." Hooks are for view concerns.++2. **One concept, one source of truth.** Pick exactly one of: action-driven reducer,+ derived selector, async loader. Don't mirror the same value into multiple places.++3. **Prefer listeners over `kea-subscriptions`.** Subscriptions install a redux+ subscription that re-runs on every dispatch and is measurably slower. Listen to the+ action that changed the value instead. See+ [references/reacting-to-changes.md](references/reacting-to-changes.md).++4. **Generated types are the contract.** Every logic has an auto-generated+ `*LogicType.ts` next to it. Import with `import type` and pass it as the kea type+ parameter. Never edit the generated file.++5. **Resources that need cleanup go through `cache.disposables`.** See the+ [using-kea-disposables](../using-kea-disposables/SKILL.md) skill.++## Anatomy at a glance++```ts+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import type { fooLogicType } from './fooLogicType'++export interface FooLogicProps {+ fooId: string+}++export const fooLogic = kea<fooLogicType>([+ props({} as FooLogicProps),+ key((props) => props.fooId),+ path((key) => ['scenes', 'foo', 'fooLogic', key]),+ connect(() => ({ values: [teamLogic, ['currentTeamId']] })),+ actions({ setName: (name: string) => ({ name }) }),+ loaders(({ props }) => ({+ foo: [null as Foo | null, { loadFoo: async () => api.foos.get(props.fooId) }],+ })),+ reducers({ name: ['', { setName: (_, { name }) => name }] }),+ selectors({ nameUpper: [(s) => [s.name], (name): string => name.toUpperCase()] }),+ listeners(({ actions }) => ({+ loadFooSuccess: () => {+ /* ... */+ },+ })),+ afterMount(({ actions }) => {+ actions.loadFoo()+ }),+])+```++Conventional block order: `props` → `key` → `path` → `connect` → `actions` → `forms` → `loaders` →+`reducers` → `selectors` → `sharedListeners` → `listeners` → `subscriptions` (rare) →+`windowValues` → `urlToAction` / `actionToUrl` → `afterMount` / `propsChanged` / `beforeUnmount`.++You almost never need all of those — half a dozen blocks is typical. Pick the ones+the logic actually uses and leave the rest out.++## Decision flow — pick the right container before you start++Most kea bugs come from picking the wrong container for a piece of state. Work+through this before reaching for any builder:++1. **Does it come from an HTTP call?** Use a [loader](references/loading-data.md).+2. **Can it be computed from other state?** Use a `selector`.+3. **Does an action change it, and does the UI need to re-render when it changes?**+ Use a `reducer`.+4. **Is it a timer, listener, or other disposable resource?** Use `cache.disposables`+ — see [using-kea-disposables](../using-kea-disposables/SKILL.md).++`cache.foo` is an escape hatch for transient flags the UI never reads — reach for it+last, not first. See [references/state-decision.md](references/state-decision.md)+for the full breakdown.++## Pattern index++Each reference covers one job-to-be-done with the pattern shape, why it's the right+shape, and the trade-offs. File citations inside references are "examples in the wild+today" — they age, so the pattern itself is the source of truth.++| You want to... | Read |+| -------------------------------------------------- | ---------------------------------------------------------------------- |+| Decide between reducer / selector / cache / loader | [references/state-decision.md](references/state-decision.md) |+| Load data from the API | [references/loading-data.md](references/loading-data.md) |+| Poll an endpoint or refresh on an interval | [references/polling.md](references/polling.md) |+| Build a form | [references/forms.md](references/forms.md) |+| Sync state with the URL | [references/routing.md](references/routing.md) |+| Persist state across reloads | [references/persisting-state.md](references/persisting-state.md) |+| React to a value change | [references/reacting-to-changes.md](references/reacting-to-changes.md) |+| Have multiple instances of one logic | [references/keyed-logics.md](references/keyed-logics.md) |+| Share state across logics or a component subtree | [references/connecting-logics.md](references/connecting-logics.md) |+| Test the logic | [references/testing.md](references/testing.md) |+| Recognise a pattern you should convert on sight | [references/anti-patterns.md](references/anti-patterns.md) |++## Types and typegen++```ts+import type { fooLogicType } from './fooLogicType'+export const fooLogic = kea<fooLogicType>([...])+```++Generated `*LogicType.ts` files are produced by `kea-typegen` (we use the+`3.6.2-leakfix.x` private fork). Commands:++- `pnpm --filter=@posthog/frontend typegen:watch` — watch mode while writing logics+- `pnpm --filter=@posthog/frontend typegen:write` — one-shot write+- `pnpm --filter=@posthog/frontend typegen:check` — CI parity check++### Iterating on one logic — skip the full scan++Full typegen + `tsc --noEmit` over the whole codebase is slow. When you're iterating+on a single logic, scope both to that file:++```sh+# Regenerate the type for one logic+pnpm --filter=@posthog/frontend exec kea-typegen write \+ -f frontend/src/scenes/foo/fooLogic.ts -r ./frontend/src++# Type-check just that file (and its imports — fast, but won't catch downstream+# breakage in other files that consume the new types)+pnpm --filter=@posthog/frontend exec tsc --noEmit \+ frontend/src/scenes/foo/fooLogic.ts+```++Use this loop while writing the logic; run the full `typegen:check` /+`typescript:check` once at the end to confirm nothing else broke.++Never edit a `*LogicType.ts` file by hand — change the logic and re-run typegen.++For keyed logics, annotate the export explicitly:+`export const fooLogic: LogicWrapper<fooLogicType> = kea<fooLogicType>([...])`.++## When in doubt++- Read the relevant reference above before inventing a new pattern.+- Read the upstream [keajs.org](https://keajs.org) docs for builder signatures.+- Search the repo for the builder name in `*Logic.ts` — there are hundreds of working+ examples and the conventions are stable.+- For state-management decisions, favour the option that lets you delete code elsewhere.diff --git a/.agents/skills/writing-kea-logics/references/anti-patterns.md b/.agents/skills/writing-kea-logics/references/anti-patterns.mdnew file mode 100644index 000000000000..05ded1ecaf02--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/anti-patterns.md@@ -0,0 +1,453 @@+# Anti-patterns — convert on sight++This is the list of shapes that look reasonable but cause specific real problems.+When you see one in code you're reviewing or working in, convert it.++## State containers++### Bare `setInterval` / `setTimeout` with `beforeUnmount` cleanup++```ts+// don't+afterMount(({ actions, cache }) => {+ cache.timer = setInterval(() => actions.poll(), 5000)+}),+beforeUnmount(({ cache }) => clearInterval(cache.timer)),+```++Use `cache.disposables` instead — handles cleanup and auto-pauses on hidden tabs.+See [using-kea-disposables](../../using-kea-disposables/SKILL.md).++### Reducer mirroring a loader's value++```ts+// don't+loaders({ foo: [null, { loadFoo: async () => api.get() }] }),+reducers({ foo: [null, { loadFooSuccess: (_, { foo }) => foo }] }), // duplicate+```++The loader already gives you `foo`, `fooLoading`, and the success/failure actions.+Delete the reducer.++### `isLoadingFoo` reducer alongside a loader++```ts+// don't+reducers({+ isLoadingFoo: [false, { loadFoo: () => true, loadFooSuccess: () => false }],+})+```++`fooLoading` exists already.++### Reducer that's a deterministic function of other state++```ts+// don't+reducers({+ fullName: [+ '',+ {+ setFirstName: (state, { first }) => `${first} ${state.split(' ')[1] ?? ''}`,+ setLastName: (state, { last }) => `${state.split(' ')[0] ?? ''} ${last}`,+ },+ ],+})+```++Selector. See [state-decision.md](state-decision.md).++### `cache.foo` used to render UI++```ts+// don't+listeners(({ cache, actions }) => ({+ open: () => {+ cache.isOpen = true+ }, // no re-render!+}))+// then in component: cache.isOpen — won't update+```++`cache` has no subscription. Use a reducer.++### `try`/`catch` around the whole loader handler++```ts+// don't+loadFoo: async () => {+ try {+ return await api.foos.get(props.fooId)+ } catch (e) {+ return null+ }+},+```++`kea-loaders` already catches and emits `loadFooFailure` with the error. Listen for+that action if you need custom handling, and only re-throw inside the handler if you+genuinely need to abort the loader machinery.++### Non-async logic in a loader++If the handler doesn't `await` anything, it's a reducer or selector wearing a loader's+hat. Loaders are for async — the action/success/failure trio and the `xLoading` boolean+are noise when the work is synchronous.++## Loading data and persistence++### `localStorage.setItem` directly inside a listener++Two tabs will race; serialisation is your problem; you've reinvented `{ persist: true }`.+Use the kea-localstorage plugin — second slot of a reducer tuple.++### Persisted loader results++```ts+// don't+foo: [+ null as Foo | null,+ { persist: true }, // serves stale data on next mount+ { loadFooSuccess: (_, { foo }) => foo },+],+```++Loaders re-fetch on mount anyway, so persisting the value just shows stale data+during the gap. Persist only if the previous value is genuinely better than a loading+spinner.++### Persisting a selector++Selectors aren't reducers. Persist the inputs and recompute.++### `window.matchMedia(...)` registered without going through `cache.disposables`++Same shape as bare `setInterval` — you'll leak a listener on unmount. Wrap the+`addEventListener` / `removeEventListener` pair in `cache.disposables.add(...)`. See+[using-kea-disposables](../../using-kea-disposables/SKILL.md).++## Reactions++### `subscriptions` reacting to a value set by an action++```ts+// don't+subscriptions(({ actions }) => ({+ foo: (foo) => {+ if (foo) actions.processFoo()+ },+}))+```++Listen to the action that sets `foo` instead. See+[reacting-to-changes.md](reacting-to-changes.md).++### `subscriptions` in a `products/*` logic++```ts+import { subscriptions } from 'kea-subscriptions' // build fails+```++`kea-subscriptions` is only in `frontend/`. Use listeners.++### `useEffect` in a component reacting to a logic value++```tsx+// don't+const { foo } = useValues(fooLogic)+useEffect(() => {+ if (foo) doSideEffectFoo()+}, [foo])+```++That's a listener. Move it into the logic.++### `propsChanged` body that doesn't guard++```ts+// don't+propsChanged(({ actions, props }) => {+ actions.loadFoo() // fires on every parent re-render+})+```++Guard with `props.fooId !== oldProps.fooId`. React will re-render with referentially+different but structurally equal props.++### A listener that just dispatches one other action++```ts+// smells off+listeners(({ actions }) => ({+ setX: ({ x }) => actions.setY(x),+}))+```++Sometimes this is the right shape — adapting payload shape across a logic boundary, or+re-firing a connected action you don't own. But if you do own both actions and they+take the same args, this is a hint that the action shape is wrong. Check whether you+can rename the upstream action, or whether two callers should share a body via+`sharedListeners`.++### Polling without a stop condition++If the thing you're waiting on can finish (a job, a migration, a build), listen for+the terminal state and `cache.disposables.dispose('pollKey')`. Otherwise the poller+hammers the API indefinitely while the page is open.++### Polling on a singleton when only a subset of views need fresh data++Mount the polling logic from the view that needs it (via `useMountedLogic` or+`useValues`) so the timer is scoped to where it matters.++### `setInterval(... 0)` as "next tick"++If you need to act on the next event-loop turn, use a listener on the action that+should trigger the work, or `requestAnimationFrame` for frame-boundary cases.+`setInterval(0)` is a wasted timer.++## Keying++### Keyed logic with no key in the path++```ts+// don't+key((props) => props.fooId),+path(['scenes', 'foo', 'fooLogic']), // key not visible in path+```++Instance identity is handled by `key`, but PostHog convention is to also append the+key to `path` so the key shows up in redux devtools, in typegen output, and in any+log lines that include the logic path. Use `path((key) => ['...', key])`.++### `key` reading from `window`, locals, or another logic++```ts+// don't+key(() => window.currentFooId),+```++Keys must be derivable from props alone. Anything else and two callers with the same+props get different instances — or worse, the same instance when they shouldn't.++### Different key shapes across callers++```ts+// don't+key((props) => props.fooId)+// elsewhere: `${props.fooId}-${props.mode}` for the same logic+```++Pull the key derivation into a helper. Inconsistent keys mean callers don't talk to+the same instance.++### Mounting a keyed logic with `fooLogic()` (no props)++Same as `fooLogic({})` — keys to `undefined`. All such callers share one phantom+instance. Always pass props at the call site.++### Forgetting to type the export when the logic is keyed++```ts+// don't (call-site types end up as any)+export const fooLogic = kea<fooLogicType>([+ props({} as FooLogicProps),+ key((props) => props.fooId),+ // ...+])+```++```ts+// do+export const fooLogic: LogicWrapper<fooLogicType> = kea<fooLogicType>([...])+```++## Routing++### Hard-coded URLs++```ts+// don't+urlToAction(({ actions }) => ({ '/foos/:id': ({ id }) => actions.openFoo(id) }))+```++Use `urls.foo(id)` so renames in one place propagate everywhere.++### `actionToUrl` / `urlToAction` feedback loop++The classic: `setQuery` updates URL → URL change fires `setQuery` again → infinite+loop. See [routing.md](routing.md) for guard patterns.++### Plain `urlToAction` on a scene root logic++Scene roots own the URL. Use `tabAwareUrlToAction` so inactive tabs don't hijack+navigation. See [making-scenes-tab-aware](../../making-scenes-tab-aware/SKILL.md).++### Mutating `window.location` directly++```ts+// don't+window.location.href = '/foos/' + id+```++Bypasses kea-router entirely — `urlToAction` won't fire. Use `router.actions.push`.++### `useNavigate` / `useParams` in a component when there's a logic++URL is logic state. Move the reaction to `urlToAction` and the navigation to+`actionToUrl` (or `router.actions.push` inside a listener) so the logic owns the+behaviour and the component shrinks back to view code.++## Forms++### Validation in the submit handler++```ts+// don't+submit: async (values) => {+ if (!values.email) throw new Error('Email required')+ await api.send(values)+}+```++Validation belongs in `errors`. Submit is for the work.++### Returning `''` from `errors`++```ts+errors: ({ email }) => ({ email: email ? '' : 'Required' }) // '' is not undefined — counts as a present error+```++`kea-forms` treats any non-`undefined` value in the errors map as a present error,+so `''` and `'Required'` both make the field invalid. Return `undefined` for+"no error".++### Side effects inside `errors`++`errors` re-runs on every keystroke. Keep it pure — no logging, no analytics, no+async work. Reach for a listener on `setFooValues` if you need to react to typing.++### `useState` for form values++```tsx+// don't+const [email, setEmail] = useState('')+const [name, setName] = useState('')+```++That's a `forms` builder waiting to be written.++### Manual `setFoo` / `setFooValue` chains instead of `<Field>`++```tsx+// don't+<LemonInput value={values.signup.email} onChange={(v) => actions.setSignupValue('email', v)} />+```++`<Field name="email">` already wires the change handler. Use it; the component shrinks.++## Types++### Editing `*LogicType.ts` by hand++It's regenerated by `kea-typegen`. Your changes will be wiped. Change the logic and+re-run typegen.++### Importing the runtime logic when you only need its type++```ts+// don't+import { fooLogic } from './fooLogic'+type FooState = ReturnType<typeof fooLogic.build>['values']+```++```ts+// do+import type { fooLogicType } from './fooLogicType'+type FooState = fooLogicType['values']+```++Importing the runtime forces it to load even if you never call it.++## Mounting and unmounting++### `.mount()` with no stored `unmount`++```ts+// don't+otherLogic.build(props).mount() // leaks+```++Always store the return value and dispose it, ideally via `cache.disposables`.++### Calling `initKea` outside `initKea.ts` / `initKeaTests`++```ts+// don't+import { initKea } from 'initKea'+initKea() // resets the entire store+```++Blows away every mounted logic in the app.++## React integration++### `BindLogic` for a singleton++Singletons have one instance. `BindLogic` is for keyed logics. For singletons, just+call `useValues(fooLogic)`.++### Reading another logic's state from a render function++```tsx+// don't+function FooView(): JSX.Element {+ const x = otherLogic.values.x // no subscription — won't re-render when x changes+ return <div>{x}</div>+}+```++Use `useValues(otherLogic)` so the component subscribes and re-renders on change.++### `useEffect` to mount another logic and dispatch an action++```tsx+// don't+useEffect(() => {+ otherLogic(props).actions.x()+}, [])+```++Use `useMountedLogic(otherLogic)` to manage the lifecycle, plus `useActions` to call+the action — or do the mounting inside a logic that owns the relationship.++### `connect.values: [otherLogic, ['everything']]` copy-paste++Pull only the names you actually use. The generated types are tighter, downstream+refactors stay obvious, and unused names won't trigger spurious re-renders.++### Business logic in `useEffect`++If the body of a `useEffect` does anything beyond mounting / focus / DOM, it+probably belongs in a logic listener.++## History++The patterns banned here aren't theoretical — most have a PR behind them where the+thing went wrong in real code:++- [PR #38754](https://github.com/PostHog/posthog/pull/38754) — introduced the+ disposables plugin to replace bare `setInterval` + `beforeUnmount` cleanup.+- [PR #40284](https://github.com/PostHog/posthog/pull/40284) — added auto-pause on+ hidden tab to disposables. This is why polling through `cache.disposables`+ doesn't waste cycles when the user switches away.+- [PR #58691](https://github.com/PostHog/posthog/pull/58691) — fixed a subtle bug+ where disposables registered while the page was hidden would still start+ immediately, defeating the auto-pause.+- [PR #48042](https://github.com/PostHog/posthog/pull/48042) — canonical example of+ converting a "bare `setInterval` poll" to `cache.disposables` (the managed-migrations+ logic). Read this alongside the disposables skill if you're doing the same+ conversion in another product.+- Commit [`7ef47b68e75`](https://github.com/PostHog/posthog/commit/7ef47b68e75) —+ why `kea-subscriptions` doesn't work inside a `products/*` logic, and the+ listener-based fix.diff --git a/.agents/skills/writing-kea-logics/references/connecting-logics.md b/.agents/skills/writing-kea-logics/references/connecting-logics.mdnew file mode 100644index 000000000000..524a0a7713d2--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/connecting-logics.md@@ -0,0 +1,132 @@+# Connecting logics and React++Two parts to this: kea-to-kea (`connect`, imperative mounting) and kea-to-React+(`useValues`, `useActions`, `BindLogic`).++## Pulling values and actions from another logic — `connect`++```ts+connect(() => ({+ values: [teamLogic, ['currentTeamId', 'currentTeam'], userLogic, ['user']],+ actions: [teamLogic, ['loadCurrentTeam']],+ logic: [eventUsageLogic], // mount-only, no values pulled+}))+```++- **Always use the function form `connect(() => ({...}))`.** Defers evaluation past+ module load, so circular imports don't blow up.+- `values: [logic, ['a', 'b'], otherLogic, ['c']]` flattens — each logic followed by+ its names. The names become available on `values` inside the logic.+- `actions: [logic, ['x']]` lets you both dispatch `actions.x()` and listen for `x`+ in your own `listeners`.+- `logic: [otherLogic]` mounts the logic without pulling anything. Use when you need+ the other logic running for its side effects (e.g. analytics, polling).++### Connecting to a keyed logic++```ts+connect((props: FooLogicProps) => ({+ values: [barLogic(props), ['something']],+}))+```++Take props and pass them through to the keyed logic. Same props → same key → same+instance, so you talk to the same one as everyone else with the same props.++## Mounting another logic from inside a logic++When you need a logic's _instance_ (to track it, find it, or hand it to something),+use `.build()` + `.mount()`:++```ts+listeners(({ actions, cache }) => ({+ openInsight: ({ insightId }) => {+ const logic = insightLogic.build({ dashboardItemId: insightId })+ const unmount = logic.mount()+ cache.disposables.add(() => unmount, `insightRef:${insightId}`)+ },+}))+```++- `.build(props)` returns the wrapper without mounting.+- `.mount()` mounts it and returns an unmount function.+- Register the unmount with `cache.disposables` so it's cleaned up automatically.++### `findMounted` — peek without mounting++```ts+const logic = otherLogic.findMounted({ id })+if (logic) {+ actions.doSomething(logic.values.x)+}+```++Returns `undefined` if the logic isn't mounted. Use when "if it happens to be+running, sync with it; otherwise nothing".++## Wiring up React — `useValues` / `useActions`++```tsx+import { useActions, useValues } from 'kea'++function FooView({ fooId }: { fooId: string }): JSX.Element {+ const logic = fooLogic({ fooId }) // for keyed logics+ const { foo, fooLoading } = useValues(logic)+ const { setName } = useActions(logic)+ return <input value={foo?.name ?? ''} onChange={(e) => setName(e.target.value)} />+}+```++For singletons, drop the `(props)`: `useValues(fooLogic)`.++These hooks are how a component subscribes to a logic. `useValues` re-renders the+component when the chosen values change; `useActions` returns stable action refs.++## `BindLogic` — provide a keyed instance to a subtree++If a parent component knows the key and its children don't want to thread props+everywhere, wrap them in `BindLogic`:++```tsx+<BindLogic logic={fooLogic} props={{ fooId }}>+ <FooHeader /> {/* useValues(fooLogic) resolves to the bound instance */}+ <FooDetails />+ <FooFooter />+</BindLogic>+```++Inside the subtree, `useValues(fooLogic)` (no props) works because `BindLogic` set+the context.++Nest `BindLogic` when you have multiple keyed dependencies:++```tsx+<BindLogic logic={dataNodeLogic} props={dataNodeProps}>+ <BindLogic logic={dataVisualizationLogic} props={vizProps}>+ <SQLEditor />+ </BindLogic>+</BindLogic>+```++## `useMountedLogic` — own the logic lifecycle++```tsx+function FooHost(): JSX.Element {+ useMountedLogic(fooLogic) // mounts on mount, unmounts on unmount+ return <FooView />+}+```++Use when a logic should live exactly as long as a particular component, and no one+else is going to mount it. `useValues` and `useActions` already mount as a side+effect, so `useMountedLogic` is only needed when no values are pulled.++## `useAttachedLogic` — keep a logic mounted through the scene++For scene-level child logics that must survive React unmounts during tab switching,+use `useAttachedLogic`. See+[making-scenes-tab-aware](../../making-scenes-tab-aware/SKILL.md).++## Anti-patterns++See [anti-patterns.md](anti-patterns.md) for the consolidated catalogue.diff --git a/.agents/skills/writing-kea-logics/references/forms.md b/.agents/skills/writing-kea-logics/references/forms.mdnew file mode 100644index 000000000000..ec2e8517d29d--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/forms.md@@ -0,0 +1,114 @@+# Forms++Use `kea-forms` for any form. It manages values, validation, submission state, and+success/failure actions in one builder. Hand-rolling a form means rebuilding all of+that for no good reason.++## Why a forms builder and not reducers + listeners++A `forms` builder named `foo` generates:++- `fooValues` — current values+- `fooValidationErrors` — keyed by field, computed from `errors`+- `fooHasErrors` — boolean+- `setFooValues({ a: 1 })` / `setFooValue('a', 1)` — partial updates+- `submitFoo()` / `submitFooSuccess` / `submitFooFailure`+- `isFooSubmitting` — boolean+- `resetFoo(defaults?)` — back to defaults+- `<Form logic={fooLogic} formKey="foo">` and `<Field name="...">` on the component side++You can't beat that with hand-written reducers without rewriting all of it.++## Basic shape++```ts+import { forms } from 'kea-forms'++export interface SignupForm {+ email: string+ organization_name: string+}++forms(() => ({+ signup: {+ defaults: { email: '', organization_name: '' } as SignupForm,+ errors: ({ email, organization_name }) => ({+ email: !email ? 'Please enter your email' : undefined,+ organization_name: !organization_name ? 'Please enter your org' : undefined,+ }),+ submit: async (formValues) => {+ await api.create('api/social_signup/', formValues)+ },+ },+})),+```++- `defaults` — initial values (typed).+- `errors` — function from values to a per-field error object. Return `undefined`+ for "no error" — never an empty string.+- `submit` — async function; throws are caught by the plugin and surface as+ `submitFooFailure`.++## Field-dependent and conditional errors++```ts+errors: ({ source_type, s3_bucket, access_key }) => ({+ source_type: !source_type ? 'Pick a source' : undefined,+ s3_bucket: source_type === 's3' && !s3_bucket ? 'Bucket required' : undefined,+ access_key: source_type === 's3' && !access_key ? 'Access key required' : undefined,+}),+```++The errors function re-runs on every value change, so it naturally supports cross-field+validation. Keep it pure — no I/O, no `Math.random()`.++## Reacting to submit success or failure++```ts+listeners(({ actions }) => ({+ submitSignupSuccess: () => {+ router.actions.push(urls.home())+ },+ submitSignupFailure: ({ error }) => {+ lemonToast.error(error.message ?? 'Something went wrong')+ },+})),+```++Don't put navigation or toasts inside `submit` — let the success/failure listeners+handle them. Submit is for the actual work; reacting to outcomes is a listener concern.++## Resetting++```ts+listeners(({ actions }) => ({+ submitSignupSuccess: () => {+ actions.resetSignup() // back to defaults+ // or: actions.resetSignup({ email: values.signup.email }) // partial reset+ },+})),+```++## On the component side++```tsx+import { Form, Field } from 'kea-forms'+;<Form logic={signupLogic} formKey="signup" enableFormOnSubmit>+ <Field name="email" label="Email">+ <LemonInput type="email" />+ </Field>+ <Field name="organization_name" label="Org">+ <LemonInput />+ </Field>+ <LemonButton type="primary" htmlType="submit" loading={isSignupSubmitting}>+ Sign up+ </LemonButton>+</Form>+```++`enableFormOnSubmit` makes Enter submit the form. Use it unless you have a reason+not to.++## Anti-patterns++See [anti-patterns.md](anti-patterns.md) for the consolidated catalogue.diff --git a/.agents/skills/writing-kea-logics/references/keyed-logics.md b/.agents/skills/writing-kea-logics/references/keyed-logics.mdnew file mode 100644index 000000000000..5922b309b9f5--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/keyed-logics.md@@ -0,0 +1,142 @@+# Keyed logics — many instances of one logic++Most logics are singletons — one global instance, accessed everywhere. But when you+need one instance per resource (per insight, per dashboard, per chat thread), you+key the logic by the resource id.++## Why a keyed logic and not a singleton++A singleton holding `currentFooId` and `currentFoo` works for one foo at a time.+Open two foos side-by-side (split view, tab system) and they fight over the same+state.++A keyed logic creates an independent instance per key — same code, separate state,+separate listeners, separate cache. The redux store puts each instance under its own+path.++## The minimum keyed shape++```ts+import { actions, kea, key, path, props, reducers } from 'kea'++import type { fooLogicType } from './fooLogicType'++export interface FooLogicProps {+ fooId: string+}++export const fooLogic = kea<fooLogicType>([+ props({} as FooLogicProps), // 1+ key((props) => props.fooId), // 2+ path((key) => ['scenes', 'foo', 'fooLogic', key]), // 3+ actions({+ /* ... */+ }),+ reducers({+ /* ... */+ }),+])+```++1. **`props({} as FooLogicProps)`** declares the typed default. Always cast — kea+ can't otherwise type-check the props at the `key` function.+2. **`key`** picks one field (or a composite) out of props as the instance+ identifier. Same key → same instance.+3. **`path` includes the key.** Without this, every instance writes to the same+ redux node and they collide. The function form `path((key) => [...])` is what+ wires the key in.++## Calling a keyed logic++```ts+// In another logic+connect((props) => ({ values: [fooLogic(props), ['foo']] }))++// In a component+const logic = fooLogic({ fooId })+const { foo } = useValues(logic)+const { setName } = useActions(logic)+```++`fooLogic(props)` returns the wrapper for that specific instance — same return type+as `fooLogic.build(props)` but lazily mounted on use.++## Composite keys++When a single id isn't enough, build a composite key with a helper that lives next+to the logic:++```ts+// keyForInsightLogicProps.ts+export function keyForInsightLogicProps(defaultKey: string) {+ return (props: InsightLogicProps): string => {+ return props.dashboardItemId ? `${props.dashboardItemId}::${props.dashboard ?? 'no-dashboard'}` : defaultKey+ }+}++// fooLogic.ts+key((props) => keyForInsightLogicProps('new')(props))+```++The helper makes the key predictable and reusable across `connect` calls — anyone+who needs to talk to the same instance can compute the same key.++## Required vs optional keys++```ts+// Throws if fooId is missing — for logics that must have a resource+key((props) => {+ if (!props.fooId) throw new Error('Must init fooLogic with fooId')+ return props.fooId+}),++// Falls back for "new" / "draft" cases+key((props) => props.fooId ?? 'new'),+```++Throwing is friendlier than silently mounting under a key like `undefined`, which+will mysteriously share state across all the places that forgot the prop.++## Reacting to a key or prop change++Two distinct cases — distinguish them:++- **Props change, key stays the same.** Same logic instance, new props. Use+ `propsChanged` to react.+- **Key changes.** A different instance is mounted; the old one is torn down when its+ React subscriber unmounts. `propsChanged` does **not** fire across instances —+ it's a same-instance hook. The new instance gets `afterMount` as usual.++```ts+// Same instance, new props (a non-keyed prop changes):+propsChanged(({ actions, props }, oldProps) => {+ if (props.filter !== oldProps.filter) {+ actions.loadFoo()+ }+}),++// New instance via key change: afterMount fires on the new one as usual+afterMount(({ actions }) => {+ actions.loadFoo()+}),+```++## Typing the export++```ts+export const fooLogic: LogicWrapper<fooLogicType> = kea<fooLogicType>([...])+```++The explicit `LogicWrapper<fooLogicType>` annotation gives you the right overloads+for calling `fooLogic(props)`. For singletons it's not needed; for keyed logics it+makes the call-site types behave.++## Scene root logics keyed by `tabId`++Scene root logics use `tabId` as their key so each internal tab gets its own+instance. This is its own concern — see+[making-scenes-tab-aware](../../making-scenes-tab-aware/SKILL.md).++## Anti-patterns++See [anti-patterns.md](anti-patterns.md) for the consolidated catalogue.diff --git a/.agents/skills/writing-kea-logics/references/loading-data.md b/.agents/skills/writing-kea-logics/references/loading-data.mdnew file mode 100644index 000000000000..5e9cf5b6b443--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/loading-data.md@@ -0,0 +1,113 @@+# Loading data++Use `kea-loaders` for any state whose value comes from an async source (an HTTP call,+a query helper, anything that returns a promise). Don't roll your own+`isLoadingFoo` reducer.++## Why a loader and not a reducer + listener++A loader on a key `foo` generates:++- A reducer `foo` holding the value+- A boolean selector `fooLoading`+- Actions `loadFoo`, `loadFooSuccess`, `loadFooFailure`+- A global error toast wired up via [`initKea.ts`](../../../../frontend/src/initKea.ts)+- Cancellation via `breakpoint` (next dispatch supersedes the previous in-flight one)++Doing this by hand requires three reducers, a listener with manual try/catch, and+no cancellation. Don't.++## Basic shape++```ts+import { loaders } from 'kea-loaders'++loaders(({ values, props }) => ({+ foo: [+ null as Foo | null,+ {+ loadFoo: async () => {+ return await api.foos.get(props.fooId)+ },+ },+ ],+})),+```++The default value (`null as Foo | null`) is the first element of the tuple. The+handlers object is the second. Each handler is an async function that returns the+next value.++## Handlers can take arguments++```ts+loaders(({ values }) => ({+ results: [+ [] as Result[],+ {+ search: async ({ query }: { query: string }) => {+ return await api.search.list({ query })+ },+ },+ ],+})),+```++Calling `actions.search({ query: 'hi' })` invokes the handler with that payload.+The generated `search` action shape mirrors the argument type.++## Debouncing and cancellation with `breakpoint`++```ts+loaders(({ values }) => ({+ results: [+ [] as Result[],+ {+ search: async ({ query }: { query: string }, breakpoint) => {+ await breakpoint(300) // debounce+ const results = await api.search.list({ query })+ breakpoint() // discard if superseded+ return results+ },+ },+ ],+})),+```++- `await breakpoint(ms)` throws `BreakPointError` if `search` fires again within `ms`.+- A bare `breakpoint()` after an `await` throws if a newer action has fired. Use this+ after the response comes back to discard stale results.++This is how you build a search-as-you-type without flicker.++## Error handling++The global `loadersPlugin` config in `initKea.ts` shows a toast for every non-2xx+loader failure, **unless** the action key (e.g. `loadFoo`) is in `ERROR_FILTER_ALLOW_LIST`.++If your loader has its own error UI (a banner, an inline message), add the action key+to `ERROR_FILTER_ALLOW_LIST` in `initKea.ts` so users don't see a duplicate toast.++To react to a failure in your own logic, listen for `loadFooFailure`:++```ts+listeners(({ actions }) => ({+ loadFooFailure: ({ error }) => {+ // your custom UI / retry / metrics+ },+})),+```++## Examples in the wild++To find current examples, grep for `loaders(` in `.ts` and `.tsx` files. Patterns to+look for:++- **Single fetch on mount** — a loader called from `afterMount` with no payload.+- **Paginated / appended** — handler reads `values.thing.next` to fetch the next page+ and merges into existing results.+- **Search with debounce** — handler uses `breakpoint(ms)` early to debounce typing.++## Anti-patterns++See [anti-patterns.md](anti-patterns.md) for the consolidated catalogue.diff --git a/.agents/skills/writing-kea-logics/references/persisting-state.md b/.agents/skills/writing-kea-logics/references/persisting-state.mdnew file mode 100644index 000000000000..7684e7fc18d5--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/persisting-state.md@@ -0,0 +1,83 @@+# Persisting state++Two plugins cover persistence concerns:++- `kea-localstorage` — survive reload by writing a reducer to `localStorage`+- `kea-window-values` — derive values from `window` (`innerWidth`, `fullscreenElement`)+ and stay in sync as the window changes++Both are globally registered in `initKea.ts`, so any logic can use them.++## `{ persist: true }` — survive reload++Make a reducer's value survive page reload by passing `{ persist: true }` as the+second element of the reducer tuple:++```ts+reducers({+ themeMode: [+ 'system' as ThemeMode, // default+ { persist: true }, // persistence config+ { setThemeMode: (_, { themeMode }) => themeMode }, // handlers+ ],+})+```++The plugin writes the value to `localStorage` keyed by the logic's path. On mount it+hydrates the reducer from storage if a value exists, otherwise uses the default.++### When persist is the right answer++- User preferences (theme, sidebar width, default tab)+- Dismissed-once UI (tooltip dismissals, onboarding banners)+- Filter state that should survive reload but isn't worth a URL++### When persist is the wrong answer++- **Server state.** Use a loader. localStorage will go stale immediately and confuse+ the next session.+- **Auth / identity.** That belongs in the API layer (cookies / auth headers).+- **Anything sensitive.** localStorage is plaintext, JS-readable, and synced by some+ browser profiles.+- **State another tab also writes.** localStorage is shared; concurrent writes race.++### Resetting++If you change a reducer's shape, the old value in localStorage will type-mismatch.+Either:++- Add migration logic in the reducer default (read the old shape, transform).+- Change the path (rare — breaks everything else).++Don't silently break — at minimum, the reducer default should be a valid value if+the stored shape doesn't match.++## `windowValues` — read live values from `window`++```ts+import { windowValues } from 'kea-window-values'++windowValues(() => ({+ fullscreen: (window: Window) => !!window.document.fullscreenElement,+ mobileLayout: (window: Window) => window.innerWidth < 992,+})),+```++Each key becomes a selector. The plugin re-evaluates them on `resize` / `scroll` /+`fullscreenchange` and triggers a re-render for subscribers.++### When this is the right answer++- Responsive breakpoints in a logic (so the JSX stays clean)+- Reading `document.fullscreenElement` for fullscreen-aware UI++### When this is the wrong answer++- **Media queries.** `MediaQueryList.addEventListener('change', ...)` via+ `cache.disposables` is more efficient and gives you the exact breakpoint.+- **`window.innerWidth` checks inside a render function.** Use a `windowValues` entry+ so it's reactive.++## Anti-patterns++See [anti-patterns.md](anti-patterns.md) for the consolidated catalogue.diff --git a/.agents/skills/writing-kea-logics/references/polling.md b/.agents/skills/writing-kea-logics/references/polling.mdnew file mode 100644index 000000000000..1e7567388cf0--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/polling.md@@ -0,0 +1,129 @@+# Polling and intervals++When you need to refresh something on a fixed interval (poll a running job, refresh+a count, tick a clock), do it through `cache.disposables`. The disposables plugin+handles cleanup on unmount and **auto-pauses the interval when the tab is hidden**,+which is almost always what you want for polling.++For the full disposables API see the [using-kea-disposables](../../using-kea-disposables/SKILL.md) skill.+The patterns below are kea-side conventions for the common shapes.++## Why not a bare `setInterval`?++```ts+// don't do this+afterMount(({ actions, cache }) => {+ cache.pollTimer = setInterval(() => actions.loadFoo(), 5000)+}),+beforeUnmount(({ cache }) => clearInterval(cache.pollTimer)),+```++Problems:++- Hidden-tab waste: the interval keeps hitting the API while the user is on a different tab.+- Easy to leak: forget the `beforeUnmount` and the timer outlives the logic.+- No way to stop early on a state change (need to track the timer manually).++The disposables plugin solves all three. The patterns below are just the right shape+for common polling jobs.++## Pattern: poll while a flag is true++Use case: a long-running job, an "active" indicator. The polling lives only as long+as the work it's tracking.++```ts+listeners(({ actions, values, cache }) => ({+ startPolling: () => {+ cache.disposables.add(() => {+ const id = setInterval(() => actions.loadStatus(), 5000)+ return () => clearInterval(id)+ }, 'statusPoll')+ },+ stopPolling: () => {+ cache.disposables.dispose('statusPoll')+ },+ loadStatusSuccess: ({ status }) => {+ if (status === 'finished') {+ actions.stopPolling()+ }+ },+})),+```++**Why the named key (`'statusPoll'`):** calling `startPolling` twice replaces the+previous timer instead of running two in parallel. And `dispose('statusPoll')`+stops it without unmounting the whole logic.++## Pattern: poll while mounted++Use case: a heartbeat / counter that runs the whole time the view is open.++```ts+afterMount(({ actions, cache }) => {+ cache.disposables.add(() => {+ const id = setInterval(() => actions.loadCurrentTeam(), 30000)+ return () => clearInterval(id)+ })+}),+```++**No key needed** — the timer is fire-and-forget; the plugin tears it down on+unmount. The auto-pause on hidden tabs means it costs nothing while the user is+elsewhere.++## Pattern: poll on hover only++Use case: a tooltip / popover that wants live data while the cursor is over it.++```ts+listeners(({ actions, cache }) => ({+ setIsHovering: ({ isHovering }) => {+ if (isHovering) {+ cache.disposables.add(() => {+ const id = setInterval(() => actions.setNow(new Date()), 500)+ return () => clearInterval(id)+ }, 'hoverTick')+ } else {+ cache.disposables.dispose('hoverTick')+ }+ },+})),+```++The key lets the mouseleave handler stop the ticker without unmounting anything.++## Pattern: one-shot timeout that may be spammed++Use case: a "saved!" banner that disappears after 2 seconds; if you save again, the+timer resets.++```ts+listeners(({ actions, cache }) => ({+ showSaved: () => {+ cache.disposables.add(() => {+ const id = setTimeout(() => actions.hideSaved(), 2000)+ return () => clearTimeout(id)+ }, 'savedBanner')+ },+})),+```++Same key on each call — the previous timer is auto-disposed before the new one is+registered. No manual tracking.++## Picking the interval++- **Faster than 1 second**: hover/animation only. Anything API-driven at this rate+ pummels the server.+- **1–5 seconds**: live indicators while the view is open (current online count, hot+ job status).+- **10–30 seconds**: background state refresh while the user is doing something else.+- **Minutes**: stale-data refresh on long-lived pages.++Always include the interval as a named constant near the top of the file+(`REFRESH_INTERVAL_MS = 5000`). It makes the trade-off explicit.++## Anti-patterns++See [anti-patterns.md](anti-patterns.md) for the consolidated catalogue.diff --git a/.agents/skills/writing-kea-logics/references/reacting-to-changes.md b/.agents/skills/writing-kea-logics/references/reacting-to-changes.mdnew file mode 100644index 000000000000..9e6d5e2c2e70--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/reacting-to-changes.md@@ -0,0 +1,145 @@+# Reacting to changes++When a value changes, what should run? PostHog has a hierarchy. Try each option in+order — only fall through to the next when the previous can't express the case.++| Option | Use when |+| ----------------------------- | ------------------------------------------------------ |+| Selector | The "reaction" is just a derived value. |+| `listeners` on the action | Something dispatches an action when the value changes. |+| `propsChanged` | The value is a logic prop changing from React. |+| `urlToAction` / `actionToUrl` | The value is URL state. See [routing.md](routing.md). |+| `kea-subscriptions` | Truly nothing above fits. |++Why the order: each option is cheaper and more predictable than the next. Subscriptions+re-run on every dispatch in the entire app — pay that cost only when you have to.++## Selectors — "react" by computing++If your "reaction" is just deriving a new value (a count, a formatted string, a+boolean), use a selector. The UI re-renders when the inputs change; there's no+imperative listener at all.++```ts+selectors({+ visibleItems: [(s) => [s.items, s.filter], (items, filter) => items.filter((i) => i.name.includes(filter))],+})+```++If you found yourself writing a listener that just does+`actions.setVisibleItems(items.filter(...))`, that's a selector instead.++## Listeners — react to an action++Use when the value change is the result of an action somebody dispatched.++```ts+listeners(({ actions, values }) => ({+ setFilter: ({ filter }) => {+ // filter changed via an action — react here+ actions.loadResults(filter)+ },+ loadResultsSuccess: () => {+ // an async action finished — react here+ actions.trackEvent('results_loaded', { count: values.results.length })+ },+})),+```++If the value lives in another logic, `connect` to its action and listen for it:++```ts+connect(() => ({ actions: [otherLogic, ['setX']] })),+listeners(({ actions }) => ({+ setX: ({ x }) => { /* react to other logic */ },+})),+```++## `propsChanged` — react to props++When a value comes from React props (the parent re-renders with new props), use+`propsChanged`:++```ts+propsChanged(({ actions, props }, oldProps) => {+ if (props.fooId !== oldProps.fooId) {+ actions.loadFoo()+ }+})+```++The second argument is the previous props. Always guard against+identity-but-not-value changes — React may re-render with structurally equal but+referentially different props.++## Why **not** `kea-subscriptions` (almost always)++`subscriptions(({ actions }) => ({ x: (next, prev) => ... }))` installs a redux+subscription. That subscription runs **on every dispatch in the app**, not just when+`x` changes — it checks `x` against the previous value and fires your callback only+when it differs.++That's cheap per-dispatch, but multiplied by the dispatches happening across all+logics, it adds up. There's also a project preference against it: when you reach for+a subscription, almost always you can listen to the action that changed the value+instead, which runs only on that one action.++Two cases where subscriptions are the right tool:++1. **The value is a derived selector you don't own, and there's no action you can+ listen to** — e.g. you need to react to "the active scene's filter object",+ which is composed across multiple logics.+2. **Bidirectional sync between two values that would otherwise loop** — listening+ in both directions creates a cycle; subscriptions break it because they fire+ on value change, not action dispatch.++Both are rare. Default to listeners.++### Workspace constraint++`kea-subscriptions` is only in the `frontend/` workspace `package.json`. **Importing+it from a `products/*` logic fails the build.** Always use listeners there.++## Pattern: same body for multiple actions — `sharedListeners`++If three actions all need to call the same logic, factor it through `sharedListeners`:++```ts+sharedListeners(({ actions, values }) => ({+ reloadIfChanged: () => {+ if (values.shouldReload) actions.loadFoo()+ },+})),+listeners(({ sharedListeners }) => ({+ setFilter: sharedListeners.reloadIfChanged,+ setSort: sharedListeners.reloadIfChanged,+ setDateRange: sharedListeners.reloadIfChanged,+})),+```++Listeners can also be array-valued — the first element can be a shared listener and+the second can be inline:++```ts+listeners(({ sharedListeners }) => ({+ setFilter: [+ sharedListeners.reloadIfChanged,+ ({ filter }) => { /* extra inline behaviour */ },+ ],+})),+```++## Anti-patterns++See [anti-patterns.md](anti-patterns.md) for the consolidated catalogue.++## History++- Commit [`ac783822712`](https://github.com/PostHog/posthog/commit/ac783822712) —+ replaces a `subscriptions` block with `afterMount` + `propsChanged` for a+ prop-derived value in the taxonomic filter. The commit message has the cleanest+ one-line explanation of why the redux-subscription overhead is worth avoiding.+- Commit [`7ef47b68e75`](https://github.com/PostHog/posthog/commit/7ef47b68e75) —+ drops `kea-subscriptions` from a `products/*` logic after the build failed; the+ fix is a listener on the connected action. The canonical example of the+ workspace constraint.diff --git a/.agents/skills/writing-kea-logics/references/routing.md b/.agents/skills/writing-kea-logics/references/routing.mdnew file mode 100644index 000000000000..8a969d666e5e--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/routing.md@@ -0,0 +1,112 @@+# Routing — syncing state with the URL++PostHog uses `kea-router` for URL state. Two builders cover almost everything:++- `urlToAction` — URL change → fire an action+- `actionToUrl` — action fires → update the URL++For scene root logics, use `tabAwareUrlToAction` / `tabAwareActionToUrl` instead.+See [making-scenes-tab-aware](../../making-scenes-tab-aware/SKILL.md).++For imperative navigation, dispatch `router.actions.push(urls.foo())` inside a listener.++## Why a router builder and not `useNavigate` / `useParams`++- The logic owns URL state, not the component. Reload-safe, deep-linkable, and the+ state survives React unmounts.+- One place to update both internal state and the URL together — no two-step "set+ state, then call navigate" dance.+- Works inside a logic that isn't bound to any component (e.g. a singleton).++## `urlToAction` — react to URL changes++```ts+urlToAction(({ actions }) => ({+ [urls.fooList()]: () => {+ actions.setSelectedId(null)+ },+ [`${urls.foo()}/:id`]: ({ id }) => {+ actions.setSelectedId(id ?? null)+ },+})),+```++- Keys are URL patterns; `:id`-style placeholders are extracted into the first arg.+- All matching patterns fire, in order. Put the most-specific first if you care.+- Use `urls.foo()` helpers (in `frontend/src/scenes/urls.ts`) — don't hard-code paths.++## `actionToUrl` — update the URL from an action++```ts+actionToUrl(({ values }) => ({+ setSelectedId: ({ id }) => (id ? urls.foo(id) : urls.fooList()),+ setFilter: ({ filter }) => [+ router.values.location.pathname,+ { q: filter }, // searchParams (object — router serialises it)+ router.values.hashParams, // hashParams (object — keep existing hash)+ { replace: true }, // don't push history entry+ ],+})),+```++Return shapes:++- A string — replaces the pathname.+- `[pathname, searchParams, hashParams, options]` — full control. `searchParams` and+ `hashParams` are **objects**; the router serialises them. Don't pass a raw query+ string here — it'll get URL-encoded twice.+- Nothing / `undefined` — no URL change for this action.++Use `{ replace: true }` for filter/sort changes so the back button skips through+intermediate states.++## Avoiding the feedback loop++The classic bug: `setX` updates the URL, the URL change fires `setX` again with the+same value, loop.++Two ways out:++```ts+// 1. Check the value didn't change+urlToAction(({ actions, values }) => ({+ [urls.foo()]: (_, search) => {+ if (search.q !== values.query) {+ actions.setQuery(search.q ?? '')+ }+ },+})),++// 2. Only react to user-initiated navigations+urlToAction(({ actions }) => ({+ [urls.foo()]: (_, search, hash, { method }) => {+ if (method === 'REPLACE') return // ignore our own replace+ actions.setQuery(search.q ?? '')+ },+})),+```++`method` is one of `PUSH | REPLACE | POP`. `POP` is back/forward, `PUSH`/`REPLACE`+are from `actionToUrl` or imperative navigation.++## Imperative navigation++Inside a listener:++```ts+import { router } from 'kea-router'++listeners(() => ({+ createFooSuccess: ({ foo }) => {+ router.actions.push(urls.foo(foo.id))+ },+})),+```++`router.actions.push(url)` for a normal navigation, `.replace(url)` to avoid pushing+history. Prefer `actionToUrl` over imperative navigation when the action and URL are+the same concept — let the builder do the wiring.++## Anti-patterns++See [anti-patterns.md](anti-patterns.md) for the consolidated catalogue.diff --git a/.agents/skills/writing-kea-logics/references/state-decision.md b/.agents/skills/writing-kea-logics/references/state-decision.mdnew file mode 100644index 000000000000..55018d566615--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/state-decision.md@@ -0,0 +1,103 @@+# Reducer vs selector vs cache vs loader++Most kea bugs come from picking the wrong container for a piece of state. Use this+decision flow before you write a new field.++## Decision flow++1. **Does it come from an HTTP call?** Use a [loader](loading-data.md).+2. **Can it be computed from other state?** Use a `selector`.+3. **Does an action change it, and does the UI need to re-render when it changes?**+ Use a `reducer`.+4. **Is it a timer, listener, or other disposable resource?** Use `cache.disposables`+ — see [using-kea-disposables](../../using-kea-disposables/SKILL.md).++If none of the above fit and you need a transient, non-reactive flag the UI never+reads (a re-entry guard inside a listener, for example), then `cache.foo` is the+escape hatch. Reach for it last, not first — most "I need a flag" cases are actually+served by `fooLoading` from a loader or `isFooSubmitting` from a form. `cache.foo`+also has nothing to do with `cache.disposables` despite sharing the namespace — they+are separate concerns.++## Why this matters++- **Reducers are the only thing React subscribes to via `useValues`.** Putting+ reactive state in `cache` means components won't re-render when it changes.+- **Selectors are memoised.** A reducer that mirrors a computed value will drift+ out of sync the moment one of its inputs changes from somewhere else.+- **Loaders give you `xLoading` for free.** Building your own `isLoadingFoo` reducer+ duplicates state you already have.+- **`cache` is escape-hatch state**: re-entry guards, one-shot flags, debounce+ timers (when not using disposables). The UI must never depend on it.++## Patterns++### Action-driven state — reducer++```ts+reducers({+ name: ['' as string, { setName: (_, { name }) => name }],+ selectedIds: [+ [] as string[],+ {+ select: (state, { id }) => [...state, id],+ deselect: (state, { id }) => state.filter((x) => x !== id),+ clearSelection: () => [],+ },+ ],+})+```++A reducer **listens to actions and returns the next state**. Pure function, no side+effects. The default value is the first array element; handlers are the last.++### Derived state — selector++```ts+selectors({+ selectedCount: [(s) => [s.selectedIds], (selectedIds): number => selectedIds.length],+ isAllSelected: [+ (s) => [s.selectedIds, s.allIds],+ (selectedIds, allIds): boolean => selectedIds.length === allIds.length,+ ],+})+```++Selectors take an array of input selectors and a result function. Result is memoised+on identity of the inputs. Always annotate the return type — typegen needs it for+downstream consumers.++You can read another logic's selector inside a result function via `s.someValue` (if+connected) or `otherLogic.selectors.someValue` (when you'd rather not connect). The+connected form is preferred — type safety, explicit dependency declaration, and+nothing surprising at mount time.++### Transient flag — cache++```ts+listeners(({ values, actions, cache }) => ({+ submit: async () => {+ if (cache.submitting) return // re-entry guard+ cache.submitting = true+ try {+ await api.things.create(values.thing)+ } finally {+ cache.submitting = false+ }+ },+}))+```++`cache` is plain mutable state on the logic instance. No reducers, no actions, no+React subscription. Only use for things the UI doesn't render.++## Common mistakes++- **Reducer that duplicates a selector.** If `fullName` is always+ `firstName + ' ' + lastName`, it's a selector, not a reducer.+- **Selector that should be a reducer.** If the value is set by an action and not+ computed from anything else, it's a reducer.+- **Cache used for UI state.** No re-render will happen. The UI will look stale until+ some other action triggers a re-render coincidentally.+- **Mirroring loader data into a reducer.** Loaders already give you the value plus+ `xLoading`. Don't add a `foo` reducer alongside a `loadFoo` loader.diff --git a/.agents/skills/writing-kea-logics/references/testing.md b/.agents/skills/writing-kea-logics/references/testing.mdnew file mode 100644index 000000000000..e8d18c97d862--- /dev/null+++ b/.agents/skills/writing-kea-logics/references/testing.md@@ -0,0 +1,164 @@+# Testing kea logics++PostHog tests kea logics with [`kea-test-utils`](https://github.com/keajs/kea-test-utils)+plus jest, MSW for HTTP, and a small `initKeaTests` helper.++## Setup boilerplate++```ts+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { fooLogic } from './fooLogic'++describe('fooLogic', () => {+ let logic: ReturnType<typeof fooLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/foos/:id/': (req) => [200, { id: req.params.id, name: 'hello' }],+ },+ post: { '/api/environments/:team_id/foos/': { id: 'new', name: 'new' } },+ })+ initKeaTests()+ logic = fooLogic({ fooId: '123' })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })+})+```++- `initKeaTests()` (in `frontend/src/test/init.ts`) calls `initKea` with an in-memory+ history and mounts the common logics (`preflightLogic`, `teamLogic`, `projectLogic`,+ `organizationLogic`). Pass `mountCommonLogic = false` only if your test needs to+ control those manually.+- `useMocks(...)` (in `frontend/src/mocks/jest.ts`) is the MSW handler registration. The+ matcher supports path parameters and HTTP methods. Unhandled requests log a warning.+- `ReturnType<typeof fooLogic.build>` is the conventional way to type the local variable+ for both keyed and unkeyed logics.++## `expectLogic` assertions++```ts+// Synchronous dispatch+expectLogic(logic, () => {+ logic.actions.setName('hi')+})+ .toDispatchActions(['setName'])+ .toMatchValues({ name: 'hi' })++// Async — await the whole expectation+await expectLogic(logic, () => {+ logic.actions.loadFoo()+})+ .toFinishAllListeners()+ .toMatchValues({+ foo: { id: '123', name: 'hello' },+ fooLoading: false,+ })++// Assert an action did NOT fire+await expectLogic(logic, () => {+ logic.actions.setQuery(logic.values.query) // same value, should be a no-op+}).toNotHaveDispatchedActions(['loadResults'])++// Router-driven action+import { router } from 'kea-router'++router.actions.push('/foos/123')+expectLogic(logic).toDispatchActions(['setFooId']).toMatchValues({ fooId: '123' })+```++Common assertion methods from `kea-test-utils`:++| Method | Use |+| ------------------------------------- | ------------------------------------------------------------- |+| `.toDispatchActions([...])` | Actions fired in order (other actions may interleave). |+| `.toDispatchActionsInAnyOrder([...])` | Actions fired but order doesn't matter. |+| `.toNotHaveDispatchedActions([...])` | None of the listed actions fired. |+| `.toMatchValues({ key: value })` | Reducer/selector values match (partial matching for objects). |+| `.toFinishAllListeners(timeoutMs?)` | Awaits all in-flight async listeners. |+| `.toFinishListener(actionName)` | Awaits a specific listener. |+| `partial({ ... })` / `truth(fn)` | Helpers for value matching. |++## Parameterise++Per repo convention ([CLAUDE.md](../../../../CLAUDE.md)), parameterise variations of the+same shape rather than copy-pasting describe bodies:++```ts+describe.each([+ ['draft', 'editFoo', { editing: true }],+ ['saved', 'saveFoo', { editing: false }],+])('after %s', (_, action, expectedValues) => {+ it('updates editing state', async () => {+ await expectLogic(logic, () => {+ logic.actions[action]()+ })+ .toFinishAllListeners()+ .toMatchValues(expectedValues)+ })+})+```++## Mocking non-HTTP async work++For loaders backed by code that isn't an HTTP call (e.g. `performQuery`,+`api.foos.bar` helpers that wrap multiple calls), use `jest.mock` at the top of the+file — jest hoists these above imports:++```ts+jest.mock('~/queries/query', () => ({+ __esModule: true,+ ...jest.requireActual('~/queries/query'),+ performQuery: jest.fn().mockResolvedValue({ result: [] }),+}))+```++## Intentional loader failures++If you're testing a loader's failure path, the global `onFailure` toast will fire and+spam console errors. Silence it for the test:++```ts+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'++beforeEach(() => silenceKeaLoadersErrors())+afterEach(() => resumeKeaLoadersErrors())+```++## Keyed logics++```ts+logic = fooLogic({ fooId: '123' })+logic.mount()++expect(logic.key).toEqual('123')++// Asserting required props throw on missing key+it('requires fooId', () => {+ expect(() => fooLogic()).toThrow(/must init/i)+})+```++## What not to do++- **Don't share a single `logic` instance across `describe` blocks** — kea's redux store+ is reset by `initKeaTests()` per `beforeEach`. Build and mount inside `beforeEach`.+- **Don't `await` plain action calls** — actions are synchronous dispatches. Await+ `expectLogic(...).toFinishAllListeners()` instead.+- **Don't rely on real HTTP** — every loader hit must be mocked via `useMocks`,+ otherwise MSW warns and your test depends on the dev server being up.++## Finding examples in the wild++For each pattern (form logic test, loader test with `toFinishAllListeners`, keyed+logic with `useMocks`, router-driven test with `urlToAction` assertions), grep for+the relevant builder or matcher inside `**/*.test.ts` — there are plenty of+current examples and the conventions are stable.