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.

feat(data-catalog): create a metric from a saved insight (#73986)

Thiago Salvatorede14fa320b9a
diff --git a/frontend/src/scenes/insights/InsightModals.tsx b/frontend/src/scenes/insights/InsightModals.tsx
index 76f6defff467..34e19df5959a 100644
--- a/frontend/src/scenes/insights/InsightModals.tsx
+++ b/frontend/src/scenes/insights/InsightModals.tsx
@@ -4,7 +4,9 @@ import { router } from 'kea-router'
import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboardModal'
import { SharingModal } from 'lib/components/Sharing/SharingModal'
import { TerraformExportModal } from 'lib/components/TerraformExporter/TerraformExportModal'
+import { FEATURE_FLAGS } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -17,6 +19,7 @@ import { InsightLogicProps, InsightShortId, ItemMode } from '~/types'
import { areAlertsSupportedForInsight } from 'products/alerts/frontend/logic/insightAlertsLogic'
import { EditAlertModal } from 'products/alerts/frontend/views/EditAlertModal'
import { ManageAlertsModal } from 'products/alerts/frontend/views/ManageAlertsModal'
+import { MetricFromInsightModal } from 'products/data_catalog/frontend/components/MetricFromInsightModal'
import { EndpointFromInsightModal } from 'products/endpoints/frontend/EndpointFromInsightModal'
import { SubscriptionsModal } from 'products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal'
@@ -35,6 +38,7 @@ export function InsightModals({ insightLogicProps }: { insightLogicProps: Insigh
<InsightAlertsModals insightLogicProps={insightLogicProps} />
<NewDashboardModal />
<InsightEndpointModalWrapper insightLogicProps={insightLogicProps} />
+ <InsightMetricModalWrapper insightLogicProps={insightLogicProps} />
</>
)}
@@ -175,3 +179,23 @@ function InsightEndpointModalWrapper({ insightLogicProps }: { insightLogicProps:
/>
)
}
+
+function InsightMetricModalWrapper({
+ insightLogicProps,
+}: {
+ insightLogicProps: InsightLogicProps
+}): JSX.Element | null {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { insight } = useValues(insightLogic(insightLogicProps))
+
+ if (!featureFlags[FEATURE_FLAGS.PRODUCT_DATA_CATALOG]) {
+ return null
+ }
+
+ return (
+ <MetricFromInsightModal
+ insightShortId={insight.short_id}
+ insightName={insight.name || insight.derived_name || undefined}
+ />
+ )
+}
diff --git a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
index baf39595cef1..79ac746cc907 100644
--- a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
+++ b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { IconCode2, IconCopy, IconEndpoints, IconPencil, IconPeople } from '@posthog/icons'
+import { IconCode2, IconCopy, IconEndpoints, IconGraph, IconPencil, IconPeople } from '@posthog/icons'
import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { SceneAddToDashboardButton } from 'lib/components/Scenes/InsightOrDashboard/SceneAddToDashboardButton'
@@ -34,6 +34,7 @@ import {
QueryBasedInsightModel,
} from '~/types'
+import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
import { endpointLogic } from 'products/endpoints/frontend/endpointLogic'
import { insightModalsLogic } from '../insightModalsLogic'
@@ -191,6 +192,10 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:
</ButtonPrimitive>
) : null}
+ {featureFlags[FEATURE_FLAGS.PRODUCT_DATA_CATALOG] ? (
+ <CreateMetricFromInsightButton isSavedInsight={isSavedInsight} insightShortId={insight?.short_id} />
+ ) : null}
+
{canEditInSqlEditor && (
<Link
to={urls.sqlEditor({ query: hogQL ?? undefined })}
@@ -219,3 +224,32 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:
</ScenePanelActionsSection>
)
}
+
+function CreateMetricFromInsightButton({
+ isSavedInsight,
+ insightShortId,
+}: {
+ isSavedInsight: boolean
+ insightShortId?: string
+}): JSX.Element | null {
+ const { openMetricFromInsightModal } = useActions(metricsLogic)
+ const { allMetrics } = useValues(metricsLogic)
+
+ // A metric already snapshots this insight, so don't offer to create a duplicate.
+ if (insightShortId && allMetrics.some((metric) => metric.source_insight_short_id === insightShortId)) {
+ return null
+ }
+
+ return (
+ <ButtonPrimitive
+ onClick={openMetricFromInsightModal}
+ menuItem
+ disabledReasons={{
+ 'You must save the insight first before creating a metric from it': !isSavedInsight,
+ }}
+ >
+ <IconGraph />
+ Create metric
+ </ButtonPrimitive>
+ )
+}
diff --git a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
index bb8c5f04d03c..c4df536e7f6c 100644
--- a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
+++ b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
@@ -7,6 +7,7 @@ import {
IconCopy,
IconDownload,
IconEndpoints,
+ IconGraph,
IconPencil,
IconPeople,
IconPlusSmall,
@@ -60,6 +61,7 @@ import {
SidePanelTab,
} from '~/types'
+import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
import { endpointLogic } from 'products/endpoints/frontend/endpointLogic'
import { urlForSubscriptions } from 'products/subscriptions/frontend/components/Subscriptions/utils'
@@ -148,9 +150,11 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: In
featureFlags[FEATURE_FLAGS.ENDPOINTS] &&
isSavedInsight &&
!getAccessControlDisabledReason(AccessControlResourceType.Endpoint, AccessControlLevel.Editor)
+ const showCreateMetric = !!featureFlags[FEATURE_FLAGS.PRODUCT_DATA_CATALOG] && isSavedInsight
const showAddToNotebook = isSavedInsight
const showCreateMenu =
showCreateEndpoint ||
+ showCreateMetric ||
showCohort ||
isSavedInsight /* add-to-dashboard, add-to-notebook, subscribe, alerts, share */
const showMetadataMenu = true // tags + activity always shown
@@ -200,6 +204,7 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: In
Endpoint
</SceneMenuBarItem>
)}
+ {showCreateMetric && <CreateMetricMenuBarItem insightShortId={insight?.short_id} />}
{showCohort && (
<SceneMenuBarItem
opensFloatingUi
@@ -420,3 +425,24 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: In
</SceneMenuBar>
)
}
+
+function CreateMetricMenuBarItem({ insightShortId }: { insightShortId?: string }): JSX.Element | null {
+ const { openMetricFromInsightModal } = useActions(metricsLogic)
+ const { allMetrics } = useValues(metricsLogic)
+
+ // A metric already snapshots this insight, so don't offer to create a duplicate.
+ if (insightShortId && allMetrics.some((metric) => metric.source_insight_short_id === insightShortId)) {
+ return null
+ }
+
+ return (
+ <SceneMenuBarItem
+ opensFloatingUi
+ onClick={openMetricFromInsightModal}
+ data-attr={`${RESOURCE_TYPE}-menubar-create-metric`}
+ >
+ <IconGraph />
+ Metric
+ </SceneMenuBarItem>
+ )
+}
diff --git a/products/data_catalog/frontend/components/MetricFromInsightModal.tsx b/products/data_catalog/frontend/components/MetricFromInsightModal.tsx
new file mode 100644
index 000000000000..22c5e7a10ca8
--- /dev/null
+++ b/products/data_catalog/frontend/components/MetricFromInsightModal.tsx
@@ -0,0 +1,138 @@
+import { useActions, useValues } from 'kea'
+import { useMemo, useState } from 'react'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { LemonTable } from 'lib/lemon-ui/LemonTable'
+import { Link } from 'lib/lemon-ui/Link'
+import { slugify } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
+
+import { validateMetricName } from '../common'
+import { metricsLogic } from '../metricsLogic'
+
+export interface MetricFromInsightModalProps {
+ insightShortId?: string
+ insightName?: string
+}
+
+export function MetricFromInsightModal({ insightShortId, insightName }: MetricFromInsightModalProps): JSX.Element {
+ const { metricFromInsightModalOpen, isCreatingMetric, allMetrics } = useValues(metricsLogic)
+ const { createMetricFromInsight, closeMetricFromInsightModal } = useActions(metricsLogic)
+
+ const [name, setName] = useState('')
+ const [displayName, setDisplayName] = useState('')
+ const [description, setDescription] = useState('')
+
+ const prefilledName = useMemo(() => slugify(insightName || '').replace(/-/g, '_'), [insightName])
+ const effectiveName = name || prefilledName
+ const nameError = validateMetricName(effectiveName)
+
+ const metricsFromThisInsight = insightShortId
+ ? allMetrics.filter((metric) => metric.source_insight_short_id === insightShortId)
+ : []
+
+ const submitDisabledReason = !insightShortId
+ ? 'Save the insight first'
+ : nameError
+ ? nameError
+ : !description.trim()
+ ? 'Add a description'
+ : undefined
+
+ const handleClose = (): void => {
+ setName('')
+ setDisplayName('')
+ setDescription('')
+ closeMetricFromInsightModal()
+ }
+
+ const handleSubmit = (): void => {
+ if (submitDisabledReason || !insightShortId) {
+ return
+ }
+ createMetricFromInsight({
+ name: effectiveName,
+ display_name: displayName.trim(),
+ description: description.trim(),
+ source_insight_short_id: insightShortId,
+ })
+ }
+
+ return (
+ <LemonModal
+ isOpen={metricFromInsightModalOpen}
+ onClose={handleClose}
+ width={560}
+ title="Create metric from insight"
+ >
+ <LemonModal.Content>
+ <div className="flex flex-col gap-4">
+ {metricsFromThisInsight.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <span className="text-secondary">Metrics already created from this insight</span>
+ <LemonTable
+ dataSource={metricsFromThisInsight}
+ columns={[
+ {
+ title: 'Name',
+ key: 'name',
+ render: (_, metric) => (
+ <Link to={urls.dataCatalogMetric(metric.name)}>
+ {metric.display_name || metric.name}
+ </Link>
+ ),
+ },
+ ]}
+ size="small"
+ embedded
+ />
+ </div>
+ )}
+
+ <LemonField.Pure
+ label="Name"
+ error={effectiveName ? nameError : undefined}
+ info="A unique identifier for the metric, like monthly_active_users."
+ >
+ <LemonInput
+ value={effectiveName}
+ onChange={setName}
+ placeholder="monthly_active_users"
+ autoFocus
+ />
+ </LemonField.Pure>
+
+ <LemonField.Pure label="Display name">
+ <LemonInput value={displayName} onChange={setDisplayName} placeholder="Monthly active users" />
+ </LemonField.Pure>
+
+ <LemonField.Pure label="Description">
+ <LemonInput
+ value={description}
+ onChange={setDescription}
+ placeholder="What this metric measures and how to read it"
+ />
+ </LemonField.Pure>
+ </div>
+ </LemonModal.Content>
+
+ <LemonModal.Footer>
+ <LemonButton type="secondary" onClick={handleClose} disabled={isCreatingMetric}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={handleSubmit}
+ loading={isCreatingMetric}
+ disabledReason={submitDisabledReason}
+ data-attr="data-catalog-create-metric-from-insight-submit"
+ >
+ Create metric
+ </LemonButton>
+ </LemonModal.Footer>
+ </LemonModal>
+ )
+}
diff --git a/products/data_catalog/frontend/metricsLogic.test.ts b/products/data_catalog/frontend/metricsLogic.test.ts
index aea6e54eb9c4..d9e5bcc4084c 100644
--- a/products/data_catalog/frontend/metricsLogic.test.ts
+++ b/products/data_catalog/frontend/metricsLogic.test.ts
@@ -139,4 +139,25 @@ describe('metricsLogic', () => {
expect(logic.values.allMetrics).toHaveLength(0)
})
+
+ it('creates a metric from an insight with the short id and no definition', async () => {
+ ;(dataCatalogMetricsCreate as jest.Mock).mockResolvedValue(
+ buildMetric({ id: 'metric-3', name: 'from_insight', source_insight_short_id: 'abc123' })
+ )
+
+ logic.actions.openMetricFromInsightModal()
+ logic.actions.createMetricFromInsight({
+ name: 'from_insight',
+ display_name: '',
+ description: 'Snapshotted from an insight',
+ source_insight_short_id: 'abc123',
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ const body = (dataCatalogMetricsCreate as jest.Mock).mock.calls.at(-1)?.[1]
+ expect(body.source_insight_short_id).toEqual('abc123')
+ expect(body.definition).toBeUndefined()
+ expect(logic.values.metricFromInsightModalOpen).toEqual(false)
+ expect(logic.values.allMetrics.map((metric) => metric.name)).toContain('from_insight')
+ })
})
diff --git a/products/data_catalog/frontend/metricsLogic.tsx b/products/data_catalog/frontend/metricsLogic.tsx
index 05628e94d61b..7959b7750a8a 100644
--- a/products/data_catalog/frontend/metricsLogic.tsx
+++ b/products/data_catalog/frontend/metricsLogic.tsx
@@ -55,6 +55,13 @@ export interface SavedInsightOption {
label: string
}
+export interface MetricFromInsightRequest {
+ name: string
+ display_name: string
+ description: string
+ source_insight_short_id: string
+}
+
const MARKDOWN_DEFINITION_KIND = 'MarkdownDefinition'
function projectId(): string {
@@ -77,6 +84,7 @@ export interface metricsLogicValues {
filters: MetricsFilters
insightSearch: string
isCreatingMetric: boolean
+ metricFromInsightModalOpen: boolean
metrics: DataCatalogMetricApi[]
newMetricForm: NewMetricForm
newMetricModalOpen: boolean
@@ -90,12 +98,18 @@ export interface metricsLogicActions {
approveMetric: (name: string) => {
name: string
}
+ closeMetricFromInsightModal: () => {
+ value: true
+ }
closeNewMetricModal: () => {
value: true
}
createMetric: () => {
value: true
}
+ createMetricFromInsight: (request: MetricFromInsightRequest) => {
+ request: MetricFromInsightRequest
+ }
deleteMetric: (name: string) => {
name: string
}
@@ -141,6 +155,9 @@ export interface metricsLogicActions {
value: true
}
}
+ openMetricFromInsightModal: () => {
+ value: true
+ }
openNewMetricModal: () => {
value: true
}
@@ -202,6 +219,9 @@ export const metricsLogic = kea<metricsLogicType>([
refreshMetricFromInsight: (name: string) => ({ name }),
deleteMetric: (name: string) => ({ name }),
setActionInFlight: (name: string, inFlight: boolean) => ({ name, inFlight }),
+ openMetricFromInsightModal: true,
+ closeMetricFromInsightModal: true,
+ createMetricFromInsight: (request: MetricFromInsightRequest) => ({ request }),
}),
loaders(({ values }) => ({
allMetrics: [
@@ -264,6 +284,13 @@ export const metricsLogic = kea<metricsLogicType>([
setCreatingMetric: (_, { creating }) => creating,
},
],
+ metricFromInsightModalOpen: [
+ false,
+ {
+ openMetricFromInsightModal: () => true,
+ closeMetricFromInsightModal: () => false,
+ },
+ ],
actionsInFlight: [
{} as Record<string, boolean>,
{
@@ -342,6 +369,32 @@ export const metricsLogic = kea<metricsLogicType>([
actions.setCreatingMetric(false)
}
},
+ createMetricFromInsight: async ({ request }) => {
+ if (values.isCreatingMetric) {
+ return
+ }
+ actions.setCreatingMetric(true)
+ try {
+ const created = await dataCatalogMetricsCreate(projectId(), {
+ name: request.name,
+ display_name: request.display_name || undefined,
+ description: request.description,
+ source_insight_short_id: request.source_insight_short_id,
+ })
+ actions.loadMetricsSuccess([created, ...values.allMetrics])
+ actions.closeMetricFromInsightModal()
+ lemonToast.success('Metric created from insight', {
+ button: {
+ label: 'View metric',
+ action: () => router.actions.push(urls.dataCatalogMetric(created.name)),
+ },
+ })
+ } catch (error) {
+ lemonToast.error(apiErrorDetail(error) || 'Could not create the metric from this insight. Try again.')
+ } finally {
+ actions.setCreatingMetric(false)
+ }
+ },
approveMetric: async ({ name }) => {
if (values.actionsInFlight[name]) {
return