: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(frontend): defer shell requests until the first scene renders (#127062)
Paul D'Ambraa59e2eb88e4e
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.tsindex 1b43b56de50a..984be81b13e4 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts@@ -1,5 +1,8 @@import { expectLogic } from 'kea-test-utils'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { InAppNotification } from '~/types'@@ -247,6 +250,36 @@ describe('sidePanelNotificationsLogic.archive', () => {})})+describe('sidePanelNotificationsLogic.unreadCount', () => {+ let logic: ReturnType<typeof sidePanelNotificationsLogic.build>++ afterEach(() => logic.unmount())++ it.each([+ { mode: 'real-time', realTime: true, legacyRequests: 0 },+ { mode: 'legacy', realTime: false, legacyRequests: 1 },+ ])('requests legacy notifications $legacyRequests times in $mode mode', async ({ realTime, legacyRequests }) => {+ let requests = 0+ useMocks({+ get: {+ '/api/projects/:tid/my_notifications': () => {+ requests += 1+ return [200, { results: [], last_read: null }]+ },+ },+ })+ initKeaTests()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.REAL_TIME_NOTIFICATIONS]: realTime })+ logic = sidePanelNotificationsLogic()+ logic.mount()++ expect(logic.values.unreadCount).toBe(0)+ await expectLogic(logic).toDispatchActions(['loadImportantChangesSuccess'])++ expect(requests).toBe(legacyRequests)+ })+})+describe('sidePanelNotificationsLogic.mainListOffset', () => {let logic: ReturnType<typeof sidePanelNotificationsLogic.build>diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsxindex 36a47982801b..e4e262fe8ace 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx@@ -22,6 +22,7 @@ import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { sceneRenderedLogic } from 'lib/logic/sceneRenderedLogic'import { liveEventsHostOrigin } from 'lib/utils/apiHost'import { retryWithBackoff } from 'lib/utils/async'import { toParams } from 'lib/utils/url'@@ -167,6 +168,7 @@ export interface sidePanelNotificationsLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogiccurrentOrganization: OrganizationType | null // organizationLogiccurrentProjectId: number | null // projectLogic+ sceneHasRendered: boolean // sceneRenderedLogicsceneSidePanelContext: SidePanelSceneContext // sidePanelContextLogiccurrentTeam: TeamPublicType | TeamType | null // teamLogiccurrentTeamId: number | null // teamLogic@@ -208,6 +210,9 @@ export interface sidePanelNotificationsLogicActions {resourceEdited: (event: ResourceEditedEvent) => {event: ResourceEditedEvent} // resourceEditedLogic+ sceneRendered: () => {+ value: true+ } // sceneRenderedLogicloadCurrentTeamSuccess: (currentTeam: TeamPublicType | null,payload?: any@@ -277,6 +282,9 @@ export interface sidePanelNotificationsLogicActions {onlyUnread: any}}+ loadInitialNotifications: () => {+ value: true+ }loadMoreArchived: () => {value: true}@@ -436,11 +444,21 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(['currentTeam', 'currentTeamId'],organizationLogic,['currentOrganization'],+ sceneRenderedLogic,+ ['sceneHasRendered'],+ ],+ actions: [+ teamLogic,+ ['loadCurrentTeamSuccess'],+ resourceEditedLogic,+ ['resourceEdited'],+ sceneRenderedLogic,+ ['sceneRendered'],],- actions: [teamLogic, ['loadCurrentTeamSuccess'], resourceEditedLogic, ['resourceEdited']],})),actions({togglePolling: (pageIsVisible: boolean) => ({ pageIsVisible }),+ loadInitialNotifications: true,incrementErrorCount: true,clearErrorCount: true,markAllAsRead: true,@@ -666,6 +684,10 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(null as ChangesResponse | null,{loadImportantChanges: async ({ onlyUnread }, breakpoint) => {+ // With real-time notifications, the panel and the unread badge read the in-app list instead.+ if (values.realTimeNotificationsEnabled) {+ return values.importantChanges+ }await breakpoint(1)try {@@ -771,6 +793,32 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(}return {+ // Notifications show in a badge and a side panel, not in the scene, so the scene's requests go first.+ sceneRendered: () => {+ if (values.realTimeNotificationsEnabled) {+ actions.loadInitialNotifications()+ }+ },+ loadInitialNotifications: async () => {+ try {+ const resp = await notificationsList((values.currentProjectId ?? '').toString(), {+ limit: NOTIFICATION_PAGE_SIZE,+ })+ actions.setInAppNotifications(resp.results as InAppNotification[], !!resp.next)+ } catch {+ // Swallow+ }+ try {+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. notificationsUnreadCountRetrieve() from 'products/notifications/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.+ const countResp = await api.get<{ count: number }>(+ `api/projects/${values.currentProjectId}/notifications/unread_count/`+ )+ actions.setInAppUnreadCount(countResp.count)+ } catch {+ // Swallow+ }+ actions.initialLoadDone()+ },togglePolling: ({ pageIsVisible }) => {if (values.realTimeNotificationsEnabled) {return@@ -1321,26 +1369,9 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(}),afterMount(({ cache, actions, values }) => {if (values.realTimeNotificationsEnabled) {- void (async () => {- try {- const resp = await notificationsList((values.currentProjectId ?? '').toString(), {- limit: NOTIFICATION_PAGE_SIZE,- })- actions.setInAppNotifications(resp.results as InAppNotification[], !!resp.next)- } catch {- // Swallow- }- try {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. notificationsUnreadCountRetrieve() from 'products/notifications/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.- const countResp = await api.get<{ count: number }>(- `api/projects/${values.currentProjectId}/notifications/unread_count/`- )- actions.setInAppUnreadCount(countResp.count)- } catch {- // Swallow- }- actions.initialLoadDone()- })()+ if (values.sceneHasRendered) {+ actions.loadInitialNotifications()+ }if (values.currentTeam?.live_events_token) {actions.startSSE()diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.tsindex 3f17f633ef4f..e787ad7037b3 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts@@ -57,6 +57,53 @@ describe('projectTreeDataLogic', () => {expect(logic.values.currentHomeFolder?.path).toBe('Research/My work')})+ it.each([+ { name: 'nothing when both lists show it', shortcut: true, rootFolder: true, reloads: [] },+ {+ name: 'the shortcuts when its shortcut is missing',+ shortcut: false,+ rootFolder: true,+ reloads: ['shortcuts'],+ },+ { name: 'the root folder when its parent is missing', shortcut: true, rootFolder: false, reloads: ['root'] },+ {+ name: 'both lists for a new home folder',+ shortcut: false,+ rootFolder: false,+ reloads: ['shortcuts', 'root'],+ },+ ])('after the home folder loads, reloads $name', async ({ shortcut, rootFolder, reloads }) => {+ useMocks({ post: { '/api/projects/:team_id/file_system/home_folder/': { id: 'home', path: 'Users/Alex' } } })+ logic.actions.loadShortcutsSuccess(+ shortcut ? [{ id: 'star-home', path: 'Alex', type: 'folder', ref: 'Users/Alex' }] : []+ )+ logic.actions.loadFolderSuccess(+ '',+ rootFolder ? [{ id: 'users', path: 'Users', type: 'folder' }] : [],+ false,+ rootFolder ? 1 : 0+ )++ await expectLogic(logic, () => logic.actions.loadHomeFolder()).toDispatchActions(['loadHomeFolderSuccess'])++ expect(api.fileSystemShortcuts.list).toHaveBeenCalledTimes(reloads.includes('shortcuts') ? 1 : 0)+ expect(api.fileSystem.list).toHaveBeenCalledTimes(reloads.includes('root') ? 1 : 0)+ })++ it('checks each list once its own boot load ends', async () => {+ useMocks({ post: { '/api/projects/:team_id/file_system/home_folder/': { id: 'home', path: 'Users/Alex' } } })+ logic.actions.loadFolderStart('')++ await expectLogic(logic, () => logic.actions.loadHomeFolder()).toDispatchActions(['loadHomeFolderSuccess'])+ expect(api.fileSystem.list).not.toHaveBeenCalled()+ expect(api.fileSystemShortcuts.list).toHaveBeenCalledTimes(1)++ logic.actions.loadFolderSuccess('', [{ id: 'users', path: 'Users', type: 'folder' }], false, 1)++ expect(api.fileSystem.list).not.toHaveBeenCalled()+ expect(api.fileSystemShortcuts.list).toHaveBeenCalledTimes(1)+ })+it.each(['loaded', 'loading', 'has-more', 'populated'] as const)('renders a starred nested folder with %s contents',(state) => {diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsxindex 1258564c6cf6..72fc02fad076 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx@@ -115,6 +115,10 @@ function applyOrder(shortcuts: FileSystemEntry[], orderedIds: string[]): FileSysreturn [...reordered, ...trailing]}+function hasFolderEntry(entries: FileSystemEntry[] | undefined, field: 'path' | 'ref', value: string): boolean {+ return !!entries?.some((entry) => entry.type === 'folder' && entry[field] === value)+}+type DeleteFolderDialogContentProps = {folderName: stringfolderPath: string@@ -552,6 +556,9 @@ export interface projectTreeDataLogicActions {projectTreeLogicKey: string}}+ reloadIfHomeFolderMissing: () => {+ value: true+ }removeQueuedAction: (action: ProjectTreeAction) => {action: ProjectTreeAction}@@ -762,6 +769,7 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([addShortcutItem: (item: FileSystemEntry, successMessage?: string) => ({ item, successMessage }),deleteShortcut: (id: FileSystemEntry['id'], successMessage?: string) => ({ id, successMessage }),loadShortcuts: true,+ reloadIfHomeFolderMissing: true,reorderShortcuts: (orderedIds: NonNullable<FileSystemEntry['id']>[]) => ({ orderedIds }),// Resolves a sibling drag ('before' / 'after' a target row) into a new ordered list and// dispatches `reorderShortcuts`. Lives here so the component stays free of business logic.@@ -1793,8 +1801,38 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([actions.loadShortcuts()},loadHomeFolderSuccess: () => {- actions.loadShortcuts()- actions.loadFolder('', true)+ cache.homeShortcutCheckPending = true+ cache.homeRootCheckPending = true+ actions.reloadIfHomeFolderMissing()+ },+ loadShortcutsSuccess: () => actions.reloadIfHomeFolderMissing(),+ loadShortcutsFailure: () => actions.reloadIfHomeFolderMissing(),+ loadFolderSuccess: ({ folder }) => {+ if (folder === '') {+ actions.reloadIfHomeFolderMissing()+ }+ },+ loadFolderFailure: ({ folder }) => {+ if (folder === '') {+ actions.reloadIfHomeFolderMissing()+ }+ },+ // The first home folder request creates the folder and its shortcut, while the boot loads of both lists+ // run. Each list reloads only if it does not show the folder, and a slow list does not hold back the other.+ reloadIfHomeFolderMissing: () => {+ const path = values.homeFolder?.path+ if (cache.homeShortcutCheckPending && !values.shortcutDataLoading) {+ cache.homeShortcutCheckPending = false+ if (path && !hasFolderEntry(values.shortcutData, 'ref', path)) {+ actions.loadShortcuts()+ }+ }+ if (cache.homeRootCheckPending && values.folderStates[''] !== 'loading') {+ cache.homeRootCheckPending = false+ if (path && !hasFolderEntry(values.folders[''], 'path', splitPath(path)[0])) {+ actions.loadFolder('', true)+ }+ }},reorderShortcutByDrag: ({ activeTreeId, overTreeId, position }) => {const map = values.shortcutEntryIdMapdiff --git a/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsxindex 51ea8414ec5a..a1a98dc22eb1 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx@@ -24,7 +24,7 @@ export function NotificationsPanel(): JSX.Element {archivedLoaded,loadedUnreadCount,inAppUnreadCount,- importantChangesLoading,+ isInitialLoadComplete,hasMoreNotifications,hasMoreArchived,isLoadingMore,@@ -126,7 +126,7 @@ export function NotificationsPanel(): JSX.Element {className="flex-1 overflow-hidden"innerClassName="p-1">- {(isArchivedTab ? !archivedLoaded : importantChangesLoading && groups.length === 0) ? (+ {(isArchivedTab ? !archivedLoaded : !isInitialLoadComplete && groups.length === 0) ? (<div className="p-2"><LemonSkeleton className="h-10 my-1" repeat={5} fade /></div>diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.test.ts b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.test.tsindex aa6bbe2faf7a..2b5aa3a6dbf0 100644--- a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.test.ts+++ b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.test.ts@@ -1,3 +1,5 @@+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { initKeaTests } from '~/test/init'import { eventDefinitionsList } from 'products/event_definitions/frontend/generated/api'@@ -38,4 +40,22 @@ describe('productSetupPreloadLogic', () => {expect(eventDefinitionsList).toHaveBeenCalledTimes(calls)})++ it('sends one request when the flags arrive while the mount request runs', async () => {+ let respond: () => void = () => {}+ jest.mocked(eventDefinitionsList).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ respond = () =>+ resolve({ results: [] } as unknown as Awaited<ReturnType<typeof eventDefinitionsList>>)+ })+ )++ productSetupPreloadLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {})+ respond()+ await jest.runOnlyPendingTimersAsync()++ expect(eventDefinitionsList).toHaveBeenCalledTimes(1)+ })})diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.tsindex a0fbe655976a..12e599d8b264 100644--- a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts+++ b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts@@ -20,6 +20,9 @@ export interface productSetupPreloadLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface productSetupPreloadLogicActions {+ preloadAgainIfAsked: () => {+ value: true+ }preloadStatuses: () => {value: true}@@ -52,6 +55,7 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([})),actions({preloadStatuses: true,+ preloadAgainIfAsked: true,}),listeners(({ actions, values, cache }) => ({preloadStatuses: async (_, breakpoint) => {@@ -89,6 +93,7 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([}// Nothing was marked seeded, so the next trigger retries; until then the// in-scene detection logic answers on its own.+ actions.preloadAgainIfAsked()return} finally {cache.requestsInFlight -= 1@@ -102,6 +107,13 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([seeded.add(`${teamId}:${probe.productKey}`)seedProbeStatus(probe, existingDefinitions, cache)}+ actions.preloadAgainIfAsked()+ },+ preloadAgainIfAsked: () => {+ if (cache.preloadAgain) {+ cache.preloadAgain = false+ actions.preloadStatuses()+ }},// Covers login and project switches that happen after mount.[teamLogic.actionTypes.loadCurrentTeamSuccess]: ({ currentTeam }) => {@@ -113,7 +125,12 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([// the boot triggers have already run - re-check so flag-gated probes aren't// silently skipped for the whole session.[featureFlagLogic.actionTypes.setFeatureFlags]: () => {- actions.preloadStatuses()+ // A second run would send the same request and cancel the one in flight, so it waits for that one.+ if (cache.requestsInFlight) {+ cache.preloadAgain = true+ } else {+ actions.preloadStatuses()+ }},})),afterMount(({ actions, cache }) => {diff --git a/frontend/src/lib/logic/billing/billingLogic.tsx b/frontend/src/lib/logic/billing/billingLogic.tsxindex f9ec6f4ace9d..afcd45d1732c 100644--- a/frontend/src/lib/logic/billing/billingLogic.tsx+++ b/frontend/src/lib/logic/billing/billingLogic.tsx@@ -18,6 +18,7 @@ import { lemonBannerLogic } from 'lib/lemon-ui/LemonBanner/lemonBannerLogic'import { LemonButtonPropsBase } from 'lib/lemon-ui/LemonButton'import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { preflightLogic } from 'lib/logic/preflightLogic'+import { sceneRenderedLogic } from 'lib/logic/sceneRenderedLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { pluralize } from 'lib/utils/strings'import { organizationLogic } from 'scenes/organizationLogic'@@ -206,6 +207,7 @@ export interface billingLogicValues {currentOrganization: OrganizationType | null // organizationLogiccurrentOrganizationId: string // organizationLogicpreflight: PreflightStatus | null // preflightLogic+ sceneHasRendered: boolean // sceneRenderedLogicfakeBillingAlert: FakeBillingAlert // superpowersLogicaccountOwner: {email?: string@@ -346,6 +348,9 @@ export interface billingLogicActions {value: true} // lemonBannerLogicloadCurrentOrganization: () => any // organizationLogic+ sceneRendered: () => {+ value: true+ } // sceneRenderedLogicloadUser: (resetOnFailure?: boolean | undefined) => {resetOnFailure: boolean | undefined} // userLogic@@ -795,8 +800,12 @@ export const billingLogic = kea<billingLogicType>([['currentOrganization', 'currentOrganizationId'],superpowersLogic,['fakeBillingAlert'],+ sceneRenderedLogic,+ ['sceneHasRendered'],],actions: [+ sceneRenderedLogic,+ ['sceneRendered'],userLogic,['loadUser'],organizationLogic,@@ -1610,7 +1619,7 @@ export const billingLogic = kea<billingLogicType>([}),},})),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({reportBillingShown: () => {posthog.capture('billing v2 shown')},@@ -1647,6 +1656,12 @@ export const billingLogic = kea<billingLogicType>([switchFlatrateSubscriptionPlan: async (payload) => {actions.setSwitchPlanLoading(payload.to_product_key)},+ sceneRendered: () => {+ if (cache.loadCreditOverviewAfterScene) {+ cache.loadCreditOverviewAfterScene = false+ actions.loadCreditOverview()+ }+ },loadBillingSuccess: async ({ payload }, breakpoint) => {actions.registerInstrumentationProps()actions.determineBillingAlert()@@ -1655,7 +1670,12 @@ export const billingLogic = kea<billingLogicType>([if (payload) {return}- actions.loadCreditOverview()+ // Only billing views show credits, so this request waits for the scene's own requests.+ if (values.sceneHasRendered) {+ actions.loadCreditOverview()+ } else {+ cache.loadCreditOverviewAfterScene = true+ }// If the activation is successful, we reload the user/organization to get the updated available features// activation can be triggered from the billing page or onboardingdiff --git a/frontend/src/lib/logic/sceneRenderedLogic.test.ts b/frontend/src/lib/logic/sceneRenderedLogic.test.tsnew file mode 100644index 000000000000..670bbdf5968e--- /dev/null+++ b/frontend/src/lib/logic/sceneRenderedLogic.test.ts@@ -0,0 +1,56 @@+import { expectLogic } from 'kea-test-utils'++import { onFirstSceneRendered } from 'lib/utils/bootTiming'++import { initKeaTests } from '~/test/init'++import { SCENE_RENDERED_MAX_WAIT_MS, sceneRenderedLogic } from './sceneRenderedLogic'++jest.mock('lib/utils/bootTiming', () => ({ onFirstSceneRendered: jest.fn() }))++describe('sceneRenderedLogic', () => {+ let renderScene: () => void++ beforeEach(() => {+ jest.useFakeTimers()+ renderScene = () => {}+ initKeaTests()+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it.each([+ { name: 'when the scene renders', trigger: 'render' },+ { name: 'after the maximum wait when no scene renders', trigger: 'wait' },+ { name: 'at mount when the scene has already rendered', trigger: 'mount' },+ ])('dispatches sceneRendered once, $name', async ({ trigger }) => {+ jest.mocked(onFirstSceneRendered).mockImplementation((listener) => {+ renderScene = listener+ if (trigger === 'mount') {+ listener()+ }+ return () => {}+ })+ const logic = sceneRenderedLogic()++ await expectLogic(logic, () => {+ logic.mount()+ jest.advanceTimersByTime(SCENE_RENDERED_MAX_WAIT_MS - 1)+ expect(logic.values.sceneHasRendered).toBe(trigger === 'mount')+ if (trigger === 'render') {+ renderScene()+ } else if (trigger === 'wait') {+ jest.advanceTimersByTime(1)+ }+ })+ .toDispatchActions(['sceneRendered'])+ .toMatchValues({ sceneHasRendered: true })++ await expectLogic(logic, () => {+ jest.advanceTimersByTime(SCENE_RENDERED_MAX_WAIT_MS)+ renderScene()+ }).toNotHaveDispatchedActions(['sceneRendered'])+ })+})diff --git a/frontend/src/lib/logic/sceneRenderedLogic.ts b/frontend/src/lib/logic/sceneRenderedLogic.tsnew file mode 100644index 000000000000..eee2aae824dd--- /dev/null+++ b/frontend/src/lib/logic/sceneRenderedLogic.ts@@ -0,0 +1,60 @@+import { MakeLogicType, actions, afterMount, kea, path, reducers } from 'kea'++import { onFirstSceneRendered } from 'lib/utils/bootTiming'+import { permanentlyMount } from 'lib/utils/kea-logic-builders'++// Longer than the 99th percentile time from `app_ready` to `scene_rendered`.+export const SCENE_RENDERED_MAX_WAIT_MS = 10000++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sceneRenderedLogicValues {+ sceneHasRendered: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sceneRenderedLogicActions {+ sceneRendered: () => {+ value: true+ }+}++export type sceneRenderedLogicType = MakeLogicType<sceneRenderedLogicValues, sceneRenderedLogicActions>++/**+ * Lets a request the first paint does not need wait for the first scene. A consumer listens for `sceneRendered`+ * and checks `sceneHasRendered` in `afterMount`. A page with no scene fires it after the maximum wait.+ */+export const sceneRenderedLogic = kea<sceneRenderedLogicType>([+ path(['lib', 'logic', 'sceneRenderedLogic']),+ actions({+ sceneRendered: true,+ }),+ reducers({+ sceneHasRendered: [+ false,+ {+ sceneRendered: () => true,+ },+ ],+ }),+ afterMount(({ actions, values, cache }) => {+ const markRendered = (): void => {+ if (!values.sceneHasRendered) {+ actions.sceneRendered()+ }+ }+ // A hidden tab must not pause these, or a consumer in a background tab would wait until the tab shows.+ cache.disposables.add(() => onFirstSceneRendered(markRendered), 'firstSceneRendered', {+ pauseOnPageHidden: false,+ })+ cache.disposables.add(+ () => {+ const timer = window.setTimeout(markRendered, SCENE_RENDERED_MAX_WAIT_MS)+ return () => clearTimeout(timer)+ },+ 'sceneRenderedFallback',+ { pauseOnPageHidden: false }+ )+ }),+ permanentlyMount(),+])diff --git a/frontend/src/lib/utils/bootTiming.test.ts b/frontend/src/lib/utils/bootTiming.test.tsindex 221ffb0d4267..b3a279791d6d 100644--- a/frontend/src/lib/utils/bootTiming.test.ts+++ b/frontend/src/lib/utils/bootTiming.test.ts@@ -3,6 +3,7 @@ import type posthogType from 'posthog-js'import type {createSceneRenderedMark as createSceneRenderedMarkType,markBootPhase as markBootPhaseType,+ onFirstSceneRendered as onFirstSceneRenderedType,} from './bootTiming'describe('bootTiming', () => {@@ -12,6 +13,7 @@ describe('bootTiming', () => {let markBootPhase: typeof markBootPhaseTypelet createSceneRenderedMark: typeof createSceneRenderedMarkType+ let onFirstSceneRendered: typeof onFirstSceneRenderedTypelet capture: jest.SpyInstancelet getDistinctId: jest.SpyInstancelet now: number@@ -22,7 +24,7 @@ describe('bootTiming', () => {jest.resetModules()now = 0nowSpy = jest.spyOn(performance, 'now').mockImplementation(() => now)- ;({ markBootPhase, createSceneRenderedMark } = require('./bootTiming'))+ ;({ markBootPhase, createSceneRenderedMark, onFirstSceneRendered } = require('./bootTiming'))const posthog: typeof posthogType = require('posthog-js').defaultcapture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)getDistinctId = jest.spyOn(posthog, 'get_distinct_id').mockReturnValue(IN_SAMPLE_ID)@@ -276,6 +278,28 @@ describe('bootTiming', () => {expect(capture).toHaveBeenCalledWith('app boot timing', expect.objectContaining({ page_was_hidden: true }))})+ it.each([+ { name: 'at once when the scene has already rendered', events: ['entry', 'render', 'listen'], calls: 1 },+ { name: 'on the first scene render', events: ['entry', 'listen', 'render', 'render'], calls: 1 },+ { name: 'at once when boot timing does not run', events: ['listen'], calls: 1 },+ { name: 'never after the listener is removed', events: ['entry', 'listen', 'remove', 'render'], calls: 0 },+ ])('onFirstSceneRendered calls the listener $name', ({ events, calls }) => {+ const listener = jest.fn()+ let remove = (): void => {}+ for (const event of events) {+ if (event === 'entry') {+ markAt(50, 'entry')+ } else if (event === 'render') {+ markAt(900, 'scene_rendered')+ } else if (event === 'listen') {+ remove = onFirstSceneRendered(listener)+ } else {+ remove()+ }+ }+ expect(listener).toHaveBeenCalledTimes(calls)+ })+it.each([{ reason: 'the entry script did not run, as in tests, storybook and the exporter', runEntry: false },{ reason: 'performance.now is unavailable', runEntry: true, nowThrows: true },diff --git a/frontend/src/lib/utils/bootTiming.ts b/frontend/src/lib/utils/bootTiming.tsindex 572016ce4370..3de05bbc4001 100644--- a/frontend/src/lib/utils/bootTiming.ts+++ b/frontend/src/lib/utils/bootTiming.ts@@ -103,10 +103,24 @@ export function markBootPhase(phase: BootPhase, phaseContext?: BootContext): voi}Object.assign(context, phaseContext)if (phase === 'scene_rendered') {+ sceneRenderedListeners.forEach((listener) => listener())+ sceneRenderedListeners.clear()void sendBootTiming().catch(() => {})}}+const sceneRenderedListeners = new Set<() => void>()++/** Calls `listener` once on the first scene render, or at once if that happened or boot timing does not run. */+export function onFirstSceneRendered(listener: () => void): () => void {+ if (phaseTimes.entry === undefined || phaseTimes.scene_rendered !== undefined) {+ listener()+ return () => {}+ }+ sceneRenderedListeners.add(listener)+ return () => sceneRenderedListeners.delete(listener)+}+export interface SceneRenderedMark {/** Holds the mark while a Suspense fallback stands in for the scene's lazy content. Returns the release. */holdUntilContent: () => () => voiddiff --git a/products/conversations/frontend/supportTicketCounterLogic.test.ts b/products/conversations/frontend/supportTicketCounterLogic.test.tsindex b344f1aab997..4fd7627568de 100644--- a/products/conversations/frontend/supportTicketCounterLogic.test.ts+++ b/products/conversations/frontend/supportTicketCounterLogic.test.ts@@ -1,23 +1,33 @@import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import { expectLogic } from 'kea-test-utils'+import api from 'lib/api'+import { sceneRenderedLogic } from 'lib/logic/sceneRenderedLogic'+import { onFirstSceneRendered } from 'lib/utils/bootTiming'import { teamLogic } from 'scenes/teamLogic'import { initKeaTests } from '~/test/init'import { supportTicketCounterLogic } from './supportTicketCounterLogic'+jest.mock('lib/utils/bootTiming', () => ({ onFirstSceneRendered: jest.fn() }))+describe('supportTicketCounterLogic', () => {let logic: ReturnType<typeof supportTicketCounterLogic.build>let unreadCount: jest.SpyInstance+ let renderScene: () => voidconst team = { ...MOCK_DEFAULT_TEAM, conversations_enabled: true }beforeEach(() => {jest.useFakeTimers()+ jest.mocked(onFirstSceneRendered).mockImplementation((listener) => {+ renderScene = listener+ return () => {}+ })initKeaTests(true, team)unreadCount = jest.spyOn(api.conversationsTickets, 'unreadCount').mockResolvedValue({ count: 3 })logic = supportTicketCounterLogic()- logic.mount()})afterEach(() => {@@ -26,7 +36,24 @@ describe('supportTicketCounterLogic', () => {jest.restoreAllMocks()})+ it.each(['before', 'after'])('loads the count once when it mounts %s the first scene render', async (when) => {+ await expectLogic(logic, () => {+ sceneRenderedLogic.mount()+ if (when === 'after') {+ renderScene()+ }+ logic.mount()+ renderScene()+ })+ .toDispatchActions(['loadUnreadCount'])+ .toNotHaveDispatchedActions(['loadUnreadCount'])+ await jest.advanceTimersByTimeAsync(1)+ expect(unreadCount).toHaveBeenCalledTimes(1)+ })+it('ignores unrelated team updates but refreshes when support is enabled again', async () => {+ logic.mount()+ renderScene()await jest.advanceTimersByTimeAsync(1)teamLogic.actions.loadCurrentTeamSuccess({ ...team, name: 'Updated name' })await jest.advanceTimersByTimeAsync(1)diff --git a/products/conversations/frontend/supportTicketCounterLogic.ts b/products/conversations/frontend/supportTicketCounterLogic.tsindex 220147008cd3..64481b9a6bfb 100644--- a/products/conversations/frontend/supportTicketCounterLogic.ts+++ b/products/conversations/frontend/supportTicketCounterLogic.ts@@ -3,6 +3,7 @@ import { loaders } from 'kea-loaders'import { subscriptions } from 'kea-subscriptions'import api from 'lib/api'+import { sceneRenderedLogic } from 'lib/logic/sceneRenderedLogic'import { teamLogic } from 'scenes/teamLogic'import type { TeamPublicType, TeamType } from '../../../frontend/src/types'@@ -17,6 +18,7 @@ export interface UnreadCountResponse {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface supportTicketCounterLogicValues {canShowNotifications: boolean // browserNotificationLogic+ sceneHasRendered: boolean // sceneRenderedLogiccurrentTeam: TeamPublicType | TeamType | null // teamLogicerrorCounter: numberisSupportEnabled: boolean@@ -29,6 +31,9 @@ export interface supportTicketCounterLogicActions {showNotification: (count: number) => {count: number} // browserNotificationLogic+ sceneRendered: () => {+ value: true+ } // sceneRenderedLogicclearErrorCount: () => {value: true}@@ -102,8 +107,15 @@ export type supportTicketCounterLogicType = MakeLogicType<export const supportTicketCounterLogic = kea<supportTicketCounterLogicType>([path(['products', 'conversations', 'frontend', 'supportTicketCounterLogic']),connect(() => ({- values: [teamLogic, ['currentTeam'], browserNotificationLogic, ['canShowNotifications']],- actions: [browserNotificationLogic, ['showNotification']],+ values: [+ teamLogic,+ ['currentTeam'],+ browserNotificationLogic,+ ['canShowNotifications'],+ sceneRenderedLogic,+ ['sceneHasRendered'],+ ],+ actions: [browserNotificationLogic, ['showNotification'], sceneRenderedLogic, ['sceneRendered']],})),actions({incrementErrorCount: true,@@ -156,6 +168,12 @@ export const supportTicketCounterLogic = kea<supportTicketCounterLogicType>([],}),listeners(({ actions, values, cache }) => ({+ // The count shows only as a badge, so its first request waits for the scene's own requests.+ sceneRendered: () => {+ if (values.isSupportEnabled) {+ actions.loadUnreadCount()+ }+ },// Re-schedule after each load completes. The loader catches API errors// and returns a value, so the failure action never actually dispatches —// a single success listener covers both the happy path and the swallowed@@ -212,7 +230,7 @@ export const supportTicketCounterLogic = kea<supportTicketCounterLogicType>([},})),afterMount(({ actions, values }) => {- if (values.isSupportEnabled) {+ if (values.sceneHasRendered && values.isSupportEnabled) {actions.loadUnreadCount()}}),diff --git a/products/webmcp/frontend/logics/webmcpLogic.ts b/products/webmcp/frontend/logics/webmcpLogic.tsindex f29cf539b71a..2487f8619da1 100644--- a/products/webmcp/frontend/logics/webmcpLogic.ts+++ b/products/webmcp/frontend/logics/webmcpLogic.ts@@ -2,6 +2,7 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path } froimport posthog from 'posthog-js'import { preflightLogic } from 'lib/logic/preflightLogic'+import { sceneRenderedLogic } from 'lib/logic/sceneRenderedLogic'import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'@@ -47,6 +48,7 @@ export function formatExecResult(result: WebMCPExecResultApi): string {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface webmcpLogicValues {preflight: PreflightStatus | null // preflightLogic+ sceneHasRendered: boolean // sceneRenderedLogiccurrentTeamId: number | null // teamLogicuser: UserType | null // userLogic}@@ -60,6 +62,9 @@ export interface webmcpLogicActions {payload?: anypreflight: PreflightStatus} // preflightLogic+ sceneRendered: () => {+ value: true+ } // sceneRenderedLogicloadCurrentTeamSuccess: (currentTeam: null | import('~/types').TeamPublicType,payload?: any@@ -77,14 +82,34 @@ export type webmcpLogicType = MakeLogicType<webmcpLogicValues, webmcpLogicActionexport const webmcpLogic = kea<webmcpLogicType>([path(['products', 'webmcp', 'frontend', 'logics', 'webmcpLogic']),connect(() => ({- values: [preflightLogic, ['preflight'], teamLogic, ['currentTeamId'], userLogic, ['user']],- actions: [preflightLogic, ['loadPreflightSuccess'], teamLogic, ['loadCurrentTeamSuccess']],+ values: [+ preflightLogic,+ ['preflight'],+ teamLogic,+ ['currentTeamId'],+ userLogic,+ ['user'],+ sceneRenderedLogic,+ ['sceneHasRendered'],+ ],+ actions: [+ preflightLogic,+ ['loadPreflightSuccess'],+ teamLogic,+ ['loadCurrentTeamSuccess'],+ sceneRenderedLogic,+ ['sceneRendered'],+ ],})),actions({registerTool: true,}),listeners(({ actions, cache, values }) => ({// The preflight and the team can arrive after mount, and the tool needs both.+ // No part of the first paint uses the tool, so its request also waits for the scene's own requests.+ sceneRendered: () => {+ actions.registerTool()+ },loadPreflightSuccess: () => {actions.registerTool()},@@ -96,6 +121,7 @@ export const webmcpLogic = kea<webmcpLogicType>([// Without an MCP server every proxy call fails, and the backend refuses impersonated sessions.if (!modelContext ||+ !values.sceneHasRendered ||!values.preflight?.webmcp_available ||values.user?.is_impersonated ||!values.currentTeamId ||