: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
feat(views): add an ordered views feed with a shared cache (#111123)
Shy Alter7d7e20a4c4ef
diff --git a/frontend/src/scenes/views/viewFeed.ts b/frontend/src/scenes/views/viewFeed.tsnew file mode 100644index 000000000000..fd32519490c3--- /dev/null+++ b/frontend/src/scenes/views/viewFeed.ts@@ -0,0 +1,159 @@+import { canvasesList } from 'products/canvas/frontend/generated/api'+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 {+ LISTED_CANVAS_KIND,+ VIEW_TYPES,+ ViewItem,+ ViewType,+ ViewTypeFilter,+ canvasToView,+ dashboardToView,+ notebookToView,+} from './viewsUtils'++export const VIEW_FEED_PAGE_SIZE = 50++export interface ViewFeedQuery {+ type: ViewTypeFilter+ search: string+}++export interface ViewSourcePage {+ items: ViewItem[]+ fetched: number+ hasMore: boolean+}++export interface ViewSourceState {+ projectId: string+ search: string+ type: ViewType+ items: ViewItem[]+ offset: number+ hasMore: boolean+ initialized: boolean+ refreshing: boolean+ loading: boolean+ failed: boolean+ generation: number+}++export interface ViewFeed {+ items: ViewItem[]+ initialized: boolean+ loading: boolean+ hasMore: boolean+ failedTypes: ViewType[]+ loadFailed: boolean+}++export function viewFeedTypes(query: ViewFeedQuery): ViewType[] {+ return query.type === 'all' ? VIEW_TYPES.map((info) => info.type) : [query.type]+}++export function viewSourceKey(projectId: string, search: string, type: ViewType): string {+ return JSON.stringify([projectId, search.trim(), type])+}++export async function fetchViewSourcePage(+ projectId: string,+ type: ViewType,+ search: string,+ offset: number+): Promise<ViewSourcePage> {+ const limit = VIEW_FEED_PAGE_SIZE+ const query = search.trim() || undefined+ if (type === 'canvas') {+ const page = await canvasesList(projectId, {+ kind: LISTED_CANVAS_KIND,+ search: query,+ ordering: '-updated_at',+ limit,+ offset,+ })+ return {+ items: page.results.map((canvas) => canvasToView(canvas, {})),+ fetched: page.results.length,+ hasMore: !!page.next && page.results.length > 0,+ }+ }+ if (type === 'notebook') {+ // The notebooks endpoint filters on `search`, but its schema does not declare the parameter.+ const params: NotebooksListParams & { search?: string } = { limit, offset, search: query }+ const page = await notebooksList(projectId, params)+ return {+ items: page.results.filter((notebook) => !notebook.deleted).map(notebookToView),+ fetched: page.results.length,+ hasMore: !!page.next && page.results.length > 0,+ }+ }+ const page = await dashboardsList(projectId, { search: query, ordering: '-last_viewed_at', limit, offset })+ return {+ items: page.results.filter((dashboard) => !dashboard.deleted).map(dashboardToView),+ fetched: page.results.length,+ hasMore: !!page.next && page.results.length > 0,+ }+}++export function viewTime(item: ViewItem): number {+ return item.timestamp ? new Date(item.timestamp).getTime() : 0+}++export function mergeViewSources(sources: (ViewSourceState | undefined)[]): {+ items: ViewItem[]+ blocking: ViewSourceState[]+} {+ const states = sources.map(+ (source) => source ?? ({ items: [], hasMore: true, initialized: false } as unknown as ViewSourceState)+ )+ const positions = states.map(() => 0)+ const items: ViewItem[] = []+ for (;;) {+ const blocking = states.filter(+ (state, index) => positions[index] >= state.items.length && (state.hasMore || !state.initialized)+ )+ if (blocking.length) {+ return { items, blocking: blocking.filter((state) => sources.includes(state)) }+ }+ let best = -1+ for (let index = 0; index < states.length; index++) {+ if (+ positions[index] < states[index].items.length &&+ (best === -1 ||+ viewTime(states[index].items[positions[index]]) > viewTime(states[best].items[positions[best]]))+ ) {+ best = index+ }+ }+ if (best === -1) {+ return { items, blocking: [] }+ }+ items.push(states[best].items[positions[best]++])+ }+}++export function viewFeedFromSources(+ sources: (ViewSourceState | undefined)[],+ spaceNames: Record<string, string>+): ViewFeed {+ const { items, blocking } = mergeViewSources(sources)+ const initialized = sources.every((source) => source?.initialized)+ const failed = sources.filter((source): source is ViewSourceState => !!source?.failed)+ return {+ items: initialized+ ? items.map((item) =>+ item.spaceId && !item.spaceName && spaceNames[item.spaceId]+ ? { ...item, spaceName: spaceNames[item.spaceId] }+ : item+ )+ : [],+ initialized,+ loading: sources.some((source) => !source || source.loading || source.refreshing),+ hasMore: blocking.length > 0,+ failedTypes: failed.map((source) => source.type),+ loadFailed: initialized && failed.length === sources.length && items.length === 0,+ }+}diff --git a/frontend/src/scenes/views/viewFeedLogic.test.ts b/frontend/src/scenes/views/viewFeedLogic.test.tsnew file mode 100644index 000000000000..884dc1b3b342--- /dev/null+++ b/frontend/src/scenes/views/viewFeedLogic.test.ts@@ -0,0 +1,115 @@+import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { ViewFeedQuery } from './viewFeed'+import { resetViewFeedSnapshot, selectViewFeed, viewFeedLogic } from './viewFeedLogic'++const ALL: ViewFeedQuery = { type: 'all', search: '' }++const at = (day: number): string => `2026-09-${String(day).padStart(2, '0')}T00:00:00Z`++describe('viewFeedLogic', () => {+ let requests: Record<string, string[]>++ beforeEach(() => {+ resetViewFeedSnapshot()+ requests = { canvases: [], notebooks: [], dashboards: [] }+ const record = (name: string, request: Request): URLSearchParams => {+ const params = new URL(request.url).searchParams+ requests[name].push(`${params.get('offset')}:${params.get('ordering') ?? ''}`)+ return params+ }+ useMocks({+ get: {+ '/api/projects/:team_id/task_channels/': [{ id: 'space-1', name: 'growth' }],+ '/api/projects/:team_id/canvases/': ({ request }) => {+ record('canvases', request)+ return {+ results: [{ id: 'c7', name: 'C', kind: 'freeform', channel: 'space-1', updated_at: at(7) }],+ next: null,+ }+ },+ '/api/projects/:team_id/notebooks/': ({ request }) => {+ record('notebooks', request)+ return {+ results: [+ { short_id: 'n9', title: 'N', deleted: false, last_modified_at: at(9) },+ { short_id: 'n1', title: 'N', deleted: false, last_modified_at: at(1) },+ ],+ next: null,+ }+ },+ '/api/projects/:team_id/dashboards/': ({ request }) => {+ const params = record('dashboards', request)+ return params.get('offset') === '0'+ ? {+ results: [+ { id: 10, name: 'D', last_viewed_at: at(10), created_at: at(1) },+ { id: 8, name: 'D', last_viewed_at: null, created_at: at(8) },+ ],+ next: '?offset=2',+ }+ : { results: [{ id: 3, name: 'D', last_viewed_at: at(3), created_at: at(1) }], next: null }+ },+ },+ })+ initKeaTests()+ })++ const feed = (logic: ReturnType<typeof viewFeedLogic.build>): string[] =>+ selectViewFeed(logic.values.sources, logic.values.spaceNames, teamLogic.values.currentTeamId, ALL).items.map(+ (item) => `${item.type}:${item.id}`+ )++ it('shows only rows whose order is final, and loads more from the type that holds them back', async () => {+ const logic = viewFeedLogic()+ logic.mount()++ await expectLogic(logic, () => logic.actions.refreshFeed(ALL)).toFinishAllListeners()+ expect(feed(logic)).toEqual(['dashboard:10', 'notebook:n9', 'dashboard:8'])++ await expectLogic(logic, () => logic.actions.ensureFeed(ALL, 100)).toFinishAllListeners()+ expect(feed(logic)).toEqual([+ 'dashboard:10',+ 'notebook:n9',+ 'dashboard:8',+ 'canvas:c7',+ 'dashboard:3',+ 'notebook:n1',+ ])+ expect(requests).toEqual({+ canvases: ['0:-updated_at'],+ notebooks: ['0:'],+ dashboards: ['0:-last_viewed_at', '2:-last_viewed_at'],+ })+ const result = selectViewFeed(+ logic.values.sources,+ logic.values.spaceNames,+ teamLogic.values.currentTeamId,+ ALL+ )+ expect(result.hasMore).toBe(false)+ expect(result.items.find((item) => item.type === 'canvas')?.spaceName).toBe('growth')+ expect(result.items.filter((item) => item.type === 'dashboard').map((item) => item.timestampLabel)).toEqual([+ 'Viewed',+ 'Created',+ 'Viewed',+ ])+ })++ it('keeps the loaded list after a remount, so a revisit shows rows at once', async () => {+ const first = viewFeedLogic()+ first.mount()+ await expectLogic(first, () => first.actions.refreshFeed(ALL)).toFinishAllListeners()+ first.unmount()++ const second = viewFeedLogic()+ second.mount()++ expect(feed(second)).toEqual(['dashboard:10', 'notebook:n9', 'dashboard:8'])+ })+})diff --git a/frontend/src/scenes/views/viewFeedLogic.ts b/frontend/src/scenes/views/viewFeedLogic.tsnew file mode 100644index 000000000000..293a51e82d95--- /dev/null+++ b/frontend/src/scenes/views/viewFeedLogic.ts@@ -0,0 +1,321 @@+import { MakeLogicType, actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { spaceLabel } from '~/layout/today/todaySpacesLogic'++import { taskChannelsList } from 'products/tasks/frontend/generated/api'+import type { ChannelDTOApi } from 'products/tasks/frontend/generated/api.schemas'++import {+ ViewFeed,+ ViewFeedQuery,+ ViewSourcePage,+ ViewSourceState,+ fetchViewSourcePage,+ mergeViewSources,+ viewFeedFromSources,+ viewFeedTypes,+ viewSourceKey,+} from './viewFeed'+import { ViewType } from './viewsUtils'++const MAX_SEARCH_SOURCES = 30++interface ViewFeedSnapshot {+ sources: Record<string, ViewSourceState>+ spaceNames: Record<string, string>+}++let snapshot: ViewFeedSnapshot | null = null++export function resetViewFeedSnapshot(): void {+ snapshot = null+}++function settledSources(sources: Record<string, ViewSourceState>): Record<string, ViewSourceState> {+ return Object.fromEntries(+ Object.entries(sources)+ .filter(([, source]) => source.initialized)+ .map(([key, source]) => [key, { ...source, refreshing: false, loading: false }])+ )+}++function withoutOldSearches(sources: Record<string, ViewSourceState>): Record<string, ViewSourceState> {+ const searchKeys = Object.keys(sources).filter((key) => sources[key].search)+ const dropped = new Set(searchKeys.slice(0, Math.max(0, searchKeys.length - MAX_SEARCH_SOURCES)))+ return dropped.size ? Object.fromEntries(Object.entries(sources).filter(([key]) => !dropped.has(key))) : sources+}++export function selectViewFeed(+ sources: Record<string, ViewSourceState>,+ spaceNames: Record<string, string>,+ projectId: number | null,+ query: ViewFeedQuery+): ViewFeed {+ return viewFeedFromSources(+ viewFeedTypes(query).map((type) =>+ projectId ? sources[viewSourceKey(String(projectId), query.search, type)] : undefined+ ),+ spaceNames+ )+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface viewFeedLogicValues {+ currentTeamId: number | null // teamLogic+ sources: Record<string, ViewSourceState>+ spaceNames: Record<string, string>+ spaceNamesLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface viewFeedLogicActions {+ ensureFeed: (+ query: ViewFeedQuery,+ count: number+ ) => {+ count: number+ query: ViewFeedQuery+ }+ loadSourcePage: (key: string) => {+ key: string+ }+ loadSpaceNames: () => any+ loadSpaceNamesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSpaceNamesSuccess: (+ spaceNames: Record<string, string>,+ payload?: any+ ) => {+ spaceNames: Record<string, string>+ payload?: any+ }+ refreshFeed: (query: ViewFeedQuery) => {+ query: ViewFeedQuery+ }+ refreshSource: (+ key: string,+ projectId: string,+ search: string,+ type: ViewType+ ) => {+ key: string+ projectId: string+ search: string+ type: ViewType+ }+ restoreSnapshot: (snapshot: ViewFeedSnapshot) => {+ snapshot: ViewFeedSnapshot+ }+ sourcePageLoaded: (+ key: string,+ generation: number,+ offset: number,+ page: ViewSourcePage | null+ ) => {+ generation: number+ key: string+ offset: number+ page: ViewSourcePage | null+ }+ sourceRefreshed: (+ key: string,+ generation: number,+ page: ViewSourcePage | null+ ) => {+ generation: number+ key: string+ page: ViewSourcePage | null+ }+}++export type viewFeedLogicType = MakeLogicType<viewFeedLogicValues, viewFeedLogicActions>++export const viewFeedLogic = kea<viewFeedLogicType>([+ path(['scenes', 'views', 'viewFeedLogic']),+ connect(() => ({ values: [teamLogic, ['currentTeamId']] })),+ actions({+ ensureFeed: (query: ViewFeedQuery, count: number) => ({ query, count }),+ refreshFeed: (query: ViewFeedQuery) => ({ query }),+ refreshSource: (key: string, projectId: string, search: string, type: ViewType) => ({+ key,+ projectId,+ search,+ type,+ }),+ sourceRefreshed: (key: string, generation: number, page: ViewSourcePage | null) => ({+ key,+ generation,+ page,+ }),+ loadSourcePage: (key: string) => ({ key }),+ sourcePageLoaded: (key: string, generation: number, offset: number, page: ViewSourcePage | null) => ({+ key,+ generation,+ offset,+ page,+ }),+ restoreSnapshot: (snapshot: ViewFeedSnapshot) => ({ snapshot }),+ }),+ loaders(({ values }) => ({+ spaceNames: [+ {} as Record<string, string>,+ {+ loadSpaceNames: async () => {+ if (!values.currentTeamId) {+ return values.spaceNames+ }+ try {+ const response = await taskChannelsList(String(values.currentTeamId))+ // 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)]))+ } catch {+ return values.spaceNames+ }+ },+ },+ ],+ })),+ reducers({+ spaceNames: {+ restoreSnapshot: (state, { snapshot }) => (Object.keys(state).length ? state : snapshot.spaceNames),+ },+ sources: [+ {} as Record<string, ViewSourceState>,+ {+ restoreSnapshot: (state, { snapshot }) => ({ ...snapshot.sources, ...state }),+ refreshSource: (state, { key, projectId, search, type }) => {+ const { [key]: current, ...rest } = state+ return withoutOldSearches({+ ...rest,+ [key]: current+ ? { ...current, refreshing: true, generation: current.generation + 1 }+ : {+ projectId,+ search,+ type,+ items: [],+ offset: 0,+ hasMore: true,+ initialized: false,+ refreshing: true,+ loading: false,+ failed: false,+ generation: 1,+ },+ })+ },+ sourceRefreshed: (state, { key, generation, page }) => {+ const current = state[key]+ if (!current || current.generation !== generation) {+ return state+ }+ const next: ViewSourceState = page+ ? {+ ...current,+ items: page.items,+ offset: page.fetched,+ hasMore: page.hasMore,+ initialized: true,+ refreshing: false,+ loading: false,+ failed: false,+ }+ : current.initialized+ ? { ...current, refreshing: false, failed: true }+ : { ...current, hasMore: false, initialized: true, refreshing: false, failed: true }+ return { ...state, [key]: next }+ },+ loadSourcePage: (state, { key }) =>+ state[key] ? { ...state, [key]: { ...state[key], loading: true } } : state,+ sourcePageLoaded: (state, { key, generation, offset, page }) => {+ const current = state[key]+ if (!current || current.generation !== generation || current.offset !== offset) {+ return state+ }+ if (!page) {+ return { ...state, [key]: { ...current, loading: false, hasMore: false, failed: true } }+ }+ const known = new Set(current.items.map((item) => item.id))+ return {+ ...state,+ [key]: {+ ...current,+ items: [...current.items, ...page.items.filter((item) => !known.has(item.id))],+ offset: current.offset + page.fetched,+ hasMore: page.hasMore,+ loading: false,+ },+ }+ },+ },+ ],+ }),+ listeners(({ actions, values }) => ({+ refreshFeed: ({ query }) => {+ if (!values.currentTeamId) {+ return+ }+ const projectId = String(values.currentTeamId)+ for (const type of viewFeedTypes(query)) {+ const key = viewSourceKey(projectId, query.search, type)+ if (!values.sources[key]?.refreshing) {+ actions.refreshSource(key, projectId, query.search.trim(), type)+ }+ }+ },+ ensureFeed: ({ query, count }) => {+ if (!values.currentTeamId) {+ return+ }+ const projectId = String(values.currentTeamId)+ const keys = viewFeedTypes(query).map((type) => viewSourceKey(projectId, query.search, type))+ if (keys.some((key) => !values.sources[key])) {+ actions.refreshFeed(query)+ return+ }+ const { items, blocking } = mergeViewSources(keys.map((key) => values.sources[key]))+ if (items.length >= count) {+ return+ }+ for (const source of blocking) {+ if (source.initialized && !source.loading && !source.refreshing) {+ actions.loadSourcePage(viewSourceKey(source.projectId, source.search, source.type))+ }+ }+ },+ refreshSource: async ({ key, projectId, search, type }) => {+ const generation = values.sources[key].generation+ const page = await fetchViewSourcePage(projectId, type, search, 0).catch(() => null)+ actions.sourceRefreshed(key, generation, page)+ },+ loadSourcePage: async ({ key }) => {+ const source = values.sources[key]+ if (!source) {+ return+ }+ const { generation, offset } = source+ const page = await fetchViewSourcePage(source.projectId, source.type, source.search, offset).catch(+ () => null+ )+ actions.sourcePageLoaded(key, generation, offset, page)+ },+ })),+ afterMount(({ actions }) => {+ if (snapshot) {+ actions.restoreSnapshot(snapshot)+ }+ actions.loadSpaceNames()+ }),+ beforeUnmount(({ values }) => {+ snapshot = { sources: settledSources(values.sources), spaceNames: values.spaceNames }+ }),+])diff --git a/frontend/src/scenes/views/viewsUtils.ts b/frontend/src/scenes/views/viewsUtils.tsindex 5ba297a95199..a8fe70215688 100644--- a/frontend/src/scenes/views/viewsUtils.ts+++ b/frontend/src/scenes/views/viewsUtils.ts@@ -44,6 +44,7 @@ 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 const+export const LISTED_CANVAS_KIND = 'freeform'export interface ViewItem {type: ViewType