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(metrics): replace the setup prompt with the product empty state (#90610)

Rafael Audibert185aef0089e9
diff --git a/docs/internal/product-empty-state-adoption.md b/docs/internal/product-empty-state-adoption.md
index c0b8e9c541ba..36a071540a7b 100644
--- a/docs/internal/product-empty-state-adoption.md
+++ b/docs/internal/product-empty-state-adoption.md
@@ -53,7 +53,7 @@ Rows marked "in review" are not on `master` yet. See "Regenerating the lists" fo
| Error tracking | `products/error_tracking/frontend/scenes/ErrorTrackingScene/ErrorTrackingScene.tsx` | on master |
| Logs | `products/logs/frontend/LogsScene.tsx` | on master |
| Tracing | `products/tracing/frontend/TracingScene.tsx` | on master |
-| Metrics | `products/metrics/frontend/MetricsScene.tsx` | in review |
+| Metrics | `products/metrics/frontend/MetricsScene.tsx` | on master |
| Surveys | `frontend/src/scenes/surveys/Surveys.tsx` | in review |
| Session replay | `frontend/src/scenes/session-recordings/SessionRecordings.tsx` | in review |
| Web vitals | `frontend/src/scenes/web-analytics/WebAnalyticsScene.tsx` | in review |
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 38a85b349f8d..96e1a4d3d11e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1828,6 +1828,10 @@ snapshots:
hash: v1.k794b7964.4fa27c3231a20ff8e3d545a0979d1b86b1367e925d2db6ea67360941a9c10e23.bJBq_kK46OIZZXI05CslNdEuBIgjed2YSK3c5YAm4ww
components-product-empty-state--mcp-analytics-without-wizard--light:
hash: v1.k794b7964.8044fd4dc9bbf1559e453dd5a61a62c2aedc86a0d9e9cdbe32f29462a3c4096b.sAIpZsncmM_qxpuHF0Cq6PPIVJT412weeElI8Juz2XI
+ components-product-empty-state--metrics-needs-setup--dark:
+ hash: v1.k794b7964.f871f80c2e0437044742c14a0db2f29109168ec4dcb8ccec7e6fd814248bfc3f.GEM_Stq79cSU_62UY6840MfBQiGz-SJZ1u9dW5JG_pQ
+ components-product-empty-state--metrics-needs-setup--light:
+ hash: v1.k794b7964.508b62772da1dcd8700e677010732092b48e105cf837a8b074aa0bf5522abb9e.RySrCBS1xNDjeB8G8w7HObsdeP2ZssrvUNfm-We6Vpc
components-product-empty-state--not-empty-with-action--dark:
hash: v1.k794b7964.e344a03ab4fb6bbef2cf88d2b89c12bccfe1b5307e5e80051e47ad6adec22d93.w4TEddGy6INFXoaPeIr201fD_4xWA6jG0Uugfke9ytM
components-product-empty-state--not-empty-with-action--light:
diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
index 41f3e118679b..b26665a50b27 100644
--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
@@ -16,6 +16,7 @@ import { featureFlagsEmptyState } from 'products/feature_flags/frontend/emptySta
import { linksEmptyState } from 'products/links/frontend/emptyState/linksEmptyState'
import { logsEmptyState } from 'products/logs/frontend/emptyState/logsEmptyState'
import { mcpAnalyticsEmptyState } from 'products/mcp_analytics/frontend/emptyState/mcpAnalyticsEmptyState'
+import { metricsEmptyState } from 'products/metrics/frontend/emptyState/metricsEmptyState'
import { productToursEmptyState } from 'products/product_tours/frontend/emptyState/productToursEmptyState'
import { replayVisionEmptyState } from 'products/replay_vision/frontend/emptyState/replayVisionEmptyState'
import { llmSkillsEmptyState } from 'products/skills/frontend/emptyState/llmSkillsEmptyState'
@@ -220,3 +221,8 @@ export const TracingNeedsSetup: ProductEmptyStateStory = productEmptyStateStory(
// nosemgrep: no-environments-api-urls-frontend -- api.tracing is env-scoped, so the msw mock must match /api/environments to intercept it
mocks: { get: { '/api/environments/:team_id/tracing/spans/has_spans': [200, { hasSpans: false }] } },
})
+
+// Metrics detection asks the has-metrics API on mount - answer "none yet".
+export const MetricsNeedsSetup: ProductEmptyStateStory = productEmptyStateStory(metricsEmptyState, 'needs-setup', {
+ mocks: { get: { '/api/projects/:team_id/metrics/has_metrics/': [200, { hasMetrics: false }] } },
+})
diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx
index 284bbfd17284..cbc7b3d89a91 100644
--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx
+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx
@@ -99,14 +99,14 @@ export function ProductEmptyState({ config, mode }: ProductEmptyStateProps): JSX
copyLabel={`${config.productName} wizard command`}
onCopy={() => captureClick('wizard command copied')}
/>
- {guardedPrimaryAction ? (
+ {config.PrimaryAction || guardedPrimaryAction ? (
<>
<div className="flex items-center gap-3">
<div className="h-px flex-1 bg-border-primary" />
<span className="text-xs text-tertiary uppercase tracking-wide">or</span>
<div className="h-px flex-1 bg-border-primary" />
</div>
- {guardedPrimaryAction}
+ {config.PrimaryAction ? <config.PrimaryAction /> : guardedPrimaryAction}
</>
) : null}
</>
@@ -165,7 +165,7 @@ export function ProductEmptyState({ config, mode }: ProductEmptyStateProps): JSX
{config.statusIndicator ? <div className="text-xs">{config.statusIndicator}</div> : null}
<div className="flex items-center gap-4">
- {showWizard && !primaryActionButton && manualUrl ? (
+ {showWizard && !primaryActionButton && !config.PrimaryAction && manualUrl ? (
<LemonButton
type="secondary"
icon={<IconGear />}
diff --git a/frontend/src/lib/components/ProductEmptyState/types.ts b/frontend/src/lib/components/ProductEmptyState/types.ts
index c966136fad45..fda389c2c68b 100644
--- a/frontend/src/lib/components/ProductEmptyState/types.ts
+++ b/frontend/src/lib/components/ProductEmptyState/types.ts
@@ -112,7 +112,8 @@ export interface ProductEmptyStateConfig {
/**
* Rendered in the primary-action slot instead of the `primaryAction` button, for
* actions that need hooks - e.g. a create flow that opens PostHog AI via `useMaxTool`.
- * Takes precedence over `primaryAction`.
+ * Takes precedence over `primaryAction`. With `wizard` also set, the terminal card
+ * stays the hero and this renders under the "or" divider.
*/
PrimaryAction?: ComponentType
docsUrl?: string
diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsx
index d13812178925..c892dc7a4c6b 100644
--- a/products/metrics/frontend/MetricsScene.tsx
+++ b/products/metrics/frontend/MetricsScene.tsx
@@ -1,6 +1,6 @@
import { useActions, useMountedLogic, useValues } from 'kea'
-import { LemonBanner, LemonTabs } from '@posthog/lemon-ui'
+import { LemonTabs } from '@posthog/lemon-ui'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { sceneConfigurations } from 'scenes/scenes'
@@ -15,12 +15,11 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { metricNamePickerLogic } from './components/metricNamePickerLogic'
import { MetricsFundamentals } from './components/MetricsFundamentals'
import { MetricsOverview } from './components/MetricsOverview'
-import { MetricsSetupPrompt } from './components/MetricsSetupPrompt'
import { MetricsSqlEditor } from './components/MetricsSqlEditor'
import { metricsUsageTrackingLogic } from './components/metricsUsageTrackingLogic'
import { MetricsViewer } from './components/MetricsViewer'
+import { metricsEmptyState } from './emptyState/metricsEmptyState'
import { metricsFeaturePreviewGate } from './featurePreviewGate'
-import { metricsIngestionLogic } from './metricsIngestionLogic'
import { MetricsSceneActiveTab, metricsSceneLogic } from './metricsSceneLogic'
export const METRICS_LOGIC_KEY = 'metrics'
@@ -36,6 +35,7 @@ export const scene: SceneExport = {
component: MetricsScene,
logic: metricsSceneLogic,
productKey: ProductKey.METRICS,
+ emptyState: metricsEmptyState,
}
export function MetricsScene(): JSX.Element {
@@ -51,7 +51,6 @@ export function MetricsScene(): JSX.Element {
const MetricsSceneContent = (): JSX.Element => {
const { activeTab } = useValues(metricsSceneLogic)
const { setActiveTab } = useActions(metricsSceneLogic)
- const { teamHasMetricsCheckFailed } = useValues(metricsIngestionLogic)
const metricsViewerDisabledReason = getAccessControlDisabledReason(
AccessControlResourceType.Metrics,
AccessControlLevel.Viewer
@@ -82,19 +81,6 @@ const MetricsSceneContent = (): JSX.Element => {
type: sceneConfigurations[Scene.Metrics].iconType || 'default_icon_type',
}}
/>
- {teamHasMetricsCheckFailed && (
- <LemonBanner
- type="info"
- dismissKey="metrics-setup-hint-banner"
- action={{
- to: 'https://posthog.com/docs/metrics',
- targetBlank: true,
- children: 'Setup guide',
- }}
- >
- Unable to verify metrics setup. If you haven't configured metrics yet, check out our setup guide.
- </LemonBanner>
- )}
<LemonTabs<MetricsSceneActiveTab>
activeKey={activeTab}
onChange={(tab) => {
@@ -108,14 +94,12 @@ const MetricsSceneContent = (): JSX.Element => {
}))}
sceneInset
/>
- <MetricsSetupPrompt>
- <div className="flex flex-col gap-2 py-2 flex-1 min-h-0">
- {activeTab === 'overview' && <MetricsOverview />}
- {activeTab === 'viewer' && <MetricsViewer />}
- {activeTab === 'sql' && <MetricsSqlEditor />}
- {activeTab === 'fundamentals' && <MetricsFundamentals />}
- </div>
- </MetricsSetupPrompt>
+ <div className="flex flex-col gap-2 py-2 flex-1 min-h-0">
+ {activeTab === 'overview' && <MetricsOverview />}
+ {activeTab === 'viewer' && <MetricsViewer />}
+ {activeTab === 'sql' && <MetricsSqlEditor />}
+ {activeTab === 'fundamentals' && <MetricsFundamentals />}
+ </div>
</>
)
}
diff --git a/products/metrics/frontend/components/MetricsSetupPrompt.tsx b/products/metrics/frontend/components/MetricsSetupPrompt.tsx
deleted file mode 100644
index fcfef27e54b3..000000000000
--- a/products/metrics/frontend/components/MetricsSetupPrompt.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-import { useActions, useValues } from 'kea'
-import posthog from 'posthog-js'
-import { useEffect, useState } from 'react'
-
-import * as greekPng from '@posthog/brand/hoggies/png/greek'
-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 javascriptImage from 'scenes/onboarding/shared/logos/javascript_web.svg'
-import nodejsImage from 'scenes/onboarding/shared/logos/nodejs.svg'
-import pythonImage from 'scenes/onboarding/shared/logos/python.svg'
-import { teamLogic } from 'scenes/teamLogic'
-
-import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
-
-import { metricsIngestionLogic } from '../metricsIngestionLogic'
-
-const HedgehogGreek = pngHoggie(greekPng)
-
-// The SDK paths come first: a product engineer on a PaaS reaches for the SDK they
-// already have, where the scrape agent below needs infra they may not run. The
-// agent's own Docker and Kubernetes paths are the tabbed snippets, not links.
-const FRAMEWORK_LINKS: { name: string; image?: string; docsLink: string }[] = [
- {
- name: 'JavaScript',
- image: javascriptImage,
- docsLink: 'https://posthog.com/docs/metrics/installation/javascript',
- },
- { name: 'Node.js', image: nodejsImage, docsLink: 'https://posthog.com/docs/metrics/installation/nodejs' },
- { name: 'Python', image: pythonImage, docsLink: 'https://posthog.com/docs/metrics/installation/python' },
- { name: 'Other', docsLink: 'https://posthog.com/docs/metrics/installation/other' },
-]
-
-const POLLING_INTERVAL_MS = 5000
-
-export const MetricsSetupPrompt = ({
- children,
- className,
-}: {
- children: React.ReactNode
- className?: string
-}): JSX.Element => {
- const { hasMetrics, teamHasMetricsLoading, teamHasMetricsCheckFailed } = useValues(metricsIngestionLogic)
- const { currentTeam } = useValues(teamLogic)
-
- if ((teamHasMetricsLoading && hasMetrics === undefined) || !currentTeam) {
- return (
- <div className="flex justify-center">
- <Spinner />
- </div>
- )
- }
-
- if (teamHasMetricsCheckFailed || hasMetrics === undefined) {
- return <>{children}</>
- }
-
- if (!hasMetrics) {
- return <NoMetricsPrompt className={className} />
- }
-
- return <>{children}</>
-}
-
-const NoMetricsPrompt = ({ className }: { className?: string }): JSX.Element | null => {
- const { addProductIntent } = useActions(teamLogic)
- const { currentTeam } = useValues(teamLogic)
- const { hasMetrics } = useValues(metricsIngestionLogic)
- const { loadTeamHasMetrics, reportScrapeSnippetCopied } = useActions(metricsIngestionLogic)
- const [agentTab, setAgentTab] = useState<'docker' | 'kubernetes'>('docker')
-
- useEffect(() => {
- posthog.capture('metrics setup prompt viewed')
- }, [])
-
- useInterval(() => {
- if (!hasMetrics) {
- loadTeamHasMetrics()
- }
- }, POLLING_INTERVAL_MS)
-
- const onDocsLinkClick = (docsType: string): void => {
- posthog.capture('metrics onboarding docs clicked', { docs_type: docsType })
- addProductIntent({
- product_type: ProductKey.METRICS,
- intent_context: ProductIntentContext.METRICS_DOCS_VIEWED,
- })
- }
-
- 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 (
- <ProductIntroduction
- productName="Metrics"
- thingName="metric"
- titleOverride="You haven't sent any metrics yet"
- description="Send metrics from the PostHog SDK you already have, from any OpenTelemetry-compatible client over OTLP, or by scraping the Prometheus endpoints you already expose."
- isEmpty={true}
- productKey={ProductKey.METRICS}
- className={className}
- customHog={HedgehogGreek}
- actionElementOverride={
- <div className="flex flex-col items-start gap-4">
- <p className="text-sm text-secondary m-0">
- Read our{' '}
- <Link to="https://posthog.com/docs/metrics" onClick={() => onDocsLinkClick('Metrics')}>
- metrics docs
- </Link>
- , learn more about{' '}
- <Link
- to="https://opentelemetry.io/docs/what-is-opentelemetry/"
- target="_blank"
- disableDocsPanel
- onClick={() => onDocsLinkClick('OpenTelemetry')}
- >
- OpenTelemetry
- </Link>
- , or pick a language to get started:
- </p>
- <div className="flex flex-wrap gap-2">
- {FRAMEWORK_LINKS.map(({ name, image, docsLink }) => (
- <LemonButton
- key={name}
- type="secondary"
- size="small"
- to={docsLink}
- onClick={() => onDocsLinkClick(name)}
- icon={
- image ? (
- <img src={image} alt="" aria-hidden="true" className="w-5 h-5" />
- ) : undefined
- }
- >
- {name}
- </LemonButton>
- ))}
- </div>
- <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-2 px-3 py-1.5 border border-accent rounded">
- <div className="relative flex items-center justify-center">
- <div className="absolute w-3 h-3 border-2 border-accent rounded-full animate-ping" />
- <div className="w-2 h-2 bg-accent rounded-full" />
- </div>
- <span className="text-sm">Watching for metrics</span>
- </div>
- </div>
- }
- />
- )
-}
diff --git a/products/metrics/frontend/emptyState/MetricsPreview.scss b/products/metrics/frontend/emptyState/MetricsPreview.scss
new file mode 100644
index 000000000000..0eba3c50c3f8
--- /dev/null
+++ b/products/metrics/frontend/emptyState/MetricsPreview.scss
@@ -0,0 +1,241 @@
+@import '../../../../frontend/src/lib/components/ProductEmptyState/previewMixins';
+
+.MetricsPreview {
+ --metrics-preview-accent: var(--empty-state-accent, var(--color-primary-500));
+
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+
+ // Hidden selection state. A direct child of .MetricsPreview so `:checked ~` reaches both cards.
+ &__checkbox {
+ position: absolute;
+ width: 0;
+ height: 0;
+ pointer-events: none;
+ opacity: 0;
+ }
+
+ &__panel,
+ &__chart {
+ overflow: hidden;
+ background: var(--color-bg-surface-primary);
+ border: 1px solid var(--color-border-primary);
+ border-radius: var(--radius);
+ }
+
+ &__chart {
+ padding: 0.5rem 0.75rem 0.625rem;
+ }
+
+ // Latency/memory pairs are stacked on one grid cell and crossfaded, so swapping
+ // the charted metric never changes any element's size (no layout shift).
+ &__swap {
+ display: grid;
+ }
+
+ &__swap > * {
+ grid-area: 1 / 1;
+ min-width: 0;
+ }
+
+ &__when-memory {
+ @include preview-swap-hidden;
+ }
+
+ &__when-latency {
+ @include preview-swap-visible;
+ }
+
+ &__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0.5rem 0.75rem;
+ border-bottom: 1px solid var(--color-border-primary);
+ }
+
+ &__title {
+ display: flex;
+ gap: 0.375rem;
+ align-items: center;
+ font-size: 0.75rem;
+ font-weight: 600;
+ }
+
+ &__live-dot {
+ width: 7px;
+ height: 7px;
+ background: var(--metrics-preview-accent);
+ border-radius: 50%;
+ animation: MetricsPreview__pulse 2s ease-in-out infinite;
+ }
+
+ // Metric list
+
+ &__rows {
+ display: flex;
+ flex-direction: column;
+ padding: 0.25rem 0.5rem;
+ }
+
+ &__row {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) auto;
+ gap: 0.5rem;
+ align-items: center;
+ padding: 0.375rem 0.5rem;
+ border-radius: var(--radius);
+ transition: background-color 250ms ease;
+ }
+
+ &__row--memory {
+ cursor: pointer;
+ user-select: none;
+ }
+
+ &__row--memory:hover {
+ background: var(--color-bg-fill-highlight-50);
+ }
+
+ &__radio {
+ width: 9px;
+ height: 9px;
+ background: var(--metrics-preview-accent);
+ border-radius: 50%;
+ box-shadow: inset 0 0 0 2px var(--color-bg-surface-primary);
+ transition: background-color 250ms ease;
+ }
+
+ &__radio--off {
+ background: var(--color-bg-fill-tertiary);
+ }
+
+ &__name {
+ overflow: hidden;
+ font-family: var(--font-mono);
+ font-size: 0.6875rem;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__kind {
+ font-size: 0.5625rem;
+ font-weight: 600;
+ color: var(--color-text-tertiary);
+ text-transform: uppercase;
+ }
+
+ &__hint {
+ padding: 0.25rem 0.75rem 0.5rem;
+ font-size: 0.625rem;
+ color: var(--color-text-tertiary);
+ }
+
+ // Chart card
+
+ &__spark-window {
+ font-size: 0.625rem;
+ font-weight: 400;
+ color: var(--color-text-tertiary);
+ }
+
+ &__spark-area {
+ fill: color-mix(in oklab, var(--metrics-preview-accent) 13%, transparent);
+ stroke: none;
+ }
+
+ &__spark-line {
+ fill: none;
+ stroke: color-mix(in oklab, var(--metrics-preview-accent) 32%, transparent);
+ stroke-width: 2;
+ }
+
+ // The moving bit: a short bright segment cycling along the line.
+ &__spark-trace {
+ fill: none;
+ stroke: var(--metrics-preview-accent);
+ stroke-dasharray: 16 84;
+ stroke-linecap: round;
+ stroke-width: 2;
+ animation: MetricsPreview__trace 3.2s linear infinite;
+ }
+
+ @include preview-sparkline;
+}
+
+// Memory selected (user clicked the gauge row)
+
+.MetricsPreview__checkbox:checked ~ * .MetricsPreview__when-memory {
+ @include preview-swap-visible;
+}
+
+.MetricsPreview__checkbox:checked ~ * .MetricsPreview__when-latency {
+ @include preview-swap-hidden;
+}
+
+// The list's selection dot follows the charted metric.
+.MetricsPreview__checkbox:checked ~ .MetricsPreview__panel .MetricsPreview__row--latency .MetricsPreview__radio {
+ background: var(--color-bg-fill-tertiary);
+}
+
+.MetricsPreview__checkbox:not(:checked) ~ .MetricsPreview__panel .MetricsPreview__row--memory .MetricsPreview__radio {
+ background: var(--color-bg-fill-tertiary);
+}
+
+.MetricsPreview__checkbox:checked ~ .MetricsPreview__panel .MetricsPreview__row--memory {
+ background: color-mix(in oklab, var(--metrics-preview-accent) 8%, transparent);
+}
+
+// The checkbox stays keyboard-focusable while visually hidden, so the row it labels
+// needs a visible focus indicator (WCAG 2.4.7).
+.MetricsPreview__checkbox:focus-visible ~ .MetricsPreview__panel .MetricsPreview__row--memory {
+ outline: 2px solid var(--metrics-preview-accent);
+ outline-offset: 1px;
+}
+
+// Nudge attention at the gauge row until it's selected.
+.MetricsPreview:not(.MetricsPreview--static)
+ .MetricsPreview__checkbox:not(:checked)
+ ~ .MetricsPreview__panel
+ .MetricsPreview__row--memory
+ .MetricsPreview__radio {
+ animation: MetricsPreview__nudge 2.4s ease-in-out infinite;
+}
+
+@keyframes MetricsPreview__nudge {
+ 0%,
+ 100% {
+ box-shadow:
+ inset 0 0 0 2px var(--color-bg-surface-primary),
+ 0 0 0 0 color-mix(in oklab, var(--metrics-preview-accent) 45%, transparent);
+ }
+
+ 50% {
+ box-shadow:
+ inset 0 0 0 2px var(--color-bg-surface-primary),
+ 0 0 0 4px color-mix(in oklab, var(--metrics-preview-accent) 20%, transparent);
+ }
+}
+
+@keyframes MetricsPreview__pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+
+ 50% {
+ opacity: 0.35;
+ }
+}
+
+// pathLength is normalized to 100, so the dash offset loops cleanly regardless of length.
+@keyframes MetricsPreview__trace {
+ to {
+ stroke-dashoffset: -100;
+ }
+}
+
+// Storybook snapshots and reduced motion drop all ambient motion; clicking the
+// gauge row still flips the state (transitions only).
+@include preview-motion-guards('MetricsPreview');
diff --git a/products/metrics/frontend/emptyState/MetricsPreview.tsx b/products/metrics/frontend/emptyState/MetricsPreview.tsx
new file mode 100644
index 000000000000..486741541b5c
--- /dev/null
+++ b/products/metrics/frontend/emptyState/MetricsPreview.tsx
@@ -0,0 +1,116 @@
+import './MetricsPreview.scss'
+
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
+import { cn } from 'lib/utils/css-classes'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
+
+// Hand-authored series. Latency is spiky around a steady band; memory is a
+// sawtooth that climbs and drops on every garbage-collection cycle.
+const LINE_LATENCY = 'M 0 24 L 10 20 L 20 26 L 30 18 L 40 25 L 50 12 L 60 22 L 70 16 L 80 24 L 90 19 L 100 21'
+const LINE_MEMORY = 'M 0 30 L 14 22 L 28 14 L 29 30 L 43 23 L 57 15 L 58 31 L 72 24 L 86 16 L 87 30 L 100 24'
+
+function areaPath(line: string): string {
+ return `${line} L 100 40 L 0 40 Z`
+}
+
+/**
+ * Example-data preview for the metrics empty state: a metric list driving a
+ * chart card. Clicking the memory gauge swaps the chart from request latency to
+ * the memory sawtooth. One hidden checkbox drives it via `:checked ~` styles -
+ * no timers or state, per the preview rules in the `building-product-empty-states`
+ * skill. Chart states crossfade in `__swap` grids, so nothing shifts.
+ */
+export function MetricsPreview(): JSX.Element {
+ const isStatic = inStorybook() || inStorybookTestRunner()
+
+ return (
+ <div className={cn('MetricsPreview', isStatic && 'MetricsPreview--static')}>
+ {/* Selection state, before both cards so `:checked ~` can style them. */}
+ <input type="checkbox" id="metrics-preview-select" className="MetricsPreview__checkbox" />
+
+ <div className="MetricsPreview__panel">
+ <div className="MetricsPreview__head">
+ <span className="MetricsPreview__title">
+ <span className="MetricsPreview__live-dot" aria-hidden="true" />
+ Metrics
+ </span>
+ <LemonTag size="small">example data</LemonTag>
+ </div>
+ <div className="MetricsPreview__rows">
+ <div className="MetricsPreview__row MetricsPreview__row--latency">
+ <span className="MetricsPreview__radio" aria-hidden="true" />
+ <span className="MetricsPreview__name">http_request_duration_seconds</span>
+ <span className="MetricsPreview__kind">histogram</span>
+ </div>
+ <label htmlFor="metrics-preview-select" className="MetricsPreview__row MetricsPreview__row--memory">
+ <span className="MetricsPreview__radio" aria-hidden="true" />
+ <span className="MetricsPreview__name">process_resident_memory_bytes</span>
+ <span className="MetricsPreview__kind">gauge</span>
+ </label>
+ <div className="MetricsPreview__row">
+ <span className="MetricsPreview__radio MetricsPreview__radio--off" aria-hidden="true" />
+ <span className="MetricsPreview__name">orders_total</span>
+ <span className="MetricsPreview__kind">counter</span>
+ </div>
+ </div>
+ <div className="MetricsPreview__hint MetricsPreview__swap">
+ <span className="MetricsPreview__when-latency">Click the memory gauge to chart it instead.</span>
+ <span className="MetricsPreview__when-memory">
+ A sawtooth: memory climbs, then GC drops it. Click again for latency.
+ </span>
+ </div>
+ </div>
+
+ <div className="MetricsPreview__chart">
+ <div className="MetricsPreview__spark-head">
+ <span className="MetricsPreview__spark-title MetricsPreview__swap">
+ <span className="MetricsPreview__when-latency">p95 http_request_duration_seconds</span>
+ <span className="MetricsPreview__when-memory">process_resident_memory_bytes</span>
+ </span>
+ </div>
+ <div className="MetricsPreview__spark-value">
+ <span className="MetricsPreview__swap">
+ <span className="MetricsPreview__when-latency">412 ms</span>
+ <span className="MetricsPreview__when-memory">1.4 GB</span>
+ </span>
+ <span className="MetricsPreview__spark-window">last 60 min</span>
+ </div>
+ <svg
+ className="MetricsPreview__spark-svg"
+ viewBox="0 0 100 40"
+ preserveAspectRatio="none"
+ aria-hidden="true"
+ >
+ <g className="MetricsPreview__spark-g MetricsPreview__when-latency">
+ <path className="MetricsPreview__spark-area" d={areaPath(LINE_LATENCY)} />
+ <path
+ className="MetricsPreview__spark-line"
+ d={LINE_LATENCY}
+ vectorEffect="non-scaling-stroke"
+ />
+ <path
+ className="MetricsPreview__spark-trace"
+ d={LINE_LATENCY}
+ pathLength={100}
+ vectorEffect="non-scaling-stroke"
+ />
+ </g>
+ <g className="MetricsPreview__spark-g MetricsPreview__when-memory">
+ <path className="MetricsPreview__spark-area" d={areaPath(LINE_MEMORY)} />
+ <path
+ className="MetricsPreview__spark-line"
+ d={LINE_MEMORY}
+ vectorEffect="non-scaling-stroke"
+ />
+ <path
+ className="MetricsPreview__spark-trace"
+ d={LINE_MEMORY}
+ pathLength={100}
+ vectorEffect="non-scaling-stroke"
+ />
+ </g>
+ </svg>
+ </div>
+ </div>
+ )
+}
diff --git a/products/metrics/frontend/emptyState/MetricsScrapeAgentSetup.tsx b/products/metrics/frontend/emptyState/MetricsScrapeAgentSetup.tsx
new file mode 100644
index 000000000000..492d4e88b89d
--- /dev/null
+++ b/products/metrics/frontend/emptyState/MetricsScrapeAgentSetup.tsx
@@ -0,0 +1,94 @@
+import { useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useState } from 'react'
+
+import { LemonTabs } from '@posthog/lemon-ui'
+
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+import { apiHostOrigin } from 'lib/utils/apiHost'
+import { addProductIntent } from 'lib/utils/product-intents'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+
+// One intent per variant per session: repeated copies of the same snippet are
+// retries, not new adoption signals.
+const scrapeIntentFired = new Set<string>()
+
+function reportScrapeSnippetCopied(variant: 'docker' | 'kubernetes'): void {
+ posthog.capture('metrics scrape agent snippet copied', { variant })
+ if (scrapeIntentFired.has(variant)) {
+ return
+ }
+ scrapeIntentFired.add(variant)
+ void addProductIntent({
+ product_type: ProductKey.METRICS,
+ intent_context: ProductIntentContext.METRICS_SCRAPE_AGENT_SNIPPET_COPIED,
+ metadata: { variant },
+ })
+}
+
+/**
+ * The metrics empty state's hero action: deploy the scrape agent against the
+ * Prometheus endpoints the team already exposes. The SDK and OTLP paths live in
+ * the docs link next to it.
+ */
+export function MetricsScrapeAgentSetup(): JSX.Element {
+ const { currentTeam } = useValues(teamLogic)
+ const [agentTab, setAgentTab] = useState<'docker' | 'kubernetes'>('docker')
+
+ 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 (
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-tertiary">
+ Already exposing Prometheus metrics? The scrape agent forwards them, no code changes needed:
+ </span>
+ <LemonTabs
+ activeKey={agentTab}
+ onChange={setAgentTab}
+ size="small"
+ 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>
+ )
+}
diff --git a/products/metrics/frontend/emptyState/metricsEmptyState.tsx b/products/metrics/frontend/emptyState/metricsEmptyState.tsx
new file mode 100644
index 000000000000..ec33f87d51d7
--- /dev/null
+++ b/products/metrics/frontend/emptyState/metricsEmptyState.tsx
@@ -0,0 +1,40 @@
+import * as chartPng from '@posthog/brand/hoggies/png/chart'
+import { IconGraph } from '@posthog/icons'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import type { SceneProductEmptyState } from 'lib/components/ProductEmptyState/types'
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+
+import { MetricsPreview } from './MetricsPreview'
+import { MetricsScrapeAgentSetup } from './MetricsScrapeAgentSetup'
+import { metricsSetupLogic } from './metricsSetupLogic'
+
+const HedgehogChart = pngHoggie(chartPng)
+
+export const metricsEmptyState: SceneProductEmptyState = {
+ statusLogic: metricsSetupLogic,
+ // The whole product is behind this flag; its feature-preview gate handles the flag-off case.
+ featureFlag: FEATURE_FLAGS.METRICS,
+ config: {
+ productKey: ProductKey.METRICS,
+ productName: 'Metrics',
+ icon: <IconGraph />,
+ accentColor: 'var(--color-product-metrics-light)',
+ accentColorDark: 'var(--color-product-metrics-dark)',
+ hedgehog: HedgehogChart,
+ text: {
+ 'needs-setup': {
+ headline: 'Watch your counters, gauges, and histograms live',
+ lead: 'Send metrics from the PostHog SDK you already have, from any OpenTelemetry-compatible client over OTLP, or by scraping the Prometheus endpoints you already expose. Chart them next to your product data and query them with SQL.',
+ hint: 'Starting fresh? Wizard wires up metrics in your app:',
+ },
+ },
+ wizard: { slug: 'metrics', pinProjectId: true },
+ PrimaryAction: MetricsScrapeAgentSetup,
+ docsUrl: 'https://posthog.com/docs/metrics',
+ previewLabel: 'Your metrics, once connected',
+ Preview: MetricsPreview,
+ },
+}
diff --git a/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts b/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts
new file mode 100644
index 000000000000..1f9f92bc4539
--- /dev/null
+++ b/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts
@@ -0,0 +1,36 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { metricsHasMetricsRetrieve } from '../generated/api'
+import { canViewMetrics } from '../metricsAccess'
+import { metricsSetupLogic } from './metricsSetupLogic'
+
+jest.mock('../metricsAccess', () => ({ canViewMetrics: jest.fn() }))
+jest.mock('../generated/api', () => ({ metricsHasMetricsRetrieve: jest.fn() }))
+
+describe('metricsSetupLogic', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ initKeaTests()
+ })
+
+ // Guards the status mapping the scene gate hangs off: treating "no access"
+ // as "no metrics" would show the setup screen to viewers who simply cannot
+ // run the check, and flipping the has-metrics branch would gate teams with
+ // real samples.
+ it.each([
+ [false, undefined, 'unknown'],
+ [true, true, 'has-data'],
+ [true, false, 'needs-setup'],
+ ])('access=%s, hasMetrics=%s maps to %s', async (access, hasMetrics, expected) => {
+ ;(canViewMetrics as jest.Mock).mockReturnValue(access)
+ ;(metricsHasMetricsRetrieve as jest.Mock).mockResolvedValue({ hasMetrics })
+ metricsSetupLogic.mount()
+ await expectLogic(metricsSetupLogic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.METRICS }).values.status).toBe(expected)
+ })
+})
diff --git a/products/metrics/frontend/emptyState/metricsSetupLogic.ts b/products/metrics/frontend/emptyState/metricsSetupLogic.ts
new file mode 100644
index 000000000000..f0ccbad3b1c1
--- /dev/null
+++ b/products/metrics/frontend/emptyState/metricsSetupLogic.ts
@@ -0,0 +1,53 @@
+import { createSetupDetectionLogic } from 'lib/components/ProductEmptyState/setupDetectionLogic'
+import { retryWithBackoff } from 'lib/utils/async'
+import { addProductIntent } from 'lib/utils/product-intents'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+
+import { metricsHasMetricsRetrieve } from '../generated/api'
+import { canViewMetrics } from '../metricsAccess'
+
+// Session-scoped intent state: only an observed no-metrics -> has-metrics
+// transition counts as first ingestion. A team whose first check already
+// returns true (or was cached true) just has pre-existing metrics.
+let sawNoMetrics = false
+let firstIngestIntentFired = false
+
+/**
+ * Setup detection for the metrics empty state. Binary: the team has ingested at
+ * least one metric sample, or it hasn't. Without viewer access the check cannot
+ * run, so the status is `unknown` and the gate fails open to the scene, whose
+ * own access controls take over.
+ */
+export const metricsSetupLogic = createSetupDetectionLogic({
+ productKey: ProductKey.METRICS,
+ path: ['products', 'metrics', 'frontend', 'emptyState', 'metricsSetupLogic'],
+ detect: async () => {
+ if (!canViewMetrics()) {
+ return 'unknown'
+ }
+ const teamId = teamLogic.findMounted()?.values.currentTeamId
+ if (!teamId) {
+ return 'unknown'
+ }
+ const response = await retryWithBackoff(() => metricsHasMetricsRetrieve(String(teamId)), { maxAttempts: 3 })
+ return response.hasMetrics ? 'has-data' : 'needs-setup'
+ },
+ onDetected: (status) => {
+ if (status === 'needs-setup') {
+ sawNoMetrics = true
+ }
+ if (status === 'has-data' && sawNoMetrics && !firstIngestIntentFired) {
+ firstIngestIntentFired = true
+ void addProductIntent({
+ product_type: ProductKey.METRICS,
+ intent_context: ProductIntentContext.METRICS_FIRST_INGESTED,
+ })
+ }
+ },
+ // The first sample usually lands moments after the agent starts, so re-check
+ // often enough for the flip to feel immediate.
+ pollIntervalMs: 5000,
+ cacheHasData: true,
+})
diff --git a/products/metrics/frontend/metricsIngestionLogic.test.ts b/products/metrics/frontend/metricsIngestionLogic.test.ts
deleted file mode 100644
index c353fe2e8327..000000000000
--- a/products/metrics/frontend/metricsIngestionLogic.test.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { teamLogic } from 'scenes/teamLogic'
-
-import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
-import { initKeaTests } from '~/test/init'
-import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
-
-import { metricsHasMetricsRetrieve } from './generated/api'
-import { metricsIngestionLogic } from './metricsIngestionLogic'
-
-jest.mock('./generated/api', () => ({
- metricsHasMetricsRetrieve: jest.fn(),
-}))
-
-describe('metricsIngestionLogic', () => {
- let logic: ReturnType<typeof metricsIngestionLogic.build>
-
- // teamLogic is mounted via connect once `logic` mounts, so its actionCreators are available here.
- const firstIngestIntent = (): any =>
- teamLogic.actionCreators.addProductIntent({
- product_type: ProductKey.METRICS,
- intent_context: ProductIntentContext.METRICS_FIRST_INGESTED,
- })
-
- beforeEach(() => {
- localStorage.clear()
- window.POSTHOG_APP_CONTEXT = {
- ...window.POSTHOG_APP_CONTEXT,
- resource_access_control: {
- ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
- [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
- },
- } as AppContext
- initKeaTests()
- jest.mocked(metricsHasMetricsRetrieve).mockReset()
- })
-
- afterEach(() => {
- logic?.unmount()
- })
-
- // Distinguishes a team completing OTel setup mid-session (intent) from a team that simply
- // already had metrics (no intent) — firing on any `true` would mark every long-standing
- // team as newly intending and corrupt the activation funnel.
- it('records a product intent only on an observed no-metrics -> has-metrics transition, once', async () => {
- jest.mocked(metricsHasMetricsRetrieve).mockResolvedValue({ hasMetrics: false } as any)
- logic = metricsIngestionLogic()
- logic.mount()
- await expectLogic(logic)
- .toDispatchActions(['loadTeamHasMetricsSuccess'])
- .toNotHaveDispatchedActions([firstIngestIntent()])
-
- jest.mocked(metricsHasMetricsRetrieve).mockResolvedValue({ hasMetrics: true } as any)
- await expectLogic(logic, () => {
- logic.actions.loadTeamHasMetrics()
- }).toDispatchActions([firstIngestIntent()])
-
- await expectLogic(logic, () => {
- logic.actions.loadTeamHasMetrics()
- }).toNotHaveDispatchedActions([firstIngestIntent()])
- })
-
- it('a team that already has metrics on first check records no intent', async () => {
- jest.mocked(metricsHasMetricsRetrieve).mockResolvedValue({ hasMetrics: true } as any)
- logic = metricsIngestionLogic()
- logic.mount()
- await expectLogic(logic)
- .toDispatchActions(['loadTeamHasMetricsSuccess'])
- .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,
- resource_access_control: {
- ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
- [AccessControlResourceType.Metrics]: AccessControlLevel.None,
- },
- } as AppContext
- logic = metricsIngestionLogic()
- logic.mount()
-
- await expectLogic(logic).delay(10)
-
- expect(metricsHasMetricsRetrieve).not.toHaveBeenCalled()
-
- // A denied check must stay "unknown", not become "no metrics" - false would
- // show the setup prompt to a user on a team that may have plenty of metrics.
- await expectLogic(logic, () => {
- logic.actions.loadTeamHasMetrics()
- }).toFinishAllListeners()
-
- expect(metricsHasMetricsRetrieve).not.toHaveBeenCalled()
- expect(logic.values.hasMetrics).toBeUndefined()
- })
-})
diff --git a/products/metrics/frontend/metricsIngestionLogic.tsx b/products/metrics/frontend/metricsIngestionLogic.tsx
deleted file mode 100644
index f79cb3ef787f..000000000000
--- a/products/metrics/frontend/metricsIngestionLogic.tsx
+++ /dev/null
@@ -1,158 +0,0 @@
-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'
-
-import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
-
-import type { ProductIntentProperties } from '../../../frontend/src/lib/utils/product-intents'
-import { metricsHasMetricsRetrieve } from './generated/api'
-import { canViewMetrics } from './metricsAccess'
-
-const teamId = window.POSTHOG_APP_CONTEXT?.current_team?.id
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface metricsIngestionLogicValues {
- currentTeamId: number | null // teamLogic
- cachedTeamHasMetrics: boolean | null
- hasMetrics: boolean | undefined
- teamHasMetrics: boolean | undefined
- teamHasMetricsCheckFailed: boolean
- teamHasMetricsLoading: boolean
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface metricsIngestionLogicActions {
- addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
- loadTeamHasMetrics: () => any
- loadTeamHasMetricsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadTeamHasMetricsSuccess: (
- teamHasMetrics: boolean | undefined,
- payload?: any
- ) => {
- teamHasMetrics: boolean | undefined
- payload?: any
- }
- reportScrapeSnippetCopied: (variant: 'docker' | 'kubernetes') => {
- variant: 'docker' | 'kubernetes'
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface metricsIngestionLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- hasMetrics: (teamHasMetrics: boolean | undefined, cachedTeamHasMetrics: boolean | null) => boolean | undefined
- }
-}
-
-export type metricsIngestionLogicType = MakeLogicType<
- metricsIngestionLogicValues,
- metricsIngestionLogicActions,
- Record<string, any>,
- metricsIngestionLogicMeta
->
-
-export const metricsIngestionLogic = kea<metricsIngestionLogicType>([
- path(['products', 'metrics', 'frontend', 'metricsIngestionLogic']),
- connect(() => ({
- values: [teamLogic, ['currentTeamId']],
- actions: [teamLogic, ['addProductIntent']],
- })),
- actions({
- reportScrapeSnippetCopied: (variant: 'docker' | 'kubernetes') => ({ variant }),
- }),
- loaders(({ values }) => ({
- teamHasMetrics: {
- __default: undefined as boolean | undefined,
- loadTeamHasMetrics: async (): Promise<boolean | undefined> => {
- if (!canViewMetrics()) {
- // No access means "unknown", not "no metrics" - false would show the setup prompt
- return values.teamHasMetrics
- }
- const response = await retryWithBackoff(() => metricsHasMetricsRetrieve(String(values.currentTeamId)), {
- maxAttempts: 3,
- })
- return Boolean(response.hasMetrics)
- },
- },
- })),
-
- reducers({
- teamHasMetricsCheckFailed: [
- false,
- {
- loadTeamHasMetrics: () => false,
- loadTeamHasMetricsSuccess: () => false,
- loadTeamHasMetricsFailure: () => true,
- },
- ],
- cachedTeamHasMetrics: [
- null as boolean | null,
- { persist: true, prefix: `${teamId}__` },
- {
- // Only cache true - metrics don't disappear once ingested
- loadTeamHasMetricsSuccess: (_, { teamHasMetrics }) => teamHasMetrics || null,
- },
- ],
- }),
-
- 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
- // skip resolves with undefined and must not count.
- if (teamHasMetrics === false) {
- cache.sawNoMetrics = true
- }
- return
- }
- // Only an observed no-metrics -> has-metrics transition is an intent: the user
- // completed external OTel setup during this session. A team whose first check
- // already returns true (or was cached true) just has pre-existing metrics.
- if (cache.sawNoMetrics && !cache.firstIngestIntentFired) {
- cache.firstIngestIntentFired = true
- actions.addProductIntent({
- product_type: ProductKey.METRICS,
- intent_context: ProductIntentContext.METRICS_FIRST_INGESTED,
- })
- }
- },
- })),
-
- selectors({
- hasMetrics: [
- (s) => [s.teamHasMetrics, s.cachedTeamHasMetrics],
- (teamHasMetrics: boolean | undefined, cachedTeamHasMetrics: boolean | null): boolean | undefined =>
- teamHasMetrics ?? cachedTeamHasMetrics ?? undefined,
- ],
- }),
-
- afterMount(({ actions, values }) => {
- if (canViewMetrics() && values.cachedTeamHasMetrics !== true) {
- actions.loadTeamHasMetrics()
- }
- }),
-])