: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(views): load the views page from the ordered feed (#111113)
Shy Alter9c575f95b661
diff --git a/frontend/src/scenes/views/Views.tsx b/frontend/src/scenes/views/Views.tsxindex 9eab333cf911..9672d622810f 100644--- a/frontend/src/scenes/views/Views.tsx+++ b/frontend/src/scenes/views/Views.tsx@@ -1,4 +1,6 @@import { useActions, useValues } from 'kea'+import { useEffect } from 'react'+import { useInView } from 'react-intersection-observer'import { IconGridMasonry, IconPlus, IconSearch } from '@posthog/icons'import {@@ -35,6 +37,8 @@ import { ViewRow } from './ViewRow'import { viewsLogic } from './viewsLogic'import { VIEW_TYPES, VIEW_TYPE_INFO, ViewTypeFilter } from './viewsUtils'+const SCROLL_PREFETCH_MARGIN = '1200px 0px'+export const scene: SceneExport = {component: Views,logic: viewsLogic,@@ -52,10 +56,38 @@ export function Views(): JSX.Element {return viewsEnabled ? <ViewsContent /> : <NotFound object="page" />}+function ViewRowSkeletons({ count }: { count: number }): JSX.Element {+ return (+ <>+ {Array.from({ length: count }, (_, index) => (+ <Item key={index} variant="outline" size="sm">+ <ItemMedia variant="icon">+ <Skeleton className="size-4" />+ </ItemMedia>+ <ItemContent className="gap-1.5">+ <Skeleton className="h-3.5 w-48 max-w-full" />+ <Skeleton className="h-3 w-32 max-w-full" />+ </ItemContent>+ </Item>+ ))}+ </>+ )+}+function ViewsContent(): JSX.Element {- const { views, visibleViews, viewsLoading, loadFailed, search, typeFilter } = useValues(viewsLogic)- const { setSearch, setTypeFilter, loadViews } = useActions(viewsLogic)- const failedTypes = views?.failedTypes ?? []+ const { feed, feedStale, search, typeFilter } = useValues(viewsLogic)+ const { setSearch, setTypeFilter, loadViews, loadMoreViews } = useActions(viewsLogic)+ const { ref: endRef, inView: endInView } = useInView({+ root: document.getElementById('main-content'),+ rootMargin: SCROLL_PREFETCH_MARGIN,+ })+ const { items, initialized, loading, hasMore, failedTypes, loadFailed } = feed++ useEffect(() => {+ if (endInView && hasMore) {+ loadMoreViews()+ }+ }, [endInView, hasMore, items.length, loadMoreViews])const newViewButton = (<NewViewMenu trigger={<Button variant="primary" size="sm" data-attr="views-new" />}>@@ -65,41 +97,29 @@ function ViewsContent(): JSX.Element {)const renderList = (): JSX.Element => {- if (!views || (viewsLoading && !visibleViews.length)) {- return loadFailed ? (+ if (loadFailed) {+ return (<Empty><EmptyHeader><EmptyTitle>Couldn’t load your views</EmptyTitle><EmptyDescription>Try again, and if it keeps happening contact support.</EmptyDescription></EmptyHeader><EmptyContent>- <Button- variant="outline"- loading={viewsLoading}- onClick={() => loadViews()}- data-attr="views-retry"- >+ <Button variant="outline" loading={loading} onClick={() => loadViews()} data-attr="views-retry">Try again</Button></EmptyContent></Empty>- ) : (+ )+ }+ if (!initialized) {+ return (<ItemGroup combined aria-busy aria-label="Loading your views">- {Array.from({ length: 6 }, (_, index) => (- <Item key={index} variant="outline" size="sm">- <ItemMedia variant="icon">- <Skeleton className="size-4" />- </ItemMedia>- <ItemContent className="gap-1.5">- <Skeleton className="h-3.5 w-48 max-w-full" />- <Skeleton className="h-3 w-32 max-w-full" />- </ItemContent>- </Item>- ))}+ <ViewRowSkeletons count={6} /></ItemGroup>)}- if (!visibleViews.length) {+ if (!items.length) {const filterLabel = typeFilter === 'all' ? 'views' : VIEW_TYPE_INFO[typeFilter].pluralLabel.toLowerCase()return (<Empty>@@ -119,10 +139,15 @@ function ViewsContent(): JSX.Element {)}return (- <ItemGroup combined>- {visibleViews.map((view) => (+ <ItemGroup+ combined+ aria-busy={feedStale || hasMore}+ className={feedStale ? 'opacity-60 transition-opacity' : 'transition-opacity'}+ >+ {items.map((view) => (<ViewRow key={`${view.type}-${view.id}`} view={view} />))}+ {hasMore && <ViewRowSkeletons count={3} />}</ItemGroup>)}@@ -165,19 +190,17 @@ function ViewsContent(): JSX.Element {))}</ToggleGroup></div>- {views && (loadFailed || failedTypes.length > 0) && (+ {initialized && !loadFailed && failedTypes.length > 0 && (<div className="flex flex-wrap items-center gap-2" role="alert"><Text size="sm" variant="destructive">- {loadFailed- ? 'Couldn’t refresh your views, so this list may be out of date.'- : `${failedTypes- .map((type) => VIEW_TYPE_INFO[type].pluralLabel)- .join(' and ')} didn’t load, so this list may be incomplete.`}+ {`${failedTypes+ .map((type) => VIEW_TYPE_INFO[type].pluralLabel)+ .join(' and ')} didn’t load, so this list may be incomplete.`}</Text><Buttonvariant="outline"size="xs"- loading={viewsLoading}+ loading={loading}onClick={() => loadViews()}data-attr="views-retry">@@ -185,17 +208,8 @@ function ViewsContent(): JSX.Element {</Button></div>)}- {views?.truncated && (- <Text size="sm" variant="muted">- 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 ref={endRef} aria-hidden /></div></SceneContent>)diff --git a/frontend/src/scenes/views/fetchViewItems.test.ts b/frontend/src/scenes/views/fetchViewItems.test.tsdeleted file mode 100644index 9941a4aef96e..000000000000--- a/frontend/src/scenes/views/fetchViewItems.test.ts+++ /dev/null@@ -1,111 +0,0 @@-import { useMocks } from '~/mocks/jest'--import { fetchViewItems } from './fetchViewItems'--describe('fetchViewItems', () => {- it('bounds pagination and marks an incomplete list', async () => {- let requests = 0- 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/': () => {- requests += 1- return {- results: [{ id: requests, name: 'Dashboard', created_at: '2026-01-01' }],- next: requests < 8 ? `?offset=${requests}` : null,- }- },- },- })- 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/': 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' }],- next: '?offset=1',- }- : {- results: [{ id: 2, name: 'Z', created_at: '2026-01-01', last_viewed_at: '2026-01-02' }],- next: null,- }- },- },- })- 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.tsdeleted file mode 100644index c9e12a575382..000000000000--- a/frontend/src/scenes/views/fetchViewItems.ts+++ /dev/null@@ -1,188 +0,0 @@-import { isBreakpoint } from 'kea'--import { spaceLabel } from '~/layout/today/todaySpacesLogic'--import { canvasesList } from 'products/canvas/frontend/generated/api'-import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'-import { dashboardsList } from 'products/dashboards/frontend/generated/api'-import { notebooksList } from 'products/notebooks/frontend/generated/api'-import type { NotebooksListParams } from 'products/notebooks/frontend/generated/api.schemas'-import { taskChannelsList } from 'products/tasks/frontend/generated/api'-import type { ChannelDTOApi } from 'products/tasks/frontend/generated/api.schemas'--import { LISTED_CANVAS_KINDS, ViewItem, ViewSources, ViewType, mergeViews } from './viewsUtils'--const VIEWS_PAGE_SIZE = 100-const MAX_VIEW_PAGES = 5--export interface ViewItemsPage {- items: ViewItem[]- /** Types whose request failed. The list holds the other types only. */- failedTypes: ViewType[]- truncated?: boolean-}--async function fetchViewPages<T>(- fetchPage: (offset: number) => Promise<{ results: T[]; next?: string | null }>,- onPage?: (items: T[]) => void-): Promise<{ items: T[]; truncated: boolean }> {- const results: T[] = []- let page- for (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 }- }- }- return { items: results, truncated: true }-}--async function fetchCanvases(- projectId: string,- search: string | undefined,- 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 }),- (items) => {- itemsByKind.set(kind, items)- onPage([...itemsByKind.values()].flat())- }- )- )- )- return { items: pages.flatMap((page) => page.items), truncated: pages.some((page) => page.truncated) }-}--async function fetchSpaceNames(projectId: string): Promise<Record<string, string>> {- const response = await taskChannelsList(projectId)- // Without `limit` the endpoint answers with a bare array rather than a page.- const spaces = Array.isArray(response) ? (response as ChannelDTOApi[]) : response.results- return Object.fromEntries(spaces.map((space) => [space.id, spaceLabel(space)]))-}--/** Canvases, notebooks and dashboards in one list. A type that fails to load leaves the others in place. */-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_SIZE- const 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, (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) : []),- ...(notebooks.status === 'rejected' ? (['notebook'] as const) : []),- ...(dashboards.status === 'rejected' ? (['dashboard'] as const) : []),- ]- if (failedTypes.length === 3) {- throw canvases.status === 'rejected' ? canvases.reason : new Error('Views did not load')- }- return {- items: mergeViews({- canvases: canvases.status === 'fulfilled' ? canvases.value.items : [],- notebooks: notebooks.status === 'fulfilled' ? notebooks.value.items : [],- dashboards: dashboards.status === 'fulfilled' ? dashboards.value.items : [],- // Without space names, canvas rows still show. They only lose the space label.- spaceNames: spaceNames.status === 'fulfilled' ? spaceNames.value : {},- }),- failedTypes,- truncated: [canvases, notebooks, dashboards].some(- (result) => result.status === 'fulfilled' && result.value.truncated- ),- }-}--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 79dff092e1d9..f0377ce20636 100644--- a/frontend/src/scenes/views/viewsLogic.ts+++ b/frontend/src/scenes/views/viewsLogic.ts@@ -1,52 +1,72 @@import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'-import { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'-import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { ViewItemsPage, fetchViewItems } from './fetchViewItems'-import { ViewItem, ViewTypeFilter, filterViews } from './viewsUtils'+import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'+import { VIEW_FEED_PAGE_SIZE, ViewFeed, ViewFeedQuery, ViewSourceState } from './viewFeed'+import { selectViewFeed, viewFeedLogic } from './viewFeedLogic'+import { ViewTypeFilter } from './viewsUtils'++export const VIEWS_PREFETCH_COUNT = VIEW_FEED_PAGE_SIZE// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface viewsLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogiccurrentTeamId: number | null // teamLogic- loadFailed: boolean+ sources: Record<string, ViewSourceState> // viewFeedLogic+ spaceNames: Record<string, string> // viewFeedLogic+ currentFeed: ViewFeed+ feed: ViewFeed+ feedQuery: ViewFeedQuery+ feedSearch: string+ feedStale: booleansearch: string+ shownQuery: ViewFeedQuery | nulltypeFilter: ViewTypeFilter- views: ViewItemsPage | null- viewsLoading: boolean- visibleViews: ViewItem[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface viewsLogicActions {- loadViews: (_: void) => void- loadViewsFailure: (- error: string,- errorObject?: any+ ensureFeed: (+ query: ViewFeedQuery,+ count: number) => {- error: string- errorObject?: any- }- loadViewsSuccess: (- views: ViewItemsPage | null,- payload?: void+ count: number+ query: ViewFeedQuery+ } // viewFeedLogic+ refreshFeed: (query: ViewFeedQuery) => {+ query: ViewFeedQuery+ } // viewFeedLogic+ sourceRefreshed: (+ key: string,+ generation: number,+ page: null | import('./viewFeed').ViewSourcePage) => {- views: ViewItemsPage | null- payload?: void+ generation: number+ key: string+ page: null | import('./viewFeed').ViewSourcePage+ } // viewFeedLogic+ loadMoreViews: () => {+ value: true}- receiveViews: (page: ViewItemsPage) => {- page: ViewItemsPage+ loadViews: () => {+ value: true+ }+ setFeedSearch: (search: string) => {+ search: string}setSearch: (search: string) => {search: string}+ setShownQuery: (query: ViewFeedQuery) => {+ query: ViewFeedQuery+ }setTypeFilter: (typeFilter: ViewTypeFilter) => {typeFilter: ViewTypeFilter}@@ -55,7 +75,21 @@ export interface viewsLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface viewsLogicMeta {__keaTypeGenInternalSelectorTypes: {- visibleViews: (views: ViewItemsPage | null, typeFilter: ViewTypeFilter) => ViewItem[]+ feedQuery: (typeFilter: ViewTypeFilter, feedSearch: string) => ViewFeedQuery+ currentFeed: (+ sources: Record<string, ViewSourceState>,+ spaceNames: Record<string, string>,+ currentTeamId: number | null,+ feedQuery: ViewFeedQuery+ ) => ViewFeed+ feed: (+ currentFeed: ViewFeed,+ sources: Record<string, ViewSourceState>,+ spaceNames: Record<string, string>,+ currentTeamId: number | null,+ shownQuery: ViewFeedQuery | null+ ) => ViewFeed+ feedStale: (currentFeed: ViewFeed, feed: ViewFeed) => boolean}}@@ -63,70 +97,127 @@ export type viewsLogicType = MakeLogicType<viewsLogicValues, viewsLogicActions,export const viewsLogic = kea<viewsLogicType>([path(['scenes', 'views', 'viewsLogic']),- connect(() => ({ values: [featureFlagLogic, ['featureFlags'], teamLogic, ['currentTeamId']] })),+ connect(() => ({+ values: [+ featureFlagLogic,+ ['featureFlags'],+ teamLogic,+ ['currentTeamId'],+ viewFeedLogic,+ ['sources', 'spaceNames'],+ ],+ actions: [viewFeedLogic, ['ensureFeed', 'refreshFeed', 'sourceRefreshed']],+ })),actions({- receiveViews: (page: ViewItemsPage) => ({ page }),setSearch: (search: string) => ({ search }),+ setFeedSearch: (search: string) => ({ search }),setTypeFilter: (typeFilter: ViewTypeFilter) => ({ typeFilter }),+ setShownQuery: (query: ViewFeedQuery) => ({ query }),+ loadViews: true,+ loadMoreViews: true,}),reducers({search: ['', { setSearch: (_, { search }) => search }],+ feedSearch: ['', { setFeedSearch: (_, { search }) => search }],typeFilter: ['all' as ViewTypeFilter, { setTypeFilter: (_, { typeFilter }) => typeFilter }],+ shownQuery: [null as ViewFeedQuery | null, { setShownQuery: (_, { query }) => query }],}),- loaders(({ values, actions }) => ({- views: [- null as ViewItemsPage | null,- {- loadViews: async (_: void, breakpoint) => {- await breakpoint(250)- if (!values.currentTeamId) {- return values.views- }- 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 values.currentTeamId === teamId && values.search === search ? page : values.views- },+ selectors({+ feedQuery: [+ (s) => [s.typeFilter, s.feedSearch],+ (typeFilter: ViewTypeFilter, feedSearch: string): ViewFeedQuery => ({+ type: typeFilter,+ search: feedSearch.trim(),+ }),+ ],+ currentFeed: [+ (s) => [s.sources, s.spaceNames, s.currentTeamId, s.feedQuery],+ (+ sources: Record<string, ViewSourceState>,+ spaceNames: Record<string, string>,+ currentTeamId: number | null,+ feedQuery: ViewFeedQuery+ ): ViewFeed => selectViewFeed(sources, spaceNames, currentTeamId, feedQuery),+ ],+ feed: [+ (s) => [s.currentFeed, s.sources, s.spaceNames, s.currentTeamId, s.shownQuery],+ (+ currentFeed: ViewFeed,+ sources: Record<string, ViewSourceState>,+ spaceNames: Record<string, string>,+ currentTeamId: number | null,+ shownQuery: ViewFeedQuery | null+ ): ViewFeed => {+ if (currentFeed.initialized || !shownQuery) {+ return currentFeed+ }+ const shownFeed = selectViewFeed(sources, spaceNames, currentTeamId, shownQuery)+ return shownFeed.initialized ? { ...shownFeed, loading: true, hasMore: false } : currentFeed},],- })),- reducers({- views: {- receiveViews: (_, { page }) => page,- },- loadFailed: [false, { loadViews: () => false, loadViewsFailure: () => true }],- }),- selectors({- visibleViews: [- (s) => [s.views, s.typeFilter],- (views: ViewItemsPage | null, typeFilter: ViewTypeFilter): ViewItem[] =>- filterViews(views?.items ?? [], typeFilter),+ feedStale: [+ (s) => [s.currentFeed, s.feed],+ (currentFeed: ViewFeed, feed: ViewFeed): boolean => !currentFeed.initialized && feed.initialized,],}),- listeners(({ actions, values }) => ({- [featureFlagLogic.actionTypes.setFeatureFlags]: () => {- // Flags can arrive after urlToAction ran, so a visit that skipped the load must load now.- if (- values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] &&- !values.views &&- !values.viewsLoading &&- removeProjectIdIfPresent(router.values.location.pathname) === urls.views()- ) {- actions.loadViews()+ listeners(({ actions, values, cache }) => {+ const syncShownQuery = (): void => {+ if (values.currentFeed.initialized) {+ if (values.shownQuery !== values.feedQuery) {+ actions.setShownQuery(values.feedQuery)+ }+ if (cache.visitStartedAt !== undefined) {+ posthog.capture('views list loaded', {+ duration_ms: Math.round(performance.now() - cache.visitStartedAt),+ cached: cache.visitCached,+ view_count: values.currentFeed.items.length,+ has_more: values.currentFeed.hasMore,+ })+ cache.visitStartedAt = undefined+ }}- },- setSearch: () => actions.loadViews(),- setTypeFilter: ({ typeFilter }) => {- // pinned: analytics event name and property. Renaming them breaks dashboards.- posthog.capture('views list filtered', { type: typeFilter })- },- })),+ }+ return {+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {+ // Flags can arrive after urlToAction ran, so a visit that skipped the load must load now.+ if (+ values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] &&+ cache.visitStartedAt === undefined &&+ !values.currentFeed.initialized &&+ !values.currentFeed.loading &&+ removeProjectIdIfPresent(router.values.location.pathname) === urls.views()+ ) {+ actions.loadViews()+ }+ },+ loadViews: () => {+ cache.visitStartedAt = performance.now()+ cache.visitCached = values.currentFeed.initialized+ actions.refreshFeed(values.feedQuery)+ syncShownQuery()+ },+ loadMoreViews: () => {+ actions.ensureFeed(values.feedQuery, values.feed.items.length + VIEWS_PREFETCH_COUNT)+ },+ setSearch: async ({ search }, breakpoint) => {+ if (search.trim() !== values.feedSearch.trim()) {+ await breakpoint(search.trim() ? 200 : 0)+ }+ actions.setFeedSearch(search)+ },+ setFeedSearch: () => {+ actions.ensureFeed(values.feedQuery, VIEWS_PREFETCH_COUNT)+ syncShownQuery()+ },+ setTypeFilter: ({ typeFilter }) => {+ // pinned: analytics event name and property. Renaming them breaks dashboards.+ posthog.capture('views list filtered', { type: typeFilter })+ actions.ensureFeed(values.feedQuery, VIEWS_PREFETCH_COUNT)+ syncShownQuery()+ },+ sourceRefreshed: () => syncShownQuery(),+ }+ }),urlToAction(({ actions, values }) => ({[urls.views()]: () => {// The Views scene renders nothing without the flag, so it must not load anything either.diff --git a/frontend/src/scenes/views/viewsUtils.test.ts b/frontend/src/scenes/views/viewsUtils.test.tsindex d6206bde57df..53a636201be3 100644--- a/frontend/src/scenes/views/viewsUtils.test.ts+++ b/frontend/src/scenes/views/viewsUtils.test.ts@@ -1,8 +1,6 @@import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'-import type { DashboardBasicApi } from 'products/dashboards/frontend/generated/api.schemas'-import type { NotebookMinimalApi } from 'products/notebooks/frontend/generated/api.schemas'-import { ViewItem, filterViews, mergeViews, newCanvasSpaceIdForPath } from './viewsUtils'+import { newCanvasSpaceIdForPath } from './viewsUtils'const canvas = (overrides: Partial<CanvasApi>): CanvasApi =>({@@ -14,64 +12,7 @@ const canvas = (overrides: Partial<CanvasApi>): CanvasApi =>...overrides,}) as CanvasApi-const notebook = (overrides: Partial<NotebookMinimalApi>): NotebookMinimalApi =>- ({- short_id: 'n',- title: 'Notebook',- deleted: false,- last_modified_at: '2026-09-01T00:00:00Z',- ...overrides,- }) as NotebookMinimalApi--const dashboard = (overrides: Partial<DashboardBasicApi>): DashboardBasicApi =>- ({- id: 1,- name: 'Dashboard',- deleted: false,- last_viewed_at: null,- created_at: '2026-09-01T00:00:00Z',- ...overrides,- }) as DashboardBasicApi--const summary = (items: ViewItem[]): string[] => items.map((item) => `${item.type}:${item.id}`)-describe('viewsUtils', () => {- it('merges every type into one list, most recent first, and leaves out unsupported canvases and deleted views', () => {- const items = mergeViews({- canvases: [- canvas({ id: 'grid', kind: 'grid', updated_at: '2026-09-20T00:00:00Z' }),- canvas({ id: 'widget', kind: 'component', updated_at: '2026-09-29T00:00:00Z' }),- canvas({ id: 'board', kind: 'freeform', updated_at: '2026-09-05T00:00:00Z' }),- ],- notebooks: [- notebook({ short_id: 'notes', last_modified_at: '2026-09-25T00:00:00Z' }),- notebook({ short_id: 'gone', deleted: true, last_modified_at: '2026-09-28T00:00:00Z' }),- ],- dashboards: [- dashboard({ id: 7, last_viewed_at: '2026-09-10T00:00:00Z', created_at: '2026-08-01T00:00:00Z' }),- dashboard({ id: 8, last_viewed_at: null, created_at: '2026-09-15T00:00:00Z' }),- ],- spaceNames: {},- })-- expect(summary(items)).toEqual(['notebook:notes', 'dashboard:8', 'dashboard:7', 'canvas:board'])- expect(filterViews(items, 'dashboard').map((item) => item.timestampLabel)).toEqual(['Created', 'Viewed'])- })-- it('names the space a canvas belongs to, and leaves it out when the space is unknown', () => {- const items = mergeViews({- canvases: [- canvas({ id: 'known', channel: 'space-1', updated_at: '2026-09-02T00:00:00Z' }),- canvas({ id: 'unknown', channel: 'space-2' }),- ],- notebooks: [],- dashboards: [],- spaceNames: { 'space-1': 'growth' },- })-- expect(items.map((item) => item.spaceName)).toEqual(['growth', null])- })-test.each([['a space page', '/spaces/space-3', 'space-3'],['a canvas page', '/canvases/board', 'space-1'],diff --git a/frontend/src/scenes/views/viewsUtils.ts b/frontend/src/scenes/views/viewsUtils.tsindex a8fe70215688..71e69cffe0f6 100644--- a/frontend/src/scenes/views/viewsUtils.ts+++ b/frontend/src/scenes/views/viewsUtils.ts@@ -43,7 +43,6 @@ export const VIEW_TYPE_INFO = Object.fromEntries(VIEW_TYPES.map((info) => [info.>// Component canvases are widgets that grids place, not views a person opens.-export const LISTED_CANVAS_KINDS = ['freeform'] as constexport const LISTED_CANVAS_KIND = 'freeform'export interface ViewItem {@@ -109,30 +108,6 @@ export function dashboardToView(dashboard: DashboardBasicApi): ViewItem {}}-export interface ViewSources {- canvases: CanvasApi[]- notebooks: NotebookMinimalApi[]- dashboards: DashboardBasicApi[]- spaceNames: Record<string, string>-}--/** Every view in one list, most recent first. */-export function mergeViews({ canvases, notebooks, dashboards, spaceNames }: ViewSources): ViewItem[] {- const items = [- ...canvases- .filter((canvas) => (LISTED_CANVAS_KINDS as readonly string[]).includes(canvas.kind))- .map((canvas) => canvasToView(canvas, spaceNames)),- ...notebooks.filter((notebook) => !notebook.deleted).map(notebookToView),- ...dashboards.filter((dashboard) => !dashboard.deleted).map(dashboardToView),- ]- const time = (item: ViewItem): number => (item.timestamp ? new Date(item.timestamp).getTime() : 0)- return items.sort((first, second) => time(second) - time(first) || first.name.localeCompare(second.name))-}--export function filterViews(items: ViewItem[], filter: ViewTypeFilter): ViewItem[] {- return filter === 'all' ? items : items.filter((item) => item.type === filter)-}-/*** The space a new canvas defaults to from the page the person is on: the open space, or the open* canvas's space. Null when the page names no space, so the start page falls back to the personal space.