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(insights): show sample data placeholder before first event ingestion (#68089)

Rafael Audibert063e0c5b143d
diff --git a/AGENTS.md b/AGENTS.md
index d807ad5547d1..4d49e3dac555 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,9 @@
# PostHog Development Guide
+## General guidelines
+
+- Avoid em-dashes like the plague
+
## Codebase Structure
- Key entry points: `posthog/api/__init__.py` (API URL routing skeleton; products register their own routes in `products/<name>/backend/routes.py` via `register_routes(routers)`), `posthog/settings/web.py` (Django settings, INSTALLED_APPS), `products/` (product apps)
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ce6f66ffc684..b24c6aa88a09 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1616,6 +1616,18 @@ snapshots:
hash: v1.k794b7964.9102895f346542d04ab3e70fb185e6cf65e0e78364fa376f3b3cd5a363e3133b.vyjJAwjlwiK3dn068o1HgwrsjI-x5pFkCKt3AwYimN0
components-property-key-info--property-key-info--light:
hash: v1.k794b7964.2f0245e1b92aba6695884bdf695034bf1efd85caca619940965a08338f15e41c.5Z7YHy2M9ko_15_blb0NaI7WmQeXytUWAntBAs03Qr0
+ components-sample-data-state--all-variants--dark:
+ hash: v1.k794b7964.f07ee511a2c77a4ff5a2ed0ca5030e3e57656ade775012ea85bd9c5047f29d3f.297btInaIUjNnmRtmJbS5ZyTmlux9j6wO8NlDAevNzo
+ components-sample-data-state--all-variants--light:
+ hash: v1.k794b7964.ebd4fc5add8fbb45cfe382af5aa48568c9f094574ab6e2088566a75bd3e1762a.a_1stky_5F9h4knpDr1JpdwhATEe7sdMLbVhOdHrkok
+ components-sample-data-state--with-setup-pull-request--dark:
+ hash: v1.k794b7964.a7647c826dc90cc8f49595664f6da4e08b6a623c018b67413168e7a423ea4e5b.zYzBM5U_KBYjVXH7MR_BUlxgJuH6t6IMTcDtgmwn_rQ
+ components-sample-data-state--with-setup-pull-request--light:
+ hash: v1.k794b7964.c999858750e590d7e4f9a824e9c4284cdec860e01740c3a55e3da95e07ac0b3b.sQkDf-suJjVk-MAuh_TLKI14oh4mQH5jnHRjFTCV6wM
+ components-sample-data-state--wizard-installing--dark:
+ hash: v1.k794b7964.5f13bf50d33b9d3257d8a93eea04dc06edfc31a86ac947e74fc7f32ff23750da.vV-ots4x1jS78n1arxGnPxkVZ2x3hiQSekk9XBwvvdo
+ components-sample-data-state--wizard-installing--light:
+ hash: v1.k794b7964.2052c49beff2e0a5c5c533ae05c73bacc2619a04053b4529acf93574160c3a66.sTXp62J02o4EVCFfSt9_QV7YwS6UN87FpVxkPGrmZ3o
components-search--default--dark:
hash: v1.k794b7964.2143ca217d17aa04c982553503978c63645ece2137b5c8fb960ab032f00bbb37.9TgUxYSAp0acIhnmBMb9dPfmAAl1kkaUQgMkeeDz6wM
components-search--default--light:
diff --git a/frontend/src/lib/components/CommandBlock/CommandBlock.tsx b/frontend/src/lib/components/CommandBlock/CommandBlock.tsx
index f1514eab700c..abb2efa5969d 100644
--- a/frontend/src/lib/components/CommandBlock/CommandBlock.tsx
+++ b/frontend/src/lib/components/CommandBlock/CommandBlock.tsx
@@ -44,6 +44,13 @@ interface CommandBlockProps {
/** Skip the "Copied … to clipboard" toast. Set when this block lives inside another
* long-lived toast that would otherwise get pushed around by the success info toast. */
silentCopy?: boolean
+ /** Hide noise (`-y` flags and `@latest` version pins) from the displayed text to keep the
+ * block compact. The full `command` is still what gets copied. */
+ condensed?: boolean
+}
+
+function condenseCommand(command: string): string {
+ return command.replace(/ -y\b/g, '').replace(/@latest\b/g, '')
}
export function CommandBlock({
@@ -55,11 +62,13 @@ export function CommandBlock({
decoration = 'plain',
onCopy,
silentCopy = false,
+ condensed = false,
}: CommandBlockProps): JSX.Element {
const [copyKey, setCopyKey] = useState(0)
const buttonRef = useRef<HTMLButtonElement>(null)
const sizeStyle = SIZE_STYLES[size]
const isStorybook = inStorybook() || inStorybookTestRunner()
+ const displayCommand = condensed ? condenseCommand(command) : command
const handleCopy = (): void => {
void copyToClipboard(command, copyLabel, { silent: silentCopy })
@@ -96,7 +105,7 @@ export function CommandBlock({
'rainbow-text-animating': decoration === 'rainbow' && !isStorybook,
})}
>
- {command}
+ {displayCommand}
</code>
{copyKey > 0 && (
<code
@@ -104,7 +113,7 @@ export function CommandBlock({
className="CommandBlock__flash !bg-transparent !p-0 !border-0"
aria-hidden="true"
>
- {command}
+ {displayCommand}
</code>
)}
</span>
diff --git a/frontend/src/lib/lemon-ui/Spinner/Spinner.scss b/frontend/src/lib/lemon-ui/Spinner/Spinner.scss
index 8cbb1b7e0273..3f13c4cc7828 100644
--- a/frontend/src/lib/lemon-ui/Spinner/Spinner.scss
+++ b/frontend/src/lib/lemon-ui/Spinner/Spinner.scss
@@ -48,6 +48,13 @@
}
}
+// Paused rather than removed, so the arc keeps the keyframes' resting shape ("both" fill)
+// while staying deterministic for screenshots.
+.Spinner--frozen .Spinner__layer,
+.Spinner--frozen .Spinner__layer > circle {
+ animation-play-state: paused;
+}
+
@keyframes Spinner__writhe {
0%,
100% {
diff --git a/frontend/src/lib/lemon-ui/Spinner/Spinner.tsx b/frontend/src/lib/lemon-ui/Spinner/Spinner.tsx
index fc040b212a2d..98b52962272c 100644
--- a/frontend/src/lib/lemon-ui/Spinner/Spinner.tsx
+++ b/frontend/src/lib/lemon-ui/Spinner/Spinner.tsx
@@ -35,6 +35,7 @@ export interface SpinnerProps {
speed?: `${number}s` // Seconds
captureTime?: boolean
size?: 'small' | 'medium' | 'large'
+ frozen?: boolean
}
/** Smoothly animated spinner for loading states. It does not indicate progress, only that something's happening. */
@@ -44,6 +45,7 @@ export function Spinner({
speed = '1s',
captureTime = false,
size = 'small',
+ frozen = false,
}: SpinnerProps): JSX.Element {
useTimingCapture(captureTime)
const ref = useCancelAnimationsOnUnmount<SVGSVGElement>()
@@ -57,6 +59,7 @@ export function Spinner({
'LemonIcon Spinner',
textColored && `Spinner--textColored`,
size && `Spinner--${size}`,
+ frozen && 'Spinner--frozen',
className
)}
viewBox="0 0 48 48"
diff --git a/frontend/src/lib/utils/dom.ts b/frontend/src/lib/utils/dom.ts
index 64c55d40b46e..02b0ddcc7d1e 100644
--- a/frontend/src/lib/utils/dom.ts
+++ b/frontend/src/lib/utils/dom.ts
@@ -104,7 +104,9 @@ export function inStorybookTestRunner(): boolean {
}
export function inStorybook(): boolean {
- return '__STORYBOOK_CLIENT_API__' in window
+ // `__STORYBOOK_CLIENT_API__` was removed in Storybook 8; `__STORYBOOK_PREVIEW__` is its
+ // modern counterpart. Keep both so this works across versions.
+ return '__STORYBOOK_CLIENT_API__' in window || '__STORYBOOK_PREVIEW__' in window
}
export const shouldIgnoreInput = (e: KeyboardEvent): boolean => {
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts
index 255a1f38d634..01e26a4a8f89 100644
--- a/frontend/src/mocks/handlers.ts
+++ b/frontend/src/mocks/handlers.ts
@@ -99,6 +99,7 @@ function posthogCORSResponse(info: MockResolverInfo): Response {
export const defaultMocks: Mocks = {
get: {
'/api/projects/:team_id/my_notifications/': EMPTY_PAGINATED_RESPONSE,
+ '/api/projects/:team_id/tasks/': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team_id/actions/': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team_id/annotations/': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team_id/event_definitions/': EMPTY_PAGINATED_RESPONSE,
diff --git a/frontend/src/queries/nodes/DataTable/DataTable.tsx b/frontend/src/queries/nodes/DataTable/DataTable.tsx
index f49290f1b0d3..b79598730f28 100644
--- a/frontend/src/queries/nodes/DataTable/DataTable.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTable.tsx
@@ -944,6 +944,7 @@ export function DataTable({
heading={context?.emptyStateHeading}
detail={context?.emptyStateDetail}
icon={context?.emptyStateIcon}
+ sampleDataVariant="table"
/>
)
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
index 282fcf3481dd..847cd92e2313 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
@@ -262,7 +262,11 @@ export const Table = (props: TableProps): JSX.Element => {
}
/>
) : (
- <InsightEmptyState heading="There are no matching rows for this query" detail="" />
+ <InsightEmptyState
+ heading="There are no matching rows for this query"
+ detail=""
+ sampleDataVariant="table"
+ />
)
}
footer={tabularData.length > 0 ? <LoadNext query={props.query} /> : null}
diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
index 0ff208fae01b..86a76d2e07c1 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
@@ -277,7 +277,13 @@ export function InsightVizDisplay({
if (activeView === InsightType.FUNNELS && !isFlowViz) {
if (!hasFunnelResults && !erroredQueryId && !insightDataLoading) {
- return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="funnel"
+ />
+ )
}
}
diff --git a/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx b/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx
index 12508b6a36f1..f11ed111719a 100644
--- a/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx
+++ b/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx
@@ -484,7 +484,7 @@ function TestingEventsList(): JSX.Element | null {
},
},
]}
- emptyState={<InsightEmptyState />}
+ emptyState={<InsightEmptyState sampleDataVariant="table" />}
/>
)
}
diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
index 88998b5980dc..24602d86e882 100644
--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
@@ -44,16 +44,38 @@ import {
import { MathAvailability } from '../filters/ActionFilter/ActionFilterRow/ActionFilterRow'
import { insightDataLogic } from '../insightDataLogic'
import { insightVizDataLogic } from '../insightVizDataLogic'
+import { SampleDataState, SampleDataVariant } from './SampleDataState'
+import { sampleDataStateLogic } from './sampleDataStateLogic'
export function InsightEmptyState({
- heading = 'There are no matching events for this query',
- detail = 'Try changing the date range, or pick another action, event or breakdown.',
+ heading,
+ detail,
icon: iconProp,
+ sampleDataVariant,
}: {
heading?: string
detail?: string | JSX.Element
icon?: JSX.Element
+ /**
+ * Shape of the pre-ingestion sample-data placeholder. When omitted, a line chart is shown unless
+ * custom heading/detail copy was provided; pass a variant to opt in even with custom copy, or
+ * `null` to opt this call site out entirely.
+ */
+ sampleDataVariant?: SampleDataVariant | null
}): JSX.Element {
+ const { shouldShowSampleData } = useValues(sampleDataStateLogic)
+
+ // Before a project has ingested any events, "no matching events" is misleading — every chart is
+ // empty because nothing is flowing in yet. Show clearly-fake sample data instead, explaining on
+ // hover how to get real data. Call sites with purposeful custom copy keep their empty state
+ // unless they explicitly opted in with a variant.
+ const hasCustomCopy = heading !== undefined || detail !== undefined
+ if (shouldShowSampleData && sampleDataVariant !== null && (sampleDataVariant !== undefined || !hasCustomCopy)) {
+ return <SampleDataState variant={sampleDataVariant ?? 'line'} />
+ }
+
+ heading = heading ?? 'There are no matching events for this query'
+ detail = detail ?? 'Try changing the date range, or pick another action, event or breakdown.'
const icon =
iconProp ??
(isChristmas() ? (
diff --git a/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx b/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx
new file mode 100644
index 000000000000..f7098d69a63f
--- /dev/null
+++ b/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx
@@ -0,0 +1,78 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import '@testing-library/jest-dom'
+
+import { cleanup, render } from '@testing-library/react'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { TeamType } from '~/types'
+
+import { InsightEmptyState } from './EmptyStates'
+
+describe('<InsightEmptyState />', () => {
+ beforeEach(() => {
+ initKeaTests()
+ useMocks({
+ get: {
+ '/api/projects/:projectId/tasks/': { count: 0, results: [] },
+ },
+ })
+ })
+
+ const mountWithTeam = (overrides: Partial<TeamType>): void => {
+ teamLogic.mount()
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, ...overrides })
+ }
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it.each([
+ {
+ name: 'sample data before any events were ingested',
+ team: { ingested_event: false, is_demo: false },
+ props: {},
+ expectSampleData: true,
+ },
+ {
+ name: 'the regular empty state once events were ingested',
+ team: { ingested_event: true, is_demo: false },
+ props: {},
+ expectSampleData: false,
+ },
+ {
+ name: 'the regular empty state in demo projects',
+ team: { ingested_event: false, is_demo: true },
+ props: {},
+ expectSampleData: false,
+ },
+ {
+ name: 'custom copy over sample data when no variant was passed',
+ team: { ingested_event: false, is_demo: false },
+ props: { heading: 'No revenue data' },
+ expectSampleData: false,
+ },
+ {
+ name: 'sample data over custom copy when a variant explicitly opted in',
+ team: { ingested_event: false, is_demo: false },
+ props: { heading: 'No rows', sampleDataVariant: 'table' as const },
+ expectSampleData: true,
+ },
+ {
+ name: 'the regular empty state when the call site opted out',
+ team: { ingested_event: false, is_demo: false },
+ props: { sampleDataVariant: null },
+ expectSampleData: false,
+ },
+ ])('renders $name', ({ team, props, expectSampleData }) => {
+ mountWithTeam(team)
+ const { container } = render(<InsightEmptyState {...props} />)
+
+ expect(!!container.querySelector('[data-attr="insight-sample-data-state"]')).toBe(expectSampleData)
+ expect(!!container.querySelector('[data-attr="insight-empty-state"]')).toBe(!expectSampleData)
+ })
+})
diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataState.scss b/frontend/src/scenes/insights/EmptyStates/SampleDataState.scss
new file mode 100644
index 000000000000..cf3de7e7da21
--- /dev/null
+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataState.scss
@@ -0,0 +1,108 @@
+.SampleDataState {
+ position: relative;
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ width: 100%;
+ height: 100%;
+ min-height: 6rem;
+
+ &__tag {
+ position: absolute;
+ top: 0.5rem;
+ right: 0.5rem;
+ z-index: 1;
+ }
+
+ &__viz {
+ display: flex;
+ flex: 1;
+ align-items: center;
+ justify-content: center;
+ min-height: 0;
+ overflow: hidden;
+ transition: opacity 0.3s ease;
+ animation: SampleDataState__breathe 5s ease-in-out infinite;
+
+ // Settle to full opacity while the user is interacting with the chart
+ &:hover {
+ opacity: 1;
+ animation: none;
+ }
+ }
+
+ &__chart {
+ // The quill chart root stretches via flex-1, so it needs a flex column parent
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ height: 100%;
+ opacity: 0;
+ animation: SampleDataState__fade-up 0.7s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
+ }
+
+ &__row {
+ opacity: 0;
+ animation: SampleDataState__fade-up 0.5s ease-out forwards;
+ }
+
+ &__row-cell {
+ height: 0.5rem;
+ background: var(--color-skeleton-light);
+ border-radius: 0.25rem;
+ }
+
+ &__number {
+ opacity: 0;
+ animation: SampleDataState__fade-up 0.7s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
+ }
+
+ // One-shot entrance animations complete instantly for reduced motion or screenshot tests;
+ // the looping "breathe" is dropped entirely.
+ &--static &__viz {
+ animation: none;
+ }
+
+ &--static &__chart,
+ &--static &__row,
+ &--static &__number {
+ animation-duration: 0s;
+ animation-delay: 0s;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .SampleDataState__viz {
+ animation: none;
+ }
+
+ .SampleDataState__chart,
+ .SampleDataState__row,
+ .SampleDataState__number {
+ animation-duration: 0s;
+ animation-delay: 0s;
+ }
+}
+
+@keyframes SampleDataState__fade-up {
+ from {
+ opacity: 0;
+ transform: translateY(0.375rem);
+ }
+
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+@keyframes SampleDataState__breathe {
+ 0%,
+ 100% {
+ opacity: 0.8;
+ }
+
+ 50% {
+ opacity: 0.55;
+ }
+}
diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataState.stories.tsx b/frontend/src/scenes/insights/EmptyStates/SampleDataState.stories.tsx
new file mode 100644
index 000000000000..d6b5fedde099
--- /dev/null
+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataState.stories.tsx
@@ -0,0 +1,99 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { SampleDataState, SampleDataVariant } from './SampleDataState'
+
+const VARIANTS: SampleDataVariant[] = ['line', 'bar', 'pie', 'funnel', 'number', 'table']
+
+const meta: Meta<typeof SampleDataState> = {
+ component: SampleDataState,
+ title: 'Components/Sample Data State',
+ parameters: {
+ testOptions: {
+ waitForSelector: '[data-attr="insight-sample-data-state"]',
+ waitForLoadersToDisappear: false,
+ },
+ },
+}
+export default meta
+type Story = StoryObj<typeof SampleDataState>
+
+export const AllVariants: Story = {
+ render: () => (
+ <div className="grid grid-cols-3 gap-4">
+ {VARIANTS.map((variant) => (
+ <div key={variant} className="h-60 border rounded flex flex-col">
+ <div className="p-2 text-xs text-tertiary">{variant}</div>
+ <SampleDataState variant={variant} />
+ </div>
+ ))}
+ </div>
+ ),
+}
+
+/** The wizard's cloud run is still working - no PR yet, so an "Installing PostHog..." tag shows. */
+export const WizardInstalling: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/tasks/': () => [
+ 200,
+ {
+ count: 1,
+ results: [
+ {
+ id: 'sample-task-id',
+ created_at: '2026-07-01T00:00:00Z',
+ latest_run: {
+ created_at: '2026-07-01T00:10:00Z',
+ status: 'in_progress',
+ output: null,
+ },
+ },
+ ],
+ },
+ ],
+ },
+ }),
+ ],
+ render: () => (
+ <div className="h-60 w-160 border rounded flex flex-col">
+ <SampleDataState variant="line" />
+ </div>
+ ),
+}
+
+/** Hover the "Sample data" tag to see the tooltip point at the unmerged onboarding-wizard PR. */
+export const WithSetupPullRequest: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/tasks/': () => [
+ 200,
+ {
+ count: 1,
+ results: [
+ {
+ id: 'sample-task-id',
+ created_at: '2026-07-01T00:00:00Z',
+ latest_run: {
+ created_at: '2026-07-01T00:10:00Z',
+ output: {
+ pr_url: 'https://github.com/posthog/posthog/pull/12345',
+ pr_merged: false,
+ },
+ },
+ },
+ ],
+ },
+ ],
+ },
+ }),
+ ],
+ render: () => (
+ <div className="h-60 w-160 border rounded flex flex-col">
+ <SampleDataState variant="line" />
+ </div>
+ ),
+}
diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx
new file mode 100644
index 000000000000..7a82829aeae8
--- /dev/null
+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx
@@ -0,0 +1,262 @@
+import './SampleDataState.scss'
+
+import clsx from 'clsx'
+import { useValues } from 'kea'
+import { useEffect, useState } from 'react'
+import { TextMorph } from 'torph/react'
+
+import { LemonButton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { BarChart, LineChart, PieChart } from '@posthog/quill-charts'
+import type { BarChartConfig, LineChartConfig, Series } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+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'
+
+export type SampleDataVariant = 'line' | 'bar' | 'pie' | 'funnel' | 'number' | 'table'
+
+const WEEK_LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
+const LINE_SERIES: Series[] = [
+ { key: 'pageviews', label: 'Pageviews', data: [34, 27, 41, 38, 52, 46, 61], fill: { opacity: 0.1 } },
+ { key: 'signups', label: 'Sign-ups', data: [12, 16, 14, 22, 19, 26, 31] },
+]
+const BAR_SERIES: Series[] = [{ key: 'events', label: 'Events', data: [16, 24, 13, 30, 21, 38, 29] }]
+const FUNNEL_LABELS = ['Step 1', 'Step 2', 'Step 3', 'Step 4']
+const FUNNEL_SERIES: Series[] = [{ key: 'steps', label: 'Users', data: [412, 265, 179, 112] }]
+const PIE_SERIES: Series[] = [
+ { key: 'organic', label: 'Organic search', data: [46] },
+ { key: 'direct', label: 'Direct', data: [31] },
+ { key: 'referral', label: 'Referral', data: [23] },
+]
+const TABLE_HEADER = ['Event', 'Users', 'Count']
+const TABLE_ROWS = [
+ ['Pageview', '512', '1,284'],
+ ['Sign up', '76', '91'],
+ ['Purchase', '24', '30'],
+ ['Invite teammate', '12', '16'],
+]
+// Cycled through by the "number" variant, morphing from one to the next
+const SAMPLE_NUMBERS = [1284, 1327, 1291, 1362, 1408, 1373]
+
+const LINE_CONFIG: LineChartConfig = { showGrid: true, showCrosshair: true }
+const BAR_CONFIG: BarChartConfig = { bars: { cornerRadius: 2 } }
+
+function SampleNumber({ animate }: { animate: boolean }): JSX.Element {
+ const [valueIndex, setValueIndex] = useState(0)
+
+ useEffect(() => {
+ if (!animate) {
+ return
+ }
+ const interval = setInterval(() => setValueIndex((index) => (index + 1) % SAMPLE_NUMBERS.length), 4000)
+ return () => clearInterval(interval)
+ }, [animate])
+
+ return (
+ <div className="SampleDataState__number flex flex-col items-center gap-1">
+ <TextMorph as="div" className="text-4xl font-semibold tabular-nums text-secondary">
+ {humanFriendlyNumber(SAMPLE_NUMBERS[valueIndex])}
+ </TextMorph>
+ <div className="SampleDataState__row-cell w-16" />
+ </div>
+ )
+}
+
+function SampleTable(): JSX.Element {
+ return (
+ <div className="w-full max-w-120 self-center m-4 rounded border overflow-hidden text-secondary">
+ <div className="flex items-center gap-3 px-3 py-2 bg-surface-secondary text-xs font-semibold">
+ {TABLE_HEADER.map((label, cellIndex) => (
+ <div key={cellIndex} className={clsx('flex-1', cellIndex > 0 && 'text-right')}>
+ {label}
+ </div>
+ ))}
+ </div>
+ {TABLE_ROWS.map((cells, index) => (
+ <div
+ key={index}
+ className="SampleDataState__row flex items-center gap-3 px-3 py-2 border-t text-sm"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ animationDelay: `${index * 110}ms` }}
+ >
+ {cells.map((value, cellIndex) => (
+ <div
+ key={cellIndex}
+ className={clsx(
+ 'flex-1',
+ cellIndex === 0 ? 'flex items-center gap-2' : 'text-right tabular-nums'
+ )}
+ >
+ {cellIndex === 0 ? (
+ <>
+ <div className="SampleDataState__row-cell h-3 w-3 shrink-0 rounded-full" />
+ <span className="truncate">{value}</span>
+ </>
+ ) : (
+ value
+ )}
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function SampleChart({ variant }: { variant: Exclude<SampleDataVariant, 'number' | 'table'> }): JSX.Element {
+ const theme = useChartTheme()
+
+ return (
+ <div className="SampleDataState__chart">
+ {variant === 'line' ? (
+ <LineChart series={LINE_SERIES} labels={WEEK_LABELS} theme={theme} config={LINE_CONFIG} />
+ ) : variant === 'bar' ? (
+ <BarChart series={BAR_SERIES} labels={WEEK_LABELS} theme={theme} config={BAR_CONFIG} />
+ ) : variant === 'funnel' ? (
+ <BarChart series={FUNNEL_SERIES} labels={FUNNEL_LABELS} theme={theme} config={BAR_CONFIG} />
+ ) : (
+ <PieChart series={PIE_SERIES} theme={theme} />
+ )}
+ </div>
+ )
+}
+
+function SampleDataTooltipContent(): JSX.Element {
+ const { setupStatus } = useValues(setupWizardStatusLogic)
+
+ return (
+ <div className="max-w-72 space-y-1.5 p-0.5">
+ <div className="font-semibold">This is sample data</div>
+ <p className="m-0">
+ This project hasn't received any events yet - you'll see your real data here as soon as events start
+ coming in.
+ </p>
+ {setupStatus?.kind === 'installing' &&
+ (setupStatus.mode === 'cloud' ? (
+ <p className="m-0">
+ The setup wizard is installing PostHog in your codebase. Once it's done, it will open a pull
+ request for you to merge.
+ </p>
+ ) : (
+ <p className="m-0">
+ The setup wizard is installing PostHog in your codebase. You'll see real data here soon after
+ it's done.
+ </p>
+ ))}
+ {setupStatus?.kind === 'pull_request' &&
+ (setupStatus.pullRequest.merged ? (
+ <p className="m-0">
+ Your setup pull request is merged. Once the updated code is live and sending events, this chart
+ will fill in automatically.
+ </p>
+ ) : (
+ <p className="m-0">
+ Your setup pull request hasn't been merged yet -{' '}
+ <Link to={setupStatus.pullRequest.url} target="_blank" targetBlankIcon>
+ merge it
+ </Link>{' '}
+ to start sending events.
+ </p>
+ ))}
+ </div>
+ )
+}
+
+/** Obviously-fake placeholder chart shown instead of an empty state before a project has ingested any events. */
+export function SampleDataState({ variant = 'line' }: { variant?: SampleDataVariant }): JSX.Element {
+ const { setupStatus, setupStatusLoading } = useValues(setupWizardStatusLogic)
+ const { wizardCommand, isCloudOrDev } = useWizardCommand()
+ const isStatic =
+ inStorybook() ||
+ inStorybookTestRunner() ||
+ (typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
+
+ return (
+ <div
+ data-attr="insight-sample-data-state"
+ className={clsx('SampleDataState', isStatic && 'SampleDataState--static')}
+ >
+ <div className="SampleDataState__tag flex items-center gap-1">
+ {setupStatus?.kind === 'pull_request' && !setupStatus.pullRequest.merged && (
+ <LemonButton size="xsmall" type="primary" to={setupStatus.pullRequest.url} targetBlank>
+ Merge setup PR
+ </LemonButton>
+ )}
+ {setupStatus?.kind === 'installing' && (
+ <Tooltip
+ title={
+ <div className="max-w-72 space-y-1.5 p-0.5">
+ <div className="font-semibold">Setup wizard is running</div>
+ {setupStatus.mode === 'cloud' ? (
+ <p className="m-0">
+ The AI setup wizard is installing PostHog in the cloud, on a copy of your
+ codebase. Once it's done, it will open a pull request for you to review and
+ merge.
+ </p>
+ ) : (
+ <p className="m-0">
+ The AI setup wizard is installing PostHog in your codebase from your terminal.
+ You'll see real data here soon after it's done.
+ </p>
+ )}
+ </div>
+ }
+ placement="bottom"
+ delayMs={0}
+ >
+ <LemonTag type="muted" className="gap-1 cursor-help">
+ <Spinner className="text-xs" frozen={isStatic} />
+ Installing PostHog...
+ </LemonTag>
+ </Tooltip>
+ )}
+ {variant === 'line' && !setupStatus && !setupStatusLoading && isCloudOrDev && (
+ <Tooltip
+ title={
+ <div className="max-w-72 space-y-1.5 p-0.5">
+ <div className="font-semibold">AI setup wizard</div>
+ <p className="m-0">
+ Run this command from the root of your project - the wizard detects your framework,
+ installs the PostHog SDK, and starts sending events. Click to copy.
+ </p>
+ </div>
+ }
+ placement="bottom"
+ delayMs={0}
+ >
+ <span>
+ <CommandBlock
+ command={wizardCommand}
+ copyLabel="Setup wizard command"
+ ariaLabel="Copy setup wizard command"
+ size="sm"
+ decoration="rainbow"
+ condensed
+ // Sized down to sit flush with the LemonTag next to it
+ className="gap-1 px-1 py-0.5 rounded text-[0.6875rem] leading-4 bg-surface-primary border hover:border-accent"
+ />
+ </span>
+ </Tooltip>
+ )}
+ <Tooltip title={<SampleDataTooltipContent />} interactive delayMs={100} placement="bottom">
+ <LemonTag className="cursor-help" type="muted">
+ Sample data
+ </LemonTag>
+ </Tooltip>
+ </div>
+ <div className="SampleDataState__viz">
+ {variant === 'number' ? (
+ <SampleNumber animate={!isStatic} />
+ ) : variant === 'table' ? (
+ <SampleTable />
+ ) : (
+ <SampleChart variant={variant} />
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/insights/EmptyStates/sampleDataStateLogic.ts b/frontend/src/scenes/insights/EmptyStates/sampleDataStateLogic.ts
new file mode 100644
index 000000000000..1d6215ace211
--- /dev/null
+++ b/frontend/src/scenes/insights/EmptyStates/sampleDataStateLogic.ts
@@ -0,0 +1,22 @@
+import { connect, kea, path, selectors } from 'kea'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { sampleDataStateLogicType } from './sampleDataStateLogicType'
+
+/**
+ * Gates the pre-ingestion sample-data placeholder: only projects that never ingested an event see
+ * it. The wizard setup status shown on the placeholder comes from `setupWizardStatusLogic`.
+ */
+export const sampleDataStateLogic = kea<sampleDataStateLogicType>([
+ path(['scenes', 'insights', 'EmptyStates', 'sampleDataStateLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeam']],
+ })),
+ selectors({
+ shouldShowSampleData: [
+ (s) => [s.currentTeam],
+ (currentTeam): boolean => !!currentTeam && !currentTeam.ingested_event && !currentTeam.is_demo,
+ ],
+ }),
+])
diff --git a/frontend/src/scenes/insights/views/BoldNumber/BoldNumber.tsx b/frontend/src/scenes/insights/views/BoldNumber/BoldNumber.tsx
index edf03b57a5f5..e2878032cbc1 100644
--- a/frontend/src/scenes/insights/views/BoldNumber/BoldNumber.tsx
+++ b/frontend/src/scenes/insights/views/BoldNumber/BoldNumber.tsx
@@ -177,7 +177,7 @@ export function BoldNumber({ showPersonsModal = true, context }: ChartParams): J
{showComparison && <BoldNumberComparison showPersonsModal={showPersonsModal} context={context} />}
</div>
) : (
- <InsightEmptyState />
+ <InsightEmptyState sampleDataVariant="number" />
)
}
@@ -295,7 +295,7 @@ export function HogQLBoldNumber(): JSX.Element {
if (formattedValue === null || directValue === null || resultsValue === null || resultValue === null) {
return (
<div className="LemonTable HogQL">
- <InsightEmptyState />
+ <InsightEmptyState sampleDataVariant="number" />
</div>
)
}
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.tsx b/frontend/src/scenes/insights/views/Metric/Metric.tsx
index c38cda76cc14..b58b12e5255d 100644
--- a/frontend/src/scenes/insights/views/Metric/Metric.tsx
+++ b/frontend/src/scenes/insights/views/Metric/Metric.tsx
@@ -49,7 +49,7 @@ export function Metric({ inCardView }: ChartParams): JSX.Element {
// `count` is typed as a number but can be absent at runtime, which would render a blank tile.
if (!resultSeries || resultSeries.count == null) {
- return <InsightEmptyState />
+ return <InsightEmptyState sampleDataVariant="number" />
}
const summary = trendsFilter?.metricSummary ?? METRIC_SUMMARY_DEFAULT
diff --git a/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.ts b/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.ts
new file mode 100644
index 000000000000..5358cf58e652
--- /dev/null
+++ b/frontend/src/scenes/onboarding/shared/setupWizardStatusLogic.ts
@@ -0,0 +1,286 @@
+import { actions, afterMount, connect, getContext, kea, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
+
+import { wizardActiveSessionDetectorLogic } from 'scenes/onboarding/legacy/sdks/OnboardingInstallStep/wizardActiveSessionDetectorLogic'
+import { activeCloudRunLogic } from 'scenes/onboarding/self-driving/sdks/OnboardingInstallStep/activeCloudRunLogic'
+import {
+ InstallationMode,
+ InstallationProgress,
+ installationProgressLogic,
+} from 'scenes/onboarding/self-driving/sdks/OnboardingInstallStep/installationProgressLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { tasksList, tasksRunsList } from 'products/tasks/frontend/generated/api'
+import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
+
+import type { setupWizardStatusLogicType } from './setupWizardStatusLogicType'
+
+export interface SetupPullRequest {
+ url: string
+ merged: boolean
+}
+
+/** Where the onboarding wizard's setup run is at, coarse enough for any surface to render. */
+export type SetupWizardStatus =
+ /** The wizard opened a pull request - surface it so the user merges it. */
+ | { kind: 'pull_request'; pullRequest: SetupPullRequest }
+ /** The wizard is still working on the integration - cloud runs end in a PR, local ones don't. */
+ | { kind: 'installing'; mode: InstallationMode }
+
+export interface SetupRunHandle {
+ taskId: string
+ runId: string
+}
+
+export interface DiscoveredSetupRun {
+ status: SetupWizardStatus
+ /** Null when the tasks API response carried no run id, so there is nothing to stream. */
+ handle: SetupRunHandle | null
+}
+
+const RUNNING_STATUSES = ['not_started', 'queued', 'in_progress']
+
+const byCreatedAtDesc = (a: { created_at?: string | null }, b: { created_at?: string | null }): number =>
+ (b.created_at ?? '').localeCompare(a.created_at ?? '')
+
+type LatestRunDetail = Pick<TaskRunDetailDTOApi, 'id' | 'status' | 'output' | 'created_at'>
+
+/**
+ * The tasks list endpoint nests the full run detail in `latest_run`, but the generated type
+ * collapses it to the bare run id (OpenAPI schema-name collision with the conversation envelope
+ * variant), so the nested shape has to be recovered with a cast.
+ */
+function asLatestRunDetail(latestRun: unknown): Partial<LatestRunDetail> | null {
+ return latestRun && typeof latestRun === 'object' ? (latestRun as Partial<LatestRunDetail>) : null
+}
+
+export function pullRequestFromRunOutput(output: Record<string, unknown> | null | undefined): SetupPullRequest | null {
+ const url = output?.pr_url
+ if (typeof url !== 'string' || !url) {
+ return null
+ }
+ return { url, merged: output?.pr_merged === true }
+}
+
+export function isRunRunning(run: Partial<LatestRunDetail> | null): boolean {
+ return typeof run?.status === 'string' && RUNNING_STATUSES.includes(run.status)
+}
+
+/**
+ * Collapse the live installation progress into the coarse setup status. The stream does not know
+ * whether a PR got merged, so `merged` only ever turns true via the REST snapshot.
+ */
+export function statusFromProgress(progress: InstallationProgress | null): SetupWizardStatus | null {
+ if (!progress?.isCurrent) {
+ return null
+ }
+ if (progress.prUrl) {
+ return { kind: 'pull_request', pullRequest: { url: progress.prUrl, merged: false } }
+ }
+ if (progress.phase === 'connecting' || progress.phase === 'running') {
+ return { kind: 'installing', mode: 'cloud' }
+ }
+ return null
+}
+
+/**
+ * App-wide status of the onboarding wizard's setup task run (the cloud run that installs PostHog
+ * in the user's codebase and opens a pull request).
+ *
+ * Two complementary sources, merged in `setupStatus`:
+ * - REST discovery (`loadDiscoveredRun`): finds the newest onboarding task via the tasks API, so
+ * runs kicked off elsewhere (another browser, before a refresh) are found too. Also the only
+ * source that knows whether the PR got merged.
+ * - Live streaming: when a run handle is known (the persisted `activeCloudRunLogic` handle, or a
+ * still-running discovered run), `installationProgressLogic` is mounted for it and its
+ * normalized progress is mirrored here, so the status updates in real time.
+ * - Local runs: the CLI wizard creates no task run, so `wizardActiveSessionDetectorLogic`'s cheap
+ * session poll fills in "installing" when neither cloud source knows of a run.
+ *
+ * Mounting this logic starts the REST discovery and, while a run is live, an SSE stream. Mount it
+ * from surfaces that actually need setup state rather than app-wide (INC-886).
+ */
+export const setupWizardStatusLogic = kea<setupWizardStatusLogicType>([
+ path(['scenes', 'onboarding', 'shared', 'setupWizardStatusLogic']),
+ connect(() => ({
+ values: [
+ teamLogic,
+ ['currentTeamId'],
+ activeCloudRunLogic,
+ ['activeCloudRun'],
+ wizardActiveSessionDetectorLogic,
+ ['hasActiveSession'],
+ ],
+ })),
+ actions({
+ liveProgressUpdated: (progress: InstallationProgress | null) => ({ progress }),
+ }),
+ loaders(({ values }) => ({
+ discoveredRun: [
+ null as DiscoveredSetupRun | null,
+ {
+ loadDiscoveredRun: async (): Promise<DiscoveredSetupRun | null> => {
+ // Mounted before the team loaded: the currentTeamId subscription below retries
+ if (values.currentTeamId === null) {
+ return null
+ }
+ try {
+ const projectId = String(values.currentTeamId)
+ const tasks = await tasksList(projectId, { origin_product: 'onboarding', limit: 10 })
+ const newestFirst = [...tasks.results].sort(byCreatedAtDesc)
+ for (const task of newestFirst) {
+ const run = asLatestRunDetail(task.latest_run)
+ const pullRequest = pullRequestFromRunOutput(run?.output)
+ if (pullRequest) {
+ return {
+ status: { kind: 'pull_request', pullRequest },
+ handle: run?.id ? { taskId: task.id, runId: run.id } : null,
+ }
+ }
+ }
+ // Fallback for when `latest_run` really is a bare run id: check the newest task's runs
+ const newestTask = newestFirst[0]
+ if (newestTask && typeof newestTask.latest_run === 'string') {
+ const runs = await tasksRunsList(projectId, newestTask.id)
+ const runsNewestFirst = [...runs.results].sort(byCreatedAtDesc)
+ for (const run of runsNewestFirst) {
+ const pullRequest = pullRequestFromRunOutput(run.output)
+ if (pullRequest) {
+ return {
+ status: { kind: 'pull_request', pullRequest },
+ handle: { taskId: newestTask.id, runId: run.id },
+ }
+ }
+ }
+ const runningRun = runsNewestFirst.find((run) => isRunRunning(run))
+ if (runningRun) {
+ return {
+ status: { kind: 'installing', mode: 'cloud' },
+ handle: { taskId: newestTask.id, runId: runningRun.id },
+ }
+ }
+ }
+ // No PR anywhere: the wizard may still be working on it
+ for (const task of newestFirst) {
+ const run = asLatestRunDetail(task.latest_run)
+ if (isRunRunning(run)) {
+ return {
+ status: { kind: 'installing', mode: 'cloud' },
+ handle: run?.id ? { taskId: task.id, runId: run.id } : null,
+ }
+ }
+ }
+ return null
+ } catch {
+ // Consumers work without wizard context: a tasks API failure is non-fatal
+ return null
+ }
+ },
+ },
+ ],
+ })),
+ reducers({
+ liveProgress: [
+ null as InstallationProgress | null,
+ {
+ liveProgressUpdated: (_, { progress }) => progress,
+ },
+ ],
+ }),
+ selectors({
+ liveRunHandle: [
+ (s) => [s.activeCloudRun, s.discoveredRun],
+ (activeCloudRun, discoveredRun): SetupRunHandle | null => {
+ if (activeCloudRun) {
+ return { taskId: activeCloudRun.taskId, runId: activeCloudRun.runId }
+ }
+ // Only stream discovered runs that are still going; finished runs are fully described by REST
+ return discoveredRun?.status.kind === 'installing' ? discoveredRun.handle : null
+ },
+ ],
+ setupStatus: [
+ (s) => [s.liveProgress, s.discoveredRun, s.hasActiveSession],
+ (liveProgress, discoveredRun, hasActiveSession): SetupWizardStatus | null => {
+ const live = statusFromProgress(liveProgress)
+ const discovered = discoveredRun?.status ?? null
+ if (live?.kind === 'pull_request') {
+ // Only REST knows whether the PR got merged, so prefer its record of the same PR
+ if (discovered?.kind === 'pull_request' && discovered.pullRequest.url === live.pullRequest.url) {
+ return discovered
+ }
+ return live
+ }
+ if (live) {
+ return live
+ }
+ // The live layer watched the run reach a terminal state without a PR: a stale REST
+ // "installing" snapshot must not keep claiming the wizard is still at work
+ if (
+ liveProgress?.isCurrent &&
+ (liveProgress.phase === 'error' || liveProgress.phase === 'completed') &&
+ discovered?.kind === 'installing'
+ ) {
+ return null
+ }
+ if (discovered) {
+ return discovered
+ }
+ // No cloud run anywhere, but the CLI wizard has an active local session
+ return hasActiveSession ? { kind: 'installing', mode: 'local' } : null
+ },
+ ],
+ setupStatusLoading: [(s) => [s.discoveredRunLoading], (discoveredRunLoading): boolean => discoveredRunLoading],
+ }),
+ subscriptions(({ actions, cache }) => ({
+ // The afterMount load no-ops when the logic mounts before the team is known; (re)load once
+ // the team id arrives or changes. kea-subscriptions' initial mount call (prev undefined) is
+ // skipped since afterMount already covers it.
+ currentTeamId: (teamId: number | null, prevTeamId: number | null | undefined) => {
+ if (teamId !== null && prevTeamId !== undefined && teamId !== prevTeamId) {
+ actions.loadDiscoveredRun()
+ }
+ },
+ // installationProgressLogic is keyed by a run id we only know at runtime, so it can't be
+ // connected statically. Mount it imperatively for the current handle and mirror its
+ // progress selector through a store subscription; disposables tear it all down on unmount.
+ liveRunHandle: (handle: SetupRunHandle | null) => {
+ const runKey = handle ? `${handle.taskId}:${handle.runId}` : null
+ if (runKey === cache.liveRunKey) {
+ return
+ }
+ cache.liveRunKey = runKey
+ cache.disposables.dispose('live-progress')
+ if (!handle) {
+ actions.liveProgressUpdated(null)
+ return
+ }
+ cache.disposables.add(() => {
+ const progressLogic = installationProgressLogic.build({
+ mode: 'cloud',
+ runId: handle.runId,
+ taskId: handle.taskId,
+ })
+ const unmount = progressLogic.mount()
+ const { store } = getContext()
+ let lastPushed: InstallationProgress | null = null
+ const push = (): void => {
+ const progress = progressLogic.selectors.installationProgress(store.getState(), progressLogic.props)
+ if (progress !== lastPushed) {
+ lastPushed = progress
+ actions.liveProgressUpdated(progress)
+ }
+ }
+ push()
+ const unsubscribe = store.subscribe(push)
+ return () => {
+ unsubscribe()
+ unmount()
+ }
+ }, 'live-progress')
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadDiscoveredRun()
+ }),
+])
diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx
index 28467ebd1b2a..8a98cd347b97 100644
--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx
+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx
@@ -195,7 +195,13 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.El
)
if (!hasData) {
- return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="bar"
+ />
+ )
}
return (
diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx
index df6572942aa5..55487295a7be 100644
--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx
+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx
@@ -193,7 +193,13 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.
)
if (!hasData) {
- return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="line"
+ />
+ )
}
return (
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index 9ec7aaf3a500..275fe6df1868 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -423,7 +423,13 @@ export function TrendsBarChart({
)
if (!hasData) {
- return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="bar"
+ />
+ )
}
if (isAggregated) {
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
index 98f4bee8971e..0d9792cc981b 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
@@ -224,7 +224,13 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi
)
if (!hasData) {
- return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="bar"
+ />
+ )
}
const showAnnotations = !inSharedMode
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
index fd481c854a40..97dcea64e4de 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
@@ -296,7 +296,13 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
)
if (!hasData) {
- return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="line"
+ />
+ )
}
const showAnnotations = !inSharedMode && trendsFilter?.showAnnotations !== false
diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx
index 7e857e242649..f95a062f1b14 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx
@@ -238,7 +238,13 @@ export function TrendsPieChart({ context, showPersonsModal = true }: TrendsPieCh
)
if (!visibleResults.length) {
- return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="pie"
+ />
+ )
}
return (
diff --git a/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx
index 5869b25c63a1..2c561b139730 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx
@@ -67,7 +67,13 @@ export function TrendsSlopeChart({ context }: TrendsSlopeChartProps): JSX.Elemen
)
if (series.length === 0) {
- return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="line"
+ />
+ )
}
return (
diff --git a/products/revenue_analytics/frontend/nodes/shared.tsx b/products/revenue_analytics/frontend/nodes/shared.tsx
index 92e0802c5f88..2cb6ceef0dea 100644
--- a/products/revenue_analytics/frontend/nodes/shared.tsx
+++ b/products/revenue_analytics/frontend/nodes/shared.tsx
@@ -96,7 +96,13 @@ export const TileWrapper = ({ title, tooltip, extra, children, context }: TileWr
'results' in response &&
response.results.length === 0
) {
- return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ return (
+ <InsightEmptyState
+ heading={context?.emptyStateHeading}
+ detail={context?.emptyStateDetail}
+ sampleDataVariant="line"
+ />
+ )
}
if (responseErrorObject) {
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index d78d2e7670a6..5c9e432ccbb8 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -101,6 +101,64 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(call_kwargs["properties"]["run_id"], str(self.task_run.id))
self.assertEqual(call_kwargs["properties"]["pr_source"], "task")
+ self.task_run.refresh_from_db()
+ assert self.task_run.output is not None
+ self.assertIs(self.task_run.output.get("pr_merged"), True)
+
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_pr_merged_from_fork_does_not_record_pr_merged(self, mock_capture, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ branch="feature/fork-merge",
+ output={},
+ )
+ payload = {
+ "action": "closed",
+ "pull_request": {
+ "html_url": "https://github.com/attacker/posthog/pull/2",
+ "merged": True,
+ "head": {"ref": "feature/fork-merge", "repo": {"full_name": "attacker/posthog"}},
+ },
+ "repository": {"full_name": "posthog/posthog"},
+ }
+
+ response = self._make_webhook_request(payload)
+ self.assertEqual(response.status_code, 200)
+
+ run.refresh_from_db()
+ self.assertEqual(run.output, {})
+
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_pr_merged_for_other_pr_on_same_branch_does_not_record_pr_merged(self, mock_capture, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ branch="feature/shared-branch",
+ output={"pr_url": "https://github.com/posthog/posthog/pull/10"},
+ )
+ payload = {
+ "action": "closed",
+ "pull_request": {
+ "html_url": "https://github.com/posthog/posthog/pull/11",
+ "merged": True,
+ "head": {"ref": "feature/shared-branch", "repo": {"full_name": "posthog/posthog"}},
+ },
+ "repository": {"full_name": "posthog/posthog"},
+ }
+
+ response = self._make_webhook_request(payload)
+ self.assertEqual(response.status_code, 200)
+
+ run.refresh_from_db()
+ self.assertEqual(run.output, {"pr_url": "https://github.com/posthog/posthog/pull/10"})
+
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_closed_without_merge_webhook(self, mock_capture, mock_get_secret):
diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.py
index b8edb1d1a1cd..c7f9d026cb41 100644
--- a/products/tasks/backend/webhooks.py
+++ b/products/tasks/backend/webhooks.py
@@ -138,6 +138,12 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:
_capture_pr_event(payload, task_run, analytics_event, event_uuid)
if task_run and action == "closed" and merged:
+ # Only trust the merge for the run that actually claims this PR URL. The pr_url backstop
+ # above already covers branch-matched internal PRs, so requiring equality here keeps a
+ # same-branch webhook for a different PR from marking this run's PR as merged.
+ run_output = task_run.output if isinstance(task_run.output, dict) else {}
+ if run_output.get("pr_url") == pr_url:
+ _record_run_pr_merged(task_run)
_resolve_signal_reports_for_task(task_run.task_id, pr_url)
return HttpResponse(status=200)
@@ -150,23 +156,41 @@ def _record_run_pr_url(task_run: TaskRun, pr_url: str) -> None:
the PR. When that detection misses, a branch+repo webhook match is the
backstop — without this the run is recognized for analytics but its
``output.pr_url`` stays empty, so inbox notifications, the CI follow-up loop,
- and later webhook lookups never resolve the PR. Tolerant: a failure here must
- not fail the webhook (GitHub retries 5xx, and the event is already handled).
+ and later webhook lookups never resolve the PR.
"""
- if isinstance(task_run.output, dict) and task_run.output.get("pr_url"):
+ _record_run_output_field(task_run, "pr_url", pr_url, "github_pr_webhook_record_pr_url_failed")
+
+
+def _record_run_pr_merged(task_run: TaskRun) -> None:
+ """Persist ``output.pr_merged`` when the run's PR is merged.
+
+ Surfaces that gate on merge state (e.g. the pre-ingestion sample-data placeholder pointing at
+ the wizard's setup PR) read it off the run's ``output``, which is the only PR state the task
+ APIs expose.
+ """
+ _record_run_output_field(task_run, "pr_merged", True, "github_pr_webhook_record_pr_merged_failed")
+
+
+def _record_run_output_field(task_run: TaskRun, key: str, value: str | bool, failure_log_event: str) -> None:
+ """Idempotently merge ``{key: value}`` into a run's ``output`` JSON under a row lock.
+
+ Tolerant: a failure here must not fail the webhook (GitHub retries 5xx, and the event is
+ already handled).
+ """
+ if isinstance(task_run.output, dict) and task_run.output.get(key):
return
try:
with transaction.atomic():
locked = TaskRun.objects.select_for_update().get(id=task_run.id)
output = locked.output if isinstance(locked.output, dict) else {}
- if output.get("pr_url"):
+ if output.get(key):
return
- locked.output = {**output, "pr_url": pr_url}
+ locked.output = {**output, key: value}
locked.save(update_fields=["output", "updated_at"])
# Keep the in-memory instance consistent for the rest of this request.
- task_run.output = {**(task_run.output if isinstance(task_run.output, dict) else {}), "pr_url": pr_url}
+ task_run.output = locked.output
except Exception:
- logger.warning("github_pr_webhook_record_pr_url_failed", run_id=str(task_run.id), exc_info=True)
+ logger.warning(failure_log_event, run_id=str(task_run.id), exc_info=True)
# Nulled on external PRs so their schema matches task-originated PR events.