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.

feat(frontend): start loading the page's scene when the app boots (#127407)

Paul D'Ambraf009a9ff99fc
diff --git a/frontend/package.json b/frontend/package.json
index c9cced3a1e4d..4857761d82dd 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -306,6 +306,7 @@
"tailwind-merge": "^2.2.2",
"torph": "^0.0.9",
"ts-pattern": "catalog:",
+ "url-pattern": "^1.0.3",
"use-debounce": "catalog:",
"use-resize-observer": "^8.0.0",
"v86": "0.5.458",
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index 460843f62eb1..3b80f83f3249 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -14,9 +14,9 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import {
addProjectIdIfMissing,
ensureRoutablePathname,
- removeProjectIdIfPresent,
- stripTrailingSlash,
+ pathFromWindowToRoutes,
stripTrailingSlashFromUrl,
+ urlPatternOptions,
} from 'lib/utils/kea-router'
import { identifierToHuman } from 'lib/utils/strings'
@@ -259,11 +259,7 @@ export function initKea({
routerPlugin({
history: routerHistory,
location: routerLocation,
- urlPatternOptions: {
- // :TRICKY: What chars to allow in named segment values i.e. ":key"
- // in "/url/:key". Default: "a-zA-Z0-9-_~ %".
- segmentValueCharset: "a-zA-Z0-9-_~ %.@()!'|:",
- },
+ urlPatternOptions,
pathFromRoutesToWindow: (path) => {
return addProjectIdIfMissing(path)
},
@@ -277,9 +273,7 @@ export function initKea({
// navigation that runs every `urlToAction` of the scene again.
return addProjectIdIfMissing(stripTrailingSlashFromUrl(ensureRoutablePathname(path)))
},
- pathFromWindowToRoutes: (path) => {
- return stripTrailingSlash(removeProjectIdIfPresent(path))
- },
+ pathFromWindowToRoutes,
replaceInitialPathInWindow:
typeof replaceInitialPathInWindow === 'undefined' ? true : replaceInitialPathInWindow,
}),
diff --git a/frontend/src/lib/utils/bootTiming.ts b/frontend/src/lib/utils/bootTiming.ts
index c78fe8699df1..7bf3ae193b30 100644
--- a/frontend/src/lib/utils/bootTiming.ts
+++ b/frontend/src/lib/utils/bootTiming.ts
@@ -8,6 +8,7 @@ export type BootPhase =
| 'app_modules_loaded'
| 'css_ready'
| 'app_booted'
+ | 'scene_prefetched'
| 'app_first_render'
| 'app_ready'
| 'scene_loaded'
@@ -15,6 +16,7 @@ export type BootPhase =
export interface BootContext {
scene?: string
+ prefetched_scene?: string
logged_in?: boolean
deferred_app_context?: boolean
deferred_app_context_variant?: string
diff --git a/frontend/src/lib/utils/kea-router.ts b/frontend/src/lib/utils/kea-router.ts
index 82b65e49c631..901a76e1db52 100644
--- a/frontend/src/lib/utils/kea-router.ts
+++ b/frontend/src/lib/utils/kea-router.ts
@@ -124,6 +124,16 @@ export function stripTrailingSlash(path: string): string {
return path
}
+export const urlPatternOptions = {
+ // :TRICKY: What chars to allow in named segment values i.e. ":key"
+ // in "/url/:key". Default: "a-zA-Z0-9-_~ %".
+ segmentValueCharset: "a-zA-Z0-9-_~ %.@()!'|:",
+}
+
+export function pathFromWindowToRoutes(path: string): string {
+ return stripTrailingSlash(removeProjectIdIfPresent(path))
+}
+
/**
* Strips the trailing slash of the path only, so a query string or hash that ends in a slash
* (e.g. `?next=/oauth/authorize/`) survives. Safe on a full URL as well as a bare path.
diff --git a/frontend/src/scenes/bootApp.ts b/frontend/src/scenes/bootApp.ts
index f05b70d7b365..3786a6e7a68e 100644
--- a/frontend/src/scenes/bootApp.ts
+++ b/frontend/src/scenes/bootApp.ts
@@ -1,5 +1,6 @@
import { registerToastGetHelp } from 'lib/components/Support/registerToastGetHelp'
import { registerNotebookLinkDrag } from 'scenes/notebooks/AddToNotebook/registerNotebookLinkDrag'
+import { prefetchScene } from 'scenes/prefetchScene'
import { initKea } from '../initKea'
import { loadPostHogJS } from '../loadPostHogJS'
@@ -33,6 +34,7 @@ export function bootApp(): void {
// Same seam for the error toast's "Get help" button: the app opens support in place, the
// toolbar and exporter keep linking out to the support options docs
registerToastGetHelp()
+ prefetchScene()
const idle =
typeof window.requestIdleCallback === 'function'
diff --git a/frontend/src/scenes/prefetchScene.test.ts b/frontend/src/scenes/prefetchScene.test.ts
new file mode 100644
index 000000000000..a3e6342ae84a
--- /dev/null
+++ b/frontend/src/scenes/prefetchScene.test.ts
@@ -0,0 +1,42 @@
+import { appScenes } from 'scenes/appScenes'
+import { prefetchScene, sceneForPathname } from 'scenes/prefetchScene'
+import { Scene } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+describe('prefetchScene', () => {
+ afterEach(() => {
+ jest.restoreAllMocks()
+ window.history.replaceState(null, '', '/')
+ })
+
+ it.each([
+ ['a project page', `/project/1${urls.savedInsights()}`, Scene.SavedInsights],
+ ['a page with params', `/project/1${urls.replaySingle('abc')}`, Scene.ReplaySingle],
+ ['a trailing slash', `/project/1${urls.savedInsights()}/`, Scene.SavedInsights],
+ ['a page outside a project', urls.savedInsights(), Scene.SavedInsights],
+ ['a redirect that also matches a route', '/project/1/replay/recent', null],
+ ['the root', '/', null],
+ ['an unknown page', '/project/1/no-such-page/at-all', null],
+ ['a path that does not decode', '/project/1/person/50%off', null],
+ ])('finds the scene for %s', (_case, pathname, expected) => {
+ expect(sceneForPathname(pathname)).toEqual(expected)
+ })
+
+ it.each([
+ [
+ 'throws',
+ (): never => {
+ throw new Error('import failed')
+ },
+ ],
+ ['rejects', (): Promise<never> => Promise.reject(new Error('import failed'))],
+ ])('lets the boot continue when the scene import %s', async (_case, failingImport) => {
+ window.history.replaceState(null, '', `/project/1${urls.savedInsights()}`)
+ const importScene = jest.spyOn(appScenes, Scene.SavedInsights).mockImplementation(failingImport)
+
+ expect(() => prefetchScene()).not.toThrow()
+ await Promise.resolve()
+
+ expect(importScene).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/scenes/prefetchScene.ts b/frontend/src/scenes/prefetchScene.ts
new file mode 100644
index 000000000000..59ec74004a67
--- /dev/null
+++ b/frontend/src/scenes/prefetchScene.ts
@@ -0,0 +1,45 @@
+import posthog from 'posthog-js'
+import UrlPattern from 'url-pattern'
+
+import { markBootPhase } from 'lib/utils/bootTiming'
+import { pathFromWindowToRoutes, urlPatternOptions } from 'lib/utils/kea-router'
+import { appScenes } from 'scenes/appScenes'
+import { redirects, routes } from 'scenes/scenes'
+
+function matchesRoute(pattern: string, path: string): boolean {
+ const staticPrefix = pattern.split(/[:*(]/)[0]
+ return path.startsWith(staticPrefix) && new UrlPattern(pattern, urlPatternOptions).match(path) !== null
+}
+
+/** The scene that sceneLogic opens for `pathname`, or null when a redirect handles it or no route matches. */
+export function sceneForPathname(pathname: string): string | null {
+ let path: string
+ try {
+ path = pathFromWindowToRoutes(decodeURI(pathname))
+ } catch {
+ return null
+ }
+ if (path === '/' || Object.keys(redirects).some((pattern) => matchesRoute(pattern, path))) {
+ return null
+ }
+ const route = Object.entries(routes).find(([pattern]) => matchesRoute(pattern, path))
+ return route ? route[1][0] : null
+}
+
+/**
+ * Starts to load the code of the scene for this page, so it downloads while the app renders.
+ * The boot timing event reports the scene, so a wrong guess shows up as a `prefetched_scene` that differs from `scene`.
+ */
+export function prefetchScene(): void {
+ try {
+ const scene = sceneForPathname(window.location.pathname)
+ const importScene = scene ? appScenes[scene] : undefined
+ if (!scene || !importScene) {
+ return
+ }
+ Promise.resolve(importScene()).catch(() => {})
+ markBootPhase('scene_prefetched', { prefetched_scene: scene })
+ } catch (error) {
+ posthog.captureException(error, { extra: { source: 'prefetchScene' } })
+ }
+}
diff --git a/frontend/src/scenes/project-homepage/importProjectHomepage.test.ts b/frontend/src/scenes/project-homepage/importProjectHomepage.test.ts
index 465b8c5ecbbc..ffdb18ab3b4e 100644
--- a/frontend/src/scenes/project-homepage/importProjectHomepage.test.ts
+++ b/frontend/src/scenes/project-homepage/importProjectHomepage.test.ts
@@ -24,18 +24,26 @@ describe('importProjectHomepage', () => {
beforeEach(() => {
loadedModules.length = 0
jest.resetModules()
- initKeaTests()
- featureFlagLogic.mount()
})
it.each([
[true, 'TodayHome'],
[false, 'AiFirstHomepage'],
])('loads the home content with the scene (today on: %s)', async (todayOn, content) => {
+ initKeaTests()
+ featureFlagLogic.mount()
featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TODAY_RAIL_NAV]: todayOn })
await importProjectHomepage()
expect(loadedModules.sort()).toEqual([content, 'ProjectHomepage'].sort())
})
+
+ it('loads only the scene before the app mounts the flag logic', async () => {
+ initKeaTests(false)
+
+ await importProjectHomepage()
+
+ expect(loadedModules).toEqual(['ProjectHomepage'])
+ })
})
diff --git a/frontend/src/scenes/project-homepage/importProjectHomepage.ts b/frontend/src/scenes/project-homepage/importProjectHomepage.ts
index c7681b46b813..0e4c99966325 100644
--- a/frontend/src/scenes/project-homepage/importProjectHomepage.ts
+++ b/frontend/src/scenes/project-homepage/importProjectHomepage.ts
@@ -13,10 +13,10 @@ export function importTodayHome(): Promise<typeof import('./today/TodayHome')> {
}
export function importProjectHomepage(): Promise<typeof import('./ProjectHomepage')> {
- const importContent = featureFlagLogic.values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]
- ? importTodayHome
- : importAiFirstHomepage
- // ProjectHomepage imports the content again and handles a failure there.
- importContent().catch(() => {})
+ const featureFlags = featureFlagLogic.findMounted()?.values.featureFlags
+ if (featureFlags) {
+ const importContent = featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] ? importTodayHome : importAiFirstHomepage
+ importContent().catch(() => {})
+ }
return import('./ProjectHomepage')
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ae9d35f86422..735323841ec3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1294,6 +1294,9 @@ importers:
ts-pattern:
specifier: 'catalog:'
version: 4.3.0
+ url-pattern:
+ specifier: ^1.0.3
+ version: 1.0.3
use-debounce:
specifier: 'catalog:'
version: 9.0.3([email protected])