: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(storybook): add STORYBOOK_STORIES and storybook docs (#123742)
Rafael Audibert6d0e5929895d
diff --git a/.agents/skills/qa-frontend/references/feature-reel.md b/.agents/skills/qa-frontend/references/feature-reel.mdindex 9730a4df9f7b..430c9412292d 100644--- a/.agents/skills/qa-frontend/references/feature-reel.md+++ b/.agents/skills/qa-frontend/references/feature-reel.md@@ -16,7 +16,7 @@ Run every command below from the root of the PostHog checkout.## 1. Pick the sourceUse a Storybook story when one shows the start of the flow, or when a scratch story can.-Reuse a Storybook that runs. Otherwise, start one with `pnpm storybook` (port 6006).+Reuse a Storybook that runs. Otherwise, start one with `STORYBOOK_STORIES=<dir or story file> pnpm storybook` (port 6006).Story ids are in `http://localhost:6006/index.json`.On a cold dev server the first load of a story can take minutes, because Vite compiles each lazy chunk on its first request.`reel-capture.mjs` waits up to five minutes for it.diff --git a/.agents/skills/setting-feature-flags-in-storybook/SKILL.md b/.agents/skills/setting-feature-flags-in-storybook/SKILL.mddeleted file mode 100644index acd83f579bc5..000000000000--- a/.agents/skills/setting-feature-flags-in-storybook/SKILL.md+++ /dev/null@@ -1,97 +0,0 @@-----name: setting-feature-flags-in-storybook-description: 'Use when writing a Storybook story for a component gated on a feature flag — boolean flags or multivariate/experiment-arm variants. Covers the `featureFlags` story parameter and why imperatively setting flags renders the flag-off branch in visual-regression snapshots while passing in jest.'------# Setting feature flags in Storybook--> [!WARNING]-> Never call `featureFlagLogic.actions.setFeatureFlags(...)` from a story. It silently-> no-ops in the visual-regression runtime (rendering the flag-OFF branch) while passing-> in jest — so unit tests stay green and the snapshot is wrong. Use the `featureFlags`-> **story parameter** instead.--**Mental model:** boolean flags always work (they ride the always-merged baseline);-variant values need a gate that _only the `featureFlags` parameter opens correctly_.--## How to use it--This is the stable contract — prefer it over anything in "Under the hood" below.--### Boolean flags (flag is simply on)--```ts-const meta: Meta = {- title: 'Scenes/MyScene',- parameters: {- featureFlags: [FEATURE_FLAGS.MY_FLAG, FEATURE_FLAGS.OTHER_FLAG],- },-}-```--Array entries are flags that evaluate to `true`. This is the common case.--### Multivariate flags (pin a specific variant)--For a flag whose value is a variant string (experiment arms, multivariate rollouts), use-the **record form** — the array form can only express `true`:--```ts-// meta-level: applies to every story in the file-parameters: { featureFlags: { [FEATURE_FLAGS.THEME_OVERRIDE]: 'intent_plus' } }--// per-story: a different arm per story-export const ControlArm: Story = {- parameters: { featureFlags: { [FEATURE_FLAGS.THEME_OVERRIDE]: 'control' } },-}-export const TreatmentArm: Story = {- parameters: { featureFlags: { [FEATURE_FLAGS.THEME_OVERRIDE]: 'intent_plus' } },-}-```--You can mix booleans and variants in one record: `{ 'some-bool-flag': true, 'my-experiment': 'test_b' }`.--> [!IMPORTANT]-> A story's `parameters` **replace** the meta's (shallow merge), so a per-story-> `featureFlags` drops every flag set at the meta level. **Re-list any meta flags you-> still need** — silently losing one renders the flag-off branch and is easy to miss.--## Why the obvious approach fails--Setting flags imperatively (`featureFlagLogic.actions.setFeatureFlags`) works in `jest`-(`NODE_ENV==='test'`) but not in the built visual-regression Storybook. posthog-js loads-flags and fires `onFeatureFlags` with an empty set, which dispatches `setFeatureFlags`-and **wipes** whatever you set imperatively — so the unit test passes while the snapshot-renders the flag-OFF branch. The `featureFlags` parameter avoids this by writing flags to-the always-merged baseline instead (below), so the empty callback can't clobber them.--> Do **not** try to fix this by disabling posthog-js flags (e.g. `advanced_disable_feature_flags`).-> The app shell (`appLogic.showApp`) normally waits until `receivedFeatureFlags` is true,-> which is set by that same `onFeatureFlags` callback — suppress it and every-> `Scenes-App/*` story stalls behind a 3s timeout and flakes.-> The login page is an intentional exception: with no user on `/login`, `showApp` renders-> without waiting for flags. Login stories still need the `featureFlags` parameter for-> deterministic flag state.--## Under the hood (implementation detail — may drift)--> This explains _why_ the parameter works, for trust and for anyone extending the harness.-> Treat "How to use it" above as the contract, not this.--`withFeatureFlags` → `setFeatureFlags` (`frontend/src/mocks/browser.tsx`) writes the-flags (array or record) straight to `window.POSTHOG_APP_CONTEXT.persisted_feature_flags`.-`getPersistedFeatureFlags` (`frontend/src/lib/logic/featureFlagLogic.ts`) reads that as-`featureFlagLogic`'s initial value and `spyOnFeatureFlags` always merges it as the-baseline — so both booleans and pinned variants survive the empty `onFeatureFlags`-callback. The only production-side support this needs is `getPersistedFeatureFlags`-accepting the record form (variant values) in addition to the server's array form.--You should not need to touch any of this. If you're extending the harness, that's the seam.--## See also--The `featureFlags` parameter only controls the flag. If a component's render also depends-on other runtime state (localStorage, an `APP_CONTEXT` field, a kea logic that resolves an-entry), stage that state too — typically in a small wrapper the story renders that sets it-and mounts the logic before rendering the component. Keep that wrapper in the story file;-don't add test-only props to the production component to make it renderable.diff --git a/.agents/skills/verifying-changes/SKILL.md b/.agents/skills/verifying-changes/SKILL.mdindex 019630be64ae..5ee72836b927 100644--- a/.agents/skills/verifying-changes/SKILL.md+++ b/.agents/skills/verifying-changes/SKILL.md@@ -20,7 +20,7 @@ Start with the cheapest, and move up only when the current layer cannot see what| 1 | Lint, format, typecheck | `hogli verify --changed`, or `ruff check` and `pnpm --filter=@posthog/frontend typescript:check` || 2 | The nearest unit test | `hogli test <file>`, `hogli test --changed` || 3 | Serializer and OpenAPI regen | `hogli up -d`, `hogli build:openapi`, then commit the generated diff |-| 4 | Storybook render | `pnpm storybook`, open the affected story, compare before and after |+| 4 | Storybook render | `STORYBOOK_STORIES=<dir> pnpm storybook`, open the affected story, compare before and after || 5 | The running stack | `hogli up -d`, `hogli wait`, then exercise the flow || 6 | Playwright or a recorded run | `hogli test playwright/<spec>.spec.ts` against a running stack |@@ -29,6 +29,9 @@ It does not report the diff as verified when a check was skipped, when a check omypy is one of those advice-only checks. It runs repo-wide, so `hogli verify` prints its command instead of running it.Use `--plan` to see the classification without running anything.+For layer 4, set `STORYBOOK_STORIES` to the directories or story files you need instead of editing the `stories` list in `main.ts`.+`/working-with-storybook` covers starting Storybook, opening a story by URL, screenshots, and writing the story itself.+## Decision table| Change | Enough | Wasted |diff --git a/.agents/skills/working-with-storybook/SKILL.md b/.agents/skills/working-with-storybook/SKILL.mdnew file mode 100644index 000000000000..2d375b556c73--- /dev/null+++ b/.agents/skills/working-with-storybook/SKILL.md@@ -0,0 +1,47 @@+---+name: working-with-storybook+description: >+ Runs, writes and debugs PostHog Storybook stories and their visual review snapshots.+ Use when you start Storybook to look at a change, write or change a `*.stories.tsx` file,+ set feature flags, the date, the URL, mocks or `testOptions` for a story,+ or fix a story that times out, renders nothing or flakes in visual review.+ Points to the Storybook docs in `common/storybook/` and adds the steps an agent follows to render and screenshot a story.+ Trigger terms: storybook, story, stories, pnpm storybook, STORYBOOK_STORIES, featureFlags, testOptions,+ mswDecorator, mockDate, visual review, snapshot, flaky story.+---++# Working with Storybook++The Storybook docs live next to the setup, in [common/storybook/README.md](../../../common/storybook/README.md) and its `docs/` folder.+This skill does not repeat them. Read the one the task needs:++| Task | Read |+| ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |+| Start Storybook, open a story by URL, run the snapshot runner locally | [README](../../../common/storybook/README.md) |+| Write a story, or set its feature flags, date, URL, layout, theme or tags | [Writing stories](../../../common/storybook/docs/writing-stories.md) |+| Mock API responses, plan features, the current user, team or preflight | [Mocking data](../../../common/storybook/docs/mocking-data.md) |+| Pick `testOptions`, fix a timeout, an empty render or a flake, understand baselines | [Snapshots](../../../common/storybook/docs/snapshots.md) |+| Write a story that loads data, measures itself or uses timers | [Deterministic stories](../../../docs/published/handbook/engineering/conventions/frontend-coding.md#deterministic-stories) |+| Find out why visual review blocks a PR, approve, tolerate or quarantine a snapshot | [triaging-visual-review-runs](../../../products/visual_review/skills/triaging-visual-review-runs/SKILL.md) |++## Render a story to check a change++1. Start Storybook in the background with only the stories you need: `STORYBOOK_STORIES=<dir or story file> pnpm storybook`. Never edit the `stories` list in `common/storybook/.storybook/main.ts`.+2. Wait for the index, then find the story ID:++ ```sh+ until curl -sf http://localhost:6006/index.json >/dev/null; do sleep 1; done+ curl -s http://localhost:6006/index.json | jq -r '.entries | keys[]'+ ```++3. Load `http://localhost:6006/iframe.html?viewMode=story&id=<story-id>&globals=theme:<light|dark>` in a headless browser. The first load after a start compiles the dependencies and can take a few minutes, so give it a page load timeout of a few minutes.+4. Take screenshots with a Playwright script kept outside the repo, for example in your scratch directory. Use `deviceScaleFactor: 2`, so a screenshot in a PR doesn't look soft.+5. Check the light and dark themes, and the narrow widths the root `AGENTS.md` asks for. Compare before and after.++A story you write only for this check or for a PR screenshot is scratch. Keep it out of the commit.++## Before you commit a story++- Read [Writing stories](../../../common/storybook/docs/writing-stories.md) first when the story sets feature flags. The wrong way passes in jest and fails only in visual review.+- Each committed story shows a state no other story shows, because each one adds two baselines that every later change must approve again.+- Don't commit images from a local snapshot run. CI takes the snapshots, and visual review commits the baseline hashes.diff --git a/.agents/skills/writing-skills/SKILL.md b/.agents/skills/writing-skills/SKILL.mdindex af215763effa..f7579e120641 100644--- a/.agents/skills/writing-skills/SKILL.md+++ b/.agents/skills/writing-skills/SKILL.md@@ -51,6 +51,12 @@ it's about how an experienced person would approach a job using those tools.Ask: "If a customer asked an agent to do X with my feature, would the agent know the right approach?"If not, write a skill.+### Docs or skill?++A skill holds only what an agent needs on top of the docs: the steps of one job, the checks before it reports done, and the decisions it must not make alone.+How a system works, its setup, options and gotchas go in docs (a README next to the code, or an existing page under `docs/`), and the skill links to them.+If an engineer would look it up without an agent, it is docs.+### How many is too many?Skill count is a budgeted, shared resource — agents pick from a list of _all_ skill descriptions, and many harnesses truncate that list once it grows long, so every extra skill makes the others less likely to fire.diff --git a/.agents/skills/writing-ui-components/SKILL.md b/.agents/skills/writing-ui-components/SKILL.mdindex f9a8ce6c89bb..acefe070ec19 100644--- a/.agents/skills/writing-ui-components/SKILL.md+++ b/.agents/skills/writing-ui-components/SKILL.md@@ -48,8 +48,8 @@ This skill owns _structure_. These own their own territory — link to them, don- [building-product-empty-states](../building-product-empty-states/SKILL.md) — scene-levelfirst-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.+- [working-with-storybook](../working-with-storybook/SKILL.md) — rendering, writing and debugging+ stories.## Survey precedent before you build@@ -221,7 +221,7 @@ acts on it.A story written onlyto look at a change or to take a PR screenshot is scratch: keep it out of the commit.Flag-gated components use the `featureFlags` story parameter- ([setting-feature-flags-in-storybook](../setting-feature-flags-in-storybook/SKILL.md)).+ ([Writing stories](../../../common/storybook/docs/writing-stories.md#featureflags)).A story must render the same picture on every run: pin the clock, wait for readiness, and fixthe width of self-measuring content. Read[Deterministic stories](../../../docs/published/handbook/engineering/conventions/frontend-coding.md#deterministic-stories)diff --git a/.claude/rules/storybook-feature-flags.md b/.claude/rules/storybook-feature-flags.mdindex 9e17fa582619..e051268f9351 100644--- a/.claude/rules/storybook-feature-flags.md+++ b/.claude/rules/storybook-feature-flags.md@@ -9,4 +9,4 @@ If this story renders a component gated on a feature flag, set the flag via theimperatively (that is silently dropped in the visual-regression runtime). For amultivariate flag use the record form, e.g.`parameters: { featureFlags: { [FEATURE_FLAGS.MY_FLAG]: 'test_b' } }`.-Invoke the `/setting-feature-flags-in-storybook` skill before making changes.+Invoke the `/working-with-storybook` skill and read the feature flags section of `common/storybook/docs/writing-stories.md` before making changes.diff --git a/.coderabbit.yaml b/.coderabbit.yamlindex b657a7a7d4eb..c569667acf3b 100644--- a/.coderabbit.yaml+++ b/.coderabbit.yaml@@ -169,7 +169,7 @@ knowledge_base:applyTo: 'frontend/src/**,products/**/frontend/**'# Feature flags in Storybook stories.- - files: '.agents/skills/setting-feature-flags-in-storybook/SKILL.md'+ - files: 'common/storybook/docs/writing-stories.md'applyTo: '**/*.stories.tsx'# The taxonomic filter, which is easy to break from the outside.diff --git a/common/storybook/.storybook/README.md b/common/storybook/.storybook/README.mddeleted file mode 100644index ccef9cc56533..000000000000--- a/common/storybook/.storybook/README.md+++ /dev/null@@ -1,56 +0,0 @@-# Storybook--## Adding new Tailwind classes--Tailwind is compiled by `@tailwindcss/postcss` on the initial build. Webpack's-HMR does not re-run PostCSS when story content changes, so a **newly used**-Tailwind utility (e.g. `bg-[rebeccapurple]`) won't appear until you restart-Storybook. Classes already present in the codebase hot-reload fine.--## Storybook visual regression tests--In CI, Playwright loads each story and takes a light and a dark snapshot by default. A story can skip either theme with `testOptions.skipLightMode` or `testOptions.skipDarkMode`.-Visual review compares them with the baselines in `frontend/snapshots.yml`. A changed picture is approved in the visual review run, and finalizing the run commits the new baselines to the PR.--`test-runner.ts` holds the capture logic and the `testOptions` story parameters. To keep a story from flaking, see [Deterministic stories](../../../docs/published/handbook/engineering/conventions/frontend-coding.md#deterministic-stories) in the frontend coding conventions.--Uses `"@storybook/test-runner"` see: https://storybook.js.org/docs/writing-tests/test-runner--## to run locally--before you do this... 🤷--in one terminal--```bash-hogli storybook-```--in another--```bash-pnpm exec playwright install-hogli storybook:test-```--## Viewport width variants--You can snapshot a story at multiple viewport widths-by setting `viewportWidths` in `testOptions`.-This produces one snapshot per width instead of the default single snapshot.--Available widths: `narrow` (568px), `medium` (960px), `wide` (1300px), `superwide` (1920px).--```ts-export const MyStoryViewports: Story = createInsightStory(fixture, 'edit')-MyStoryViewports.parameters = {- testOptions: {- viewportWidths: ['medium', 'wide', 'superwide'],- },-}-```--Each width generates a separate snapshot file suffixed with the width name,-e.g. `my-story-viewports--medium--light.png`.--See `frontend/src/scenes/data-management/definition/DefinitionView.stories.tsx` for a working example.diff --git a/common/storybook/.storybook/main.ts b/common/storybook/.storybook/main.tsindex 877812f3273d..6dee728b7af7 100644--- a/common/storybook/.storybook/main.ts+++ b/common/storybook/.storybook/main.ts@@ -34,16 +34,27 @@ const SINGLETON_PACKAGES = ['@testing-library/dom',]-const createStoriesPathFor = (storyPath: string): string => `../../../${storyPath}/**/*.stories.@(js|jsx|ts|tsx)`+const STORY_FILE = /\.stories\.(js|jsx|ts|tsx)$/++const createStoriesPathFor = (storyPath: string): string =>+ STORY_FILE.test(storyPath) ? `../../../${storyPath}` : `../../../${storyPath}/**/*.stories.@(js|jsx|ts|tsx)`++const DEFAULT_STORY_ROOTS = [+ 'frontend/src',+ 'products/**/frontend',+ 'products/**/mcp/apps',+ 'services/mcp/src/ui-apps',+ 'packages/quill/packages/charts/src',+]++// Comma-separated directories or story files, relative to the repo root.+const storyRootsOverride = (process.env.STORYBOOK_STORIES ?? '')+ .split(',')+ .map((storyRoot) => storyRoot.trim().replace(/\/+$/, ''))+ .filter(Boolean)const config: StorybookConfig = {- stories: [- createStoriesPathFor('frontend/src'),- createStoriesPathFor('products/**/frontend'),- createStoriesPathFor('products/**/mcp/apps'),- createStoriesPathFor('services/mcp/src/ui-apps'),- createStoriesPathFor('packages/quill/packages/charts/src'),- ],+ stories: (storyRootsOverride.length > 0 ? storyRootsOverride : DEFAULT_STORY_ROOTS).map(createStoriesPathFor),addons: ['@storybook/addon-docs', '@storybook/addon-links', '@storybook/addon-a11y'],diff --git a/common/storybook/README.md b/common/storybook/README.mdnew file mode 100644index 000000000000..40930315f327--- /dev/null+++ b/common/storybook/README.md@@ -0,0 +1,127 @@+# Storybook++Storybook is where a UI change gets looked at before the stack runs.+CI also takes a light and a dark snapshot of each story, and visual review compares them with the baselines.++The setup lives in `common/storybook/.storybook/`:++- `main.ts` has the story globs and the Vite config.+- `preview.tsx` has the global decorators and parameters.+- `test-runner.ts` is the snapshot runner and reads the `testOptions` story parameters.+- `decorators/` has one file per global decorator.++More docs:++| Read | When you |+| ---------------------------------------------- | --------------------------------------------------------------------------------------------------- |+| [Writing stories](docs/writing-stories.md) | write a story, or set its feature flags, date, URL, layout, theme or tags |+| [Mocking data](docs/mocking-data.md) | mock API responses, plan features, or the current user, team or preflight |+| [Snapshots](docs/snapshots.md) | pick `testOptions`, debug a timeout, an empty render or a flake, or need to know how baselines work |+| [Deterministic stories][deterministic-stories] | write a story that loads data, measures itself or uses timers, or fix one that flakes |++[deterministic-stories]: ../../docs/published/handbook/engineering/conventions/frontend-coding.md#deterministic-stories++## Run it locally++```bash+pnpm storybook+```++Storybook indexes every story in the repo by default, and the first page load compiles all of it.+To work on a few stories, set `STORYBOOK_STORIES` to the directories or story files you need.+It takes a comma-separated list of paths relative to the repo root. A directory includes every `*.stories.{js,jsx,ts,tsx}` file under it.++```bash+STORYBOOK_STORIES=frontend/src/toolbar pnpm storybook+STORYBOOK_STORIES=frontend/src/scenes/insights,products/logs/frontend pnpm storybook+STORYBOOK_STORIES=frontend/src/lib/lemon-ui/LemonButton/LemonButton.stories.tsx pnpm storybook+```++Use the variable instead of editing the `stories` list in `main.ts`.+That edit is easy to commit by mistake, and it changes the set for every other run in the checkout.+Storybook reads the variable when it starts, so restart it to change the set.++A narrow set also helps when the sidebar shows no stories at all.+One story file the indexer can't parse empties the whole index, and a set that leaves it out still renders.++Without the variable, Storybook indexes the default roots in `main.ts`: `frontend/src`, `products/**/frontend`, `products/**/mcp/apps`, `services/mcp/src/ui-apps` and `packages/quill/packages/charts/src`.+A story file outside those roots is never served. CI never sets the variable.+`.github/scripts/verify-storybook-new-stories.sh` keeps its own copy of the default roots, so change both when you add a root.++### What `pnpm storybook` does++`pnpm storybook` runs the `start` script of `common/storybook` through turbo:++1. `pnpm build:products` generates the product manifests the app imports.+2. `pnpm build:workers` builds the web workers into `common/storybook/.workers`, which Storybook serves under `/static`. Without them every `new Worker(...)` gets a 404, and the error fails any story whose play function is still running.+3. `storybook dev -p 6006` starts the server.++Turbo drops env vars that a task doesn't declare.+`common/storybook/turbo.json` declares `STORYBOOK_STORIES` for `start`, so add any new variable that `main.ts` reads there too.++### Open one story++`http://localhost:6006/index.json` lists every story ID.+An ID is the kebab-case title, two dashes, then the kebab-case export name: `title: 'Scenes-Other/Toolbar'` with `export const Heatmap` is `scenes-other-toolbar--heatmap`.++This URL shows one story without the Storybook UI, in the theme you pick:++```text+http://localhost:6006/iframe.html?viewMode=story&id=<story-id>&globals=theme:dark+```++## Run the snapshot runner locally++CI takes the snapshots, so you rarely need this.+It helps when a story fails only in the runner, for example on a timeout.++The runner needs a static build, the same as in CI.+Against `pnpm storybook`, almost every story fails with `globalThis.__getContext is not a function`.+The build uses the same port, so stop the dev server first. Then, from `common/storybook`:++```bash+pnpm exec playwright install chromium+pnpm build:products && pnpm build:workers # once, if `pnpm storybook` hasn't run them yet+STORYBOOK_STORIES=frontend/src/toolbar pnpm exec storybook build --test -o /tmp/storybook-static+pnpm exec http-server /tmp/storybook-static --port 6006 --silent &+STORYBOOK_STORIES=frontend/src/toolbar pnpm exec test-storybook --browsers chromium -u+```++- `test-storybook` reads the story list from `main.ts` in its own process, so give it the same `STORYBOOK_STORIES` as the build. Otherwise it collects every story in the repo, and each one the build doesn't have fails with "Couldn't find story matching id".+- `-u` writes fresh images. Without it, the runner compares each story with the image an earlier local run left in `frontend/__snapshots__/`, and an old image fails the story with a size or pixel diff.+- Images go to `frontend/__snapshots__/`, which git ignores. Failure images go to `frontend/__snapshots__/__failures__/` under the directory you ran from, so delete `common/storybook/frontend/` afterwards.+- These images are not the baseline. Visual review keeps the baseline hashes in `frontend/snapshots.yml`. See [Snapshots](docs/snapshots.md#baselines-and-visual-review).++Other scripts in `common/storybook/package.json`:++| Script | What it does |+| ----------------------- | ----------------------------------------------------------------------------------------------------- |+| `test:visual:debug` | Runs the runner with `PWDEBUG=1`, which opens the Playwright inspector, in Chromium and WebKit. |+| `test:visual:update` | Runs the runner in the Playwright Docker image against `host.docker.internal:6006` and writes images. |+| `test:visual:ci:update` | What CI runs: `test-storybook -u --junit --no-index-json --maxWorkers=2`. |++The runner reads these env vars:++| Variable | Effect |+| ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |+| `TARGET_URL` | The Storybook URL to test. The default is port 6006 on this machine. |+| `CI` | Turns on the wait for network idle before each snapshot. |+| `STORYBOOK_INCLUDE_TAGS`, `STORYBOOK_EXCLUDE_TAGS`, `STORYBOOK_SKIP_TAGS` | Override which tags the runner collects, drops or skips. CI sets `STORYBOOK_SKIP_TAGS=test-skip,test-skip-<browser>`. |++The runner is `@storybook/test-runner`. See its [docs](https://storybook.js.org/docs/writing-tests/test-runner).++## Adding new Tailwind classes++`@tailwindcss/postcss` compiles Tailwind on the initial build.+Webpack's HMR does not re-run PostCSS when story content changes, so a newly used Tailwind utility (for example `bg-[rebeccapurple]`) won't appear until you restart Storybook.+Classes already present in the codebase hot-reload fine.++## Detect Storybook from app code++`lib/utils/dom.ts` has two checks:++- `inStorybook()` is true in any Storybook page.+- `inStorybookTestRunner()` is true only while the runner takes snapshots. The runner sets its user agent before any page script runs, so a check at module scope sees it too.++App code uses them to freeze values that change on every run, for example a fixed query ID in `dataNodeLogic` and a still progress bar in `LoadingBar`.+Prefer a mock or a parameter in the story. Use these checks only when the value comes from inside the component and no mock reaches it.diff --git a/common/storybook/docs/mocking-data.md b/common/storybook/docs/mocking-data.mdnew file mode 100644index 000000000000..0a4960bf041c--- /dev/null+++ b/common/storybook/docs/mocking-data.md@@ -0,0 +1,150 @@+# Mocking data in stories++Stories talk to the PostHog API through a Mock Service Worker that starts in `preview.tsx`.+Every request goes to the worker first: a story mock, then a default mock, then the network.++## Mock API responses++Two helpers in `frontend/src/mocks/browser.tsx` add mocks for one story:++| Helper | Where it goes | Use it when |+| -------------------------- | ------------------------------------------------ | -------------------------------------------------------------- |+| `mswDecorator(mocks)` | `decorators: [...]` on the meta or on a story | The mocks are fixed for the story. This is the usual choice. |+| `useStorybookMocks(mocks)` | Inside `render`, a story function or a decorator | The mocks depend on `args` or on other values built in render. |++```ts+decorators: [+ mswDecorator({+ get: {+ '/api/environments/:team_id/insights/': toPaginatedResponse([insight]),+ '/api/environments/:team_id/insights/:id/': ({ params }) => insightsById[params.id as string],+ },+ post: {+ '/api/environments/:team_id/query/': async ({ request }) => {+ const body = await request.json()+ return body.query.kind === 'TrendsQuery' ? trendsResult : [400, { detail: 'Unexpected query' }]+ },+ },+ delete: { '/api/environments/:team_id/insights/:id/': [204] },+ }),+]+```++- The methods are `get`, `post`, `put`, `patch`, `delete` and `options`. Paths use MSW syntax: `:param` matches one segment.+- `mswDecorator` adds a trailing slash to every path, so a default mock with a slash can't shadow a story mock without one.+- Story mocks go before the defaults, so a story mock always wins.+- `mswDecorator` also reads `parameters.msw.mocks`, and its own argument wins over them. `parameters.msw.mocks` does nothing without `mswDecorator` on the story or meta.+- A meta `mswDecorator` and a story `mswDecorator` both apply. The story's decorator runs last, so its mocks win for the same path.+- `worker.resetHandlers()` runs before each story, so no mock carries over to the next one.++### What a mock returns++| The mock returns | The response |+| ------------------------------------------------ | --------------------------------------------------------------- |+| An object, an array or any other JSON value | That value as a JSON body, status 200 |+| `[status, body]` | That body with that status |+| `[status]` | An empty body with that status |+| A `Response` or an MSW `HttpResponse` | That response, as is |+| `undefined` or `null` | An empty 200 |+| A function `({ request, params, cookies }) => …` | Whatever the function returns, from this list. It can be async. |++- An empty 200 is not a network error. Return `HttpResponse.error()` to model a failed request.+- A request that never answers keeps a loader on screen: `() => new Promise(() => {})`. Set `testOptions.waitForLoadersToDisappear: false` and wait for the loading state with `waitForSelector`, or the story times out.+- `toPaginatedResponse(results)` and `EMPTY_PAGINATED_RESPONSE` from `~/mocks/handlers` build a DRF page.++### `environments` and `projects` paths++`/api/environments/` is an alias of `/api/projects/` on the backend.+A mock on an `/api/environments/...` path also answers the same `/api/projects/...` path, unless a mock already covers that one.+The alias goes one way only: a `/api/projects/...` mock never answers an `/api/environments/...` request.++### Requests nobody mocks++The worker logs a warning and lets the request through to the network. Locally that is the Storybook server, in CI the static build, so the request fails or returns HTML.+That can resolve after the snapshot and change it. Mock every request the story makes.+Look for `[MSW] Warning: intercepted a request without a matching request handler` in the browser console to find them.++## Default mocks++`frontend/src/mocks/handlers.ts` answers the requests most scenes make on load, so a story mocks only what it shows. Among them:++- `/api/users/@me/`, `/api/organizations/@current/`, `/api/environments/@current/` and `/api/projects/@current/` return the default user, organization, team and project.+- `/_preflight` returns `frontend/src/mocks/fixtures/_preflight.json`: not cloud, debug on, region US, `site_url` `http://localhost:6006`.+- Many common lists return empty pages, for example dashboards, actions, feature flags and experiments. Cohorts return one default cohort.+- `POST /api/environments/:team_id/query/` returns `{ results: [] }`.+- The posthog-js endpoints answer `ok`, so the app's own analytics never reach a real host.+- Requests that would add a banner that changes over time return a quiet answer: the posthog-js release check returns no tags, and the proxy check returns a working proxy.+- The sidebar starts with four starred products, so a scene story doesn't show the whole product catalog.++Read `handlers.ts` before you mock a path. A default may already return what you need, and your mock replaces it for the whole story.++## The app context every story starts with++`common/storybook/.storybook/app-context.ts` sets `window.POSTHOG_APP_CONTEXT`:++- `current_team` is `MOCK_DEFAULT_TEAM`, and `current_project` is `MOCK_DEFAULT_PROJECT`, both from `lib/api.mock`.+- `current_user` and `preflight` are empty, so the app fetches `/api/users/@me/` and `/_preflight`, and the default mocks answer.+- `persisted_feature_flags` holds the story's `featureFlags`.+- `resource_access_control` gives `manager` access to everything except the activity log and the toolbar, which are `viewer`.++To change the user, the organization or the preflight, mock its endpoint with a copy of the default:++```ts+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++mswDecorator({ get: { '/api/users/@me/': { ...MOCK_DEFAULT_USER, is_staff: true } } })+```++The team and the project work differently.+`teamLogic` and `projectLogic` take them from the app context when they mount and never request them, so a mock of their endpoint changes nothing.+Set them after mount instead, with `teamLogic.actions.loadCurrentTeamSuccess` or `projectLogic.actions.loadCurrentProjectSuccess`:++```tsx+render: () => {+ const { loadCurrentTeamSuccess } = useActions(teamLogic)+ useDelayedOnMountEffect(() => {+ loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, created_at: '2023-05-23T00:00:00Z' })+ })+ return <App />+},+```++`OnboardingWelcome.stories.tsx` uses this pattern. `withKea` remounts the logics for the next story, so nothing carries over.++`lib/api.mock.ts` holds `MOCK_DEFAULT_USER`, `MOCK_DEFAULT_TEAM`, `MOCK_DEFAULT_ORGANIZATION`, `MOCK_TEAM_ID` and the other defaults. `frontend/src/mocks/fixtures/` holds larger JSON fixtures.++## Plan features: `useAvailableFeatures`++```ts+import { useAvailableFeatures } from '~/mocks/features'+import { AvailableFeature } from '~/types'++export const WithAdvancedPermissions: Story = {+ render: () => {+ useAvailableFeatures([AvailableFeature.ADVANCED_PERMISSIONS])+ return <MyComponent />+ },+}+```++- The default user and organization mocks return these features as `available_product_features`, so paywalled UI unlocks.+- `withKea` resets the list to none before each story. The list is module state, so set it in every story that needs it, not once in a shared helper that runs only for the first story.+- Call it in a decorator or in `render`, before the component mounts. The user loads once per story.++## Kea and the router++`withKea` gives each story a fresh start:++1. It resets the mocks to the defaults.+2. It unmounts every logic the previous story mounted, so an unfinished listener can't write into the next story's store.+3. It clears the cached "has data" answers that empty states read, so one story's data can't hide the next story's empty state.+4. It starts kea with an in-memory router history.+5. It mounts `featureFlagLogic`, `teamLogic`, `projectLogic`, `userLogic` and the router.++The story renders only after this reset. A story can then mount its own logics, for example with `useMountedLogic(myLogic(props))`, and drive them with actions to reach a state.+Drive a logic from a `useEffect` or a `play` function, after mount, and wait for the result with `testOptions.waitForSelector`.++## Helpers for common surfaces++- `createInsightStory(insight, mode)` in `frontend/src/scenes/insights/__mocks__/createInsightScene.tsx` mocks the endpoints an insight scene needs and renders it.+- Story-only fixtures and fakes live next to the story in a `__mocks__/` folder, for example `frontend/src/toolbar/__mocks__/`.diff --git a/common/storybook/docs/snapshots.md b/common/storybook/docs/snapshots.mdnew file mode 100644index 000000000000..7605aa739173--- /dev/null+++ b/common/storybook/docs/snapshots.md@@ -0,0 +1,103 @@+# Snapshots and visual review++In CI, `common/storybook/.storybook/test-runner.ts` loads each story in Playwright and takes a light and a dark snapshot.+Visual review compares each snapshot with its baseline and asks a person to approve any change.+A story that renders two different pictures for the same code blocks unrelated PRs, so most of this file is about making the picture the same on every run.++## `testOptions`++Set them in `parameters.testOptions` on the meta or on a story. A story's keys merge with the meta's.++### Waiting++| Key | Default | What it does |+| --------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------- |+| `waitForLoadersToDisappear` | `true` | Waits until no loader shows, for 5 seconds (10 for dashboard and Max stories). See the loader list below. |+| `waitForSelector` | none | Waits until the selector matches. An array waits for every selector. `'iframe.X >>> .inner'` waits inside an iframe. |+| `waitForSelectorTimeout` | the Playwright timeout | The timeout for `waitForSelector`, in milliseconds. |+| `allowImagesWithoutWidth` | `false` | Skips the wait for every image to load. Use it for a story that shows a broken image on purpose. |+| `skipIframeWait` | `false` | Skips the wait for iframes and for network idle. Use it for an external iframe or background polling. |+| `jestTimeout` | 60 seconds | The time the whole story may take. A slow story is usually a bug, so raise this only with a reason. |++The runner counts these as loaders: `.Spinner`, `.quill-spinner`, `.LemonSkeleton`, `.LemonTableLoader`, `.Toastify__toast`, `[aria-busy="true"]`, `.SessionRecordingPlayer--buffering`, `.Lettermark--unknown` and `[data-attr="loading-bar"]`.++- A toast counts as a loader. A story that leaves a toast on screen times out.+- The loader wait checks only the first element that matches. When a story shows more than one loader, wait for content that renders after the last one.+- `waitForSelector` waits for existence. Pick an element that exists only after the async work is done, such as a row from the mocked data, not a container that renders before the data.+- For Monaco, wait for `.CodeEditor[data-editor-ready="true"]`. `.monaco-editor` also matches a root that Monaco adds to `<body>` before any editor mounts.+- A story that shows a loading state on purpose sets `waitForLoadersToDisappear: false` and waits for the loader with `waitForSelector`.++### Viewport and target++| Key | Default | What it does |+| ----------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- |+| `viewport` | 1280 × 720 | The page size for the story. |+| `viewportWidths` | none | One snapshot per preset width: `narrow` 568, `medium` 960, `wide` 1300, `superwide` 1920, all 720 tall. Timeouts scale with the count. |+| `snapshotTargetSelector` | `#storybook-root` | Snapshots one element. Throws with `layout: 'fullscreen'`. |+| `includeNavigationInSnapshot` | `false` | For `layout: 'fullscreen'`, snapshots the viewport with the navigation instead of the scene alone. |++`viewportWidths` takes one snapshot per width instead of the single default one, and names each `<story-id>--<width>--<theme>`:++```ts+export const MyStoryViewports: Story = createInsightStory(fixture, 'edit')+MyStoryViewports.parameters = {+ testOptions: { viewportWidths: ['medium', 'wide', 'superwide'] },+}+```++That gives `my-story-viewports--medium--light` and so on. `frontend/src/scenes/data-management/definition/DefinitionView.stories.tsx` is a working example.++### Themes, browsers and charts++| Key | Default | What it does |+| ------------------ | -------------- | ---------------------------------------------------------------------------------------------------------------------- |+| `skipLightMode` | `false` | No light snapshot. For a story pinned to dark. |+| `skipDarkMode` | `false` | No dark snapshot. For a story that has no dark mode, or a known dark mode issue. |+| `snapshotBrowsers` | `['chromium']` | Every browser runs the story, but only these take snapshots. `[]` runs the story and its play function and takes none. |+| `skipCanvasDraw` | `false` | Quill charts don't paint their canvas. Use it when the chart is not what the story shows and its paint flakes. |++`snapshotBrowsers: []` suits a story whose picture can't be the same twice, but whose play function still tests something.++## What the runner does before each snapshot++You don't need to add waits for any of this. Knowing the order helps when a story times out or flakes.++1. It loads the story and waits for `load`. In CI it also waits for network idle.+2. The `storybook-test-runner` body class turns off transitions and animations, pins the end state of a few animations, and hides scrollbars and decorative overlays. A component opts in to more with `.storybook-test-runner &` in its styles.+3. It makes hidden `content-visibility` content visible, fires a resize, and waits 300 ms for resize observers.+4. It runs the loader wait and `waitForSelector`.+5. For each theme, it sets `body[theme]` and the color scheme, then:+ - makes lazy images eager, waits until every image has loaded and decoded, and hides GIFs;+ - waits up to 8 seconds for iframes, plus 1 second;+ - scrolls the window and the scroll containers back to the top;+ - waits until the body size stops changing, for up to 3 seconds;+ - waits 1 more second;+ - waits until no quill chart canvas is still painting.+6. It captures the target. A component snapshot grows to include a popover or a tooltip that overflows the root.++An iframe that loads `/embedded/` or `/shared/` gets a fixed placeholder page, so a shared dashboard or embed never loads the real app inside the story.++### Errors you may see++- **"rendered nothing"**: the snapshot target had no size. A component that positions itself, such as a modal or a popover, needs a decorator that gives it a sized box. Tag the story `test-skip` only when nothing can show it.+- **A timeout in the loader wait**: a spinner, a skeleton or a toast is still on screen. An unmocked request or a request that never answers is the usual cause.+- **A timeout in `waitForSelector`**: the selector never matched. Open the story locally with the same parameters and look for the element.+- **The story passes locally but fails in CI**: CI waits for network idle, its machine can use a different time zone, and it is slower. Look for polling, unmocked requests and time-of-day text.++## Baselines and visual review++- Baselines are hashes in `frontend/snapshots.yml`, one entry per `<story-id>[--<width>]--<theme>`, signed by visual review. The PNGs under `frontend/__snapshots__/` are not the baseline, and CI deletes them before each run.+- On a PR, CI runs only the stories that the diff can affect, in Chromium. Master and the merge queue run every story, in WebKit too.+- The `run-ci-frontend` label runs every story on a PR. Use it to bring back a baseline for a story that the diff doesn't touch. The label takes effect on the next push or ready-for-review, not when you add it.+- Each changed snapshot shows up in the visual review run for the PR. A person approves it there, and finalizing the run commits the new hashes to the PR branch.+- A finalized run pushes a commit to the branch. In a stack, that forces a restack of every layer above it, so put the stories that change in the top layer.+- New and changed story files run up to three more times. A story that renders two different pictures across those runs fails as flaky before anyone approves it.+- A quarantined story still renders and is diffed, but it doesn't gate the PR. The Quarantine part of [the visual review README](../../../products/visual_review/README.md#current-state) says when to approve its new picture and how a quarantine ends.++## Make a story deterministic++[Deterministic stories](../../../docs/published/handbook/engineering/conventions/frontend-coding.md#deterministic-stories) in the frontend coding conventions lists each pattern that caused a real quarantine, and its fix.++Before you change a flaky story, compare the two pictures. The Flakiness tab in visual review lists the stories that flaked on master, and each run shows the baseline and the variant.+The region that differs usually names the cause: a strip at the bottom is a height race, an empty chart is a canvas reset, a shifted block is a width race, a skeleton is a late load.+Some flakes are a stale baseline. Compare with the git history of `frontend/snapshots.yml` first.diff --git a/common/storybook/docs/writing-stories.md b/common/storybook/docs/writing-stories.mdnew file mode 100644index 000000000000..5ce1a4c04bca--- /dev/null+++ b/common/storybook/docs/writing-stories.md@@ -0,0 +1,178 @@+# Writing stories++## Shape of a story file++```tsx+import { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'++import { mswDecorator } from '~/mocks/browser'++import { MyComponent } from './MyComponent'++const meta: Meta<typeof MyComponent> = {+ title: 'Components/My component',+ component: MyComponent,+ decorators: [+ mswDecorator({+ get: { '/api/environments/:team_id/my_things/': { results: [{ id: 1, name: 'First thing' }] } },+ }),+ ],+ parameters: {+ layout: 'padded',+ mockDate: '2024-01-15',+ featureFlags: [FEATURE_FLAGS.MY_FLAG],+ testOptions: { waitForSelector: 'text=First thing' },+ },+}+export default meta++type Story = StoryObj<typeof MyComponent>++export const Default: Story = {}++export const Empty: Story = {+ decorators: [mswDecorator({ get: { '/api/environments/:team_id/my_things/': { results: [] } } })],+ parameters: { testOptions: { waitForSelector: 'text=No things yet' } },+}+```++Each committed story should show a state that no other story shows.+Every story adds a light and a dark baseline, and every later change to that surface has to approve both again.+A story you write only to look at a change, or for a PR screenshot, is scratch. Keep it out of the commit.++A story must render the same picture on every run.+[Deterministic stories](../../../docs/published/handbook/engineering/conventions/frontend-coding.md#deterministic-stories) lists the patterns that broke that, with a fix for each.++## Global decorators++Every story runs inside six global decorators from `common/storybook/.storybook/preview.tsx`.+Each one reads a parameter, so set state through the parameter, not by calling logic actions.+An action dispatched from a story can run after the snapshot, or a load that finishes later can undo it.++| Decorator | Parameter | What it does |+| ------------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------- |+| `withKea` | none | Resets kea, the router and the mocks for each story, and resets `useAvailableFeatures` to none. |+| `withMockDate` | `mockDate` | Pins the clock with `MockDate.set`, or resets it when the story sets none. |+| `withFeatureFlags` | `featureFlags` | Writes the flags into `window.POSTHOG_APP_CONTEXT.persisted_feature_flags`. |+| `withTheme` | the `theme` global | Sets `document.body[theme]` to `light` or `dark`. |+| `withPageUrl` | `pageUrl` | Pushes the URL to the kea router after the story mounts. |+| `withChartCanvasSnapshot` | `testOptions.skipCanvasDraw` | Stops quill charts from painting their canvas, only in the test runner. |++A decorator in a story or meta, such as `mswDecorator`, sits inside all of them.+Before each render, Storybook also waits for the Inter and RoundHog fonts. Canvas charts measure text when they paint and never paint again after a font arrives.++## How story and meta parameters combine++Storybook merges a story's `parameters` into the meta's.+Plain objects merge key by key at every depth. Every other value, arrays included, replaces the meta's value.++- `testOptions` in a story keeps the meta's other `testOptions` keys.+- An array `featureFlags` in a story replaces the meta's list. Repeat the meta's flags in it.+- A record `featureFlags` merges with a meta record.++## `featureFlags`++```ts+parameters: { featureFlags: [FEATURE_FLAGS.MY_FLAG] } // each listed flag is on+parameters: { featureFlags: { [FEATURE_FLAGS.MY_EXPERIMENT]: 'test_b' } } // pin a variant+parameters: { featureFlags: { 'bool-flag': true, 'my-experiment': 'test' } } // mix both+```++- The default is no flags, so every flag is off.+- `featureFlagLogic` reads the persisted flags on mount and keeps them under every later flag load, so a pinned variant survives the empty flag callback posthog-js fires on load.+- `STORYBOOK_FEATURE_FLAGS` from `lib/constants` is every flag except `TODAY_RAIL_NAV` and `INTERNAL_FEEDBACK_WIDGET`. The rail swaps the whole navigation, so a story opts in to it on its own. Use the constant for a scene story that shows the app with everything on.+- A component that reads flags from a different posthog-js instance, such as the toolbar, needs that instance's own override. `Toolbar.stories.tsx` calls `toolbarPosthogJS.featureFlags.overrideFeatureFlags` for this reason.+- The parameter only sets the flag. When the render also depends on other runtime state, such as localStorage, an `APP_CONTEXT` field or a logic that has to resolve an entry, set that up too. A small wrapper in the story file can set the state and mount the logic before it renders the component. Don't add test-only props to the production component.++### Don't set flags from a story++Never call `featureFlagLogic.actions.setFeatureFlags` from a story.+It works in jest, where `NODE_ENV` is `test`, but not in the built Storybook that visual review uses.+There, posthog-js loads flags and fires `onFeatureFlags` with an empty set.+That dispatches `setFeatureFlags` and wipes the flags the story set, so the unit test passes and the snapshot shows the flag-off branch.++Don't work around it by turning off posthog-js flags, for example with `advanced_disable_feature_flags`, either.+`appLogic.showApp` waits until `receivedFeatureFlags` is true, and the same `onFeatureFlags` callback sets it.+Without that callback, every `Scenes-App/*` story waits for a 3 second timeout and flakes.+The login page is the exception: with no user on `/login`, `showApp` renders without waiting for flags. Login stories still need the `featureFlags` parameter to get a fixed flag state.++### Why the parameter works++`withFeatureFlags` calls `setFeatureFlags` in `frontend/src/mocks/browser.tsx`, which writes the flags, array or record, to `window.POSTHOG_APP_CONTEXT.persisted_feature_flags`.+`getPersistedFeatureFlags` in `frontend/src/lib/logic/featureFlagLogic.ts` reads that as the initial value of `featureFlagLogic`, and `spyOnFeatureFlags` always merges it in as the baseline.+So booleans and pinned variants both survive the empty `onFeatureFlags` callback.+The one production-side piece is that `getPersistedFeatureFlags` accepts the record form as well as the array form the server sends.++## `mockDate`++```ts+parameters: {+ mockDate: '2024-01-15'+} // also a timestamp or a Date+parameters: {+ mockDate: '2024-01-15 10:01:00'+}+```++- `Date.now()`, `new Date()` and dayjs read the pinned time. Timers still run on the real clock.+- Write the dates in mock data relative to the pinned date. A story that shows "3 days ago" from a real clock fails next week on every branch.+- Nothing pins the time zone. The browser uses the zone of the machine it runs on, so a time of day can render differently on your machine and in CI. Check it in the CI snapshot, or format it in UTC.++## `pageUrl`++```ts+parameters: {+ pageUrl: urls.insightNew()+}+```++- The router uses an in-memory history per story, so the browser URL never changes and stories don't leak routes into each other.+- A story that renders the whole app (`<App />` from `scenes/App`) needs `pageUrl` to pick the scene.+- `pageUrl` pushes in an effect, after the story's first render. A component that reads the URL during that first render sees the default route once, then the pushed one.++## `layout`++| Value | Body class in the runner | What the snapshot captures |+| -------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------- |+| `'padded'` (default) | `storybook-test-runner--padded` | `#storybook-root`, which shrink-wraps its content, with a transparent background |+| `'centered'` | `storybook-test-runner--centered` | `#storybook-root` |+| `'fullscreen'` | `storybook-test-runner--fullscreen` | The scene: the last of `body` and `main`, without navigation unless `includeNavigationInSnapshot` |++- In `padded`, content that measures its container when it mounts (Monaco, charts, React Flow) takes whatever width the root had. Wrap it in a fixed width such as `w-[42rem]`, not a `max-w-*`.+- In `fullscreen`, the app shell has `min-height: 100vh`. Content shorter than the viewport leaves a blank strip under it. Add a decorator that lets the shell hug its content when that matters.+- The `storybook-viewport-layout` body class keeps the app shell at the viewport height instead. `TerminalScene.stories.tsx` uses it for a docked panel that resizes.+- `testOptions.snapshotTargetSelector` throws with `fullscreen`. Use `padded` to snapshot one element.++## Theme++- The `theme` global sets `body[theme]`. The toolbar in Storybook switches it, and a URL picks it with `&globals=theme:dark`.+- A story can set `globals: { theme: 'dark' }`, but the runner still takes a light and a dark snapshot and sets the theme for each one. A story pinned to dark sets `testOptions.skipLightMode: true` too.+- `themeLogic.isDarkModeOn` follows the runner's theme. A component that reads it can lag one render behind the attribute. Read `document.body.getAttribute('theme')` when a snapshot shows the wrong theme.++## `viewMode`, `docs` and other Storybook parameters++- Many stories set `viewMode: 'story'`. Nothing in the runner reads it, and it changes nothing that a snapshot shows.+- `docs`, `controls`, `actions` and `options` are standard Storybook parameters for the Storybook UI. The runner ignores them.+- `parameters.msw.mocks` works only with `mswDecorator` on the story or meta. No global decorator reads it. See [Mocking data](mocking-data.md).+- A parameter that only one file uses, such as `narrow`, `width` or `tab`, is read by that file's own `render` or `beforeEach`. Read the file before you copy one.++## Story functions: `render`, `play`, `beforeEach`, `loaders`++- `render(args, context)` builds the story. `context.parameters` holds the merged parameters, so a meta `render` can read a story parameter.+- `play` runs after the render, in the browser, and the runner waits for it before the snapshot. In a play function, import `within` and `waitFor` from `@testing-library/dom`, which has a 15 second async timeout here. `storybook/test` has its own shorter default.+- `beforeEach` runs before each render and can return a cleanup function. Use it for setup that must be undone, such as a body class.+- On a retry the runner remounts the story and runs `play` again. A play function that fails or doesn't settle within 30 seconds fails the story.++## Tags++| Tag | Effect |+| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |+| `'test-skip'` | The runner skips the story: no snapshot. Say why in a comment, for example a canvas the runner can't capture. |+| `'test-skip-webkit'` | The WebKit run skips the story. CI sets `STORYBOOK_SKIP_TAGS=test-skip,test-skip-<browser>`. `'test-skip-chromium'` works the same way. |+| `'!test'` | Removes Storybook's implicit `test` tag, so the runner never collects the story. Use it for a story that needs a live service. |+| `'autodocs'` | Storybook generates a docs page for the file. Only tagged files get one. |++Put tags on the meta (`tags: ['test-skip']`) to cover every story in the file, or on one story.+A skipped story has no baseline, so visual review can't catch a regression in it. Fix the cause when you can, and skip only what the runner can't capture.diff --git a/common/storybook/turbo.json b/common/storybook/turbo.jsonindex 681acf615819..839629939186 100644--- a/common/storybook/turbo.json+++ b/common/storybook/turbo.json@@ -9,7 +9,8 @@"dependsOn": ["@posthog/frontend#prepare"]},"start": {- "dependsOn": ["@posthog/frontend#prepare"]+ "dependsOn": ["@posthog/frontend#prepare"],+ "passThroughEnv": ["$TURBO_EXTENDS$", "STORYBOOK_STORIES"]}}}diff --git a/docs/published/handbook/engineering/ai/writing-skills.md b/docs/published/handbook/engineering/ai/writing-skills.mdindex 1f471cd4eba7..bf091ad7b562 100644--- a/docs/published/handbook/engineering/ai/writing-skills.md+++ b/docs/published/handbook/engineering/ai/writing-skills.md@@ -107,6 +107,20 @@ Additional signals that a skill is the right answer even when tool prompts are aDon't write a skill for something the agent already one-shots from generic knowledge. A few real examples from review: `creating-isolated-project` or `finding-experiments` were unnecessary — the agent can do it without help. `setting-up-reverse-proxy` was the right call — the agent failed at it, and the skill needed to ship code snippets it couldn't derive. The bar is PostHog-specific judgement that a smart generalist agent wouldn't have, not project setup it can already handle.+### Docs or skill?++A skill holds the steps an agent follows for one job: the order of tool calls, the checks to run before it reports done, and the decisions it must not make alone.+Most of that is detail a person doing the same job would skip.++Everything else goes in docs, because people need it too.+That covers how a system works, how to set it up or run it, its options, and its gotchas.+Put it in a README next to the code or in an existing page under `docs/`, and have the skill link to it with a line on when to read it.+A published product skill links to the public page on posthog.com.+If an engineer would look something up without an agent, it belongs in docs.++The `working-with-charts` skill is the model.+The chart API docs live in the package. The skill keeps how to pick a chart, a few rules for its data, and what to check before calling the work done, and links to the package docs for the rest.+### How many skills is too many?A common worry when shipping a set of skills is "am I adding too many?" — and it's the right worry. Skill count is a budgeted, shared resource, not a free axis to expand. Agents pick skills from a list of _all_ available descriptions, and many harnesses **truncate that list** once it grows long. Every extra skill dilutes discovery for every other skill, so a bloated set makes each individual skill _less_ likely to fire, not more.diff --git a/docs/published/handbook/engineering/conventions/frontend-coding.md b/docs/published/handbook/engineering/conventions/frontend-coding.mdindex da723bd7a320..502971617732 100644--- a/docs/published/handbook/engineering/conventions/frontend-coding.md+++ b/docs/published/handbook/engineering/conventions/frontend-coding.md@@ -73,7 +73,7 @@ Hence the explicit separation between the data and view layers.- Before adding a test, make sure it earns its place and sits as low on the test pyramid as it can — the value/cost rubric in [Backend coding conventions › Testing](backend-coding#testing) is language-agnostic.- Write [logic tests](https://keajs.org/docs/intro/testing) for all logic files.- [react testing library](https://testing-library.com/docs/react-testing-library/intro/) tests are particularly useful for components with complex interactions or to guide future humans or agents when they're changing components without full context of the uses and edge cases- - Add all new presentational elements and scenes to [our storybook](https://storybook.dev.posthog.dev/). Run `pnpm storybook` locally.+ - Add all new presentational elements and scenes to [our storybook](https://storybook.dev.posthog.dev/). Run `pnpm storybook` locally. The [Storybook README](https://github.com/PostHog/posthog/blob/master/common/storybook/README.md) covers running it, writing stories, and mocking data.- In web Storybook play functions, import `within` and `waitFor` from `@testing-library/dom`. The preview configures their async timeout; `storybook/test` uses a separate default.- A story must render the same picture on every run. See [Deterministic stories](#deterministic-stories).diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.mdindex 5d24b3b926a6..5c84d753a1aa 100644--- a/docs/published/handbook/engineering/developing-locally.md+++ b/docs/published/handbook/engineering/developing-locally.md@@ -330,12 +330,15 @@ You can narrow the run down to only files under matching paths:hogli test frontend/src/lib/components/DateFilter/DateFilter.test.tsx```-To update all visual regression test snapshots, make sure Storybook is running on your machine (you can start it with `hogli storybook` in a separate Terminal tab). You may also need to install Playwright with `pnpm exec playwright install`. And then run:+CI takes the visual regression snapshots of every Storybook story, and you approve changed ones in the visual review run on your PR.+To look at stories locally, run `pnpm storybook`. Set `STORYBOOK_STORIES` to a directory or a story file to load only those:```bash-hogli storybook:test+STORYBOOK_STORIES=frontend/src/toolbar pnpm storybook```+The [Storybook README](https://github.com/PostHog/posthog/blob/master/common/storybook/README.md) covers the local snapshot runner, writing stories, and mocking data.+### BackendFor backend tests, run:diff --git a/tools/hogli-commands/hogli_commands/verify_layers.py b/tools/hogli-commands/hogli_commands/verify_layers.pyindex de904e1676f6..8038c658d44c 100644--- a/tools/hogli-commands/hogli_commands/verify_layers.py+++ b/tools/hogli-commands/hogli_commands/verify_layers.py@@ -110,7 +110,7 @@ FALLBACK_RULE = KindRule(kind=ChangeKind.PURE_LOGIC, globs=("*",), sufficient=CoCOMPLEXITY_LAYERS: dict[ComplexityLayer, str] = {ComplexityLayer.OPENAPI: "Start the services with `hogli up -d`, run `hogli build:openapi`, and commit the generated types.",- ComplexityLayer.STORYBOOK: "Render the affected stories with `pnpm storybook` and compare them before and after.",+ ComplexityLayer.STORYBOOK: "Render the affected stories with `STORYBOOK_STORIES=<dir> pnpm storybook` and compare them before and after.",ComplexityLayer.STACK: "Start the stack with `hogli up -d` and `hogli wait`, then exercise the change in the app.",ComplexityLayer.END_TO_END: "Run the changed Playwright specs with `hogli test <spec>` against a running stack.",}