Skip to content

: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.

fix(dashboards): prevent stale PATCH from resetting display option state (#65970)

Sam Penningtonafc23b5bcce8
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 05e1ad842c65..7d5d5f7c2126 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -3,10 +3,9 @@ import './InsightCard.scss'
import { useMergeRefs } from '@floating-ui/react'
import clsx from 'clsx'
import { BindLogic, useActions, useValues } from 'kea'
-import React, { useMemo, useRef, useState } from 'react'
+import React, { useMemo, useState } from 'react'
import { LayoutItem } from 'react-grid-layout'
import { useInView } from 'react-intersection-observer'
-import { useDebouncedCallback } from 'use-debounce'
import { ApiError } from 'lib/api'
import { Resizeable } from 'lib/components/Cards/CardMeta'
@@ -27,10 +26,9 @@ import { insightLogic } from 'scenes/insights/insightLogic'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
-import { insightsModel } from '~/models/insightsModel'
import { extractValidationError } from '~/queries/nodes/InsightViz/utils'
import { Query } from '~/queries/Query/Query'
-import { DashboardFilter, HogQLVariable, Node } from '~/queries/schema/schema-general'
+import { DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'
import {
AccessControlLevel,
AccessControlResourceType,
@@ -48,7 +46,6 @@ import { EditModeEdge, EditModeEdgeOverlay } from './EditModeEdgeOverlay'
import { InsightMeta } from './InsightMeta'
const IS_STORYBOOK = inStorybook() || inStorybookTestRunner()
-const DISPLAY_OPTIONS_PERSIST_DEBOUNCE_MS = 700
export interface InsightCardProps extends Resizeable {
/** Insight to display. */
@@ -176,32 +173,34 @@ function InsightCardInternal(
const mergedRefs = useMergeRefs([ref, inViewRef])
const { theme } = useValues(themeLogic)
- const { updateInsightDirect } = useActions(insightsModel)
- // Display options edited from the card ⋯ menu mutate the saved insight directly (no per-tile
- // override), mirroring the legend/labels/annotations quick toggles. Debounced so rapid edits
- // (e.g. typing an axis label) collapse into a single PATCH.
- const insightRef = useRef(insight)
- insightRef.current = insight
const canEditInsight = insight.user_access_level
? accessLevelSatisfied(AccessControlResourceType.Insight, insight.user_access_level, AccessControlLevel.Editor)
: true
const canPersistDisplayOptions = !!dashboardId && canEditInsight
- const persistDisplayOptions = useDebouncedCallback((node: Node) => {
- updateInsightDirect(insightRef.current, { query: node })
- }, DISPLAY_OPTIONS_PERSIST_DEBOUNCE_MS)
- // Stable reference so the memoized viz below isn't invalidated on every grid re-render.
- const insightLogicProps: InsightLogicProps = useMemo(
+ // Base props without setQuery — used to mount insightDataLogic and retrieve the
+ // persistDisplayOptions action before wiring it back in as setQuery below.
+ const insightLogicPropsBase: InsightLogicProps = useMemo(
() => ({
dashboardItemId: insight.short_id,
dashboardId: dashboardId,
cachedInsight: insight,
loadPriority,
doNotLoad,
+ }),
+ [insight, dashboardId, loadPriority, doNotLoad]
+ )
+
+ const { persistDisplayOptions } = useActions(insightDataLogic(insightLogicPropsBase))
+
+ // Stable reference so the memoized viz below isn't invalidated on every grid re-render.
+ const insightLogicProps: InsightLogicProps = useMemo(
+ () => ({
+ ...insightLogicPropsBase,
setQuery: canPersistDisplayOptions ? persistDisplayOptions : undefined,
}),
- [insight, dashboardId, loadPriority, doNotLoad, canPersistDisplayOptions, persistDisplayOptions]
+ [insightLogicPropsBase, canPersistDisplayOptions, persistDisplayOptions]
)
const { insightLoading } = useValues(insightLogic(insightLogicProps))
diff --git a/frontend/src/scenes/insights/insightDataLogic.test.ts b/frontend/src/scenes/insights/insightDataLogic.test.ts
index 388af5f5bfe0..5dd2d89313e9 100644
--- a/frontend/src/scenes/insights/insightDataLogic.test.ts
+++ b/frontend/src/scenes/insights/insightDataLogic.test.ts
@@ -10,6 +10,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { useMocks } from '~/mocks/jest'
+import { insightsModel } from '~/models/insightsModel'
import { examples } from '~/queries/examples'
import { getDefaultQuery } from '~/queries/nodes/InsightViz/utils'
import { performQuery } from '~/queries/query'
@@ -416,4 +417,58 @@ describe('insightDataLogic', () => {
logic.unmount()
})
})
+
+ describe('persistDisplayOptions', () => {
+ const insightId = 42
+ const Insight42 = '42' as InsightShortId
+ const baseQuery: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, series: [] },
+ }
+ const updatedQuery: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, series: [], trendsFilter: { showLegend: true } as any },
+ }
+
+ let logic: ReturnType<typeof insightDataLogic.build>
+ let patchSpy: jest.Mock
+
+ beforeEach(() => {
+ patchSpy = jest.fn().mockResolvedValue([200, { id: insightId, short_id: Insight42, query: updatedQuery }])
+ useMocks({
+ patch: { '/api/environments/:team_id/insights/:id': patchSpy },
+ })
+
+ const props = {
+ dashboardItemId: Insight42,
+ cachedInsight: { id: insightId, short_id: Insight42, query: baseQuery } as any,
+ }
+ insightsModel.mount()
+ insightLogic(props).mount()
+ logic = insightDataLogic(props)
+ logic.mount()
+ })
+
+ it('debounces and fires renameInsightSuccess on success', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.persistDisplayOptions(updatedQuery)
+ })
+ .toFinishAllListeners()
+ .toDispatchActions(['renameInsightSuccess'])
+
+ expect(patchSpy).toHaveBeenCalledTimes(1)
+ })
+
+ it('collapses multiple rapid dispatches into a single PATCH', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.persistDisplayOptions(updatedQuery)
+ logic.actions.persistDisplayOptions(updatedQuery)
+ logic.actions.persistDisplayOptions(updatedQuery)
+ })
+ .toFinishAllListeners()
+ .toDispatchActions(['renameInsightSuccess'])
+
+ expect(patchSpy).toHaveBeenCalledTimes(1)
+ })
+ })
})
diff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsx
index 2bcf303143cb..e767d05f29dc 100644
--- a/frontend/src/scenes/insights/insightDataLogic.tsx
+++ b/frontend/src/scenes/insights/insightDataLogic.tsx
@@ -1,16 +1,32 @@
-import { actions, afterMount, connect, kea, key, listeners, path, props, propsChanged, reducers, selectors } from 'kea'
+import {
+ actions,
+ afterMount,
+ connect,
+ isBreakpoint,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ reducers,
+ selectors,
+} from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router } from 'kea-router'
import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectsEqual } from 'lib/utils/objects'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
+import { insightsApi } from 'scenes/insights/utils/api'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'
import { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'
+import { insightsModel } from '~/models/insightsModel'
import { examples } from '~/queries/examples'
import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { nodeKindToInsightType } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'
@@ -80,6 +96,8 @@ export const insightDataLogic = kea<insightDataLogicType>([
['setInsight', 'setInsightMetadata', 'loadInsightSuccess'],
dataNodeLogic({ key: insightVizDataNodeKey(props) } as DataNodeLogicProps),
['loadData', 'loadDataSuccess', 'loadDataFailure', 'setResponse as setInsightData'],
+ insightsModel,
+ ['renameInsightSuccess'],
],
logic: [insightDataTimingLogic(props), insightUsageLogic(props)],
})),
@@ -90,6 +108,7 @@ export const insightDataLogic = kea<insightDataLogicType>([
toggleQueryEditorPanel: true,
toggleDebugPanel: true,
cancelChanges: true,
+ persistDisplayOptions: (query: Node) => ({ query }),
}),
reducers({
@@ -274,6 +293,27 @@ export const insightDataLogic = kea<insightDataLogicType>([
}),
listeners(({ actions, values, props }) => ({
+ persistDisplayOptions: async ({ query }, breakpoint) => {
+ // Debounce rapid clicks. insightDataLogic is keyed per insight, so breakpoint
+ // only cancels concurrent saves for THIS insight — not unrelated tiles.
+ await breakpoint(700)
+ const insightId = values.insight.id
+ if (!insightId) {
+ return
+ }
+ try {
+ const updatedItem = await insightsApi.update(insightId, { query })
+ // Drop the response if a newer save started while this request was in flight.
+ await breakpoint(0)
+ actions.renameInsightSuccess(updatedItem)
+ lemonToast.success('Insight updated')
+ } catch (e) {
+ if (!isBreakpoint(e as Error)) {
+ lemonToast.error('Failed to update insight')
+ }
+ }
+ },
+
generateInsightMetadataSuccess: ({ generatedInsightMetadata }) => {
if (generatedInsightMetadata) {
actions.setInsightMetadata({