:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import {
MakeLogicType,
BuiltLogic,
actions,
connect,
kea,
listeners,
path,
props,
reducers,
selectors,
sharedListeners,
} from 'kea'
import type { BreakPointFunction } from 'kea'
import { router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import { superpowersLogic } from 'lib/components/Superpowers/superpowersLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { ActivityScope, Breadcrumb, Experiment, ProjectTreeRef, type UserType } from '~/types'
import type { ExperimentIdType } from '~/types'
import { NEW_EXPERIMENT } from 'products/experiments/frontend/constants'
import { isLaunched } from 'products/experiments/frontend/experimentStatus'
import {
type ExperimentLogicProps,
type experimentLogicType,
FORM_MODES,
type FormModes,
experimentLogic,
} from './experimentLogic'
import { EXPERIMENT_RECORDINGS_DEEP_LINK_PARAMS } from './ExperimentView/experimentRecordingsDeepLink'
import { stepStorageKey } from './ExperimentWizard/experimentWizardLogic'
import { modalsLogic } from './modalsLogic'
import { isLegacyExperiment } from './utils'
function reportExperimentTabViewed(experimentId: ExperimentIdType, tab: string): void {
posthog.capture('experiment tab viewed', {
experiment_id: experimentId,
tab,
})
}
export const EXPERIMENT_TABS = [
'metrics',
'health',
'settings',
'code',
'variants',
'recordings',
'feedback',
'history',
'health-debug',
] as const
export type ExperimentTab = (typeof EXPERIMENT_TABS)[number]
export const DEFAULT_EXPERIMENT_TAB: ExperimentTab = 'metrics'
// The single source of truth for which tabs an experiment renders, shared by the views and by the
// scene logic that clamps the URL-driven tab. Keep it in sync with the tab lists in ExperimentView
// and LegacyExperimentView — a tab the views render but this omits gets clamped away on load.
export const getAvailableExperimentTabs = (
experiment: Experiment,
{ canSeeHealth = false, canSeeHealthDebug = false }: { canSeeHealth?: boolean; canSeeHealthDebug?: boolean } = {}
): ExperimentTab[] => {
// Legacy experiments render a reduced, read-only view with only these two tabs.
if (isLegacyExperiment(experiment)) {
return ['metrics', 'variants']
}
const isDraft = !isLaunched(experiment) && !experiment.archived
return EXPERIMENT_TABS.filter((tab) => {
switch (tab) {
case 'code':
// Implementation code is only meaningful once the experiment is launched.
return !isDraft
case 'feedback':
return !!experiment.feature_flag
case 'health':
return canSeeHealth
case 'health-debug':
return canSeeHealthDebug
default:
return true
}
})
}
// Staff only. While impersonating, the user is the customer: superpowers are off for the staff member at the keyboard
// and the flag evaluates on the customer, so the impersonation itself counts.
export const canSeeHealthDebugTab = ({
superpowersEnabled,
isImpersonated,
healthFindingsEnabled,
}: {
superpowersEnabled: boolean
isImpersonated: boolean
healthFindingsEnabled: boolean
}): boolean => isImpersonated || (superpowersEnabled && healthFindingsEnabled)
// kea-router coerces numeric-looking params to numbers, so check the type before membership
const isExperimentTab = (tab: unknown): tab is ExperimentTab =>
typeof tab === 'string' && (EXPERIMENT_TABS as readonly string[]).includes(tab)
const getExperimentTabFromSearchParams = (searchParams: Record<string, any>): ExperimentTab => {
if (isExperimentTab(searchParams.tab)) {
return searchParams.tab
}
if (searchParams.activity) {
// Activity-log deep links (?activity=<id>) point at an entry on the history tab
return 'history'
}
return DEFAULT_EXPERIMENT_TAB
}
// Resolves the tab a URL asks for, clamped to what this experiment actually renders. The clamp only
// applies once the experiment is loaded: while it loads, availability is provisional, so clamping
// could bounce a valid deep link (e.g. ?tab=code to a launched experiment still reading as the draft
// placeholder). The availableTabs subscription catches the load-completes-after-navigation case.
const resolveExperimentTab = (
query: Record<string, any>,
values: { experimentLoaded: boolean; availableTabs: ExperimentTab[] }
): ExperimentTab => {
const requested = getExperimentTabFromSearchParams(query)
if (values.experimentLoaded && !values.availableTabs.includes(requested)) {
return DEFAULT_EXPERIMENT_TAB
}
return requested
}
export interface ExperimentSceneLogicProps extends ExperimentLogicProps {}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentSceneLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
superpowersEnabled: boolean | undefined // superpowersLogic
user: UserType | null // userLogic
activeTabKey: ExperimentTab
availableTabs: ExperimentTab[]
breadcrumbs: Breadcrumb[]
canSeeHealth: boolean
canSeeHealthDebug: boolean
experiment: Experiment
experimentId: ExperimentIdType
experimentLoaded: boolean
experimentLogicRef: {
logic: BuiltLogic<experimentLogicType>
props: ExperimentLogicProps
unmount: () => void
} | null
experimentMissing: boolean
experimentMissingSelector: ((state: any, props?: ExperimentLogicProps | undefined) => boolean) | undefined
experimentSelector: ((state: any, props?: ExperimentLogicProps | undefined) => Experiment) | undefined
formMode: FormModes
isExperimentLaunched: boolean
isExperimentLaunchedSelector: ((state: any, props?: ExperimentLogicProps | undefined) => boolean) | undefined
projectTreeRef: ProjectTreeRef
sidePanelContext: SidePanelSceneContext | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentSceneLogicActions {
resetExperimentState: (experimentConfig: Experiment) => {
experimentConfig: Experiment
}
setActiveTabKey: (activeTabKey: ExperimentTab) => {
activeTabKey:
| 'code'
| 'feedback'
| 'health'
| 'health-debug'
| 'history'
| 'metrics'
| 'recordings'
| 'settings'
| 'variants'
}
setEditMode: (editing: boolean) => {
editing: boolean
}
setExperimentLogicRef: (
logic: BuiltLogic<experimentLogicType> | null,
unmount: (() => void) | null,
logicProps: ExperimentLogicProps | null
) => {
logic: BuiltLogic<experimentLogicType> | null
logicProps: ExperimentLogicProps | null
unmount: (() => void) | null
}
setSceneState: (
experimentId: Experiment['id'],
formMode: FormModes
) => {
experimentId: ExperimentIdType
formMode: FormModes
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentSceneLogicMeta {
sharedListeners: {
ensureExperimentLogicMounted: (
payload: any,
breakpoint: BreakPointFunction,
action: {
type: string
payload: any
},
previousState: any
) => void | Promise<void>
}
__keaTypeGenInternalSelectorTypes: {
experimentSelector: (
experimentLogicRef: {
logic: BuiltLogic<experimentLogicType>
props: ExperimentLogicProps
unmount: () => void
} | null
) => ((state: any, props?: ExperimentLogicProps | undefined) => Experiment) | undefined
experiment: (arg: Experiment | null | undefined) => Experiment
experimentMissingSelector: (
experimentLogicRef: {
logic: BuiltLogic<experimentLogicType>
props: ExperimentLogicProps
unmount: () => void
} | null
) => ((state: any, props?: ExperimentLogicProps | undefined) => boolean) | undefined
experimentMissing: (arg: boolean | undefined) => boolean
isExperimentLaunchedSelector: (
experimentLogicRef: {
logic: BuiltLogic<experimentLogicType>
props: ExperimentLogicProps
unmount: () => void
} | null
) => ((state: any, props?: ExperimentLogicProps | undefined) => boolean) | undefined
isExperimentLaunched: (arg: boolean | undefined) => boolean
canSeeHealth: (user: UserType | null, featureFlags: FeatureFlagsSet) => boolean
canSeeHealthDebug: (
superpowersEnabled: boolean | undefined,
user: UserType | null,
featureFlags: FeatureFlagsSet
) => boolean
availableTabs: (experiment: Experiment, canSeeHealth: boolean, canSeeHealthDebug: boolean) => ExperimentTab[]
experimentLoaded: (experiment: Experiment) => boolean
breadcrumbs: (experiment: Experiment, experimentId: ExperimentIdType) => Breadcrumb[]
sidePanelContext: (experimentId: ExperimentIdType) => SidePanelSceneContext | null
projectTreeRef: (experimentId: ExperimentIdType) => ProjectTreeRef
}
}
export type experimentSceneLogicType = MakeLogicType<
experimentSceneLogicValues,
experimentSceneLogicActions,
ExperimentSceneLogicProps,
experimentSceneLogicMeta
>
export const experimentSceneLogic = kea<experimentSceneLogicType>([
props({} as ExperimentSceneLogicProps),
path(['scenes', 'experiments', 'experimentSceneLogic']),
connect(() => ({
values: [superpowersLogic, ['superpowersEnabled'], featureFlagLogic, ['featureFlags'], userLogic, ['user']],
})),
actions({
setActiveTabKey: (activeTabKey: ExperimentTab) => ({ activeTabKey }),
setSceneState: (experimentId: Experiment['id'], formMode: FormModes) => ({ experimentId, formMode }),
setExperimentLogicRef: (
logic: BuiltLogic<experimentLogicType> | null,
unmount: null | (() => void),
logicProps: ExperimentLogicProps | null
) => ({
logic,
unmount,
logicProps,
}),
setEditMode: (editing: boolean) => ({ editing }),
resetExperimentState: (experimentConfig: Experiment) => ({ experimentConfig }),
}),
reducers({
// setActiveTabKey is deliberately the only writer, so a listener on it sees every tab
// change; URL-driven changes are dispatched through it in urlToAction below
activeTabKey: [
DEFAULT_EXPERIMENT_TAB as ExperimentTab,
{
setActiveTabKey: (_, { activeTabKey }) => activeTabKey,
},
],
experimentId: [
(props: ExperimentSceneLogicProps) => props.experimentId ?? 'new',
{
setSceneState: (_, { experimentId }) => experimentId,
},
],
formMode: [
(props: ExperimentSceneLogicProps) => props.formMode ?? FORM_MODES.update,
{
setSceneState: (_, { formMode }) => formMode,
},
],
experimentLogicRef: [
null as null | {
logic: BuiltLogic<experimentLogicType>
unmount: () => void
props: ExperimentLogicProps
},
{
setExperimentLogicRef: (_, { logic, unmount, logicProps }) =>
logic && unmount && logicProps ? { logic, unmount, props: logicProps } : null,
},
],
}),
selectors({
experimentSelector: [
(s) => [s.experimentLogicRef],
(
experimentLogicRef: {
logic: BuiltLogic<experimentLogicType>
props: ExperimentLogicProps
unmount: () => void
} | null
) => experimentLogicRef?.logic.selectors.experiment,
],
experiment: [
(s) => [
(state, props) => {
try {
return s.experimentSelector?.(state, props)?.(state, props)
} catch {
return null
}
},
],
(experiment: Experiment | null | undefined): Experiment => (experiment ?? NEW_EXPERIMENT) as Experiment,
],
experimentMissingSelector: [
(s) => [s.experimentLogicRef],
(
experimentLogicRef: {
logic: BuiltLogic<experimentLogicType>
props: ExperimentLogicProps
unmount: () => void
} | null
) => experimentLogicRef?.logic.selectors.experimentMissing,
],
experimentMissing: [
(s) => [
(state, props) => {
try {
return s.experimentMissingSelector?.(state, props)?.(state, props)
} catch {
return false
}
},
],
(experimentMissing: boolean | undefined): boolean => experimentMissing ?? false,
],
isExperimentLaunchedSelector: [
(s) => [s.experimentLogicRef],
(
experimentLogicRef: {
logic: BuiltLogic<experimentLogicType>
props: ExperimentLogicProps
unmount: () => void
} | null
) => experimentLogicRef?.logic.selectors.isExperimentLaunched,
],
isExperimentLaunched: [
(s) => [
(state, props) => {
try {
return s.isExperimentLaunchedSelector?.(state, props)?.(state, props)
} catch {
return false
}
},
],
(isExperimentLaunched: boolean | undefined): boolean => isExperimentLaunched ?? false,
],
canSeeHealth: [
(s) => [s.user, s.featureFlags],
// The same readers as experimentLogic's `showsHealthFindings`, so the tab shows wherever the findings do.
(user: UserType | null, featureFlags: FeatureFlagsSet): boolean =>
!!featureFlags[FEATURE_FLAGS.EXPERIMENT_HEALTH_FINDINGS] || !!user?.is_impersonated,
],
canSeeHealthDebug: [
(s) => [s.superpowersEnabled, s.user, s.featureFlags],
(superpowersEnabled: boolean | undefined, user: UserType | null, featureFlags: FeatureFlagsSet): boolean =>
canSeeHealthDebugTab({
superpowersEnabled: !!superpowersEnabled,
isImpersonated: !!user?.is_impersonated,
healthFindingsEnabled: !!featureFlags[FEATURE_FLAGS.EXPERIMENT_HEALTH_FINDINGS],
}),
],
availableTabs: [
(s) => [s.experiment, s.canSeeHealth, s.canSeeHealthDebug],
(experiment: Experiment, canSeeHealth: boolean, canSeeHealthDebug: boolean): ExperimentTab[] =>
getAvailableExperimentTabs(experiment, { canSeeHealth, canSeeHealthDebug }),
],
experimentLoaded: [
(s) => [s.experiment],
// While the experiment loads, `experiment` is the NEW_EXPERIMENT placeholder (id 'new'),
// so tab availability derived from it is only provisional. A numeric id means the real
// experiment has arrived and its available tabs are trustworthy.
(experiment: Experiment): boolean => experiment.id !== 'new',
],
breadcrumbs: [
(s) => [s.experiment, s.experimentId],
(experiment: Experiment, experimentId: Experiment['id']): Breadcrumb[] => {
return [
{
key: Scene.Experiments,
name: sceneConfigurations[Scene.Experiments].name || 'Experiments',
path: urls.experiments(),
iconType: sceneConfigurations[Scene.Experiments].iconType || 'default_icon_type',
},
{
key: [Scene.Experiment, experimentId],
name: experiment?.name || 'New Experiment',
iconType: sceneConfigurations[Scene.Experiment].iconType || 'default_icon_type',
},
]
},
],
[SIDE_PANEL_CONTEXT_KEY]: [
(s) => [s.experimentId],
(experimentId: Experiment['id']): SidePanelSceneContext | null => {
return experimentId && experimentId !== 'new'
? {
activity_scope: ActivityScope.EXPERIMENT,
activity_item_id: `${experimentId}`,
}
: null
},
],
projectTreeRef: [
(s) => [s.experimentId],
(experimentId: Experiment['id']): ProjectTreeRef => {
return { type: 'experiment', ref: experimentId === 'new' ? null : String(experimentId) }
},
],
}),
subscriptions(({ values, actions }) => ({
// Fires when the experiment arrives or changes (a draft and its placeholder can share the
// same available set, so keying off availableTabs alone would miss the load). Once loaded,
// its tab set can exclude the URL-driven tab (a launched-only tab on a draft, a legacy
// experiment's reduced set); route the correction through setActiveTabKey so the URL and the
// `experiment tab viewed` event track what the view actually renders.
experiment: () => {
if (values.experimentLoaded && !values.availableTabs.includes(values.activeTabKey)) {
actions.setActiveTabKey(DEFAULT_EXPERIMENT_TAB)
}
},
})),
sharedListeners(({ actions, values }) => ({
ensureExperimentLogicMounted: () => {
const currentProps = values.experimentLogicRef?.props
const desiredExperimentId = values.experimentId ?? 'new'
const desiredFormMode = values.formMode ?? FORM_MODES.update
if (
!values.experimentLogicRef ||
currentProps?.experimentId !== desiredExperimentId ||
currentProps?.formMode !== desiredFormMode
) {
const oldRef = values.experimentLogicRef
const logicProps: ExperimentLogicProps = {
experimentId: desiredExperimentId,
formMode: desiredFormMode,
}
const logic = experimentLogic.build(logicProps)
const unmount = logic.mount()
actions.setExperimentLogicRef(logic, unmount, logicProps)
if (oldRef) {
oldRef.unmount()
}
}
},
})),
listeners(({ selectors, sharedListeners, values }) => ({
// LemonTabs fires onChange on every tab click, including the already-active tab, so a
// dispatch that doesn't change the tab is not a view.
setActiveTabKey: ({ activeTabKey }, _breakpoint, _action, previousState) => {
if (values.experimentId !== 'new' && selectors.activeTabKey(previousState) !== activeTabKey) {
reportExperimentTabViewed(values.experimentId, activeTabKey)
}
},
setSceneState: (payload, breakpoint, action, previousState) => {
sharedListeners.ensureExperimentLogicMounted(payload, breakpoint, action, previousState)
values.experimentLogicRef?.logic.actions.loadExperiment({ triggeredBy: 'page_load' })
},
setEditMode: (payload, breakpoint, action, previousState) => {
sharedListeners.ensureExperimentLogicMounted(payload, breakpoint, action, previousState)
},
resetExperimentState: (payload, breakpoint, action, previousState) => {
sharedListeners.ensureExperimentLogicMounted(payload, breakpoint, action, previousState)
},
})),
trackedActionToUrl(({ values }) => {
const actionToUrl = ({
experimentId = values.experimentId,
formMode = values.formMode,
}: {
experimentId?: Experiment['id']
formMode?: FormModes
}):
| [string, Record<string, any> | string | undefined, Record<string, any> | string | undefined]
| undefined => {
const id = experimentId ?? 'new'
const effectiveFormMode =
id === 'new' && formMode === FORM_MODES.create
? undefined
: formMode === FORM_MODES.update
? undefined
: formMode
// 'new' keeps the full search so the ?metric=/?name= prefill survives, while numeric ids
// keep only the params this scene owns: shared links (?tab=, ?activity=) survive the
// initial setSceneState, and the create flow still drops the prefill params. The
// recordings tab's deep-link params are kept for the same reason: the tab consumes them
// on mount and removes them itself (see `experimentRecordingsDeepLink.ts`).
const currentSearch = router.values.currentLocation.searchParams
const search =
id === 'new'
? currentSearch
: Object.fromEntries(
Object.entries(currentSearch).filter(
([key]) =>
key === 'tab' ||
key === 'activity' ||
EXPERIMENT_RECORDINGS_DEEP_LINK_PARAMS.some((param) => param === key)
)
)
return [urls.experiment(id, effectiveFormMode), search, router.values.hashParams]
}
return {
setSceneState: actionToUrl,
setActiveTabKey: ({ activeTabKey }) => {
const searchParams = { ...router.values.searchParams }
if (activeTabKey === DEFAULT_EXPERIMENT_TAB) {
delete searchParams.tab
} else {
searchParams.tab = activeTabKey
}
// The activity deep-link param belongs to the history tab; kept on another tab it
// would resolve the tab straight back to history on the next URL pass.
if (activeTabKey !== 'history') {
delete searchParams.activity
}
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
},
}
}),
urlToAction(({ actions, values }) => ({
'/experiments/:id': ({ id }, query, __, currentLocation, previousLocation) => {
// Ignore sub-routes like /experiments/shared-metrics/new
// The :id parameter should only be 'new' or a number, not strings like 'shared-metrics'
if (!id || (id !== 'new' && isNaN(parseInt(id, 10)))) {
return
}
const didPathChange = currentLocation.initial || currentLocation.pathname !== previousLocation?.pathname
const targetTab = resolveExperimentTab(query, values)
if (id && didPathChange) {
const parsedId = id === 'new' ? 'new' : parseInt(id)
const formMode = parsedId === 'new' ? FORM_MODES.create : FORM_MODES.update
const existingProps = values.experimentLogicRef?.props
const matchesExistingLogic =
existingProps?.experimentId === parsedId && existingProps?.formMode === formMode
const isSameSceneState = values.experimentId === parsedId && values.formMode === formMode
actions.setEditMode(false)
// The previous experimentLogic (and with it the global modalsLogic) stays mounted
// across navigation, so a modal left open would reappear on the next experiment.
modalsLogic.findMounted()?.actions.closeAllModals()
if (!currentLocation.initial && matchesExistingLogic && isSameSceneState) {
// Same experiment, already mounted — skip the full reload, but still run the
// page-load stale check so a warming-up experiment refreshes on in-app return.
values.experimentLogicRef?.logic.actions.refreshStaleResultsOnReentry()
} else {
actions.setSceneState(parsedId, formMode)
// The setActiveTabKey dispatch below reports tab changes; a landing on the
// already-active tab dispatches nothing, so it is reported here instead.
if (parsedId !== 'new' && targetTab === values.activeTabKey) {
reportExperimentTabViewed(parsedId, targetTab)
}
if (parsedId === 'new') {
// Only reset if we're not already viewing a new experiment (tab switch scenario)
const shouldReset = currentLocation.initial || values.experimentId !== 'new'
if (shouldReset) {
// Clear wizard step before the wizard mounts so it starts on 'about'
try {
sessionStorage.removeItem(stepStorageKey())
} catch {
// ignore
}
actions.resetExperimentState({
...NEW_EXPERIMENT,
metrics: query.metric ? [query.metric] : [],
name: query.name ?? '',
})
}
}
}
}
if (targetTab !== values.activeTabKey) {
actions.setActiveTabKey(targetTab)
}
},
'/experiments/:id/:formMode': ({ id, formMode }, query, __, currentLocation, previousLocation) => {
// Ignore routes where id is not a valid experiment identifier (number or 'new')
// This prevents matching routes like /experiments/shared-metrics/new
if (!id || (id !== 'new' && isNaN(parseInt(id, 10)))) {
return
}
const didPathChange = currentLocation.initial || currentLocation.pathname !== previousLocation?.pathname
const targetTab = resolveExperimentTab(query, values)
if (id && didPathChange) {
const parsedId = id === 'new' ? 'new' : parseInt(id)
const parsedFormMode =
formMode && Object.values(FORM_MODES).includes(formMode as FormModes)
? (formMode as FormModes)
: parsedId === 'new'
? FORM_MODES.create
: FORM_MODES.update
const existingProps = values.experimentLogicRef?.props
const matchesExistingLogic =
existingProps?.experimentId === parsedId && existingProps?.formMode === parsedFormMode
const isSameSceneState = values.experimentId === parsedId && values.formMode === parsedFormMode
actions.setEditMode(false)
modalsLogic.findMounted()?.actions.closeAllModals()
if (!currentLocation.initial && matchesExistingLogic && isSameSceneState) {
// Same experiment, already mounted — skip the full reload, but still run the
// page-load stale check so a warming-up experiment refreshes on in-app return.
values.experimentLogicRef?.logic.actions.refreshStaleResultsOnReentry()
} else {
actions.setSceneState(parsedId, parsedFormMode)
}
}
if (targetTab !== values.activeTabKey) {
actions.setActiveTabKey(targetTab)
}
},
})),
])