: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(dashboards): switch product analytics charts (#93952)
Vasco de Krijgerb6c8c53477a5
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 02c243d420ed..cd7dbf426e45 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2270,8 +2270,8 @@ const api = {async create(data: any): Promise<InsightModel> {return await new ApiRequest().insights().create({ data })},- async update(id: number, data: any): Promise<InsightModel> {- return await new ApiRequest().insight(id).update({ data })+ async update(id: number, data: any, options?: ApiMethodOptions): Promise<InsightModel> {+ return await new ApiRequest().insight(id).update({ data, ...options })},async cancelQuery(clientQueryId: string, teamId: TeamType['id'] = ApiConfig.getCurrentTeamId()): Promise<void> {await new ApiRequest().insightsCancel(teamId).create({ data: { client_query_id: clientQueryId } })diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsxindex 84a4e0f600dd..8197eadf9d4b 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx@@ -173,6 +173,7 @@ export interface InsightCardProps extends Resizeable {timedOut?: boolean/** Whether the editing controls should be enabled or not. */showEditingControls?: boolean+ refreshAfterDisplayOptionsChange?: (insight: QueryBasedInsightModel) => void/** While this tile is being resized: throttle canvas chart redraws instead of repainting on every frame. */isResizing?: boolean/** Whether the controls for showing details should be enabled or not. */@@ -234,6 +235,7 @@ function InsightCardInternal(queryId,timedOut,highlighted,+ refreshAfterDisplayOptionsChange,showResizeHandles,isResizing,showEditingControls,@@ -293,6 +295,11 @@ function InsightCardInternal(? accessLevelSatisfied(AccessControlResourceType.Insight, insight.user_access_level, AccessControlLevel.Editor): trueconst canPersistDisplayOptions = !!dashboardId && canEditInsight+ const refreshAfterDisplayOptionsChangeRef = useRef(refreshAfterDisplayOptionsChange)+ refreshAfterDisplayOptionsChangeRef.current = refreshAfterDisplayOptionsChange+ const handleRefreshAfterDisplayOptionsChange = useCallback((updatedInsight: QueryBasedInsightModel): void => {+ refreshAfterDisplayOptionsChangeRef.current?.(updatedInsight)+ }, [])// Base props without setQuery — used to mount insightDataLogic and retrieve the// persistDisplayOptions action before wiring it back in as setQuery below.@@ -303,8 +310,9 @@ function InsightCardInternal(cachedInsight: insight,loadPriority,doNotLoad,+ refreshAfterDisplayOptionsChange: handleRefreshAfterDisplayOptionsChange,}),- [insight, dashboardId, loadPriority, doNotLoad]+ [insight, dashboardId, loadPriority, doNotLoad, handleRefreshAfterDisplayOptionsChange])const { persistDisplayOptions } = useActions(insightDataLogic(insightLogicPropsBase))@@ -454,6 +462,7 @@ function InsightCardInternal(ribbonColor={ribbonColor}dashboardId={dashboardId}persistDisplayOptions={canPersistDisplayOptions ? persistDisplayOptions : undefined}+ refreshAfterDisplayOptionsChange={handleRefreshAfterDisplayOptionsChange}updateColor={updateColor}toggleShowDescription={toggleShowDescription}removeFromDashboard={removeFromDashboard}diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsxindex 60b79b406ac0..b670673487d5 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx@@ -71,7 +71,7 @@ import { ManageAlertsModal } from 'products/alerts/frontend/views/ManageAlertsMoimport { DashboardInsightDisplayOptions } from './DashboardInsightDisplayOptions'import { useDashboardVisualizationOptions } from './dashboardVisualizationOptions'-import type { DashboardSqlVisualizationPersistence } from './dashboardVisualizationOptions'+import type { DashboardVisualizationPersistence } from './dashboardVisualizationOptions'import { dashboardWidgetMenusLogic } from './dashboardWidgetMenusLogic'import { DashboardWidgetPlacementMenus } from './DashboardWidgetPlacementMenus'import { InsightCardProps } from './InsightCard'@@ -86,6 +86,7 @@ interface InsightMetaProps extends Pick<| 'removeFromDashboard'| 'deleteWithUndo'| 'refresh'+ | 'refreshAfterDisplayOptionsChange'| 'loading'| 'loadingQueued'| 'rename'@@ -127,6 +128,7 @@ export function InsightMeta({removeFromDashboard,deleteWithUndo,refresh,+ refreshAfterDisplayOptionsChange,loading,loadingQueued,rename,@@ -158,12 +160,12 @@ export function InsightMeta({variablesOverride: variablesOverride ?? null,tileFiltersOverride: tileFiltersOverride ?? null,setQuery: persistDisplayOptions,+ refreshAfterDisplayOptionsChange,}const { insightFeedback } = useValues(insightLogic(insightLogicProps))const { setInsightFeedback } = useActions(insightLogic(insightLogicProps))- const { exportContext, insightData, query, savingSqlVisualization, sqlVisualizationVersion } = useValues(- insightDataLogic(insightLogicProps)- )+ const { exportContext, insightData, query, savingDisplayOptions, savingSqlVisualization, sqlVisualizationVersion } =+ useValues(insightDataLogic(insightLogicProps))const { persistSqlVisualization } = useActions(insightDataLogic(insightLogicProps))const [isManageAlertsModalOpen, setIsManageAlertsModalOpen] = useState(false)const { loadAlerts: loadDeferredInsightAlerts } = useActions(@@ -252,7 +254,7 @@ export function InsightMeta({// Hoist the hooks out of the More overlay so kea logics they mount don't do so lazily inside a// portal, which cascades into closing the dropdown before the user can interact with it.const { items: displayOptionItems } = useInsightDisplayOptions()- const sqlVisualizationPersistence: DashboardSqlVisualizationPersistence | undefined = persistDisplayOptions+ const dashboardVisualizationPersistence: DashboardVisualizationPersistence | undefined = persistDisplayOptions? {saving: savingSqlVisualization,version: sqlVisualizationVersion,@@ -266,7 +268,8 @@ export function InsightMeta({insightData,variablesOverride,loading: loading || loadingQueued,- persistence: sqlVisualizationPersistence,+ persistence: dashboardVisualizationPersistence,+ savingDisplayOptions,})const displayMenuItems = [...visualizationItems, ...displayOptionItems]diff --git a/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.ts b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.tsindex fbe78c63f261..746d4fe654c2 100644--- a/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.ts+++ b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.ts@@ -2,12 +2,17 @@ import '@testing-library/jest-dom'import { cleanup, render, renderHook, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { BindLogic, Provider } from 'kea'+import { createElement } from 'react'import { LemonMenuItems, LemonMenuSection } from 'lib/lemon-ui/LemonMenu'+import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'-import { DataVisualizationNode, InsightVizNode, Node, NodeKind } from '~/queries/schema/schema-general'+import { DataVisualizationNode, FunnelsQuery, InsightVizNode, Node, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { ChartDisplayType } from '~/types'+import { ChartDisplayType, InsightShortId, InsightType, RetentionDashboardDisplayType } from '~/types'import { sqlQueryForVisualizationPicker, useDashboardVisualizationOptions } from './dashboardVisualizationOptions'@@ -24,9 +29,7 @@ function displayOptionsElement(items: LemonMenuItems): JSX.Element {}function chartTypeElement(items: LemonMenuItems): JSX.Element {- const section = items.find(- (item): item is LemonMenuSection => !!item && 'title' in item && item.title === 'Chart type'- )+ const section = items.find((item): item is LemonMenuSection => !!item && 'items' in item && item.key !== 'display')expect(section).not.toBeUndefined()const item = section?.items[0]@@ -46,6 +49,75 @@ describe('dashboardVisualizationOptions', () => {source: { kind: NodeKind.TrendsQuery, series: [] },} as unknown as InsightVizNode+ const stickinessQuery = {+ kind: NodeKind.InsightVizNode,+ source: { kind: NodeKind.StickinessQuery, series: [] },+ } as unknown as InsightVizNode++ const retentionQuery = {+ kind: NodeKind.InsightVizNode,+ source: { kind: NodeKind.RetentionQuery, retentionFilter: {} },+ } as unknown as InsightVizNode++ const retentionQueryWithoutGraph = {+ kind: NodeKind.InsightVizNode,+ vizSpecificOptions: { [InsightType.RETENTION]: { hideLineGraph: true } },+ source: {+ kind: NodeKind.RetentionQuery,+ retentionFilter: {},+ },+ } as unknown as InsightVizNode++ const funnelsQuery = {+ kind: NodeKind.InsightVizNode,+ source: { kind: NodeKind.FunnelsQuery, series: [] } as FunnelsQuery,+ } as InsightVizNode++ const persistence = {+ saving: null,+ version: 0,+ persistChartType: jest.fn(),+ persistDisplayOptions: jest.fn(),+ } as const++ function renderProductAnalyticsChartPicker(+ query: InsightVizNode,+ savingDisplayOptions = false+ ): {+ container: HTMLElement+ items: LemonMenuItems+ vizDataLogic: ReturnType<typeof insightVizDataLogic.build>+ } {+ initKeaTests()+ const insightProps = {+ dashboardItemId: 'dashboard-chart-picker' as InsightShortId,+ query,+ setQuery: jest.fn(),+ }+ insightLogic(insightProps).mount()+ insightDataLogic(insightProps).mount()+ const vizDataLogic = insightVizDataLogic(insightProps)+ vizDataLogic.mount()+ vizDataLogic.actions.updateQuerySource(query.source)++ const { result } = renderHook(() =>+ useDashboardVisualizationOptions({ query, insightData: {}, persistence, savingDisplayOptions })+ )+ const { container } = render(+ createElement(+ Provider,+ null,+ createElement(BindLogic, {+ logic: insightLogic,+ props: insightProps,+ children: chartTypeElement(result.current),+ })+ )+ )++ return { container, items: result.current, vizDataLogic }+ }+afterEach(() => {cleanup()})@@ -80,6 +152,82 @@ describe('dashboardVisualizationOptions', () => {})})+ describe('product analytics chart controls', () => {+ it.each([+ { label: 'Trends', query: trendsQuery, canPersist: true, expected: true },+ { label: 'Stickiness', query: stickinessQuery, canPersist: true, expected: true },+ { label: 'Retention', query: retentionQuery, canPersist: true, expected: true },+ {+ label: 'Retention with its graph hidden',+ query: retentionQueryWithoutGraph,+ canPersist: true,+ expected: false,+ },+ { label: 'Funnels', query: funnelsQuery, canPersist: true, expected: false },+ { label: 'read-only Trends', query: trendsQuery, canPersist: false, expected: false },+ ])('shows the editor picker for $label: $expected', ({ query, canPersist, expected }) => {+ const { result } = renderHook(() =>+ useDashboardVisualizationOptions({+ query,+ insightData: {},+ persistence: canPersist ? persistence : undefined,+ })+ )++ const hasChartTypeSection = result.current.some(+ (item) => !!item && 'title' in item && item.title === 'Chart type'+ )+ expect(hasChartTypeSection).toBe(expected)+ })++ it('shows when product analytics display changes are being saved', () => {+ const { container, items } = renderProductAnalyticsChartPicker(trendsQuery, true)+ const section = items.find(+ (item): item is LemonMenuSection => !!item && 'title' in item && item.title !== undefined+ )++ render(createElement('div', null, section?.title))++ expect(screen.getByRole('status')).toHaveTextContent('Saving')+ expect(container.querySelector('[data-attr="chart-filter"]')).toHaveAttribute('aria-disabled', 'true')+ expect(container.querySelector('[inert]')).toBeNull()+ })++ it.each([+ ['Stickiness', stickinessQuery],+ ['Retention', retentionQuery],+ ])('aligns the %s selector with the other full-width menu controls', (_label, query) => {+ const { container } = renderProductAnalyticsChartPicker(query)+ const selector = container.querySelector('[data-attr="chart-filter"]')++ expect(selector).toHaveClass('LemonButton--full-width')+ expect(selector?.parentElement).toHaveClass('px-2', 'pb-2')+ })++ it('shows the retention graph after selecting its active chart type on a dashboard', async () => {+ const { container, vizDataLogic } = renderProductAnalyticsChartPicker(retentionQuery)++ await userEvent.click(container.querySelector('[data-attr="chart-filter"]') as HTMLElement)+ const matches = screen.getAllByText('Line chart')+ await userEvent.click(matches[matches.length - 1])++ await waitFor(() =>+ expect(vizDataLogic.values.retentionFilter).toMatchObject({+ display: ChartDisplayType.ActionsLineGraph,+ dashboardDisplay: RetentionDashboardDisplayType.GraphOnly,+ })+ )+ })++ it('disables box plots when the series has no numeric property', async () => {+ const { container } = renderProductAnalyticsChartPicker(trendsQuery)++ await userEvent.click(container.querySelector('[data-attr="chart-filter"]') as HTMLElement)++ expect(screen.getByText('Box plot').closest('button')).toHaveAttribute('aria-disabled', 'true')+ })+ })+describe('SQL display controls', () => {const insightData = {columns: ['day', 'total'],diff --git a/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.tsx b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.tsxindex 4f5b315d3638..eca468d11062 100644--- a/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.tsx@@ -1,23 +1,70 @@+import { useActions, useValues } from 'kea'import { useCallback, useMemo, useRef } from 'react'import { Spinner } from '@posthog/lemon-ui'+import { ChartFilter } from 'lib/components/ChartFilter/ChartFilter'import { LemonMenuItems } from 'lib/lemon-ui/LemonMenu'+import { RetentionChartPicker } from 'scenes/insights/filters/RetentionChartPicker'+import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'import { isDisplayTabSupported } from '~/queries/nodes/DataVisualization/Components/SideBar'import { DataVisualizationNode, HogQLVariable, Node } from '~/queries/schema/schema-general'-import { isDataVisualizationNodeWithHogQLQuery } from '~/queries/utils'-import { ChartDisplayType } from '~/types'+import {+ isDataVisualizationNodeWithHogQLQuery,+ isInsightVizNode,+ isRetentionQuery,+ isStickinessQuery,+ isTrendsQuery,+} from '~/queries/utils'+import { ChartDisplayType, InsightType, RetentionDashboardDisplayType } from '~/types'import { DashboardSqlChartType, DashboardSqlDisplayOptions } from './DashboardSqlDisplayOptions'-export interface DashboardSqlVisualizationPersistence {+export interface DashboardVisualizationPersistence {saving: 'chart-type' | 'display-options' | nullversion: numberpersistChartType: (display: ChartDisplayType) => voidpersistDisplayOptions: (query: DataVisualizationNode) => void}+type ProductAnalyticsChartPicker = 'chart-filter' | 'retention'++function productAnalyticsChartPicker(query: Node | null, canPersist: boolean): ProductAnalyticsChartPicker | null {+ if (!canPersist || !isInsightVizNode(query)) {+ return null+ }+ if (isTrendsQuery(query.source) || isStickinessQuery(query.source)) {+ return 'chart-filter'+ }+ if (isRetentionQuery(query.source)) {+ return query.vizSpecificOptions?.[InsightType.RETENTION]?.hideLineGraph ? null : 'retention'+ }+ return null+}++function DashboardRetentionChartPicker({ disabledReason }: { disabledReason?: string }): JSX.Element {+ const { insightProps } = useValues(insightLogic)+ const { retentionFilter } = useValues(insightVizDataLogic(insightProps))+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))++ const selectChart = useCallback(+ (display: ChartDisplayType): void => {+ updateInsightFilter({+ display,+ ...(!retentionFilter?.dashboardDisplay ||+ retentionFilter.dashboardDisplay === RetentionDashboardDisplayType.TableOnly+ ? { dashboardDisplay: RetentionDashboardDisplayType.GraphOnly }+ : {}),+ })+ },+ [retentionFilter?.dashboardDisplay, updateInsightFilter]+ )++ return <RetentionChartPicker fullWidth disabledReason={disabledReason} onSelect={selectChart} />+}+export function sqlQueryForVisualizationPicker(query: Node | null, canPersist: boolean): DataVisualizationNode | null {return canPersist && query && isDataVisualizationNodeWithHogQLQuery(query) ? query : null}@@ -28,14 +75,17 @@ export function useDashboardVisualizationOptions({variablesOverride,loading,persistence,+ savingDisplayOptions,}: {query: Node | nullinsightData: Record<string, any>variablesOverride?: Record<string, HogQLVariable> | nullloading?: boolean- persistence?: DashboardSqlVisualizationPersistence+ persistence?: DashboardVisualizationPersistence+ savingDisplayOptions?: boolean}): LemonMenuItems {const sqlQuery = sqlQueryForVisualizationPicker(query, !!persistence)+ const insightChartPicker = productAnalyticsChartPicker(query, !!persistence)const overriddenVariable = Object.keys(sqlQuery?.source.variables ?? {}).find((key) => variablesOverride?.[key])const pickerProps = {@@ -70,6 +120,22 @@ export function useDashboardVisualizationOptions({)}, [])+ const insightChartPickerPropsRef = useRef({ insightChartPicker, savingDisplayOptions })+ insightChartPickerPropsRef.current = { insightChartPicker, savingDisplayOptions }+ const renderInsightChartPicker = useCallback((): JSX.Element => {+ const props = insightChartPickerPropsRef.current+ const disabledReason = props.savingDisplayOptions ? 'Saving…' : undefined+ return (+ <div className="w-full px-2 pb-2">+ {props.insightChartPicker === 'retention' ? (+ <DashboardRetentionChartPicker disabledReason={disabledReason} />+ ) : (+ <ChartFilter fullWidth disabledReason={disabledReason} />+ )}+ </div>+ )+ }, [])+const displayOptionsProps = {query: sqlQuery,cachedResults: insightData,@@ -101,16 +167,26 @@ export function useDashboardVisualizationOptions({}, [])return useMemo<LemonMenuItems>(() => {- if (!sqlQuery || !persistence) {+ if ((!sqlQuery && !insightChartPicker) || !persistence) {return []}return [{- title: 'Chart type',- items: [{ label: renderPicker }],+ title:+ insightChartPicker && savingDisplayOptions ? (+ <h5 className="mx-2 my-1 flex items-center justify-between gap-2">+ Chart type+ <span className="flex items-center gap-1 font-normal text-muted" role="status">+ <Spinner /> Saving+ </span>+ </h5>+ ) : (+ 'Chart type'+ ),+ items: [{ label: sqlQuery ? renderPicker : renderInsightChartPicker }],},- isDisplayTabSupported(sqlQuery.display ?? ChartDisplayType.ActionsTable)+ sqlQuery && isDisplayTabSupported(sqlQuery.display ?? ChartDisplayType.ActionsTable)? {key: 'display',title: (@@ -127,5 +203,13 @@ export function useDashboardVisualizationOptions({}: false,]- }, [sqlQuery, persistence, renderPicker, renderDisplayOptions])+ }, [+ sqlQuery,+ insightChartPicker,+ persistence,+ savingDisplayOptions,+ renderPicker,+ renderInsightChartPicker,+ renderDisplayOptions,+ ])}diff --git a/frontend/src/lib/components/ChartFilter/ChartFilter.tsx b/frontend/src/lib/components/ChartFilter/ChartFilter.tsxindex b37384a0c4ab..fd3783a72679 100644--- a/frontend/src/lib/components/ChartFilter/ChartFilter.tsx+++ b/frontend/src/lib/components/ChartFilter/ChartFilter.tsx@@ -8,7 +8,9 @@ import { Icon123, IconAreaChart, IconCumulativeChart, IconDonutChart, IconTableCimport { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'+import { isBoxPlotMissingProperty } from 'scenes/insights/utils/queryUtils'+import type { TrendsQuery } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'function ChartFilterOptionLabel(props: { label: string; description?: string }): JSX.Element {@@ -20,18 +22,31 @@ function ChartFilterOptionLabel(props: { label: string; description?: string }):)}-export function ChartFilter(): JSX.Element {+export function ChartFilter({+ fullWidth = false,+ disabledReason,+}: {+ fullWidth?: boolean+ disabledReason?: string+}): JSX.Element {const { insightProps, editingDisabledReason } = useValues(insightLogic)const { display } = useValues(insightVizDataLogic(insightProps))const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))const { featureFlags } = useValues(featureFlagLogic)- const { isTrends, isSingleSeriesOutput, formula, breakdownFilter } = useValues(insightVizDataLogic(insightProps))+ const { isTrends, isSingleSeriesOutput, formula, breakdownFilter, series } = useValues(+ insightVizDataLogic(insightProps)+ )const trendsOnlyDisabledReason = !isTrends ? 'This type is only available in Trends.' : undefinedconst singleSeriesOnlyDisabledReason = !isSingleSeriesOutput? 'This type currently only supports insights with one series, and this insight has multiple series.': undefined+ const boxPlotDisabledReason =+ trendsOnlyDisabledReason ||+ (isBoxPlotMissingProperty(series as TrendsQuery['series'])+ ? 'Select a numeric property to use a box plot.'+ : undefined)const options: LemonSelectOptions<ChartDisplayType> = [{@@ -85,7 +100,7 @@ export function ChartFilter(): JSX.Element {value: ChartDisplayType.BoxPlot,icon: <IconGraph />,label: 'Box plot',- disabledReason: trendsOnlyDisabledReason,+ disabledReason: boxPlotDisabledReason,labelInMenu: (<ChartFilterOptionLabellabel="Box plot"@@ -234,7 +249,8 @@ export function ChartFilter(): JSX.Element {data-attr="chart-filter"options={options}size="small"- disabledReason={editingDisabledReason}+ fullWidth={fullWidth}+ disabledReason={editingDisabledReason ?? disabledReason}/>)}diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsxindex ed1c69729926..a21b3f12fe8e 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx@@ -117,9 +117,7 @@ describe('InsightDisplayConfig', () => {}describe('Options menu sections per insight/chart type', () => {- // For each type: the section headers in the Options menu, and the toggles inside the "Display"- // section. Empty `displayItems` means the Display header renders with no options under it.- const cases: [string, InsightQueryNode, { sections: string[]; displayItems: string[] }][] = [+ const cases: [string, InsightQueryNode, { sections: string[]; displayItems?: string[] }][] = [['trends line graph',makeTrendsQuery(ChartDisplayType.ActionsLineGraph),@@ -184,11 +182,7 @@ describe('InsightDisplayConfig', () => {],},],- [- 'trends number',- makeTrendsQuery(ChartDisplayType.BoldNumber),- { sections: ['Display', 'Unit'], displayItems: [] },- ],+ ['trends number', makeTrendsQuery(ChartDisplayType.BoldNumber), { sections: ['Unit'] }],['trends pie',makeTrendsQuery(ChartDisplayType.ActionsPie),@@ -218,21 +212,13 @@ describe('InsightDisplayConfig', () => {],},],- [- 'trends table',- makeTrendsQuery(ChartDisplayType.ActionsTable),- { sections: ['Display', 'Unit'], displayItems: [] },- ],+ ['trends table', makeTrendsQuery(ChartDisplayType.ActionsTable), { sections: ['Unit'] }],['trends bar value (horizontal)',makeTrendsQuery(ChartDisplayType.ActionsBarValue),{ sections: ['Display', 'X-axis unit', 'Axis labels'], displayItems: ['Show values on series'] },],- [- 'trends world map',- makeTrendsQuery(ChartDisplayType.WorldMap),- { sections: ['Display', 'Unit'], displayItems: [] },- ],+ ['trends world map', makeTrendsQuery(ChartDisplayType.WorldMap), { sections: ['Unit'] }],['box plot',makeTrendsQuery(ChartDisplayType.BoxPlot),@@ -259,6 +245,7 @@ describe('InsightDisplayConfig', () => {displayItems: ['Show values on series', 'Show multiple Y-axes', 'Show legendBottom'],},],+ ['stickiness table', makeStickinessQuery(ChartDisplayType.ActionsTable), { sections: [] }],['lifecycle',makeLifecycleQuery(),@@ -276,10 +263,20 @@ describe('InsightDisplayConfig', () => {it.each(cases)('%s shows the expected sections and display options', async (_name, query, expected) => {setupAndRender(query)++ if (expected.sections.length === 0) {+ expect(screen.queryByLabelText('Options')).not.toBeInTheDocument()+ return+ }+await openOptionsMenu()expect(getSectionTitles()).toEqual(expected.sections)- expect(getDisplaySectionItems()).toEqual(expected.displayItems)+ if (!expected.displayItems) {+ expect(screen.queryByTestId('options-display-section')).not.toBeInTheDocument()+ } else {+ expect(getDisplaySectionItems()).toEqual(expected.displayItems)+ }})})diff --git a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsxindex 9ae21f998407..591136987689 100644--- a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx+++ b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx@@ -170,15 +170,16 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numb}const items: LemonMenuItems = []+ const displayItems = getDisplayItems()if (showSmoothing) {items.push({ title: 'Smoothing', items: [DisplayOptions.Smoothing] })}- if (showDisplaySection) {+ if (showDisplaySection && displayItems.length > 0) {items.push({title: <SectionHeader dataAttr="options-display-section">Display</SectionHeader>,- items: getDisplayItems(),+ items: displayItems,})}diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsxindex cb42b87097eb..c331efe3b34c 100644--- a/frontend/src/scenes/dashboard/DashboardItems.tsx+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx@@ -605,6 +605,14 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPrefresh={refreshDashboardTile ? () => refreshDashboardTile({ tile }) : undefined}+ refreshAfterDisplayOptionsChange={+ refreshDashboardTile+ ? (updatedInsight) =>+ refreshDashboardTile({+ tile: { ...tile, insight: updatedInsight },+ })+ : undefined+ }rename={() => renameInsight(insight)}duplicate={() => duplicateTile(tile)}setOverride={() => setTileOverride(tile)}diff --git a/frontend/src/scenes/insights/filters/RetentionChartPicker.tsx b/frontend/src/scenes/insights/filters/RetentionChartPicker.tsxindex 76c1d8fc1263..c9b46b0dd1d6 100644--- a/frontend/src/scenes/insights/filters/RetentionChartPicker.tsx+++ b/frontend/src/scenes/insights/filters/RetentionChartPicker.tsx@@ -47,25 +47,36 @@ const OPTIONS: LemonSelectOptions<ChartDisplayType> = [},]-export function RetentionChartPicker(): JSX.Element {+export function RetentionChartPicker({+ fullWidth = false,+ disabledReason,+ onSelect,+}: {+ fullWidth?: boolean+ disabledReason?: string+ onSelect?: (display: ChartDisplayType) => void+}): JSX.Element {const { insightProps, editingDisabledReason } = useValues(insightLogic)const { retentionFilter } = useValues(insightVizDataLogic(insightProps))const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))+ const selectChart = (value: ChartDisplayType): void => {+ updateInsightFilter({ display: value })+ }return (<LemonSelectkey="2"value={retentionFilter?.display || ChartDisplayType.ActionsLineGraph}- onChange={(value) => {- updateInsightFilter({ display: value })- }}+ onChange={onSelect ? undefined : selectChart}+ onSelect={onSelect}dropdownPlacement="bottom-end"optionTooltipPlacement="left"dropdownMatchSelectWidth={false}data-attr="chart-filter"options={OPTIONS}size="small"- disabledReason={editingDisabledReason}+ fullWidth={fullWidth}+ disabledReason={editingDisabledReason ?? disabledReason}/>)}diff --git a/frontend/src/scenes/insights/insightDataLogic.test.ts b/frontend/src/scenes/insights/insightDataLogic.test.tsindex c1630072369e..285e11f9bfae 100644--- a/frontend/src/scenes/insights/insightDataLogic.test.ts+++ b/frontend/src/scenes/insights/insightDataLogic.test.ts@@ -9,9 +9,12 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { delay } from 'lib/utils/async'import { insightLogic } from 'scenes/insights/insightLogic'import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'+import { insightsApi } from 'scenes/insights/utils/api'import { sceneLogic } from 'scenes/sceneLogic'import { Scene } from 'scenes/sceneTypes'@@ -534,16 +537,22 @@ describe('insightDataLogic', () => {let logic: ReturnType<typeof insightDataLogic.build>let patchSpy: jest.Mock+ let refreshAfterDisplayOptionsChange: jest.MockbeforeEach(() => {- patchSpy = jest.fn().mockResolvedValue([200, { id: insightId, short_id: Insight42, query: updatedQuery }])+ patchSpy = jest.fn(async ({ request }: { request: Request }) => {+ const body = (await request.json()) as Record<string, any>+ return [200, { id: insightId, short_id: Insight42, ...body }]+ })useMocks({patch: { '/api/environments/:team_id/insights/:id': patchSpy },})+ refreshAfterDisplayOptionsChange = jest.fn()const props = {dashboardItemId: Insight42,cachedInsight: { id: insightId, short_id: Insight42, query: baseQuery } as any,+ refreshAfterDisplayOptionsChange,}insightsModel.mount()insightLogic(props).mount()@@ -552,13 +561,35 @@ describe('insightDataLogic', () => {})it('debounces and fires renameInsightSuccess on success', async () => {- await expectLogic(logic, () => {+ const expectation = expectLogic(logic, () => {logic.actions.persistDisplayOptions(updatedQuery)})- .toFinishAllListeners()- .toDispatchActions(['renameInsightSuccess'])++ expect(logic.values.savingDisplayOptions).toBe(true)++ await expectation.toFinishAllListeners().toDispatchActions(['renameInsightSuccess'])expect(patchSpy).toHaveBeenCalledTimes(1)+ expect(refreshAfterDisplayOptionsChange).not.toHaveBeenCalled()+ expect(logic.values.savingDisplayOptions).toBe(false)+ })++ it('refreshes dashboard data when the chart needs a different result shape', async () => {+ const cumulativeQuery: InsightVizNode = {+ ...baseQuery,+ source: {+ ...baseQuery.source,+ trendsFilter: { display: ChartDisplayType.ActionsLineGraphCumulative },+ } as TrendsQuery,+ }++ await expectLogic(logic, () => {+ logic.actions.persistDisplayOptions(cumulativeQuery)+ }).toFinishAllListeners()++ expect(refreshAfterDisplayOptionsChange).toHaveBeenCalledWith(+ expect.objectContaining({ query: cumulativeQuery })+ )})it('collapses multiple rapid dispatches into a single PATCH', async () => {@@ -601,6 +632,196 @@ describe('insightDataLogic', () => {sceneLogic.unmount()}})++ it('sends overlapping saves one at a time, so the newest query is written last', async () => {+ const laterQuery: InsightVizNode = {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [],+ trendsFilter: { showLegend: true, showValuesOnSeries: true } as any,+ },+ }+ const patchedQueries: Node[] = []+ let markFirstPatchSent: () => void = () => {}+ let releaseFirstPatch: () => void = () => {}+ const firstPatchSent = new Promise<void>((resolve) => {+ markFirstPatchSent = resolve+ })+ const firstPatchHeld = new Promise<void>((resolve) => {+ releaseFirstPatch = resolve+ })+ const recordPatch = async (request: Request): Promise<Record<string, any>> => {+ const body = (await request.json()) as Record<string, any>+ patchedQueries.push(body.query)+ return body+ }+ patchSpy.mockImplementationOnce(async ({ request }: { request: Request }) => {+ const body = await recordPatch(request)+ markFirstPatchSent()+ await firstPatchHeld+ return [200, { id: insightId, short_id: Insight42, ...body }]+ })+ patchSpy.mockImplementationOnce(async ({ request }: { request: Request }) => {+ const body = await recordPatch(request)+ return [200, { id: insightId, short_id: Insight42, ...body }]+ })++ logic.actions.persistDisplayOptions(updatedQuery)+ await firstPatchSent++ const secondSave = expectLogic(logic, () => {+ logic.actions.persistDisplayOptions(laterQuery)+ })+ // Past the 700ms debounce, so the second PATCH would run next to the first one if the+ // saves were not serialized.+ await delay(800)+ expect(patchedQueries).toEqual([updatedQuery])++ releaseFirstPatch()+ await secondSave.toFinishAllListeners().toDispatchActions(['renameInsightSuccess'])++ expect(patchedQueries).toEqual([updatedQuery, laterQuery])+ })++ it('restores the saved query when the current save fails', async () => {+ patchSpy.mockResolvedValueOnce([500, { detail: 'Save failed' }])+ logic.actions.setQuery(updatedQuery)++ await expectLogic(logic, () => {+ logic.actions.persistDisplayOptions(updatedQuery)+ }).toFinishAllListeners()++ expect(logic.values.query).toEqual(baseQuery)+ expect(logic.values.savingDisplayOptions).toBe(false)+ })++ it('does not roll back a newer edit when the previous save fails', async () => {+ const laterQuery: InsightVizNode = {+ ...updatedQuery,+ source: {+ ...updatedQuery.source,+ trendsFilter: { showLegend: true, showValuesOnSeries: true } as any,+ } as TrendsQuery,+ }+ let failFirstPatch: () => void = () => {}+ let markFirstPatchSent: () => void = () => {}+ let markSecondPatchSent: () => void = () => {}+ let releaseSecondPatch: () => void = () => {}+ const firstPatchSent = new Promise<void>((resolve) => {+ markFirstPatchSent = resolve+ })+ const firstPatchHeld = new Promise<[number, { detail: string }]>((resolve) => {+ failFirstPatch = () => resolve([500, { detail: 'Save failed' }])+ })+ const secondPatchSent = new Promise<void>((resolve) => {+ markSecondPatchSent = resolve+ })+ const secondPatchHeld = new Promise<void>((resolve) => {+ releaseSecondPatch = resolve+ })++ patchSpy.mockImplementationOnce(async () => {+ markFirstPatchSent()+ return await firstPatchHeld+ })+ patchSpy.mockImplementationOnce(async ({ request }: { request: Request }) => {+ const body = (await request.json()) as Record<string, any>+ markSecondPatchSent()+ await secondPatchHeld+ return [200, { id: insightId, short_id: Insight42, ...body }]+ })++ logic.actions.setQuery(updatedQuery)+ logic.actions.persistDisplayOptions(updatedQuery)+ await firstPatchSent++ logic.actions.setQuery(laterQuery)+ logic.actions.persistDisplayOptions(laterQuery)+ failFirstPatch()+ await secondPatchSent++ expect(logic.values.query).toEqual(laterQuery)+ expect(logic.values.savingDisplayOptions).toBe(true)++ releaseSecondPatch()+ await expectLogic(logic).toFinishAllListeners()+ })++ it('keeps the optimistic query when a save times out', async () => {+ jest.useFakeTimers()+ const warningToast = jest.spyOn(lemonToast, 'warning').mockReturnValue('toast-id')+ const updateSpy = jest.spyOn(insightsApi, 'update').mockImplementationOnce(+ async (_id: number, _update: Record<string, any>, options?: { signal?: AbortSignal }): Promise<never> =>+ await new Promise((_, reject) => {+ options?.signal?.addEventListener('abort', () => reject(new Error('Request aborted')))+ })+ )++ try {+ logic.actions.setQuery(updatedQuery)+ logic.actions.persistDisplayOptions(updatedQuery)+ await jest.advanceTimersByTimeAsync(700)+ expect(updateSpy).toHaveBeenCalledTimes(1)++ await jest.advanceTimersByTimeAsync(15_000)+ await jest.advanceTimersByTimeAsync(0)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.query).toEqual(updatedQuery)+ expect(logic.values.savingDisplayOptions).toBe(false)+ expect(warningToast).toHaveBeenCalledWith(+ "Couldn't confirm whether the insight was updated. Refresh the dashboard to check."+ )+ } finally {+ warningToast.mockRestore()+ updateSpy.mockRestore()+ jest.useRealTimers()+ }+ })++ it('lets the latest save proceed when the previous request hangs', async () => {+ jest.useFakeTimers()+ const laterQuery: InsightVizNode = {+ ...updatedQuery,+ source: {+ ...updatedQuery.source,+ trendsFilter: { showLegend: true, showValuesOnSeries: true } as any,+ } as TrendsQuery,+ }+ const updateSpy = jest.spyOn(insightsApi, 'update') as jest.Mock+ updateSpy+ .mockImplementationOnce(+ async (+ _id: number,+ _update: Record<string, any>,+ options?: { signal?: AbortSignal }+ ): Promise<never> =>+ await new Promise((_, reject) => {+ options?.signal?.addEventListener('abort', () => reject(new Error('Request aborted')))+ })+ )+ .mockResolvedValueOnce({ id: insightId, short_id: Insight42, query: laterQuery })++ try {+ logic.actions.persistDisplayOptions(updatedQuery)+ await jest.advanceTimersByTimeAsync(700)+ expect(updateSpy).toHaveBeenCalledTimes(1)++ logic.actions.persistDisplayOptions(laterQuery)+ await jest.advanceTimersByTimeAsync(700)+ expect(updateSpy).toHaveBeenCalledTimes(1)++ await jest.advanceTimersByTimeAsync(15_000)+ await jest.advanceTimersByTimeAsync(0)++ expect(updateSpy).toHaveBeenCalledTimes(2)+ expect(logic.values.query).toEqual(laterQuery)+ } finally {+ updateSpy.mockRestore()+ jest.useRealTimers()+ }+ })})describe('persistSqlVisualization', () => {diff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsxindex 895c61bbbd1b..43392632197c 100644--- a/frontend/src/scenes/insights/insightDataLogic.tsx+++ b/frontend/src/scenes/insights/insightDataLogic.tsx@@ -19,6 +19,7 @@ import posthog from 'posthog-js'import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { PromiseTimeoutError, withTimeout } from 'lib/utils/async'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { objectsEqual } from 'lib/utils/objects'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'@@ -162,6 +163,7 @@ export interface insightDataLogicValues {query: Node | nullqueryChanged: booleanqueryFromUrl: boolean+ savingDisplayOptions: booleansavingSqlVisualization: SqlVisualizationUpdate['type'] | nullshowDebugPanel: booleanshowQueryEditor: boolean@@ -414,6 +416,9 @@ export interface insightDataLogicActions {persistDisplayOptions: (query: Node) => {query: Node<Record<string, any>>}+ persistDisplayOptionsSettled: () => {+ value: true+ }persistSqlVisualization: (update: SqlVisualizationUpdate) => {update: SqlVisualizationUpdate}@@ -541,12 +546,20 @@ export const insightDataLogic = kea<insightDataLogicType>([toggleDebugPanel: true,cancelChanges: true,persistDisplayOptions: (query: Node) => ({ query }),+ persistDisplayOptionsSettled: true,persistSqlVisualization: (update: SqlVisualizationUpdate) => ({ update }),persistSqlVisualizationFailed: (update: SqlVisualizationUpdate) => ({ update }),persistSqlVisualizationSettled: true,}),reducers({+ savingDisplayOptions: [+ false,+ {+ persistDisplayOptions: () => true,+ persistDisplayOptionsSettled: () => false,+ },+ ],savingSqlVisualization: [null as SqlVisualizationUpdate['type'] | null,{@@ -786,13 +799,12 @@ export const insightDataLogic = kea<insightDataLogicType>([// (a display toggle or removing a filter) would PATCH the insight before the user// clicks Save. Edits there must persist only through an explicit save.if (isInsightSceneInstance(props)) {+ actions.persistDisplayOptionsSettled()return}- // Debounce rapid clicks. insightDataLogic is keyed per insight, so breakpoint- // only cancels concurrent saves for this insight without affecting unrelated tiles.- await breakpoint(700)const insightId = values.insight.idif (!insightId) {+ actions.persistDisplayOptionsSettled()return}// Only persist when the query actually differs from what's saved. The setQuery →@@ -800,17 +812,50 @@ export const insightDataLogic = kea<insightDataLogicType>([// re-syncs (tile re-renders, results refreshes) that carry an unchanged query;// persisting those produces spurious saves and activity-log churn.if (objectsEqual(query, values.savedInsight.query)) {+ actions.persistDisplayOptionsSettled()return}+ const refreshResults = values.savedInsight.query+ ? !compareQuery(query, values.savedInsight.query, { ignoreVisualizationOnlyChanges: true })+ : false+ const saveId = (cache.displayOptionsSaveId ?? 0) + 1+ cache.displayOptionsSaveId = saveIdtry {- const updatedItem = await insightsApi.update(insightId, { query })- // Drop the response if a newer save started while this request was in flight.- await breakpoint(0)+ // Debounce rapid clicks. insightDataLogic is keyed per insight, so breakpoint+ // only cancels concurrent saves for this insight without affecting unrelated tiles.+ await breakpoint(700)+ // Breakpoints cannot cancel PATCHes that have already started, so serialize them per insight.+ await cache.displayOptionsSave+ breakpoint()+ const save = withTimeout(+ (signal) => insightsApi.update(insightId, { query }, { signal }),+ 15_000,+ 'Saving display options timed out'+ )+ // The next save only needs to know when this request finishes.+ cache.displayOptionsSave = save.catch(() => undefined)+ const updatedItem = await save+ if (saveId !== cache.displayOptionsSaveId) {+ return+ }actions.renameInsightSuccess(updatedItem)+ if (refreshResults) {+ props.refreshAfterDisplayOptionsChange?.(updatedItem)+ }+ actions.persistDisplayOptionsSettled()lemonToast.success('Insight updated')} catch (e) {// A breakpoint means a newer save superseded this one, and that save owns the state.- if (!isBreakpoint(e as Error)) {+ if (!isBreakpoint(e as Error) && saveId === cache.displayOptionsSaveId) {+ if (e instanceof PromiseTimeoutError) {+ actions.persistDisplayOptionsSettled()+ lemonToast.warning(+ "Couldn't confirm whether the insight was updated. Refresh the dashboard to check."+ )+ return+ }+ actions.syncQueryFromProps(values.savedInsight.query ?? null)+ actions.persistDisplayOptionsSettled()lemonToast.error('Failed to update insight')}}diff --git a/frontend/src/scenes/insights/utils/api.ts b/frontend/src/scenes/insights/utils/api.tsindex 7de877d9bb54..a4f529fa07a6 100644--- a/frontend/src/scenes/insights/utils/api.ts+++ b/frontend/src/scenes/insights/utils/api.ts@@ -1,4 +1,4 @@-import api from 'lib/api'+import api, { ApiMethodOptions } from 'lib/api'import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'import { DashboardFilter, HogQLVariable, RefreshType, TileFilters } from '~/queries/schema/schema-general'@@ -7,10 +7,11 @@ import { InsightShortId, QueryBasedInsightModel } from '~/types'async function _perform(method: 'create' | 'update',insight: Partial<QueryBasedInsightModel>,- id?: number+ id?: number,+ options?: ApiMethodOptions): Promise<QueryBasedInsightModel> {const legacyInsight =- method === 'create' ? await api.insights[method](insight) : await api.insights[method](id!, insight)+ method === 'create' ? await api.insights[method](insight) : await api.insights[method](id!, insight, options)return getQueryBasedInsightModel(legacyInsight, 'insight_write')}@@ -48,8 +49,12 @@ export const insightsApi = {async create(insight: Partial<QueryBasedInsightModel>): Promise<QueryBasedInsightModel> {return this._perform('create', insight)},- async update(id: number, insightUpdate: Partial<QueryBasedInsightModel>): Promise<QueryBasedInsightModel> {- return this._perform('update', insightUpdate, id)+ async update(+ id: number,+ insightUpdate: Partial<QueryBasedInsightModel>,+ options?: ApiMethodOptions+ ): Promise<QueryBasedInsightModel> {+ return this._perform('update', insightUpdate, id, options)},async duplicate(insight: QueryBasedInsightModel): Promise<QueryBasedInsightModel> {const { id, short_id, result, created_at, created_by, last_modified_at, last_modified_by, ...rest } = insightdiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex e64cd6d6ee19..b5b6631950c1 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -3732,6 +3732,7 @@ export interface InsightLogicProps<Q extends QuerySchema = QuerySchema> {/** query when used as ad-hoc insight */query?: QsetQuery?: (node: Q) => void+ refreshAfterDisplayOptionsChange?: (insight: QueryBasedInsightModel) => void/** Used to group DataNodes into a collection for group operations like refreshAll **/dataNodeCollectionId?: string