Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(product-empty-states): shared detection factory and stale-aware boot probes (#90606)

Rafael Audibert96f816553ea1
diff --git a/.agents/skills/building-product-empty-states/SKILL.md b/.agents/skills/building-product-empty-states/SKILL.md
index 6dda49ee7e5c..5764e2f906d7 100644
--- a/.agents/skills/building-product-empty-states/SKILL.md
+++ b/.agents/skills/building-product-empty-states/SKILL.md
@@ -23,7 +23,22 @@ Before a user has set a product up, its scene should show a setup empty state: t
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:
+Default: one call to `createSetupDetectionLogic` (`lib/components/ProductEmptyState/setupDetectionLogic.ts`). Supply a `detect` function resolving the product's status; the factory owns the shared contract - detect on mount, optionally poll until data lands (stopping for good on `has-data`, pausing on hidden tabs), fail open on errors, and wait out bootstrap before the first check:
+
+```ts
+export const logsSetupLogic = createSetupDetectionLogic({
+ productKey: ProductKey.LOGS,
+ path: ['products', 'logs', 'frontend', 'emptyState', 'logsSetupLogic'],
+ detect: async () => ((await api.logs.hasLogs()) ? 'has-data' : 'needs-setup'),
+ // Only for products where data arrives from outside (SDK events); entity-count
+ // products omit it - the gate remounts the logic on every scene entry.
+ pollIntervalMs: 20000,
+})
+```
+
+`detect` composes freely: retry inside it with `retryWithBackoff`, return `unknown` for "cannot tell" (e.g. no access), return `waiting-for-data` from an opt-in flag + count check. When the query is a fresh event count, use `refresh: 'force_blocking'` - a cached pre-ingestion `[0,0]` would otherwise stick. `recheckActionTypes` re-detects immediately when app state changes elsewhere (a team-setting opt-in). `cacheHasData` remembers a has-data answer in localStorage so returning users skip the spinner and the query - use it for products with no boot-time probe.
+
+Products whose detection drives more than the gate (extra selectors, staged dashboards) keep a bespoke logic instead - template: `products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.ts`. It must push the status from a listener and handle failure the same way the factory does:
```ts
connect(() => ({
@@ -87,7 +102,7 @@ Then **delete** the scene's bespoke empty/loading branches (including any custom
### 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.
+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 all at boot with one batched event-definitions request (Postgres, cheap). This is what lets the app resolve your status before the user ever opens the scene; your in-scene detection stays the fresher source of truth. Set `staleAfterDays` when your detection logic uses a staleness window, so a project that stopped sending long ago reads as needing setup at boot too. Use string literals for event names - the probe is cloned into the eager generated `products.tsx`, so it must not import from your product chunk. The `ProductSetupProbe` shape and the definitions-to-status mapping live in `lib/components/ProductEmptyState/setupProbes.ts`. Products whose detection isn't event-based (exists APIs, entity counts) skip this; their status resolves on first scene visit.
### 5. Test the status mapping
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 72364d6fcbdd..d12a275981a2 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1757,7 +1757,7 @@ snapshots:
components-product-empty-state--empty-with-action--light:
hash: v1.k794b7964.80a94ce3b72b30fc78f17c3df97f60b02513da190f16b10b785ddc6410e29610.LI50ALV6r5CTuWZhpD9jAdNFn5t82tuAdtAuP0FZw7o
components-product-empty-state--endpoints-needs-setup--dark:
- hash: v1.k794b7964.31d843c9f5b5474e95f2f3cba65e0eaccd633a550a117e7b00843faca66897a8.2Zjm-wMj9BWhNxwccN3ziu3_bwNd8wBCSWMgTevhMQQ
+ hash: v1.k794b7964.de021a6d2a8c7ec6bc031fc7c9586a2d9f12e80804b9a92ec1a9f464c096314e.jqj7jfnrY7rf7IO2Uqrc784pV_YXfH52sTArLcXn8c0
components-product-empty-state--endpoints-needs-setup--light:
hash: v1.k794b7964.f704e98aa8d0102c164b7db7390449584c4b84f461cc5bbeac426e48a16dc200.S0QeUPtO_6LQsU5lZ09MyJMaf_Q_CPBBuYbvKzik1cU
components-product-empty-state--experiments-needs-setup--dark:
diff --git a/frontend/src/lib/components/ProductEmptyState/README.md b/frontend/src/lib/components/ProductEmptyState/README.md
index 25e6505f6fad..7a0d49821949 100644
--- a/frontend/src/lib/components/ProductEmptyState/README.md
+++ b/frontend/src/lib/components/ProductEmptyState/README.md
@@ -6,6 +6,10 @@ Scenes opt in declaratively: set `emptyState` on the scene's `SceneExport` and t
`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.
+Most detection logics are one call to `createSetupDetectionLogic` (`setupDetectionLogic.ts`): the product supplies a `detect` function resolving its status, and the factory owns the shared contract — detect on mount, optionally poll until data lands (stopping for good on `has-data`), and fail open on errors so a broken query never strands the gate on its spinner. Products whose detection drives more than the gate (extra selectors, staged dashboards like MCP analytics) keep a bespoke logic that pushes into `productSetupStatusLogic` directly.
+
+Products detectable from event definitions also declare a `setupProbe` in their manifest, which `productSetupPreloadLogic` answers at app boot with one batched request — so the status is usually known before the scene is ever opened. Probes support a `staleAfterDays` window for products where old, abandoned data shouldn't count as set up.
+
**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/_previewMixins.scss b/frontend/src/lib/components/ProductEmptyState/_previewMixins.scss
index c124abf39bfd..6ef9503f70fb 100644
--- a/frontend/src/lib/components/ProductEmptyState/_previewMixins.scss
+++ b/frontend/src/lib/components/ProductEmptyState/_previewMixins.scss
@@ -95,11 +95,13 @@ $preview-swap-duration: 250ms;
}
// One of the window dots in a preview's fake browser or app chrome.
+// `--color-bg-fill-tertiary`, not `--color-fill-secondary`: the latter is not
+// defined in the main app, so it computes to transparent and the dots vanish.
@mixin preview-chrome-dot {
&__chrome-dot {
width: 7px;
height: 7px;
- background: var(--color-fill-secondary);
+ background: var(--color-bg-fill-tertiary);
border-radius: 50%;
}
}
diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts
index 44a8fc5e4ca0..9f75ad1fce01 100644
--- a/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts
+++ b/frontend/src/lib/components/ProductEmptyState/productSetupPreloadLogic.ts
@@ -9,7 +9,7 @@ import * as api from 'products/event_definitions/frontend/generated/api'
import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
import { productSetupStatusLogic } from './productSetupStatusLogic'
-import { ProductSetupProbe, statusFromProbeDefinitions } from './setupProbes'
+import { ProbeEventDefinition, ProductSetupProbe, statusFromProbeDefinitions } from './setupProbes'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupPreloadLogicValues {
@@ -74,13 +74,13 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([
...new Set(probes.flatMap((probe) => [...probe.hasDataEvents, ...(probe.waitingEvents ?? [])])),
]
- let existingEventNames: Set<string>
+ let existingDefinitions: ProbeEventDefinition[]
try {
const response = await api.eventDefinitionsList(String(teamId), {
names: eventNames,
limit: eventNames.length,
})
- existingEventNames = new Set(response.results.map(({ name }) => name))
+ existingDefinitions = response.results.map(({ name, last_seen_at }) => ({ name, last_seen_at }))
} catch (error) {
if (error instanceof Error && isBreakpoint(error)) {
throw error
@@ -96,7 +96,7 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([
for (const probe of probes) {
seeded.add(`${teamId}:${probe.productKey}`)
- seedProbeStatus(probe, existingEventNames, cache)
+ seedProbeStatus(probe, existingDefinitions, cache)
}
},
// Covers login and project switches that happen after mount.
@@ -126,7 +126,11 @@ export const productSetupPreloadLogic = kea<productSetupPreloadLogicType>([
}),
])
-function seedProbeStatus(probe: ProductSetupProbe, eventNames: Set<string>, cache: Record<string, any>): void {
+function seedProbeStatus(
+ probe: ProductSetupProbe,
+ definitions: ProbeEventDefinition[],
+ 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
@@ -145,6 +149,6 @@ function seedProbeStatus(probe: ProductSetupProbe, eventNames: Set<string>, cach
// 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(statusFromProbeDefinitions(probe, eventNames))
+ instance.actions.setDetectedStatus(statusFromProbeDefinitions(probe, definitions))
}
}
diff --git a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts
new file mode 100644
index 000000000000..2ef30087281b
--- /dev/null
+++ b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts
@@ -0,0 +1,163 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { createSetupDetectionLogic } from './setupDetectionLogic'
+import type { ProductSetupStatus } from './types'
+
+describe('createSetupDetectionLogic', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ function buildLogic(
+ detect: jest.Mock<Promise<ProductSetupStatus>, []>,
+ pollIntervalMs?: number
+ ): ReturnType<ReturnType<typeof createSetupDetectionLogic>['build']> {
+ const logic = createSetupDetectionLogic({
+ productKey: ProductKey.LOGS,
+ path: ['test', 'setupDetectionLogic'],
+ detect,
+ pollIntervalMs,
+ })
+ return logic.build()
+ }
+
+ // The factory's whole job is feeding the scene gate: a status that never
+ // arrives strands every adopting product on the scene-level spinner.
+ it.each([['has-data'], ['needs-setup'], ['waiting-for-data'], ['unknown']] as const)(
+ 'pushes a detected %s into productSetupStatusLogic',
+ async (status) => {
+ const logic = buildLogic(jest.fn().mockResolvedValue(status))
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe(status)
+ }
+ )
+
+ it('fails open to unknown when detection fails before any answer', async () => {
+ const logic = buildLogic(jest.fn().mockRejectedValue(new Error('network down')))
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe('unknown')
+ })
+
+ it('never downgrades an existing answer on a poll blip', async () => {
+ const detect = jest
+ .fn<Promise<ProductSetupStatus>, []>()
+ .mockResolvedValueOnce('needs-setup')
+ .mockRejectedValueOnce(new Error('blip'))
+ const logic = buildLogic(detect)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.detectStatus()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe('needs-setup')
+ })
+
+ // `toFinishAllListeners` waits on real timers, so under fake timers flush
+ // the microtask queue by hand instead.
+ async function flushMicrotasks(): Promise<void> {
+ for (let i = 0; i < 10; i++) {
+ await Promise.resolve()
+ }
+ }
+
+ it('polls until data arrives, then stops for good', async () => {
+ jest.useFakeTimers()
+ const detect = jest
+ .fn<Promise<ProductSetupStatus>, []>()
+ .mockResolvedValueOnce('needs-setup')
+ .mockResolvedValue('has-data')
+ const logic = buildLogic(detect, 1000)
+ logic.mount()
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(1)
+
+ // First tick re-detects and lands on has-data...
+ jest.advanceTimersByTime(1000)
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(2)
+ expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe('has-data')
+
+ // ...after which the poll is disposed: more ticks run no more detections.
+ jest.advanceTimersByTime(5000)
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(2)
+ })
+
+ it('re-detects when a recheck action fires', async () => {
+ const detect = jest
+ .fn<Promise<ProductSetupStatus>, []>()
+ .mockResolvedValueOnce('needs-setup')
+ .mockResolvedValue('waiting-for-data')
+ const logic = createSetupDetectionLogic({
+ productKey: ProductKey.LOGS,
+ path: ['test', 'setupDetectionLogic'],
+ detect,
+ recheckActionTypes: () => [teamLogic.actionTypes.updateCurrentTeamSuccess],
+ }).build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe('needs-setup')
+
+ // A team-setting flip (e.g. enabling exception autocapture) must refresh
+ // the status right away, not on the next poll tick.
+ teamLogic.actions.updateCurrentTeamSuccess(MOCK_DEFAULT_TEAM, undefined)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(detect).toHaveBeenCalledTimes(2)
+ expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe('waiting-for-data')
+ })
+
+ it('with cacheHasData, remembers has-data and skips detection on the next mount', async () => {
+ const onDetected = jest.fn()
+ const buildCached = (
+ detect: jest.Mock<Promise<ProductSetupStatus>, []>
+ ): ReturnType<ReturnType<typeof createSetupDetectionLogic>['build']> =>
+ createSetupDetectionLogic({
+ productKey: ProductKey.LOGS,
+ path: ['test', 'setupDetectionLogic'],
+ detect,
+ cacheHasData: true,
+ onDetected,
+ }).build()
+
+ const first = buildCached(jest.fn().mockResolvedValue('has-data'))
+ first.mount()
+ await expectLogic(first).toFinishAllListeners()
+ first.unmount()
+ onDetected.mockClear()
+
+ // A stale-cached needs-setup would gate projects with real data, so only
+ // has-data may skip detection.
+ const detect = jest.fn<Promise<ProductSetupStatus>, []>().mockResolvedValue('needs-setup')
+ const second = buildCached(detect)
+ second.mount()
+ await expectLogic(second).toFinishAllListeners()
+ expect(detect).not.toHaveBeenCalled()
+ expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe('has-data')
+ expect(onDetected).toHaveBeenCalledWith('has-data')
+ })
+
+ it('does not poll when no interval is configured', async () => {
+ jest.useFakeTimers()
+ const detect = jest.fn<Promise<ProductSetupStatus>, []>().mockResolvedValue('needs-setup')
+ const logic = buildLogic(detect)
+ logic.mount()
+ await flushMicrotasks()
+ jest.advanceTimersByTime(60000)
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
new file mode 100644
index 000000000000..f57aea76dd56
--- /dev/null
+++ b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
@@ -0,0 +1,205 @@
+import { BreakPointFunction, LogicWrapper, MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { projectLogic } from 'scenes/projectLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+
+import { productSetupStatusLogic } from './productSetupStatusLogic'
+import type { ProductSetupStatus } from './types'
+
+// Alias kea so kea-typegen skips this factory - the logic type is hand-written below.
+const buildKea = kea
+
+export interface SetupDetectionLogicOptions {
+ productKey: ProductKey
+ /** kea path, e.g. `['products', 'logs', 'frontend', 'emptyState', 'logsSetupLogic']` */
+ path: string[]
+ /**
+ * Resolve the product's current setup status. Runs on mount and on every poll
+ * tick. Return `unknown` for "cannot tell" (e.g. no access) - the gate fails
+ * open. Throwing counts as a detection failure: the gate fails open if nothing
+ * has answered yet, and a later blip never downgrades an existing answer.
+ */
+ detect: () => Promise<ProductSetupStatus>
+ /**
+ * Re-check cadence while the product has no data yet, so the empty state flips
+ * to the real scene on its own once events land. Polling stops for good on the
+ * first `has-data` answer, and pauses on hidden tabs. Omit for products whose
+ * status only changes through in-app actions (entity counts) - the gate
+ * remounts this logic on every scene entry, which is fresh enough.
+ */
+ pollIntervalMs?: number
+ /** Side effects on each successful detection (product intents, setup-task completion). */
+ onDetected?: (status: ProductSetupStatus) => void
+ /**
+ * Action types (e.g. `teamLogic.actionTypes.updateCurrentTeamSuccess`) that
+ * trigger an immediate re-detect, for products whose status hangs off state
+ * changed elsewhere in the app - a team-setting opt-in, an entity created
+ * from a modal. Without one, the next poll tick (or scene re-entry) is the
+ * only refresh. A function, because `actionTypes` cannot be read at module
+ * import time - it is evaluated when this logic mounts.
+ */
+ recheckActionTypes?: () => string[]
+ /**
+ * Remember a has-data answer in localStorage (keyed team + product) and skip
+ * detection on later mounts. Only that direction is cached - data never
+ * disappears once ingested, while needs-setup keeps re-checking. For products
+ * without a boot-time probe, this is what spares the returning user a spinner
+ * and a query on every scene entry.
+ */
+ cacheHasData?: boolean
+}
+
+export interface SetupDetectionValues {
+ detectedStatus: ProductSetupStatus | null
+ detectedStatusLoading: boolean
+ setupStatus: ProductSetupStatus
+ currentProjectId: number | null
+ currentTeamId: number | null
+}
+
+export interface SetupDetectionActions {
+ detectStatus: () => void
+ detectStatusSuccess: (
+ detectedStatus: ProductSetupStatus | null,
+ payload?: void
+ ) => { detectedStatus: ProductSetupStatus | null }
+ detectStatusFailure: (error: string, errorObject?: unknown) => { error: string }
+ setDetectedStatus: (status: ProductSetupStatus) => { status: ProductSetupStatus }
+}
+
+export type SetupDetectionLogicType = MakeLogicType<SetupDetectionValues, SetupDetectionActions>
+
+/**
+ * Builds a product's empty-state detection logic: the piece that answers "is this
+ * product set up?" and pushes the answer into `productSetupStatusLogic`. Wraps the
+ * contract every adoption re-implemented by hand - detect on mount, poll until data
+ * arrives, fail open on errors - so a product only supplies its `detect` function:
+ *
+ * ```ts
+ * export const logsSetupLogic = createSetupDetectionLogic({
+ * productKey: ProductKey.LOGS,
+ * path: ['products', 'logs', 'frontend', 'emptyState', 'logsSetupLogic'],
+ * detect: async () => ((await api.logs.hasLogs()) ? 'has-data' : 'needs-setup'),
+ * pollIntervalMs: 20000,
+ * })
+ * ```
+ *
+ * Products whose detection drives more than the gate (extra selectors, multi-stage
+ * dashboards like MCP analytics) keep a bespoke logic instead.
+ */
+function hasDataCacheKey(teamId: number, productKey: ProductKey): string {
+ return `ph-product-setup-has-data/${teamId}/${productKey}`
+}
+
+// localStorage can throw (private modes, disabled storage); a cache miss is always safe.
+function readCachedHasData(teamId: number | null, productKey: ProductKey): boolean {
+ try {
+ return teamId !== null && window.localStorage.getItem(hasDataCacheKey(teamId, productKey)) === '1'
+ } catch {
+ return false
+ }
+}
+
+function writeCachedHasData(teamId: number | null, productKey: ProductKey): void {
+ try {
+ if (teamId !== null) {
+ window.localStorage.setItem(hasDataCacheKey(teamId, productKey), '1')
+ }
+ } catch {
+ // Nothing cached; the next mount just detects again.
+ }
+}
+
+export function createSetupDetectionLogic(options: SetupDetectionLogicOptions): LogicWrapper<SetupDetectionLogicType> {
+ const { productKey, detect, pollIntervalMs, onDetected, recheckActionTypes, cacheHasData } = options
+ return buildKea<SetupDetectionLogicType>([
+ path(options.path),
+ connect(() => ({
+ actions: [productSetupStatusLogic({ productKey }), ['setDetectedStatus']],
+ values: [
+ productSetupStatusLogic({ productKey }),
+ ['status as setupStatus'],
+ projectLogic,
+ ['currentProjectId'],
+ teamLogic,
+ ['currentTeamId'],
+ ],
+ })),
+ loaders({
+ detectedStatus: {
+ __default: null as ProductSetupStatus | null,
+ detectStatus: async (_: void, breakpoint: BreakPointFunction): Promise<ProductSetupStatus> => {
+ const status = await detect()
+ breakpoint()
+ return status
+ },
+ },
+ }),
+ listeners(({ actions, values, cache }) => ({
+ ...Object.fromEntries(
+ (recheckActionTypes?.() ?? []).map((actionType) => [
+ actionType,
+ () => {
+ if (values.currentProjectId) {
+ actions.detectStatus()
+ }
+ },
+ ])
+ ),
+ detectStatusSuccess: ({ detectedStatus }) => {
+ if (!detectedStatus) {
+ return
+ }
+ actions.setDetectedStatus(detectedStatus)
+ onDetected?.(detectedStatus)
+ // Data never disappears once it exists, so the poll's job is done.
+ if (detectedStatus === 'has-data') {
+ cache.disposables.dispose('poll')
+ if (cacheHasData) {
+ writeCachedHasData(values.currentTeamId, productKey)
+ }
+ }
+ },
+ detectStatusFailure: () => {
+ // Never strand the gate on its spinner: if nothing (preload included)
+ // has answered yet, fail open to the real scene. The poll keeps
+ // retrying, and a failure never downgrades an existing answer.
+ if (values.setupStatus === 'loading') {
+ actions.setDetectedStatus('unknown')
+ }
+ },
+ [projectLogic.actionTypes.loadCurrentProjectSuccess]: () => {
+ // Covers non-polling products mounted before bootstrap settled.
+ if (values.detectedStatus === null && !values.detectedStatusLoading) {
+ actions.detectStatus()
+ }
+ },
+ })),
+ afterMount(({ actions, values, cache }) => {
+ if (cacheHasData && readCachedHasData(values.currentTeamId, productKey)) {
+ actions.setDetectedStatus('has-data')
+ // The cache skips detection, not the side effects - returning users take
+ // this path on every later visit.
+ onDetected?.('has-data')
+ return
+ }
+ // The API layer resolves the project from bootstrap state, so a check fired
+ // before that settles throws instead of answering - skip those ticks.
+ const detectIfProjectKnown = (): void => {
+ if (values.currentProjectId) {
+ actions.detectStatus()
+ }
+ }
+ detectIfProjectKnown()
+ if (pollIntervalMs) {
+ cache.disposables.add(() => {
+ const id = window.setInterval(detectIfProjectKnown, pollIntervalMs)
+ return () => clearInterval(id)
+ }, 'poll')
+ }
+ }),
+ ])
+}
diff --git a/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts b/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts
index 2c4a486d2cfc..72077122c1db 100644
--- a/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts
+++ b/frontend/src/lib/components/ProductEmptyState/setupProbes.test.ts
@@ -1,6 +1,6 @@
import { ProductKey } from '~/queries/schema/schema-general'
-import { statusFromProbeDefinitions, type ProductSetupProbe } from './setupProbes'
+import { statusFromProbeDefinitions, type ProbeEventDefinition, type ProductSetupProbe } from './setupProbes'
describe('statusFromProbeDefinitions', () => {
const probe: ProductSetupProbe = {
@@ -9,6 +9,8 @@ describe('statusFromProbeDefinitions', () => {
waitingEvents: ['$mcp_initialize'],
}
+ const fresh = (name: string): ProbeEventDefinition => ({ name, last_seen_at: new Date().toISOString() })
+
// 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.
@@ -17,7 +19,7 @@ describe('statusFromProbeDefinitions', () => {
[['$mcp_initialize'], 'waiting-for-data'],
[[], 'needs-setup'],
] as const)('maps definitions %j to %s', (definitions, expected) => {
- expect(statusFromProbeDefinitions(probe, new Set(definitions))).toBe(expected)
+ expect(statusFromProbeDefinitions(probe, definitions.map(fresh))).toBe(expected)
})
it('never reports waiting-for-data for probes without waitingEvents', () => {
@@ -25,6 +27,32 @@ describe('statusFromProbeDefinitions', () => {
productKey: ProductKey.MCP_ANALYTICS,
hasDataEvents: ['$exception'],
}
- expect(statusFromProbeDefinitions(binaryProbe, new Set(['$mcp_initialize']))).toBe('needs-setup')
+ expect(statusFromProbeDefinitions(binaryProbe, [fresh('$mcp_initialize')])).toBe('needs-setup')
+ })
+
+ // Staleness must cut both ways: a definition from a product abandoned long ago
+ // must not hide the setup screen, while an unstamped (`last_seen_at` null)
+ // definition must still count as data - it usually means the event just landed.
+ it.each([
+ ['2020-01-01T00:00:00Z', 'needs-setup'],
+ [new Date().toISOString(), 'has-data'],
+ [null, 'has-data'],
+ // Half a day past the window: whole-day rounding would still read this as fresh.
+ [new Date(Date.now() - 90.5 * 24 * 60 * 60 * 1000).toISOString(), 'needs-setup'],
+ ] as const)('with staleAfterDays, last_seen_at %s maps to %s', (lastSeenAt, expected) => {
+ const staleAwareProbe: ProductSetupProbe = {
+ productKey: ProductKey.AI_OBSERVABILITY,
+ hasDataEvents: ['$ai_generation'],
+ staleAfterDays: 90,
+ }
+ expect(
+ statusFromProbeDefinitions(staleAwareProbe, [{ name: '$ai_generation', last_seen_at: lastSeenAt }])
+ ).toBe(expected)
+ })
+
+ it('ignores last_seen_at entirely when the probe declares no staleness window', () => {
+ expect(
+ statusFromProbeDefinitions(probe, [{ name: '$mcp_tool_call', last_seen_at: '2020-01-01T00:00:00Z' }])
+ ).toBe('has-data')
})
})
diff --git a/frontend/src/lib/components/ProductEmptyState/setupProbes.ts b/frontend/src/lib/components/ProductEmptyState/setupProbes.ts
index f7b6fa67975d..e2336c326382 100644
--- a/frontend/src/lib/components/ProductEmptyState/setupProbes.ts
+++ b/frontend/src/lib/components/ProductEmptyState/setupProbes.ts
@@ -1,4 +1,5 @@
import { type FeatureFlagKey } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
import { ProductKey } from '~/queries/schema/schema-general'
@@ -22,16 +23,47 @@ export interface ProductSetupProbe {
hasDataEvents: string[]
/** Any of these existing (without `hasDataEvents`) means instrumented but no traffic yet. */
waitingEvents?: string[]
+ /**
+ * Ignore definitions whose last ingested occurrence is older than this many
+ * days, so a product that stopped sending long ago reads as needing setup
+ * again. Definitions that were never stamped (`last_seen_at` null) count as
+ * fresh. Omit to match on bare existence, for products where any history
+ * means set up. Keep in sync with the staleness window the product's own
+ * detection logic uses.
+ */
+ staleAfterDays?: number
/** Only probe when this flag is enabled. */
featureFlag?: FeatureFlagKey
}
-export function statusFromProbeDefinitions(probe: ProductSetupProbe, eventNames: Set<string>): ProductSetupStatus {
- if (probe.hasDataEvents.some((event) => eventNames.has(event))) {
+/** The slice of an event definition a probe needs to answer. */
+export interface ProbeEventDefinition {
+ name: string
+ last_seen_at?: string | null
+}
+
+export function statusFromProbeDefinitions(
+ probe: ProductSetupProbe,
+ definitions: ProbeEventDefinition[]
+): ProductSetupStatus {
+ const freshNames = new Set(
+ definitions
+ .filter(
+ (definition) =>
+ probe.staleAfterDays === undefined ||
+ !definition.last_seen_at ||
+ // Seconds, to match the `isDefinitionStale` the products themselves use:
+ // a `has-data` published here cannot be replaced by a later `needs-setup`.
+ dayjs().diff(dayjs(definition.last_seen_at), 'second') <= probe.staleAfterDays * 24 * 60 * 60
+ )
+ .map((definition) => definition.name)
+ )
+
+ if (probe.hasDataEvents.some((event) => freshNames.has(event))) {
return 'has-data'
}
- if (probe.waitingEvents?.some((event) => eventNames.has(event))) {
+ if (probe.waitingEvents?.some((event) => freshNames.has(event))) {
return 'waiting-for-data'
}
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index b84f27df386c..b67af844a329 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1667,6 +1667,11 @@ export const fileSystemTypes = {
/** This const is auto-generated, as is the whole file */
export const productSetupProbes: ProductSetupProbe[] = [
+ {
+ productKey: ProductKey.AI_OBSERVABILITY,
+ hasDataEvents: ['$ai_generation', '$ai_trace', '$ai_span', '$ai_embedding'],
+ staleAfterDays: 90,
+ },
{
productKey: ProductKey.MCP_ANALYTICS,
hasDataEvents: ['$mcp_tool_call'],
diff --git a/products/ai_observability/frontend/utils/aiEvents.ts b/products/ai_observability/frontend/utils/aiEvents.ts
index 4ab57b801eba..a6394d370bde 100644
--- a/products/ai_observability/frontend/utils/aiEvents.ts
+++ b/products/ai_observability/frontend/utils/aiEvents.ts
@@ -5,6 +5,7 @@ import { HogQLQuery, NodeKind, ProductKey } from '~/queries/schema/schema-genera
import { hogql } from '~/queries/utils'
import { EventDefinitionType } from '~/types'
+// Keep in sync with the `setupProbe` in ../../manifest.tsx (the boot-time approximation of this check).
const AI_EVENT_NAMES = ['$ai_generation', '$ai_trace', '$ai_span', '$ai_embedding']
// Use a longer staleness window than the global default so orgs that ingested AI events
diff --git a/products/ai_observability/manifest.tsx b/products/ai_observability/manifest.tsx
index d6b1560f5691..1ead1a6e9065 100644
--- a/products/ai_observability/manifest.tsx
+++ b/products/ai_observability/manifest.tsx
@@ -287,6 +287,14 @@ export const manifest: ProductManifest = {
'/llm-observability/playground': (_params, searchParams, hashParams) =>
combineUrl(urls.aiObservabilityPlayground(), searchParams, hashParams).url,
},
+ // Keep the event list and staleness window in sync with the in-scene check
+ // (`hasRecentAIEvents` in frontend/utils/aiEvents.ts) - string literals here
+ // because the probe is cloned into the eager generated products.tsx.
+ setupProbe: {
+ productKey: ProductKey.AI_OBSERVABILITY,
+ hasDataEvents: ['$ai_generation', '$ai_trace', '$ai_span', '$ai_embedding'],
+ staleAfterDays: 90,
+ },
urls: {
aiObservabilityDashboard: (): string => '/ai-observability/dashboard',
aiObservabilitySelfDriving: (): string => '/ai-observability/self-driving',