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): put the active experiment tab in the URL (#79726)

Marcel Poelker3dbd74fa2f08
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 1b72c68b7e72..70500a993892 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1214,10 +1214,12 @@ export const productUrls = {
options?: {
metric?: ExperimentMetric
name?: string
+ tab?: string
}
): string => {
const baseUrl = formMode ? `/experiments/${id}/${formMode}` : `/experiments/${id}`
- return `${baseUrl}${options ? `?${toParams(options)}` : ''}`
+ const params = options ? toParams(options) : ''
+ return params ? `${baseUrl}?${params}` : baseUrl
},
experiments: (): string => '/experiments',
experimentsSharedMetrics: (): string => '/experiments/shared-metrics',
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx
index 34de6efd4706..e0e191abf5c4 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx
@@ -15,7 +15,7 @@ import { ActivityScope } from '~/types'
import { EmptyMetricsPanel } from '../ExperimentForm/MetricsPanel/EmptyMetricsPanel'
import { ExperimentImplementationDetails } from '../ExperimentImplementationDetails'
import { experimentLogic } from '../experimentLogic'
-import { experimentSceneLogic } from '../experimentSceneLogic'
+import { DEFAULT_EXPERIMENT_TAB, type ExperimentTab, experimentSceneLogic } from '../experimentSceneLogic'
import { ExperimentMetricModal } from '../Metrics/ExperimentMetricModal'
import { experimentMetricModalLogic } from '../Metrics/experimentMetricModalLogic'
import { MetricSourceModal } from '../Metrics/MetricSourceModal'
@@ -102,9 +102,7 @@ const VariantsTab = (): JSX.Element => {
}
export function ExperimentView(): JSX.Element {
- const { experimentLoading, experimentId, experiment, isExperimentDraft, exposureCriteria, showDebugPanel } =
- useValues(experimentLogic)
- const { featureFlags } = useValues(featureFlagLogic)
+ const { experimentLoading, experimentId, experiment, exposureCriteria, showDebugPanel } = useValues(experimentLogic)
const {
setExperiment,
setExposureCriteria,
@@ -115,7 +113,7 @@ export function ExperimentView(): JSX.Element {
removeMetric,
} = useActions(experimentLogic)
- const { activeTabKey } = useValues(experimentSceneLogic)
+ const { activeTabKey, availableTabs } = useValues(experimentSceneLogic)
const { setActiveTabKey } = useActions(experimentSceneLogic)
const { closeExperimentMetricModal } = useActions(experimentMetricModalLogic)
@@ -127,56 +125,24 @@ export function ExperimentView(): JSX.Element {
}
// Ordered as: results (Metrics), configuration (Settings, Code, Variants),
- // feature tabs (Recordings, User feedback), audit trail (History)
- const tabs: LemonTab<string>[] = [
- {
- key: 'metrics',
- label: 'Metrics',
- content: <MetricsTab />,
- },
- {
- key: 'settings',
- label: 'Settings',
- content: <SettingsTab />,
- },
- ...(!isExperimentDraft
- ? [
- {
- key: 'code',
- label: 'Code',
- content: <CodeTab />,
- },
- ]
- : []),
- {
- key: 'variants',
- label: 'Variants',
- content: <VariantsTab />,
- },
- ...(featureFlags[FEATURE_FLAGS.EXPERIMENT_RECORDINGS_TAB]
- ? [
- {
- key: 'recordings',
- label: 'Recordings',
- content: <ExperimentReplayTab experiment={experiment} />,
- },
- ]
- : []),
- ...(experiment.feature_flag
- ? [
- {
- key: 'feedback',
- label: 'User feedback',
- content: <ExperimentFeedbackTab experiment={experiment} />,
- },
- ]
- : []),
- {
- key: 'history',
- label: 'History',
- content: <ActivityLog scope={ActivityScope.EXPERIMENT} id={experimentId} />,
- },
- ]
+ // feature tabs (Recordings, User feedback), audit trail (History). Which of these actually
+ // render is resolved by experimentSceneLogic's availableTabs, so the tab set, the URL, and the
+ // tracked tab stay in agreement.
+ const tabs: LemonTab<ExperimentTab>[] = (
+ [
+ { key: 'metrics', label: 'Metrics', content: <MetricsTab /> },
+ { key: 'settings', label: 'Settings', content: <SettingsTab /> },
+ { key: 'code', label: 'Code', content: <CodeTab /> },
+ { key: 'variants', label: 'Variants', content: <VariantsTab /> },
+ { key: 'recordings', label: 'Recordings', content: <ExperimentReplayTab experiment={experiment} /> },
+ { key: 'feedback', label: 'User feedback', content: <ExperimentFeedbackTab experiment={experiment} /> },
+ {
+ key: 'history',
+ label: 'History',
+ content: <ActivityLog scope={ActivityScope.EXPERIMENT} id={experimentId} />,
+ },
+ ] satisfies LemonTab<ExperimentTab>[]
+ ).filter((tab) => availableTabs.includes(tab.key))
return (
<SceneContent>
@@ -204,7 +170,7 @@ export function ExperimentView(): JSX.Element {
<ExperimentHeader />
<LemonTabs
// Fall back to the default tab if the active one is conditionally hidden
- activeKey={tabs.some((tab) => tab.key === activeTabKey) ? activeTabKey : 'metrics'}
+ activeKey={tabs.some((tab) => tab.key === activeTabKey) ? activeTabKey : DEFAULT_EXPERIMENT_TAB}
onChange={(key) => setActiveTabKey(key)}
sceneInset
// Keep the tab bar full-width, but cap the content under each tab for readability
diff --git a/frontend/src/scenes/experiments/experimentSceneLogic.test.ts b/frontend/src/scenes/experiments/experimentSceneLogic.test.ts
index e9f86f83389c..6d5b05c08730 100644
--- a/frontend/src/scenes/experiments/experimentSceneLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentSceneLogic.test.ts
@@ -1,13 +1,30 @@
-import { resetContext } from 'kea'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { urls } from 'scenes/urls'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { Experiment } from '~/types'
+
import { FORM_MODES } from './experimentLogic'
-import { experimentSceneLogic } from './experimentSceneLogic'
+import { DEFAULT_EXPERIMENT_TAB, experimentSceneLogic, getAvailableExperimentTabs } from './experimentSceneLogic'
+
+const LEGACY_EXPERIMENT = {
+ id: 123,
+ metrics: [{ kind: NodeKind.ExperimentTrendsQuery }],
+} as unknown as Experiment
+const DRAFT_EXPERIMENT = { id: 123 } as Experiment
+const LAUNCHED_EXPERIMENT = { id: 123, start_date: '2020-01-01T00:00:00Z' } as Experiment
type ExperimentLogicMock = {
experimentLogic: {
build: jest.Mock<any, any>
+ // Presents a loaded experiment through the same selector the scene proxies. Undefined (the
+ // default) leaves the scene reading the NEW_EXPERIMENT placeholder, i.e. "still loading".
+ __setExperiment: (experiment: Partial<Experiment> | undefined) => void
__logic: {
mount: jest.Mock<any, any>
actions: {
@@ -23,6 +40,7 @@ type ExperimentLogicMock = {
}
jest.mock('./experimentLogic', () => {
+ const experimentHolder: { current: any } = { current: undefined }
const logicInstance = {
mount: jest.fn(() => jest.fn()),
actions: {
@@ -32,6 +50,9 @@ jest.mock('./experimentLogic', () => {
loadExposures: jest.fn(),
refreshStaleResultsOnReentry: jest.fn(),
},
+ selectors: {
+ experiment: () => experimentHolder.current,
+ },
props: {},
}
@@ -43,8 +64,11 @@ jest.mock('./experimentLogic', () => {
return logicInstance
}),
__logic: logicInstance,
+ __setExperiment: (experiment: any) => {
+ experimentHolder.current = experiment
+ },
},
- NEW_EXPERIMENT: {},
+ NEW_EXPERIMENT: { id: 'new' },
}
})
@@ -52,8 +76,9 @@ const mockModule = require('./experimentLogic') as ExperimentLogicMock
describe('experimentSceneLogic', () => {
beforeEach(() => {
- resetContext({ createStore: true })
+ initKeaTests()
jest.clearAllMocks()
+ mockModule.experimentLogic.__setExperiment(undefined)
mockModule.experimentLogic.__logic.actions.loadExperiment.mockClear()
mockModule.experimentLogic.__logic.actions.loadExposures.mockClear()
})
@@ -118,10 +143,11 @@ describe('experimentSceneLogic', () => {
// LemonTabs fires onChange on every tab click, including clicks on the already-active
// tab, so a same-tab dispatch must not count as another view.
const capture = posthog.capture as jest.Mock
+ router.actions.push(urls.experiment(123))
const logic = experimentSceneLogic({ experimentId: 123 as any, formMode: FORM_MODES.update })
logic.mount()
- // Mounting replays `urlToAction` for the current URL, which reports a landing tab when
- // earlier tests left a matching /experiments/:id URL behind — not this test's subject.
+ // Mounting replays `urlToAction` for the current URL, which reports the landing tab —
+ // not this test's subject.
capture.mockClear()
logic.actions.setActiveTabKey('recordings')
@@ -134,4 +160,155 @@ describe('experimentSceneLogic', () => {
logic.unmount()
})
+
+ describe('tab query param sync', () => {
+ it('hydrates the tab from ?tab on load and keeps the param in the URL', async () => {
+ router.actions.push(urls.experiment(123), { tab: 'variants' })
+ const logic = experimentSceneLogic({ experimentId: 123 as any, formMode: FORM_MODES.update })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ activeTabKey: 'variants' })
+ expect(router.values.searchParams['tab']).toEqual('variants')
+
+ logic.unmount()
+ })
+
+ it('falls back to the default tab for an unknown ?tab value', async () => {
+ router.actions.push(urls.experiment(123), { tab: 'bogus' })
+ const logic = experimentSceneLogic({ experimentId: 123 as any, formMode: FORM_MODES.update })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ activeTabKey: DEFAULT_EXPERIMENT_TAB })
+
+ logic.unmount()
+ })
+
+ it('opens the history tab for an ?activity deep link and keeps the param in the URL', async () => {
+ router.actions.push(urls.experiment(123), { activity: 'some-uuid' })
+ const logic = experimentSceneLogic({ experimentId: 123 as any, formMode: FORM_MODES.update })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ activeTabKey: 'history' })
+ expect(router.values.searchParams['activity']).toEqual('some-uuid')
+
+ logic.unmount()
+ })
+
+ it('writes the tab to the URL with replace and clears it for the default tab', async () => {
+ router.actions.push(urls.experiment(123))
+ const logic = experimentSceneLogic({ experimentId: 123 as any, formMode: FORM_MODES.update })
+ logic.mount()
+
+ await expectLogic(logic, () => logic.actions.setActiveTabKey('code'))
+ expect(router.values.searchParams['tab']).toEqual('code')
+ expect(router.values.lastMethod).toEqual('REPLACE')
+
+ await expectLogic(logic, () => logic.actions.setActiveTabKey(DEFAULT_EXPERIMENT_TAB))
+ expect(router.values.searchParams['tab']).toBeUndefined()
+
+ logic.unmount()
+ })
+
+ it('drops the activity param when switching away from the history tab', async () => {
+ router.actions.push(urls.experiment(123), { activity: 'some-uuid' })
+ const logic = experimentSceneLogic({ experimentId: 123 as any, formMode: FORM_MODES.update })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ activeTabKey: 'history' })
+
+ await expectLogic(logic, () => logic.actions.setActiveTabKey('variants')).toMatchValues({
+ activeTabKey: 'variants',
+ })
+ expect(router.values.searchParams['activity']).toBeUndefined()
+ expect(router.values.searchParams['tab']).toEqual('variants')
+
+ logic.unmount()
+ })
+
+ it('resets to the default tab when navigating to another experiment', async () => {
+ router.actions.push(urls.experiment(123), { tab: 'variants' })
+ const logic = experimentSceneLogic({ experimentId: 123 as any, formMode: FORM_MODES.update })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ activeTabKey: 'variants' })
+
+ await expectLogic(logic, () => router.actions.push(urls.experiment(456))).toMatchValues({
+ activeTabKey: DEFAULT_EXPERIMENT_TAB,
+ })
+
+ logic.unmount()
+ })
+
+ it.each([
+ ['a ?tab deep link', { tab: 'code' }, 'code'],
+ ['no tab params', {}, 'metrics'],
+ ])('reports exactly one tab view when landing with %s', async (_label, searchParams, expectedTab) => {
+ // A landing must report once whether the listener fires (tab differs from the
+ // default) or the explicit landing report does (tab already active).
+ const capture = posthog.capture as jest.Mock
+ router.actions.push(urls.experiment(123), searchParams)
+ capture.mockClear()
+
+ const logic = experimentSceneLogic({ experimentId: 123 as any, formMode: FORM_MODES.update })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ const tabViews = capture.mock.calls.filter(([event]) => event === 'experiment tab viewed')
+ expect(tabViews.map(([, properties]) => (properties as any)?.tab)).toEqual([expectedTab])
+
+ logic.unmount()
+ })
+ })
+
+ describe('getAvailableExperimentTabs', () => {
+ it('reduces legacy experiments to metrics and variants', () => {
+ expect(getAvailableExperimentTabs(LEGACY_EXPERIMENT, {})).toEqual(['metrics', 'variants'])
+ })
+
+ it.each([
+ ['launched experiments', LAUNCHED_EXPERIMENT, true],
+ ['draft experiments', DRAFT_EXPERIMENT, false],
+ ])('offers the code tab only for %s', (_label, experiment, expected) => {
+ expect(getAvailableExperimentTabs(experiment, {}).includes('code')).toBe(expected)
+ })
+
+ it('offers the feedback tab only when a feature flag is linked', () => {
+ expect(getAvailableExperimentTabs(DRAFT_EXPERIMENT, {}).includes('feedback')).toBe(false)
+ const withFlag = { ...DRAFT_EXPERIMENT, feature_flag: { id: 1 } } as Experiment
+ expect(getAvailableExperimentTabs(withFlag, {}).includes('feedback')).toBe(true)
+ })
+
+ it('offers the recordings tab only when the feature flag is enabled', () => {
+ expect(getAvailableExperimentTabs(DRAFT_EXPERIMENT, {}).includes('recordings')).toBe(false)
+ expect(
+ getAvailableExperimentTabs(DRAFT_EXPERIMENT, {
+ [FEATURE_FLAGS.EXPERIMENT_RECORDINGS_TAB]: true,
+ }).includes('recordings')
+ ).toBe(true)
+ })
+ })
+
+ it('clamps the active tab to the default once the experiment loads without it', async () => {
+ // The deep-link path: ?tab=code resolves from the URL before the experiment loads, so the
+ // scene holds 'code' provisionally. Once it loads as a draft (no code tab), scene state —
+ // not just the rendered tab — must fall back to metrics, or the URL and the
+ // `experiment tab viewed` event keep naming a tab the user never sees.
+ router.actions.push(urls.experiment(123), { tab: 'code' })
+ const logic = experimentSceneLogic({ experimentId: 123 as any, formMode: FORM_MODES.update })
+ logic.mount()
+ await expectLogic(logic).toMatchValues({ activeTabKey: 'code' })
+
+ await expectLogic(logic, () => {
+ // Simulate the experiment finishing loading as a draft; the ref update re-derives its
+ // available tabs, standing in for the loadExperimentSuccess that swaps in real data.
+ mockModule.experimentLogic.__setExperiment(DRAFT_EXPERIMENT)
+ logic.actions.setExperimentLogicRef(mockModule.experimentLogic.__logic as any, jest.fn(), {
+ experimentId: 123,
+ formMode: FORM_MODES.update,
+ } as any)
+ }).toMatchValues({ activeTabKey: DEFAULT_EXPERIMENT_TAB })
+ expect(router.values.searchParams['tab']).toBeUndefined()
+
+ logic.unmount()
+ })
})
diff --git a/frontend/src/scenes/experiments/experimentSceneLogic.tsx b/frontend/src/scenes/experiments/experimentSceneLogic.tsx
index 66b1d6741b41..511af4ef3cb0 100644
--- a/frontend/src/scenes/experiments/experimentSceneLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentSceneLogic.tsx
@@ -13,7 +13,10 @@ import {
} from 'kea'
import type { BreakPointFunction } from 'kea'
import { router, urlToAction } from 'kea-router'
+import { subscriptions } from 'kea-subscriptions'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { sceneConfigurations } from 'scenes/scenes'
@@ -32,16 +35,79 @@ import {
type FormModes,
experimentLogic,
} from './experimentLogic'
+import { isLaunched } from './experimentStatus'
import { stepStorageKey } from './ExperimentWizard/experimentWizardLogic'
+import { isLegacyExperiment } from './utils'
+
+export const EXPERIMENT_TABS = ['metrics', 'settings', 'code', 'variants', 'recordings', 'feedback', 'history'] 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, featureFlags: FeatureFlagsSet): 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 'recordings':
+ return !!featureFlags[FEATURE_FLAGS.EXPERIMENT_RECORDINGS_TAB]
+ case 'feedback':
+ return !!experiment.feature_flag
+ default:
+ return true
+ }
+ })
+}
+
+// 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 {
- activeTabKey: string
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ activeTabKey: ExperimentTab
+ availableTabs: ExperimentTab[]
breadcrumbs: Breadcrumb[]
experiment: Experiment
experimentId: ExperimentIdType
+ experimentLoaded: boolean
experimentLogicRef: {
logic: BuiltLogic<experimentLogicType>
props: ExperimentLogicProps
@@ -69,8 +135,8 @@ export interface experimentSceneLogicActions {
resetExperimentState: (experimentConfig: Experiment) => {
experimentConfig: Experiment
}
- setActiveTabKey: (activeTabKey: string) => {
- activeTabKey: string
+ setActiveTabKey: (activeTabKey: ExperimentTab) => {
+ activeTabKey: 'code' | 'feedback' | 'history' | 'metrics' | 'recordings' | 'settings' | 'variants'
}
setEditMode: (editing: boolean) => {
editing: boolean
@@ -131,6 +197,8 @@ export interface experimentSceneLogicMeta {
} | null
) => ((state: any, props?: ExperimentLogicProps | undefined) => boolean) | undefined
isExperimentLaunched: (arg: boolean | undefined) => boolean
+ availableTabs: (experiment: Experiment, featureFlags: FeatureFlagsSet) => ExperimentTab[]
+ experimentLoaded: (experiment: Experiment) => boolean
breadcrumbs: (experiment: Experiment, experimentId: ExperimentIdType) => Breadcrumb[]
sidePanelContext: (experimentId: ExperimentIdType) => SidePanelSceneContext | null
projectTreeRef: (experimentId: ExperimentIdType) => ProjectTreeRef
@@ -149,9 +217,10 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
path(['scenes', 'experiments', 'experimentSceneLogic']),
connect(() => ({
actions: [eventUsageLogic, ['reportExperimentTabViewed']],
+ values: [featureFlagLogic, ['featureFlags']],
})),
actions({
- setActiveTabKey: (activeTabKey: string) => ({ activeTabKey }),
+ setActiveTabKey: (activeTabKey: ExperimentTab) => ({ activeTabKey }),
setSceneState: (experimentId: Experiment['id'], formMode: FormModes) => ({ experimentId, formMode }),
setExperimentLogicRef: (
logic: BuiltLogic<experimentLogicType> | null,
@@ -166,11 +235,12 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
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: [
- 'metrics' as string,
+ DEFAULT_EXPERIMENT_TAB as ExperimentTab,
{
setActiveTabKey: (_, { activeTabKey }) => activeTabKey,
- setSceneState: () => 'metrics',
},
],
experimentId: [
@@ -264,6 +334,18 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
],
(isExperimentLaunched: boolean | undefined): boolean => isExperimentLaunched ?? false,
],
+ availableTabs: [
+ (s) => [s.experiment, s.featureFlags],
+ (experiment: Experiment, featureFlags: FeatureFlagsSet): ExperimentTab[] =>
+ getAvailableExperimentTabs(experiment, featureFlags),
+ ],
+ 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[] => {
@@ -300,6 +382,18 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
},
],
}),
+ 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
@@ -366,13 +460,35 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
? undefined
: formMode
- // Preserve search params (e.g. ?metric=...) when navigating to a new experiment
- const search = id === 'new' ? router.values.currentLocation.searchParams : undefined
- return [urls.experiment(id, effectiveFormMode), search, undefined]
+ // '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.
+ const currentSearch = router.values.currentLocation.searchParams
+ const search =
+ id === 'new'
+ ? currentSearch
+ : Object.fromEntries(
+ Object.entries(currentSearch).filter(([key]) => key === 'tab' || key === 'activity')
+ )
+ 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 }) => ({
@@ -384,6 +500,7 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
}
const didPathChange = currentLocation.initial || currentLocation.pathname !== previousLocation?.pathname
+ const targetTab = resolveExperimentTab(query, values)
if (id && didPathChange) {
const parsedId = id === 'new' ? 'new' : parseInt(id)
@@ -399,39 +516,39 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
// 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()
- return
- }
-
- actions.setSceneState(parsedId, formMode)
+ } else {
+ actions.setSceneState(parsedId, formMode)
- // `setSceneState` resets the tab reducer to 'metrics' without dispatching
- // `setActiveTabKey`, so the tab a page load lands on is reported here instead.
- // `?activity` switches away before anything renders, so only that tab is reported.
- if (query.activity) {
- actions.setActiveTabKey('history')
- } else if (parsedId !== 'new') {
- actions.reportExperimentTabViewed(parsedId, 'metrics')
- }
+ // 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) {
+ actions.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 (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
+ 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 ?? '',
+ })
}
- 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')
@@ -441,6 +558,7 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
}
const didPathChange = currentLocation.initial || currentLocation.pathname !== previousLocation?.pathname
+ const targetTab = resolveExperimentTab(query, values)
if (id && didPathChange) {
const parsedId = id === 'new' ? 'new' : parseInt(id)
@@ -461,14 +579,13 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
// 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()
- return
+ } else {
+ actions.setSceneState(parsedId, parsedFormMode)
}
+ }
- actions.setSceneState(parsedId, parsedFormMode)
-
- if (query.activity) {
- actions.setActiveTabKey('history')
- }
+ if (targetTab !== values.activeTabKey) {
+ actions.setActiveTabKey(targetTab)
}
},
})),
diff --git a/frontend/src/scenes/experiments/legacy/LegacyExperimentView.tsx b/frontend/src/scenes/experiments/legacy/LegacyExperimentView.tsx
index b0018dd16fd1..ee4506a9a07b 100644
--- a/frontend/src/scenes/experiments/legacy/LegacyExperimentView.tsx
+++ b/frontend/src/scenes/experiments/legacy/LegacyExperimentView.tsx
@@ -1,7 +1,7 @@
import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
import { useEffect } from 'react'
-import { LemonBanner, LemonTabs } from '@posthog/lemon-ui'
+import { LemonBanner, LemonTab, LemonTabs } from '@posthog/lemon-ui'
import { PendingChangeRequestBanner } from 'scenes/approvals/PendingChangeRequestBanner'
@@ -25,7 +25,7 @@ import {
import { Experiment } from '~/types'
import { experimentLogic } from '../experimentLogic'
-import { experimentSceneLogic } from '../experimentSceneLogic'
+import { DEFAULT_EXPERIMENT_TAB, type ExperimentTab, experimentSceneLogic } from '../experimentSceneLogic'
import { DistributionModal, DistributionTable } from '../ExperimentView/DistributionTable'
import { ExperimentWarningBanner } from '../ExperimentView/ExperimentWarningBanners'
import { LoadingState } from '../ExperimentView/LoadingState'
@@ -168,6 +168,19 @@ export function LegacyExperimentView(): JSX.Element {
}
}, [experimentLoading, experiment?.id, experiment, refreshExperimentResults])
+ const tabs: LemonTab<ExperimentTab>[] = [
+ {
+ key: 'metrics',
+ label: 'Metrics',
+ content: <LegacyMetricsTab />,
+ },
+ {
+ key: 'variants',
+ label: 'Variants',
+ content: <VariantsTab />,
+ },
+ ]
+
return (
<BindLogic logic={legacyExperimentLogic} props={legacyLogicProps}>
<SceneContent>
@@ -198,21 +211,13 @@ export function LegacyExperimentView(): JSX.Element {
{/* Tab navigation - only includes minimal tabs for legacy experiments */}
<LemonTabs
- activeKey={activeTabKey}
+ // Fall back to the default tab if the active one isn't rendered here
+ activeKey={
+ tabs.some((tab) => tab.key === activeTabKey) ? activeTabKey : DEFAULT_EXPERIMENT_TAB
+ }
onChange={(key) => setActiveTabKey(key)}
sceneInset
- tabs={[
- {
- key: 'metrics',
- label: 'Metrics',
- content: <LegacyMetricsTab />,
- },
- {
- key: 'variants',
- label: 'Variants',
- content: <VariantsTab />,
- },
- ]}
+ tabs={tabs}
/>
{/* Modals that legacy experiments support */}
diff --git a/products/experiments/manifest.tsx b/products/experiments/manifest.tsx
index 93c109efae91..a713943275a0 100644
--- a/products/experiments/manifest.tsx
+++ b/products/experiments/manifest.tsx
@@ -14,10 +14,12 @@ export const manifest: ProductManifest = {
options?: {
metric?: ExperimentMetric
name?: string
+ tab?: string
}
): string => {
const baseUrl = formMode ? `/experiments/${id}/${formMode}` : `/experiments/${id}`
- return `${baseUrl}${options ? `?${toParams(options)}` : ''}`
+ const params = options ? toParams(options) : ''
+ return params ? `${baseUrl}?${params}` : baseUrl
},
experiments: (): string => '/experiments',
experimentsSharedMetrics: (): string => '/experiments/shared-metrics',