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(experiments): keep the wizard guide visible and add an Ask AI button (#108052)

ruby childsaf5c2992251f
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 36b216025db3..bd6de85acae2 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -1255,15 +1255,14 @@ export interface eventUsageLogicActions {
context: ExperimentWatchHighlightContext
experimentId: ExperimentIdType
}
- reportExperimentWizardGuideToggled: (
- visible: boolean,
+ reportExperimentWizardAskAiClicked: (currentStep: string) => {
currentStep: string
- ) => {
- currentStep: string
- visible: boolean
}
- reportExperimentWizardStarted: (guideVisible: boolean) => {
- guideVisible: boolean
+ reportExperimentWizardStarted: () => {
+ value: true
+ }
+ reportExperimentsListAiBadgeClicked: () => {
+ value: true
}
reportFeatureFlagBulkCopy: (
flagCount: number,
@@ -1915,8 +1914,9 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
draftAgeSeconds,
}),
reportInsightDraftDiscarded: (draftAgeSeconds: number) => ({ draftAgeSeconds }),
- reportExperimentWizardStarted: (guideVisible: boolean) => ({ guideVisible }),
- reportExperimentWizardGuideToggled: (visible: boolean, currentStep: string) => ({ visible, currentStep }),
+ reportExperimentWizardStarted: true,
+ reportExperimentWizardAskAiClicked: (currentStep: string) => ({ currentStep }),
+ reportExperimentsListAiBadgeClicked: true,
reportExperimentViewed: (experiment: Experiment, duration: number | null) => ({ experiment, duration }),
reportExperimentMetricBreakdownAdded: (
experiment: Experiment,
@@ -2549,16 +2549,14 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
})
}
},
- reportExperimentWizardStarted: ({ guideVisible }) => {
- posthog.capture('experiment wizard started', {
- guide_visible: guideVisible,
- })
+ reportExperimentWizardStarted: () => {
+ posthog.capture('experiment wizard started')
},
- reportExperimentWizardGuideToggled: ({ visible, currentStep }) => {
- posthog.capture('experiment wizard guide toggled', {
- visible,
- current_step: currentStep,
- })
+ reportExperimentWizardAskAiClicked: ({ currentStep }) => {
+ posthog.capture('experiment wizard ask ai clicked', { current_step: currentStep })
+ },
+ reportExperimentsListAiBadgeClicked: () => {
+ posthog.capture('experiments list ai badge clicked')
},
reportExperimentViewed: ({ experiment, duration }) => {
posthog.capture('experiment viewed', {
diff --git a/frontend/src/scenes/experiments/ExperimentForm/MetricsPanel/EmptyMetricsPanel.tsx b/frontend/src/scenes/experiments/ExperimentForm/MetricsPanel/EmptyMetricsPanel.tsx
index 66fcb2c8152c..a0a3f42e32e1 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/MetricsPanel/EmptyMetricsPanel.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/MetricsPanel/EmptyMetricsPanel.tsx
@@ -27,13 +27,14 @@ export const EmptyMetricsPanel = ({
</div>
</LemonBanner>
)}
- <div className="border border-dashed rounded p-8 flex flex-col items-center gap-4">
- <div className="flex flex-col sm:flex-row gap-3 items-stretch sm:items-start w-full sm:w-auto">
+ {/* Sized off its own width rather than the screen's, so the two buttons stack in a narrow column */}
+ <div className="@container border border-dashed rounded p-8 flex flex-col items-center gap-4">
+ <div className="flex flex-col @xl:flex-row gap-3 items-stretch @xl:items-start w-full @xl:w-auto">
<LemonButton
type="secondary"
icon={<IconPlus />}
onClick={() => openMetricSourceModal(METRIC_CONTEXTS.primary)}
- className="!h-[80px] flex-1 sm:w-[280px] sm:flex-none"
+ className="!h-[80px] flex-1 @xl:w-[280px] @xl:flex-none"
>
<div className="flex flex-col gap-0.5 text-left">
<span className="font-medium text-sm">Add primary metric</span>
@@ -44,7 +45,7 @@ export const EmptyMetricsPanel = ({
type="secondary"
icon={<IconPlus />}
onClick={() => openMetricSourceModal(METRIC_CONTEXTS.secondary)}
- className="!h-[80px] flex-1 sm:w-[280px] sm:flex-none"
+ className="!h-[80px] flex-1 @xl:w-[280px] @xl:flex-none"
>
<div className="flex flex-col gap-0.5 text-left">
<span className="font-medium text-sm">Add secondary metric</span>
diff --git a/frontend/src/scenes/experiments/ExperimentWizard/ExperimentWizard.tsx b/frontend/src/scenes/experiments/ExperimentWizard/ExperimentWizard.tsx
index 13ec9aa68c3b..e549aafb2703 100644
--- a/frontend/src/scenes/experiments/ExperimentWizard/ExperimentWizard.tsx
+++ b/frontend/src/scenes/experiments/ExperimentWizard/ExperimentWizard.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconArrowLeft, IconLightBulb } from '@posthog/icons'
+import { IconArrowLeft } from '@posthog/icons'
import { LemonButton, Link } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
@@ -14,30 +14,16 @@ import { AnalyticsStep } from './steps/AnalyticsStep'
import { VariantsStep } from './steps/VariantsStep'
export function ExperimentWizard(): JSX.Element {
- const {
- currentStep,
- isLastStep,
- isFirstStep,
- isExperimentSubmitting,
- showGuide,
- stepValidationErrors,
- hasFormErrors,
- } = useValues(experimentWizardLogic)
- const { nextStep, prevStep, setStep, saveExperiment, toggleGuide } = useActions(experimentWizardLogic)
+ const { currentStep, isLastStep, isFirstStep, isExperimentSubmitting, stepValidationErrors, hasFormErrors } =
+ useValues(experimentWizardLogic)
+ const { nextStep, prevStep, setStep, saveExperiment } = useActions(experimentWizardLogic)
const header = (
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} to={urls.experiments()}>
- Experiments
- </LemonButton>
- <h1 className="text-2xl font-semibold">New experiment</h1>
- </div>
- {!showGuide && (
- <LemonButton type="secondary" size="small" icon={<IconLightBulb />} onClick={toggleGuide}>
- Show guide
- </LemonButton>
- )}
+ <div className="space-y-1">
+ <LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} to={urls.experiments()}>
+ Experiments
+ </LemonButton>
+ <h1 className="text-2xl font-semibold">New experiment</h1>
</div>
)
@@ -52,77 +38,69 @@ export function ExperimentWizard(): JSX.Element {
)
const body = (
- <div className="bg-surface-primary border border-border rounded-lg p-6">
+ // Grows to meet the footer, so short steps don't change the card's height
+ <div className="flex-1 bg-surface-primary border border-border rounded-lg p-6">
{currentStep === 'about' && <AboutStep />}
{currentStep === 'variants' && <VariantsStep />}
{currentStep === 'analytics' && <AnalyticsStep />}
</div>
)
+ // Pinned to the bottom so the buttons stay put on every step. Equal-width button groups keep the link centered.
const footer = (
- <>
- <div className="flex items-center justify-between">
- <div>
- {!isFirstStep && (
- <LemonButton type="secondary" onClick={prevStep}>
- Back
- </LemonButton>
- )}
- </div>
- <div className="flex items-center gap-2">
- {isLastStep ? (
- <LemonButton
- type="primary"
- onClick={saveExperiment}
- loading={isExperimentSubmitting}
- disabledReason={hasFormErrors ? 'Please fix all errors before saving' : undefined}
- >
- Save as draft
- </LemonButton>
- ) : (
- <LemonButton type="primary" onClick={nextStep}>
- Continue
- </LemonButton>
- )}
- </div>
+ <div className="@container sticky bottom-0 z-10 flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-primary bg-bg-light py-4">
+ <div className="flex flex-1 basis-0">
+ {!isFirstStep && (
+ <LemonButton type="secondary" onClick={prevStep}>
+ Back
+ </LemonButton>
+ )}
</div>
-
- <div className="text-center text-xs text-muted">
- <p>
- Looking for no-code? They are created using the toolbar,{' '}
- <Link
- target="_blank"
- targetBlankIcon
- to="https://posthog.com/docs/experiments/no-code-web-experiments"
+ <p className="order-last m-0 w-full text-center text-xs text-muted @2xl:order-none @2xl:w-auto">
+ Looking for no-code? They are created using the toolbar,{' '}
+ <Link target="_blank" targetBlankIcon to="https://posthog.com/docs/experiments/no-code-web-experiments">
+ see no-code docs
+ </Link>
+ </p>
+ <div className="flex flex-1 basis-0 items-center justify-end gap-2">
+ {isLastStep ? (
+ <LemonButton
+ type="primary"
+ onClick={saveExperiment}
+ loading={isExperimentSubmitting}
+ disabledReason={hasFormErrors ? 'Please fix all errors before saving' : undefined}
>
- see no-code docs
- </Link>
- </p>
+ Save as draft
+ </LemonButton>
+ ) : (
+ <LemonButton type="primary" onClick={nextStep}>
+ Continue
+ </LemonButton>
+ )}
</div>
- </>
+ </div>
)
+ // Sized off the container, so the layout holds when the side panel narrows the scene. From 1024px the form is
+ // centered with the guide on the right, and an empty left column as wide as the right keeps it centered. From
+ // 672px the form and guide sit side by side, and narrower screens get one column with the guide under the form.
+ const mainColumn =
+ 'w-full max-w-3xl min-w-0 justify-self-center space-y-6 @2xl:col-start-1 @2xl:max-w-none @5xl:col-start-2'
+ // The second row fills the scene's height, so the footer stays at the same height whether or not the step scrolls
return (
- <div className="flex-1 bg-bg-light">
- <div className={cn('mx-auto px-6 py-6 space-y-6', showGuide ? 'max-w-5xl' : 'max-w-3xl')}>
- {header}
-
- {showGuide ? (
- <div className="grid grid-cols-[1fr_280px] gap-6">
- <div className="space-y-6">
- {stepper}
- {body}
- {footer}
- </div>
- <ExperimentWizardGuide />
- </div>
- ) : (
- <div className="space-y-6">
- {stepper}
- {body}
- {footer}
- </div>
- )}
+ <div className="@container flex flex-1 flex-col bg-bg-light">
+ <div className="grid flex-1 grid-cols-1 grid-rows-[auto_1fr_auto] gap-6 px-6 pt-6 pb-6 @2xl:pb-0 @2xl:grid-cols-[minmax(0,1fr)_14rem] @2xl:grid-rows-[auto_1fr] @5xl:grid-cols-[minmax(14rem,1fr)_minmax(0,48rem)_minmax(14rem,1fr)]">
+ <div className={mainColumn}>
+ {header}
+ {stepper}
+ </div>
+ <div className={cn(mainColumn, 'flex flex-col')}>
+ {body}
+ {footer}
+ </div>
+ <aside className="w-full max-w-3xl min-w-0 justify-self-center @2xl:col-start-2 @2xl:row-start-2 @2xl:max-w-80 @2xl:justify-self-start @5xl:col-start-3">
+ <ExperimentWizardGuide />
+ </aside>
</div>
</div>
)
diff --git a/frontend/src/scenes/experiments/ExperimentWizard/ExperimentWizardGuide.tsx b/frontend/src/scenes/experiments/ExperimentWizard/ExperimentWizardGuide.tsx
index 5032d57c91e7..dc8e85c6604a 100644
--- a/frontend/src/scenes/experiments/ExperimentWizard/ExperimentWizardGuide.tsx
+++ b/frontend/src/scenes/experiments/ExperimentWizard/ExperimentWizardGuide.tsx
@@ -1,7 +1,14 @@
import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
-import { IconLightBulb, IconX } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
+import { IconLightBulb, IconSparkles } from '@posthog/icons'
+import { LemonButton, lemonToast } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { useMaxTool } from 'scenes/max/useMaxTool'
+import { urls } from 'scenes/urls'
import { ExperimentWizardStep, experimentWizardLogic } from './experimentWizardLogic'
@@ -20,8 +27,9 @@ const GUIDE_CONTENT: Record<ExperimentWizardStep, GuideContent> = {
],
},
variants: {
- title: 'Configuring variants',
+ title: 'Variants',
tips: [
+ "A variant is one version of what you're testing, like your current page (control) and the change you want to try (test).",
'The more variants you add, the more traffic you need to get reliable results.',
'It is recommended to split traffic equally between variants. The lower the traffic a variant has, the longer it will take to reach reliable results.',
],
@@ -38,36 +46,64 @@ const GUIDE_CONTENT: Record<ExperimentWizardStep, GuideContent> = {
export function ExperimentWizardGuide(): JSX.Element {
const { currentStep } = useValues(experimentWizardLogic)
- const { toggleGuide } = useActions(experimentWizardLogic)
+ const { reportExperimentWizardAskAiClicked } = useActions(eventUsageLogic)
+
+ const { openMax } = useMaxTool({
+ identifier: 'create_experiment',
+ initialMaxPrompt: 'Create an experiment for ',
+ callback: (toolOutput: { experiment_id?: string | number; error?: string }) => {
+ if (toolOutput?.error || !toolOutput?.experiment_id) {
+ lemonToast.error(`Failed to create experiment: ${toolOutput?.error || 'Unknown error'}`)
+ return
+ }
+ router.actions.push(urls.experiment(toolOutput.experiment_id))
+ },
+ // Recorded as `ai_entry_point` on `experiment created`, to attribute AI-created experiments to this button
+ context: { entry_point: 'experiment_wizard_guide' },
+ })
const guide = GUIDE_CONTENT[currentStep]
return (
- <div className="sticky top-6 space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-1.5 text-sm font-medium text-secondary">
- <IconLightBulb className="size-4" />
- Guide
- </div>
- <LemonButton
- type="tertiary"
- size="xsmall"
- icon={<IconX />}
- onClick={toggleGuide}
- tooltip="Hide guide"
- />
+ <div className="sticky top-6 rounded-lg border border-dashed border-primary bg-bg-light p-4 flex flex-col gap-3">
+ <div className="flex items-center gap-2">
+ <IconLightBulb className="size-4 shrink-0" />
+ <h4 className="m-0 text-sm font-semibold">{guide.title}</h4>
</div>
- <h4 className="text-sm font-semibold">{guide.title}</h4>
-
- <ul className="space-y-2.5">
+ <ul className="m-0 pl-5 list-disc text-xs text-muted leading-relaxed space-y-1.5">
{guide.tips.map((tip, i) => (
- <li key={i} className="flex gap-2 text-[13px] leading-relaxed text-secondary">
- <span className="text-muted select-none shrink-0">&#8226;</span>
- <span>{tip}</span>
- </li>
+ <li key={i}>{tip}</li>
))}
</ul>
+
+ {openMax && (
+ <div className="flex flex-col gap-2 pt-3 border-t border-dashed border-primary">
+ <div className="text-sm text-default">Rather describe it? PostHog AI can set it up for you.</div>
+ <div>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconSparkles className="text-ai" />}
+ onClick={() => {
+ reportExperimentWizardAskAiClicked(currentStep)
+ openMax()
+ }}
+ data-attr="experiment-wizard-guide-ask-ai"
+ >
+ {/* Skip the animation in Storybook so visual snapshots don't flake on the moving gradient */}
+ <span
+ className={cn(
+ 'rainbow-text font-semibold',
+ !(inStorybook() || inStorybookTestRunner()) && 'rainbow-text-animating'
+ )}
+ >
+ Ask AI
+ </span>
+ </LemonButton>
+ </div>
+ </div>
+ )}
</div>
)
}
diff --git a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx
index a8b5d0112c6b..ae528b0a7d3f 100644
--- a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx
@@ -104,55 +104,6 @@ const apiMocks = {
},
}
-describe('guide panel localStorage persistence', () => {
- let logic: ReturnType<typeof experimentWizardLogic.build>
-
- beforeEach(() => {
- localStorage.clear()
- useMocks(apiMocks)
- initKeaTests()
-
- featureFlagsLogic.mount()
- experimentsLogic.mount()
- createExperimentLogic().mount()
- })
-
- afterEach(() => {
- logic?.unmount()
- })
-
- it.each([
- { stored: null, expected: true, label: 'defaults to true when nothing stored' },
- { stored: 'true', expected: true, label: 'reads true from localStorage' },
- { stored: 'false', expected: false, label: 'reads false from localStorage' },
- { stored: 'other', expected: false, label: 'treats non-true strings as false' },
- ])('$label', async ({ stored, expected }) => {
- if (stored !== null) {
- localStorage.setItem('experiment-wizard-show-guide', stored)
- }
-
- logic = experimentWizardLogic()
- logic.mount()
-
- await expectLogic(logic).toMatchValues({ showGuide: expected })
- })
-
- it('persists to localStorage when toggled', async () => {
- logic = experimentWizardLogic()
- logic.mount()
-
- await expectLogic(logic).toMatchValues({ showGuide: true })
-
- logic.actions.toggleGuide()
- await expectLogic(logic).toMatchValues({ showGuide: false })
- expect(localStorage.getItem('experiment-wizard-show-guide')).toEqual('false')
-
- logic.actions.toggleGuide()
- await expectLogic(logic).toMatchValues({ showGuide: true })
- expect(localStorage.getItem('experiment-wizard-show-guide')).toEqual('true')
- })
-})
-
describe('experimentWizardLogic', () => {
describe('feature flag input flow', () => {
let logic: ReturnType<typeof experimentWizardLogic.build>
diff --git a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts
index f51b200a522c..11301f6cdaf3 100644
--- a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts
@@ -20,9 +20,6 @@ import { getExperimentVariants, getFlagVariants } from '../utils'
export type ExperimentWizardStep = 'about' | 'variants' | 'analytics'
-const SHOW_GUIDE_STORAGE_KEY = 'experiment-wizard-show-guide'
-const SHOW_GUIDE_DEFAULT = true
-
const WIZARD_STEPS: ExperimentWizardStep[] = ['about', 'variants', 'analytics']
export function stepStorageKey(): string {
@@ -70,7 +67,6 @@ export interface experimentWizardLogicValues {
isFirstStep: boolean
isLastStep: boolean
linkedFeatureFlag: FeatureFlagType | null
- showGuide: boolean
stepNumber: number
stepValidationErrors: Record<ExperimentWizardStep, string[]>
}
@@ -118,15 +114,8 @@ export interface experimentWizardLogicActions {
secondary: ExperimentMetricUnion[]
}
} // createExperimentLogic
- reportExperimentWizardGuideToggled: (
- visible: boolean,
- currentStep: string
- ) => {
- currentStep: string
- visible: boolean
- } // eventUsageLogic
- reportExperimentWizardStarted: (guideVisible: boolean) => {
- guideVisible: boolean
+ reportExperimentWizardStarted: () => {
+ value: true
} // eventUsageLogic
loadFeatureFlagsForAutocomplete: () => {
value: true
@@ -171,9 +160,6 @@ export interface experimentWizardLogicActions {
setStep: (step: ExperimentWizardStep) => {
step: ExperimentWizardStep
}
- toggleGuide: () => {
- value: true
- }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -242,7 +228,7 @@ export const experimentWizardLogic = kea<experimentWizardLogicType>([
selectExistingFeatureFlagModalLogic,
['loadFeatureFlagsForAutocomplete', 'loadFeatureFlagsSuccess'],
eventUsageLogic,
- ['reportExperimentWizardStarted', 'reportExperimentWizardGuideToggled'],
+ ['reportExperimentWizardStarted'],
],
})),
@@ -256,7 +242,6 @@ export const experimentWizardLogic = kea<experimentWizardLogicType>([
_applyStep: (step: ExperimentWizardStep) => ({ step }),
markStepDeparted: (step: ExperimentWizardStep) => ({ step }),
resetWizard: true,
- toggleGuide: true,
setLinkedFeatureFlag: (flag: FeatureFlagType | null) => ({ flag }),
}),
@@ -272,19 +257,6 @@ export const experimentWizardLogic = kea<experimentWizardLogicType>([
saveExperimentSuccess: () => false,
},
],
- showGuide: [
- (() => {
- try {
- const stored = localStorage.getItem(SHOW_GUIDE_STORAGE_KEY)
- return stored === null ? SHOW_GUIDE_DEFAULT : stored === 'true'
- } catch {
- return SHOW_GUIDE_DEFAULT
- }
- })(),
- {
- toggleGuide: (state) => !state,
- },
- ],
currentStep: [
readStoredStep(),
{
@@ -413,14 +385,6 @@ export const experimentWizardLogic = kea<experimentWizardLogicType>([
// ignore
}
},
- toggleGuide: () => {
- actions.reportExperimentWizardGuideToggled(values.showGuide, values.currentStep)
- try {
- localStorage.setItem(SHOW_GUIDE_STORAGE_KEY, JSON.stringify(values.showGuide))
- } catch {
- // Ignore localStorage errors
- }
- },
loadFeatureFlagsSuccess: ({
featureFlags,
}: {
@@ -475,9 +439,9 @@ export const experimentWizardLogic = kea<experimentWizardLogicType>([
},
})),
- events(({ actions, values }) => ({
+ events(({ actions }) => ({
afterMount: () => {
- actions.reportExperimentWizardStarted(values.showGuide)
+ actions.reportExperimentWizardStarted()
actions.loadFeatureFlagsForAutocomplete()
},
})),
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 973f7ac72793..eeb4ead8d3a8 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -1083,6 +1083,7 @@ class ExperimentService:
event_source: EventSource | None = None,
allow_unknown_events: bool = False,
creation_mode: ExperimentCreationMode = "new",
+ analytics_properties: dict[str, Any] | None = None,
) -> Experiment:
"""Create experiment with full validation and defaults."""
# Seed the dedup set with uuids the inline metrics must not collide with:
@@ -1239,6 +1240,7 @@ class ExperimentService:
event_source=event_source,
allow_unknown_events=allow_unknown_events,
creation_mode=creation_mode,
+ analytics_properties=analytics_properties,
)
)
@@ -1252,6 +1254,7 @@ class ExperimentService:
event_source: EventSource | None,
allow_unknown_events: bool,
creation_mode: ExperimentCreationMode,
+ analytics_properties: dict[str, Any] | None = None,
) -> None:
# Post-commit: the experiment is already persisted, so analytics failures must not break the request.
try:
@@ -1261,6 +1264,7 @@ class ExperimentService:
event_source=event_source,
allow_unknown_events=allow_unknown_events,
creation_mode=creation_mode,
+ analytics_properties=analytics_properties,
)
except Exception:
logger.exception("experiment_created_analytics_failed", experiment_id=experiment.id)
@@ -1297,6 +1301,7 @@ class ExperimentService:
event_source: EventSource | None,
allow_unknown_events: bool = False,
creation_mode: ExperimentCreationMode,
+ analytics_properties: dict[str, Any] | None = None,
) -> None:
request = serializer_context.get("request") if serializer_context else None
if request is None and event_source is None:
@@ -1310,6 +1315,8 @@ class ExperimentService:
analytics_metadata["allow_unknown_events"] = True
if request is not None:
analytics_metadata.update(_deprecated_fields_in_request(request))
+ if analytics_properties:
+ analytics_metadata.update(analytics_properties)
report_user_action(
self.user,
diff --git a/products/experiments/backend/max_tools.py b/products/experiments/backend/max_tools.py
index 9c65473bd2c9..a257988a328c 100644
--- a/products/experiments/backend/max_tools.py
+++ b/products/experiments/backend/max_tools.py
@@ -18,6 +18,9 @@ from ee.hogai.context.experiment.context import ExperimentContext
from ee.hogai.tool import MaxTool
from ee.hogai.tool_errors import MaxToolAccessDeniedError
+# Pages that pass an `entry_point`. It comes from the client, so other values aren't recorded on `experiment created`
+AI_ENTRY_POINTS = frozenset({"experiment_wizard_guide", "experiments_list"})
+
CREATE_EXPERIMENT_TOOL_DESCRIPTION = dedent("""
Use this tool to create A/B test experiments that measure the impact of changes.
@@ -114,6 +117,11 @@ class CreateExperimentTool(MaxTool):
if not feature_flag_key or not feature_flag_key.strip():
return "Feature flag key cannot be empty", {"error": "invalid_flag_key"}
+ entry_point = self.context.get("entry_point") if isinstance(self.context, dict) else None
+ analytics_properties = (
+ {"ai_entry_point": entry_point} if isinstance(entry_point, str) and entry_point in AI_ENTRY_POINTS else None
+ )
+
@database_sync_to_async
def create_experiment() -> Experiment:
existing_experiment = Experiment.objects.filter(team=self._team, name=name, deleted=False).first()
@@ -147,6 +155,7 @@ class CreateExperimentTool(MaxTool):
description=description or "",
type=type,
event_source=EventSource.POSTHOG_AI,
+ analytics_properties=analytics_properties,
)
try:
diff --git a/products/experiments/backend/test/test_max_tools.py b/products/experiments/backend/test/test_max_tools.py
index f4e885e562cc..d40f18eeec77 100644
--- a/products/experiments/backend/test/test_max_tools.py
+++ b/products/experiments/backend/test/test_max_tools.py
@@ -2,6 +2,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import ANY, AsyncMock, MagicMock, patch
from asgiref.sync import sync_to_async
+from parameterized import parameterized
from posthog.schema import (
MaxExperimentMetricResult,
@@ -182,6 +183,41 @@ class TestCreateExperimentTool(APIBaseTest):
assert mock_report_user_action.call_args.kwargs["team"] == self.team
assert mock_report_user_action.call_args.kwargs["request"] is None
+ @parameterized.expand(
+ [
+ ("known", "experiment_wizard_guide", "experiment_wizard_guide"),
+ ("unknown", "x" * 500, None),
+ ("not_a_string", ["experiment_wizard_guide"], None),
+ ]
+ )
+ @patch("django.db.transaction.on_commit", side_effect=lambda func: func())
+ @patch("products.experiments.backend.experiment_service.report_user_action")
+ async def test_create_experiment_records_only_known_ai_entry_points(
+ self,
+ case: str,
+ entry_point: object,
+ expected: str | None,
+ mock_report_user_action: MagicMock,
+ _mock_on_commit: MagicMock,
+ ) -> None:
+ flag_key = f"entry-point-{case.replace('_', '-')}"
+ await self._create_multivariate_flag(key=flag_key)
+ context_manager = MagicMock()
+ context_manager.get_contextual_tools.return_value = {"create_experiment": {"entry_point": entry_point}}
+ tool = CreateExperimentTool(
+ team=self.team,
+ user=self.user,
+ state=AssistantState(messages=[]),
+ context_manager=context_manager,
+ config={},
+ )
+
+ await tool._arun_impl(name=f"Entry point {case}", feature_flag_key=flag_key)
+
+ metadata = mock_report_user_action.call_args.args[2]
+ assert metadata["source"] == EventSource.POSTHOG_AI
+ assert metadata.get("ai_entry_point") == expected
+
async def test_create_experiment_flag_already_used(self):
flag = await self._create_multivariate_flag(key="used-flag")
await Experiment.objects.acreate(
diff --git a/products/experiments/frontend/scenes/ExperimentsScene.tsx b/products/experiments/frontend/scenes/ExperimentsScene.tsx
index 6a4064d0b3ad..f1e600a7bf37 100644
--- a/products/experiments/frontend/scenes/ExperimentsScene.tsx
+++ b/products/experiments/frontend/scenes/ExperimentsScene.tsx
@@ -25,6 +25,7 @@ import { atColumn, createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTa
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
import { pluralize } from 'lib/utils/strings'
import stringWithWBR from 'lib/utils/stringWithWBR'
@@ -709,6 +710,7 @@ const ExperimentsTable = ({
export function ExperimentsScene(): JSX.Element {
const { tab } = useValues(experimentsLogic)
const { setExperimentsTab, loadExperiments } = useActions(experimentsLogic)
+ const { reportExperimentsListAiBadgeClicked } = useActions(eventUsageLogic)
const [duplicateModalExperiment, setDuplicateModalExperiment] = useState<Experiment | null>(null)
const [copyToProjectModalExperiment, setCopyToProjectModalExperiment] = useState<Experiment | null>(null)
const [surveyModalExperiment, setSurveyModalExperiment] = useState<Experiment | null>(null)
@@ -768,7 +770,9 @@ export function ExperimentsScene(): JSX.Element {
}}
position="bottom-right"
active={true}
- context={{}}
+ onMaxOpen={reportExperimentsListAiBadgeClicked}
+ // Recorded as `ai_entry_point` on `experiment created`
+ context={{ entry_point: 'experiments_list' }}
>
<Shortcut
name="NewExperiment"