: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(scenes): show a real error when a scene fails to load (#105735)
posthog[bot]85a8e94351d6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 39af4da79b32..3066d4e6a6ac 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -13758,6 +13758,10 @@ snapshots:hash: v1.k794b7964.5a65f3fe94b288f66e436ecd8677bc2d1b3fe08ca885f03eae64bc8847b783ee.YfBWEDQwkl46pC03TjLQBVNXq96nOm91Lc0KcpIXegcscenes-app-saved-insights-new-insight-menu--overlay--light:hash: v1.k794b7964.b1f8b76506ff046ee7667a54f64fc587413ce238932d26039b8fa398d864f19f.X8ZiWahHO3f74wwMcFkt2tCuh29Dn6IZL_CXzVZUxHI+ scenes-app-scene-load-error--default--dark:+ hash: v1.k794b7964.9a8c6e48ee1ae0e662a41affffd04503fe6462adf9938929f83299ae99d5c627.Fzldjn7eFyKz3HbqcaXmv2L-WtpEEVvkHp-lBgpgmGc+ scenes-app-scene-load-error--default--light:+ hash: v1.k794b7964.4e83d81a25b8833226bf4cc2bd3d90c9255218a03600b1b2c1af86060d68ecce.XE216IXmlXfOahQjfDFVw0Sw4BxU_ANX9vjCCf19TtIscenes-app-sessionattributionexplorer--session-attribution-explorer--dark:hash: v1.k794b7964.f155136ab341d343517047052786c945b29e035f5c6688c170ddb34644977402.YdTYmTEtPQ8DA5jLsTAJuOZMdr956Jug7d1kOO4BvDMscenes-app-sessionattributionexplorer--session-attribution-explorer--light:diff --git a/frontend/src/layout/SceneLoadError.stories.tsx b/frontend/src/layout/SceneLoadError.stories.tsxnew file mode 100644index 000000000000..582aa8b6ac61--- /dev/null+++ b/frontend/src/layout/SceneLoadError.stories.tsx@@ -0,0 +1,17 @@+import { Meta, StoryObj } from '@storybook/react'++import { SceneLoadError } from './SceneLoadError'++const meta: Meta<typeof SceneLoadError> = {+ title: 'Scenes-App/Scene Load Error',+ component: SceneLoadError,+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ },+}+export default meta++type Story = StoryObj<typeof SceneLoadError>++export const Default: Story = {}diff --git a/frontend/src/layout/SceneLoadError.tsx b/frontend/src/layout/SceneLoadError.tsxnew file mode 100644index 000000000000..ba61b676e886--- /dev/null+++ b/frontend/src/layout/SceneLoadError.tsx@@ -0,0 +1,50 @@+import { useActions, useValues } from 'kea'++import { IconRefresh } from '@posthog/icons'++import { supportLogic } from 'lib/components/Support/supportLogic'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { sceneLogic } from 'scenes/sceneLogic'++/**+ * Shown when a scene's code fails to import, or its logic throws while mounting. Without it the+ * address bar moves to the new scene while the old one stays rendered, so the person is left on a+ * page that no longer matches the URL.+ */+export function SceneLoadError(): JSX.Element {+ const { openSupportForm } = useActions(supportLogic)+ const { sceneLoadExceptionEvent } = useValues(sceneLogic)++ return (+ <div className="p-4">+ <h1 className="mb-1 text-2xl font-bold">Couldn't load this page</h1>+ <p>+ Something went wrong while this page was loading. Reload to try again. If it keeps happening, let us+ know.+ </p>+ <div className="flex gap-2 flex-wrap">+ <LemonButton+ type="primary"+ icon={<IconRefresh />}+ onClick={() => window.location.reload()}+ data-attr="scene-load-error-reload"+ >+ Reload the page+ </LemonButton>+ <LemonButton+ type="secondary"+ onClick={() =>+ openSupportForm({+ kind: 'bug',+ isEmailFormOpen: true,+ exception_event: sceneLoadExceptionEvent ?? undefined,+ })+ }+ data-attr="scene-load-error-email-engineer"+ >+ Email an engineer+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsxindex 03ef961b914a..96236a431053 100644--- a/frontend/src/scenes/sceneLogic.test.tsx+++ b/frontend/src/scenes/sceneLogic.test.tsx@@ -1,6 +1,6 @@import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_PROJECT, MOCK_DEFAULT_TEAM, MOCK_USER_UUID } from 'lib/api.mock'-import { kea, path } from 'kea'+import { afterMount, kea, path } from 'kea'import { router } from 'kea-router'import { expectLogic, partial, testUtilsContext, truth } from 'kea-test-utils'import posthog from 'posthog-js'@@ -44,6 +44,16 @@ const Component = (): JSX.Element => <div />const testLogic = kea<testLogicType>([path(['scenes', 'sceneLogic', 'test'])])const sceneImport = (): any => ({ scene: { component: Component, logic: testLogic } })+const failingLogic = kea<testLogicType>([+ path(['scenes', 'sceneLogic', 'testFailingLogic']),+ afterMount(() => {+ throw new Error('scene logic mount failed')+ }),+])++// Held so a test can reject a still-pending scene import after navigating somewhere else.+let pendingImportRejection: ((error: Error) => void) | null = null+const testScenes: Record<string, () => any> = {[Scene.Alerts]: sceneImport,[Scene.AIObservabilityEvaluations]: sceneImport,@@ -58,6 +68,12 @@ const testScenes: Record<string, () => any> = {Inbox: sceneImport,ScoutTrials: sceneImport,[Scene.ProjectFiles]: sceneImport,+ [Scene.Surveys]: (): any => Promise.reject(new Error('scene import failed')),+ [Scene.Cohorts]: (): any => ({ scene: { component: Component, logic: failingLogic } }),+ [Scene.Experiments]: (): any =>+ new Promise((_resolve, reject) => {+ pendingImportRejection = reject+ }),}describe('sceneLogic', () => {@@ -88,6 +104,57 @@ describe('sceneLogic', () => {})})+ // A scene that never mounts must not leave the address bar on it with the previous scene still+ // rendered, and must leave something error tracking can count.+ describe('a scene that fails to load', () => {+ const exceptionEvent = { uuid: 'scene-load-exception', event: '$exception' }+ let captureExceptionSpy: jest.SpyInstance++ beforeEach(() => {+ pendingImportRejection = null+ captureExceptionSpy = jest+ .spyOn(posthog, 'captureException')+ .mockImplementation(() => exceptionEvent as any)+ })++ afterEach(() => {+ captureExceptionSpy.mockRestore()+ })++ it.each([+ ['its code cannot be imported', urls.surveys(), Scene.Surveys, 'import'],+ ['its logic throws while mounting', urls.cohorts(), Scene.Cohorts, 'logic_mount'],+ ])('shows the load error and reports it when %s', async (_desc, url, sceneId, stage) => {+ router.actions.push(url)+ await expectLogic(logic).delay(1)++ expect(logic.values.activeSceneId).toEqual(Scene.ErrorSceneLoad)+ expect(captureExceptionSpy).toHaveBeenCalledWith(expect.any(Error), {+ extra: expect.objectContaining({ sceneId, stage }),+ })+ // The support form needs this event, or a non-entitled organization cannot report the failure.+ expect(logic.values.sceneLoadExceptionEvent).toEqual(exceptionEvent)+ })++ // An import can reject long after the person gave up and went somewhere else. The error+ // scene must not then replace whatever they are reading now.+ it('leaves a newer scene alone when a stale import rejects', async () => {+ router.actions.push(urls.experiments())+ await expectLogic(logic).delay(1)++ router.actions.push(urls.settings('user'))+ await expectLogic(logic).delay(1)+ expect(logic.values.activeSceneId).toEqual(Scene.Settings)++ // Without this the rejection below is a no-op and the assertion passes vacuously.+ expect(pendingImportRejection).not.toBeNull()+ pendingImportRejection!(new Error('scene import failed'))+ await expectLogic(logic).delay(1)++ expect(logic.values.activeSceneId).toEqual(Scene.Settings)+ })+ })+it('keeps teamLogic mounted after every other mount reference is released', () => {// openScene and activeSceneId read teamLogic.values directly. Without a mount reference of// its own, navigation throws as soon as nothing else holds teamLogic up.diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex d989f5918948..816b88a0659c 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -17,6 +17,7 @@ import posthog from 'posthog-js'import { useEffect, useState } from 'react'import api from 'lib/api'+import type { SupportTicketExceptionEvent } from 'lib/components/Support/supportLogic'import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'import { trackFileSystemLogView } from 'lib/hooks/useFileSystemLogView'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -195,6 +196,13 @@ const DelayedLoadingSpinner = (): JSX.Element => {return <>{show ? <Spinner /> : null}</>}+const captureSceneLoadFailure = (+ error: unknown,+ sceneId: string,+ stage: 'import' | 'logic_mount',+ extra: Record<string, unknown> = {}+): SupportTicketExceptionEvent | undefined => posthog.captureException(error, { extra: { sceneId, stage, ...extra } })+const scrollMainContentToTop = (): void => {const element = document.getElementById('main-content')if (!element) {@@ -282,6 +290,7 @@ export interface sceneLogicValues {sceneConfig: SceneConfig | nullsceneId: string | nullsceneKey: string | null+ sceneLoadExceptionEvent: SupportTicketExceptionEvent | nullsceneParams: SceneParamssearchParams: Record<string, any>titleAndIcon: {@@ -360,6 +369,9 @@ export interface sceneLogicActions {sceneKey: string | undefinedscrollToTop: boolean}+ setSceneLoadExceptionEvent: (exceptionEvent: SupportTicketExceptionEvent | undefined) => {+ exceptionEvent: SupportTicketExceptionEvent | undefined+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -476,6 +488,7 @@ export const sceneLogic = kea<sceneLogicType>([homepageSaved: (tab: SceneTab | null) => ({ tab }),setHomepageSaving: (saving: boolean) => ({ saving }),resetUnavailableHomepage: (pathname: string) => ({ pathname }),+ setSceneLoadExceptionEvent: (exceptionEvent: SupportTicketExceptionEvent | undefined) => ({ exceptionEvent }),}),reducers({sceneId: [@@ -549,6 +562,10 @@ export const sceneLogic = kea<sceneLogicType>([},],homepageSaving: [false, { setHomepageSaving: (_, { saving }) => saving }],+ sceneLoadExceptionEvent: [+ null as SupportTicketExceptionEvent | null,+ { setSceneLoadExceptionEvent: (_, { exceptionEvent }) => exceptionEvent ?? null },+ ],})),selectors({sceneConfig: [@@ -843,7 +860,9 @@ export const sceneLogic = kea<sceneLogicType>([}}} catch (error) {- posthog.captureException(error, { extra: { sceneId, sceneKey } })+ actions.setSceneLoadExceptionEvent(+ captureSceneLoadFailure(error, sceneId, 'logic_mount', { sceneKey })+ )newLogicErrored = true}} else {@@ -859,7 +878,11 @@ export const sceneLogic = kea<sceneLogicType>([}if (newLogicErrored) {- actions.loadScene(Scene.Error404, undefined, emptySceneParams, 'REPLACE')+ // Not a 404: the route exists and the person is allowed on it, so saying the page+ // is missing sends them looking for a URL mistake that isn't there. `setScene`+ // rather than `loadScene`, because the error scenes are preloaded and so are+ // absent from `props.scenes`.+ actions.setScene(Scene.ErrorSceneLoad, undefined, emptySceneParams, false)return}@@ -1032,7 +1055,17 @@ export const sceneLogic = kea<sceneLogicType>([}return}- throw error+ // A slow import can reject after the person has already navigated somewhere+ // else, so break first: the error scene must not replace a newer one.+ breakpoint()+ // Rethrowing here escapes the listener unhandled: the address bar sits on the+ // scene that failed while the previous one stays rendered, and nothing reaches+ // error tracking. Report it, then render an error where the URL points.+ actions.setSceneLoadExceptionEvent(+ captureSceneLoadFailure(error, sceneId, 'import', { sceneKey, source: 'sceneLogic.loadScene' })+ )+ actions.setScene(Scene.ErrorSceneLoad, undefined, emptySceneParams, clickedLink)+ return} finally {window.clearTimeout(timeout)}diff --git a/frontend/src/scenes/sceneSmoke.test.tsx b/frontend/src/scenes/sceneSmoke.test.tsxindex 92bf44d951c1..7c05ed7e65f1 100644--- a/frontend/src/scenes/sceneSmoke.test.tsx+++ b/frontend/src/scenes/sceneSmoke.test.tsx@@ -41,6 +41,7 @@ const ERROR_SCENES: string[] = [Scene.ErrorProjectUnavailable,Scene.ErrorProjectAccessDenied,Scene.ErrorAccessDenied,+ Scene.ErrorSceneLoad,]// Index routes resolve without an entity id; the entity routes additionally build the id-keyeddiff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex f236dbc2ecd9..fb00edb0d9a7 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -63,6 +63,7 @@ export enum Scene {ErrorNetwork = '4xx',ErrorProjectAccessDenied = 'ProjectAccessDenied',ErrorProjectUnavailable = 'ProjectUnavailable',+ ErrorSceneLoad = 'SceneLoadError',ErrorTracking = 'ErrorTracking',ErrorTrackingFingerprint = 'ErrorTrackingFingerprint',ErrorTrackingIssue = 'ErrorTrackingIssue',diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex 7eddce32d59e..b305b72ae99a 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -12,6 +12,7 @@ import { ErrorAccessDenied as ErrorAccessDeniedComponent } from '~/layout/ErrorAimport { ErrorNetwork as ErrorNetworkComponent } from '~/layout/ErrorNetwork'import { ErrorProjectAccessDenied as ErrorProjectAccessDeniedComponent } from '~/layout/ErrorProjectAccessDenied'import { ErrorProjectUnavailable as ErrorProjectUnavailableComponent } from '~/layout/ErrorProjectUnavailable'+import { SceneLoadError as SceneLoadErrorComponent } from '~/layout/SceneLoadError'import { productConfiguration, productRedirects, productRoutes } from '~/products'import { EventsQuery } from '~/queries/schema/schema-general'import { ActivityScope, ActivityTab, InsightShortId, ReplayTabs } from '~/types'@@ -36,6 +37,9 @@ export const preloadedScenes: Record<string, SceneExport> = {[Scene.ErrorProjectUnavailable]: {component: ErrorProjectUnavailableComponent,},+ [Scene.ErrorSceneLoad]: {+ component: SceneLoadErrorComponent,+ },}export const sceneConfigurations: Record<Scene | string, SceneConfig> = {@@ -158,6 +162,9 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {[Scene.ErrorNetwork]: { name: 'Network error' },[Scene.ErrorProjectAccessDenied]: { name: 'Project access denied' },[Scene.ErrorProjectUnavailable]: { name: 'Project unavailable' },+ // Any scene can fail to mount, including a logged-out one (login, signup, invite, password reset),+ // so this generic error scene must render for both logged-out and logged-in visitors.+ [Scene.ErrorSceneLoad]: { name: 'Page could not load', allowUnauthenticated: true },[Scene.EventDefinitionEdit]: {projectBased: true,name: 'Data management',