: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(metrics): one-click starter dashboard for a service (#70851)
Daniel Viscad8f97606ec6f
diff --git a/products/metrics/frontend/components/MetricsStarterDashboardModal.tsx b/products/metrics/frontend/components/MetricsStarterDashboardModal.tsxnew file mode 100644index 000000000000..2df8d5e02a45--- /dev/null+++ b/products/metrics/frontend/components/MetricsStarterDashboardModal.tsx@@ -0,0 +1,92 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonInput, LemonInputSelect, LemonModal, LemonSelect } from '@posthog/lemon-ui'++import { metricOptionKey, metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'++export function MetricsStarterDashboardModal(): JSX.Element {+ const {+ isModalOpen,+ dashboardName,+ serviceName,+ selectedMetrics,+ services,+ servicesLoading,+ metricOptions,+ metricOptionsLoading,+ creating,+ } = useValues(metricsStarterDashboardLogic)+ const { closeModal, setDashboardName, setServiceName, setSelectedMetrics, createDashboard } =+ useActions(metricsStarterDashboardLogic)++ return (+ <LemonModal+ isOpen={isModalOpen}+ onClose={closeModal}+ closable={!creating}+ title="New service dashboard"+ description="One insight per metric, charted with its recommended aggregation."+ footer={+ <>+ <LemonButton+ type="secondary"+ onClick={closeModal}+ disabledReason={creating ? 'Creating…' : undefined}+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={createDashboard}+ loading={creating}+ disabledReason={+ !dashboardName.trim()+ ? 'Name the dashboard'+ : !selectedMetrics.length+ ? 'Pick at least one metric'+ : undefined+ }+ data-attr="metrics-starter-dashboard-create"+ >+ Create dashboard+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-3">+ <LemonInput+ value={dashboardName}+ onChange={setDashboardName}+ placeholder="Dashboard name, e.g. Billing worker"+ autoFocus+ data-attr="metrics-starter-dashboard-name"+ />+ <LemonSelect+ value={serviceName}+ onChange={(value) => setServiceName(value ?? '')}+ loading={servicesLoading}+ options={[+ { value: '', label: 'All services' },+ ...services.map((service) => ({ value: service, label: service })),+ ]}+ placeholder="Scope to a service"+ fullWidth+ data-attr="metrics-starter-dashboard-service"+ />+ <LemonInputSelect+ mode="multiple"+ value={selectedMetrics}+ onChange={setSelectedMetrics}+ loading={metricOptionsLoading}+ options={metricOptions.map((option) => ({+ // Composite key: the same name can exist under two OTel types.+ key: metricOptionKey(option.name, option.metric_type),+ label: `${option.name} (${option.metric_type})`,+ }))}+ placeholder="Pick the metrics to chart"+ data-attr="metrics-starter-dashboard-metrics"+ />+ </div>+ </LemonModal>+ )+}diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 34d1228277e4..3de5936e414b 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -43,6 +43,8 @@ import { metricNamePickerLogic } from './metricNamePickerLogic'import { MetricsChartLegend } from './MetricsChartLegend'import { metricsSamplesLogic } from './metricsSamplesLogic'import { MetricsSamplesPanel } from './MetricsSamplesPanel'+import { metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'+import { MetricsStarterDashboardModal } from './MetricsStarterDashboardModal'import { MetricStatPanel } from './MetricStatPanel'import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'import {@@ -118,6 +120,7 @@ export const MetricsViewer = (): JSX.Element => {// The side panel's logic listens to this viewer's filter changes; mounting it// here keeps samples in sync even while the panel itself is off-screen.useMountedLogic(metricsSamplesLogic())+ const { openModal: openStarterDashboardModal } = useActions(metricsStarterDashboardLogic)const {metricName,aggregation,@@ -375,7 +378,17 @@ export const MetricsViewer = (): JSX.Element => {>Add to dashboard</LemonButton>+ <LemonButton+ size="small"+ type="secondary"+ onClick={openStarterDashboardModal}+ tooltip="Create a dashboard with one insight per metric, using each metric's recommended aggregation"+ data-attr="metrics-viewer-starter-dashboard"+ >+ New service dashboard+ </LemonButton></div>+ <MetricsStarterDashboardModal />{savedInsight && (<AddToDashboardModalisOpen={isAddToDashboardModalOpen}diff --git a/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts b/products/metrics/frontend/components/metricsStarterDashboardLogic.test.tsnew file mode 100644index 000000000000..00a0b88b8caf--- /dev/null+++ b/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts@@ -0,0 +1,191 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { insightsApi } from 'scenes/insights/utils/api'++import { initKeaTests } from '~/test/init'++import { metricsAttributeValuesRetrieve, metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'++import { metricOptionKey, metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'++jest.mock('products/metrics/frontend/generated/api', () => ({+ ...jest.requireActual('products/metrics/frontend/generated/api'),+ metricsValuesRetrieve: jest.fn(),+ metricsAttributeValuesRetrieve: jest.fn(),+}))+jest.mock('scenes/insights/utils/api', () => ({+ insightsApi: { create: jest.fn() },+}))+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), warning: jest.fn(), error: jest.fn() },+}))++const mockNames = metricsValuesRetrieve as jest.MockedFunction<typeof metricsValuesRetrieve>+const mockValues = metricsAttributeValuesRetrieve as jest.MockedFunction<typeof metricsAttributeValuesRetrieve>+const mockInsightCreate = insightsApi.create as jest.MockedFunction<typeof insightsApi.create>++describe('metricsStarterDashboardLogic', () => {+ let logic: ReturnType<typeof metricsStarterDashboardLogic.build>+ let apiCreateSpy: jest.SpyInstance++ beforeEach(() => {+ initKeaTests()+ mockNames.mockReset()+ mockValues.mockReset()+ mockInsightCreate.mockReset()+ ;(lemonToast.success as jest.Mock).mockReset()+ ;(lemonToast.warning as jest.Mock).mockReset()+ ;(lemonToast.error as jest.Mock).mockReset()+ mockNames.mockResolvedValue({+ results: [+ { name: 'billing.invoices.processed', metric_type: 'sum' },+ { name: 'billing.queue.depth', metric_type: 'gauge' },+ { name: 'billing.job.duration', metric_type: 'histogram' },+ ],+ })+ mockValues.mockResolvedValue({+ results: [+ { id: 'billing-worker', name: 'billing-worker', count: 10 },+ { id: 'checkout', name: 'checkout', count: 5 },+ ],+ })+ mockInsightCreate.mockResolvedValue({ id: 101, short_id: 'abc' } as any)+ apiCreateSpy = jest.spyOn(api, 'create').mockResolvedValue({ id: 42, name: 'Billing' } as any)+ logic = metricsStarterDashboardLogic()+ logic.mount()+ })++ afterEach(() => {+ apiCreateSpy.mockRestore()+ logic?.unmount()+ })++ it('opening the modal loads the service and metric options', async () => {+ await expectLogic(logic, () => {+ logic.actions.openModal()+ }).toDispatchActions(['loadServicesSuccess', 'loadMetricOptionsSuccess'])++ expect(logic.values.services).toEqual(['billing-worker', 'checkout'])+ expect(logic.values.metricOptions).toHaveLength(3)+ })++ it('creates the dashboard, then one insight per metric with the recommended aggregation and service filter', async () => {+ logic.actions.openModal()+ await expectLogic(logic).toDispatchActions(['loadMetricOptionsSuccess'])+ logic.actions.setDashboardName('Billing service')+ logic.actions.setServiceName('billing-worker')+ logic.actions.setSelectedMetrics([+ metricOptionKey('billing.invoices.processed', 'sum'),+ metricOptionKey('billing.job.duration', 'histogram'),+ ])++ await expectLogic(logic, () => {+ logic.actions.createDashboard()+ }).toDispatchActions(['createDashboardSuccess'])++ expect(apiCreateSpy).toHaveBeenCalledTimes(1)+ expect(apiCreateSpy.mock.calls[0][1]).toEqual({ name: 'Billing service' })++ expect(mockInsightCreate).toHaveBeenCalledTimes(2)+ const [countInsight, histogramInsight] = mockInsightCreate.mock.calls.map(([insight]) => insight)+ expect(countInsight.dashboards).toEqual([42])+ expect(countInsight.query).toMatchObject({+ kind: 'MetricsQuery',+ clauses: [+ {+ name: 'a',+ metricName: 'billing.invoices.processed',+ aggregation: 'increase', // recommended for counters+ metricType: 'sum',+ filters: [{ key: 'service.name', op: 'eq', value: 'billing-worker' }],+ },+ ],+ })+ // The node schema has no 'p95' — the recommended shorthand maps to quantile + 0.95.+ expect(histogramInsight.query).toMatchObject({+ clauses: [expect.objectContaining({ aggregation: 'quantile', quantile: 0.95, metricType: 'histogram' })],+ })+ })++ it('navigates to the partially built dashboard when an insight create fails mid-loop', async () => {+ // The dashboard exists after a mid-loop failure — the flow must say so and go+ // there, not claim total failure and invite a duplicate-creating retry.+ logic.actions.openModal()+ await expectLogic(logic).toDispatchActions(['loadMetricOptionsSuccess'])+ logic.actions.setDashboardName('Billing service')+ logic.actions.setSelectedMetrics([+ metricOptionKey('billing.invoices.processed', 'sum'),+ metricOptionKey('billing.job.duration', 'histogram'),+ ])+ mockInsightCreate+ .mockResolvedValueOnce({ id: 101, short_id: 'abc' } as any)+ .mockRejectedValueOnce(new Error('boom'))++ await expectLogic(logic, () => {+ logic.actions.createDashboard()+ }).toDispatchActions(['createDashboardSuccess'])++ expect(apiCreateSpy).toHaveBeenCalledTimes(1)+ expect(logic.values.isModalOpen).toBe(false)+ // Partial failure surfaces exactly one toast: the warning, not the success.+ expect(lemonToast.warning).toHaveBeenCalledTimes(1)+ expect((lemonToast.warning as jest.Mock).mock.calls[0][0]).toContain('only 1 of 2 insights')+ expect(lemonToast.success).not.toHaveBeenCalled()+ })++ it('keeps the picked type when the same metric name exists under two OTel types', async () => {+ mockNames.mockResolvedValue({+ results: [+ { name: 'billing.throughput', metric_type: 'sum' },+ { name: 'billing.throughput', metric_type: 'gauge' },+ ],+ })+ logic.actions.openModal()+ await expectLogic(logic).toDispatchActions(['loadMetricOptionsSuccess'])+ logic.actions.setDashboardName('Billing service')+ logic.actions.setSelectedMetrics([metricOptionKey('billing.throughput', 'sum')])++ await expectLogic(logic, () => {+ logic.actions.createDashboard()+ }).toDispatchActions(['createDashboardSuccess'])++ // Name-keyed lookup would collapse to the last-listed type (gauge/avg).+ const [insight] = mockInsightCreate.mock.calls[0]+ expect((insight.query as any).clauses[0]).toMatchObject({+ metricName: 'billing.throughput',+ metricType: 'sum',+ aggregation: 'increase',+ })+ })++ it('drops non-enum metric types instead of sending raw ingest strings', async () => {+ mockNames.mockResolvedValue({ results: [{ name: 'legacy.metric', metric_type: 'counter' }] })+ logic.actions.openModal()+ await expectLogic(logic).toDispatchActions(['loadMetricOptionsSuccess'])+ logic.actions.setDashboardName('Legacy')+ logic.actions.setSelectedMetrics([metricOptionKey('legacy.metric', 'counter')])++ await expectLogic(logic, () => {+ logic.actions.createDashboard()+ }).toDispatchActions(['createDashboardSuccess'])++ const [insight] = mockInsightCreate.mock.calls[0]+ expect((insight.query as any).clauses[0].metricType).toBeUndefined()+ })++ it('guards against double submission while the create is in flight', async () => {+ logic.actions.openModal()+ await expectLogic(logic).toDispatchActions(['loadMetricOptionsSuccess'])+ logic.actions.setDashboardName('Billing service')+ logic.actions.setSelectedMetrics([metricOptionKey('billing.queue.depth', 'gauge')])++ await expectLogic(logic, () => {+ logic.actions.createDashboard()+ logic.actions.createDashboard()+ }).toDispatchActions(['createDashboardSuccess'])++ expect(apiCreateSpy).toHaveBeenCalledTimes(1)+ })+})diff --git a/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsxnew file mode 100644index 000000000000..923ac2f04911--- /dev/null+++ b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx@@ -0,0 +1,270 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { insightsApi } from 'scenes/insights/utils/api'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { NodeKind } from '~/queries/schema/schema-general'+import type { MetricsQuery, MetricsQueryClause } from '~/queries/schema/schema-general'+import type { DashboardType } from '~/types'++import { metricsAttributeValuesRetrieve, metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'+import type { _MetricNameApi } from 'products/metrics/frontend/generated/api.schemas'++import type { InsightModel } from '../../../../frontend/src/types'+import { RECOMMENDED_AGGREGATION_BY_TYPE, toKnownMetricType } from './metricsViewerLogic'++// A metric name can appear under more than one OTel type, so option identity+// must include both. \0 can't occur in ingest strings, so the key is collision-free.+export const metricOptionKey = (name: string, metricType: string): string => `${name}\0${metricType}`++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsStarterDashboardLogicValues {+ currentTeamId: number | null // teamLogic+ creating: boolean+ dashboardName: string+ isModalOpen: boolean+ metricOptions: _MetricNameApi[]+ metricOptionsLoading: boolean+ selectedMetrics: string[]+ serviceName: string+ services: string[]+ servicesLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsStarterDashboardLogicActions {+ closeModal: () => {+ value: true+ }+ createDashboard: () => {+ value: true+ }+ createDashboardFailure: (message: string) => {+ message: string+ }+ createDashboardSuccess: (+ createdDashboard: DashboardType,+ warning?: string+ ) => {+ createdDashboard: DashboardType<InsightModel>+ warning: string | undefined+ }+ loadMetricOptions: (_: any) => any+ loadMetricOptionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadMetricOptionsSuccess: (+ metricOptions: _MetricNameApi[],+ payload?: any+ ) => {+ metricOptions: _MetricNameApi[]+ payload?: any+ }+ loadServices: (_: any) => any+ loadServicesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadServicesSuccess: (+ services: string[],+ payload?: any+ ) => {+ services: string[]+ payload?: any+ }+ openModal: () => {+ value: true+ }+ setDashboardName: (dashboardName: string) => {+ dashboardName: string+ }+ setSelectedMetrics: (selectedMetrics: string[]) => {+ selectedMetrics: string[]+ }+ setServiceName: (serviceName: string) => {+ serviceName: string+ }+}++export type metricsStarterDashboardLogicType = MakeLogicType<+ metricsStarterDashboardLogicValues,+ metricsStarterDashboardLogicActions+>++// One dashboard, one insight per picked metric, each charted with the+// aggregation its type recommends and scoped to the picked service — the+// onboarding doc's starter set, productized.+export const metricsStarterDashboardLogic = kea<metricsStarterDashboardLogicType>([+ path(['products', 'metrics', 'frontend', 'components', 'metricsStarterDashboardLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),+ actions({+ openModal: true,+ closeModal: true,+ setDashboardName: (dashboardName: string) => ({ dashboardName }),+ setServiceName: (serviceName: string) => ({ serviceName }),+ // selectedMetrics holds metricOptionKey() composites, not bare names.+ setSelectedMetrics: (selectedMetrics: string[]) => ({ selectedMetrics }),+ createDashboard: true,+ createDashboardSuccess: (createdDashboard: DashboardType, warning?: string) => ({ createdDashboard, warning }),+ createDashboardFailure: (message: string) => ({ message }),+ }),+ reducers({+ isModalOpen: [false, { openModal: () => true, closeModal: () => false }],+ // The whole form resets on close so a reopen can't silently mint a near-duplicate.+ dashboardName: [+ '' as string,+ { setDashboardName: (_, { dashboardName }) => dashboardName, closeModal: () => '' },+ ],+ // '' = all services: the insights get no service filter.+ serviceName: ['' as string, { setServiceName: (_, { serviceName }) => serviceName, closeModal: () => '' }],+ selectedMetrics: [+ [] as string[],+ { setSelectedMetrics: (_, { selectedMetrics }) => selectedMetrics, closeModal: () => [] },+ ],+ // Drives the create button's loading/disabled state so a double click can't+ // fire twice; the listener's cache flag is the authoritative in-flight guard.+ creating: [+ false,+ {+ createDashboard: () => true,+ createDashboardSuccess: () => false,+ createDashboardFailure: () => false,+ },+ ],+ }),+ loaders(({ values }) => ({+ services: [+ [] as string[],+ {+ loadServices: async (_, breakpoint) => {+ await breakpoint(100)+ const response = await metricsAttributeValuesRetrieve(String(values.currentTeamId), {+ key: 'service.name',+ })+ breakpoint()+ return response.results.map((value) => value.name)+ },+ },+ ],+ metricOptions: [+ [] as _MetricNameApi[],+ {+ loadMetricOptions: async (_, breakpoint) => {+ await breakpoint(100)+ const response = await metricsValuesRetrieve(String(values.currentTeamId), {})+ breakpoint()+ return response.results+ },+ },+ ],+ })),+ listeners(({ actions, values, cache }) => ({+ openModal: () => {+ actions.loadServices({})+ actions.loadMetricOptions({})+ },+ createDashboard: async () => {+ // kea-loaders doesn't dedupe concurrent runs, so the create is a plain+ // listener with an explicit in-flight guard.+ if (cache.creatingDashboard) {+ return+ }+ cache.creatingDashboard = true+ // Snapshot the form before the first await: a modal dismissed or edited+ // mid-create must not change (or empty) what gets created.+ const name = values.dashboardName.trim()+ const selectedMetrics = [...values.selectedMetrics]+ const serviceName = values.serviceName+ const optionByKey: Record<string, _MetricNameApi> = Object.fromEntries(+ values.metricOptions.map((option) => [metricOptionKey(option.name, option.metric_type), option])+ )+ // Resolve keys to options up front so a name shared by two OTel types+ // keeps the type the user actually picked.+ const pickedMetrics: _MetricNameApi[] = selectedMetrics.map(+ (key) => optionByKey[key] ?? { name: key, metric_type: '' }+ )+ let dashboard: DashboardType | null = null+ let created = 0+ try {+ if (!name || !selectedMetrics.length) {+ actions.createDashboardFailure('Pick a dashboard name and at least one metric')+ return+ }+ // The core dashboards create endpoint has no generated client yet+ // (only its sharing sub-resources are in the codegen surface), so this+ // stays a manual call until the Dashboard viewset is tagged.+ // nosemgrep: prefer-codegen-api+ dashboard = await api.create<DashboardType>(`api/projects/${values.currentTeamId}/dashboards/`, {+ name,+ })+ for (const { name: metricName, metric_type: rawType } of pickedMetrics) {+ // The names endpoint reports raw ingest strings; only enum members+ // may reach the API — mirrors the viewer's metricsQueryNode.+ const metricType = toKnownMetricType(rawType)+ const recommended = (rawType && RECOMMENDED_AGGREGATION_BY_TYPE[rawType]) || 'avg'+ const clause: MetricsQueryClause = {+ name: 'a',+ metricName,+ // The REST viewer's 'p95' shorthand maps to the node's quantile aggregation.+ aggregation: recommended === 'p95' ? 'quantile' : recommended,+ ...(recommended === 'p95' ? { quantile: 0.95 } : {}),+ ...(metricType ? { metricType } : {}),+ ...(serviceName+ ? { filters: [{ key: 'service.name', op: 'eq' as const, value: serviceName }] }+ : {}),+ }+ const query: MetricsQuery = { kind: NodeKind.MetricsQuery, clauses: [clause] }+ await insightsApi.create({+ name: `${metricName} (${recommended})`,+ saved: true,+ dashboards: [dashboard.id],+ query,+ })+ created+++ }+ actions.createDashboardSuccess(dashboard)+ } catch (error: any) {+ if (dashboard) {+ // The dashboard exists with a partial insight set — say so and take+ // the user there rather than implying nothing happened (a retry+ // from the modal would mint a duplicate dashboard). The warning+ // replaces the success toast so only one shows.+ actions.createDashboardSuccess(+ dashboard,+ `Dashboard "${dashboard.name}" created, but only ${created} of ${selectedMetrics.length} insights could be added`+ )+ } else {+ actions.createDashboardFailure(error?.detail || error?.message || 'Failed to create the dashboard')+ }+ } finally {+ cache.creatingDashboard = false+ }+ },+ createDashboardSuccess: ({ createdDashboard, warning }) => {+ actions.closeModal()+ if (warning) {+ lemonToast.warning(warning)+ } else {+ lemonToast.success(`Dashboard "${createdDashboard.name}" created`)+ }+ router.actions.push(urls.dashboard(createdDashboard.id))+ },+ createDashboardFailure: ({ message }) => {+ lemonToast.error(message)+ },+ })),+])diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex 79c1173a1698..adf52b0369fc 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -147,7 +147,7 @@ export const resolveDate = (value: string | null | undefined): string | null =>}// The picker reports raw ingest strings; only enum members may reach the API.-const toKnownMetricType = (metricType: string | undefined): OtelMetricTypeEnumApi | null => {+export const toKnownMetricType = (metricType: string | undefined): OtelMetricTypeEnumApi | null => {const known = Object.values(OtelMetricTypeEnumApi) as string[]return metricType && known.includes(metricType) ? (metricType as OtelMetricTypeEnumApi) : null}