Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(storybook): support multivariate feature flag variants in stories (#60775)

Paul D'Ambra61c32f1abfee
diff --git a/.agents/skills/setting-feature-flags-in-storybook/SKILL.md b/.agents/skills/setting-feature-flags-in-storybook/SKILL.md
new file mode 100644
index 000000000000..d5047e6b8b3f
--- /dev/null
+++ b/.agents/skills/setting-feature-flags-in-storybook/SKILL.md
@@ -0,0 +1,94 @@
+---
+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.PROMOTED_PRODUCT]: 'intent_plus' } }
+
+// per-story: a different arm per story
+export const ControlArm: Story = {
+ parameters: { featureFlags: { [FEATURE_FLAGS.PROMOTED_PRODUCT]: 'control' } },
+}
+export const TreatmentArm: Story = {
+ parameters: { featureFlags: { [FEATURE_FLAGS.PROMOTED_PRODUCT]: '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`) only renders once `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.
+
+## 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/.claude/rules/storybook-feature-flags.md b/.claude/rules/storybook-feature-flags.md
new file mode 100644
index 000000000000..9e17fa582619
--- /dev/null
+++ b/.claude/rules/storybook-feature-flags.md
@@ -0,0 +1,12 @@
+---
+paths:
+ - 'frontend/src/**/*.stories.tsx'
+ - 'products/*/frontend/**/*.stories.tsx'
+---
+
+If this story renders a component gated on a feature flag, set the flag via the
+`featureFlags` story parameter — not by calling `featureFlagLogic.setFeatureFlags`
+imperatively (that is silently dropped in the visual-regression runtime). For a
+multivariate 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.
diff --git a/common/storybook/.storybook/decorators/withFeatureFlags.tsx b/common/storybook/.storybook/decorators/withFeatureFlags.tsx
index c3eaf992f847..2b5a19452b45 100644
--- a/common/storybook/.storybook/decorators/withFeatureFlags.tsx
+++ b/common/storybook/.storybook/decorators/withFeatureFlags.tsx
@@ -4,20 +4,20 @@ import { setFeatureFlags } from '~/mocks/browser'
declare module '@storybook/types' {
interface Parameters {
- featureFlags?: string[]
+ featureFlags?: string[] | Record<string, string | boolean>
}
}
/** Global story decorator that allows setting feature flags.
*
+ * Boolean flags (just "on") — pass an array:
* ```ts
- * export default {
- * title: 'My story',
- * component: MyComponent,
- * parameters: {
- * featureFlags: [FEATURE_FLAGS.HOGQL], // add flags here
- * },
- * } as ComponentMeta<typeof MyComponent>
+ * parameters: { featureFlags: [FEATURE_FLAGS.HOGQL] }
+ * ```
+ *
+ * Multivariate flags — pin a specific variant with the record form:
+ * ```ts
+ * parameters: { featureFlags: { [FEATURE_FLAGS.PROMOTED_PRODUCT]: 'intent_plus' } }
* ```
*/
export const withFeatureFlags: Decorator = (Story, { parameters: { featureFlags = [] } }) => {
diff --git a/frontend/src/lib/logic/featureFlagLogic.ts b/frontend/src/lib/logic/featureFlagLogic.ts
index cf1210fc4eb7..ee89c77ff3c9 100644
--- a/frontend/src/lib/logic/featureFlagLogic.ts
+++ b/frontend/src/lib/logic/featureFlagLogic.ts
@@ -25,13 +25,14 @@ function notifyFlagIfNeeded(flag: string, flagState: string | boolean | undefine
function getPersistedFeatureFlags(appContext: AppContext | undefined = getAppContext()): FeatureFlagsSet {
const persistedFeatureFlags = appContext?.persisted_feature_flags || []
- const flags = Object.fromEntries(
- persistedFeatureFlags.map((f) => {
- return [f, true]
- })
- )
-
- return flags
+ // The server sends a list of enabled flag keys (each maps to `true`). Storybook can
+ // instead supply a record so a story can pin a multivariate variant (e.g. an
+ // experiment arm) — those values ride this always-merged baseline and survive the
+ // empty `onFeatureFlags` callback that posthog-js fires on load.
+ if (!Array.isArray(persistedFeatureFlags)) {
+ return { ...persistedFeatureFlags }
+ }
+ return Object.fromEntries(persistedFeatureFlags.map((f) => [f, true]))
}
let cachedFlagsSerialized: string | null = null
diff --git a/frontend/src/mocks/browser.tsx b/frontend/src/mocks/browser.tsx
index f807779f9c61..6e2187df3cfd 100644
--- a/frontend/src/mocks/browser.tsx
+++ b/frontend/src/mocks/browser.tsx
@@ -3,6 +3,7 @@ import { rest, setupWorker } from 'msw'
import { handlers } from '~/mocks/handlers'
import { MockSignature, Mocks, mocksToHandlers } from '~/mocks/utils'
+import type { AppContext } from '~/types'
// Default handlers ensure no request is unhandled by msw
export const worker: ReturnType<typeof setupWorker> = setupWorker(...handlers)
@@ -33,6 +34,19 @@ export const mswDecorator = (mocks: Mocks): DecoratorFunction<any> => {
}
}
-export const setFeatureFlags = (featureFlags: string[]): void => {
- ;(window as any).POSTHOG_APP_CONTEXT.persisted_feature_flags = featureFlags
+/**
+ * Set feature flags for a story.
+ *
+ * - `string[]` — flags that are simply **on** (each maps to `true`).
+ * - `Record<string, string | boolean>` — pin specific **multivariate** variants
+ * (e.g. `{ 'my-flag': 'test_b' }`); mix with booleans freely.
+ *
+ * Both forms are written straight to `persisted_feature_flags`, the baseline
+ * `featureFlagLogic` reads on mount and always merges (see `getPersistedFeatureFlags`).
+ * That's what makes a pinned variant survive the empty `onFeatureFlags` callback
+ * posthog-js fires on load — no need to disable flags or touch preflight.
+ */
+export const setFeatureFlags = (featureFlags: string[] | Record<string, string | boolean>): void => {
+ const appContext = (window as any).POSTHOG_APP_CONTEXT as AppContext
+ appContext.persisted_feature_flags = featureFlags
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 80d990fcbf72..a66d21cabf79 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4757,7 +4757,11 @@ export interface AppContext {
default_event_name: string | null
has_pageview: boolean
has_screen: boolean
- persisted_feature_flags?: string[]
+ /**
+ * Flags the server bootstraps as enabled (a list of keys). Storybook may instead pass a
+ * record to pin specific multivariate variants (e.g. an experiment arm) for a story.
+ */
+ persisted_feature_flags?: string[] | Record<string, string | boolean>
anonymous: boolean
frontend_apps?: Record<number, FrontendAppConfig>
effective_resource_access_control: Record<AccessControlResourceType, AccessControlLevel>