: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(actions): lazy load actions (#85698)
Matt Puab7654436f8df
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.tsindex 2394a72062de..d114be6714ee 100644--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts@@ -35,10 +35,16 @@ window.POSTHOG_APP_CONTEXT = {describe('taxonomicFilterLogic', () => {let logic: ReturnType<typeof taxonomicFilterLogic.build>+ let actionRequestCount: numberbeforeEach(() => {+ actionRequestCount = 0useMocks({get: {+ '/api/projects/:team/actions/': () => {+ actionRequestCount+++ return [200, { results: [], count: 0 }]+ },'/api/projects/:team/event_definitions': ({ request }) => {const search = new URL(request.url).searchParams.get('search')const results = search@@ -69,7 +75,6 @@ describe('taxonomicFilterLogic', () => {})initKeaTests()featureFlagLogic.mount()- actionsModel.mount()groupsModel.mount()const logicProps: TaxonomicFilterLogicProps = {@@ -102,6 +107,25 @@ describe('taxonomicFilterLogic', () => {).toBeFalsy()})+ it('loads actions when a taxonomic filter mounts', async () => {+ await expectLogic(actionsModel).toDispatchActions(['loadActionsSuccess'])+ expect(actionRequestCount).toBe(1)+ })++ it('does not request actions for a filter without the Actions group', () => {+ const actionRequestsBeforeMount = actionRequestCount+ const noActionsLogic = taxonomicFilterLogic({+ taxonomicFilterLogicKey: 'noActions',+ taxonomicGroupTypes: [TaxonomicFilterGroupType.EventProperties, TaxonomicFilterGroupType.PersonProperties],+ })+ noActionsLogic.mount()++ expect(actionsModel({ shouldLoad: false }).isMounted()).toBe(true)+ expect(actionRequestCount).toBe(actionRequestsBeforeMount)++ noActionsLogic.unmount()+ })+it('keeps infiniteListCounts in sync', async () => {await expectLogic(logic).toMatchValues({diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsxindex 0c592feee75e..68e9730f48d1 100644--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx@@ -648,7 +648,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([props({} as TaxonomicFilterLogicProps),key((props) => `${props.taxonomicFilterLogicKey}`),path(['lib', 'components', 'TaxonomicFilter', 'taxonomicFilterLogic']),- connect(() => ({+ connect((props: TaxonomicFilterLogicProps) => ({values: [teamLogic,['currentTeamId', 'currentTeam'],@@ -668,6 +668,12 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([['primaryProperties'],],actions: [primaryEventPropertiesModel, ['ensureLoadedForEvents']],+ logic: [+ actionsModel({+ shouldLoad:+ !props.taxonomicGroupTypes || props.taxonomicGroupTypes.includes(TaxonomicFilterGroupType.Actions),+ }),+ ],})),actions(() => ({moveUp: true,diff --git a/frontend/src/models/actionsModel.test.ts b/frontend/src/models/actionsModel.test.tsnew file mode 100644index 000000000000..69be07c1cb64--- /dev/null+++ b/frontend/src/models/actionsModel.test.ts@@ -0,0 +1,38 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { actionsModel } from './actionsModel'++describe('actionsModel', () => {+ let requestCount: number+ let logic: ReturnType<typeof actionsModel.build>++ beforeEach(() => {+ requestCount = 0+ useMocks({+ get: {+ '/api/projects/:team/actions/': () => {+ requestCount+++ return [200, { results: [], count: 0 }]+ },+ },+ })+ initKeaTests()+ logic = actionsModel.build()+ })++ it('reuses actions after a consumer remounts', async () => {+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadActionsSuccess'])++ logic.unmount()+ expect(logic.isMounted()).toBe(true)++ logic.mount()+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(requestCount).toBe(1)+ })+})diff --git a/frontend/src/models/actionsModel.ts b/frontend/src/models/actionsModel.tsindex 252701040708..0310c0ca766c 100644--- a/frontend/src/models/actionsModel.ts+++ b/frontend/src/models/actionsModel.ts@@ -1,4 +1,4 @@-import { MakeLogicType, connect, events, kea, path, props, selectors } from 'kea'+import { MakeLogicType, connect, events, kea, key, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import api from 'lib/api'@@ -11,10 +11,11 @@ import type { TeamPublicType, TeamType } from '../types'export interface ActionsModelProps {params?: string+ shouldLoad?: boolean}export function findActionName(id: number): string | null {- return actionsModel.findMounted()?.values.actions.find((a) => a.id === id)?.name || null+ return actionsModel.findMounted({ shouldLoad: true })?.values.actions.find((a) => a.id === id)?.name || null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -29,6 +30,7 @@ export interface actionsModelValues {value: number}[]}[]+ actionsLoaded: booleanactionsLoading: booleanactionsSorted: ActionType[]pin: any@@ -37,7 +39,7 @@ export interface actionsModelValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface actionsModelActions {- loadActions: () => any+ loadActions: (force?: any) => anyloadActionsFailure: (error: string,errorObject?: any@@ -101,6 +103,7 @@ export interface actionsModelActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface actionsModelMeta {+ key: 'default' | 'skip-load'__keaTypeGenInternalSelectorTypes: {actionsGrouped: (actions: ActionType[]) => {label: string@@ -123,15 +126,20 @@ export type actionsModelType = MakeLogicType<export const actionsModel = kea<actionsModelType>([props({} as ActionsModelProps),- path(['models', 'actionsModel']),+ key((props) => (props.shouldLoad === false ? 'skip-load' : 'default')),+ path((key) => ['models', 'actionsModel', key]),connect(() => ({values: [teamLogic, ['currentTeam']],})),loaders(({ props, values, actions }) => ({actions: {__default: [] as ActionType[],- loadActions: async () => {+ loadActions: async (force = false, breakpoint) => {+ if (!force && values.actionsLoaded) {+ return values.actions+ }const response = await api.actions.list(props.params)+ breakpoint()return response.results ?? []},updateAction: (action: ActionType) => (values.actions || []).map((a) => (action.id === a.id ? action : a)),@@ -153,6 +161,14 @@ export const actionsModel = kea<actionsModelType>([},},})),+ reducers({+ actionsLoaded: [+ false,+ {+ loadActionsSuccess: () => true,+ },+ ],+ }),selectors(({ selectors }) => ({actionsGrouped: [() => [selectors.actions],@@ -179,10 +195,9 @@ export const actionsModel = kea<actionsModelType>([},],})),- events(({ values, actions }) => ({+ events(({ props, values, actions }) => ({afterMount: () => {- if (isAuthenticatedTeam(values.currentTeam)) {- // Don't load on shared insights/dashboards+ if (props.shouldLoad !== false && isAuthenticatedTeam(values.currentTeam)) {actions.loadActions()}},diff --git a/frontend/src/models/saveAsActionDialog.tsx b/frontend/src/models/saveAsActionDialog.tsxindex 42d99c75c98f..1bfadf0af8fe 100644--- a/frontend/src/models/saveAsActionDialog.tsx+++ b/frontend/src/models/saveAsActionDialog.tsx@@ -123,7 +123,7 @@ export function openSaveAsActionDialog({ suggestedName, step, createInFolder }:steps: [step],...(createInFolder ? { _create_in_folder: createInFolder } : {}),})- actionsModel.findMounted()?.actions.loadActions()+ actionsModel.findMounted({ shouldLoad: true })?.actions.loadActions(true)lemonToast.success(<>Action created. <Link to={urls.action(action.id)}>View action</Link>diff --git a/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx b/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsxindex f852d033fced..98993d5cfd5c 100644--- a/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx+++ b/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx@@ -1,7 +1,7 @@import './CohortField.scss'import clsx from 'clsx'-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { useEffect, useId, useRef } from 'react'import { DateFilter } from 'lib/components/DateFilter/DateFilter'@@ -31,6 +31,7 @@ import {} from 'scenes/cohorts/CohortFilters/types'import { determineFilterType } from 'scenes/cohorts/cohortUtils'+import { actionsModel } from '~/models/actionsModel'import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import {AnyCohortCriteriaType,@@ -160,6 +161,8 @@ export function CohortTaxonomicField({placeholder = 'Choose event',onChange: _onChange,}: CohortTaxonomicFieldProps): JSX.Element {+ const supportsActions = taxonomicGroupTypes.includes(TaxonomicFilterGroupType.Actions)+ useMountedLogic(actionsModel({ shouldLoad: supportsActions }))const { logic } = useCohortFieldLogic({fieldKey,criteria,diff --git a/frontend/src/scenes/max/maxLogic.test.ts b/frontend/src/scenes/max/maxLogic.test.tsindex 3b282fea780b..0f1db983c7bc 100644--- a/frontend/src/scenes/max/maxLogic.test.ts+++ b/frontend/src/scenes/max/maxLogic.test.ts@@ -27,11 +27,22 @@ import { MOCK_CONVERSATION, MOCK_CONVERSATION_ID, maxMocks } from './testUtils'describe('maxLogic', () => {let logic: ReturnType<typeof maxLogic.build>let threadLogic: ReturnType<typeof maxThreadLogic.build> | null = null+ let actionsRequestCount: numberbeforeEach(() => {localStorage.clear()sessionStorage.clear()- useMocks(maxMocks)+ actionsRequestCount = 0+ useMocks({+ ...maxMocks,+ get: {+ ...maxMocks.get,+ '/api/projects/:team/actions/': () => {+ actionsRequestCount+++ return [200, { results: [], count: 0 }]+ },+ },+ })initKeaTests()})@@ -56,6 +67,15 @@ describe('maxLogic', () => {})})+ it('does not load actions when Max mounts', async () => {+ logic = maxLogic({ panelId: 'test' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadConversationHistorySuccess'])++ expect(actionsRequestCount).toBe(0)+ })+it('sets the question when URL has hash param #panel=max:Foo', async () => {// Set up sidePanelStateLogic with the options before mounting maxLogicsidePanelStateLogic.mount()diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsxindex ded345bd44ef..33413a5884f3 100644--- a/frontend/src/scenes/max/maxLogic.tsx+++ b/frontend/src/scenes/max/maxLogic.tsx@@ -15,7 +15,6 @@ import { urls } from 'scenes/urls'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'-import { actionsModel } from '~/models/actionsModel'import { productUrls } from '~/products'import { AgentMode, RootAssistantMessage } from '~/queries/schema/schema-assistant-messages'import {@@ -27,7 +26,6 @@ import {SidePanelTab,} from '~/types'-import type { ActionType } from '../../types'import type { ToolRegistration } from './max-constants'import { PENDING_AI_PROMPT_KEY } from './max-storage-keys'import { maxContextLogic } from './maxContextLogic'@@ -159,7 +157,6 @@ function sceneTabId(panelId?: string, syncUrl?: boolean): string | null {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface maxLogicValues {- actions: ActionType[] // actionsModelconversationHistory: ConversationDetail[] // maxGlobalLogicconversationHistoryLoading: boolean // maxGlobalLogicdataProcessingAccepted: boolean // maxGlobalLogic@@ -382,9 +379,6 @@ export const maxLogic = kea<maxLogicType>(['conversationHistoryLoading','effectivePhaiView',],- // Actions are lazy-loaded. In order to display their names in the UI, we're loading them here.- actionsModel({ params: 'include_count=1' }),- ['actions'],tabUiStateLogic,['chatDraftFor'],],diff --git a/products/actions/frontend/logics/actionEditLogic.tsx b/products/actions/frontend/logics/actionEditLogic.tsxindex 9001371ca744..2c40679f7ab1 100644--- a/products/actions/frontend/logics/actionEditLogic.tsx+++ b/products/actions/frontend/logics/actionEditLogic.tsx@@ -72,7 +72,6 @@ export interface actionEditLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface actionEditLogicActions {- loadActions: () => any // actionsModelloadEventDefinitions: (url?: string | null | undefined) => {url: string | null} // eventDefinitionsTableLogic@@ -204,14 +203,7 @@ export const actionEditLogic = kea<actionEditLogicType>([props({} as ActionEditLogicProps),key((props) => `${props.id || 'new'}`),connect(() => ({- actions: [- actionsModel,- ['loadActions'],- eventDefinitionsTableLogic,- ['loadEventDefinitions'],- tagsModel,- ['loadTags'],- ],+ actions: [eventDefinitionsTableLogic, ['loadEventDefinitions'], tagsModel, ['loadTags']],})),actions({setAction: (action: Partial<ActionType>, options: SetActionProps = { merge: true }) => ({@@ -322,9 +314,8 @@ export const actionEditLogic = kea<actionEditLogicType>([logic?.actions.loadActionSuccess(action)}- // reload actions so they are immediately available throughout the appactions.loadEventDefinitions()- actions.loadActions()+ actionsModel.findMounted({ shouldLoad: true })?.actions.loadActions(true)actions.loadTags() // reload tags in case new tags are being savedreturn action},@@ -411,7 +402,7 @@ export const actionEditLogic = kea<actionEditLogicType>([actions.resetAction()deleteFromTree('action', String(actionId))router.actions.push(urls.actions())- actions.loadActions()+ actionsModel.findMounted({ shouldLoad: true })?.actions.loadActions(true)}})},