: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
perf(mcp-analytics): back off the activity poll when nobody uses the page (#124797)
Paul D'Ambra5064901f6619
diff --git a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.ts b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.tsindex 742933d169d4..aa9bafb0cf0a 100644--- a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.ts+++ b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.ts@@ -71,4 +71,41 @@ describe('mcpEarlyDataLogic', () => {expect(overviewMock.mock.calls[0][1]).toMatchObject(expectedParams)expect(logic.values.activityQuery.source).toMatchObject(expectedQuery)})++ const MINUTE = 60_000++ it.each([+ ['refreshes after one minute', [MINUTE], 1],+ ['waits two minutes after a refresh nobody reacted to', [3 * MINUTE - 1], 1],+ ['refreshes again once the doubled wait passes', [3 * MINUTE], 2],+ ['goes back to every minute after user input', [3 * MINUTE, 'input', MINUTE], 3],+ ['does not back off when the input came before the refresh', [MINUTE - 1, 'input', MINUTE + 1], 2],+ [+ 'does not push the refresh back while the user keeps moving',+ [3 * MINUTE, 'input', MINUTE / 2, 'input', MINUTE / 2],+ 3,+ ],+ ['never waits more than 30 minutes', [91 * MINUTE], 7],+ ] as [string, (number | 'input')[], number][])('%s', async (_label, timeline, expectedRefreshes) => {+ logic.unmount()+ jest.useFakeTimers()+ try {+ initKeaTests()+ logic = mcpEarlyDataLogic()+ logic.mount()+ overviewMock.mockClear()++ for (const step of timeline) {+ if (step === 'input') {+ window.dispatchEvent(new Event('keydown'))+ } else {+ jest.advanceTimersByTime(step)+ }+ }++ expect(overviewMock).toHaveBeenCalledTimes(expectedRefreshes)+ } finally {+ jest.useRealTimers()+ }+ })})diff --git a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.tsindex 22c76ebfa0d8..96a31748499c 100644--- a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts+++ b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts@@ -56,6 +56,10 @@ export const ACTIVITY_FILTERS: HogQLFilters = { dateRange: { date_from: '-30d' }// overview aggregates 30 days of property-reading queries server-side, and "within// a minute" is live enough.const REFRESH_INTERVAL_MS = 60000+// A tab left open with nobody looking still polls, so each refresh that sees no user input+// doubles the wait, up to this cap. Any input goes back to one minute.+const MAX_REFRESH_INTERVAL_MS = 30 * REFRESH_INTERVAL_MS+const USER_INPUT_EVENTS = ['pointermove', 'pointerdown', 'keydown', 'wheel'] as const// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpEarlyDataLogicValues {@@ -68,12 +72,15 @@ export interface mcpEarlyDataLogicValues {harnessRowsLoading: booleanhasFailureNotification: boolean | nullhasModelData: boolean+ inputSinceRefresh: booleanmodelRows: ModelRow[]modelRowsLoading: booleannextSteps: NextStep[]notificationsResolved: booleanoverview: MCPActivityOverviewApi | nulloverviewLoading: boolean+ refreshDelayMs: number+ refreshesWithoutInput: numberstats: EarlyStatssummary: ActivitySummarytopTools: EarlyToolRow[]@@ -149,12 +156,24 @@ export interface mcpEarlyDataLogicActions {overview: MCPActivityOverviewApi | nullpayload?: void}+ noteUserInput: () => {+ value: true+ }refreshAll: () => {value: true}refreshFilteredActivity: () => {value: true}+ refreshOnSchedule: (hadInput: boolean) => {+ hadInput: boolean+ }+ resetRefreshBackoff: () => {+ value: true+ }+ scheduleRefresh: () => {+ value: true+ }setActivityQuery: (query: DataTableNode) => {query: DataTableNode}@@ -172,6 +191,7 @@ export interface mcpEarlyDataLogicMeta {hasFailureNotification: (notificationsResolved: boolean, notifications: HogFunctionType[]) => boolean | nullnextSteps: (stats: EarlyStats, hasFailureNotification: boolean | null) => NextStep[]hasModelData: (modelRows: ModelRow[]) => boolean+ refreshDelayMs: (refreshesWithoutInput: number) => number}}@@ -209,8 +229,12 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([],})),actions({+ noteUserInput: true,refreshAll: true,refreshFilteredActivity: true,+ refreshOnSchedule: (hadInput: boolean) => ({ hadInput }),+ resetRefreshBackoff: true,+ scheduleRefresh: true,setActivityQuery: (query: DataTableNode) => ({ query }),showFailedCallsOnly: true,}),@@ -218,6 +242,14 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([activityQuery: [DEFAULT_MCP_ACTIVITY_QUERY, { setActivityQuery: (_, { query }) => query }],// The list defaults to empty before its first load, which would read as "no alert set up".notificationsResolved: [false, { loadNotificationsSuccess: () => true }],+ inputSinceRefresh: [false, { noteUserInput: () => true, refreshOnSchedule: () => false }],+ refreshesWithoutInput: [+ 0,+ {+ refreshOnSchedule: (count, { hadInput }) => (hadInput ? 0 : count + 1),+ resetRefreshBackoff: () => 0,+ },+ ],}),loaders(({ values }) => ({overview: {@@ -316,8 +348,32 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([(s) => [s.modelRows],(modelRows: ModelRow[]): boolean => modelRows.some((row) => row.total_calls > 0),],+ refreshDelayMs: [+ (s) => [s.refreshesWithoutInput],+ (refreshesWithoutInput: number): number =>+ Math.min(REFRESH_INTERVAL_MS * 2 ** refreshesWithoutInput, MAX_REFRESH_INTERVAL_MS),+ ],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({+ scheduleRefresh: () => {+ cache.disposables.add(() => {+ const id = window.setTimeout(+ () => actions.refreshOnSchedule(values.inputSinceRefresh),+ values.refreshDelayMs+ )+ return () => clearTimeout(id)+ }, 'refresh')+ },+ refreshOnSchedule: () => {+ actions.refreshAll()+ actions.scheduleRefresh()+ },+ noteUserInput: () => {+ if (values.refreshesWithoutInput > 0) {+ actions.resetRefreshBackoff()+ }+ },+ resetRefreshBackoff: () => actions.scheduleRefresh(),refreshAll: () => {actions.loadSignals()actions.loadNotifications()@@ -337,7 +393,7 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([actions.setActivityQuery(withFailedCallsOnly(values.activityQuery))},})),- afterMount(({ actions, cache }) => {+ afterMount(({ actions, values, cache }) => {actions.setActivityQuery(withSharedFilters(DEFAULT_MCP_ACTIVITY_QUERY, mcpAnalyticsFiltersLogic.values.queryFilters))@@ -345,9 +401,15 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([actions.loadNotifications()actions.loadHarnessRows()actions.loadModelRows()+ actions.scheduleRefresh()cache.disposables.add(() => {- const id = window.setInterval(() => actions.refreshAll(), REFRESH_INTERVAL_MS)- return () => clearInterval(id)- }, 'refresh')+ const onUserInput = (): void => {+ if (!values.inputSinceRefresh) {+ actions.noteUserInput()+ }+ }+ USER_INPUT_EVENTS.forEach((event) => window.addEventListener(event, onUserInput, { passive: true }))+ return () => USER_INPUT_EVENTS.forEach((event) => window.removeEventListener(event, onUserInput))+ }, 'userInput')}),])