: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(insights): A/A/B test add-to-dashboard affordances (#64476)
Paul D'Ambrac675c86e4476
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 5e3bd6ea1500..d7f8426d9f2c 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -430,6 +430,7 @@ export const FEATURE_FLAGS = {PRODUCT_ANALYTICS_FUNNELS_COMPARE: 'product-analytics-funnels-compare', // owner: @thmsobrmlr #team-product-analytics, gates "Compare to previous" toggle on funnel insightsPRODUCT_ANALYTICS_HIDE_WEEKENDS: 'product-analytics-hide-weekends', // owner: @kliment-slice #team-irl-eventsPRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analytics+ INSIGHT_ADD_TO_DASHBOARD_AAB: 'insight-add-to-dashboard-aab', // owner: @pauldambra #team-product-analytics multivariate=control,control_2,testPRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analyticsPRODUCT_ANALYTICS_QUILL_SQL_CHARTS: 'product-analytics-quill-sql-charts', // owner: #team-data-tools, gates rendering DataVisualization line/area charts via @posthog/quill-chartsPRODUCT_ANALYTICS_RETENTION_AGGREGATION: 'retention-aggregation', // owner: @anirudhpillai #team-product-analyticsdiff --git a/frontend/src/scenes/insights/InsightPageHeader.tsx b/frontend/src/scenes/insights/InsightPageHeader.tsxindex 00d009eb0a4b..31d96cb88d09 100644--- a/frontend/src/scenes/insights/InsightPageHeader.tsx+++ b/frontend/src/scenes/insights/InsightPageHeader.tsx@@ -2,6 +2,8 @@ import { useActions, useValues } from 'kea'import { combineUrl, router } from 'kea-router'import { useMemo } from 'react'+import { IconPlusSmall } from '@posthog/icons'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { areAlertsSupportedForInsight } from 'lib/components/Alerts/insightAlertsLogic'import { InsightSubscribeProminentButton } from 'lib/components/Scenes/InsightSubscribeProminentButton'@@ -9,6 +11,7 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'+import { insightModalsLogic } from 'scenes/insights/insightModalsLogic'import { InsightSaveButton } from 'scenes/insights/InsightSaveButton'import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'import { useMaxTool } from 'scenes/max/useMaxTool'@@ -52,6 +55,22 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: Inconst { setInsightMetadata, setInsightMetadataLocal, saveAs, saveInsight } = useActions(insightLogic(insightLogicProps))+ const { openAddToDashboardModal, saveAndAddToDashboard } = useActions(insightModalsLogic(insightLogicProps))++ // B branch of the add-to-dashboard A/A/B test (control + control_2 keep current behavior).+ const isAddToDashboardTest = useFeatureFlag('INSIGHT_ADD_TO_DASHBOARD_AAB', 'test')++ // A saved insight with its own short_id — the precondition for every view-mode action in this header.+ const isPersistedInsight = !!isSavedInsight && !!insight.short_id++ // New insights need a target folder; existing ones save in place. Shared by every save trigger in this header.+ const saveInsightToFolder = (redirectToViewMode?: boolean): void => {+ if (insight.short_id) {+ saveInsight(redirectToViewMode)+ } else {+ saveInsight(redirectToViewMode, getLastNewFolder() ?? 'Unfiled/Insights')+ }+ }const { query, queryChanged, insightQuery, generatedInsightMetadataLoading } = useValues(insightDataLogic(insightProps)@@ -150,8 +169,20 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: In</LemonButton>)}- {insightMode !== ItemMode.Edit && isSavedInsight && insight.short_id && (- <InsightSubscribeProminentButton insightShortId={insight.short_id} />+ {insightMode !== ItemMode.Edit && isAddToDashboardTest && isPersistedInsight && (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconPlusSmall />}+ data-attr="insight-add-to-dashboard-prominent-button"+ onClick={() => openAddToDashboardModal()}+ >+ Add to dashboard+ </LemonButton>+ )}++ {insightMode !== ItemMode.Edit && isPersistedInsight && (+ <InsightSubscribeProminentButton insightShortId={insight.short_id!} />)}{insightMode !== ItemMode.Edit ? (@@ -194,15 +225,20 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: In) : (<InsightSaveButtonsaveAs={() => saveAs(undefined, undefined, 'Unfiled/Insights')}- saveInsight={(redirectToViewMode) =>- insight.short_id- ? saveInsight(redirectToViewMode)- : saveInsight(redirectToViewMode, getLastNewFolder() ?? 'Unfiled/Insights')- }+ saveInsight={saveInsightToFolder}isSaved={isSavedInsight}addingToDashboard={!!insight.dashboards?.length && !insight.id}insightSaving={insightSaving}insightChanged={insightChanged || queryChanged}+ // Only offered for already-saved insights: the add-to-dashboard modal is keyed by the+ // insight id, so saving a brand-new insight navigates to its real id and re-keys the+ // modal logic, dropping the open state. New insights use the view-mode button instead.+ // `saveAndAddToDashboard` owns the save-then-open ordering (see insightModalsLogic).+ onSaveAndAddToDashboard={+ isAddToDashboardTest && isPersistedInsight+ ? () => saveAndAddToDashboard()+ : undefined+ }/>)}</>diff --git a/frontend/src/scenes/insights/InsightSaveButton.tsx b/frontend/src/scenes/insights/InsightSaveButton.tsxindex 616f6fb89571..6b1ca4e3ee58 100644--- a/frontend/src/scenes/insights/InsightSaveButton.tsx+++ b/frontend/src/scenes/insights/InsightSaveButton.tsx@@ -7,6 +7,7 @@ export function InsightSaveButton({insightSaving,insightChanged,addingToDashboard,+ onSaveAndAddToDashboard,}: {saveAs: () => voidsaveInsight: (redirectToViewMode?: boolean) => void@@ -14,6 +15,8 @@ export function InsightSaveButton({insightSaving: booleaninsightChanged: booleanaddingToDashboard: boolean+ // When provided, adds a "Save & add to dashboard" dropdown option that saves then opens the add-to-dashboard modal.+ onSaveAndAddToDashboard?: () => void}): JSX.Element {const disabled = isSaved && !insightChangedconst saveAsAvailable = isSaved && !addingToDashboard@@ -36,10 +39,21 @@ export function InsightSaveButton({onClick={() => saveInsight(false)}data-attr="insight-save-and-continue"fullWidth+ loading={insightSaving}>{addingToDashboard ? 'Save, add to dashboard' : 'Save'} & continue editing</LemonButton>)}+ {!disabled && onSaveAndAddToDashboard && (+ <LemonButton+ onClick={() => onSaveAndAddToDashboard()}+ data-attr="insight-save-and-add-to-dashboard"+ fullWidth+ loading={insightSaving}+ >+ Save & add to dashboard…+ </LemonButton>+ )}{saveAsAvailable && (<LemonButton onClick={() => saveAs()} data-attr="insight-save-as-new-insight" fullWidth>Save as…diff --git a/frontend/src/scenes/insights/insightModalsLogic.test.ts b/frontend/src/scenes/insights/insightModalsLogic.test.tsnew file mode 100644index 000000000000..30d24a374747--- /dev/null+++ b/frontend/src/scenes/insights/insightModalsLogic.test.ts@@ -0,0 +1,90 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { sceneLogic } from 'scenes/sceneLogic'+import { teamLogic } from 'scenes/teamLogic'++import { useMocks } from '~/mocks/jest'+import { insightsModel } from '~/models/insightsModel'+import { NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { InsightLogicProps, InsightShortId } from '~/types'++import { insightLogic } from './insightLogic'+import { insightModalsLogic } from './insightModalsLogic'++const Insight42 = '42' as InsightShortId++const savedInsightProps: InsightLogicProps = {+ dashboardItemId: Insight42,+ cachedInsight: {+ id: 42,+ short_id: Insight42,+ result: ['result'],+ saved: true,+ query: { kind: NodeKind.InsightVizNode, source: { kind: NodeKind.TrendsQuery, series: [] } },+ } as any,+}++describe('insightModalsLogic', () => {+ let logic: ReturnType<typeof insightModalsLogic.build>++ beforeEach(async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/insights/42': { id: 42, short_id: Insight42, result: ['result'] },+ '/api/environments/:team_id/insights/': { results: [], count: 0 },+ },+ patch: {+ '/api/environments/:team_id/insights/:id': async ({ request, params }) => {+ const payload = (await request.json()) as Record<string, any>+ return [200, { ...payload, id: params.id, short_id: Insight42 }]+ },+ },+ })+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM })+ teamLogic.mount()+ sceneLogic.mount()+ insightsModel.mount()+ insightLogic(savedInsightProps).mount()+ logic = insightModalsLogic(savedInsightProps)+ logic.mount()+ })++ it('saves first, then opens the add-to-dashboard modal once the save succeeds', async () => {+ await expectLogic(logic, () => {+ logic.actions.saveAndAddToDashboard()+ })+ .toDispatchActions(['saveAndAddToDashboard', 'saveInsight'])+ .toMatchValues({ pendingAddToDashboardAfterSave: true })+ .toDispatchActions(['saveInsightSuccess', 'openAddToDashboardModal'])+ .toMatchValues({ pendingAddToDashboardAfterSave: false, isAddToDashboardModalOpen: true })+ })++ it('does not open the modal and clears the pending flag when the save fails', async () => {+ // Hold the save open so the pending flag stays set, then drive the failure signal directly — this exercises+ // insightModalsLogic's reaction without depending on insightLogic re-throwing on a real API error.+ useMocks({ patch: { '/api/environments/:team_id/insights/:id': () => new Promise(() => {}) } })++ await expectLogic(logic, () => {+ logic.actions.saveAndAddToDashboard()+ }).toMatchValues({ pendingAddToDashboardAfterSave: true })++ await expectLogic(logic, () => {+ insightLogic(savedInsightProps).actions.saveInsightFailure()+ })+ .toDispatchActions(['saveInsightFailure'])+ .toNotHaveDispatchedActions(['openAddToDashboardModal'])+ .toMatchValues({ pendingAddToDashboardAfterSave: false, isAddToDashboardModalOpen: false })+ })++ it('does not open the modal on a plain save with nothing pending', async () => {+ await expectLogic(logic, () => {+ insightLogic(savedInsightProps).actions.saveInsightSuccess()+ })+ .toDispatchActions(['saveInsightSuccess'])+ .toNotHaveDispatchedActions(['openAddToDashboardModal'])+ .toMatchValues({ pendingAddToDashboardAfterSave: false, isAddToDashboardModalOpen: false })+ })+})diff --git a/frontend/src/scenes/insights/insightModalsLogic.ts b/frontend/src/scenes/insights/insightModalsLogic.tsindex 0490b3553d8d..c9c3a38d12c6 100644--- a/frontend/src/scenes/insights/insightModalsLogic.ts+++ b/frontend/src/scenes/insights/insightModalsLogic.ts@@ -1,7 +1,8 @@-import { actions, kea, key, path, props, reducers } from 'kea'+import { actions, connect, kea, key, listeners, path, props, reducers } from 'kea'import { InsightLogicProps } from '~/types'+import { insightLogic } from './insightLogic'import type { insightModalsLogicType } from './insightModalsLogicType'import { keyForInsightLogicProps } from './sharedUtils'@@ -10,9 +11,14 @@ export const insightModalsLogic = kea<insightModalsLogicType>([key(keyForInsightLogicProps('new')),path((key) => ['scenes', 'insights', 'insightModalsLogic', key]),+ connect((props: InsightLogicProps) => ({+ actions: [insightLogic(props), ['saveInsight', 'saveInsightSuccess', 'saveInsightFailure']],+ })),+actions({openAddToDashboardModal: true,closeAddToDashboardModal: true,+ saveAndAddToDashboard: true,openTerraformModal: true,closeTerraformModal: true,}),@@ -25,6 +31,15 @@ export const insightModalsLogic = kea<insightModalsLogicType>([closeAddToDashboardModal: () => false,},],+ pendingAddToDashboardAfterSave: [+ false,+ {+ saveAndAddToDashboard: () => true,+ openAddToDashboardModal: () => false,+ closeAddToDashboardModal: () => false,+ saveInsightFailure: () => false,+ },+ ],isTerraformModalOpen: [false,{@@ -33,4 +48,20 @@ export const insightModalsLogic = kea<insightModalsLogicType>([},],}),++ listeners(({ actions, values }) => ({+ // Save first, then open the add-to-dashboard modal once the save lands. Opening it concurrently with the save+ // races the save response (which carries the pre-modal `dashboards` list) against the dashboard the user picks,+ // silently overwriting that addition. `pendingAddToDashboardAfterSave` carries the intent across the save, and+ // reducers run before listeners, so the flag must NOT be cleared on `saveInsightSuccess` itself — it is read+ // here and cleared by `openAddToDashboardModal`.+ saveAndAddToDashboard: () => {+ actions.saveInsight(false)+ },+ saveInsightSuccess: () => {+ if (values.pendingAddToDashboardAfterSave) {+ actions.openAddToDashboardModal()+ }+ },+ })),])