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.

fix(storybook): fail play errors fast and fix AccountsTab boot race (#72862)

Paul D'Ambraea486f0ad1ae
diff --git a/common/storybook/.storybook/preview.tsx b/common/storybook/.storybook/preview.tsx
index 2aa0c642e7c8..6caead130769 100644
--- a/common/storybook/.storybook/preview.tsx
+++ b/common/storybook/.storybook/preview.tsx
@@ -2,6 +2,7 @@ import '~/styles'
import { Controls, Description, Primary, Stories, Subtitle, Title } from '@storybook/addon-docs/blocks'
import type { Meta, Parameters, Preview } from '@storybook/react'
+import { configure as configureTestingLibrary } from '@testing-library/dom'
import { apiHostOrigin } from 'lib/utils/apiHost'
@@ -17,6 +18,12 @@ import { withMockDate } from './decorators/withMockDate'
import { withPageUrl } from './decorators/withPageUrl'
import { withTheme } from './decorators/withTheme'
+// Play functions start as soon as React commits the first render, but scene-based stories keep
+// loading data for several seconds after that — longer on a busy CI runner. testing-library's
+// default 1s findBy*/waitFor timeout loses that race and fails plays spuriously, so give every
+// story a load-tolerant default budget instead of making each play pass its own timeout.
+configureTestingLibrary({ asyncUtilTimeout: 15000 })
+
const setupMsw = (): void => {
// Make sure the msw worker is started
worker.start({
diff --git a/common/storybook/.storybook/test-runner.ts b/common/storybook/.storybook/test-runner.ts
index c070de96a1b4..61e1e4944b71 100644
--- a/common/storybook/.storybook/test-runner.ts
+++ b/common/storybook/.storybook/test-runner.ts
@@ -128,6 +128,19 @@ const VIEWPORT_SETTLE_TIMEOUT_MS = 5000
const ATTEMPT_COUNT_PER_ID: Record<string, number> = {}
+// Storybook channel events that mean a forced remount's play function failed. Shared between the
+// in-page listener (which also waits for the success event, `storyRendered`) and the outer check
+// that decides whether to fail the retry, so the two can't drift apart.
+const REMOUNT_FAILURE_EVENTS = [
+ 'storyErrored',
+ 'storyThrewException',
+ 'playFunctionThrewException',
+ // Storybook can still emit `storyRendered` after this one (an unhandled error doesn't stop the
+ // story from finishing), so it must be listened for directly instead of relying on the later
+ // `storyRendered` to end the wait.
+ 'unhandledErrorsWhilePlaying',
+]
+
// Sharing/embed stories render a preview iframe pointing at the shared/embedded URL, which Storybook
// can't serve, so it 404s to a browser error page whose rendering is browser-version-dependent (and so
// produces noisy, non-deterministic snapshots). Stub those navigations with a fixed page.
@@ -147,6 +160,83 @@ export default {
await page.route(/\/(embedded|shared)\//, (route) =>
route.fulfill({ status: 200, contentType: 'text/html', body: EMBED_STUB_HTML })
)
+ // On jest retries the preview answers setCurrentStory with `storyUnchanged`, which
+ // does NOT re-run loaders or the play function — the retry would just re-snapshot the
+ // page the failed attempt left behind. Force a full remount so retries start fresh,
+ // and surface the replayed play function's error if it throws again.
+ if (ATTEMPT_COUNT_PER_ID[context.id]) {
+ const remountResult = await page
+ .evaluate(
+ ({ storyId, failureEvents }) => {
+ return new Promise<{ event: string; message?: string }>((resolve) => {
+ const channel = (
+ window as unknown as {
+ __STORYBOOK_ADDONS_CHANNEL__: {
+ on: (event: string, listener: (data?: unknown) => void) => void
+ off: (event: string, listener: (data?: unknown) => void) => void
+ emit: (event: string, data?: unknown) => void
+ }
+ }
+ ).__STORYBOOK_ADDONS_CHANNEL__
+ const doneEvents = [...failureEvents, 'storyRendered']
+ const listeners: Record<string, (data?: unknown) => void> = {}
+ // Purely diagnostic: when the remount wait times out, the phase it was stuck
+ // in ("loading" vs "playing") points at the story rather than the machinery.
+ let lastPhase: string | undefined
+ const phaseListener = (data?: unknown): void => {
+ lastPhase = (data as { newPhase?: string } | undefined)?.newPhase
+ }
+ const finish = (event: string, data?: unknown): void => {
+ clearTimeout(timeoutId)
+ channel.off('storyRenderPhaseChanged', phaseListener)
+ doneEvents.forEach((e) => channel.off(e, listeners[e]))
+ // unhandledErrorsWhilePlaying's payload is an array of serialized errors;
+ // every other done event passes the error object directly.
+ const error = (Array.isArray(data) ? data[0] : data) as
+ | { message?: string; description?: string }
+ | undefined
+ resolve({ event, message: error?.message ?? error?.description })
+ }
+ doneEvents.forEach((e) => {
+ listeners[e] = (data?: unknown) => finish(e, data)
+ channel.on(e, listeners[e])
+ })
+ channel.on('storyRenderPhaseChanged', phaseListener)
+ // If the remount never settles, stop waiting so postVisit can proceed — but
+ // treat it as a failed retry below rather than silently falling through as if
+ // the remount had finished cleanly.
+ const timeoutId = setTimeout(
+ () =>
+ finish('timeout', {
+ message: `remount did not settle within 30s (last render phase: ${
+ lastPhase ?? 'unknown'
+ })`,
+ }),
+ 30000
+ )
+ channel.emit('forceRemount', { storyId })
+ })
+ },
+ { storyId: context.id, failureEvents: REMOUNT_FAILURE_EVENTS }
+ )
+ // page.evaluate() itself can reject (e.g. the page navigated or its execution context
+ // was destroyed mid-remount) — treat that as a failure too instead of letting `undefined`
+ // pass the check below as if the remount had finished cleanly.
+ .catch((error) => ({ event: 'evaluationFailed', message: (error as Error).message }))
+ if (
+ [
+ ...REMOUNT_FAILURE_EVENTS,
+ 'evaluationFailed',
+ // A remount that's still running when the wait times out must not be treated as
+ // a clean success — the snapshot flow below would then race unfinished play logic.
+ 'timeout',
+ ].includes(remountResult.event)
+ ) {
+ throw new Error(
+ `Story remount on retry failed (${remountResult.event}): ${remountResult.message ?? 'unknown error'}`
+ )
+ }
+ }
const storyContext = await getStoryContext(page, context)
const { viewport, viewportWidths, jestTimeout } = storyContext.parameters?.testOptions ?? {}
applyStoryTimeouts(page, viewportWidths, jestTimeout)
@@ -158,6 +248,13 @@ export default {
async postVisit(page, context) {
ATTEMPT_COUNT_PER_ID[context.id] = (ATTEMPT_COUNT_PER_ID[context.id] || 0) + 1
+ // The generated test also calls postVisit when the story or its play function already
+ // failed (so configs can do failure handling — our jest environment takes the failure
+ // screenshot). Don't run the snapshot flow then: its selector waits can outlast the jest
+ // timeout, which would bury the real error under an opaque "Exceeded timeout of 60000 ms".
+ if (context.hasFailure) {
+ return
+ }
const storyContext = await getStoryContext(page, context)
const { viewport, viewportWidths, jestTimeout } = storyContext.parameters?.testOptions ?? {}
const effectiveViewport = viewportWidths?.length
@@ -283,8 +380,11 @@ async function expectStoryToMatchSnapshot(
// Allow ResizeObserver callbacks to fire and React to re-render with updated dimensions
await page.waitForTimeout(300)
- const { waitForLoadersToDisappear = true, waitForSelector, waitForSelectorTimeout } =
- storyContext.parameters?.testOptions ?? {}
+ const {
+ waitForLoadersToDisappear = true,
+ waitForSelector,
+ waitForSelectorTimeout,
+ } = storyContext.parameters?.testOptions ?? {}
if (waitForLoadersToDisappear) {
// The timeout allows loaders and toasts to disappear - toasts usually signify something wrong
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index eb248242681d..4c060b4e5a61 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7747,9 +7747,9 @@ snapshots:
scenes-other-onboarding-shared-wizard-cloud-run--pull-request-queued--light:
hash: v1.k794b7964.7ec7e9d1698b2e62f5228a13c1991d64086be0fbc9840457922b154816df2431.nTPGOZUNcBJ1gNrgTQKjPqKNAbhaFCjmCARBoKuu2lo
scenes-other-onboarding-shared-wizard-cloud-run--repo-picker-open--dark:
- hash: v1.k794b7964.0c903b9c3884ef83e1a10473b1e9acdbebc5b38b588a99bed35441b8b7ee8c0b.66xwKVU7w_BHjzjGHEkDulTABAKCpGSpl94tgE8nYSE
+ hash: v1.k794b7964.1a977cbb0a6a59c9c68182be1a30768abfe0d98ddd11cdace4a415d08b1e053d.uJCiReQqjQhBLVYGSmMSn3XpIwEaQ-aPfvRaqU8TgS8
scenes-other-onboarding-shared-wizard-cloud-run--repo-picker-open--light:
- hash: v1.k794b7964.4a4081541ed8303ac183359a9ca8e594b33d3b056abb86e0e936599fae609f4b.5xbzTpuLkhIYejeCA54MJabm-t9nCGSmB5zi0kJQT-c
+ hash: v1.k794b7964.216f9a849d9a48cfecdcedaa318a996d7bf66c65b6e497bc96d8a7043bcba4ff.nPN0rXCSllfOEB414bqIPAGN4gMB07O7rAZmtC460Xk
scenes-other-onboarding-shared-wizard-cloud-run--repo-selected--dark:
hash: v1.k794b7964.c83127f9e424470e3a9dbef3100148560455f9b3a9b5a17c82c67a63e10bd6c4.eptdbuPervntKMHipq7abx7efzF8oT1sm7zKS2Jhtxg
scenes-other-onboarding-shared-wizard-cloud-run--repo-selected--light:
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts
index 8de4a149dc2f..bd4ccb20ded7 100644
--- a/frontend/src/mocks/handlers.ts
+++ b/frontend/src/mocks/handlers.ts
@@ -306,6 +306,9 @@ export const defaultMocks: Mocks = {
'/api/environments/:team_id/query/': { results: [] },
'/api/environments/:team_id/query/:query_kind/': { results: [] },
'/api/environments/:team_id/insights/viewed/': () => [201, null],
+ // Background telemetry beacon fired by metalyticsLogic when a scene is viewed — stub it so
+ // stories that render insights don't hit an unhandled 405 during play.
+ '/api/projects/:team_id/metalytics/': () => [201, null],
'api/environments/:team_id/query': { results: [] },
'api/environments/:team_id/query/:query_kind/': { results: [] },
'/api/environments/:team_id/file_system/log_view/': {},
diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx
index 8e922ecbcd3b..2b6043bf977d 100644
--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx
+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.stories.tsx
@@ -117,9 +117,11 @@ export default meta
type Story = StoryObj
-// The scene mounts asynchronously after navigation, so waits inside play functions need far more
-// than @testing-library's 1s default before CI can be trusted to have rendered the install step.
-const WAIT_OPTIONS = { timeout: 8000, interval: 200 }
+// The scene mounts asynchronously after navigation (and only 500ms after mount does the delayed
+// effect even start it), so play-function waits need a load-tolerant budget: on a busy CI shard
+// the install step can take well past the global 15s default to render, and retries genuinely
+// re-run play now — an under-budgeted wait fails all three attempts instead of flaking once.
+const WAIT_OPTIONS = { timeout: 30000, interval: 200 }
// Click a footer/body button by its exact label, waiting for it to mount first.
async function clickButton(text: string): Promise<void> {
@@ -205,12 +207,14 @@ export const RepoPickerOpen: Story = cloudRunStory({
integrations: [githubIntegration],
waitForSelector: '[data-attr="select-github-repository"]',
extraPlay: async () => {
+ // LemonInput puts data-attr on the <input> element itself, so match the input directly —
+ // a descendant selector like `[data-attr=...] input` never matches anything.
await waitFor(() => {
- if (!document.querySelector('[data-attr="select-github-repository"] input')) {
+ if (!document.querySelector('input[data-attr="select-github-repository"]')) {
throw new Error('repo picker not ready')
}
}, WAIT_OPTIONS)
- await userEvent.click(document.querySelector('[data-attr="select-github-repository"] input') as Element)
+ await userEvent.click(document.querySelector('input[data-attr="select-github-repository"]') as Element)
// full_name only appears in the open dropdown (nothing is selected), so this confirms it's open.
await waitFor(() => {
if (!Array.from(document.querySelectorAll('span')).some((el) => el.textContent === 'acme-co/mobile-app')) {