: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
fix(storybook): stabilize the last quarantined stories and document deterministic stories (#112478)
Julian Bez41296e8359ad
diff --git a/.agents/skills/writing-ui-components/SKILL.md b/.agents/skills/writing-ui-components/SKILL.mdindex af20ece32cdb..1d90d8e7039c 100644--- a/.agents/skills/writing-ui-components/SKILL.md+++ b/.agents/skills/writing-ui-components/SKILL.md@@ -221,6 +221,10 @@ acts on it.to 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)).+ A story must render the same picture on every run: pin the clock, wait for readiness, and fix+ the width of self-measuring content. Read+ [Deterministic stories](../../../docs/published/handbook/engineering/conventions/frontend-coding.md#deterministic-stories)+ before you write a story that loads data, measures itself, or uses timers, and when a story flakes.## Anti-patternsdiff --git a/.claude/commands/conventions.md b/.claude/commands/conventions.mdindex b00d1ad87047..03503bafac9d 100644--- a/.claude/commands/conventions.md+++ b/.claude/commands/conventions.md@@ -82,6 +82,7 @@ Hence the explicit separation between the data and view layers.- [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.posthog.net/). Run `pnpm storybook` locally.- 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. Read [Deterministic stories](../../docs/published/handbook/engineering/conventions/frontend-coding.md#deterministic-stories) when a story flakes or before you write one that loads data, measures itself, or uses timers.---diff --git a/common/storybook/.storybook/README.md b/common/storybook/.storybook/README.mdindex 15269bdc6b55..05745cad0de4 100644--- a/common/storybook/.storybook/README.md+++ b/common/storybook/.storybook/README.md@@ -9,13 +9,10 @@ Storybook. Classes already present in the codebase hot-reload fine.## Storybook visual regression tests-In CI we use playwright to load our storybooks scenes and take snapshots of them+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.-If they have changed we commit those snapshots back to the PR--This lets you check if you have broken the UI unexpectedly or changed it in the way you expected--You can check `test-runner.ts` to see how this is done+`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-runnerdiff --git a/docs/published/handbook/engineering/conventions/frontend-coding.md b/docs/published/handbook/engineering/conventions/frontend-coding.mdindex a9f95afa0c0b..e1ba2cd89d86 100644--- a/docs/published/handbook/engineering/conventions/frontend-coding.md+++ b/docs/published/handbook/engineering/conventions/frontend-coding.md@@ -74,5 +74,76 @@ Hence the explicit separation between the data and view layers.- [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.- 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).++#### Deterministic stories++By default a story renders a light and a dark visual review snapshot on every run that selects it (`testOptions.skipLightMode` and `skipDarkMode` turn one off).+A story that renders two different pictures for the same code blocks unrelated PRs, collects tolerations, and ends up quarantined.+Every pattern below caused a real quarantine. Each one has a fix that removes the race instead of hiding it.++##### What the runner already does++`common/storybook/.storybook/test-runner.ts` turns off animations and transitions, makes lazy images eager and waits for them to decode, preloads fonts, waits for a known loader to disappear, waits for network idle, and sets the theme on `body[theme]` before each snapshot.+Do not add your own waits for these.+The loader wait checks only the first element that matches a loader selector.+When a story shows more than one loader, set `waitForSelector` to content that renders after the last one.+The runner does not know when your own async content is done, when a timer changes the UI, or when a component measured itself at the wrong size.++##### Pin the clock++Relative text ("3 days ago", "2 years ago") changes as the wall clock moves, so a story that passes today fails next week on every branch at once.+Set `parameters.mockDate`, and write the dates in mock data relative to that date.++##### Wait for readiness, not for existence++`testOptions.waitForSelector` waits until the selector matches. Pick an element that only exists after the async work is done.+A container that renders before its data loads does not help.++- Monaco: wait for `.CodeEditor[data-editor-ready="true"]`. `.monaco-editor` also matches Monaco's shared overflow root on `<body>`, which exists before any editor mounts.+- A panel that loads its own data after the page loader is gone: wait for an element that renders only from the loaded data, for example a button that shows only when the list arrived empty.++Mock every request the story fires with `mswDecorator`. An unmocked request can resolve after the snapshot.++##### Give self-measuring content a fixed width++`layout: 'padded'` makes `#storybook-root` an inline block that shrink-wraps its content (`frontend/src/styles/base.scss`).+Content that measures its container when it mounts (Monaco, charts, React Flow) then takes whatever width the root had at that moment.+The first story in a file is the usual victim, because the layout class lands right before its snapshot.+Wrap the content in a fixed width (`w-[42rem]`), not a `max-w-*`.++##### Do not let the viewport set the height++The app shell has `min-height: 100vh`. When the viewport at capture time is taller than the content, the shell grows to the viewport height and the snapshot gets a blank strip below the content.+Let the shell hug the content in that story, for example with a decorator that sets `.Navigation3000 { min-height: 0 }`.++##### Wait for timers to settle++UI that changes on a timer (player controls that hide after 1.5 seconds, toasts, auto-collapsing panels) gives a different picture depending on when the snapshot fires.+In the `play` function, wait for the settled state, not the first state.+For example, wait until the controls are visible and then until they are hidden again.++##### Read the theme from the DOM++The runner switches the theme by setting `body[theme]`. A component that reads a logic value such as `isDarkModeOn` can lag one render behind and draw the first frame in the wrong theme.+Read `document.body.getAttribute('theme')`, or a hook that reads it.++##### Do not chain layout on previous state++A computation that uses the current state to produce the next one (for example React Flow `fitView` padding computed from the current zoom) lands on a different result depending on how often a resize observer fires.+Compute from the target state (the zoom the fit lands on), and clamp it to the same limits the library uses.++##### Canvas charts++A resize resets a canvas bitmap, and the redraw runs on the next animation frame.+If the chart region changes size while the page settles (for example because a footer wraps after the chart width changes), the snapshot can catch an empty canvas.+Keep chart containers at a fixed size in stories, and avoid content around the chart whose height depends on the chart width.++##### Find the variant before you fix it++Look at both pictures before you change anything.+The Flakiness tab in visual review lists the stories that flaked on the default branch, and each run shows the baseline and the variant image.+The diff region 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 or wrong baseline. Compare the variant with the git history of `frontend/snapshots.yml` before you change the story.> Sync note: This file is also copied to posthog/posthog/.claude/commands/conventions.md for Claude Code. When updating this file, please also update the copy there.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex df0044f56b58..7617da3d5ccf 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2885,7 +2885,7 @@ snapshots:errortracking-exceptioncard--exception-card-base--light:hash: v1.k794b7964.40a5fd88410919603dc60b886450c6011806a70502e144dfc559380eec5cd9cf.LXtqQwhm5OiXOmRO3LnQdS-BtoNHpRABg21xA3_FthYerrortracking-exceptioncard--exception-card-header-widths--dark:- hash: v1.k794b7964.51badf8f8e16413e7e9d0cf410ea7b7ab349d566b2df111cd6ce8e52d6482f3a.LWGWR4hXx5Ax0XkCrRTxYq0LwuceCz-ox3xyKzqFrdA+ hash: v1.k794b7964.2fd597859f64b0598f04d444d1951665d553891c260eca98bc237e1d9a131c3a.Jej64hrDTzRNtzVbCfTVReFGSTXB5yd-sgRKzs2hKt8errortracking-exceptioncard--exception-card-header-widths--light:hash: v1.k794b7964.96ab37bc32797721d97410925e8c89bf739322a340ff8ee62dbd014a139a7f59.HCV39CI_4XqbwUW8QD8DDxSw_CeL5cui9smBv0MDeY0errortracking-exceptioncard--exception-card-header-widths-with-action--dark:diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsxindex 3e20f69fbaa1..0ba07ce0275a 100644--- a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx+++ b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx@@ -55,6 +55,18 @@ const withPinnedSceneHeight: Decorator = function PinnedSceneHeightDecorator(Sto)}+// The app shell has a `100vh` min-height, so when the viewport at capture time is taller than the+// card, the shell grows to the viewport and adds a blank strip below the card. Let the shell hug its+// content so only the card sets the height.+const withContentSceneHeight: Decorator = function ContentSceneHeightDecorator(Story): JSX.Element {+ return (+ <>+ <style>{'.Navigation3000 { min-height: 0 !important; }'}</style>+ <Story />+ </>+ )+}+const pushAuthorize = (scope?: string, resolvedScopes?: string[]): void => {const appContext = (window as any).POSTHOG_APP_CONTEXTappContext.oauth_scope_resolution = {@@ -137,7 +149,7 @@ type Story = StoryObj<{}>// A client that sends no `scope` at all: the server defaults the request to the app's ceiling,// so every row arrives selected at its highest level with the bulk actions available.export const DefaultScopes: Story = {- decorators: [withOAuthApplication({ required_scopes: [] })],+ decorators: [withContentSceneHeight, withOAuthApplication({ required_scopes: [] })],render: () => {useDelayedOnMountEffect(() =>pushAuthorize(undefined, [diff --git a/products/ai_observability/frontend/playground/MessageToolCallsEditor.stories.tsx b/products/ai_observability/frontend/playground/MessageToolCallsEditor.stories.tsxindex be3f1e8ffedf..92f61a3ef539 100644--- a/products/ai_observability/frontend/playground/MessageToolCallsEditor.stories.tsx+++ b/products/ai_observability/frontend/playground/MessageToolCallsEditor.stories.tsx@@ -7,6 +7,13 @@ import { MessageToolCallsEditor } from './MessageToolCallsEditor'const meta: Meta<typeof MessageToolCallsEditor> = {title: 'Components/Message Tool Calls Editor',component: MessageToolCallsEditor,+ parameters: {+ testOptions: {+ // Wait for the editor itself: `.monaco-editor` also matches Monaco's shared overflow root on+ // <body>, which exists before any editor mounts.+ waitForSelector: '.CodeEditor[data-editor-ready="true"]',+ },+ },}export default metatype Story = StoryObj<typeof MessageToolCallsEditor>@@ -17,7 +24,9 @@ export const EditableToolCalls: Story = {{ id: 'call_1a2b3c4d', name: 'get_weather', arguments: '{\n "location": "San Francisco, CA"\n}' },])return (- <div className="max-w-150">+ // A fixed width, not max-w: the snapshot root shrink-wraps its content, so the editor would+ // take whatever width the root had at the moment it mounted.+ <div className="w-150"><MessageToolCallsEditor toolCalls={toolCalls} onChange={setToolCalls} /></div>)diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex 9a5d651a4ebf..ea284e2e5749 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -1333,6 +1333,8 @@ export const ObservationDetailFailed: StoryObj = {...observationDetailStory(failedObservationDetail),play: async ({ canvasElement }) => {await waitFor(() => expect(canvasElement.querySelector('[data-attr="recording-play"]')).toBeVisible())+ // The floating player controls hide on a timer after mount, so wait for that to happen before the snapshot.+ await waitFor(() => expect(canvasElement.querySelector('[data-attr="recording-play"]')).not.toBeVisible())},}diff --git a/products/signals/frontend/inbox/InboxScene.stories.tsx b/products/signals/frontend/inbox/InboxScene.stories.tsxindex b4793c99becb..0aafdfeb760b 100644--- a/products/signals/frontend/inbox/InboxScene.stories.tsx+++ b/products/signals/frontend/inbox/InboxScene.stories.tsx@@ -159,7 +159,12 @@ const LEGACY_FLAGS = {export const Legacy: Story = {parameters: {featureFlags: LEGACY_FLAGS,- testOptions: { waitForLoadersToDisappear: true },+ testOptions: {+ waitForLoadersToDisappear: true,+ // The setup rail loads its own team config and integrations, sometimes after the loader wait.+ // This button renders only after both loads finish.+ waitForSelector: '[data-attr="signals-issue-tracker-connect"]',+ },},decorators: [routeTo(urls.inbox('pulls'))],}diff --git a/products/visual_review/skills/triaging-visual-review-runs/SKILL.md b/products/visual_review/skills/triaging-visual-review-runs/SKILL.mdindex daace249a085..93ee4c15f4f6 100644--- a/products/visual_review/skills/triaging-visual-review-runs/SKILL.md+++ b/products/visual_review/skills/triaging-visual-review-runs/SKILL.md@@ -62,7 +62,8 @@ The list is paginated and does not put quarantined rows first, so follow `next`- A quarantined story that your change renders differently needs its new picture approved by identifier, then finalized."Approve all" and `approve_all` skip quarantined snapshots.Without the approval, the default branch keeps the old entry, and every run fails on the day the quarantine is lifted or expires.-- A quarantined story that your change does not touch can still show `changed`, because it is flaky. Leave it.+- A quarantined story that your change does not touch can still show `changed`, because it is flaky. Leave it, and do not approve it.+ Approving re-baselines the story to whatever this run rendered, which can be the flaky picture or one from before a fix, and a pending lift request for that story then fails on the baseline check.- A fix for the flake changes nothing VR can see in one run, so the story renders `unchanged` and the list above leaves it out.Record the fix with `posthog:visual-review-runs-lift-on-merge-create { id: <run_id>, identifier: <identifier> }` for each identifier the fix should release, and name the identifiers in the PR description.The quarantine lifts only after the PR merges and a default-branch run that contains the merge renders the same picture against a matching entry.