: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): record a product intent when an agent snippet is copied (#75200)
Daniel Viscaf640448aa67e
diff --git a/frontend/src/lib/components/CodeSnippet/CodeSnippet.test.tsx b/frontend/src/lib/components/CodeSnippet/CodeSnippet.test.tsxnew file mode 100644index 000000000000..1226fe75ee46--- /dev/null+++ b/frontend/src/lib/components/CodeSnippet/CodeSnippet.test.tsx@@ -0,0 +1,34 @@+import { act, fireEvent, render } from '@testing-library/react'++import { copyToClipboard } from 'lib/utils/copyToClipboard'++import { CodeSnippet } from './CodeSnippet'++jest.mock('lib/utils/copyToClipboard', () => ({+ copyToClipboard: jest.fn(),+}))++describe('CodeSnippet', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ })++ // Callers hang telemetry off onCopy (capture events, product intents that mark adoption), so+ // firing it when copyToClipboard reported failure records a copy the user never got. That+ // happens for real: without navigator.clipboard (plain HTTP) or with the write denied,+ // copyToClipboard toasts the error and resolves false.+ it.each([+ ['reaches the clipboard', true, 1],+ ['fails to reach the clipboard', false, 0],+ ])('calls onCopy only when the snippet %s', async (_description, copied, expectedCalls) => {+ jest.mocked(copyToClipboard).mockResolvedValue(copied)+ const onCopy = jest.fn()+ const { container } = render(<CodeSnippet onCopy={onCopy}>echo hello</CodeSnippet>)++ fireEvent.click(container.querySelector('[data-attr="copy-code-button"]')!)+ await act(async () => {})++ expect(copyToClipboard).toHaveBeenCalledWith('echo hello', 'snippet')+ expect(onCopy).toHaveBeenCalledTimes(expectedCalls)+ })+})diff --git a/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx b/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsxindex 2d63fa0b75c0..c625f09a14f2 100644--- a/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx+++ b/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx@@ -125,7 +125,10 @@ export interface CodeSnippetProps {thing?: string/** If set, the snippet becomes expandable when there's more than this number of lines. */maxLinesWithoutExpansion?: number- /** Called after the snippet contents are copied to the clipboard. Useful for telemetry. */+ /**+ * Called after the snippet contents reach the clipboard. Useful for telemetry. Not called when+ * the copy fails, so it is safe to treat as a successful copy.+ */onCopy?: () => void}@@ -162,8 +165,15 @@ export const CodeSnippet = React.memo(function CodeSnippet({onClick={(e) => {if (text) {e.stopPropagation()- void copyToClipboard(text, thing)- onCopy?.()+ // Only report a copy the user actually got: copyToClipboard resolves+ // false when the clipboard is unavailable (no navigator.clipboard over+ // plain HTTP) or the write is denied, and callers treat onCopy as+ // evidence of a successful copy.+ void copyToClipboard(text, thing).then((copied) => {+ if (copied) {+ onCopy?.()+ }+ })}}}size={compact ? 'small' : 'medium'}diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 682529f70212..9ca66e1aedf4 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -35115,6 +35115,7 @@"metrics_sql_query_run","metrics_query_saved","metrics_first_ingested",+ "metrics_scrape_agent_snippet_copied","taxonomic filter empty state","create_experiment_from_funnel_button","web_analytics_insight",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 84c41fccde18..f286bceac0c0 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -8859,6 +8859,7 @@ export enum ProductIntentContext {METRICS_SQL_QUERY_RUN = 'metrics_sql_query_run',METRICS_QUERY_SAVED = 'metrics_query_saved',METRICS_FIRST_INGESTED = 'metrics_first_ingested',+ METRICS_SCRAPE_AGENT_SNIPPET_COPIED = 'metrics_scrape_agent_snippet_copied',// Product AnalyticsTAXONOMIC_FILTER_EMPTY_STATE = 'taxonomic filter empty state',diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 2d250422f61c..6f183a990965 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3325,6 +3325,7 @@ class ProductIntentContext(StrEnum):METRICS_SQL_QUERY_RUN = "metrics_sql_query_run"METRICS_QUERY_SAVED = "metrics_query_saved"METRICS_FIRST_INGESTED = "metrics_first_ingested"+ METRICS_SCRAPE_AGENT_SNIPPET_COPIED = "metrics_scrape_agent_snippet_copied"TAXONOMIC_FILTER_EMPTY_STATE = "taxonomic filter empty state"CREATE_EXPERIMENT_FROM_FUNNEL_BUTTON = "create_experiment_from_funnel_button"WEB_ANALYTICS_INSIGHT = "web_analytics_insight"diff --git a/products/metrics/frontend/components/MetricsSetupPrompt.tsx b/products/metrics/frontend/components/MetricsSetupPrompt.tsxindex c34dca5414d4..2d9dc4a394ca 100644--- a/products/metrics/frontend/components/MetricsSetupPrompt.tsx+++ b/products/metrics/frontend/components/MetricsSetupPrompt.tsx@@ -1,13 +1,15 @@import { useActions, useValues } from 'kea'import posthog from 'posthog-js'-import { useEffect } from 'react'+import { useEffect, useState } from 'react'import * as greekPng from '@posthog/brand/hoggies/png/greek'-import { LemonButton, Link, Spinner } from '@posthog/lemon-ui'+import { LemonButton, LemonTabs, Link, Spinner } from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'import { useInterval } from 'lib/hooks/useInterval'+import { apiHostOrigin } from 'lib/utils/apiHost'import { teamLogic } from 'scenes/teamLogic'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'@@ -49,8 +51,10 @@ export const MetricsSetupPrompt = ({const NoMetricsPrompt = ({ className }: { className?: string }): JSX.Element | null => {const { addProductIntent } = useActions(teamLogic)+ const { currentTeam } = useValues(teamLogic)const { hasMetrics } = useValues(metricsIngestionLogic)- const { loadTeamHasMetrics } = useActions(metricsIngestionLogic)+ const { loadTeamHasMetrics, reportScrapeSnippetCopied } = useActions(metricsIngestionLogic)+ const [agentTab, setAgentTab] = useState<'docker' | 'kubernetes'>('docker')useEffect(() => {posthog.capture('metrics setup prompt viewed')@@ -70,6 +74,25 @@ const NoMetricsPrompt = ({ className }: { className?: string }): JSX.Element | n})}+ const apiKey = currentTeam?.api_token ?? '<your project API key>'+ const dockerSnippet = [+ 'docker run -d --name posthog-metrics-agent \\',+ ` -e POSTHOG_API_KEY=${apiKey} \\`,+ ` -e POSTHOG_HOST=${apiHostOrigin()} \\`,+ ' -e SCRAPE_TARGETS=your-app:9090 \\',+ ' posthog/metrics-agent:latest',+ ].join('\n')+ const helmSnippet = [+ 'helm install posthog-metrics-agent \\',+ ' oci://ghcr.io/posthog/charts/posthog-metrics-agent \\',+ ` --set posthog.apiKey=${apiKey} \\`,+ ` --set posthog.host=${apiHostOrigin()}`,+ '',+ '# then annotate the pods you want scraped:',+ '# prometheus.io/scrape: "true"',+ '# prometheus.io/port: "9090"',+ ].join('\n')+return (<ProductIntroductionproductName="Metrics"@@ -98,6 +121,47 @@ const NoMetricsPrompt = ({ className }: { className?: string }): JSX.Element | n</Link>.</p>+ <div className="flex flex-col gap-1 w-full max-w-160">+ <h5 className="m-0">Or scrape your existing Prometheus metrics</h5>+ <p className="text-sm text-secondary m-0">+ Already exposing Prometheus metrics? Deploy the PostHog metrics agent in your infra and it+ forwards them for you, no code changes needed. Counters and histograms with OpenMetrics+ exemplars get clickable trace links automatically.+ </p>+ <LemonTabs+ activeKey={agentTab}+ onChange={(key) => {+ setAgentTab(key)+ onDocsLinkClick(key === 'docker' ? 'agent-docker' : 'agent-helm')+ }}+ tabs={[+ {+ key: 'docker' as const,+ label: 'Docker',+ content: (+ <CodeSnippet+ language={Language.Bash}+ onCopy={() => reportScrapeSnippetCopied('docker')}+ >+ {dockerSnippet}+ </CodeSnippet>+ ),+ },+ {+ key: 'kubernetes' as const,+ label: 'Kubernetes',+ content: (+ <CodeSnippet+ language={Language.Bash}+ onCopy={() => reportScrapeSnippetCopied('kubernetes')}+ >+ {helmSnippet}+ </CodeSnippet>+ ),+ },+ ]}+ />+ </div><div className="flex items-center gap-4"><div className="flex items-center gap-2 px-3 py-1.5 border border-accent rounded"><div className="relative flex items-center justify-center">diff --git a/products/metrics/frontend/metricsIngestionLogic.test.ts b/products/metrics/frontend/metricsIngestionLogic.test.tsindex 343941b2d8e9..c353fe2e8327 100644--- a/products/metrics/frontend/metricsIngestionLogic.test.ts+++ b/products/metrics/frontend/metricsIngestionLogic.test.ts@@ -70,6 +70,42 @@ describe('metricsIngestionLogic', () => {.toNotHaveDispatchedActions([firstIngestIntent()])})+ // Copying the agent snippet is the strongest pre-ingest signal a team is taking+ // the scrape path — it must register a distinct intent (not the generic docs one)+ // so activation can attribute the scrape funnel, once per variant per session.+ it('records a scrape-path intent when an agent snippet is copied, once per variant', async () => {+ jest.mocked(metricsHasMetricsRetrieve).mockResolvedValue({ hasMetrics: false } as any)+ logic = metricsIngestionLogic()+ logic.mount()++ const scrapeIntent = (): any =>+ teamLogic.actionCreators.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_SCRAPE_AGENT_SNIPPET_COPIED,+ metadata: { variant: 'docker' },+ })++ await expectLogic(logic, () => {+ logic.actions.reportScrapeSnippetCopied('docker')+ }).toDispatchActions([scrapeIntent()])++ // The same variant again is not a new intent...+ await expectLogic(logic, () => {+ logic.actions.reportScrapeSnippetCopied('docker')+ }).toNotHaveDispatchedActions([scrapeIntent()])++ // ...but the other variant is.+ await expectLogic(logic, () => {+ logic.actions.reportScrapeSnippetCopied('kubernetes')+ }).toDispatchActions([+ teamLogic.actionCreators.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_SCRAPE_AGENT_SNIPPET_COPIED,+ metadata: { variant: 'kubernetes' },+ }),+ ])+ })+it('does not check ingestion without metrics viewer access', async () => {window.POSTHOG_APP_CONTEXT = {...window.POSTHOG_APP_CONTEXT,diff --git a/products/metrics/frontend/metricsIngestionLogic.tsx b/products/metrics/frontend/metricsIngestionLogic.tsxindex 7ef117541bc9..f79cb3ef787f 100644--- a/products/metrics/frontend/metricsIngestionLogic.tsx+++ b/products/metrics/frontend/metricsIngestionLogic.tsx@@ -1,5 +1,6 @@-import { MakeLogicType, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'import { retryWithBackoff } from 'lib/utils/async'import { teamLogic } from 'scenes/teamLogic'@@ -40,6 +41,9 @@ export interface metricsIngestionLogicActions {teamHasMetrics: boolean | undefinedpayload?: any}+ reportScrapeSnippetCopied: (variant: 'docker' | 'kubernetes') => {+ variant: 'docker' | 'kubernetes'+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -62,6 +66,9 @@ export const metricsIngestionLogic = kea<metricsIngestionLogicType>([values: [teamLogic, ['currentTeamId']],actions: [teamLogic, ['addProductIntent']],})),+ actions({+ reportScrapeSnippetCopied: (variant: 'docker' | 'kubernetes') => ({ variant }),+ }),loaders(({ values }) => ({teamHasMetrics: {__default: undefined as boolean | undefined,@@ -98,6 +105,21 @@ export const metricsIngestionLogic = kea<metricsIngestionLogicType>([}),listeners(({ actions, cache }) => ({+ reportScrapeSnippetCopied: ({ variant }) => {+ posthog.capture('metrics scrape agent snippet copied', { variant })+ // One intent per variant per session: repeated copies of the same+ // snippet are retries, not new adoption signals.+ cache.scrapeIntentFired ??= {}+ if (cache.scrapeIntentFired[variant]) {+ return+ }+ cache.scrapeIntentFired[variant] = true+ actions.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_SCRAPE_AGENT_SNIPPET_COPIED,+ metadata: { variant },+ })+ },loadTeamHasMetricsSuccess: ({ teamHasMetrics }) => {if (!teamHasMetrics) {// Only an observed "no metrics yet" arms the intent - an access-denied