: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(empty-state): add shared ProductEmptyState gate with MCP analytics as reference adoption (#72442)
Rafael Audibert3af0672afdfa
diff --git a/.agents/skills/building-product-empty-states/SKILL.md b/.agents/skills/building-product-empty-states/SKILL.mdnew file mode 100644index 000000000000..19185c6cdf8c--- /dev/null+++ b/.agents/skills/building-product-empty-states/SKILL.md@@ -0,0 +1,103 @@+---+name: building-product-empty-states+description: Guide for adding a product setup empty state — the skippable first-run screen a product scene shows until real data arrives, built on the shared ProductEmptyState component. Use when adding an empty state or first-run/setup screen to a product scene, declaring `emptyState` on a `SceneExport`, writing a product setup-status detection logic, building an animated example-data preview widget, or migrating away from the deprecated `ProductIntroduction` component. Covers the `productSetupStatusLogic` single-layer contract, real-data detection rules, local-only skip semantics, wizard commands, and design tokens.+---++# Building product empty states++Before a user has set a product up, its scene should show a setup empty state: the product pitch and install command on the left, an animated preview of the product filled with realistic example data on the right. The shared component lives in `frontend/src/lib/components/ProductEmptyState/`; MCP analytics (`products/mcp_analytics/frontend/emptyState/`) is the reference adoption.++`ProductIntroduction` is **deprecated** — don't add new call sites. Both of its jobs fold into this system: "product not installed" (data-existence detection) and "no entities yet" (entity-count detection with a `primaryAction` create CTA).++## How it works++1. A scene declares `emptyState` on its `SceneExport`. The app shell (`frontend/src/scenes/App.tsx`) wraps the scene in `ProductEmptyStateGate` — the scene component itself contains **no** empty-state branching.+2. The gate mounts the product's **detection logic**, which pushes a normalized status into `productSetupStatusLogic({ productKey })` — the app-wide single read point for "is product X set up?".+3. The gate renders the setup empty state for `needs-setup` / `waiting-for-data`, and the scene untouched for `has-data`. While `loading` it shows the standard scene-level spinner — the one shared loading treatment. **Never add a product-specific loading fallback.**+4. Statuses are **preloaded at app boot**: `productSetupPreloadLogic` (mounted in `App.tsx`) answers every manifest-declared probe (each product's `setupProbe`, aggregated into `productSetupProbes`) with one combined event-count query on idle, so by the time a user opens the scene the status is usually already known and the spinner never shows. The product's in-scene detection stays the fresher source of truth.+5. Users can always **skip**. Skip is local-only (localStorage, keyed team + product, never backend-persisted); detection keeps polling, and a slim "Set up" banner stays visible until data lands.++## Adoption steps++### 1. Write (or extend) the detection logic++The status must come from a **real signal**: a data-existence query (HogQL count / exists API), the product's opt-in flag, or an entity count for creation-first products. Never a dismissal flag — `has_completed_onboarding_for` is routing metadata, not evidence of data.++Template: `products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.ts` — a cheap event-count loader with `refresh: 'force_blocking'` (a cached pre-ingestion `[0,0]` would otherwise stick), a `cache.disposables` poll that stops once data arrives, and product-intent registration. Push the status from a listener:++```ts+connect(() => ({+ actions: [productSetupStatusLogic({ productKey: ProductKey.MY_PRODUCT }), ['setDetectedStatus']],+ values: [productSetupStatusLogic({ productKey: ProductKey.MY_PRODUCT }), ['status as setupStatus']],+})),+listeners(({ actions, values }) => ({+ loadSignalsSuccess: () => actions.setDetectedStatus(values.hasData ? 'has-data' : 'needs-setup'),+ loadSignalsFailure: () => {+ // Never strand the gate on its spinner: if nothing has answered yet, fail+ // open to the real scene. Don't downgrade an existing answer on a poll blip.+ if (values.setupStatus === 'loading') {+ actions.setDetectedStatus('unknown')+ }+ },+})),+```++Statuses: `loading` (not yet known - the gate holds a spinner, never flashes the empty dashboard), `unknown` (detection failed with no earlier answer - the gate fails open to the scene), `needs-setup`, `waiting-for-data` (optional middle state: instrumented but no traffic yet), `has-data`. Binary products simply never emit `waiting-for-data`. **Your detection logic must handle its failure path** - a query that fails forever must not leave the status `loading`. Statuses are stamped with the team they were detected for, so project switches automatically reset to `loading`.++### 2. Create the config++`products/<product>/frontend/emptyState/<product>EmptyState.tsx` exports a `SceneProductEmptyState` (see `lib/components/ProductEmptyState/types.ts` for every field). Reference: `products/mcp_analytics/frontend/emptyState/mcpAnalyticsEmptyState.tsx`. Notes:++- **Accent**: use the product's `--color-product-<name>-light`/`-dark` token (`frontend/src/styles/base.scss`). If your product has none, add one there (get the color from design) rather than hardcoding a hex.+- **Wizard vs primary action**: SDK-installed products set `wizard: { slug }` (the slug must exist in `@posthog/wizard`); creation-first products (flags, surveys) set `primaryAction` instead. Self-hosted degrades automatically: no cloud → the terminal hides and the manual path is promoted.+- **`featureFlag`**: set it when the scene is already flag-gated (so the scene's own gate keeps handling flag-off) or to roll the empty state out gradually.+- **Hedgehog**: a `pngHoggie(...)`-wrapped module — import only inside the product chunk (eager-graph guard: `frontend/bin/check-eager-graph.mjs`). Never hardcode image URLs (e.g. Cloudinary) — `@posthog/brand` assets only.+- **`text` is keyed by mode**: provide the `needs-setup` base; add a `waiting-for-data` entry only if your product has that middle state (missing fields fall back to the base). Sentence case, benefit-first, no AI tells (see "User-facing copy" in `CLAUDE.md`).+- **Product header**: the gate keeps the product header (name, description, icon) above the empty state automatically, sourced from the scene's `SceneConfig` in your product manifest — make sure your manifest's scene entry has `name`, `description`, and `iconType` set.++### 3. Build the signature preview++`Preview` is the right-hand widget: the product's most recognizable UI, populated with **static, realistic fake data** (label it "example data"). Reference: `products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.tsx`.++- The shared layout renders it vertically centered on a darker full-height panel — the preview itself must **never scroll or loop**; a handful of static rows is the whole job. Style with tailwind; any motion is CSS only (no `setInterval`, no computed timestamps) with `motion-reduce:` variants for reduced motion.+- Honor the `mode` prop: `waiting-for-data` should read as "listening" (e.g. a pinned spinner row).++### 4. Declare it on the scene++```ts+export const scene: SceneExport = {+ component: MyScene,+ logic: mySceneLogic,+ productKey: ProductKey.MY_PRODUCT,+ emptyState: myProductEmptyState,+}+```++Then **delete** the scene's bespoke empty/loading branches (including any custom loading component) — the gate owns them now. This is strictly an **in-product** surface: do not modify the app-wide onboarding flow (`frontend/src/scenes/onboarding/`), and if the product currently redirects never-set-up users into that flow, remove the redirect — the empty state now covers first-visit setup right in the scene (reference: `mcpAnalyticsSceneLogic.ts`, which kept only its landing-tab logic).++### 4b. Register a boot-time probe++Declare a `setupProbe` in your product manifest (`products/<name>/manifest.tsx`) - the `productKey`, the event names that prove your product has data (and optionally the "instrumented but no traffic" events), and the `featureFlag` to gate on, mirroring your detection logic's semantics. `build-products.mjs` aggregates every manifest's `setupProbe` into `productSetupProbes` (regenerate with `pnpm build:products`), and `productSetupPreloadLogic` answers them at boot. This is what lets the app resolve your status before the user ever opens the scene. The probe query only looks back `PRELOAD_LOOKBACK_DAYS` (so it prunes to recent partitions); your in-scene detection stays the source of truth for anything older. The `ProductSetupProbe` shape and the count-to-status mapping live in `lib/components/ProductEmptyState/setupProbes.ts`. Products whose detection isn't event-based (exists APIs, entity counts) skip this for now; their status resolves on first scene visit.++### 5. Test the status mapping++Extend the detection logic's existing jest file with a parameterized push-through case: mount with mocked signals, assert `productSetupStatusLogic({ productKey }).values.status`. Reference: `products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.test.ts`. Run `/writing-tests` first; don't re-test the shared gate or skip mechanics (covered in `productSetupStatusLogic.test.ts`).++### 6. Add storybook coverage++Add one story per mode to `lib/components/ProductEmptyState/ProductEmptyState.stories.tsx` with `productEmptyStateStory(myProductEmptyState, mode)` (from `storybookHelpers.ts`) - it renders your real config and gives you visual-regression snapshots for free. Default mocks answer queries and product intents so a bare call renders cleanly; pass `mocks` to drive your status indicator into a specific state (see the MCP stories).++## Migrating a ProductIntroduction call site++- Full-scene "product not set up" uses → this system, via steps 1-4.+- Entity-list empties ("create your first X") → detection = entity count, `primaryAction` = the create button.+- The SetupPrompt family (error_tracking, logs, tracing, metrics, ai_observability) already has detection logics — step 1 is just the `connect` + push; then replace the wrapper with a scene-level `emptyState` declaration.+- `has_seen_product_intro_for` dismissals are superseded by local skip; don't migrate the flag.++## QA checklist++- Dark mode, reduced motion (`prefers-reduced-motion`), self-hosted (no wizard terminal).+- Loading never flashes the real scene or the empty dashboard.+- Skip → scene renders immediately, persists across reload, "Set up" banner shows, onboarding redirect suppressed.+- Non-adopting scenes unaffected (the gate is a strict no-op without `emptyState`).+- `pnpm --filter=@posthog/frontend typescript:check`, storybook snapshots stable.diff --git a/frontend/build-products.mjs b/frontend/build-products.mjsindex cac63f2d38fa..3a89d8310685 100644--- a/frontend/build-products.mjs+++ b/frontend/build-products.mjs@@ -73,6 +73,7 @@ function buildProductManifests() {const routes = []const redirects = []const fileSystemTypes = []+ const setupProbes = []const treeItemsNew = {}const treeItemsGames = {}const treeItemsMetadata = {}@@ -107,6 +108,9 @@ function buildProductManifests() {sceneConfigs.push(cfg)}})+ } else if (name === 'setupProbe') {+ // One object per manifest, aggregated into the `productSetupProbes` array.+ setupProbes.push(cloneNode(node.initializer))} else {ts.forEachChild(node, walk)}@@ -274,6 +278,9 @@ function buildProductManifests() {if (!globalNames.has('FileSystemImport')) {addImport('~/queries/schema/schema-general', 'typeNamed', 'FileSystemImport')}+ if (!globalNames.has('ProductSetupProbe')) {+ addImport('lib/components/ProductEmptyState/setupProbes', 'typeNamed', 'ProductSetupProbe')+ }// 5. Serialise gathered imports → valid TypeScript code// (no duplicate names, type/value kept separate)@@ -320,6 +327,11 @@ function buildProductManifests() {const serializedFileSystemTypes = makeObjExpr(fileSystemTypes.sort((a, b) => a.name.text.localeCompare(b.name.text)))+ const serializedSetupProbes = printer.printNode(+ ts.EmitHint.Unspecified,+ ts.factory.createArrayLiteralExpression(setupProbes),+ ts.createSourceFile('', '', ts.ScriptTarget.ESNext)+ )const serializedTreeItemsNew = makeArrExpr(treeItemsNew)const serializedTreeItemsProducts = makeArrExpr(treeItemsProducts)const serializedTreeItemsGames = makeArrExpr(treeItemsGames)@@ -352,6 +364,9 @@ function buildProductManifests() {${autogenDisclaimer}export const fileSystemTypes = ${serializedFileSystemTypes}+ ${autogenDisclaimer}+ export const productSetupProbes: ProductSetupProbe[] = ${serializedSetupProbes}+${autogenDisclaimer}export const getTreeItemsNew = (): FileSystemImport[] => ${serializedTreeItemsNew}diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8131fc9b1e91..f1ce7c7203cf 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1636,6 +1636,18 @@ snapshots:hash: v1.k794b7964.1a7835b12a48c2b04c7a3bb1731c2582b45ec28a3042827ad9ff7fcee708e44c.1jIs0ZfSBza47nPWDk_DLIkvW9tlcFpvEonyVU_5FVscomponents-product-empty-state--hog-layout-responsive-with-main-content-container-queries--light:hash: v1.k794b7964.21032c000615555ecc02b4546fc2425c677f06c451b6b8d10307c4ec89faf6a0.1ZPt3gD7fOiCI28QnBWuHfoBz6EhHsDtdHBWv04lQMg+ components-product-empty-state--mcp-analytics-needs-setup--dark:+ hash: v1.k794b7964.96b74daaa8de6ae7205da58c89dc6fcc7abc783d43d1dfe552dcd173da06de8c.zf0X-77OyUQSa8ryOwocWYWnsltAEccWd3hjH7t6WzE+ components-product-empty-state--mcp-analytics-needs-setup--light:+ hash: v1.k794b7964.6136228cdbceb19c9382e1d0e467d6783a15879546b0f49f60c4a2bc406d9e58.YKebSnq-iuiVbNo1JPs8Q67CwzZX_3swPDPIt3Sb8qk+ components-product-empty-state--mcp-analytics-waiting-for-data--dark:+ hash: v1.k794b7964.a5db8b3fba90c2ebc4ad2b6c3d8be1ef179c920a576bb95d57059fd785f4b45f.vr8Dy59N9OOLni-5yhqGNnQBOVYbO3_9giTOVl_zaK4+ components-product-empty-state--mcp-analytics-waiting-for-data--light:+ hash: v1.k794b7964.d832f1a88d382c4b48e0998fccd24711fcab84c1d6483e16fba11aee13c1fff2.kpyIq-AzkbWWQNEI3YarmI7j-8oUZ3JFvDWY3idEbYk+ components-product-empty-state--mcp-analytics-without-wizard--dark:+ hash: v1.k794b7964.1c47697aee2d066caeb333779050edc862323f4b60c822a2769da8b674cac542.bjAaIsrC_ytw29rSryk7kdU441aLnMTBnSrU_tpo0oM+ components-product-empty-state--mcp-analytics-without-wizard--light:+ hash: v1.k794b7964.884452e78cb03952beb1e19dfa274e4164a5830663a5041d51389d243a04c521.Hxo5ZUQv8-FN80GvzUxLp0YTykQdIkJe7uCODD4wliccomponents-product-empty-state--not-empty-with-action--dark:hash: v1.k794b7964.d3371e56eeca6104b3abd3f662f074c11e13beb35ae7f7aab1691ec84cdf0399.eh3J5gvQtp0morSaAJJZlOj0JE0VBGdfxIIpZYHJAJocomponents-product-empty-state--not-empty-with-action--light:@@ -7545,7 +7557,7 @@ snapshots:scenes-other-onboarding-legacy--ai-observability-sdk-install--dark:hash: v1.k794b7964.bda729452fe657398c480b5294c7e56e7d3635b19abb4002709522f13f369305.LhnETlVSPxPSo_ngJjnaI12lyQMOsH0FpWWkQEq2KiMscenes-other-onboarding-legacy--ai-observability-sdk-install--light:- hash: v1.k794b7964.64e2dadc01e847ba81ba43ae802bbfd18631e50257d614530d96ce653be5a79b.6FFnEwMajbRRFZskpqcVbBDQuJvWHC2I4CmuVZ9Hmls+ hash: v1.k794b7964.a1842546695652319121598bd2aaa2704849e8e5955eb93f83c41f35c86badf0.kDO2SUbAAToRtImoolidHjnavtu6do9Y-rsce2RKn9cscenes-other-onboarding-legacy--alerts--dark:hash: v1.k794b7964.c22b202da34ceea01a9dc7162520e35f2366b891dc31dfef3f4cc1c02a732925.NcL-srF2HqgOaQZS2T1bWylckrTCHkBSYe72zVWgpIwscenes-other-onboarding-legacy--alerts--light:@@ -7573,7 +7585,7 @@ snapshots:scenes-other-onboarding-legacy--sdk-install--dark:hash: v1.k794b7964.f13a0b1bc0a7c913b5a646ad6f4b5b7a7ce710f2e47cda5a690223b520081e04.lvFIUEL8PE1wjTEDg9pkETDK92FthhUTV-NcPWAMS7oscenes-other-onboarding-legacy--sdk-install--light:- hash: v1.k794b7964.18d05e299c4a40b287c82a60336a90fb0274a4b80f0d508ac133bc8d45eb0b85.vUUYGmiP92yv5fyRj_Q2XUNZhIMNnMwYXhwATJSHmdE+ hash: v1.k794b7964.0dee2ad0a0147363b315e0c1d124a3c31e464a060a50800431b107cc33986e53.7wpbC_M2I7IlJtPytFqw2cBftc8YgPDusy2KgLkmUXQscenes-other-onboarding-legacy--session-replay-configuration--dark:hash: v1.k794b7964.482b435a0c7fb6c0dca145e39284ac5aa006030ab1035b723e003d35848e5e2d.i34nHHj6IPgy0lXkozVwUKpCPi2VwzUdeElaD7rz6Vcscenes-other-onboarding-legacy--session-replay-configuration--light:@@ -7597,7 +7609,7 @@ snapshots:scenes-other-onboarding-legacy-install-step--control-arm--dark:hash: v1.k794b7964.f13a0b1bc0a7c913b5a646ad6f4b5b7a7ce710f2e47cda5a690223b520081e04.e-amahshVCgQCqBHq3BIQanQqoUyk5XiuHSw8w8spfEscenes-other-onboarding-legacy-install-step--control-arm--light:- hash: v1.k794b7964.18d05e299c4a40b287c82a60336a90fb0274a4b80f0d508ac133bc8d45eb0b85.gC_x7uIHFCn2MnPytLcK7oqq4kF6CkNvjPLSCZ7v7tw+ hash: v1.k794b7964.710900c728f127be4b17b3993f833dae3270a5f024da1294653d127ac343d440.GFx5lI0LaPlR1m8thVqJObGd0gS871nc8XWbrTNFIS0scenes-other-onboarding-legacy-install-step--test-arm--dark:hash: v1.k794b7964.5963b383d7d2a3f876f2047c116e50bc3a092fd34fe42c659b76a57767de8268.aZlFPXrA9RCYIpXFCV50iqgffZ-26-8qKML2-PffSuQscenes-other-onboarding-legacy-install-step--test-arm--light:diff --git a/frontend/src/layout/scenes/components/SceneMenuBar.tsx b/frontend/src/layout/scenes/components/SceneMenuBar.tsxindex 9df54a11f9f3..3aad1092b4e1 100644--- a/frontend/src/layout/scenes/components/SceneMenuBar.tsx+++ b/frontend/src/layout/scenes/components/SceneMenuBar.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'import posthog from 'posthog-js'-import { Children, ComponentProps, MouseEvent, ReactNode, useEffect } from 'react'+import { Children, ComponentProps, MouseEvent, ReactNode, useContext, useEffect } from 'react'import { IconExternal, IconSidePanel, IconSparkles } from '@posthog/icons'import {@@ -24,6 +24,7 @@ import {PopoverTrigger,} from '@posthog/quill'+import { SetupReminderContext } from 'lib/components/ProductEmptyState/setupReminderContext'import { IconBlank } from 'lib/lemon-ui/icons'import { LinkPrimitive } from 'lib/lemon-ui/Link'import { cn } from 'lib/utils/css-classes'@@ -62,37 +63,44 @@ export function SceneMenuBar({ children, className }: SceneMenuBarProps): JSX.Elconst layout = sceneLayoutConfig?.layout ?? 'app'const isPaddedLayout = PADDED_LAYOUTS.has(layout)+ // A skipped product empty state parks its "isn't receiving data yet" reminder here so it+ // sits just below the bar. Null for every other scene, so nothing extra renders.+ const setupReminder = useContext(SetupReminderContext)+useEffect(() => {captureSceneMenuBar('scene menu bar shown')}, [])return (- <div- data-attr="scene-menu-bar"- data-scene-layout={layout}- className={cn(- 'scene-menu-bar px-0.5 py-0.5 border-b border-primary flex items-center justify-between',- // Bleed past the scene container's padding so the bar feels full-width — only- // safe when the layout actually has padding to cancel. Unpadded layouts- // (app-raw, plain, etc.) would overflow.- isPaddedLayout && '-mx-4 -mt-4',- // When LemonTabs is the immediately preceding sibling it already bleeds with- // its own -mt-6, leaving the menu bar floating in the flex `gap-y-*`. Pull the- // bar up so they sit flush.- '[.LemonTabs+&]:-mt-6',- className- )}- >- {/*- Right-side cluster lives OUTSIDE <Menubar> so it doesn't pollute the Menubar's- CompositeRoot — that's what coordinates ArrowLeft/Right navigation and- hover-to-switch between menus.- */}- <Menubar className="gap-0 border-0">{children}</Menubar>+ <>+ <div+ data-attr="scene-menu-bar"+ data-scene-layout={layout}+ className={cn(+ 'scene-menu-bar px-0.5 py-0.5 border-b border-primary flex items-center justify-between',+ // Bleed past the scene container's padding so the bar feels full-width — only+ // safe when the layout actually has padding to cancel. Unpadded layouts+ // (app-raw, plain, etc.) would overflow.+ isPaddedLayout && '-mx-4 -mt-4',+ // When LemonTabs is the immediately preceding sibling it already bleeds with+ // its own -mt-6, leaving the menu bar floating in the flex `gap-y-*`. Pull the+ // bar up so they sit flush.+ '[.LemonTabs+&]:-mt-6',+ className+ )}+ >+ {/*+ Right-side cluster lives OUTSIDE <Menubar> so it doesn't pollute the Menubar's+ CompositeRoot — that's what coordinates ArrowLeft/Right navigation and+ hover-to-switch between menus.+ */}+ <Menubar className="gap-0 border-0">{children}</Menubar>- <Badge className="hidden @[800px]:flex">OS-like menu (alpha)</Badge>- <SceneMenuBarRightLinks />- </div>+ <Badge className="hidden @[800px]:flex">OS-like menu (alpha)</Badge>+ <SceneMenuBarRightLinks />+ </div>+ {setupReminder}+ </>)}diff --git a/frontend/src/lib/components/CommandBlock/CommandBlock.tsx b/frontend/src/lib/components/CommandBlock/CommandBlock.tsxindex abb2efa5969d..fce0a59f21f2 100644--- a/frontend/src/lib/components/CommandBlock/CommandBlock.tsx+++ b/frontend/src/lib/components/CommandBlock/CommandBlock.tsx@@ -49,7 +49,8 @@ interface CommandBlockProps {condensed?: boolean}-function condenseCommand(command: string): string {+/** Strips display noise (`-y` flags, `@latest` pins) from a command; copy the original, show this. */+export function condenseCommand(command: string): string {return command.replace(/ -y\b/g, '').replace(/@latest\b/g, '')}diff --git a/frontend/src/lib/components/CommandBlock/TerminalCard.scss b/frontend/src/lib/components/CommandBlock/TerminalCard.scssnew file mode 100644index 000000000000..8d603dfc13da--- /dev/null+++ b/frontend/src/lib/components/CommandBlock/TerminalCard.scss@@ -0,0 +1,49 @@+// Only the animations tailwind can't express: a steps() timing function driven by+// a CSS variable, and a keyframe animating to a variable width. Everything else+// on TerminalCard is tailwind.++.TerminalCard__cmd {+ width: var(--terminal-cmd-chars);+ animation: TerminalCard__type 2s steps(var(--terminal-cmd-steps, 40), end) 0.4s both;++ // Storybook snapshots: render the finished state, no motion.+ &--static {+ width: auto;+ animation: none;+ }+}++.TerminalCard__caret {+ animation: TerminalCard__blink 1.1s step-end infinite;++ &--static {+ animation: none;+ }+}++@keyframes TerminalCard__type {+ from {+ width: 0;+ }++ to {+ width: var(--terminal-cmd-chars);+ }+}++@keyframes TerminalCard__blink {+ 50% {+ opacity: 0;+ }+}++@media (prefers-reduced-motion: reduce) {+ .TerminalCard__cmd {+ width: auto;+ animation: none;+ }++ .TerminalCard__caret {+ animation: none;+ }+}diff --git a/frontend/src/lib/components/CommandBlock/TerminalCard.tsx b/frontend/src/lib/components/CommandBlock/TerminalCard.tsxnew file mode 100644index 000000000000..afff24210323--- /dev/null+++ b/frontend/src/lib/components/CommandBlock/TerminalCard.tsx@@ -0,0 +1,100 @@+import './TerminalCard.scss'++import { useState } from 'react'++import { IconCheck, IconCopy } from '@posthog/icons'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { cn } from 'lib/utils/css-classes'+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'++import { condenseCommand } from './CommandBlock'++const COPIED_RESET_MS = 1700++interface TerminalCardProps {+ command: string+ /** Label passed to the copy-to-clipboard toast (e.g. "MCP wizard command"). */+ copyLabel: string+ className?: string+}++/**+ * A dark terminal-chrome card that types its command out with a blinking caret.+ * The hero treatment for install commands on product empty states — for a compact+ * inline command pill, use `CommandBlock` instead.+ *+ * Styled with tailwind except the typewriter/caret animations (TerminalCard.scss):+ * a `steps(var(--steps))` timing function and a `width: var(--chars)` keyframe+ * can't be expressed as utilities.+ */+export function TerminalCard({ command, copyLabel, className }: TerminalCardProps): JSX.Element {+ const [copied, setCopied] = useState(false)++ // Freeze the typewriter in storybook so visual snapshots are deterministic.+ const isStatic = inStorybook() || inStorybookTestRunner()++ // Show the command without `-y`/`@latest` noise; the full `command` is still what gets copied.+ const displayCommand = condenseCommand(command)++ const handleCopy = (): void => {+ void copyToClipboard(command, copyLabel)+ setCopied(true)+ window.setTimeout(() => setCopied(false), COPIED_RESET_MS)+ }++ return (+ // Deliberately dark in both themes (primitive grays don't flip with the theme): it's a terminal.+ <div className={cn('overflow-hidden rounded border border-gray-700 bg-gray-900 text-[0.8125rem]', className)}>+ <div className="flex items-center gap-1.5 border-b border-gray-700 bg-gray-800 px-2.5 py-1.5">+ <span className="size-2.5 rounded-full bg-red-500" />+ <span className="size-2.5 rounded-full bg-yellow-400" />+ <span className="size-2.5 rounded-full bg-[var(--color-green-500)]" />+ <span className="ml-1.5 flex-1 font-mono text-[0.6875rem] text-gray-400">bash</span>++ <LemonButton+ size="xsmall"+ icon={copied ? <IconCheck /> : <IconCopy />}+ onClick={handleCopy}+ // Force white regardless of theme: LemonButton colors its inner chrome via+ // `--lemon-button-color`, so overriding that (not `text-white`) is what actually lands.+ className="[--lemon-button-color:#fff] [--lemon-button-icon-opacity:1]"+ aria-label={`Copy command: ${command}`}+ >+ {copied ? 'Copied' : 'Copy'}+ </LemonButton>+ </div>+ <div className="flex items-baseline gap-2 overflow-x-auto whitespace-nowrap px-4 py-3.5 font-mono">+ <span className="select-none text-[var(--color-green-500)]">$</span>+ <span className="inline-flex min-w-0 items-baseline">+ <code+ className={cn(+ 'inline-block max-w-full overflow-hidden whitespace-nowrap !border-0 !bg-transparent !p-0 text-gray-100',+ 'TerminalCard__cmd',+ isStatic && 'TerminalCard__cmd--static'+ )}+ // The typewriter reveals the command by animating width in `ch` units,+ // so the CSS needs the character count.+ style={+ {+ '--terminal-cmd-chars': `${displayCommand.length}ch`,+ '--terminal-cmd-steps': displayCommand.length,+ } as React.CSSProperties+ }+ >+ {displayCommand}+ </code>+ <span+ className={cn(+ 'ml-0.5 inline-block h-[1em] w-[7px] self-center bg-gray-100',+ 'TerminalCard__caret',+ isStatic && 'TerminalCard__caret--static'+ )}+ aria-hidden="true"+ />+ </span>+ </div>+ </div>+ )+}diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsxnew file mode 100644index 000000000000..f71968c4554e--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx@@ -0,0 +1,54 @@+import { Meta } from '@storybook/react'++import type { Mocks } from '~/mocks/utils'++import { mcpAnalyticsEmptyState } from 'products/mcp_analytics/frontend/emptyState/mcpAnalyticsEmptyState'++import { ProductEmptyState } from './ProductEmptyState'+import { ProductEmptyStateStory, productEmptyStateStory } from './storybookHelpers'++// Every adopting product renders its real empty-state config here (the exact object+// its scene gate uses) via productEmptyStateStory, so storybook and visual regression+// cover the shipped surface rather than a demo.++/**+ * The MCP status indicator polls a signal query - answer it per story so the+ * indicator matches the story's mode. Signal row shape:+ * [has_initialize, tool_calls_total, tool_calls_7d, first_call_at]+ */+function mcpSignalMocks(hasInitialize: boolean): Mocks {+ return {+ post: {+ '/api/environments/:team_id/query/:kind': [+ 200,+ { results: [[hasInitialize, 0, 0, '1970-01-01T00:00:00Z']] },+ ],+ },+ }+}++const meta: Meta<typeof ProductEmptyState> = {+ title: 'Components/Product Empty State',+ component: ProductEmptyState,+}+export default meta++export const MCPAnalyticsNeedsSetup: ProductEmptyStateStory = productEmptyStateStory(+ mcpAnalyticsEmptyState,+ 'needs-setup',+ { mocks: mcpSignalMocks(false) }+)++export const MCPAnalyticsWaitingForData: ProductEmptyStateStory = productEmptyStateStory(+ mcpAnalyticsEmptyState,+ 'waiting-for-data',+ { mocks: mcpSignalMocks(true) }+)++// No wizard configured (the self-hosted rendering, where the terminal hides and the+// manual setup path is promoted).+export const MCPAnalyticsWithoutWizard: ProductEmptyStateStory = productEmptyStateStory(+ mcpAnalyticsEmptyState,+ 'needs-setup',+ { config: { wizard: undefined }, mocks: mcpSignalMocks(false) }+)diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsxnew file mode 100644index 000000000000..31609de63358--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx@@ -0,0 +1,121 @@+import { useActions } from 'kea'++import { IconBook, IconGear } from '@posthog/icons'++import { TerminalCard } from 'lib/components/CommandBlock/TerminalCard'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'++import { productSetupStatusLogic } from './productSetupStatusLogic'+import type { ProductEmptyStateConfig, ProductEmptyStateMode, ProductEmptyStateText } from './types'++export interface ProductEmptyStateProps {+ config: ProductEmptyStateConfig+ mode: ProductEmptyStateMode+}++const ACCENT_TEXT = 'text-[var(--empty-state-accent)] dark:text-[var(--empty-state-accent-dark)]'++/**+ * The product setup empty state: pitch + install command on the left, an animated+ * preview of the product filled with example data on the right. Shown before+ * a product has been set up — gate it with `ProductEmptyStateGate` (or declare+ * `emptyState` on the scene's `SceneExport` and the app shell gates for you).+ */+export function ProductEmptyState({ config, mode }: ProductEmptyStateProps): JSX.Element {+ const { wizardCommand, isCloudOrDev } = useWizardCommand(config.wizard?.slug, {+ pinProjectId: config.wizard?.pinProjectId,+ })+ const { skipEmptyState } = useActions(productSetupStatusLogic({ productKey: config.productKey }))++ // Mode-specific text overrides the base; missing fields fall back to it.+ const text: ProductEmptyStateText = { ...config.text['needs-setup'], ...config.text[mode] }++ // Wizard commands only work against cloud; self-hosted falls back to the manual path.+ const showWizard = !!config.wizard && isCloudOrDev++ const manualUrl = config.manualSetupUrl ?? config.docsUrl+ const Hedgehog = config.hedgehog+ const Preview = config.Preview++ return (+ <div+ // Fill the scene: viewport minus the app chrome and the product header above us.+ className="grid w-full flex-1 grid-cols-1 items-stretch gap-10 md:grid-cols-[minmax(0,1fr)_40%] min-h-[calc(100vh-var(--breadcrumbs-height-full,0px)-var(--scene-padding,1rem)-4rem)]"+ style={+ {+ '--empty-state-accent': config.accentColor,+ '--empty-state-accent-dark': config.accentColorDark ?? config.accentColor,+ } as React.CSSProperties+ }+ >+ <div className="mx-auto flex w-full min-w-0 max-w-[36rem] flex-col justify-center gap-4 px-6">+ <div className="flex flex-col items-start gap-3">+ {Hedgehog ? <Hedgehog className="w-32 shrink-0" /> : null}+ <div className="inline-flex items-center gap-2.5 text-4xl font-bold [&_svg]:text-[2.25rem]">+ <span className={ACCENT_TEXT}>{config.icon}</span>+ <span>{config.productName}</span>+ </div>+ </div>+ <div className="flex flex-col gap-1">+ <h2 className="text-xl font-semibold m-0">{text.headline}</h2>+ <p className="text-secondary text-sm m-0">{text.lead}</p>+ </div>++ {text.hint ? <div className="text-xs text-tertiary mt-2">{text.hint}</div> : null}++ {showWizard ? (+ <TerminalCard command={wizardCommand} copyLabel={`${config.productName} wizard command`} />+ ) : config.primaryAction ? (+ <LemonButton+ type="primary"+ to={config.primaryAction.to}+ onClick={config.primaryAction.onClick}+ className="self-start"+ >+ {config.primaryAction.label}+ </LemonButton>+ ) : manualUrl ? (+ <LemonButton type="primary" to={manualUrl} targetBlank className="self-start">+ Set up {config.productName}+ </LemonButton>+ ) : null}++ {config.statusIndicator ? <div className="text-xs">{config.statusIndicator}</div> : null}++ <div className="flex items-center gap-4">+ {showWizard && manualUrl ? (+ <LemonButton type="secondary" icon={<IconGear />} to={manualUrl} targetBlank>+ Configure manually+ </LemonButton>+ ) : null}+ {config.docsUrl ? (+ <LemonButton size="xsmall" type="tertiary" icon={<IconBook />} to={config.docsUrl} targetBlank>+ Read the docs+ </LemonButton>+ ) : null}+ <LemonButton size="xsmall" type="tertiary" onClick={skipEmptyState}>+ Skip for now+ </LemonButton>+ </div>+ </div>++ <div+ className="hidden min-w-0 flex-col justify-center gap-3 p-10 md:flex rounded-md border border-primary"+ style={{+ backgroundImage:+ 'linear-gradient(135deg, color-mix(in oklab, var(--empty-state-accent) 16%, transparent) 0%, color-mix(in oklab, var(--empty-state-accent) 5%, transparent) 45%, transparent 80%)',+ }}+ >+ <div className="flex items-center gap-2 text-xs font-semibold text-secondary">+ <span+ className="size-2 rounded-full bg-[var(--empty-state-accent)] dark:bg-[var(--empty-state-accent-dark)] animate-pulse motion-reduce:animate-none"+ aria-hidden="true"+ />+ {config.previewLabel}+ </div>+ <Preview mode={mode} />+ </div>+ </div>+ )+}diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.tsxnew file mode 100644index 000000000000..8d096a7a34dd--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.tsx@@ -0,0 +1,120 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import type { ReactNode } from 'react'++import { FEATURE_FLAGS } from 'lib/constants'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { SpinnerOverlay } from 'lib/lemon-ui/Spinner'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { sceneLogic } from 'scenes/sceneLogic'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import { ProductEmptyState } from './ProductEmptyState'+import { productSetupStatusLogic } from './productSetupStatusLogic'+import { SetupReminderContext } from './setupReminderContext'+import type { ProductEmptyStateConfig, SceneProductEmptyState } from './types'++export interface ProductEmptyStateGateProps {+ emptyState: SceneProductEmptyState+ children: ReactNode+}++/**+ * Gates scene content on the product's setup status:+ * - `loading` → hold a spinner (never flash the real scene before we know)+ * - `needs-setup` / `waiting-for-data` → the ProductEmptyState setup screen+ * - `has-data` / `unknown` (or the user skipped) → the scene, untouched+ *+ * Mounts the product's detection logic, which pushes its normalized status into+ * `productSetupStatusLogic`. Wired automatically by the app shell for scenes that+ * declare `emptyState` on their `SceneExport`.+ */+export function ProductEmptyStateGate({ emptyState, children }: ProductEmptyStateGateProps): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)++ // When the empty state is flag-gated, stay a strict no-op while the flag is off —+ // don't even mount detection (the inner component is what mounts it).+ if (emptyState.featureFlag && !featureFlags[emptyState.featureFlag]) {+ return <>{children}</>+ }+ return <ProductEmptyStateGateInner emptyState={emptyState}>{children}</ProductEmptyStateGateInner>+}++function ProductEmptyStateGateInner({ emptyState, children }: ProductEmptyStateGateProps): JSX.Element {+ const { config, statusLogic } = emptyState+ useMountedLogic(statusLogic)+ const setupLogic = productSetupStatusLogic({ productKey: config.productKey })+ const { status, skipped, showEmptyState, mode } = useValues(setupLogic)+ const { unskipEmptyState } = useActions(setupLogic)+ const { featureFlags } = useValues(featureFlagLogic)++ if (skipped) {+ // Skip bypasses the screen, not detection: render the scene, plus a "Set up" reminder+ // until data lands, so there's always a way back to setup.+ const needsSetup = status === 'needs-setup' || status === 'waiting-for-data'+ const reminder = needsSetup ? (+ <LemonBanner type="info" action={{ children: `Set up ${config.productName}`, onClick: unskipEmptyState }}>+ {config.productName} isn't receiving data yet.+ </LemonBanner>+ ) : null+ // With the menu bar on, the reminder renders just below the bar (the scene's+ // SceneMenuBar consumes the context). With it off there is no consumer, so+ // render the banner here - otherwise a skipped product has no way back.+ if (featureFlags[FEATURE_FLAGS.SCENE_MENU_BAR]) {+ return <SetupReminderContext.Provider value={reminder}>{children}</SetupReminderContext.Provider>+ }+ return (+ <>+ {reminder ? <div className="mb-4">{reminder}</div> : null}+ {children}+ </>+ )+ }+ if (status === 'loading') {+ // One consistent loading treatment app-wide — the same scene-level spinner+ // shown while scene chunks load. Statuses are preloaded at app boot (see+ // productSetupPreloadLogic), so this rarely renders in practice.+ return (+ <ProductSceneFrame config={config}>+ <SpinnerOverlay sceneLevel />+ </ProductSceneFrame>+ )+ }+ if (showEmptyState) {+ return (+ <ProductSceneFrame config={config}>+ <ProductEmptyState config={config} mode={mode} />+ </ProductSceneFrame>+ )+ }+ return <>{children}</>+}++/**+ * Keeps the product header above the empty state, sourced from the scene's own+ * `SceneConfig` (name, description, iconType from the product manifest).+ */+function ProductSceneFrame({+ config,+ children,+}: {+ config: ProductEmptyStateConfig+ children: ReactNode+}): JSX.Element {+ const { sceneConfig } = useValues(sceneLogic)+ return (+ <SceneContent>+ <SceneTitleSection+ name={sceneConfig?.name ?? config.productName}+ description={sceneConfig?.description ?? null}+ resourceType={+ sceneConfig?.iconType+ ? { type: sceneConfig.iconType }+ : { type: String(config.productKey), forceIcon: config.icon }+ }+ />+ {children}+ </SceneContent>+ )+}diff --git a/frontend/src/lib/components/ProductEmptyState/README.md b/frontend/src/lib/components/ProductEmptyState/README.mdnew file mode 100644index 000000000000..21e1ab97c4d9--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/README.md@@ -0,0 +1,11 @@+# ProductEmptyState++The empty state a product scene shows until it has received real data: the product pitch and install command on the left, an animated preview of the product filled with example data on the right. Users can always skip it (stored locally in the browser), and it disappears on its own once data arrives — gating is driven by real data detection, never by dismissal flags.++Scenes opt in declaratively: set `emptyState` on the scene's `SceneExport` and the app shell handles loading, empty, and has-data states — no branching inside the scene component.++`productSetupStatusLogic` (keyed by `ProductKey`) is the app-wide single read point for "is product X set up?"; each product's detection logic pushes its status into it.++**To adopt this for your product, follow the `building-product-empty-states` skill** (`.agents/skills/building-product-empty-states/SKILL.md`). Reference adoption: `products/mcp_analytics/frontend/emptyState/`.++`ProductIntroduction` is deprecated in favor of this component.diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.tsnew file mode 100644index 000000000000..eef6dabd9a56--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts@@ -0,0 +1,171 @@+import { MakeLogicType, actions, afterMount, connect, isBreakpoint, kea, listeners, path } from 'kea'++import api from 'lib/api'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { teamLogic } from 'scenes/teamLogic'++import { productSetupProbes } from '~/products'+import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'++import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'+import { productSetupStatusLogic } from './productSetupStatusLogic'+import { ProductSetupProbe, statusFromProbeCounts } from './setupProbes'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface productSetupPreloadLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ currentTeamId: number | null // teamLogic+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface productSetupPreloadLogicActions {+ preloadStatuses: () => {+ value: true+ }+}++export type productSetupPreloadLogicType = MakeLogicType<+ productSetupPreloadLogicValues,+ productSetupPreloadLogicActions+>++/**+ * Only count events this recent when approximating setup status. Keeps the probe+ * query prunable to recent partitions instead of scanning the team's full history;+ * a product whose newest event is older than this briefly shows its empty state+ * until the in-scene detection (which owns the real semantics) answers.+ */+export const PRELOAD_LOOKBACK_DAYS = 90++/**+ * Resolves every registered product's setup status as early as possible — one+ * combined event-count query on idle after the team loads — and seeds+ * `productSetupStatusLogic` with the results. By the time a user first opens a+ * gated product scene, the status is usually already known, so the gate renders+ * the empty state (or the scene) directly instead of a loading spinner.+ *+ * The product's own detection logic remains the in-scene source of truth: it+ * re-checks with a fresh (uncached) query and keeps polling. The preload only+ * seeds instances still in `loading`, so it can never override a fresher answer.+ *+ * Best-effort by design: a failed run marks nothing as done, so the next trigger+ * (team load, flags arriving, idle) retries, and a probe is only skipped once it+ * has actually been seeded for the current team.+ */+export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([+ path(['lib', 'components', 'ProductEmptyState', 'productSetupPreloadLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],+ })),+ actions({+ preloadStatuses: true,+ }),+ listeners(({ actions, values, cache }) => ({+ preloadStatuses: async (_, breakpoint) => {+ const teamId = values.currentTeamId+ if (!teamId) {+ return+ }+ // Keyed by team AND probe: a project switch re-seeds for the new team, and a+ // flag-gated probe whose flag arrives late still gets its turn.+ const seeded: Set<string> = (cache.seeded ??= new Set())+ const probes = productSetupProbes.filter(+ (probe) =>+ (!probe.featureFlag || values.featureFlags[probe.featureFlag]) &&+ !seeded.has(`${teamId}:${probe.productKey}`)+ )+ if (!probes.length) {+ return+ }++ // Event names are static internal literals from the probe registry, so+ // inlining them is safe. The timestamp bound keeps the scan to recent+ // partitions - without it this would touch every partition the team has+ // ever written; a cached result is fine for seeding.+ const events = [+ ...new Set(probes.flatMap((probe) => [...probe.hasDataEvents, ...(probe.waitingEvents ?? [])])),+ ]+ const query = `SELECT event, count() FROM events WHERE event IN (${events+ .map((event) => `'${event}'`)+ .join(', ')}) AND timestamp > now() - INTERVAL ${PRELOAD_LOOKBACK_DAYS} DAY GROUP BY event`++ let response: HogQLQueryResponse+ try {+ response = (await api.query({ kind: NodeKind.HogQLQuery, query })) as HogQLQueryResponse+ } catch (error) {+ if (error instanceof Error && isBreakpoint(error)) {+ throw error+ }+ // Nothing was marked seeded, so the next trigger retries; until then the+ // in-scene detection logic answers on its own.+ return+ }+ breakpoint()+ if (values.currentTeamId !== teamId) {+ return+ }++ const countsByEvent: Record<string, number> = {}+ for (const row of response?.results ?? []) {+ const [event, count] = row as [string, unknown]+ countsByEvent[event] = Number(count) || 0+ }++ for (const probe of probes) {+ seeded.add(`${teamId}:${probe.productKey}`)+ seedProbeStatus(probe, countsByEvent, cache)+ }+ },+ // Covers login and project switches that happen after mount.+ [teamLogic.actionTypes.loadCurrentTeamSuccess]: ({ currentTeam }) => {+ if (currentTeam) {+ actions.preloadStatuses()+ }+ },+ // Flags resolve asynchronously (posthog-js `onFeatureFlags`), possibly after+ // the boot triggers have already run - re-check so flag-gated probes aren't+ // silently skipped for the whole session.+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {+ actions.preloadStatuses()+ },+ })),+ afterMount(({ actions, cache }) => {+ // Defer to idle so boot-critical work (scene chunk, first queries) wins.+ cache.disposables.add(() => {+ const run = (): void => actions.preloadStatuses()+ if (typeof window.requestIdleCallback === 'function') {+ const id = window.requestIdleCallback(run, { timeout: 5000 })+ return () => window.cancelIdleCallback(id)+ }+ const id = window.setTimeout(run, 1000)+ return () => clearTimeout(id)+ }, 'idle-preload')+ }),+])++function seedProbeStatus(+ probe: ProductSetupProbe,+ countsByEvent: Record<string, number>,+ cache: Record<string, any>+): void {+ const instance = productSetupStatusLogic.build({ productKey: probe.productKey })+ if (!instance.isMounted()) {+ // Keep the instance alive for the app's lifetime so the seeded status is+ // still there when the scene finally opens. Mounting inside the disposable's+ // setup (with hidden-tab pausing off) is what keeps it alive across tab+ // switches - pausing would unmount it and silently discard the seed.+ cache.disposables.add(+ () => {+ instance.mount()+ return () => instance.unmount()+ },+ `status-${probe.productKey}`,+ { pauseOnPageHidden: false }+ )+ }+ // Seed only unknown statuses - a product logic that already answered+ // (fresh, uncached) always beats this cached approximation.+ if (instance.values.status === 'loading') {+ instance.actions.setDetectedStatus(statusFromProbeCounts(probe, countsByEvent))+ }+}diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.test.ts b/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.test.tsnew file mode 100644index 000000000000..e93c18db32bb--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.test.ts@@ -0,0 +1,62 @@+import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { ProductKey } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { productSetupStatusLogic } from './productSetupStatusLogic'++describe('productSetupStatusLogic', () => {+ beforeEach(() => {+ localStorage.clear()+ initKeaTests()+ })++ function mountLogic(): ReturnType<typeof productSetupStatusLogic.build> {+ const logic = productSetupStatusLogic({ productKey: ProductKey.MCP_ANALYTICS })+ logic.mount()+ return logic+ }++ // Guards the skip path end to end: a broken skip either traps users on the+ // empty state or (worse) permanently hides it for users who never skipped.+ it('skip hides the empty state without touching detection, and unskip restores it', async () => {+ const logic = mountLogic()+ logic.actions.setDetectedStatus('needs-setup')+ expect(logic.values.showEmptyState).toBe(true)++ await expectLogic(logic, () => logic.actions.skipEmptyState()).toFinishAllListeners()+ expect(logic.values.skipped).toBe(true)+ expect(logic.values.showEmptyState).toBe(false)+ // Detection is untouched by skipping.+ expect(logic.values.status).toBe('needs-setup')++ await expectLogic(logic, () => logic.actions.unskipEmptyState()).toFinishAllListeners()+ expect(logic.values.showEmptyState).toBe(true)+ })++ it.each([+ ['loading', false],+ ['unknown', false],+ ['needs-setup', true],+ ['waiting-for-data', true],+ ['has-data', false],+ ] as const)('status %s → showEmptyState %s', (status, expected) => {+ const logic = mountLogic()+ logic.actions.setDetectedStatus(status)+ expect(logic.values.showEmptyState).toBe(expected)+ })++ // Guards the team stamp: without it, a project switch serves the previous+ // team's detected status and the gate exposes (or hides) the wrong screen.+ it('a detected status does not survive a project switch', async () => {+ const logic = mountLogic()+ logic.actions.setDetectedStatus('has-data')+ expect(logic.values.status).toBe('has-data')++ const otherTeam = { ...teamLogic.values.currentTeam!, id: (teamLogic.values.currentTeamId ?? 0) + 1 }+ await expectLogic(logic, () => teamLogic.actions.loadCurrentTeamSuccess(otherTeam)).toFinishAllListeners()+ expect(logic.values.status).toBe('loading')+ })+})diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.ts b/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.tsnew file mode 100644index 000000000000..a481b2834c9a--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.ts@@ -0,0 +1,166 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'++import { teamLogic } from 'scenes/teamLogic'++import type { ProductKey } from '~/queries/schema/schema-general'++import type { ProductEmptyStateMode, ProductSetupStatus } from './types'++export interface ProductSetupStatusLogicProps {+ productKey: ProductKey+}++interface DetectedStatus {+ status: ProductSetupStatus+ teamId: number | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface productSetupStatusLogicValues {+ currentTeamId: number | null // teamLogic+ detected: DetectedStatus+ mode: ProductEmptyStateMode+ showEmptyState: boolean+ skipped: boolean+ skippedByTeam: Record<number, boolean>+ status: ProductSetupStatus+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface productSetupStatusLogicActions {+ applyDetectedStatus: (+ status: ProductSetupStatus,+ teamId: number | null+ ) => {+ status: ProductSetupStatus+ teamId: number | null+ }+ setDetectedStatus: (status: ProductSetupStatus) => {+ status: ProductSetupStatus+ }+ setSkippedForTeam: (+ teamId: number,+ skipped: boolean+ ) => {+ skipped: boolean+ teamId: number+ }+ skipEmptyState: () => {+ value: true+ }+ unskipEmptyState: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface productSetupStatusLogicMeta {+ key: ProductKey+ __keaTypeGenInternalSelectorTypes: {+ status: (detected: DetectedStatus, currentTeamId: number | null) => ProductSetupStatus+ skipped: (skippedByTeam: Record<number, boolean>, currentTeamId: number | null) => boolean+ showEmptyState: (status: ProductSetupStatus, skipped: boolean) => boolean+ mode: (status: ProductSetupStatus) => ProductEmptyStateMode+ }+}++export type productSetupStatusLogicType = MakeLogicType<+ productSetupStatusLogicValues,+ productSetupStatusLogicActions,+ ProductSetupStatusLogicProps,+ productSetupStatusLogicMeta+>++/**+ * The single read point for "is product X set up?".+ *+ * Detection stays with each product (they know their own events/APIs), but every+ * product pushes its normalized `ProductSetupStatus` here via `setDetectedStatus`,+ * so any surface — the scene-level empty-state gate, nav, activation — can ask one+ * place instead of reaching into per-product logics.+ *+ * Detection must be a real signal: data existence (HogQL count / exists API), the+ * product's opt-in flag, or entity count for creation-first products. Never a+ * dismissal flag — `has_completed_onboarding_for` is routing metadata, not evidence+ * of data.+ *+ * Skip is local-only (per browser, keyed by team): it bypasses the empty-state+ * screen without writing anything to the backend, and detection keeps running so+ * the real product appears as soon as data lands.+ */+export const productSetupStatusLogic = kea<productSetupStatusLogicType>([+ props({} as ProductSetupStatusLogicProps),+ key((props) => {+ if (!props.productKey) {+ throw new Error('productSetupStatusLogic must be initialized with a productKey')+ }+ return props.productKey+ }),+ path((key) => ['lib', 'components', 'ProductEmptyState', 'productSetupStatusLogic', key]),+ connect(() => ({ values: [teamLogic, ['currentTeamId']] })),+ actions({+ setDetectedStatus: (status: ProductSetupStatus) => ({ status }),+ applyDetectedStatus: (status: ProductSetupStatus, teamId: number | null) => ({ status, teamId }),+ skipEmptyState: true,+ unskipEmptyState: true,+ setSkippedForTeam: (teamId: number, skipped: boolean) => ({ teamId, skipped }),+ }),+ reducers({+ // Stamped with the team the detection ran against, so a stale answer is+ // never served across a project switch (see the `status` selector).+ detected: [+ { status: 'loading', teamId: null } as DetectedStatus,+ {+ applyDetectedStatus: (_, { status, teamId }) => ({ status, teamId }),+ },+ ],+ // Keyed by team so switching projects never leaks a skip across tenants.+ skippedByTeam: [+ {} as Record<number, boolean>,+ { persist: true },+ {+ setSkippedForTeam: (state, { teamId, skipped }) => ({ ...state, [teamId]: skipped }),+ },+ ],+ }),+ selectors({+ // A detected status only counts for the team it was detected for; after a+ // project switch we're back to `loading` until a detection (or the preload)+ // answers for the new team.+ status: [+ (s) => [s.detected, s.currentTeamId],+ (detected: DetectedStatus, currentTeamId: number | null): ProductSetupStatus =>+ detected.teamId === currentTeamId ? detected.status : 'loading',+ ],+ skipped: [+ (s) => [s.skippedByTeam, s.currentTeamId],+ (skippedByTeam: Record<number, boolean>, currentTeamId: number | null): boolean =>+ !!(currentTeamId && skippedByTeam[currentTeamId]),+ ],+ showEmptyState: [+ (s) => [s.status, s.skipped],+ (status: ProductSetupStatus, skipped: boolean): boolean =>+ !skipped && (status === 'needs-setup' || status === 'waiting-for-data'),+ ],+ mode: [+ (s) => [s.status],+ (status: ProductSetupStatus): ProductEmptyStateMode =>+ status === 'waiting-for-data' ? 'waiting-for-data' : 'needs-setup',+ ],+ }),+ listeners(({ actions, values }) => ({+ setDetectedStatus: ({ status }) => {+ actions.applyDetectedStatus(status, values.currentTeamId)+ },+ skipEmptyState: () => {+ if (values.currentTeamId) {+ actions.setSkippedForTeam(values.currentTeamId, true)+ }+ },+ unskipEmptyState: () => {+ if (values.currentTeamId) {+ actions.setSkippedForTeam(values.currentTeamId, false)+ }+ },+ })),+])diff --git a/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts b/frontend/src/lib/components/ProductEmptyState/setupProbes.test.tsnew file mode 100644index 000000000000..175530035c23--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts@@ -0,0 +1,28 @@+import { ProductKey } from '~/queries/schema/schema-general'++import { statusFromProbeCounts, type ProductSetupProbe } from './setupProbes'++describe('statusFromProbeCounts', () => {+ const probe: ProductSetupProbe = {+ productKey: ProductKey.MCP_ANALYTICS,+ hasDataEvents: ['$mcp_tool_call'],+ waitingEvents: ['$mcp_initialize'],+ }++ // Guards the boot-time seeding for every adopting product: a precedence flip+ // (waiting beating has-data) or a crash on missing counts would either hide+ // the empty state or show it to fully onboarded projects app-wide.+ it.each([+ [{ $mcp_tool_call: 5, $mcp_initialize: 2 }, 'has-data'],+ [{ $mcp_initialize: 2 }, 'waiting-for-data'],+ [{}, 'needs-setup'],+ [{ $mcp_tool_call: 0, $mcp_initialize: 0 }, 'needs-setup'],+ ] as const)('maps counts %j to %s', (counts, expected) => {+ expect(statusFromProbeCounts(probe, counts as Record<string, number>)).toBe(expected)+ })++ it('never reports waiting-for-data for probes without waitingEvents', () => {+ const binaryProbe: ProductSetupProbe = { productKey: ProductKey.MCP_ANALYTICS, hasDataEvents: ['$exception'] }+ expect(statusFromProbeCounts(binaryProbe, { $mcp_initialize: 10 })).toBe('needs-setup')+ })+})diff --git a/frontend/src/lib/components/ProductEmptyState/setupProbes.ts b/frontend/src/lib/components/ProductEmptyState/setupProbes.tsnew file mode 100644index 000000000000..b09125c6e9a5--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/setupProbes.ts@@ -0,0 +1,42 @@+import { type FeatureFlagKey } from 'lib/constants'++import { ProductKey } from '~/queries/schema/schema-general'++import type { ProductSetupStatus } from './types'++/**+ * A cheap, declarative approximation of a product's setup status, resolvable at+ * app boot from event counts alone. A product declares its probe as `setupProbe`+ * in its manifest; `build-products.mjs` aggregates them into `productSetupProbes`+ * (see `~/products`), and all of them are answered by ONE combined ClickHouse+ * count query (see `productSetupPreloadLogic`), so statuses are known before the+ * user first opens the product and the loading spinner rarely shows.+ *+ * Keep each probe's semantics in sync with the product's own detection logic+ * (e.g. `mcpAnalyticsOnboardingLogic`) — the product logic stays the in-scene+ * source of truth and its fresher result always wins over the preload.+ */+export interface ProductSetupProbe {+ productKey: ProductKey+ /** Any of these events existing (within the preload lookback window) means the product has real data. */+ hasDataEvents: string[]+ /** Any of these existing (without `hasDataEvents`) means instrumented but no traffic yet. */+ waitingEvents?: string[]+ /** Only probe when this flag is enabled. */+ featureFlag?: FeatureFlagKey+}++export function statusFromProbeCounts(+ probe: ProductSetupProbe,+ countsByEvent: Record<string, number>+): ProductSetupStatus {+ if (probe.hasDataEvents.some((event) => (countsByEvent[event] ?? 0) > 0)) {+ return 'has-data'+ }++ if (probe.waitingEvents?.some((event) => (countsByEvent[event] ?? 0) > 0)) {+ return 'waiting-for-data'+ }++ return 'needs-setup'+}diff --git a/frontend/src/lib/components/ProductEmptyState/setupReminderContext.ts b/frontend/src/lib/components/ProductEmptyState/setupReminderContext.tsnew file mode 100644index 000000000000..3d4c51b83212--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/setupReminderContext.ts@@ -0,0 +1,9 @@+import { createContext } from 'react'+import type { ReactNode } from 'react'++/**+ * The "isn't receiving data yet" reminder a skipped-but-still-empty product scene shows.+ * The empty-state gate publishes it here so the SceneMenuBar can render it just below the+ * bar instead of above the whole scene. Defaults to null — scenes without one render nothing.+ */+export const SetupReminderContext = createContext<ReactNode>(null)diff --git a/frontend/src/lib/components/ProductEmptyState/storybookHelpers.ts b/frontend/src/lib/components/ProductEmptyState/storybookHelpers.tsnew file mode 100644index 000000000000..11d93270e0a0--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/storybookHelpers.ts@@ -0,0 +1,55 @@+import type { StoryObj } from '@storybook/react'++import { mswDecorator } from '~/mocks/browser'+import type { Mocks } from '~/mocks/utils'++import type { ProductEmptyState } from './ProductEmptyState'+import type { ProductEmptyStateConfig, ProductEmptyStateMode, SceneProductEmptyState } from './types'++export type ProductEmptyStateStory = StoryObj<typeof ProductEmptyState>++export interface ProductEmptyStateStoryOptions {+ /** Per-story overrides on top of the product's real config, e.g. `{ wizard: undefined }` for the self-hosted rendering */+ config?: Partial<ProductEmptyStateConfig>+ /** Extra msw handlers, merged over the defaults (same path wins), e.g. to drive the product's status indicator into a specific state */+ mocks?: Mocks+}++/**+ * Builds a story (and therefore a visual-regression snapshot) for a product's real+ * empty-state config - the exact object its scene gate renders. A product adopting+ * the platform adds one export per mode:+ *+ * export const MyProductNeedsSetup = productEmptyStateStory(myProductEmptyState, 'needs-setup')+ *+ * Detection logics and status indicators issue requests on mount; the default mocks+ * answer the common ones (queries with empty results, product intents with 200) so a+ * bare call renders cleanly without msw warnings. Pass `mocks` to override.+ */+export function productEmptyStateStory(+ emptyState: SceneProductEmptyState,+ mode: ProductEmptyStateMode,+ { config, mocks }: ProductEmptyStateStoryOptions = {}+): ProductEmptyStateStory {+ return {+ // Empty states show a persistent "listening for data" spinner (and animated preview)+ // by design, so the snapshot runner must not wait for loaders to disappear here.+ parameters: { testOptions: { waitForLoadersToDisappear: false } },+ args: { config: { ...emptyState.config, ...config }, mode },+ decorators: [+ mswDecorator({+ ...mocks,+ post: {+ // nosemgrep: no-environments-api-urls-frontend -- api.query is env-scoped, so the msw mock must match /api/environments to intercept it+ '/api/environments/:team_id/query/:kind': [200, { results: [] }],+ ...mocks?.post,+ },+ patch: {+ // nosemgrep: no-environments-api-urls-frontend -- add_product_intent is env-scoped, so the msw mock must match /api/environments to intercept it+ '/api/environments/:team_id/add_product_intent': [200, {}],+ ...mocks?.patch,+ },+ }),+ ],+ }+}diff --git a/frontend/src/lib/components/ProductEmptyState/types.ts b/frontend/src/lib/components/ProductEmptyState/types.tsnew file mode 100644index 000000000000..abfeb5f70d43--- /dev/null+++ b/frontend/src/lib/components/ProductEmptyState/types.ts@@ -0,0 +1,100 @@+import type { LogicWrapper } from 'kea'+import type { ComponentType, CSSProperties, ReactNode } from 'react'++import type { FeatureFlagKey } from 'lib/constants'++import type { ProductKey } from '~/queries/schema/schema-general'++/**+ * Normalized setup status for a product, pushed into `productSetupStatusLogic`+ * by the product's own detection logic (data-existence query, exists API, opt-in+ * flag, or entity count). This is the single vocabulary every surface reads.+ *+ * `unknown` means detection failed and no earlier answer exists - surfaces must+ * fail open (render the real product, never a spinner or the setup screen).+ */+export type ProductSetupStatus = 'loading' | 'unknown' | 'needs-setup' | 'waiting-for-data' | 'has-data'++/** The two empty-state variants. `waiting-for-data` is for products with an "installed but no traffic yet" middle state. */+export type ProductEmptyStateMode = 'needs-setup' | 'waiting-for-data'++export interface ProductEmptyStateText {+ /** Sentence case, benefit-first, e.g. "Know how agents actually use your tools" */+ headline: string+ lead: ReactNode+ /** Small line above the install command, e.g. "Fastest way in — our wizard wires up the SDK for you:" */+ hint?: ReactNode+}++/**+ * Text keyed by mode: `needs-setup` is the base every product provides; other+ * modes override only the fields that change and fall back to the base for the+ * rest. Binary products (no intermediate state) just provide the base.+ */+export type ProductEmptyStateTextByMode = {+ 'needs-setup': ProductEmptyStateText+} & {+ [Mode in Exclude<ProductEmptyStateMode, 'needs-setup'>]?: Partial<ProductEmptyStateText>+}++export interface ProductEmptyStateWizard {+ /** Subcommand for `npx -y @posthog/wizard@latest <slug>` */+ slug: string+ /** Append `--project-id=<current team>` so the wizard pre-targets the project being viewed */+ pinProjectId?: boolean+}++export interface ProductEmptyStatePrimaryAction {+ label: string+ to?: string+ onClick?: () => void+}++export interface ProductEmptyStateConfig {+ productKey: ProductKey+ /** Eyebrow text, sentence case, e.g. "MCP analytics" */+ productName: string+ /** Eyebrow icon, e.g. `<IconMCP />` */+ icon: JSX.Element+ /** CSS color or var reference, e.g. 'var(--color-product-llm-analytics-light)' */+ accentColor: string+ /** Dark-mode accent override; falls back to `accentColor` */+ accentColorDark?: string+ /** A `pngHoggie(...)`-wrapped hedgehog, rendered above the product name */+ hedgehog?: ComponentType<{ className?: string; style?: CSSProperties }>+ text: ProductEmptyStateTextByMode+ /** Install-command CTA. Omit for creation-first products (use `primaryAction`) or self-hosted-only flows */+ wizard?: ProductEmptyStateWizard+ /** Primary CTA for products set up in the UI rather than via the wizard, e.g. "Create your first flag" */+ primaryAction?: ProductEmptyStatePrimaryAction+ docsUrl?: string+ /** Target of the small "Or configure manually" link; falls back to `docsUrl` */+ manualSetupUrl?: string+ /** Rendered as "<previewLabel>" with a pulsing live dot, above the preview */+ previewLabel: string+ /** Self-animating signature preview populated with realistic fake data */+ Preview: ComponentType<{ mode: ProductEmptyStateMode }>+ /** Product-specific live status line (e.g. a "listening for events" indicator), rendered under the command block */+ statusIndicator?: ReactNode+}++/**+ * Declared on a scene's `SceneExport` to opt into the app-shell empty-state gate.+ * Both fields live in the scene's lazy chunk, so heavy assets (hedgehog PNGs,+ * preview widgets) never enter the eager graph.+ */+export interface SceneProductEmptyState {+ config: ProductEmptyStateConfig+ /**+ * The product's detection logic. The gate mounts it; it must push its+ * normalized status into `productSetupStatusLogic({ productKey })` via+ * `setDetectedStatus`.+ */+ statusLogic: LogicWrapper+ /**+ * Only gate when this feature flag is enabled. Set it when the scene itself is+ * flag-gated (so the scene's own gate keeps handling the flag-off case), or to+ * roll the empty state out gradually.+ */+ featureFlag?: FeatureFlagKey+}diff --git a/frontend/src/lib/components/ProductIntroduction/ProductIntroduction.tsx b/frontend/src/lib/components/ProductIntroduction/ProductIntroduction.tsxindex 92d8b727c785..0120dff47ff3 100644--- a/frontend/src/lib/components/ProductIntroduction/ProductIntroduction.tsx+++ b/frontend/src/lib/components/ProductIntroduction/ProductIntroduction.tsx@@ -68,6 +68,18 @@ export type ProductIntroductionProps = {mcpSurfaceKey?: SurfaceKey}+/**+ * @deprecated Use {@link ProductEmptyState} instead: declare {@link SceneExport.emptyState} on the+ * scene's {@link SceneExport} (see {@link ../ProductEmptyState | ProductEmptyState} and the+ * `building-product-empty-states` skill).+ *+ * {@link ProductEmptyState} covers both of this component's jobs -+ * "product not installed" via real data detection and "no entities yet" via an+ * entity-count status - with a local-only skip instead of {@link UserType.has_seen_product_intro_for}.+ * Don't add new call sites; existing ones should migrate product by product.+ *+ * The Growth team is responsible for migrating all call sites to {@link ProductEmptyState}.+ */export const ProductIntroduction = ({productName,productKey,diff --git a/frontend/src/products.json b/frontend/src/products.jsonindex abbd3c675b59..945804b2f89d 100644--- a/frontend/src/products.json+++ b/frontend/src/products.json@@ -175,7 +175,7 @@"category": "AI engineering","iconType": null,"type": "mcp_analytics",- "intents": ["llm_analytics"]+ "intents": ["mcp_analytics"]},{"path": "Metrics",diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex efd5142293a2..5f22249e9f69 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -4,6 +4,7 @@import { combineUrl } from 'kea-router'import posthog from 'posthog-js'+import type { ProductSetupProbe } from 'lib/components/ProductEmptyState/setupProbes'import { FEATURE_FLAGS, INSIGHT_VISUAL_ORDER } from 'lib/constants'import { toParams } from 'lib/utils/url'import type { Params } from 'scenes/sceneTypes'@@ -1494,6 +1495,16 @@ export const fileSystemTypes = {},}+/** This const is auto-generated, as is the whole file */+export const productSetupProbes: ProductSetupProbe[] = [+ {+ productKey: ProductKey.MCP_ANALYTICS,+ hasDataEvents: ['$mcp_tool_call'],+ waitingEvents: ['$mcp_initialize'],+ featureFlag: FEATURE_FLAGS.MCP_ANALYTICS,+ },+]+/** This const is auto-generated, as is the whole file */export const getTreeItemsNew = (): FileSystemImport[] => [{@@ -2012,12 +2023,15 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [},{path: 'MCP analytics',- intents: [ProductKey.AI_OBSERVABILITY],+ intents: [ProductKey.MCP_ANALYTICS],category: ProductItemCategory.AI_ENGINEERING,visualOrder: 2,type: 'mcp_analytics',iconType: 'mcp_analytics' as FileSystemIconType,- iconColor: ['var(--color-product-llm-analytics-light)'] as FileSystemIconColor,+ iconColor: [+ 'var(--color-product-mcp-analytics-light)',+ 'var(--color-product-mcp-analytics-dark)',+ ] as FileSystemIconColor,href: urls.mcpAnalyticsDashboard(),flag: FEATURE_FLAGS.MCP_ANALYTICS,tags: ['beta'],diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsxindex 94ebd7311d10..660ad00e8f4d 100644--- a/frontend/src/scenes/App.tsx+++ b/frontend/src/scenes/App.tsx@@ -6,6 +6,8 @@ import { Slide, ToastContainer } from 'react-toastify'import { PostHogProvider } from '@posthog/react'+import { ProductEmptyStateGate } from 'lib/components/ProductEmptyState/ProductEmptyStateGate'+import { productSetupPreloadLogic } from 'lib/components/ProductEmptyState/productSetupPreloadLogic'import { MOCK_NODE_PROCESS } from 'lib/constants'import { useCancelAnimationsOnUnmount } from 'lib/hooks/useCancelAnimationsOnUnmount'import { useThemedHtml } from 'lib/hooks/useThemedHtml'@@ -66,6 +68,10 @@ export function App(): JSX.Element | null {useMountedLogic(sceneLogic({ scenes: appScenes }))useMountedLogic(autofillReleaseLogic)++ // Resolves product setup statuses on idle, so gated scenes open without a spinner.+ useMountedLogic(productSetupPreloadLogic)+// Unconditional so /oauth/callback's urlToAction is registered before routing. Inert in prod// (OAuth UI gated on preflight.is_debug); no timers/listeners, so cheap to always mount.useMountedLogic(oauthLogic)@@ -152,12 +158,18 @@ function AppScene(): JSX.Element | null {let sceneElement: JSX.Elementif (activeExportedScene?.component) {- const { component: SceneComponent } = activeExportedScene- sceneElement = (- <SceneAnimationRoot key={`scene-${activeSceneId}`}>- <SceneComponent user={user} {...activeSceneComponentParams} />- </SceneAnimationRoot>+ const { component: SceneComponent, emptyState } = activeExportedScene+ const sceneNode = <SceneComponent user={user} {...activeSceneComponentParams} />++ // Scenes that declare an empty state are gated behind the product's+ // setup screen until the product has data (or the user skips).+ const resolvedNode = emptyState ? (+ <ProductEmptyStateGate emptyState={emptyState}>{sceneNode}</ProductEmptyStateGate>+ ) : (+ sceneNode)++ sceneElement = <SceneAnimationRoot key={`scene-${activeSceneId}`}>{resolvedNode}</SceneAnimationRoot>} else {sceneElement = <SpinnerOverlay sceneLevel visible={showingDelayedSpinner} />}diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsxindex 94f7acd0333c..599e97c998f8 100644--- a/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx@@ -14,8 +14,8 @@ import { CommandBlock } from 'lib/components/CommandBlock/CommandBlock'import { Link } from 'lib/lemon-ui/Link'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'import { humanFriendlyNumber } from 'lib/utils/numbers'-import { useWizardCommand } from 'scenes/onboarding/shared/SetupWizardBanner'import { setupWizardStatusLogic } from 'scenes/onboarding/shared/setupWizardStatusLogic'+import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'export type SampleDataVariant = 'line' | 'bar' | 'pie' | 'funnel' | 'number' | 'table'diff --git a/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsx b/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsxindex cc6f98984d2e..1e87115af551 100644--- a/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsx+++ b/frontend/src/scenes/onboarding/self-driving/ContextOnboarding.tsx@@ -23,7 +23,7 @@ import selfDrivingHog from 'public/hedgehog/self-driving-hog.png'// team onboarded, redirecting out) for both variants.import { onboardingLogic } from '../legacy/onboardingLogic'import { type ContextOnboardingStepId, onboardingEventUsageLogic } from '../onboardingEventUsageLogic'-import { useWizardCommand } from '../shared/SetupWizardBanner'+import { useWizardCommand } from '../shared/useWizardCommand'import { availableOnboardingProducts, getProductIcon, toSentenceCase } from '../shared/utils'import { activeCloudRunLogic, type CloudRunHandle } from '../shared/wizard-sync/activeCloudRunLogic'import { installationProgressLogic } from '../shared/wizard-sync/installationProgressLogic'diff --git a/frontend/src/scenes/onboarding/shared/SetupWizardBanner.tsx b/frontend/src/scenes/onboarding/shared/SetupWizardBanner.tsxindex effaa34fbde0..1a1eb4bfc602 100644--- a/frontend/src/scenes/onboarding/shared/SetupWizardBanner.tsx+++ b/frontend/src/scenes/onboarding/shared/SetupWizardBanner.tsx@@ -1,23 +1,10 @@-import { useValues } from 'kea'-import { LemonDivider } from '@posthog/lemon-ui'import { Language } from 'lib/components/CodeSnippet'import { CodeSnippet } from 'lib/components/CodeSnippet'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'-import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'--import { Region } from '~/types'-export function useWizardCommand(subcommand?: string): { wizardCommand: string; isCloudOrDev: boolean } {- const { preflight, isCloudOrDev } = useValues(preflightLogic)- const region = preflight?.region || Region.US- const subcommandPart = subcommand ? ` ${subcommand}` : ''- return {- wizardCommand: `npx -y @posthog/wizard@latest${subcommandPart}${region === Region.EU ? ' --region eu' : ''}`,- isCloudOrDev: isCloudOrDev ?? false,- }-}+import { useWizardCommand } from './useWizardCommand'const SetupWizardBanner = ({integrationName,diff --git a/frontend/src/scenes/onboarding/shared/useWizardCommand.ts b/frontend/src/scenes/onboarding/shared/useWizardCommand.tsnew file mode 100644index 000000000000..b9f6316d552b--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/useWizardCommand.ts@@ -0,0 +1,41 @@+import { useValues } from 'kea'++import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { teamLogic } from 'scenes/teamLogic'++import { Region } from '~/types'++const BASE_COMMAND = 'npx -y @posthog/wizard@latest'++export interface UseWizardCommandOptions {+ /**+ * Append `--project-id=<current team>` so the wizard pre-targets the project+ * being viewed (and, once the consent screen honors the hint, pre-selects it).+ * Harmless if the user authorizes the same project.+ */+ pinProjectId?: boolean+}++/**+ * The canonical `npx @posthog/wizard` command for this region, with an optional+ * subcommand (e.g. `mcp-analytics`). Kept dependency-light so eagerly-loaded+ * surfaces (like the product empty-state gate) can use it without pulling in+ * heavy onboarding components.+ */+export function useWizardCommand(+ subcommand?: string,+ { pinProjectId = false }: UseWizardCommandOptions = {}+): { wizardCommand: string; isCloudOrDev: boolean } {+ const { preflight, isCloudOrDev } = useValues(preflightLogic)+ const { currentTeam } = useValues(teamLogic)++ const region = preflight?.region || Region.US+ const subcommandPart = subcommand ? ` ${subcommand}` : ''+ const regionPart = region === Region.EU ? ' --region eu' : ''+ const projectPart = pinProjectId && currentTeam?.id ? ` --project-id=${currentTeam.id}` : ''++ return {+ wizardCommand: `${BASE_COMMAND}${subcommandPart}${regionPart}${projectPart}`,+ isCloudOrDev: isCloudOrDev ?? false,+ }+}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.tsxindex 171b15e20881..a58c3ca6883d 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCloudRunBlock.tsx@@ -6,7 +6,7 @@ import { LemonBanner, LemonButton } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { GitHubRepositoryPicker } from 'lib/integrations/GitHubIntegrationHelpers'-import { useWizardCommand } from 'scenes/onboarding/shared/SetupWizardBanner'+import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'import { activeCloudRunLogic } from './activeCloudRunLogic'import { InstallationProgressView } from './InstallationProgressView'diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsxindex 857c9b3c69af..7234e670210b 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardCommandBlock.tsx@@ -1,7 +1,7 @@import { useState } from 'react'import { CommandBlock } from 'lib/components/CommandBlock/CommandBlock'-import { useWizardCommand } from 'scenes/onboarding/shared/SetupWizardBanner'+import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'import { WizardModeShell } from './WizardModeShell'diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsxindex 04f700085c11..cdaa82bc8142 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardInstallOptions.tsx@@ -6,7 +6,7 @@ import { LemonSegmentedButton } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { useWizardCommand } from '../SetupWizardBanner'+import { useWizardCommand } from '../useWizardCommand'import { activeCloudRunLogic } from './activeCloudRunLogic'import { WizardCloudRunBlock } from './WizardCloudRunBlock'import { WizardFrameworkBadges } from './WizardModeShell'diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardModeShell.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardModeShell.tsxindex f0c4c3e2332f..9c512b80e9d8 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardModeShell.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardModeShell.tsx@@ -3,7 +3,7 @@ import './WizardModeShell.scss'import type { ComponentType, ReactNode } from 'react'import { cn } from 'lib/utils/css-classes'-import { WIZARD_HOG_URL } from 'scenes/onboarding/shared/wizardHog'+import { WizardHog } from 'scenes/onboarding/shared/wizardHog'import androidImage from '../logos/android.svg'import angularImage from '../logos/angular.svg'@@ -87,10 +87,8 @@ export function WizardModeShell({return (<div className="flex gap-6" data-attr={dataAttr}>{!hideHog && (- <img+ <WizardHogkey={`hog-${hogCastKey}`}- src={WIZARD_HOG_URL}- alt="PostHog wizard hedgehog"className={cn('w-28 h-28 hidden sm:block shrink-0 self-center',hogCastKey > 0 && 'WizardModeShell__hogCast'diff --git a/frontend/src/scenes/onboarding/shared/wizardHog.ts b/frontend/src/scenes/onboarding/shared/wizardHog.tsdeleted file mode 100644index ccdcc6b2e356..000000000000--- a/frontend/src/scenes/onboarding/shared/wizardHog.ts+++ /dev/null@@ -1,2 +0,0 @@-/** Cloudinary URL for the wizard hedgehog image, shared across legacy and self-driving onboarding variants. */-export const WIZARD_HOG_URL = 'https://res.cloudinary.com/dmukukwp6/image/upload/wizard_3f8bb7a240.png'diff --git a/frontend/src/scenes/onboarding/shared/wizardHog.tsx b/frontend/src/scenes/onboarding/shared/wizardHog.tsxnew file mode 100644index 000000000000..12baf8e8e76b--- /dev/null+++ b/frontend/src/scenes/onboarding/shared/wizardHog.tsx@@ -0,0 +1,6 @@+import * as wizardHogPng from '@posthog/brand/hoggies/png/wizard-hog'++import { pngHoggie } from 'lib/brand/hoggies'++/** The wizard hedgehog, shared across onboarding variants and wizard-flavored surfaces. */+export const WizardHog = pngHoggie(wizardHogPng)diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 62bf8466c94e..379f7c7c1b23 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -1,5 +1,7 @@import { LogicWrapper } from 'kea'+import type { SceneProductEmptyState } from 'lib/components/ProductEmptyState/types'+import type { FileSystemIconType, ProductKey } from '~/queries/schema/schema-general'import { AccessControlResourceType, ActivityScope } from '~/types'@@ -231,6 +233,12 @@ export interface SceneExport<T = SceneProps> {logic?: LogicWrapper/** product key associated with this scene - used for Quick Start setup tracking */productKey?: ProductKey+ /**+ * Declare this to have the app shell gate the scene behind the product's+ * setup empty state until the product has received data (skippable, driven+ * by real data detection). See lib/components/ProductEmptyState.+ */+ emptyState?: SceneProductEmptyState/** convert URL parameters from scenes.ts into logic props */paramsToProps?: (params: SceneParams) => T/** when was the scene last touched, unix timestamp for sortability */diff --git a/frontend/src/styles/base.scss b/frontend/src/styles/base.scssindex 587b6dbbbc26..c09c00af693d 100644--- a/frontend/src/styles/base.scss+++ b/frontend/src/styles/base.scss@@ -337,6 +337,8 @@--color-product-llm-prompts-light: rgb(196 181 253);--color-product-ai-gateway-light: rgb(99 102 241);--color-product-ai-gateway-dark: rgb(129 140 248);+ --color-product-mcp-analytics-light: rgb(205 48 180);+ --color-product-mcp-analytics-dark: rgb(229 105 205);--color-product-links-light: rgb(143 7 255);--color-product-tracing-light: rgb(6 182 212);--color-product-tracing-dark: rgb(34 211 238);diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 43d7cc804388..5ef7099d607c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -12,6 +12,7 @@ import { ChartDataset, ChartType, InteractionItem } from 'lib/Chart'import { CommonFilters, HeatmapFilters, HeatmapFixedPositionMode } from 'lib/components/heatmaps/types'import { HedgehogActorOptions } from 'lib/components/HedgehogMode/types'import { SessionRecordingTriggerGroupsConfig, UrlTriggerConfig } from 'lib/components/IngestionControls/types'+import type { ProductSetupProbe } from 'lib/components/ProductEmptyState/setupProbes'import { JSONContent } from 'lib/components/RichContentEditor/types'import { DashboardCompatibleScenes } from 'lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'@@ -7549,6 +7550,12 @@ export interface ProductManifest {treeItemsProducts?: (FileSystemImport & { intents: ProductKey[]; category: ProductItemCategory })[] // Require `intents` and `category to be set for productstreeItemsGames?: FileSystemImport[]treeItemsMetadata?: FileSystemImport[]+ /**+ * Boot-time setup-status probe for this product's empty state. Aggregated across+ * manifests into `productSetupProbes` and answered by one combined event-count+ * query at app boot (see `productSetupPreloadLogic`).+ */+ setupProbe?: ProductSetupProbe}export interface ProjectTreeRef {diff --git a/products/data_warehouse/frontend/shared/components/DataWarehouseWizardBlock.tsx b/products/data_warehouse/frontend/shared/components/DataWarehouseWizardBlock.tsxindex c4a80ca009d8..8776c8a89c57 100644--- a/products/data_warehouse/frontend/shared/components/DataWarehouseWizardBlock.tsx+++ b/products/data_warehouse/frontend/shared/components/DataWarehouseWizardBlock.tsx@@ -1,5 +1,5 @@import { CommandBlock } from 'lib/components/CommandBlock/CommandBlock'-import { useWizardCommand } from 'scenes/onboarding/shared/SetupWizardBanner'+import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'import { ExternalDataSourceType } from '~/queries/schema/schema-general'diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/sourceMapsWizardVisuals.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/sourceMapsWizardVisuals.tsxindex 19f92e85d8fc..ef6be45f69ce 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/sourceMapsWizardVisuals.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/sourceMapsWizardVisuals.tsx@@ -1,14 +1,12 @@import './sourceMapsWizardVisuals.scss'import { cn } from 'lib/utils/css-classes'-import { WIZARD_HOG_URL } from 'scenes/onboarding/shared/wizardHog'+import { WizardHog as WizardHogImage } from 'scenes/onboarding/shared/wizardHog'export function WizardHog({ castKey = 0, className }: { castKey?: number; className?: string }): JSX.Element {return (- <img+ <WizardHogImagekey={`wizard-hog-${castKey}`}- src={WIZARD_HOG_URL}- alt="PostHog wizard hedgehog"className={cn('shrink-0 select-none', castKey > 0 && 'SourceMapsWizard__hogCast', className)}/>)diff --git a/products/mcp_analytics/frontend/MCPAnalyticsOnboarding.tsx b/products/mcp_analytics/frontend/MCPAnalyticsOnboarding.tsxdeleted file mode 100644index 2a406c1b38b7..000000000000--- a/products/mcp_analytics/frontend/MCPAnalyticsOnboarding.tsx+++ /dev/null@@ -1,80 +0,0 @@-import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'-import { LemonButton, Spinner } from '@posthog/lemon-ui'--import { pngHoggie } from 'lib/brand/hoggies'-import { CommandBlock } from 'lib/components/CommandBlock/CommandBlock'-import { WavingHog } from 'lib/components/hedgehogs'--import type { MCPOnboardingState } from './mcpAnalyticsOnboardingLogic'-import {- MCP_ANALYTICS_DOCS_URL,- MCPAnalyticsInstallHero,- MCPListeningIndicator,- useMCPAnalyticsWizardCommand,-} from './onboarding/MCPAnalyticsInstall'--const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)--/** Branded loading state shown while we work out whether the project has MCP events yet. */-export function MCPAnalyticsLoading(): JSX.Element {- return (- <div className="flex flex-col items-center justify-center gap-4 py-20 text-center">- <HedgehogMagnifyingGlass className="w-32 h-32" />- <div className="flex items-center gap-2 text-secondary">- <Spinner />- <span>Checking for MCP activity…</span>- </div>- </div>- )-}--/**- * Shown once the server is wired up (`$mcp_initialize` seen) but no tool call has landed yet.- * They're already instrumented, so the hero is "make a tool call" + the live indicator; the- * wizard command is demoted to a secondary "instrument another server" affordance.- */-function ConnectedNoCalls(): JSX.Element {- const { command, isCloudOrDev } = useMCPAnalyticsWizardCommand()-- return (- <div className="flex flex-col items-center text-center gap-6 py-12 max-w-xl mx-auto">- <WavingHog className="w-32 h-32" />- <div className="space-y-2">- <h2 className="text-2xl font-bold">You're connected — now make a tool call</h2>- <p className="text-muted m-0">- We've seen your MCP server connect, but it hasn't handled a tool call yet. Trigger a tool from your- agent and this page fills in on its own.- </p>- </div>- <MCPListeningIndicator />- {isCloudOrDev && (- <div className="w-full flex flex-col items-center gap-2 pt-2">- <p className="text-xs text-muted m-0">Instrumenting another server? Re-run setup:</p>- <CommandBlock- command={command}- copyLabel="MCP wizard command"- ariaLabel="Copy MCP analytics wizard command"- size="sm"- className="bg-bg-light border border-border"- />- </div>- )}- <LemonButton type="tertiary" size="small" to={MCP_ANALYTICS_DOCS_URL} targetBlank>- Read the docs- </LemonButton>- </div>- )-}--/** Shown until the project captures its first `$mcp_tool_call`. Tailors by signal state. */-export function MCPAnalyticsOnboarding({ state }: { state: Exclude<MCPOnboardingState, 'onboarded'> }): JSX.Element {- if (state === 'connected-no-calls') {- return <ConnectedNoCalls />- }- // not-instrumented: lead with the full install hero — same treatment as the onboarding page.- return (- <div className="py-8">- <MCPAnalyticsInstallHero />- </div>- )-}diff --git a/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx b/products/mcp_analytics/frontend/MCPAnalyticsScene.tsxindex b76ab2918bb4..c6a3be70b180 100644--- a/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx+++ b/products/mcp_analytics/frontend/MCPAnalyticsScene.tsx@@ -9,14 +9,15 @@ import { urls } from 'scenes/urls'import { FeaturePreviewSceneGate } from '~/layout/scenes/components/FeaturePreviewSceneGate'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { ProductKey } from '~/queries/schema/schema-general'import { SceneExport } from '~/scenes/sceneTypes'import { askPostHogAI } from './askPostHogAI'import { MCPAnalyticsClustering } from './clustering/MCPAnalyticsClustering'import { MCPAnalyticsActivityDashboard } from './earlyData/MCPAnalyticsEarlyData'+import { mcpAnalyticsEmptyState } from './emptyState/mcpAnalyticsEmptyState'import { mcpAnalyticsFeaturePreviewGate } from './featurePreviewGate'import { MCPAnalyticsDashboard } from './MCPAnalyticsDashboard'-import { MCPAnalyticsLoading, MCPAnalyticsOnboarding } from './MCPAnalyticsOnboarding'import { mcpAnalyticsOnboardingLogic } from './mcpAnalyticsOnboardingLogic'import { MCPAnalyticsTab, TAB_AI_PROMPTS, TAB_DESCRIPTIONS, mcpAnalyticsSceneLogic } from './mcpAnalyticsSceneLogic'import { MCPAnalyticsSceneMenuBar } from './MCPAnalyticsSceneMenuBar'@@ -26,6 +27,8 @@ import { MCPSessionsPlaylist } from './sessions/MCPSessionsPlaylist'export const scene: SceneExport = {component: MCPAnalyticsScene,logic: mcpAnalyticsSceneLogic,+ productKey: ProductKey.MCP_ANALYTICS,+ emptyState: mcpAnalyticsEmptyState,}const MCP_DOCS_URL = 'https://posthog.com/docs/mcp-analytics/installation'@@ -41,7 +44,7 @@ export function MCPAnalyticsScene(): JSX.Element {function MCPAnalyticsSceneContent(): JSX.Element {const { searchParams } = useValues(router)const { activeTab } = useValues(mcpAnalyticsSceneLogic)- const { onboardingState, signals, dashboardStage } = useValues(mcpAnalyticsOnboardingLogic)+ const { onboardingState, dashboardStage } = useValues(mcpAnalyticsOnboardingLogic)// search is Sessions-only — drop it when leaving the tab; the date range stays shared.const { search: _search, ...sharedParams } = searchParams@@ -115,16 +118,11 @@ function MCPAnalyticsSceneContent(): JSX.Element {</>}/>- {/* `signals === null` means we don't know yet — still loading, or a transient- query failure. Hold the skeleton rather than falling through to the empty- dashboard (the very state this onboarding exists to avoid); the 20s poll retries. */}- {signals === null ? (- <MCPAnalyticsLoading />- ) : onboardingState && onboardingState !== 'onboarded' ? (- <MCPAnalyticsOnboarding state={onboardingState} />- ) : (- <LemonTabs activeKey={activeTab} data-attr="mcp-analytics-tabs" tabs={tabs} sceneInset />- )}++ {/* Loading and pre-data states are handled by the app-shell empty-state gate+ (see `emptyState` on the SceneExport) — by the time this renders, either+ tool calls exist or the user explicitly skipped setup. */}+ <LemonTabs activeKey={activeTab} data-attr="mcp-analytics-tabs" tabs={tabs} sceneInset /></SceneContent>)}diff --git a/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.scss b/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.scssnew file mode 100644index 000000000000..d1ffab62ea93--- /dev/null+++ b/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.scss@@ -0,0 +1,289 @@+.MCPPreview {+ --mcp-preview-accent: var(--empty-state-accent, var(--color-primary-500));++ overflow: hidden;+ background: var(--color-bg-surface-primary);+ border: 1px solid var(--color-border-primary);+ border-radius: var(--radius);++ // Hidden filter state. Direct children of .MCPPreview so `:checked ~` can reach the rest.+ &__radio {+ position: absolute;+ width: 0;+ height: 0;+ pointer-events: none;+ opacity: 0;+ }++ &__head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 0.5rem 0.75rem;+ border-bottom: 1px solid var(--color-border-primary);+ }++ &__title {+ font-size: 0.75rem;+ font-weight: 600;+ }++ &__chips {+ display: flex;+ gap: 0.375rem;+ padding: 0.625rem 0.75rem;+ }++ &__chip {+ display: inline-flex;+ gap: 0.25rem;+ align-items: center;+ padding: 0.125rem 0.5rem;+ font-size: 0.6875rem;+ font-weight: 600;+ color: var(--color-text-secondary);+ cursor: pointer;+ user-select: none;+ border: 1px solid var(--color-border-primary);+ border-radius: 999px;+ transition:+ color 150ms ease,+ background-color 150ms ease,+ border-color 150ms ease;+ }++ &__chip:hover {+ color: var(--color-text-primary);+ }++ &__chip img {+ width: 12px;+ height: 12px;+ object-fit: contain;+ }++ &__listening {+ display: flex;+ gap: 0.5rem;+ align-items: center;+ padding: 0 0.75rem 0.5rem;+ font-size: 0.6875rem;+ color: var(--color-text-secondary);+ }++ &__rows {+ display: flex;+ flex-direction: column;+ padding: 0.25rem 0.5rem 0.625rem;+ }++ &__row {+ display: flex;+ gap: 0.625rem;+ align-items: center;+ padding: 0.4375rem 0.5rem;+ border-radius: var(--radius);+ transition: opacity 200ms ease;+ }++ &__row:hover {+ background: var(--color-bg-fill-highlight-50);+ }++ &__logo {+ display: flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ width: 20px;+ height: 20px;+ padding: 2px;+ background: var(--color-bg-surface-secondary);+ border: 1px solid var(--color-border-primary);+ border-radius: 5px;+ }++ &__logo img {+ width: 100%;+ height: 100%;+ object-fit: contain;+ }++ &__tool {+ flex-shrink: 0;+ font-family: var(--font-mono);+ font-size: 0.75rem;+ color: var(--color-text-primary);+ }++ &__time {+ flex-shrink: 0;+ margin-left: auto;+ font-family: var(--font-mono);+ font-size: 0.6875rem;+ color: var(--color-text-secondary);+ }++ &__row--error &__time {+ color: var(--color-red-500);+ }+}++// Third-party brand marks (Cursor, OpenAI) are near-black with transparent backgrounds,+// so on the default dark surface plate they disappear. In dark mode give the plate a light+// backing — the tooltip surface resolves light-on-dark — so the logos stay legible. Light+// mode is already a light plate, so it's left as-is.+[theme='dark'] .MCPPreview__logo {+ background: var(--color-bg-surface-tooltip);+ border-color: color-mix(in oklab, var(--color-black) 12%, transparent);+}++// The radios stay keyboard-focusable even while visually hidden, so the chip they+// label needs a visible focus indicator (WCAG 2.4.7).+#mcp-preview-all:focus-visible ~ .MCPPreview__chips .MCPPreview__chip--all,+#mcp-preview-claude:focus-visible ~ .MCPPreview__chips .MCPPreview__chip--claude,+#mcp-preview-cursor:focus-visible ~ .MCPPreview__chips .MCPPreview__chip--cursor,+#mcp-preview-openai:focus-visible ~ .MCPPreview__chips .MCPPreview__chip--openai {+ outline: 2px solid var(--mcp-preview-accent);+ outline-offset: 1px;+}++// Active filter chip, driven purely by the hidden radios.+#mcp-preview-all:checked ~ .MCPPreview__chips .MCPPreview__chip--all,+#mcp-preview-claude:checked ~ .MCPPreview__chips .MCPPreview__chip--claude,+#mcp-preview-cursor:checked ~ .MCPPreview__chips .MCPPreview__chip--cursor,+#mcp-preview-openai:checked ~ .MCPPreview__chips .MCPPreview__chip--openai {+ color: var(--mcp-preview-accent);+ background: color-mix(in oklab, var(--mcp-preview-accent) 12%, transparent);+ border-color: color-mix(in oklab, var(--mcp-preview-accent) 45%, transparent);+}++// Picking a client dims the rows that don't belong to it.+#mcp-preview-claude:checked ~ .MCPPreview__rows .MCPPreview__row:not([data-h='claude']),+#mcp-preview-cursor:checked ~ .MCPPreview__rows .MCPPreview__row:not([data-h='cursor']),+#mcp-preview-openai:checked ~ .MCPPreview__rows .MCPPreview__row:not([data-h='openai']) {+ opacity: 0.25;+}++.MCPSpark {+ --mcp-spark-accent: var(--empty-state-accent, var(--color-primary-500));++ padding: 1rem 1.125rem;+ background: var(--color-bg-surface-primary);+ border: 1px solid var(--color-border-primary);+ border-radius: var(--radius);++ &__head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ }++ &__title {+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--color-text-secondary);+ }++ &__value {+ display: flex;+ gap: 0.5rem;+ align-items: baseline;+ margin-top: 0.375rem;+ font-size: 1.75rem;+ font-weight: 700;+ line-height: 1.1;+ }++ &__delta {+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--color-green-500);+ }++ &__chart {+ margin-top: 0.625rem;+ }++ &__svg {+ display: block;+ width: 100%;+ height: 56px;+ overflow: visible;+ }++ &__area {+ fill: color-mix(in oklab, var(--mcp-spark-accent) 13%, transparent);+ stroke: none;+ }++ &__line {+ fill: none;+ stroke: color-mix(in oklab, var(--mcp-spark-accent) 32%, transparent);+ stroke-width: 2;+ }++ // The moving bit: a short bright segment cycling along the line.+ &__trace {+ fill: none;+ stroke: var(--mcp-spark-accent);+ stroke-dasharray: 16 84;+ stroke-linecap: round;+ stroke-width: 2;+ animation: MCPSpark__trace 3.2s linear infinite;+ }++ &__clients {+ display: flex;+ gap: 0.375rem;+ align-items: center;+ margin-top: 0.875rem;+ }++ &__clients img {+ width: 16px;+ height: 16px;+ object-fit: contain;+ opacity: 0.85;+ }++ // The PostHog Code entry is a real link; keep it a plain logo, just with a hover cue.+ &__code {+ display: inline-flex;+ transition: opacity 150ms ease;+ }++ &__code img {+ width: 16px;+ height: 16px;+ object-fit: contain;+ opacity: 0.85;+ }++ &__code:hover img {+ opacity: 1;+ }++ &__more {+ margin-left: 0.125rem;+ font-size: 0.6875rem;+ color: var(--color-text-tertiary);+ }+}++// pathLength is normalized to 100, so the dash offset loops cleanly regardless of length.+@keyframes MCPSpark__trace {+ to {+ stroke-dashoffset: -100;+ }+}++@media (prefers-reduced-motion: reduce) {+ .MCPSpark__trace {+ animation: none;+ }+}++.MCPSpark--static .MCPSpark__trace {+ animation: none;+}diff --git a/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.tsx b/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.tsxnew file mode 100644index 000000000000..b3dbf930454b--- /dev/null+++ b/products/mcp_analytics/frontend/emptyState/MCPToolCallPreview.tsx@@ -0,0 +1,168 @@+import './MCPToolCallPreview.scss'++import type { ProductEmptyStateMode } from 'lib/components/ProductEmptyState/types'+import { LemonTag } from 'lib/lemon-ui/LemonTag'+import { Link } from 'lib/lemon-ui/Link'+import { Spinner } from 'lib/lemon-ui/Spinner'+import { cn } from 'lib/utils/css-classes'+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'++import posthogCodeLogo from 'public/posthog-icon.svg'++import claudeLogo from '../harness-logos/claude.svg'+import cursorLogo from '../harness-logos/cursor.svg'+import openaiLogo from '../harness-logos/openai.svg'+import windsurfLogo from '../harness-logos/windsurf.svg'++type PreviewHarness = 'claude' | 'cursor' | 'openai'++interface PreviewCall {+ tool: string+ logo: string+ harness: PreviewHarness+ time: string+ error?: boolean+}++// Example tool calls - hand-authored, not real data. MCP tools are bare snake_case+// names (no parentheses - these are tool invocations, not function calls).+// `harness` tags a row for the filter chips.+const CALLS: PreviewCall[] = [+ { tool: 'search_docs', logo: claudeLogo, harness: 'claude', time: '142ms' },+ { tool: 'create_issue', logo: cursorLogo, harness: 'cursor', time: 'err', error: true },+ { tool: 'run_query', logo: openaiLogo, harness: 'openai', time: '210ms' },+ { tool: 'list_feature_flags', logo: claudeLogo, harness: 'claude', time: '53ms' },+ { tool: 'get_schema', logo: cursorLogo, harness: 'cursor', time: '190ms' },+]++const FILTERS: { id: string; label: string; logo?: string }[] = [+ { id: 'all', label: 'All' },+ { id: 'claude', label: 'Claude', logo: claudeLogo },+ { id: 'cursor', label: 'Cursor', logo: cursorLogo },+ { id: 'openai', label: 'Codex', logo: openaiLogo },+]++// Clients shown under the sparkline (the PostHog Code link is rendered separately, first).+const CLIENT_LOGOS = [claudeLogo, openaiLogo, cursorLogo, windsurfLogo]++// A hand-authored series for the sparkline — abstract, just enough to read as a rising trend.+const SPARK = [4, 6, 5, 7, 6, 9, 8, 10, 9, 12, 11, 14]++function sparkPaths(): { line: string; area: string } {+ const width = 100+ const height = 40+ const pad = 3+ const min = Math.min(...SPARK)+ const max = Math.max(...SPARK)+ const points = SPARK.map((value, i) => {+ const x = (i / (SPARK.length - 1)) * width+ const y = height - pad - ((value - min) / (max - min || 1)) * (height - 2 * pad)+ return `${x.toFixed(1)} ${y.toFixed(1)}`+ })+ const line = 'M ' + points.join(' L ')+ return { line, area: `${line} L ${width} ${height} L 0 ${height} Z` }+}++/**+ * Example-data preview for the MCP analytics empty state. All interaction and motion+ * are pure CSS (hidden radios drive the filter) - no timers or state, per the+ * preview rules in the `building-product-empty-states` skill.+ */+export function MCPToolCallPreview({ mode }: { mode: ProductEmptyStateMode }): JSX.Element {+ const isStatic = inStorybook() || inStorybookTestRunner()+ const { line, area } = sparkPaths()++ return (+ <div className="flex flex-col gap-3">+ <div className="MCPPreview">+ {/* Filter state, before the chips/rows so `:checked ~` can style them. */}+ {FILTERS.map((filter) => (+ <input+ key={filter.id}+ type="radio"+ name="mcp-preview-filter"+ id={`mcp-preview-${filter.id}`}+ defaultChecked={filter.id === 'all'}+ className="MCPPreview__radio"+ />+ ))}++ <div className="MCPPreview__head">+ <span className="MCPPreview__title">Tool calls</span>+ <LemonTag size="small">example data</LemonTag>+ </div>++ <div className="MCPPreview__chips">+ {FILTERS.map((filter) => (+ <label+ key={filter.id}+ htmlFor={`mcp-preview-${filter.id}`}+ className={`MCPPreview__chip MCPPreview__chip--${filter.id}`}+ >+ {filter.logo ? <img src={filter.logo} alt="" /> : null}+ {filter.label}+ </label>+ ))}+ </div>++ {mode === 'waiting-for-data' ? (+ <div className="MCPPreview__listening">+ <Spinner className="text-sm" />+ Listening for your first tool call…+ </div>+ ) : null}++ <div className="MCPPreview__rows">+ {CALLS.map((call, i) => (+ <div+ key={i}+ className={cn('MCPPreview__row', call.error && 'MCPPreview__row--error')}+ data-h={call.harness}+ >+ <span className="MCPPreview__logo">+ <img src={call.logo} alt="" />+ </span>+ <span className="MCPPreview__tool">{call.tool}</span>+ <span className="MCPPreview__time">{call.time}</span>+ </div>+ ))}+ </div>+ </div>++ <div className={cn('MCPSpark', isStatic && 'MCPSpark--static')}>+ <div className="MCPSpark__head">+ <span className="MCPSpark__title">Tool calls · 7 days</span>+ <LemonTag size="small">example data</LemonTag>+ </div>++ <div className="MCPSpark__value">+ 1,284+ <span className="MCPSpark__delta">▲ 18%</span>+ </div>++ <div className="MCPSpark__chart">+ <svg className="MCPSpark__svg" viewBox="0 0 100 40" preserveAspectRatio="none" aria-hidden="true">+ <path className="MCPSpark__area" d={area} />+ <path className="MCPSpark__line" d={line} vectorEffect="non-scaling-stroke" />+ <path className="MCPSpark__trace" d={line} pathLength={100} vectorEffect="non-scaling-stroke" />+ </svg>+ </div>++ <div className="MCPSpark__clients">+ <Link+ className="MCPSpark__code"+ to="https://posthog.com/code?utm_medium=in-product&utm_campaign=mcp-analytics-empty-state"+ target="_blank"+ title="PostHog Code"+ >+ <img src={posthogCodeLogo} alt="PostHog Code" />+ </Link>+ {CLIENT_LOGOS.map((logo, i) => (+ <img key={i} src={logo} alt="" />+ ))}+ <span className="MCPSpark__more">+12 clients</span>+ </div>+ </div>+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/emptyState/mcpAnalyticsEmptyState.tsx b/products/mcp_analytics/frontend/emptyState/mcpAnalyticsEmptyState.tsxnew file mode 100644index 000000000000..a54c449c82a0--- /dev/null+++ b/products/mcp_analytics/frontend/emptyState/mcpAnalyticsEmptyState.tsx@@ -0,0 +1,46 @@+import * as roboHogPng from '@posthog/brand/hoggies/png/robo-hog'+import { IconMCP } 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 { mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'+import { MCP_ANALYTICS_DOCS_URL, MCPListeningIndicator } from '../onboarding/MCPAnalyticsInstall'+import { MCPToolCallPreview } from './MCPToolCallPreview'++const HedgehogRoboHog = pngHoggie(roboHogPng)++export const mcpAnalyticsEmptyState: SceneProductEmptyState = {+ statusLogic: mcpAnalyticsOnboardingLogic,+ // The whole product is behind this flag; its scene-level preview gate handles the flag-off case.+ featureFlag: FEATURE_FLAGS.MCP_ANALYTICS,+ config: {+ productKey: ProductKey.MCP_ANALYTICS,+ productName: 'MCP analytics',+ icon: <IconMCP />,+ accentColor: 'var(--color-product-mcp-analytics-light)',+ accentColorDark: 'var(--color-product-mcp-analytics-dark)',+ hedgehog: HedgehogRoboHog,+ text: {+ 'needs-setup': {+ headline: 'Know how agents actually use your tools',+ lead: 'Capture every MCP tool call, argument and result, so you can see which tools agents reach for, where they fail, and how long each call takes.',+ hint: 'Point the wizard at your MCP server. LLM inference is on us, no API key needed:',+ },+ 'waiting-for-data': {+ headline: "You're connected. Now make a tool call",+ lead: "We've seen your MCP server connect, but it hasn't handled a tool call yet. Trigger a tool from your agent and this page fills in on its own.",+ hint: 'Instrumenting another server? Re-run setup:',+ },+ },+ wizard: { slug: 'mcp-analytics', pinProjectId: true },+ docsUrl: MCP_ANALYTICS_DOCS_URL,+ manualSetupUrl: 'https://posthog.com/docs/mcp-analytics/installation',+ previewLabel: 'Tool calls, once connected',+ Preview: MCPToolCallPreview,+ statusIndicator: <MCPListeningIndicator />,+ },+}diff --git a/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.test.ts b/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.test.tsindex c4e44aea6453..6a675475d871 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.test.ts@@ -1,7 +1,9 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'+import { ProductKey } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { mcpAnalyticsOnboardingLogic } from './mcpAnalyticsOnboardingLogic'@@ -69,4 +71,36 @@ describe('mcpAnalyticsOnboardingLogic', () => {await expectLogic(logic).toFinishAllListeners()expect(logic.values.signals?.firstCallAt).toBeNull()})++ // Guards the connect + mapping into the app-wide setup-status layer: if either+ // breaks, the scene empty-state gate stays on its loading spinner forever.+ it.each([+ [[[1, 1, 1, '2026-07-01T00:00:00Z']], 'has-data'],+ [[[1, 0, 0, '1970-01-01T00:00:00Z']], 'waiting-for-data'],+ [[[0, 0, 0, '1970-01-01T00:00:00Z']], 'needs-setup'],+ ])('pushes signal row %j into productSetupStatusLogic as %s', async (results, expected) => {+ const logic = mountWith(results)+ await expectLogic(logic).toFinishAllListeners()+ const setupLogic = productSetupStatusLogic({ productKey: ProductKey.MCP_ANALYTICS })+ expect(setupLogic.values.status).toBe(expected)+ })++ // Guards the fail-open path: a persistently failing signal query must publish+ // `unknown` (gate renders the scene), not leave the gate on its spinner forever.+ it('publishes unknown when the signal query fails before any answer exists', async () => {+ jest.spyOn(mockApi, 'query').mockRejectedValue(new Error('query failed'))+ const logic = mcpAnalyticsOnboardingLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(productSetupStatusLogic({ productKey: ProductKey.MCP_ANALYTICS }).values.status).toBe('unknown')+ })++ it('a failing poll never downgrades an existing answer', async () => {+ const logic = mountWith([[1, 1, 1, '2026-07-01T00:00:00Z']])+ await expectLogic(logic).toFinishAllListeners()+ jest.spyOn(mockApi, 'query').mockRejectedValue(new Error('query failed'))+ logic.actions.loadSignals()+ await expectLogic(logic).toFinishAllListeners()+ expect(productSetupStatusLogic({ productKey: ProductKey.MCP_ANALYTICS }).values.status).toBe('has-data')+ })})diff --git a/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.tsindex bd2163ed3718..bd9f0a705e90 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.ts@@ -1,7 +1,9 @@-import { MakeLogicType, afterMount, kea, listeners, path, selectors } from 'kea'+import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors } from 'kea'import { loaders } from 'kea-loaders'import api from 'lib/api'+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'+import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'import { addProductIntent } from 'lib/utils/product-intents'import { userLogic } from 'scenes/userLogic'@@ -18,6 +20,20 @@ function isImpersonatedSession(): boolean {export type MCPOnboardingState = 'not-instrumented' | 'connected-no-calls' | 'onboarded'+/** Maps MCP's three-state model onto the app-wide product setup vocabulary. */+export function emptyStateStatusForOnboardingState(onboardingState: MCPOnboardingState | null): ProductSetupStatus {+ if (onboardingState === null) {+ return 'loading'+ }+ if (onboardingState === 'onboarded') {+ return 'has-data'+ }+ if (onboardingState === 'connected-no-calls') {+ return 'waiting-for-data'+ }+ return 'needs-setup'+}+/*** Which question the dashboard answers, by volume. `activity` is for "what are* agents doing with my server?" — a live feed, verbatim intents, and an@@ -69,6 +85,7 @@ const POLL_INTERVAL_MS = 20000// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpAnalyticsOnboardingLogicValues {+ setupStatus: ProductSetupStatus // productSetupStatusLogicdashboardStage: MCPDashboardStage | nullisOnboarded: booleanonboardingState: MCPOnboardingState | null@@ -78,6 +95,9 @@ export interface mcpAnalyticsOnboardingLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpAnalyticsOnboardingLogicActions {+ setDetectedStatus: (status: ProductSetupStatus) => {+ status: ProductSetupStatus+ } // productSetupStatusLogicloadSignals: (_: void) => voidloadSignalsFailure: (error: string,@@ -113,6 +133,10 @@ export type mcpAnalyticsOnboardingLogicType = MakeLogicType<export const mcpAnalyticsOnboardingLogic = kea<mcpAnalyticsOnboardingLogicType>([path(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsOnboardingLogic']),+ connect(() => ({+ actions: [productSetupStatusLogic({ productKey: ProductKey.MCP_ANALYTICS }), ['setDetectedStatus']],+ values: [productSetupStatusLogic({ productKey: ProductKey.MCP_ANALYTICS }), ['status as setupStatus']],+ })),loaders({signals: {__default: null as MCPOnboardingSignals | null,@@ -181,8 +205,21 @@ export const mcpAnalyticsOnboardingLogic = kea<mcpAnalyticsOnboardingLogicType>(},],}),- listeners(({ values, cache }) => ({+ listeners(({ actions, values, cache }) => ({+ loadSignalsFailure: () => {+ // A failing signal query must not strand the empty-state gate on its+ // spinner. If nothing (preload included) has answered yet, publish+ // `unknown` so the gate fails open to the real scene - the poll keeps+ // retrying and a later success replaces this. A failure never downgrades+ // an existing answer.+ if (values.setupStatus === 'loading') {+ actions.setDetectedStatus('unknown')+ }+ },loadSignalsSuccess: () => {+ // Feed the app-wide setup-status layer (drives the scene empty-state gate).+ actions.setDetectedStatus(emptyStateStatusForOnboardingState(values.onboardingState))+// Mark the diagnostic middle of the funnel: the SDK is connected but no// tool calls have landed yet. Separates an install problem (never// instrumented) from a traffic problem (wired up, but the server isn'tdiff --git a/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.tsindex 997a83796532..9162c1e4e7d0 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsSceneLogic.ts@@ -1,16 +1,11 @@import { MakeLogicType, connect, kea, listeners, path, selectors } from 'kea'import { combineUrl, router } from 'kea-router'-import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { ProductKey } from '~/queries/schema/schema-general'import { sceneLogic } from '~/scenes/sceneLogic'-import { OnboardingStepKey } from '~/types'-import type { TeamPublicType, TeamType } from '../../../frontend/src/types'import { mcpAnalyticsOnboardingLogic } from './mcpAnalyticsOnboardingLogic'-import type { MCPOnboardingState } from './mcpAnalyticsOnboardingLogic'export type MCPAnalyticsTab = 'activity' | 'dashboard' | 'sessions' | 'tool-quality' | 'intent-clustering'@@ -47,9 +42,7 @@ const SCENE_KEY_TO_TAB: Record<string, MCPAnalyticsTab> = {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpAnalyticsSceneLogicValues {- onboardingState: MCPOnboardingState | null // mcpAnalyticsOnboardingLogicsceneKey: string | null // sceneLogic- currentTeam: TeamPublicType | TeamType | null // teamLogicactiveTab: MCPAnalyticsTab}@@ -70,14 +63,7 @@ export type mcpAnalyticsSceneLogicType = MakeLogicType<export const mcpAnalyticsSceneLogic = kea<mcpAnalyticsSceneLogicType>([path(['products', 'mcp_analytics', 'frontend', 'mcpAnalyticsSceneLogic']),connect(() => ({- values: [- sceneLogic,- ['sceneKey'],- mcpAnalyticsOnboardingLogic,- ['onboardingState'],- teamLogic,- ['currentTeam'],- ],+ values: [sceneLogic, ['sceneKey']],})),selectors({activeTab: [@@ -86,18 +72,10 @@ export const mcpAnalyticsSceneLogic = kea<mcpAnalyticsSceneLogicType>([],}),listeners(({ values, cache }) => ({- // Send never-set-up projects straight into the polished onboarding flow,- // rather than the bare in-scene card. Guarded on `has_completed_onboarding_for`- // so the post-onboarding return to the dashboard doesn't bounce back here —- // once they've been through setup we let the in-scene "waiting" state show.+ // Never-set-up projects stay in-scene: the scene's `emptyState` (SceneExport)+ // renders the setup screen right here until data arrives, so there's no+ // redirect into the app-wide onboarding flow.[mcpAnalyticsOnboardingLogic.actionTypes.loadSignalsSuccess]: () => {- const completed = values.currentTeam?.has_completed_onboarding_for?.[ProductKey.MCP_ANALYTICS]- if (values.onboardingState === 'not-instrumented' && !completed) {- router.actions.replace(- urls.onboarding({ productKey: ProductKey.MCP_ANALYTICS, stepKey: OnboardingStepKey.INSTALL })- )- return- }// Volume decides the default landing tab. Only fires when the manifest's// bare-URL redirect tagged the navigation with `landing=auto` — a deep link// to /dashboard never re-routes, and an explicit tab click is never overridden.diff --git a/products/mcp_analytics/frontend/onboarding/MCPAnalyticsInstall.tsx b/products/mcp_analytics/frontend/onboarding/MCPAnalyticsInstall.tsxindex db3e124be020..bccaae1fcf5d 100644--- a/products/mcp_analytics/frontend/onboarding/MCPAnalyticsInstall.tsx+++ b/products/mcp_analytics/frontend/onboarding/MCPAnalyticsInstall.tsx@@ -4,31 +4,19 @@ import { IconCheckCircle } from '@posthog/icons'import { LemonButton, Spinner } from '@posthog/lemon-ui'import { CommandBlock } from 'lib/components/CommandBlock/CommandBlock'-import { cn } from 'lib/utils/css-classes'-import { useWizardCommand } from 'scenes/onboarding/shared/SetupWizardBanner'-import { WIZARD_HOG_URL } from 'scenes/onboarding/shared/wizardHog'+import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'+import { WizardHog } from 'scenes/onboarding/shared/wizardHog'import { teamLogic } from 'scenes/teamLogic'import { mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'export const MCP_ANALYTICS_DOCS_URL = 'https://posthog.com/docs/mcp-analytics'-// The shared wizard hook only emits the base command; slot in our subcommand right-// after the package reference (before any flags like `--region eu`). Matching-// `@posthog/wizard@<anything>` keeps this working if the hook ever pins a version;-// the fallback guarantees the subcommand is never silently dropped.-const WIZARD_PKG_RE = /@posthog\/wizard@\S+/-export function useMCPAnalyticsWizardCommand(): { command: string; isCloudOrDev: boolean } {- const { wizardCommand, isCloudOrDev } = useWizardCommand()- const { currentTeam } = useValues(teamLogic)- const base = WIZARD_PKG_RE.test(wizardCommand)- ? wizardCommand.replace(WIZARD_PKG_RE, '$& mcp-analytics')- : `${wizardCommand} mcp-analytics`- // Pin the project so the wizard targets this team directly — and, once the consent- // screen honors the hint, pre-selects it. Harmless if the user authorizes the same project.- const command = currentTeam?.id ? `${base} --project-id=${currentTeam.id}` : base- return { command, isCloudOrDev }+ // Pinning the project keeps this surface and the in-scene empty state (which+ // builds the same command from its `wizard` config) from drifting apart.+ const { wizardCommand, isCloudOrDev } = useWizardCommand('mcp-analytics', { pinProjectId: true })+ return { command: wizardCommand, isCloudOrDev }}/** Live "are events arriving yet?" status, driven by the same poll the scene uses. */@@ -82,11 +70,7 @@ export function MCPAnalyticsInstallHero(): JSX.Element {{isCloudOrDev && (<div className="flex items-center gap-6">- <img- src={WIZARD_HOG_URL}- alt="PostHog wizard hedgehog"- className={cn('w-28 h-28 hidden md:block shrink-0')}- />+ <WizardHog className="w-28 h-28 hidden md:block shrink-0" /><div className="flex-1 min-w-0 flex flex-col gap-3"><CommandBlockcommand={command}diff --git a/products/mcp_analytics/manifest.tsx b/products/mcp_analytics/manifest.tsxindex fb16ba8e580d..124220a024d2 100644--- a/products/mcp_analytics/manifest.tsx+++ b/products/mcp_analytics/manifest.tsx@@ -57,17 +57,26 @@ export const manifest: ProductManifest = {mcpAnalyticsTool: (toolName: string): string => `/mcp-analytics/tool-quality/${encodeURIComponent(toolName)}`,mcpAnalyticsIntentClustering: (): string => '/mcp-analytics/intent-clustering',},+ setupProbe: {+ productKey: ProductKey.MCP_ANALYTICS,+ hasDataEvents: ['$mcp_tool_call'],+ waitingEvents: ['$mcp_initialize'],+ featureFlag: FEATURE_FLAGS.MCP_ANALYTICS,+ },fileSystemTypes: {},treeItemsNew: [],treeItemsProducts: [{path: 'MCP analytics',- intents: [ProductKey.AI_OBSERVABILITY],+ intents: [ProductKey.MCP_ANALYTICS],category: ProductItemCategory.AI_ENGINEERING,visualOrder: 2,type: 'mcp_analytics',iconType: 'mcp_analytics' as FileSystemIconType,- iconColor: ['var(--color-product-llm-analytics-light)'] as FileSystemIconColor,+ iconColor: [+ 'var(--color-product-mcp-analytics-light)',+ 'var(--color-product-mcp-analytics-dark)',+ ] as FileSystemIconColor,href: urls.mcpAnalyticsDashboard(),flag: FEATURE_FLAGS.MCP_ANALYTICS,tags: ['beta'],diff --git a/products/workflows/frontend/onboarding/steps.tsx b/products/workflows/frontend/onboarding/steps.tsxindex 23f4925b2460..020aef2a3367 100644--- a/products/workflows/frontend/onboarding/steps.tsx+++ b/products/workflows/frontend/onboarding/steps.tsx@@ -7,7 +7,7 @@ import {WorkflowsSDKTagOverrides,} from 'scenes/onboarding/legacy/sdks/workflows/WorkflowsSDKInstructions'import { type ProductOnboardingProvider } from 'scenes/onboarding/legacy/types'-import { useWizardCommand } from 'scenes/onboarding/shared/SetupWizardBanner'+import { useWizardCommand } from 'scenes/onboarding/shared/useWizardCommand'import { urls } from 'scenes/urls'import { ProductKey } from '~/queries/schema/schema-general'