: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(today): speed up home, rail, and views loading (#110598)
Shy Alter0dc77c2e7e92
diff --git a/docs/published/handbook/engineering/conventions/frontend-coding.md b/docs/published/handbook/engineering/conventions/frontend-coding.mdindex 2a41a24c5af5..1af51705fa67 100644--- a/docs/published/handbook/engineering/conventions/frontend-coding.md+++ b/docs/published/handbook/engineering/conventions/frontend-coding.md@@ -48,6 +48,8 @@ Hence the explicit separation between the data and view layers.- Scenes- Our app is built of _scenes_, managed through a scene router in `sceneLogic`.- A scene is the smallest unit in the router and for code splitting. Usually we split scenes by resource type (dashboard, insight) and function (edit, index).+ - Show available rows while other pages or sources load. Share concurrent requests for the same project and search across a scene and its sidebar.+ - Load optional panes, hover cards, and alternative home screens with `lazyWithRetry` and `Suspense`. Keep their data loaders in the component that needs them. A closed dialog or preview provider must not start requests for another pane.- Each scene (e.g. Dashboards) exports an object of type `SceneExport`, containing the scene's root `logic` and its React `component`.- The scene's logic is automatically mounted and receives the scene's URL params as props (via `paramsToProps`).- Use `urlToAction` and `actionToUrl` on the scene's logic to sync state with the URL. Try to only use them on the scene's logic, not in any deeper logics.diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex ed81f9e26c6c..f8b1e955e289 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -133,11 +133,17 @@ const ROOTS = [forbidden: [],},{- root: 'src/scenes/project-homepage/ProjectHomepage.tsx',- label: 'project home scene',- // 2026-10-01: 14.94 MiB (5579 files), linked stylesheet included. ~10% headroom.- budgetBytes: 17_240_000,- forbidden: [],+ root: [+ AUTHENTICATED_SHELL,+ 'src/scenes/project-homepage/ProjectHomepage.tsx',+ 'src/scenes/project-homepage/today/TodayHome.tsx',+ ],+ label: 'today home path',+ budgetBytes: 9_000_000,+ forbidden: [+ 'src/scenes/project-homepage/ai-first/AiFirstHomepage.tsx',+ 'src/scenes/project-homepage/today/TodayReportPage.tsx',+ ],},{root: 'src/scenes/activity/explore/EventsScene.tsx',diff --git a/frontend/src/layout/today/TodayPreviewCardProvider.tsx b/frontend/src/layout/today/TodayPreviewCardProvider.tsxindex 7e692d81e43c..22ef01584ed1 100644--- a/frontend/src/layout/today/TodayPreviewCardProvider.tsx+++ b/frontend/src/layout/today/TodayPreviewCardProvider.tsx@@ -1,18 +1,25 @@import { PreviewCard } from '@base-ui/react/preview-card'-import { useValues } from 'kea'-import { ReactNode, useCallback, useMemo, useRef, useState } from 'react'+import { ReactNode, Suspense, useCallback, useMemo, useRef, useState } from 'react'-import { Card } from '@posthog/quill'+import { Card, Skeleton } from '@posthog/quill'-import { TodayReportHoverCard } from 'scenes/project-homepage/today/TodayReportHoverCard'+import { lazyWithRetry } from 'lib/utils/retryImport'-import { TodayChatHoverCard } from './TodayChatHoverCard'import { TodayPreviewCard, TodayPreviewCardContext } from './todayPreviewCardContext'import { TodayPreviewPayload } from './todayPreviewCards'-import { TodaySessionHoverCard } from './TodaySessionHoverCard'-import { todaySessionMenuLogic } from './todaySessionMenuLogic'-import { todaySessionSelectionLogic } from './todaySessionSelectionLogic'-import { TodaySpaceHoverCard } from './TodaySpaceHoverCard'++const TodayReportHoverCard = lazyWithRetry(() =>+ import('scenes/project-homepage/today/TodayReportHoverCard').then((m) => ({ default: m.TodayReportHoverCard }))+)+const TodayChatHoverCard = lazyWithRetry(() =>+ import('./TodayChatHoverCard').then((m) => ({ default: m.TodayChatHoverCard }))+)+const TodaySessionHoverCard = lazyWithRetry(() =>+ import('./TodaySessionHoverCard').then((m) => ({ default: m.TodaySessionHoverCard }))+)+const TodaySpaceHoverCard = lazyWithRetry(() =>+ import('./TodaySpaceHoverCard').then((m) => ({ default: m.TodaySpaceHoverCard }))+)/** Beside a row, centered on it, so the path to a tall card is short from any row. Under a link in the* briefing text instead, so the card does not cover the line. */@@ -27,14 +34,17 @@ function placement(payload: TodayPreviewPayload): Pick<PreviewCard.Positioner.Pr* and Base UI skips the open delay when the pointer moves to another trigger of an open card,* so sliding down the list swaps the card's contents instead of waiting again on every row.*/-export function TodayPreviewCardProvider({ children }: { children: ReactNode }): JSX.Element {+export function TodayPreviewCardProvider({+ children,+ disabled = false,+}: {+ children: ReactNode+ disabled?: boolean+}): JSX.Element {const [handle] = useState(() => PreviewCard.createHandle<TodayPreviewPayload>())const [open, setOpen] = useState(false)// "File to…" opens outside the card, so the pointer moving there reads as leaving it.const [submenuOpen, setSubmenuOpen] = useState(false)- const { sessionDialogOpen } = useValues(todaySessionMenuLogic)- const { bulkArchiveConfirm } = useValues(todaySessionSelectionLogic)- const dialogOpen = sessionDialogOpen || bulkArchiveConfirm.open// A ref, so a hover that lands while a menu is open is refused on the same event.const menuOpen = useRef(false)const card = useMemo<TodayPreviewCard>(@@ -60,8 +70,8 @@ export function TodayPreviewCardProvider({ children }: { children: ReactNode }):<PreviewCard.Roothandle={handle}// A session dialog or the bulk archive confirm keeps the card shut, so the card cannot open over it.- open={(open || submenuOpen) && !dialogOpen}- onOpenChange={(next) => setOpen(next && !menuOpen.current && !dialogOpen)}+ open={(open || submenuOpen) && !disabled}+ onOpenChange={(next) => setOpen(next && !menuOpen.current && !disabled)}>{({ payload }) =>payload ? (@@ -76,21 +86,23 @@ export function TodayPreviewCardProvider({ children }: { children: ReactNode }):{/* Inside the popup, not its `render`: on React 18 quill's Card takes no ref. */}<PreviewCard.Popup className="outline-none"><Card size="sm" className="w-72 gap-0 border border-border py-0 shadow-md">- {payload.kind === 'space' ? (- <TodaySpaceHoverCard preview={payload} onAction={close} />- ) : payload.kind === 'chat' ? (- <TodayChatHoverCard preview={payload} onAction={close} />- ) : payload.kind === 'report' ? (- <TodayReportHoverCard preview={payload} />- ) : (- <TodaySessionHoverCard- // Keyed on the row, so moving to another row unmounts the card and lowers the submenu flag.- key={payload.menu.menuId}- preview={payload}- onAction={close}- onSubmenuOpenChange={setSubmenuOpen}- />- )}+ <Suspense fallback={<Skeleton className="h-24 w-full" />}>+ {payload.kind === 'space' ? (+ <TodaySpaceHoverCard preview={payload} onAction={close} />+ ) : payload.kind === 'chat' ? (+ <TodayChatHoverCard preview={payload} onAction={close} />+ ) : payload.kind === 'report' ? (+ <TodayReportHoverCard preview={payload} />+ ) : (+ <TodaySessionHoverCard+ // Keyed on the row, so moving to another row unmounts the card and lowers the submenu flag.+ key={payload.menu.menuId}+ preview={payload}+ onAction={close}+ onSubmenuOpenChange={setSubmenuOpen}+ />+ )}+ </Suspense></Card></PreviewCard.Popup></PreviewCard.Positioner>diff --git a/frontend/src/layout/today/TodayShell.tsx b/frontend/src/layout/today/TodayShell.tsxindex 9148d6613abc..82ea45c2a1b3 100644--- a/frontend/src/layout/today/TodayShell.tsx+++ b/frontend/src/layout/today/TodayShell.tsx@@ -1,26 +1,35 @@import './TodayShell.scss'import { useActions, useValues } from 'kea'-import { useEffect, useRef } from 'react'+import { Suspense, useEffect, useRef } from 'react'-import { ToastProvider } from '@posthog/quill'+import { Skeleton, ToastProvider } from '@posthog/quill'import 'scenes/project-homepage/today/Today.scss'import { Resizer } from 'lib/components/Resizer/Resizer'import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'import { cn } from 'lib/utils/css-classes'+import { lazyWithRetry } from 'lib/utils/retryImport'import { TodayHomeSidebar } from 'scenes/project-homepage/today/TodayHomeSidebar'-import { NewSpaceDialog } from 'products/tasks/frontend/spaces/NewSpaceDialog'--import { TodayLibrarySidebar } from './TodayLibrarySidebar'import { TodayPreviewCardProvider } from './TodayPreviewCardProvider'import { TodayRail } from './TodayRail'import { TODAY_RAIL_WIDTH, TODAY_SIDEBAR_CLOSE_THRESHOLD, clampSidebarWidth, todayShellLogic } from './todayShellLogic'import { TodaySidebarFooter } from './TodaySidebarFooter'-import { TodaySpacesSidebar } from './TodaySpacesSidebar'-import { TodayToolsSidebar } from './TodayToolsSidebar'-import { TodayViewsSidebar } from './TodayViewsSidebar'++const TodaySpacesPane = lazyWithRetry(() => import('./TodaySpacesPane').then((m) => ({ default: m.TodaySpacesPane })))+const TodayViewsSidebar = lazyWithRetry(() =>+ import('./TodayViewsSidebar').then((m) => ({ default: m.TodayViewsSidebar }))+)+const TodayToolsSidebar = lazyWithRetry(() =>+ import('./TodayToolsSidebar').then((m) => ({ default: m.TodayToolsSidebar }))+)+const TodayLibrarySidebar = lazyWithRetry(() =>+ import('./TodayLibrarySidebar').then((m) => ({ default: m.TodayLibrarySidebar }))+)+const NewSpaceDialog = lazyWithRetry(() =>+ import('products/tasks/frontend/spaces/NewSpaceDialog').then((m) => ({ default: m.NewSpaceDialog }))+)const PANE_LABELS = { home: 'Today', spaces: 'Spaces', views: 'Views', library: 'Library', tools: 'Tools' }@@ -66,21 +75,21 @@ export function TodayShell({ className }: { className?: string }): JSX.Element {const pane = (<div className="TodayShell__pane">- {activePane === 'home' ? (- <TodayPreviewCardProvider>- <TodayHomeSidebar />- </TodayPreviewCardProvider>- ) : activePane === 'spaces' ? (- <TodayPreviewCardProvider>- <TodaySpacesSidebar />- </TodayPreviewCardProvider>- ) : activePane === 'views' ? (- <TodayViewsSidebar />- ) : activePane === 'library' ? (- <TodayLibrarySidebar />- ) : (- <TodayToolsSidebar />- )}+ <Suspense fallback={<Skeleton className="m-4 h-24" />}>+ {activePane === 'home' ? (+ <TodayPreviewCardProvider>+ <TodayHomeSidebar />+ </TodayPreviewCardProvider>+ ) : activePane === 'spaces' ? (+ <TodaySpacesPane />+ ) : activePane === 'views' ? (+ <TodayViewsSidebar />+ ) : activePane === 'library' ? (+ <TodayLibrarySidebar />+ ) : (+ <TodayToolsSidebar />+ )}+ </Suspense></div>)@@ -131,7 +140,11 @@ export function TodayShell({ className }: { className?: string }): JSX.Element {))}{/* Mounted here so the sidebar and the spaces page open the same dialog. */}- <NewSpaceDialog />+ {activePane === 'spaces' && (+ <Suspense fallback={null}>+ <NewSpaceDialog />+ </Suspense>+ )}</div></ToastProvider>)diff --git a/frontend/src/layout/today/TodaySpacesPane.tsx b/frontend/src/layout/today/TodaySpacesPane.tsxnew file mode 100644index 000000000000..a528e388cbdd--- /dev/null+++ b/frontend/src/layout/today/TodaySpacesPane.tsx@@ -0,0 +1,17 @@+import { useValues } from 'kea'++import { TodayPreviewCardProvider } from './TodayPreviewCardProvider'+import { todaySessionMenuLogic } from './todaySessionMenuLogic'+import { todaySessionSelectionLogic } from './todaySessionSelectionLogic'+import { TodaySpacesSidebar } from './TodaySpacesSidebar'++export function TodaySpacesPane(): JSX.Element {+ const { sessionDialogOpen } = useValues(todaySessionMenuLogic)+ const { bulkArchiveConfirm } = useValues(todaySessionSelectionLogic)++ return (+ <TodayPreviewCardProvider disabled={sessionDialogOpen || bulkArchiveConfirm.open}>+ <TodaySpacesSidebar />+ </TodayPreviewCardProvider>+ )+}diff --git a/frontend/src/layout/today/TodayViewsSidebar.tsx b/frontend/src/layout/today/TodayViewsSidebar.tsxindex 7c16bd685bfb..6889420e5f36 100644--- a/frontend/src/layout/today/TodayViewsSidebar.tsx+++ b/frontend/src/layout/today/TodayViewsSidebar.tsx@@ -108,7 +108,7 @@ export function TodayViewsSidebar(): JSX.Element {</>}>- {!recentViews ? (+ {!recentViews || (recentViewsLoading && !recentItems.length) ? (recentUnavailable ? (<div className="TodayPane__state"><span>Your views didn’t load.</span>@@ -152,6 +152,11 @@ export function TodayViewsSidebar(): JSX.Element {Some views are not shown. Open All views and use search to find them.</div>)}+ {recentViewsLoading && (+ <div className="TodayPane__state" role="status">+ Loading more views…+ </div>+ )}{recentItems.map((item) => {const building = buildingViewIds.includes(item.id)return (diff --git a/frontend/src/layout/today/todayViewsLogic.ts b/frontend/src/layout/today/todayViewsLogic.tsindex bfd22bcdf801..4debef916ca6 100644--- a/frontend/src/layout/today/todayViewsLogic.ts+++ b/frontend/src/layout/today/todayViewsLogic.ts@@ -87,6 +87,9 @@ export interface todayViewsLogicActions {recentViews: ViewItemsPage | nullpayload?: void}+ receiveRecentViews: (page: ViewItemsPage) => {+ page: ViewItemsPage+ }setOpenCanvasBuilding: (canvasId: string,building: boolean | null@@ -164,6 +167,7 @@ export const todayViewsLogic = kea<todayViewsLogicType>([path(['layout', 'today', 'todayViewsLogic']),connect(() => ({ values: [teamLogic, ['currentTeamId'], userLogic, ['user']] })),actions({+ receiveRecentViews: (page: ViewItemsPage) => ({ page }),toggleRecent: true,setRecentQuery: (query: string) => ({ query }),setRecentSearchOpen: (open: boolean) => ({ open }),@@ -172,7 +176,7 @@ export const todayViewsLogic = kea<todayViewsLogicType>([/** The open canvas reports whether its agent or a build is at work, which it knows exactly. Null when it closes. */setOpenCanvasBuilding: (canvasId: string, building: boolean | null) => ({ canvasId, building }),}),- loaders(({ values }) => ({+ loaders(({ values, actions }) => ({recentViews: [null as ViewItemsPage | null,{@@ -182,9 +186,15 @@ export const todayViewsLogic = kea<todayViewsLogicType>([if (!values.currentTeamId) {return values.recentViews}- const page = await fetchViewItems(String(values.currentTeamId), '')+ const teamId = values.currentTeamId+ const page = await fetchViewItems(String(teamId), '', (page) => {+ breakpoint()+ if (values.currentTeamId === teamId) {+ actions.receiveRecentViews(page)+ }+ })breakpoint()- return page+ return values.currentTeamId === teamId ? page : values.recentViews},},],@@ -221,6 +231,9 @@ export const todayViewsLogic = kea<todayViewsLogicType>([],})),reducers({+ recentViews: {+ receiveRecentViews: (_, { page }) => page,+ },recentCollapsed: [false, { persist: true }, { toggleRecent: (state) => !state }],recentUnavailable: [false, { loadRecentViews: () => false, loadRecentViewsFailure: () => true }],recentQuery: ['', { setRecentQuery: (_, { query }) => query, clearRecentSearchAndFilters: () => '' }],diff --git a/frontend/src/scenes/project-homepage/ProjectHomepage.tsx b/frontend/src/scenes/project-homepage/ProjectHomepage.tsxindex 37f9a7282fdf..7a0761b99034 100644--- a/frontend/src/scenes/project-homepage/ProjectHomepage.tsx+++ b/frontend/src/scenes/project-homepage/ProjectHomepage.tsx@@ -1,12 +1,17 @@import './ProjectHomepage.scss'import { useValues } from 'kea'+import { Suspense } from 'react'+import { Spinner } from 'lib/lemon-ui/Spinner'+import { lazyWithRetry } from 'lib/utils/retryImport'import { projectHomepageLogic } from 'scenes/project-homepage/projectHomepageLogic'import { SceneExport } from 'scenes/sceneTypes'-import { AiFirstHomepage } from './ai-first/AiFirstHomepage'-import { TodayHome } from './today/TodayHome'+const AiFirstHomepage = lazyWithRetry(() =>+ import('./ai-first/AiFirstHomepage').then((m) => ({ default: m.AiFirstHomepage }))+)+const TodayHome = lazyWithRetry(() => import('./today/TodayHome').then((m) => ({ default: m.TodayHome })))export const scene: SceneExport = {component: ProjectHomepage,@@ -15,5 +20,11 @@ export const scene: SceneExport = {export function ProjectHomepage(): JSX.Element {const { todayHomeEnabled } = useValues(projectHomepageLogic)- return <div className="flex-1 min-h-0">{todayHomeEnabled ? <TodayHome /> : <AiFirstHomepage />}</div>+ return (+ <div className="flex-1 min-h-0">+ <Suspense fallback={<Spinner className="text-3xl mx-auto my-8" />}>+ {todayHomeEnabled ? <TodayHome /> : <AiFirstHomepage />}+ </Suspense>+ </div>+ )}diff --git a/frontend/src/scenes/project-homepage/today/TodayHome.tsx b/frontend/src/scenes/project-homepage/today/TodayHome.tsxindex ef91935793b4..dbf8ee8c9fdb 100644--- a/frontend/src/scenes/project-homepage/today/TodayHome.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayHome.tsx@@ -1,12 +1,18 @@import './Today.scss'import { useValues } from 'kea'+import { Suspense } from 'react'++import { Skeleton } from '@posthog/quill'++import { lazyWithRetry } from 'lib/utils/retryImport'import { TodayPreviewCardProvider } from '~/layout/today/TodayPreviewCardProvider'import { TodayBriefing } from './TodayBriefing'import { todayLogic } from './todayLogic'-import { TodayReportPage } from './TodayReportPage'++const TodayReportPage = lazyWithRetry(() => import('./TodayReportPage').then((m) => ({ default: m.TodayReportPage })))/** The Today homepage: the daily briefing at `/home`, or one report at `/home/reports/:reportId`. */export function TodayHome(): JSX.Element {@@ -15,7 +21,17 @@ export function TodayHome(): JSX.Element {return (<div className="Today flex-1 min-h-full @container/today">{reportId ? (- <TodayReportPage key={reportId} reportId={reportId} />+ <Suspense+ fallback={+ <div className="TodayReport Today__page flex flex-col gap-4">+ <Skeleton className="h-4 w-48" />+ <Skeleton className="h-10 w-3/4" />+ <Skeleton className="h-24" />+ </div>+ }+ >+ <TodayReportPage key={reportId} reportId={reportId} />+ </Suspense>) : (<TodayPreviewCardProvider><TodayBriefing />diff --git a/frontend/src/scenes/views/Views.tsx b/frontend/src/scenes/views/Views.tsxindex 1e14c735b782..9eab333cf911 100644--- a/frontend/src/scenes/views/Views.tsx+++ b/frontend/src/scenes/views/Views.tsx@@ -65,7 +65,7 @@ function ViewsContent(): JSX.Element {)const renderList = (): JSX.Element => {- if (!views) {+ if (!views || (viewsLoading && !visibleViews.length)) {return loadFailed ? (<Empty><EmptyHeader>@@ -190,6 +190,11 @@ function ViewsContent(): JSX.Element {Some views are not shown. Use search to find more views.</Text>)}+ {viewsLoading && visibleViews.length > 0 && (+ <Text size="sm" variant="muted" role="status">+ Loading more views…+ </Text>+ )}{renderList()}</div></SceneContent>diff --git a/frontend/src/scenes/views/fetchViewItems.test.ts b/frontend/src/scenes/views/fetchViewItems.test.tsindex 3d40298dcf8b..9941a4aef96e 100644--- a/frontend/src/scenes/views/fetchViewItems.test.ts+++ b/frontend/src/scenes/views/fetchViewItems.test.ts@@ -19,19 +19,40 @@ describe('fetchViewItems', () => {},},})- const page = await fetchViewItems('1', '')+ const [page, sidebar] = await Promise.all([fetchViewItems('1', ''), fetchViewItems('1', '')])expect(requests).toBe(5)expect(page.truncated).toBe(true)+ expect(sidebar).toEqual(page)+ await fetchViewItems('1', '')+ expect(requests).toBe(8)})it('includes recent dashboards from later pages', async () => {+ let releaseSpaces!: () => void+ const spacesReady = new Promise<void>((resolve) => {+ releaseSpaces = resolve+ })+ let firstPage!: () => void+ const firstPageReady = new Promise<void>((resolve) => {+ firstPage = resolve+ })+ let releaseLaterPage!: () => void+ const laterPageReady = new Promise<void>((resolve) => {+ releaseLaterPage = resolve+ })useMocks({get: {'/api/projects/:team_id/canvases/': { results: [], next: null },'/api/projects/:team_id/notebooks/': { results: [], next: null },- '/api/projects/:team_id/task_channels/': [],- '/api/projects/:team_id/dashboards/': ({ request }) => {+ '/api/projects/:team_id/task_channels/': async () => {+ await spacesReady+ return []+ },+ '/api/projects/:team_id/dashboards/': async ({ request }) => {const offset = new URL(request.url).searchParams.get('offset')+ if (offset !== '0') {+ await laterPageReady+ }return offset === '0'? {results: [{ id: 1, name: 'A', created_at: '2026-01-01', last_viewed_at: '2026-01-01' }],@@ -44,8 +65,47 @@ describe('fetchViewItems', () => {},},})- const page = await fetchViewItems('1', '')+ const progress: string[][] = []+ const pending = fetchViewItems('1', '', (page) => {+ progress.push(page.items.map((item) => item.id))+ firstPage()+ })+ await firstPageReady+ expect(progress[0]).toEqual(['1'])+ const sidebarProgress = jest.fn()+ const sidebar = fetchViewItems('1', '', sidebarProgress)+ expect(sidebarProgress.mock.calls[0][0].items.map((item: { id: string }) => item.id)).toEqual(['1'])+ releaseLaterPage()+ releaseSpaces()+ const [page, sidebarPage] = await Promise.all([pending, sidebar])expect(page.failedTypes).toEqual([])expect(page.items.map((item) => item.id)).toEqual(['2', '1'])+ expect(sidebarPage).toEqual(page)+ })++ it.each([+ ['2', ''],+ ['1', 'Revenue'],+ ])('keeps project %s and search %s separate', async (projectId, search) => {+ useMocks({+ get: {+ '/api/projects/:team_id/canvases/': { results: [], next: null },+ '/api/projects/:team_id/notebooks/': { results: [], next: null },+ '/api/projects/:team_id/task_channels/': [],+ '/api/projects/:team_id/dashboards/': ({ request, params }) => ({+ results: [+ {+ id: 1,+ name: `${params.team_id}:${new URL(request.url).searchParams.get('search') ?? ''}`,+ created_at: '2026-01-01',+ },+ ],+ next: null,+ }),+ },+ })+ const [first, second] = await Promise.all([fetchViewItems('1', ''), fetchViewItems(projectId, search)])+ expect(first.items[0].name).toBe('1:')+ expect(second.items[0].name).toBe(`${projectId}:${search}`)})})diff --git a/frontend/src/scenes/views/fetchViewItems.ts b/frontend/src/scenes/views/fetchViewItems.tsindex df8466145078..c9e12a575382 100644--- a/frontend/src/scenes/views/fetchViewItems.ts+++ b/frontend/src/scenes/views/fetchViewItems.ts@@ -1,3 +1,5 @@+import { isBreakpoint } from 'kea'+import { spaceLabel } from '~/layout/today/todaySpacesLogic'import { canvasesList } from 'products/canvas/frontend/generated/api'@@ -8,7 +10,7 @@ import type { NotebooksListParams } from 'products/notebooks/frontend/generated/import { taskChannelsList } from 'products/tasks/frontend/generated/api'import type { ChannelDTOApi } from 'products/tasks/frontend/generated/api.schemas'-import { LISTED_CANVAS_KINDS, ViewItem, ViewType, mergeViews } from './viewsUtils'+import { LISTED_CANVAS_KINDS, ViewItem, ViewSources, ViewType, mergeViews } from './viewsUtils'const VIEWS_PAGE_SIZE = 100const MAX_VIEW_PAGES = 5@@ -21,13 +23,15 @@ export interface ViewItemsPage {}async function fetchViewPages<T>(- fetchPage: (offset: number) => Promise<{ results: T[]; next?: string | null }>+ fetchPage: (offset: number) => Promise<{ results: T[]; next?: string | null }>,+ onPage?: (items: T[]) => void): Promise<{ items: T[]; truncated: boolean }> {const results: T[] = []let pagefor (let pageIndex = 0; pageIndex < MAX_VIEW_PAGES; pageIndex++) {page = await fetchPage(results.length)results.push(...page.results)+ onPage?.([...results])if (!page.next || page.results.length === 0) {return { items: results, truncated: false }}@@ -38,11 +42,19 @@ async function fetchViewPages<T>(async function fetchCanvases(projectId: string,search: string | undefined,- limit: number+ limit: number,+ onPage: (items: CanvasApi[]) => void): Promise<{ items: CanvasApi[]; truncated: boolean }> {+ const itemsByKind = new Map<string, CanvasApi[]>()const pages = await Promise.all(LISTED_CANVAS_KINDS.map((kind) =>- fetchViewPages((offset) => canvasesList(projectId, { kind, search, limit, offset }))+ fetchViewPages(+ (offset) => canvasesList(projectId, { kind, search, limit, offset }),+ (items) => {+ itemsByKind.set(kind, items)+ onPage([...itemsByKind.values()].flat())+ }+ )))return { items: pages.flatMap((page) => page.items), truncated: pages.some((page) => page.truncated) }@@ -56,16 +68,46 @@ async function fetchSpaceNames(projectId: string): Promise<Record<string, string}/** Canvases, notebooks and dashboards in one list. A type that fails to load leaves the others in place. */-export async function fetchViewItems(projectId: string, search: string): Promise<ViewItemsPage> {+async function collectViewItems(+ projectId: string,+ search: string,+ onProgress: (page: ViewItemsPage) => void+): Promise<ViewItemsPage> {+ const sources: ViewSources = { canvases: [], notebooks: [], dashboards: [], spaceNames: {} }+ const publish = (): void => {+ const items = mergeViews(sources)+ if (items.length) {+ onProgress({ items, failedTypes: [] })+ }+ }const limit = VIEWS_PAGE_SIZEconst query = search.trim() || undefined// The notebooks endpoint filters on `search`, but its schema does not declare the parameter.const notebookParams: NotebooksListParams & { search?: string } = { limit, search: query }const [canvases, notebooks, dashboards, spaceNames] = await Promise.allSettled([- fetchCanvases(projectId, query, limit),- fetchViewPages((offset) => notebooksList(projectId, { ...notebookParams, offset })),- fetchViewPages((offset) => dashboardsList(projectId, { search: query, limit, offset })),- fetchSpaceNames(projectId),+ fetchCanvases(projectId, query, limit, (items) => {+ sources.canvases = items+ publish()+ }),+ fetchViewPages(+ (offset) => notebooksList(projectId, { ...notebookParams, offset }),+ (items) => {+ sources.notebooks = items+ publish()+ }+ ),+ fetchViewPages(+ (offset) => dashboardsList(projectId, { search: query, limit, offset }),+ (items) => {+ sources.dashboards = items+ publish()+ }+ ),+ fetchSpaceNames(projectId).then((names) => {+ sources.spaceNames = names+ publish()+ return names+ }),])const failedTypes: ViewType[] = [...(canvases.status === 'rejected' ? (['canvas'] as const) : []),@@ -89,3 +131,58 @@ export async function fetchViewItems(projectId: string, search: string): Promise),}}++interface PendingViewItems {+ promise: Promise<ViewItemsPage>+ progress: ViewItemsPage | null+ subscribers: Set<(page: ViewItemsPage) => void>+}++const pendingViewItems = new Map<string, PendingViewItems>()++export async function fetchViewItems(+ projectId: string,+ search: string,+ onProgress?: (page: ViewItemsPage) => void+): Promise<ViewItemsPage> {+ const key = JSON.stringify([projectId, search.trim()])+ let pending = pendingViewItems.get(key)+ if (!pending) {+ const subscribers = new Set<(page: ViewItemsPage) => void>()+ const notify = (page: ViewItemsPage): void => {+ const current = pendingViewItems.get(key)+ if (current) {+ current.progress = page+ }+ for (const subscriber of subscribers) {+ try {+ subscriber(page)+ } catch (error) {+ if (!(error instanceof Error && isBreakpoint(error))) {+ throw error+ }+ subscribers.delete(subscriber)+ }+ }+ }+ pending = {+ promise: collectViewItems(projectId, search, notify).finally(() => pendingViewItems.delete(key)),+ progress: null,+ subscribers,+ }+ pendingViewItems.set(key, pending)+ }+ if (onProgress) {+ pending.subscribers.add(onProgress)+ }+ try {+ if (onProgress && pending.progress) {+ onProgress(pending.progress)+ }+ return await pending.promise+ } finally {+ if (onProgress) {+ pending.subscribers.delete(onProgress)+ }+ }+}diff --git a/frontend/src/scenes/views/viewsLogic.ts b/frontend/src/scenes/views/viewsLogic.tsindex 9cd2e45a538f..79dff092e1d9 100644--- a/frontend/src/scenes/views/viewsLogic.ts+++ b/frontend/src/scenes/views/viewsLogic.ts@@ -41,6 +41,9 @@ export interface viewsLogicActions {views: ViewItemsPage | nullpayload?: void}+ receiveViews: (page: ViewItemsPage) => {+ page: ViewItemsPage+ }setSearch: (search: string) => {search: string}@@ -62,6 +65,7 @@ export const viewsLogic = kea<viewsLogicType>([path(['scenes', 'views', 'viewsLogic']),connect(() => ({ values: [featureFlagLogic, ['featureFlags'], teamLogic, ['currentTeamId']] })),actions({+ receiveViews: (page: ViewItemsPage) => ({ page }),setSearch: (search: string) => ({ search }),setTypeFilter: (typeFilter: ViewTypeFilter) => ({ typeFilter }),}),@@ -69,7 +73,7 @@ export const viewsLogic = kea<viewsLogicType>([search: ['', { setSearch: (_, { search }) => search }],typeFilter: ['all' as ViewTypeFilter, { setTypeFilter: (_, { typeFilter }) => typeFilter }],}),- loaders(({ values }) => ({+ loaders(({ values, actions }) => ({views: [null as ViewItemsPage | null,{@@ -78,14 +82,24 @@ export const viewsLogic = kea<viewsLogicType>([if (!values.currentTeamId) {return values.views}- const page = await fetchViewItems(String(values.currentTeamId), values.search)+ const teamId = values.currentTeamId+ const search = values.search+ const page = await fetchViewItems(String(teamId), search, (page) => {+ breakpoint()+ if (values.currentTeamId === teamId && values.search === search) {+ actions.receiveViews(page)+ }+ })breakpoint()- return page+ return values.currentTeamId === teamId && values.search === search ? page : values.views},},],})),reducers({+ views: {+ receiveViews: (_, { page }) => page,+ },loadFailed: [false, { loadViews: () => false, loadViewsFailure: () => true }],}),selectors({