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(insights): give the insight Duplicate button loading and failure feedback (#86452)

Adam Bowker8cbbd40f273c
diff --git a/frontend/src/lib/components/Scenes/SceneDuplicate.tsx b/frontend/src/lib/components/Scenes/SceneDuplicate.tsx
index f91f61edcd4b..114b28b370ed 100644
--- a/frontend/src/lib/components/Scenes/SceneDuplicate.tsx
+++ b/frontend/src/lib/components/Scenes/SceneDuplicate.tsx
@@ -1,22 +1,25 @@
import { IconCopy } from '@posthog/icons'
+import { Spinner } from 'lib/lemon-ui/Spinner'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { SceneDataAttrKeyProps } from './utils'
interface SceneDuplicateProps extends SceneDataAttrKeyProps {
onClick: () => void
+ loading?: boolean
}
-export function SceneDuplicate({ dataAttrKey, onClick }: SceneDuplicateProps): JSX.Element {
+export function SceneDuplicate({ dataAttrKey, onClick, loading }: SceneDuplicateProps): JSX.Element {
return (
<ButtonPrimitive
menuItem
onClick={onClick}
+ disabled={loading}
data-attr={`${dataAttrKey}-duplicate-button`}
- tooltip="Duplicate resource"
+ tooltip={loading ? 'Duplicating…' : 'Duplicate resource'}
>
- <IconCopy />
+ {loading ? <Spinner textColored /> : <IconCopy />}
Duplicate
</ButtonPrimitive>
)
diff --git a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
index 3dd8f9bab4de..dc38a8b2676e 100644
--- a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
+++ b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
@@ -42,7 +42,7 @@ const RESOURCE_TYPE = 'insight'
export function InsightPanelActions({ insightLogicProps }: { insightLogicProps: InsightLogicProps }): JSX.Element {
const theInsightLogic = insightLogic(insightLogicProps)
- const { insightProps, insight, hasDashboardItemId } = useValues(theInsightLogic)
+ const { insightProps, insight, hasDashboardItemId, insightDuplicating } = useValues(theInsightLogic)
const { duplicateInsight, setInsightMetadata } = useActions(theInsightLogic)
const theInsightDataLogic = insightDataLogic(insightProps)
@@ -75,6 +75,7 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:
<ScenePanelActionsSection>
<SceneDuplicate
dataAttrKey={RESOURCE_TYPE}
+ loading={insightDuplicating}
onClick={() => duplicateInsight(insight as QueryBasedInsightModel, true)}
/>
{isSavedInsight && canCopyToProject && (
diff --git a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
index a4d97da4bd7f..361c685d9997 100644
--- a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
+++ b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
@@ -85,7 +85,8 @@ export function InsightSceneMenuBar({
function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: InsightLogicProps }): JSX.Element {
const theInsightLogic = insightLogic(insightLogicProps)
- const { insightProps, insight, hasDashboardItemId, canEditInsight, isSavingTags } = useValues(theInsightLogic)
+ const { insightProps, insight, hasDashboardItemId, canEditInsight, isSavingTags, insightDuplicating } =
+ useValues(theInsightLogic)
const { duplicateInsight, deleteInsight, setInsightMetadata } = useActions(theInsightLogic)
const theInsightDataLogic = insightDataLogic(insightProps)
@@ -340,6 +341,8 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: In
{showEditMenu && (
<SceneMenuBarMenu label="Edit" dataAttr={`${RESOURCE_TYPE}-menubar-edit`}>
<SceneMenuBarItem
+ disabled={insightDuplicating}
+ tooltip={insightDuplicating ? 'Duplicating…' : undefined}
onClick={() => duplicateInsight(insight as QueryBasedInsightModel, true)}
data-attr={`${RESOURCE_TYPE}-menubar-duplicate`}
>
diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.ts
index aab94d0be550..f30ac18ee265 100644
--- a/frontend/src/scenes/insights/insightLogic.test.ts
+++ b/frontend/src/scenes/insights/insightLogic.test.ts
@@ -2,8 +2,10 @@ import { MOCK_DEFAULT_TEAM, MOCK_TEAM_ID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic, partial, truth } from 'kea-test-utils'
+import posthog from 'posthog-js'
import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { objectsEqual } from 'lib/utils/objects'
import 'lib/constants'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
@@ -1044,6 +1046,50 @@ describe('insightLogic', () => {
await expectLogic(router).toNotHaveDispatchedActions(['push'])
})
+
+ it('marks the insight as duplicating until the request settles', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.duplicateInsight(logic.values.insight as QueryBasedInsightModel, true)
+ })
+ .toMatchValues({ insightDuplicating: true })
+ .toFinishAllListeners()
+ .toMatchValues({ insightDuplicating: false })
+ })
+
+ // Catching the rejection skips the gate `initKea` applies to loader failures, so the
+ // listener has to reapply it: a validation error is the app's own bug and stays
+ // reportable, while an access-denied 403 the AccessDenied scene already handles would
+ // file an issue sharing its stack with every other ApiError, burying real crashes.
+ it.each([
+ ['a validation error', 400, { detail: 'Insight limit reached' }, 1],
+ [
+ 'a failure the app recovers from',
+ 403,
+ { detail: 'You do not have permission', code: 'permission_denied' },
+ 0,
+ ],
+ ])(
+ 'toasts %s rather than doing nothing, and reports it only if it is worth filing',
+ async (_, status, body, timesReported) => {
+ useMocks({
+ post: {
+ '/api/environments/:team_id/insights/': () => [status, body],
+ },
+ })
+ jest.spyOn(lemonToast, 'error')
+ jest.spyOn(posthog, 'captureException')
+
+ await expectLogic(logic, () => {
+ logic.actions.duplicateInsight(logic.values.insight as QueryBasedInsightModel, true)
+ })
+ .toFinishAllListeners()
+ .toMatchValues({ insightDuplicating: false })
+
+ expect(lemonToast.error).toHaveBeenCalledWith(body.detail)
+ expect(posthog.captureException).toHaveBeenCalledTimes(timesReported)
+ await expectLogic(router).toNotHaveDispatchedActions(['push'])
+ }
+ )
})
describe('hasOverrides', () => {
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index 0e11604c14f0..0fd3ecac1098 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -19,7 +19,7 @@ import posthog from 'posthog-js'
import { LemonDialog, LemonInput } from '@posthog/lemon-ui'
import { ApiError } from 'lib/api'
-import { isTransientServerError } from 'lib/api-error'
+import { isTransientServerError, shouldReportApiFailure } from 'lib/api-error'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -120,6 +120,7 @@ export interface insightLogicValues {
highlightedSeries: IndexedTrendResult | null
insight: Partial<QueryBasedInsightModel<Node<Record<string, any>>>>
insightChanged: boolean
+ insightDuplicating: boolean
insightFeedback: 'disliked' | 'liked' | null
insightId: number | null
insightLoading: boolean
@@ -156,6 +157,9 @@ export interface insightLogicActions {
insight: QueryBasedInsightModel<Node<Record<string, any>>>
redirectToInsight: any
}
+ duplicateInsightComplete: () => {
+ value: true
+ }
handleInsightSuggested: (suggestedInsight: Node | null) => {
suggestedInsight: Node<Record<string, any>> | null
}
@@ -618,6 +622,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
insight,
redirectToInsight,
}),
+ duplicateInsightComplete: true,
deleteInsight: (dashboardId: number | null) => ({ dashboardId }),
confirmDeleteInsight: (dashboardId: number | null) => ({ dashboardId }),
setInsightFeedback: (feedback: 'liked' | 'disliked') => ({ feedback }),
@@ -747,6 +752,13 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
highlightSeries: (_, { series }) => series,
},
],
+ insightDuplicating: [
+ false,
+ {
+ duplicateInsight: () => true,
+ duplicateInsightComplete: () => false,
+ },
+ ],
insight: {
loadInsight: (state, { shortId }) =>
shortId === state.short_id
@@ -1250,22 +1262,37 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
}
},
duplicateInsight: async ({ insight, redirectToInsight }) => {
- let insightToDuplicate = insight
- if (insight.short_id) {
- try {
- const cleanInsight = await insightsApi.getByShortId(insight.short_id)
- if (cleanInsight) {
- insightToDuplicate = cleanInsight
+ try {
+ let insightToDuplicate = insight
+ if (insight.short_id) {
+ try {
+ const cleanInsight = await insightsApi.getByShortId(insight.short_id)
+ if (cleanInsight) {
+ insightToDuplicate = cleanInsight
+ }
+ } catch {
+ // Fall through to duplicate the original insight
}
- } catch {
- // Fall through to duplicate the original insight
}
+ const newInsight = await insightsApi.duplicate(insightToDuplicate)
+ for (const logic of savedInsightsLogic.findAllMounted()) {
+ logic.actions.addInsight(newInsight)
+ }
+ lemonToast.success('Insight duplicated')
+ redirectToInsight && router.actions.push(urls.insightEdit(newInsight.short_id))
+ } catch (e: any) {
+ // Nothing downstream reports this: the copy is created by a plain listener rather than
+ // a loader, so without a toast here a failure is indistinguishable from a dead button.
+ lemonToast.error(e.detail ?? 'Could not duplicate insight')
+ // Catching here also skips the gate `initKea` applies to loader failures, so reapply
+ // it: a recovered failure shares its stack with every other ApiError, so filing it
+ // buries the crashes worth seeing.
+ if (shouldReportApiFailure(e)) {
+ posthog.captureException(e)
+ }
+ } finally {
+ actions.duplicateInsightComplete()
}
- const newInsight = await insightsApi.duplicate(insightToDuplicate)
- for (const logic of savedInsightsLogic.findAllMounted()) {
- logic.actions.addInsight(newInsight)
- }
- redirectToInsight && router.actions.push(urls.insightEdit(newInsight.short_id))
},
deleteInsight: ({ dashboardId }) => {
LemonDialog.open({