: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(agents): add writing-ui-components skill (#75634)
Fernando Gomes212e4452db29
diff --git a/.agents/skills/writing-kea-logics/references/anti-patterns.md b/.agents/skills/writing-kea-logics/references/anti-patterns.mdindex dddacd33ed91..63b702dfbc37 100644--- a/.agents/skills/writing-kea-logics/references/anti-patterns.md+++ b/.agents/skills/writing-kea-logics/references/anti-patterns.md@@ -94,6 +94,23 @@ If the handler doesn't `await` anything, it's a reducer or selector wearing a lohat. Loaders are for async — the action/success/failure trio and the `xLoading` booleanare noise when the work is synchronous.+### A resolved-looking default for async state++```ts+// don't+reducers({+ hasAccess: [false, { loadAccessSuccess: (_, { access }) => access.allowed }],+})+// consumers can't tell "no access" from "nobody asked yet" — the UI renders a+// verdict (upsell, empty state) before the request resolves+```++Default async state to `null` (a loader's natural default) or an explicit `'unknown'`+so consumers can branch on resolution before acting, and keep resets distinct actions+from verdicts. See [state-decision.md](state-decision.md#unknown-is-a-state); the UI+side (loading, empty, and error are three different screens) lives in+[writing-ui-components](../../writing-ui-components/SKILL.md#resolution-states).+## Loading data and persistence### `localStorage.setItem` directly inside a listener@@ -375,6 +392,28 @@ otherLogic.build(props).mount() // leaksAlways store the return value and dispose it, ideally via `cache.disposables`.+### Acquire/release pairs assembled by hand at each call site++```ts+// don't — every caller re-implements the pairing and the count+listeners(({ cache }) => ({+ openPanel: () => {+ cache.watchers = (cache.watchers ?? 0) + 1+ if (cache.watchers === 1) startWatching()+ },+ closePanel: () => {+ cache.watchers -= 1+ if (cache.watchers === 0) stopWatching()+ },+}))+```++When operations only make sense paired — watch/unwatch, claim/release,+subscribe/unsubscribe — one helper owns the pairing (and the refcount, if there is+one) so it can't be reassembled wrong, and the refcount gets tests: double-acquire,+unbalanced release. If the resource is mount-scoped, that helper already exists:+`cache.disposables` ([using-kea-disposables](../../using-kea-disposables/SKILL.md)).+### Calling `initKea` outside `initKea.ts` / `initKeaTests````tsdiff --git a/.agents/skills/writing-kea-logics/references/state-decision.md b/.agents/skills/writing-kea-logics/references/state-decision.mdindex 55018d566615..4ac3930209df 100644--- a/.agents/skills/writing-kea-logics/references/state-decision.md+++ b/.agents/skills/writing-kea-logics/references/state-decision.md@@ -19,6 +19,21 @@ served by `fooLoading` from a loader or `isFooSubmitting` from a form. `cache.foalso has nothing to do with `cache.disposables` despite sharing the namespace — theyare separate concerns.+## Unknown is a state++"Not yet known" is not the same value as "no" or "empty". A default of `false` or `[]`+for async state makes them indistinguishable, and consumers will render a verdict+("no access", "no results") before anything has resolved.++- Default async state to `null` — a loader's natural default — or an explicit+ `'unknown'` literal.+- Branch on resolution first: `fooLoading` / `foo === null` before `foo.length === 0`.+- Keep resets distinct from verdicts: a `reset` action returning the state to `null`+ is not the same thing as a load failure or an empty result.++The UI side of this rule (loading, empty, and error are three different screens) lives+in [writing-ui-components](../../writing-ui-components/SKILL.md#resolution-states).+## Why this matters- **Reducers are the only thing React subscribes to via `useValues`.** Putting@@ -101,3 +116,6 @@ React subscription. Only use for things the UI doesn't render.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.+- **Resolved-looking defaults for async state.** `false` / `[]` as the initial value+ makes "not yet known" indistinguishable from "no" / "empty" — see+ [Unknown is a state](#unknown-is-a-state).diff --git a/.agents/skills/writing-ui-components/SKILL.md b/.agents/skills/writing-ui-components/SKILL.mdnew file mode 100644index 000000000000..6f60f3892dd4--- /dev/null+++ b/.agents/skills/writing-ui-components/SKILL.md@@ -0,0 +1,236 @@+---+name: writing-ui-components+description: >+ Structure and abstraction rules for PostHog UI code — any React component or frontend file under+ `frontend/src/` or `products/*/frontend/`. Use ALWAYS before creating, moving, splitting, or+ restructuring a component or frontend file, extracting a shared/generic component, promoting a+ component to `lib/`, renaming a frontend symbol or feature, or reviewing a diff that does any of+ these. Covers file and folder organization (one component per file, one home per symbol, no+ re-export shims or barrels), when duplication becomes a component and when a generic is premature,+ rename sweeps and the frozen-strings contract (event names, properties, flag keys, `data-attr`+ values are API), UI resolution states (loading, empty, and error are three different screens), and+ visual discipline (design tokens, on-brand custom components with no AI slop, real interactive+ elements, reduced motion, Storybook).+ Component choice (Lemon vs quill) lives in `frontend/src/AGENTS.md` Rule 1; state management in+ `/writing-kea-logics`.+---++# Writing UI components++How UI code is structured: which file a component lives in, when duplication becomes a shared+component, what a rename must sweep, and what every component renders before its data resolves.+Applies to everything under `frontend/src/` and `products/*/frontend/`.++Each section leads with its gate question. If you can answer the gate honestly, the details+below it usually follow on their own.++## Use this skill when++- Creating a new component, scene, view, hook, or frontend module+- Splitting or restructuring an existing component file, or moving one between folders+- Extracting a repeated shape into a shared/generic component, or promoting one toward `lib/`+- Renaming a frontend symbol, file, or feature vocabulary+- Adding loading/empty/error handling to a view+- Reviewing a PR that does any of the above++## Companion rules (do not duplicate)++This skill owns _structure_. These own their own territory — link to them, don't restate them:++- [frontend/src/AGENTS.md](../../../frontend/src/AGENTS.md) — **Rule 1: reuse before you create**+ (the Lemon/quill lookup table) and Rule 2 (generated API types). Both apply before anything here.+- [writing-kea-logics](../writing-kea-logics/SKILL.md) — business logic lives in a logic, not in+ React; state container choice. [using-kea-disposables](../using-kea-disposables/SKILL.md) for+ anything that needs cleanup.+- [writing-user-facing-copy](../writing-user-facing-copy/SKILL.md) — every visible string.+- [writing-code-comments](../writing-code-comments/SKILL.md) — every comment, including the+ pinned-string comments below.+- [building-product-empty-states](../building-product-empty-states/SKILL.md) — scene-level+ first-run empty states (the `ProductEmptyState` gate).+- [scene-menu-bar](../scene-menu-bar/SKILL.md) — scene action surfaces.+- [setting-feature-flags-in-storybook](../setting-feature-flags-in-storybook/SKILL.md) — stories+ for flag-gated components.++## Survey precedent before you build++> **Gate: which existing scene or component are you modeling this on — and does that model+> itself follow these rules?**++Brand consistency comes from imitation, not invention. Before building any new UI, read how+2–3 comparable scenes or components are implemented — component choice, density, layout, file+structure, logic wiring, `data-attr` naming — and name the precedent you're following. A new+surface that matches its compliant neighbors is on-brand by construction.++But **filter precedent through the conventions**. The codebase carries legacy that predates+these rules — clickable divs, hand-rolled tables, new-style-banned `LemonMenu`s, deprecated+`ProductIntroduction` call sites, re-export shims, slop styling. An existing violation is+history, not license: this skill and `frontend/src/AGENTS.md` outrank precedent. When the+nearest example violates the rules, follow the rules — and if the violation is cheap to fix,+convert it while you're there ([references/anti-patterns.md](references/anti-patterns.md)).++Telling good precedent from bad:++- **Prefer reference implementations named in skills** — e.g. MCP analytics for+ [empty states](../building-product-empty-states/SKILL.md), the migrated scenes listed in+ [scene-menu-bar](../scene-menu-bar/SKILL.md) — and recently-touched code (`git log`) over+ untouched corners.+- **Prefer current primitives**: quill menus/comboboxes over `LemonMenu`/Radix menus,+ `ProductEmptyState` over `ProductIntroduction`, generated `*Api` types over handwritten ones.+- When they conflict, the priority order is **conventions > compliant precedent > invention**.+ Inventing a new pattern when a compliant precedent exists is itself a reuse violation.++## Code organization++> **Gate: can a reader find this code by name, from the folder tree alone?**++- **One component per file.** A file exports the component its name promises — nothing else. A+ private sub-piece may stay only when it is unexported, has a single consumer in the same file,+ is small (a few lines of markup, not a second real component), and is inseparable from the+ parent (mode-variants of the same export). The moment it's exported, it moves to its own file.+ Named exports only, never `default` (handbook rule).+- **One concern per file.** When a file accumulates a second concern, split it: pure decision+ functions come out of logics and components into a sibling module and get tested directly+ (see [writing-tests](../writing-tests/SKILL.md) — extract, don't escalate); a dialog opened by+ a button is not part of the button. Copy stays inline where reviewers see it in rendering+ context — extract only long-form copy blocks or copy shared across components.+- **Folders mirror the feature.** A flow is a shell plus a `steps/` folder; reusable pieces in+ `components/`; shared helpers in `utils.ts` (or the layer's existing `helpers.ts`). The tree+ should read like a table of contents. Files are named after their main export+ (`DashboardMenu.tsx`, `dashboardLogic.ts`); no `index.ts`, `styles.css`, or other generic names.+- **Every symbol has exactly one home.** No re-export shims creating a second import path, no+ `export * from`, no new barrel files. When you extract or move a module, point every consumer+ at the new home in the same PR and delete the old path — imports are mechanical; sweep them.+ The only tolerated shim is inside a multi-PR migration that crosses team ownership boundaries,+ marked `// TODO(<issue>): delete after <migration>` and removed in the final PR of the series.++## The abstraction ladder++> **Gate: does the call site read as content, not markup?**++That's the litmus for a good extraction: callers pass data and slots; the generic owns the+scaffolding. Climb the ladder one rung at a time:++1. **Reuse before you create** — [frontend/src/AGENTS.md Rule 1](../../../frontend/src/AGENTS.md).+ The design system is the brand: Lemon/quill components carry PostHog's tokens, density, and+ interaction patterns, so building from them is what keeps a scene looking like PostHog.+ Hand-rolling markup that an existing component already is counts as duplication _and_ a+ branding leak.+2. **Duplicate before you abstract.** Extract a shared component when the same shape appears+ **three times**, or **twice within one feature with a third clearly coming**. Below that+ threshold, duplication is cheaper than the wrong abstraction.+3. **The generic owns scaffolding, not variants.** If the second call site needs a boolean prop+ to switch off half the generic's behavior (`hideIcon`, `noBorder`, `variant="other"`), it is+ not the same shape — inline the call sites again or split into two components.+4. **Keep new generics feature-local.** They live next to the feature that uses them until a+ second _feature_ needs them; promotion is one `git mv` away. The path is: feature folder →+ `frontend/src/lib/components/` (app-shared) → lemon-ui / quill (design system — needs design+ review). Products never import from each other: a second consumer in another product forces+ promotion to a shared layer, not a cross-product import.+5. **Don't abstract single-consumer, state-coordinated components.** A wrapper with one caller+ is indirection, not reuse — delete the layer.++## Naming and vocabulary++> **Gate: does the name promise exactly what the thing does — and does it promise it everywhere?**++- **One vocabulary per concept.** When a feature is renamed, sweep the code symbols completely —+ components, logics, files, folders, props, test names. `git grep` the old name before calling+ the rename done; a codename surviving alongside the real name costs every future reader a+ translation step.+- **Names don't over-promise.** A hook named for "any wizard run" must not answer only for+ self-driving; a `use<X>` that only works under one scene is named for that scene. If the scope+ is narrower than the name, rename one of them.+- **Wire strings are frozen.** The rename sweep stops at anything the outside world can see:++ | Frozen string | Who depends on it |+ | -------------------------------------- | -------------------------------------------------------------- |+ | Event names (`posthog.capture('…')`) | dashboards, insights, cohorts, alerts |+ | Event/person property names and values | the same, plus breakdowns and filters |+ | Feature flag keys | rollout state lives server-side; a renamed key is a new flag |+ | `data-attr` values | autocapture-built dashboards, Playwright selectors, QA tooling |+ | `localStorage` / `sessionStorage` keys | users' persisted state silently resets |+ | URL paths and search params | bookmarks, docs links, `urlToAction` handlers |++ Pin them where they're defined with a comment stating the constraint, e.g.+ `// pinned: analytics event name — renaming breaks dashboards`. If a wire string genuinely+ must change, that's a migration (emit both, backfill, deprecate), not a rename.++## Resolution states++> **Gate: what does this component render before its data has answered?**++**Loading, empty, and error are three different screens.** "Empty" is a verdict about resolved+data; rendering it from unresolved data shows every user a flash of the wrong screen — or worse,+acts on it.++```tsx+// don't — the empty state renders during the first fetch+{+ items.length === 0 ? <EmptyState /> : <ItemsList items={items} />+}++// do — unresolved data is its own branch, checked first+{+ itemsLoading ? <Spinner /> : items.length === 0 ? <EmptyState /> : <ItemsList items={items} />+}+```++- Branch in resolution order: loading → error → empty → content.+- Model "not yet known" explicitly in the logic — `null` (a loader's natural default) or an+ explicit `'unknown'`, never `false`/`[]` doubling as "nobody asked yet". See+ [state-decision.md](../writing-kea-logics/references/state-decision.md#unknown-is-a-state) for+ the logic side.+- Scene-level first-run ("product not set up") belongs to the+ [ProductEmptyState gate](../building-product-empty-states/SKILL.md), not bespoke branching.+- Any submit that fires a network request disables the trigger and shows a loading state while+ in flight (root `CLAUDE.md` rule) — reset in both success and error paths.++## Visual discipline++- **Design tokens, not hardcoded values.** Colors come from tokens (`--color-*`, product accents+ in `frontend/src/styles/base.scss`) — a hardcoded hex is invisible to dark mode. Spacing comes+ from the Tailwind scale; an arbitrary value (`w-[347px]`) needs a comment explaining the+ constraint, or it should be a scale value.+- **Custom components stay on brand.** When the design system genuinely lacks what you need,+ build the new component from the system's primitives and tokens (colors, spacing, radii,+ typography) and match the density and tone of the surrounding scene — PostHog's product UI is+ dense, flat, and utilitarian. Do not fill the gap with the generic AI-generated look ("AI+ slop"): purple/blue gradients and neon glows, gradient text, glassmorphism and blurred orbs,+ oversized radii and decorative shadows, icon-tile-above-heading card grids, pill badges+ floating over headings, and motion that isn't tied to a state change. The test: every styling+ choice is traceable to a token or an existing PostHog pattern — if it isn't, it's a tell. Full+ catalog: [references/anti-patterns.md](references/anti-patterns.md#the-ai-slop-component).+- **Tailwind utilities over inline styles; components over repeated class strings.** A class+ string copy-pasted across three files is a component in disguise. SCSS is the fallback for+ what Tailwind can't express, namespaced BEM-style under the component's class (handbook rule).+- **Interactive elements are real elements.** A real `<button>`/`<a>` — which is what+ `LemonButton` and quill triggers render — never `onClick` on a `<div>` or a Card. Real elements+ give keyboard focus, Enter/Space activation, and autocapture for free. If the design-system+ component isn't semantically right, extend it; don't drop to a clickable div. Don't remove+ focus outlines; give motion a `motion-reduce:` variant.+- **`data-attr` on meaningful interactions.** New buttons and key interactive elements get a+ kebab-case `data-attr` (match the surrounding scene's pattern) — it's how autocapture+ dashboards and Playwright find them. Once shipped it's frozen (see the table above).+- **New presentational components ship with a story** (handbook rule) — visual-regression+ coverage is free once the story exists. Flag-gated components use the `featureFlags` story+ parameter ([setting-feature-flags-in-storybook](../setting-feature-flags-in-storybook/SKILL.md)).++## Anti-patterns++[references/anti-patterns.md](references/anti-patterns.md) is the convert-on-sight catalog —+before/after for the rules above. Read it when reviewing UI diffs.++## Before you open the PR++- [ ] New UI is modeled on named, compliant precedent — violating neighbors were not copied+- [ ] Every new file exports what its name promises — one component each, named exports+- [ ] No new re-export shims or barrels; moved symbols' consumers all updated, old paths deleted+- [ ] New generics: call sites read as content; no variant booleans; feature-local unless a+ second feature exists today+- [ ] Loading, empty, and error all reachable and distinct; empty never renders from unresolved+ data+- [ ] No hardcoded colors; arbitrary Tailwind values justified or replaced+- [ ] Renames swept (`git grep` the old name returns nothing); wire strings untouched and pinned+- [ ] New presentational component has a story+- [ ] Typecheck/lint cadence per [frontend/src/AGENTS.md](../../../frontend/src/AGENTS.md) —+ full check once at the end, `pnpm --filter=@posthog/frontend fix` before finishingdiff --git a/.agents/skills/writing-ui-components/references/anti-patterns.md b/.agents/skills/writing-ui-components/references/anti-patterns.mdnew file mode 100644index 000000000000..53b4941b61b4--- /dev/null+++ b/.agents/skills/writing-ui-components/references/anti-patterns.md@@ -0,0 +1,265 @@+# UI anti-patterns — convert on sight++Shapes that look reasonable and cause specific real problems. When you see one in code you're+writing or reviewing, convert it. Companion to [SKILL.md](../SKILL.md); the kea-side catalog+lives in+[writing-kea-logics/references/anti-patterns.md](../../writing-kea-logics/references/anti-patterns.md).++## Precedent++### "The scene next door does it" as justification++```tsx+// don't — copying a violation because a neighboring scene has one+<div className="cursor-pointer" onClick={() => actions.open()}> {/* same as FooScene */}+```++Surveying comparable scenes before building is required — imitation is how new UI stays+on-brand — but the codebase carries legacy that predates these conventions. An existing+violation is history, not license, and copying it doubles it. Conventions outrank precedent:+model on compliant, recently-touched code and the reference implementations named in skills,+and if the neighboring violation is cheap to fix, convert it while you're there.++## Files and exports++### A second exported component in the same file++```tsx+// don't — UserSettings.tsx+export function UserSettings(): JSX.Element { ... }+export function ChangePasswordDialog(): JSX.Element { ... }+```++The file's name promises `UserSettings`; nobody will find the dialog here, and the next person+adds their own copy somewhere else. Move it to `ChangePasswordDialog.tsx`. An unexported,+single-consumer, few-line sub-piece (a row chip, mode-variants of the same export) may stay.++### A re-export shim left behind after a move++```ts+// don't — old file kept "for compatibility"+export { UserBadge } from 'lib/components/UserBadge/UserBadge'+```++Now the symbol has two import paths, half the codebase uses each, and go-to-definition lands in+a stub. Point every consumer at the new home in the same PR and delete the shim — imports are+mechanical. Exception: a `// TODO(<issue>): delete after <migration>` shim inside a multi-PR+migration crossing team boundaries, removed in the final PR.++### A new `index.ts` barrel++```ts+// don't — components/index.ts+export * from './PlanCard'+export * from './ChecklistRow'+```++Barrels create a second import path for every symbol and hide what a module actually depends+on. Import from the module directly. (The handbook also bans `index.ts` as a file name outright.)++### A component defined inside a component++```tsx+// don't+function Dashboard(): JSX.Element {+ function TileHeader({ title }: { title: string }): JSX.Element { ... } // new identity every render+ return <>{tiles.map((t) => <TileHeader title={t.title} />)}</>+}+```++The inner function is a new component type on every render — React unmounts and remounts the+subtree, losing state and focus. Hoist it to the top of the file; if it's exported or grows,+it gets its own file.++### Pure decisions trapped inside a component or logic++```tsx+// don't — 40 lines of branching inline in the render (or in a listener)+const mode = flag && !skipped && (hasData || force) ? 'resume' : sawIntro ? 'browse' : 'setup'+```++Extract `computeOnboardingMode(...)` into a sibling module and test it directly — cheaper test,+better-factored code ([writing-tests](../../writing-tests/SKILL.md): extract, don't escalate).++## Abstraction++### A generic grown variant booleans++```tsx+// don't — the second caller opted out of half the component+<ChecklistRow item={item} hideIcon noBorder compact statusOnRight />+```++If a caller needs to switch off half the scaffolding, it was never the same shape. Inline the+call sites again, or split into two components that each own their scaffolding. The test for a+good generic: the call site reads as content (data + slots), not configuration.++### A wrapper with one caller++```tsx+// don't+export function InboxPanelContainer(props: InboxPanelProps): JSX.Element {+ return <InboxPanel {...props} />+}+```++Indirection, not reuse — and state coordination through the extra layer only gets worse. Delete+the layer; extract when the second real consumer exists.++### The same class string copy-pasted across files++```tsx+// don't — the third file containing this exact string+<div className="flex items-center gap-2 rounded border p-2 text-muted hover:bg-surface-hover">+```++A repeated class string is a component in disguise — the next tweak will miss one copy. Extract+the component (feature-local first, per the ladder in [SKILL.md](../SKILL.md)).++### Hand-rolled markup a design-system component already is++A raw `<table>`, a colored status `<span>`, a hand-built modal — this is the most common agent+mistake and it produces off-design output. The lookup table lives in+[frontend/src/AGENTS.md Rule 1](../../../../frontend/src/AGENTS.md); check it before writing markup.++### Speculative promotion to `lib/`++A component built for one feature but parked in `frontend/src/lib/components/` "because someone+might need it" is shared-namespace clutter with feature-shaped props. Keep it next to the+feature; promotion is one `git mv` when the second feature actually shows up.++## Semantics and visual++### `onClick` on a `<div>` (or a Card)++```tsx+// don't+<div className="cursor-pointer" onClick={() => actions.openItem(item.id)}>++// do — a real button (LemonButton renders one)+<LemonButton onClick={() => actions.openItem(item.id)}>...</LemonButton>+```++A clickable div has no keyboard focus, no Enter/Space activation, and is invisible to+autocapture. If the design calls for a clickable card, wrap or extend the system component —+don't drop to a div.++### Hardcoded colors++```tsx+// don't+<span style={{ color: '#f54e00' }}>+// don't+<span className="text-[#f54e00]">+```++Invisible to dark mode and off-palette the next time design shifts a token. Use the token+(`text-danger`, `--color-*` vars, product accents from `frontend/src/styles/base.scss`).++### Unjustified arbitrary Tailwind values++```tsx+// don't+<div className="w-[347px] mt-[13px]">+```++Magic numbers off the spacing scale. Use scale values; if a real constraint forces an arbitrary+value (aligning to an embedded iframe, a chart's fixed gutter), say so in a comment.++### Animation without a reduced-motion variant++```tsx+// don't+<div className="animate-bounce">+// do+<div className="animate-bounce motion-reduce:animate-none">+```++`prefers-reduced-motion` is an accessibility setting, not a preference to override.++### The AI-slop component++A custom component that fills a design-system gap with the statistical average of every+Tailwind tutorial instead of PostHog's brand. The tells cluster:++- **Color:** purple/blue gradients, cyan-on-dark, gradient text, neon glows, radial halo+ backgrounds. PostHog's palette comes from tokens — if a color isn't a token, it isn't ours.+- **Surfaces:** glassmorphism/`backdrop-blur` as decoration, blurred gradient orbs, cards+ nested inside cards, a thick colored stripe down one side of a rounded card, hairline border+ plus a wide soft shadow, corners rounded into blobs.+- **Layout:** the icon-tile-above-heading three-card feature grid, pill badges floating above a+ centered heading, big-number hero metrics with tiny labels, identical even spacing everywhere+ (vary rhythm: tight within groups, generous between sections).+- **Motion:** entrance animations and bounce easing for their own sake, pulsing status dots on+ static data, hover-scale on images — motion that isn't tied to a state change.++None of these are banned for being ugly; they're banned because nobody _decided_ them — they're+what generated UI converges on without constraints. The fix is constraint, not taste: build+from Lemon/quill primitives and design tokens, match the density and flatness of the+surrounding scene (PostHog product UI is dense and utilitarian), and make every styling choice+traceable to a token or an existing PostHog pattern. The copy equivalent — hype words, punchy+antithesis, em-dash addiction — is already covered by+[writing-user-facing-copy](../../writing-user-facing-copy/SKILL.md).++## Resolution states++### Empty state derived from unresolved data++```tsx+// don't — flashes "No results" during the first fetch+{+ items.length === 0 ? <EmptyState /> : <ItemsList items={items} />+}++// do — branch in resolution order: loading → error → empty → content+{+ itemsLoading ? <Spinner /> : items.length === 0 ? <EmptyState /> : <ItemsList items={items} />+}+```++### A boolean that means both "no" and "not yet"++```tsx+// don't — renders the upsell before the access check resolves+const { hasAccess } = useValues(accessLogic) // defaults to false+return hasAccess ? <Feature /> : <UpsellBanner />+```++Unknown is a state. Default to `null` and branch on resolution first — the logic side lives in+[state-decision.md](../../writing-kea-logics/references/state-decision.md#unknown-is-a-state).++## Naming and strings++### A codename surviving alongside the real name++```ts+// don't — feature shipped as "Autopilot", half the symbols still say projectX+projectXLogic.ts, useProjectXStatus, <ProjectXBanner />+```++Sweep renames completely — components, logics, files, props, test names — and `git grep` the+old name before calling it done. Every surviving alias costs future readers a translation step.++### Renaming a wire string during a refactor++```ts+// don't — this "rename" breaks every dashboard querying the old name+posthog.capture('autopilot run started') // was: 'project x run started'+```++Event names, property names/values, flag keys, `data-attr` values, storage keys, and URL paths+are frozen API (see the table in [SKILL.md](../SKILL.md#naming-and-vocabulary)). Leave them+pinned with a comment; a genuine change is a migration (emit both, backfill, deprecate), not a+rename.++### A strings module for a handful of labels++```ts+// don't — strings.ts holding two button labels+export const SAVE_LABEL = 'Save view'+export const CANCEL_LABEL = 'Cancel'+```++Short copy stays inline where reviewers see it in rendering context (and where+[writing-user-facing-copy](../../writing-user-facing-copy/SKILL.md) reviews it). Extract only+long-form copy blocks or copy genuinely shared across components.diff --git a/.claude/commands/conventions.md b/.claude/commands/conventions.mdindex ebe1ecb9d174..9066bd2780f2 100644--- a/.claude/commands/conventions.md+++ b/.claude/commands/conventions.md@@ -46,6 +46,14 @@ Hence the explicit separation between the data and view layers.- Props for both logics and components are PascalCase and end with `Props` (`DashboardLogicProps` & `DashboardMenuProps`)- Name the `.ts` file according to its main export: `DashboardMenu.ts` or `DashboardMenu.tsx` or `dashboardLogic.ts` or `Dashboard.scss`. Pay attention to the case.- Avoid `index.ts`, `styles.css`, and other generic names, even if this is the only file in a directory.+- Component structure & reuse+ - One component per file — a file exports the component its name promises. Avoid re-export shims and barrel files: every symbol should have exactly one import path, and moving a symbol means updating its consumers, not leaving a compatibility stub.+ - Reach for an existing design-system component (Lemon/quill) before hand-rolling markup — reuse is how new UI stays on-brand. When you genuinely need a custom component, build it from the system's tokens and primitives and match the surrounding scene's density; avoid the generic AI-generated look (purple gradients, glassmorphism, gradient text, icon-tile card grids, decorative motion).+ - Before building new UI, read a few comparable scenes or components and model yours on the ones that follow these conventions. The codebase contains legacy that predates them — an existing violation is not license to repeat it. Conventions outrank precedent, and compliant precedent outranks invention.+ - Extract a shared component once the same shape appears in several places and the call sites read as content, not markup. Keep new generics next to the feature that uses them, and promote to `lib/` only when a second feature needs them. Don't build wrappers with a single consumer, and don't add boolean variant props so one caller can switch half the component off — that's two components.+ - Interactive elements are real `<button>`/`<a>` elements (`LemonButton` renders one) — never `onClick` on a `<div>`.+ - Loading, empty, and error are three different screens. Never show an empty state from data that hasn't resolved yet — branch on the loading state first.+ - When renaming a feature, sweep code symbols completely — but analytics-facing strings (event names, property names and values, `data-attr` values) and persisted keys are a frozen API: leave them as-is, with a comment noting they're pinned.- Scenes- Our app is built of _scenes_, managed through a scene router in `sceneLogic`.- A scene is the smallest unit in the router and for code splitting. Usually we split scenes by resource type (dashboard, insight) and function (edit, index).diff --git a/AGENTS.md b/AGENTS.mdindex 295f7b486d86..fa845b1a902e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -247,6 +247,7 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a- `/django-migrations` — any Django migration, including deleting a model, table, column, or whole product/app (even when no migration file is written, e.g. removing a product folder)- `/clickhouse-migrations` — any ClickHouse migration- `/adopting-generated-api-types` — any frontend file using `lib/api`, `api.get<`, `api.create<`, or handwritten API types+- `/writing-ui-components` — creating, moving, splitting, or restructuring any component or file under `frontend/src/` or `products/*/frontend/`, extracting or promoting a shared component, or renaming frontend symbols or feature vocabulary- `/writing-tests` — adding or substantially changing any test (pytest, Jest, or Playwright)- `/writing-user-facing-copy` — writing or editing any text a user reads (UI labels, tooltips, empty/error states, notifications, docs, support replies), or any code change that adds or changes a visible string- `/writing-code-comments` — writing or editing a code comment in any language, or reviewing a diff that adds commentsdiff --git a/docs/published/handbook/engineering/conventions/frontend-coding.md b/docs/published/handbook/engineering/conventions/frontend-coding.mdindex c56f77f3fe43..a5f2c74a48ab 100644--- a/docs/published/handbook/engineering/conventions/frontend-coding.md+++ b/docs/published/handbook/engineering/conventions/frontend-coding.md@@ -34,6 +34,14 @@ Hence the explicit separation between the data and view layers.- Props for both logics and components are PascalCase and end with `Props` (`DashboardLogicProps` & `DashboardMenuProps`)- Name the `.ts` file according to its main export: `DashboardMenu.ts` or `DashboardMenu.tsx` or `dashboardLogic.ts` or `Dashboard.scss`. Pay attention to the case.- Avoid `index.ts`, `styles.css`, and other generic names, even if this is the only file in a directory.+- Component structure & reuse+ - One component per file — a file exports the component its name promises. Avoid re-export shims and barrel files: every symbol should have exactly one import path, and moving a symbol means updating its consumers, not leaving a compatibility stub.+ - Reach for an existing design-system component (Lemon/quill) before hand-rolling markup — reuse is how new UI stays on-brand. When you genuinely need a custom component, build it from the system's tokens and primitives and match the surrounding scene's density; avoid the generic AI-generated look (purple gradients, glassmorphism, gradient text, icon-tile card grids, decorative motion).+ - Before building new UI, read a few comparable scenes or components and model yours on the ones that follow these conventions. The codebase contains legacy that predates them — an existing violation is not license to repeat it. Conventions outrank precedent, and compliant precedent outranks invention.+ - Extract a shared component once the same shape appears in several places and the call sites read as content, not markup. Keep new generics next to the feature that uses them, and promote to `lib/` only when a second feature needs them. Don't build wrappers with a single consumer, and don't add boolean variant props so one caller can switch half the component off — that's two components.+ - Interactive elements are real `<button>`/`<a>` elements (`LemonButton` renders one) — never `onClick` on a `<div>`.+ - Loading, empty, and error are three different screens. Never show an empty state from data that hasn't resolved yet — branch on the loading state first.+ - When renaming a feature, sweep code symbols completely — but analytics-facing strings (event names, property names and values, `data-attr` values) and persisted keys are a frozen API: leave them as-is, with a comment noting they're pinned.- Scenes- Our app is built of _scenes_, managed through a scene router in `sceneLogic`.- A scene is the smallest unit in the router and for code splitting. Usually we split scenes by resource type (dashboard, insight) and function (edit, index).diff --git a/frontend/src/AGENTS.md b/frontend/src/AGENTS.mdindex a76ee15b2834..e69498c24db0 100644--- a/frontend/src/AGENTS.md+++ b/frontend/src/AGENTS.md@@ -4,7 +4,7 @@ Applies to any change under `frontend/src`. This is a **discovery + cadence** gu## Rule 1 — Reuse before you create-**Before building any UI element, search for an existing one.** PostHog already has a badge, a label, a table, a tag, a card, a modal. Hand-rolling one with raw `<div>`/`<table>` + Tailwind is the single most common agent mistake here, and it produces unbounded, off-design output.+**Before building any UI element, search for an existing one.** PostHog already has a badge, a label, a table, a tag, a card, a modal. Hand-rolling one with raw `<div>`/`<table>` + Tailwind is the single most common agent mistake here, and it produces unbounded, off-design output. Reuse is also how the product stays on-brand: Lemon/quill components carry PostHog's tokens, density, and interaction patterns, so a scene built from them looks like PostHog without anyone having to think about it.Where to look, in order:@@ -26,7 +26,9 @@ Common reinventions and what to use instead:| a card / panel | `LemonCard` || a modal / confirm dialog | `LemonModal` / `LemonDialog` |-If nothing fits, say so and propose extending the existing component before adding a new one. Don't silently fork.+If nothing fits, say so and propose extending the existing component before adding a new one. Don't silently fork. If you do end up building custom, stay on brand: system tokens and primitives only, matching the surrounding scene's density and flatness — and none of the generic AI-generated look (purple/blue gradients, glassmorphism, gradient text, icon-tile card grids, decorative motion). The full slop-tell catalog is in the `/writing-ui-components` skill.++The same goes for patterns, not just components: before building a new scene or view, read 2–3 comparable ones and model yours on those that follow these rules. Precedent that violates Rule 4 or `/writing-ui-components` is legacy to route around, not license to repeat — conventions outrank precedent, and compliant precedent outranks invention.> LemonUI vs quill lives in the root `AGENTS.md` ("Code Style → Frontend (quill vs LemonUI)"). If you're working somewhere quill genuinely applies (an MCP app, the desktop app), `packages/quill/packages/primitives/AGENTS.md` has its component-choice and spacing rules, and the two libraries must not be mixed inside one component's internals.@@ -46,6 +48,16 @@ When touching `lib/api`, `api.get<`, `api.create<`, or any handwritten API interCovered by the root `AGENTS.md` (Code Style → Frontend). The discovery hint for this tree: if a scene/component has a `*Logic.ts`, that's where actions/reducers/selectors/listeners belong. See `/writing-kea-logics` and `/using-kea-disposables`.+## Rule 4 — Structure and abstraction++Full doctrine + convert-on-sight catalog: the `/writing-ui-components` skill. Load it before creating, moving, splitting, or restructuring any component or frontend file, extracting a shared component, or renaming frontend symbols. The always-on core:++- **One component per file**, named after its export; named exports only. Every symbol has exactly one import path — no re-export shims, no new `index.ts` barrels; moving a symbol means updating every consumer in the same PR.+- **Extract a shared component when call sites read as content, not markup** — at three occurrences, or two in one feature with a third clearly coming. If the generic needs a boolean to switch off half its behavior for one caller, it isn't one shape: leave the duplication. Keep new generics feature-local until a second feature needs them (promote via `lib/components/`; never import across `products/*`).+- **Interactive elements are real `<button>`/`<a>`** — that's what `LemonButton`/quill triggers render. Never `onClick` on a `<div>`/Card.+- **Loading, empty, and error are three different screens.** Never derive "empty" from data that hasn't resolved — branch on the loading/unknown state first.+- **Renames sweep code symbols completely; wire strings stay frozen.** Event names, property names/values, flag keys, `data-attr` values, storage keys, and URL paths are API (dashboards, rollouts, and Playwright depend on them) — pin them with a comment instead of renaming.+## Typecheck & typegen cadence (don't over-run these)These are slow; run them at the right moment, not after every edit.@@ -71,4 +83,4 @@ Adding a button/toggle/action to a scene's `ScenePanel`? It must also go in that- `layout/scenes/AGENTS.md` (scene action surfaces: `ScenePanel` + `SceneMenuBar` dual-write rule).- `packages/quill/packages/primitives/AGENTS.md` — component selection matrix.- `docs/published/handbook/engineering/conventions/frontend-coding.md` — frontend conventions.-- Skills: `/adopting-generated-api-types`, `/writing-kea-logics`, `/using-kea-disposables`, `/writing-tests`.+- Skills: `/writing-ui-components`, `/adopting-generated-api-types`, `/writing-kea-logics`, `/using-kea-disposables`, `/writing-tests`.