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(aio): add wizard setup empty state to AI observability scene (#77819)

Marco Gancitano238faa9283cf
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f340503eded3..88b8804e6ce8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1632,6 +1632,10 @@ snapshots:
hash: v1.k794b7964.a3e65d5201b873423bb6d077e88fcad12715ee293bdedcf5a2dc78efbc2d0cda.VSPF0yHLd7eCx-17S2ASvg21MoomuY6VOjuxq3oPQmI
components-playerinspector-itemsessionchange--session-previous--light:
hash: v1.k794b7964.33ce327f146d06d1412d431080ac84ae39558411b2073fe18a2ed98d834a2681.FDbDlC4-qfrH2RR1F_KpijnZNM9Ss_4s-p19Ee8fGtY
+ components-product-empty-state--ai-observability-needs-setup--dark:
+ hash: v1.k794b7964.f10735d00b8b7484f071fdcaebec654ef0042bf7894e374cbe077acb88d1de1f.DVP2UF6lwJvd5PyN12NBZIhS9EOv5z-N0T-aYKrAONw
+ components-product-empty-state--ai-observability-needs-setup--light:
+ hash: v1.k794b7964.356081f2e978bf91130ebf0aa39fdc921a169780d2c3b9e289191d40dc73f6f1.nOlwt03p_7y2o0g2xV7835qBylZDe7uIdPxowxXI8mA
components-product-empty-state--empty-no-action--dark:
hash: v1.k794b7964.01f56e9e0d751a5c0fd6cd2adee993fd8d3b1edce8c3db666da93336ca655590.zbVyer02lJY_tFXGrLIB2hZO_hwO2JxrCpe-IqphV4U
components-product-empty-state--empty-no-action--light:
diff --git a/frontend/src/lib/components/CommandBlock/TerminalCard.tsx b/frontend/src/lib/components/CommandBlock/TerminalCard.tsx
index afff24210323..6be92da9d4be 100644
--- a/frontend/src/lib/components/CommandBlock/TerminalCard.tsx
+++ b/frontend/src/lib/components/CommandBlock/TerminalCard.tsx
@@ -17,6 +17,8 @@ interface TerminalCardProps {
command: string
/** Label passed to the copy-to-clipboard toast (e.g. "MCP wizard command"). */
copyLabel: string
+ /** Called after the command is copied, e.g. to capture an analytics event. */
+ onCopy?: () => void
className?: string
}
@@ -29,7 +31,7 @@ interface TerminalCardProps {
* 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 {
+export function TerminalCard({ command, copyLabel, onCopy, className }: TerminalCardProps): JSX.Element {
const [copied, setCopied] = useState(false)
// Freeze the typewriter in storybook so visual snapshots are deterministic.
@@ -39,9 +41,13 @@ export function TerminalCard({ command, copyLabel, className }: TerminalCardProp
const displayCommand = condenseCommand(command)
const handleCopy = (): void => {
- void copyToClipboard(command, copyLabel)
- setCopied(true)
- window.setTimeout(() => setCopied(false), COPIED_RESET_MS)
+ void copyToClipboard(command, copyLabel).then((copied) => {
+ if (copied) {
+ onCopy?.()
+ setCopied(true)
+ window.setTimeout(() => setCopied(false), COPIED_RESET_MS)
+ }
+ })
}
return (
diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
index f71968c4554e..73258b4c4af7 100644
--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.stories.tsx
@@ -2,6 +2,7 @@ import { Meta } from '@storybook/react'
import type { Mocks } from '~/mocks/utils'
+import { aiObservabilityEmptyState } from 'products/ai_observability/frontend/emptyState/aiObservabilityEmptyState'
import { mcpAnalyticsEmptyState } from 'products/mcp_analytics/frontend/emptyState/mcpAnalyticsEmptyState'
import { ProductEmptyState } from './ProductEmptyState'
@@ -52,3 +53,9 @@ export const MCPAnalyticsWithoutWizard: ProductEmptyStateStory = productEmptySta
'needs-setup',
{ config: { wizard: undefined }, mocks: mcpSignalMocks(false) }
)
+
+// AI observability detection is binary (no waiting-for-data middle state).
+export const AIObservabilityNeedsSetup: ProductEmptyStateStory = productEmptyStateStory(
+ aiObservabilityEmptyState,
+ 'needs-setup'
+)
diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx
index 31609de63358..ae944394ee47 100644
--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx
+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyState.tsx
@@ -1,4 +1,5 @@
import { useActions } from 'kea'
+import posthog from 'posthog-js'
import { IconBook, IconGear } from '@posthog/icons'
@@ -28,6 +29,10 @@ export function ProductEmptyState({ config, mode }: ProductEmptyStateProps): JSX
})
const { skipEmptyState } = useActions(productSetupStatusLogic({ productKey: config.productKey }))
+ const captureClick = (action: string): void => {
+ posthog.capture(`product empty state ${action}`, { product_key: config.productKey, mode })
+ }
+
// Mode-specific text overrides the base; missing fields fall back to it.
const text: ProductEmptyStateText = { ...config.text['needs-setup'], ...config.text[mode] }
@@ -65,18 +70,33 @@ export function ProductEmptyState({ config, mode }: ProductEmptyStateProps): JSX
{text.hint ? <div className="text-xs text-tertiary mt-2">{text.hint}</div> : null}
{showWizard ? (
- <TerminalCard command={wizardCommand} copyLabel={`${config.productName} wizard command`} />
+ <TerminalCard
+ command={wizardCommand}
+ copyLabel={`${config.productName} wizard command`}
+ onCopy={() => captureClick('wizard command copied')}
+ />
) : config.primaryAction ? (
<LemonButton
type="primary"
to={config.primaryAction.to}
- onClick={config.primaryAction.onClick}
+ onClick={() => {
+ captureClick('primary action clicked')
+ config.primaryAction?.onClick?.()
+ }}
className="self-start"
+ data-attr="product-empty-state-primary-action"
>
{config.primaryAction.label}
</LemonButton>
) : manualUrl ? (
- <LemonButton type="primary" to={manualUrl} targetBlank className="self-start">
+ <LemonButton
+ type="primary"
+ to={manualUrl}
+ targetBlank
+ className="self-start"
+ onClick={() => captureClick('manual setup clicked')}
+ data-attr="product-empty-state-manual-setup"
+ >
Set up {config.productName}
</LemonButton>
) : null}
@@ -85,16 +105,36 @@ export function ProductEmptyState({ config, mode }: ProductEmptyStateProps): JSX
<div className="flex items-center gap-4">
{showWizard && manualUrl ? (
- <LemonButton type="secondary" icon={<IconGear />} to={manualUrl} targetBlank>
+ <LemonButton
+ type="secondary"
+ icon={<IconGear />}
+ to={manualUrl}
+ targetBlank
+ onClick={() => captureClick('manual setup clicked')}
+ data-attr="product-empty-state-manual-setup"
+ >
Configure manually
</LemonButton>
) : null}
{config.docsUrl ? (
- <LemonButton size="xsmall" type="tertiary" icon={<IconBook />} to={config.docsUrl} targetBlank>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ icon={<IconBook />}
+ to={config.docsUrl}
+ targetBlank
+ onClick={() => captureClick('docs clicked')}
+ data-attr="product-empty-state-docs"
+ >
Read the docs
</LemonButton>
) : null}
- <LemonButton size="xsmall" type="tertiary" onClick={skipEmptyState}>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ onClick={skipEmptyState}
+ data-attr="product-empty-state-skip"
+ >
Skip for now
</LemonButton>
</div>
diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.tsx
index 8d096a7a34dd..cbcb4c3b5ca1 100644
--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.tsx
+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.tsx
@@ -54,7 +54,14 @@ function ProductEmptyStateGateInner({ emptyState, children }: ProductEmptyStateG
// 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 }}>
+ <LemonBanner
+ type="info"
+ action={{
+ children: `Set up ${config.productName}`,
+ onClick: unskipEmptyState,
+ 'data-attr': 'product-empty-state-setup-banner',
+ }}
+ >
{config.productName} isn't receiving data yet.
</LemonBanner>
) : null
diff --git a/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.ts b/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.ts
index a481b2834c9a..bb467f62aef1 100644
--- a/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.ts
+++ b/frontend/src/lib/components/ProductEmptyState/productSetupStatusLogic.ts
@@ -1,4 +1,5 @@
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
import { teamLogic } from 'scenes/teamLogic'
@@ -148,16 +149,18 @@ export const productSetupStatusLogic = kea<productSetupStatusLogicType>([
status === 'waiting-for-data' ? 'waiting-for-data' : 'needs-setup',
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, props }) => ({
setDetectedStatus: ({ status }) => {
actions.applyDetectedStatus(status, values.currentTeamId)
},
skipEmptyState: () => {
+ posthog.capture('product empty state skipped', { product_key: props.productKey })
if (values.currentTeamId) {
actions.setSkippedForTeam(values.currentTeamId, true)
}
},
unskipEmptyState: () => {
+ posthog.capture('product empty state setup resumed', { product_key: props.productKey })
if (values.currentTeamId) {
actions.setSkippedForTeam(values.currentTeamId, false)
}
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeLLMTrace.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLLMTrace.tsx
index cadb5726498f..b0212a2e54fd 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeLLMTrace.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeLLMTrace.tsx
@@ -17,7 +17,6 @@ import { Query } from '~/queries/Query/Query'
import { TracesQuery } from '~/queries/schema/schema-general'
import { isTracesQuery } from '~/queries/utils'
-import { AIObservabilitySetupPrompt } from 'products/ai_observability/frontend/AIObservabilitySetupPrompt'
import { aiObservabilitySharedLogic } from 'products/ai_observability/frontend/aiObservabilitySharedLogic'
import { useTracesQueryContext } from 'products/ai_observability/frontend/AIObservabilityTracesScene'
import { aiObservabilityTracesTabLogic } from 'products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic'
@@ -58,36 +57,34 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeLLMTraceAttribu
return (
<BindLogic logic={dataNodeLogic} props={{ key: logicKey }}>
- <AIObservabilitySetupPrompt className="border-none" thing="trace">
- <Query
- uniqueKey={logicKey}
- attachTo={notebookLogic}
- query={{
- ...tracesQuery,
- source: {
- ...tracesQuery.source,
- tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
- },
- embedded: true,
- showTestAccountFilters: false,
- showReload: false,
- showExport: false,
- showDateRange: false,
- showPropertyFilter: false,
- showTimings: false,
- }}
- context={context}
- setQuery={(query) => {
- if (!isTracesQuery(query.source)) {
- throw new Error('Invalid query')
- }
- setDates(query.source.dateRange?.date_from || null, query.source.dateRange?.date_to || null)
- setShouldFilterTestAccounts(query.source.filterTestAccounts || false)
- setPropertyFilters(query.source.properties || [])
- setTracesQuery(query)
- }}
- />
- </AIObservabilitySetupPrompt>
+ <Query
+ uniqueKey={logicKey}
+ attachTo={notebookLogic}
+ query={{
+ ...tracesQuery,
+ source: {
+ ...tracesQuery.source,
+ tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ embedded: true,
+ showTestAccountFilters: false,
+ showReload: false,
+ showExport: false,
+ showDateRange: false,
+ showPropertyFilter: false,
+ showTimings: false,
+ }}
+ context={context}
+ setQuery={(query) => {
+ if (!isTracesQuery(query.source)) {
+ throw new Error('Invalid query')
+ }
+ setDates(query.source.dateRange?.date_from || null, query.source.dateRange?.date_to || null)
+ setShouldFilterTestAccounts(query.source.filterTestAccounts || false)
+ setPropertyFilters(query.source.properties || [])
+ setTracesQuery(query)
+ }}
+ />
</BindLogic>
)
}
diff --git a/frontend/src/styles/base.scss b/frontend/src/styles/base.scss
index f1e5c566e864..110cf78eff63 100644
--- a/frontend/src/styles/base.scss
+++ b/frontend/src/styles/base.scss
@@ -331,6 +331,7 @@
--color-product-surveys-light: rgb(243 84 84);
--color-product-data-warehouse-light: rgb(133 103 255);
--color-product-llm-analytics-light: rgb(182 42 217);
+ --color-product-llm-analytics-dark: rgb(212 106 240);
--color-product-llm-clusters-light: rgb(147 51 234);
--color-product-llm-datasets-light: rgb(124 58 237);
--color-product-llm-evaluations-light: rgb(167 139 250);
diff --git a/products/ai_observability/frontend/AIObservabilityScene.tsx b/products/ai_observability/frontend/AIObservabilityScene.tsx
index 401aeea9a113..d27aaabe6c67 100644
--- a/products/ai_observability/frontend/AIObservabilityScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityScene.tsx
@@ -36,7 +36,6 @@ import { AIObservabilityDigestScoutButton } from './AIObservabilityDigestScoutBu
import { AIObservabilityErrors } from './AIObservabilityErrors'
import { AIObservabilityReloadAction } from './AIObservabilityReloadAction'
import { AIObservabilitySessionsPlaylist } from './AIObservabilitySessionsPlaylist'
-import { AIObservabilitySetupPrompt } from './AIObservabilitySetupPrompt'
import {
buildApplyUrlStatePayload,
AI_OBSERVABILITY_DATA_COLLECTION_NODE_ID,
@@ -45,6 +44,7 @@ import {
import { AIObservabilityTools } from './AIObservabilityTools'
import { AIObservabilityTraces } from './AIObservabilityTracesScene'
import { AIObservabilityUsers } from './AIObservabilityUsers'
+import { aiObservabilityEmptyState } from './emptyState/aiObservabilityEmptyState'
import { useSortableColumns } from './hooks/useSortableColumns'
import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'
import { GENERATION_SENTIMENT_SELECT } from './sentimentResults'
@@ -64,6 +64,7 @@ export const scene: SceneExport = {
component: AIObservabilityScene,
logic: aiObservabilitySharedLogic,
productKey: ProductKey.AI_OBSERVABILITY,
+ emptyState: aiObservabilityEmptyState,
}
const Filters = ({ hidePropertyFilters = false }: { hidePropertyFilters?: boolean }): JSX.Element => {
@@ -158,23 +159,21 @@ function AIObservabilityDashboard(): JSX.Element {
}, [currentExternalFilters, nextExternalFilters, selectedDashboardId, setExternalFilters])
return (
- <AIObservabilitySetupPrompt>
- <div className="@container/dashboard" data-attr="llm-analytics-costs">
- <Filters />
-
- {availableDashboardsLoading || !selectedDashboardId ? (
- <div className="text-center p-8">
- <Spinner captureTime />
- </div>
- ) : (
- <Dashboard
- id={selectedDashboardId.toString()}
- placement={DashboardPlacement.Builtin}
- showCreateAnomalyAlertButton
- />
- )}
- </div>
- </AIObservabilitySetupPrompt>
+ <div className="@container/dashboard" data-attr="llm-analytics-costs">
+ <Filters />
+
+ {availableDashboardsLoading || !selectedDashboardId ? (
+ <div className="text-center p-8">
+ <Spinner captureTime />
+ </div>
+ ) : (
+ <Dashboard
+ id={selectedDashboardId.toString()}
+ placement={DashboardPlacement.Builtin}
+ showCreateAnomalyAlertButton
+ />
+ )}
+ </div>
)
}
@@ -509,33 +508,21 @@ function AIObservabilitySceneContent(): JSX.Element {
{
key: 'traces',
label: 'Traces',
- content: (
- <AIObservabilitySetupPrompt thing="trace">
- <AIObservabilityTraces />
- </AIObservabilitySetupPrompt>
- ),
+ content: <AIObservabilityTraces />,
link: combineUrl(urls.aiObservabilityTraces(), searchParams).url,
'data-attr': 'traces-tab',
},
{
key: 'generations',
label: 'Generations',
- content: (
- <AIObservabilitySetupPrompt>
- <AIObservabilityGenerations />
- </AIObservabilitySetupPrompt>
- ),
+ content: <AIObservabilityGenerations />,
link: combineUrl(urls.aiObservabilityGenerations(), searchParams).url,
'data-attr': 'generations-tab',
},
{
key: 'users',
label: 'Users',
- content: (
- <AIObservabilitySetupPrompt>
- <AIObservabilityUsers />
- </AIObservabilitySetupPrompt>
- ),
+ content: <AIObservabilityUsers />,
link: combineUrl(urls.aiObservabilityUsers(), searchParams).url,
'data-attr': 'users-tab',
},
@@ -544,11 +531,7 @@ function AIObservabilitySceneContent(): JSX.Element {
tabs.push({
key: 'errors',
label: 'Errors',
- content: (
- <AIObservabilitySetupPrompt>
- <AIObservabilityErrors />
- </AIObservabilitySetupPrompt>
- ),
+ content: <AIObservabilityErrors />,
link: combineUrl(urls.aiObservabilityErrors(), searchParams).url,
'data-attr': 'errors-tab',
})
@@ -556,11 +539,7 @@ function AIObservabilitySceneContent(): JSX.Element {
tabs.push({
key: 'tools',
label: 'Tools',
- content: (
- <AIObservabilitySetupPrompt>
- <AIObservabilityTools />
- </AIObservabilitySetupPrompt>
- ),
+ content: <AIObservabilityTools />,
link: combineUrl(urls.aiObservabilityTools(), searchParams).url,
'data-attr': 'tools-tab',
})
@@ -569,10 +548,10 @@ function AIObservabilitySceneContent(): JSX.Element {
key: 'sentiment',
label: 'Sentiment',
content: (
- <AIObservabilitySetupPrompt>
+ <>
<Filters />
<AIObservabilitySentiment />
- </AIObservabilitySetupPrompt>
+ </>
),
link: combineUrl(urls.aiObservabilitySentiment(), searchParams).url,
'data-attr': 'llma-sentiment-tab',
@@ -582,10 +561,10 @@ function AIObservabilitySceneContent(): JSX.Element {
key: 'sessions',
label: 'Sessions',
content: (
- <AIObservabilitySetupPrompt>
+ <>
<Filters />
<AIObservabilitySessionsPlaylist />
- </AIObservabilitySetupPrompt>
+ </>
),
link: combineUrl(urls.aiObservabilitySessions(), searchParams).url,
'data-attr': 'sessions-tab',
@@ -594,11 +573,7 @@ function AIObservabilitySceneContent(): JSX.Element {
tabs.push({
key: 'reviews',
label: 'Reviews',
- content: (
- <AIObservabilitySetupPrompt thing="trace">
- <AIObservabilityHumanReviews />
- </AIObservabilitySetupPrompt>
- ),
+ content: <AIObservabilityHumanReviews />,
link: combineUrl(urls.aiObservabilityReviews(), searchParams).url,
'data-attr': 'llma-reviews-tab',
})
diff --git a/products/ai_observability/frontend/AIObservabilitySetupPrompt.tsx b/products/ai_observability/frontend/AIObservabilitySetupPrompt.tsx
deleted file mode 100644
index 7be883d50713..000000000000
--- a/products/ai_observability/frontend/AIObservabilitySetupPrompt.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useValues } from 'kea'
-
-import { Spinner } from '@posthog/lemon-ui'
-
-import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
-
-import { ProductKey } from '~/queries/schema/schema-general'
-
-import { aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
-
-type Thing = 'generation' | 'trace'
-
-export function AIObservabilitySetupPrompt({
- children,
- className,
- thing = 'generation',
-}: {
- children: React.ReactNode
- thing?: Thing
- className?: string
-}): JSX.Element {
- const { hasSentAiEvent, hasSentAiEventLoading } = useValues(aiObservabilitySharedLogic)
-
- return hasSentAiEventLoading ? (
- <div className="flex justify-center">
- <Spinner />
- </div>
- ) : !hasSentAiEvent ? (
- <IngestionStatusCheck className={className} thing={thing} />
- ) : (
- <>{children}</>
- )
-}
-
-function IngestionStatusCheck({ className, thing }: { className?: string; thing: Thing }): JSX.Element {
- return (
- <ProductIntroduction
- productName="AI observability"
- thingName={`LLM ${thing}`}
- titleOverride={`No LLM ${thing} events have been detected!`}
- description="To use AI observability, please instrument your LLM calls with the PostHog SDK."
- isEmpty={true}
- productKey={ProductKey.AI_OBSERVABILITY}
- className={className}
- docsURL="https://posthog.com/docs/ai-observability/installation"
- />
- )
-}
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts
index a9142158e1a3..eb1dbaf3a3b3 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts
@@ -1,69 +1,126 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
-import { buildApplyUrlStatePayload } from './aiObservabilitySharedLogic'
+import { aiObservabilitySharedLogic, buildApplyUrlStatePayload } from './aiObservabilitySharedLogic'
+import { hasRecentAIEvents } from './utils/aiEvents'
+
+jest.mock('lib/api')
+jest.mock('./utils/aiEvents')
+
+const mockHasRecentAIEvents = hasRecentAIEvents as jest.MockedFunction<typeof hasRecentAIEvents>
-describe('buildApplyUrlStatePayload', () => {
- const currentDateFilter = { dateFrom: '-1h', dateTo: null as string | null }
- const currentPropertyFilters: AnyPropertyFilter[] = []
+describe('aiObservabilitySharedLogic', () => {
+ describe('buildApplyUrlStatePayload', () => {
+ const currentDateFilter = { dateFrom: '-1h', dateTo: null as string | null }
+ const currentPropertyFilters: AnyPropertyFilter[] = []
- it.each([
- { desc: 'dateFrom differs', dateFrom: '-7d', dateTo: null as string | null, expected: true },
- { desc: 'dateTo differs', dateFrom: '-1h', dateTo: '2026-04-01', expected: true },
- { desc: 'both match current', dateFrom: '-1h', dateTo: null as string | null, expected: false },
- ])('flags datesChanged=$expected when $desc', ({ dateFrom, dateTo, expected }) => {
- const payload = buildApplyUrlStatePayload({
- dateFrom,
- dateTo,
- shouldFilterTestAccounts: false,
- propertyFilters: [],
- currentDateFilter,
- currentPropertyFilters,
+ it.each([
+ { desc: 'dateFrom differs', dateFrom: '-7d', dateTo: null as string | null, expected: true },
+ { desc: 'dateTo differs', dateFrom: '-1h', dateTo: '2026-04-01', expected: true },
+ { desc: 'both match current', dateFrom: '-1h', dateTo: null as string | null, expected: false },
+ ])('flags datesChanged=$expected when $desc', ({ dateFrom, dateTo, expected }) => {
+ const payload = buildApplyUrlStatePayload({
+ dateFrom,
+ dateTo,
+ shouldFilterTestAccounts: false,
+ propertyFilters: [],
+ currentDateFilter,
+ currentPropertyFilters,
+ })
+ expect(payload.datesChanged).toBe(expected)
+ })
+
+ const modelFilter: AnyPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$ai_model',
+ operator: PropertyOperator.Exact,
+ value: ['gpt-4o'],
+ }
+ it.each([
+ {
+ desc: 'contents equal — returns current reference',
+ current: [modelFilter],
+ next: [{ ...modelFilter }],
+ expectCurrentRef: true,
+ },
+ {
+ desc: 'contents differ — returns next reference',
+ current: [] as AnyPropertyFilter[],
+ next: [modelFilter],
+ expectCurrentRef: false,
+ },
+ ])('propertyFilters: $desc', ({ current, next, expectCurrentRef }) => {
+ const payload = buildApplyUrlStatePayload({
+ dateFrom: '-1h',
+ dateTo: null,
+ shouldFilterTestAccounts: false,
+ propertyFilters: next,
+ currentDateFilter,
+ currentPropertyFilters: current,
+ })
+ expect(payload.propertyFilters).toBe(expectCurrentRef ? current : next)
})
- expect(payload.datesChanged).toBe(expected)
- })
- const modelFilter: AnyPropertyFilter = {
- type: PropertyFilterType.Event,
- key: '$ai_model',
- operator: PropertyOperator.Exact,
- value: ['gpt-4o'],
- }
- it.each([
- {
- desc: 'contents equal — returns current reference',
- current: [modelFilter],
- next: [{ ...modelFilter }],
- expectCurrentRef: true,
- },
- {
- desc: 'contents differ — returns next reference',
- current: [] as AnyPropertyFilter[],
- next: [modelFilter],
- expectCurrentRef: false,
- },
- ])('propertyFilters: $desc', ({ current, next, expectCurrentRef }) => {
- const payload = buildApplyUrlStatePayload({
- dateFrom: '-1h',
- dateTo: null,
- shouldFilterTestAccounts: false,
- propertyFilters: next,
- currentDateFilter,
- currentPropertyFilters: current,
+ it('passes through shouldFilterTestAccounts and date values unchanged', () => {
+ const payload = buildApplyUrlStatePayload({
+ dateFrom: '-30d',
+ dateTo: '-1d',
+ shouldFilterTestAccounts: true,
+ propertyFilters: [],
+ currentDateFilter,
+ currentPropertyFilters,
+ })
+ expect(payload.dateFrom).toBe('-30d')
+ expect(payload.dateTo).toBe('-1d')
+ expect(payload.shouldFilterTestAccounts).toBe(true)
})
- expect(payload.propertyFilters).toBe(expectCurrentRef ? current : next)
})
- it('passes through shouldFilterTestAccounts and date values unchanged', () => {
- const payload = buildApplyUrlStatePayload({
- dateFrom: '-30d',
- dateTo: '-1d',
- shouldFilterTestAccounts: true,
- propertyFilters: [],
- currentDateFilter,
- currentPropertyFilters,
+ // Guards the connect + mapping into the app-wide setup-status layer: if either
+ // breaks, the scene empty-state gate strands users on its spinner, or shows the
+ // setup screen to teams that already have AI events.
+ describe('setup status detection', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ initKeaTests()
+ })
+
+ it.each([
+ [true, 'has-data'],
+ [false, 'needs-setup'],
+ ])('pushes hasSentAiEvent=%s into productSetupStatusLogic as %s', async (hasEvents, expected) => {
+ mockHasRecentAIEvents.mockResolvedValue(hasEvents)
+ const logic = aiObservabilitySharedLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }).values.status).toBe(expected)
+ })
+
+ // Guards the fail-open path: a persistently failing detection query must
+ // publish `unknown` (gate renders the scene), not leave the gate on its
+ // spinner forever.
+ it('publishes unknown when detection fails before any answer exists', async () => {
+ mockHasRecentAIEvents.mockRejectedValue(new Error('query failed'))
+ const logic = aiObservabilitySharedLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }).values.status).toBe('unknown')
+ })
+
+ it('a failing re-check never downgrades an existing answer', async () => {
+ mockHasRecentAIEvents.mockResolvedValue(true)
+ const logic = aiObservabilitySharedLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ mockHasRecentAIEvents.mockRejectedValue(new Error('query failed'))
+ logic.actions.loadAIEventDefinition()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }).values.status).toBe('has-data')
})
- expect(payload.dateFrom).toBe('-30d')
- expect(payload.dateTo).toBe('-1d')
- expect(payload.shouldFilterTestAccounts).toBe(true)
})
})
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
index 9341ea3aaa95..5ab5f513d9b8 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
@@ -15,6 +15,8 @@ import {
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
+import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
@@ -70,6 +72,9 @@ export interface SortState {
direction: SortDirection
}
+// Cadence of the setup-detection re-check while the team has no AI events yet.
+const SETUP_POLL_INTERVAL_MS = 20000
+
const INITIAL_DASHBOARD_DATE_FROM = '-7d' as string | null
const INITIAL_EVENTS_DATE_FROM = '-1h' as string | null
const INITIAL_DATE_TO = null as string | null
@@ -133,6 +138,7 @@ export function buildApplyUrlStatePayload({
export interface aiObservabilitySharedLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
filterTestAccountsDefault: boolean // filterTestAccountsDefaultsLogic
+ setupStatus: ProductSetupStatus // productSetupStatusLogic
sceneKey: string | null // sceneLogic
user: UserType | null // userLogic
activeTab: AIObservabilityTabId
@@ -158,6 +164,9 @@ export interface aiObservabilitySharedLogicActions {
setLocalDefault: (value: boolean) => {
value: boolean
} // filterTestAccountsDefaultsLogic
+ setDetectedStatus: (status: ProductSetupStatus) => {
+ status: ProductSetupStatus
+ } // productSetupStatusLogic
addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
applyUrlState: (state: ApplyUrlStatePayload) => ApplyUrlStatePayload
loadAIEventDefinition: () => any
@@ -228,8 +237,17 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
['user'],
filterTestAccountsDefaultsLogic,
['filterTestAccountsDefault'],
+ productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }),
+ ['status as setupStatus'],
+ ],
+ actions: [
+ teamLogic,
+ ['addProductIntent'],
+ filterTestAccountsDefaultsLogic,
+ ['setLocalDefault'],
+ productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }),
+ ['setDetectedStatus'],
],
- actions: [teamLogic, ['addProductIntent'], filterTestAccountsDefaultsLogic, ['setLocalDefault']],
})),
actions({
@@ -309,12 +327,24 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
},
})),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
loadAIEventDefinitionSuccess: ({ hasSentAiEvent }) => {
+ // Feed the app-wide setup-status layer (drives the scene empty-state gate).
+ actions.setDetectedStatus(hasSentAiEvent ? 'has-data' : 'needs-setup')
if (hasSentAiEvent) {
+ cache.disposables.dispose('setupPoll')
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.IngestFirstLlmEvent)
}
},
+ loadAIEventDefinitionFailure: () => {
+ // A failing detection 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. A failure never
+ // downgrades an existing answer.
+ if (values.setupStatus === 'loading') {
+ actions.setDetectedStatus('unknown')
+ }
+ },
setShouldFilterTestAccounts: ({ shouldFilterTestAccounts }) => {
const divergesFromEffectiveDefault = shouldFilterTestAccounts !== values.filterTestAccountsDefault
if (divergesFromEffectiveDefault) {
@@ -525,8 +555,15 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
}
}),
- afterMount(({ actions, values }) => {
+ afterMount(({ actions, values, cache }) => {
actions.loadAIEventDefinition()
+ // While the empty state (or its post-skip reminder banner) is up, re-check on a
+ // timer so the page flips to the real product on its own once events land.
+ // Disposed as soon as data is detected; paused automatically on hidden tabs.
+ cache.disposables.add(() => {
+ const id = window.setInterval(() => actions.loadAIEventDefinition(), SETUP_POLL_INTERVAL_MS)
+ return () => clearInterval(id)
+ }, 'setupPoll')
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.TrackCosts)
const urlHasTestAccountsParam = 'filter_test_accounts' in router.values.searchParams
diff --git a/products/ai_observability/frontend/emptyState/AIObservabilityTracePreview.tsx b/products/ai_observability/frontend/emptyState/AIObservabilityTracePreview.tsx
new file mode 100644
index 000000000000..d463bf5fbcf1
--- /dev/null
+++ b/products/ai_observability/frontend/emptyState/AIObservabilityTracePreview.tsx
@@ -0,0 +1,123 @@
+import type { ProductEmptyStateMode } from 'lib/components/ProductEmptyState/types'
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+
+import slackLogo from 'public/services/slack.png'
+
+interface PreviewSession {
+ user: string
+ title: string
+ generations: string
+ duration: string
+ negative?: boolean
+}
+
+// Example sessions - hand-authored, not real data. Shaped like the sessions tab:
+// the person, what they were doing, and how the session went.
+const SESSIONS: PreviewSession[] = [
+ { user: 'sofia', title: 'Draft onboarding email', generations: '14 gens', duration: '6m' },
+ { user: 'liam', title: 'Debug a failing SQL query', generations: '9 gens', duration: '3m' },
+ { user: 'ava', title: 'Cancel subscription flow', generations: '21 gens', duration: '11m', negative: true },
+ { user: 'noah', title: 'Summarize meeting notes', generations: '5 gens', duration: '2m' },
+ { user: 'mia', title: 'Translate product docs', generations: '7 gens', duration: '4m' },
+]
+
+// A hand-authored series for the sparkline - flat baseline with a spike at the end,
+// matching the "negative sentiment spiked" alert below it.
+const SPARK = [3, 4, 3, 3, 4, 3, 4, 3, 4, 6, 10, 15]
+
+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 AI observability empty state: a sessions list plus
+ * a negative-sentiment tile with its Slack alert - static rows, no timers, per the
+ * preview rules in the `building-product-empty-states` skill.
+ */
+export function AIObservabilityTracePreview({ mode }: { mode: ProductEmptyStateMode }): JSX.Element {
+ const { line, area } = sparkPaths()
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="rounded-md border border-primary bg-surface-primary p-3">
+ <div className="mb-2 flex items-center justify-between">
+ <span className="text-xs font-semibold">Sessions</span>
+ <LemonTag size="small">example data</LemonTag>
+ </div>
+
+ {mode === 'waiting-for-data' ? (
+ <div className="mb-1 flex items-center gap-2 rounded border border-dashed border-primary px-2 py-1.5 text-xs text-secondary">
+ <Spinner className="text-sm" />
+ Listening for your first generation…
+ </div>
+ ) : null}
+
+ <div className="flex flex-col">
+ {SESSIONS.map((session, i) => (
+ <div
+ key={i}
+ className="flex items-center gap-2 border-b border-primary px-1 py-1.5 text-xs last:border-b-0"
+ >
+ <span className="w-9 shrink-0 text-secondary">{session.user}</span>
+ <span className="min-w-0 truncate font-medium">{session.title}</span>
+ {session.negative ? (
+ <LemonTag size="small" type="danger">
+ negative
+ </LemonTag>
+ ) : null}
+ <span className="ml-auto shrink-0 text-secondary">{session.generations}</span>
+ <span className="w-7 shrink-0 text-right text-secondary tabular-nums">
+ {session.duration}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="rounded-md border border-primary bg-surface-primary p-3">
+ <div className="mb-1 flex items-center justify-between">
+ <span className="text-xs font-semibold">Negative sentiment · 7 days</span>
+ <LemonTag size="small">example data</LemonTag>
+ </div>
+
+ <div className="mb-2 text-2xl font-bold tabular-nums">
+ 4.6%
+ <span className="ml-2 align-middle text-xs font-semibold text-danger">▲ spiking</span>
+ </div>
+
+ <div className="text-danger">
+ <svg className="h-10 w-full" viewBox="0 0 100 40" preserveAspectRatio="none" aria-hidden="true">
+ <path d={area} fill="currentColor" opacity={0.12} />
+ <path
+ d={line}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ vectorEffect="non-scaling-stroke"
+ />
+ </svg>
+ </div>
+
+ <div className="mt-2 flex items-center gap-2 rounded border border-primary px-2 py-1.5 text-xs text-secondary">
+ <img src={slackLogo} alt="" className="size-4 shrink-0" />
+ <span className="min-w-0 truncate">
+ Alert sent to <span className="font-semibold text-primary">#ai-quality</span>: negative
+ sentiment spiked
+ </span>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/emptyState/aiObservabilityEmptyState.tsx b/products/ai_observability/frontend/emptyState/aiObservabilityEmptyState.tsx
new file mode 100644
index 000000000000..e8c1728995bf
--- /dev/null
+++ b/products/ai_observability/frontend/emptyState/aiObservabilityEmptyState.tsx
@@ -0,0 +1,36 @@
+import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'
+import { IconLlmAnalytics } from '@posthog/icons'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import type { SceneProductEmptyState } from 'lib/components/ProductEmptyState/types'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+
+import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
+import { AIObservabilityTracePreview } from './AIObservabilityTracePreview'
+
+const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
+
+export const aiObservabilityEmptyState: SceneProductEmptyState = {
+ statusLogic: aiObservabilitySharedLogic,
+ config: {
+ productKey: ProductKey.AI_OBSERVABILITY,
+ productName: 'AI observability',
+ icon: <IconLlmAnalytics />,
+ accentColor: 'var(--color-product-llm-analytics-light)',
+ accentColorDark: 'var(--color-product-llm-analytics-dark)',
+ hedgehog: HedgehogMagnifyingGlass,
+ text: {
+ 'needs-setup': {
+ headline: 'See how your AI is doing in the wild',
+ lead: "Capture LLM sessions in full detail. See how it's being used, catch errors and regressions in real-time, and get alerted when they happen.",
+ hint: 'Point the wizard at your project root. Setup costs are on us, no API key needed:',
+ },
+ },
+ wizard: { slug: 'ai-observability', pinProjectId: true },
+ docsUrl: 'https://posthog.com/docs/ai-observability',
+ manualSetupUrl: 'https://posthog.com/docs/ai-observability/installation',
+ previewLabel: 'Sessions, once connected',
+ Preview: AIObservabilityTracePreview,
+ },
+}