: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
feat(flags): deep link to a feature flag tab with ?tab= (#79906)
Phil Haack0132f24dc823
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 393f4ae33787..9386d83dbd0d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7131,9 +7131,9 @@ snapshots:scenes-app-settings-authentication-domains--no-domains--light:hash: v1.k794b7964.37755257eeeb09bcb190a4623e6554e356ffcc6b4e61086b8d2427a3796af34b.eJhnmp6Mqw_TfNQhRHgzZylOtfr8VMwxaRjOdzUHuiIscenes-app-settings-authentication-domains--one-unverified-domain--dark:- hash: v1.k794b7964.11e795b95ee29357fe93fe8ccb852883b312788d135f6c7103d013e156023a2c.MFrqXPXOcgjF_cecrqvo7ezvtKG9cI9EuD72ZpIlQpQ+ hash: v1.k794b7964.d2354aea8e40abfcfeb18691d15e48abc24724460dbc0118185c750d3f8ce6d1.Gcj1tCTTgepeyP-Ep4JIhieodM8RlFeAjTQGNkP2UeQscenes-app-settings-authentication-domains--one-unverified-domain--light:- hash: v1.k794b7964.826b954e1c03e3156d0c10598975c3fd43583672372c163fa08264506f929cd7.C22X_4g68JpmDtmjwe33M24AQZ4CTTIwW2cMZPL0JCo+ hash: v1.k794b7964.0c40bb5374be5247d5c0e2d73a2118c34d8083775cce447d3faf00ab4012f187.rqLTqwCSkMm5b7tey65wa2ycrn4lTsv8Rw4ASlNuCKsscenes-app-settings-environment--settings-environment-access-control--dark:hash: v1.k794b7964.cdbb2694b5d5524628e578f807f3282a0e458c45172c29b79e2b6e7c06eac09f.HqYn6cyhm9cm_fXbavd2nlYeqoTVNd7ODjvCMKlAsIcscenes-app-settings-environment--settings-environment-access-control--light:diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.tsxindex 3f41c3b54683..df13c5510eb8 100644--- a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.tsx@@ -9,7 +9,11 @@ import { Suspense, useEffect, useRef, useState } from 'react'import { IconCollapse, IconExpand } from '@posthog/icons'import { LemonButton, LemonDivider, LemonTabs, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'-import { ActivityLogLogicProps, activityLogLogic } from 'lib/components/ActivityLog/activityLogLogic'+import {+ ACTIVITY_SEARCH_PARAM,+ ActivityLogLogicProps,+ activityLogLogic,+} from 'lib/components/ActivityLog/activityLogLogic'import { ActivityChange, HumanizedActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'import { TZLabel } from 'lib/components/TZLabel'import { FEATURE_FLAGS } from 'lib/constants'@@ -160,8 +164,8 @@ export const ActivityLogRow = ({const url = new URL(pathname, window.location.origin)url.search = search || ''url.hash = hash || ''- url.searchParams.delete('activity')- url.searchParams.set('activity', logItem.id)+ url.searchParams.delete(ACTIVITY_SEARCH_PARAM)+ url.searchParams.set(ACTIVITY_SEARCH_PARAM, logItem.id)void copyToClipboard(url.toString(), 'activity link')}diff --git a/frontend/src/lib/components/ActivityLog/activityLogLogic.tsx b/frontend/src/lib/components/ActivityLog/activityLogLogic.tsxindex 303eb58bdc72..2f5e69f78a34 100644--- a/frontend/src/lib/components/ActivityLog/activityLogLogic.tsx+++ b/frontend/src/lib/components/ActivityLog/activityLogLogic.tsx@@ -16,6 +16,10 @@ import { urls } from 'scenes/urls'import { ActivityScope } from '~/types'+// Search param that deep-links to a single activity item. Scene logics that host an+// ActivityLog under a tab key off this param too (e.g. to open their history tab).+export const ACTIVITY_SEARCH_PARAM = 'activity'+// Define which scopes should be expanded to include multiple scopesconst SCOPE_EXPANSIONS: Partial<Record<ActivityScope, ActivityScope[]>> = {[ActivityScope.TAG]: [ActivityScope.TAG, ActivityScope.TAGGED_ITEM],@@ -244,7 +248,7 @@ export const activityLogLogic = kea<activityLogLogicType>([})),urlToAction(({ values, actions, props }) => {const syncActivityHighlight = (searchParams: Record<string, any>): void => {- const activityId = searchParams?.activity+ const activityId = searchParams?.[ACTIVITY_SEARCH_PARAM]if (activityId && activityId !== values.highlightedActivityId) {actions.setHighlightedActivityId(activityId)} else if (!activityId && values.highlightedActivityId !== null) {diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsxindex 1d7a44342930..88c54c67075c 100644--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx@@ -128,6 +128,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {featureFlagMissing,isEditingFlag,activeTab,+ availableTabs,accessDeniedToFeatureFlag,earlyAccessFeaturesList,featureFlagActiveUpdateLoading,@@ -139,7 +140,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {restoreFeatureFlag,editFeatureFlag,createStaticCohort,- setActiveTab,+ setSelectedTab,updateFlag,saveFeatureFlag,saveDescriptionInline,@@ -170,7 +171,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {})if (hasVariantSurvey) {- setActiveTab(FeatureFlagsTab.FEEDBACK)+ setSelectedTab(FeatureFlagsTab.FEEDBACK)} else {setIsQuickSurveyModalOpen(true)setQuickSurveyVariantKey(variantKey ?? null)@@ -239,80 +240,70 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {const earlyAccessFeature = earlyAccessFeaturesList?.find((f) => f.flagKey === featureFlag.key)- const tabs = [- {- label: 'Overview',- key: FeatureFlagsTab.OVERVIEW,- content: <FeatureFlagOverview featureFlag={featureFlag} />,- },- ] as LemonTab<FeatureFlagsTab>[]-- if (id) {- tabs.push({- label: 'Usage',- key: FeatureFlagsTab.USAGE,- content: <UsageTab featureFlag={featureFlag} />,- })-- tabs.push({- label: 'Projects',- key: FeatureFlagsTab.PROJECTS,- content: <FeatureFlagProjects />,- })-- tabs.push({- label: 'Schedule',- key: FeatureFlagsTab.SCHEDULE,- content: <FeatureFlagSchedule />,- })- }-- if (featureFlag.id) {- tabs.push({- label: 'History',- key: FeatureFlagsTab.HISTORY,- content: <ActivityLog scope={ActivityScope.FEATURE_FLAG} id={featureFlag.id} />,- })- }-- if (featureFlag.can_edit) {- tabs.push({- label: 'Permissions',- key: FeatureFlagsTab.PERMISSIONS,- content: <FeatureFlagPermissions featureFlag={featureFlag} />,- })- }-- tabs.push({- label: 'User feedback',- key: FeatureFlagsTab.FEEDBACK,- content: <FeedbackTab featureFlag={featureFlag} />,- })-- tabs.push({- label: (- <div className="flex flex-row">- <div>Experiments</div>- </div>- ),- key: FeatureFlagsTab.EXPERIMENTS,- content: <ExperimentsTab featureFlag={featureFlag} />,- })-- if (id) {- tabs.push({- label: (- <div className="flex flex-row">- <div>Testing</div>- <LemonTag className="ml-2 float-right uppercase" type="primary">- New- </LemonTag>- </div>- ),- key: FeatureFlagsTab.TESTING,- content: <FeatureFlagTestingTab featureFlag={featureFlag} />,- })- }+ // Labels and content live here; which tabs exist is the logic's `availableTabs`, so the+ // tab list, the active tab, and the URL can't disagree+ const tabs = (+ [+ {+ label: 'Overview',+ key: FeatureFlagsTab.OVERVIEW,+ content: <FeatureFlagOverview featureFlag={featureFlag} />,+ },+ {+ label: 'Usage',+ key: FeatureFlagsTab.USAGE,+ content: <UsageTab featureFlag={featureFlag} />,+ },+ {+ label: 'Projects',+ key: FeatureFlagsTab.PROJECTS,+ content: <FeatureFlagProjects />,+ },+ {+ label: 'Schedule',+ key: FeatureFlagsTab.SCHEDULE,+ content: <FeatureFlagSchedule />,+ },+ {+ label: 'History',+ key: FeatureFlagsTab.HISTORY,+ content: (+ <>{featureFlag.id && <ActivityLog scope={ActivityScope.FEATURE_FLAG} id={featureFlag.id} />}</>+ ),+ },+ {+ label: 'Permissions',+ key: FeatureFlagsTab.PERMISSIONS,+ content: <FeatureFlagPermissions featureFlag={featureFlag} />,+ },+ {+ label: 'User feedback',+ key: FeatureFlagsTab.FEEDBACK,+ content: <FeedbackTab featureFlag={featureFlag} />,+ },+ {+ label: (+ <div className="flex flex-row">+ <div>Experiments</div>+ </div>+ ),+ key: FeatureFlagsTab.EXPERIMENTS,+ content: <ExperimentsTab featureFlag={featureFlag} />,+ },+ {+ label: (+ <div className="flex flex-row">+ <div>Testing</div>+ <LemonTag className="ml-2 float-right uppercase" type="primary">+ New+ </LemonTag>+ </div>+ ),+ key: FeatureFlagsTab.TESTING,+ content: <FeatureFlagTestingTab featureFlag={featureFlag} />,+ },+ ] as LemonTab<FeatureFlagsTab>[]+ ).filter((tab) => availableTabs.includes(tab.key))return (<>@@ -614,7 +605,9 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {/><LemonTabsactiveKey={activeTab}- onChange={(tab) => tab !== activeTab && setActiveTab(tab)}+ // Re-clicking the active tab must stay a no-op: the setSelectedTab listener+ // resets the schedule form, which would wipe in-progress edits+ onChange={(tab) => tab !== activeTab && setSelectedTab(tab)}tabs={tabs}sceneInset/>diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 8eb71707456b..69f7246e105b 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -65,7 +65,7 @@ import {validateFeatureFlagKey,validateFeatureFlagVariantKey,} from './featureFlagLogic'-import { featureFlagsLogic } from './featureFlagsLogic'+import { FeatureFlagsTab, featureFlagsLogic } from './featureFlagsLogic'jest.mock('posthog-js')@@ -880,6 +880,178 @@ describe('featureFlagLogic', () => {})})+ describe('active tab syncs with the URL', () => {+ it.each([+ ['?tab=usage', FeatureFlagsTab.USAGE],+ ['?tab=schedule', FeatureFlagsTab.SCHEDULE],+ // An unknown tab shouldn't strand the user on a blank page+ ['?tab=not-a-tab', FeatureFlagsTab.OVERVIEW],+ // The activity deep link belongs to the history tab+ ['?activity=42', FeatureFlagsTab.HISTORY],+ ])('opens %s on the %s tab', async (query, expectedTab) => {+ await expectLogic(logic, () => {+ router.actions.push(`${urls.featureFlag(1)}${query}`)+ }).toMatchValues({ activeTab: expectedTab })+ })++ it('opens the history tab when the page loads with ?activity already in the URL', async () => {+ logic.unmount()+ router.actions.push(`${urls.featureFlag(1)}?activity=42`)++ logic = featureFlagLogic({ id: 1 })+ logic.mount()++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ activeTab: FeatureFlagsTab.HISTORY })+ })++ it('clamps a deep link to a tab the flag does not offer', async () => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/99/`]: () => [+ 200,+ { ...MOCK_FEATURE_FLAG, id: 99, can_edit: false },+ ],+ },+ })+ const readOnlyLogic = featureFlagLogic({ id: 99 })+ readOnlyLogic.mount()++ try {+ await expectLogic(readOnlyLogic, () => {+ router.actions.push(`${urls.featureFlag(99)}?tab=permissions`)+ })+ .toFinishAllListeners()+ // The request is kept in selectedTab, so the tab appears if can_edit flips+ .toMatchValues({+ selectedTab: FeatureFlagsTab.PERMISSIONS,+ activeTab: FeatureFlagsTab.OVERVIEW,+ })+ // The URL keeps the requested tab too, so a reload re-requests it+ expect(router.values.searchParams.tab).toEqual('permissions')+ } finally {+ readOnlyLogic.unmount()+ }+ })++ it('defaults the schedule form against the loaded flag when deep-linking ?tab=schedule', async () => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/99/`]: () => [+ 200,+ { ...MOCK_FEATURE_FLAG, id: 99, active: false },+ ],+ },+ })+ router.actions.push(`${urls.featureFlag(99)}?tab=schedule`)+ const inactiveFlagLogic = featureFlagLogic({ id: 99 })+ inactiveFlagLogic.mount()++ try {+ await expectLogic(inactiveFlagLogic)+ .toFinishAllListeners()+ .toMatchValues({+ activeTab: FeatureFlagsTab.SCHEDULE,+ // The default is the opposite of the flag's real state, not the+ // NEW_FLAG placeholder the tab listener saw before the flag loaded+ schedulePayload: partial({ active: true }),+ })+ } finally {+ inactiveFlagLogic.unmount()+ }+ })++ it('keeps an in-progress schedule edit through a later reload', async () => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/98/`]: () => [+ 200,+ { ...MOCK_FEATURE_FLAG, id: 98, active: false },+ ],+ },+ })+ router.actions.push(`${urls.featureFlag(98)}?tab=schedule`)+ const inactiveFlagLogic = featureFlagLogic({ id: 98 })+ inactiveFlagLogic.mount()++ try {+ await expectLogic(inactiveFlagLogic)+ .toFinishAllListeners()+ .toMatchValues({ schedulePayload: partial({ active: true }) })++ // The user starts drafting a change before a second load (e.g. clicking Edit) lands+ inactiveFlagLogic.actions.setSchedulePayload(NEW_FLAG.filters, false, {}, null, null)++ await expectLogic(inactiveFlagLogic, () => {+ inactiveFlagLogic.actions.loadFeatureFlag()+ })+ .toFinishAllListeners()+ .toMatchValues({ schedulePayload: partial({ active: false }) })+ } finally {+ inactiveFlagLogic.unmount()+ }+ })++ it('does not fetch every flag in the project when deep-linking to the schedule tab of an unsaved flag', async () => {+ router.actions.push(`${urls.featureFlag('new')}?tab=schedule`)+ const newLogic = featureFlagLogic({ id: 'new' })+ newLogic.mount()++ try {+ await expectLogic(newLogic)+ .toFinishAllListeners()+ .toMatchValues({ activeTab: FeatureFlagsTab.SCHEDULE })+ .toNotHaveDispatchedActions(['loadScheduledChanges'])+ } finally {+ newLogic.unmount()+ }+ })++ it('falls back to overview instead of keeping the current tab when the URL names an unknown tab', async () => {+ router.actions.push(`${urls.featureFlag(1)}?tab=usage`)+ await expectLogic(logic).toMatchValues({ activeTab: FeatureFlagsTab.USAGE })++ await expectLogic(logic, () => {+ router.actions.push(`${urls.featureFlag(1)}?tab=not-a-tab`)+ }).toMatchValues({ activeTab: FeatureFlagsTab.OVERVIEW })+ })++ it('writes the tab to the URL so it can be shared and survives a reload', async () => {+ router.actions.push(urls.featureFlag(1))++ await expectLogic(logic, () => {+ logic.actions.setSelectedTab(FeatureFlagsTab.USAGE)+ }).toFinishAllListeners()+ expect(router.values.searchParams).toEqual(partial({ tab: 'usage' }))++ // Overview is the default, so it stays out of the URL+ await expectLogic(logic, () => {+ logic.actions.setSelectedTab(FeatureFlagsTab.OVERVIEW)+ }).toFinishAllListeners()+ expect(router.values.searchParams.tab).toBeUndefined()+ })++ it('drops ?activity= from the URL when leaving the history tab', async () => {+ router.actions.push(`${urls.featureFlag(1)}?activity=42`)+ await expectLogic(logic).toMatchValues({ activeTab: FeatureFlagsTab.HISTORY })++ await expectLogic(logic, () => {+ logic.actions.setSelectedTab(FeatureFlagsTab.USAGE)+ }).toFinishAllListeners()++ expect(router.values.searchParams.activity).toBeUndefined()+ })++ it('leaves the URL alone when the flag scene is not the current page', async () => {+ router.actions.push(urls.projectHomepage())++ await expectLogic(logic, () => {+ logic.actions.setSelectedTab(FeatureFlagsTab.USAGE)+ }).toFinishAllListeners()++ expect(router.values.searchParams.tab).toBeUndefined()+ })+ })+describe('default release conditions on new flags', () => {const groupDefault: FeatureFlagGroupType = {properties: [diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex cb30b2cf0450..00e39c08be9b 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -25,6 +25,7 @@ import { createElement } from 'react'import api, { PaginatedResponse } from 'lib/api'import { isAccessDeniedError } from 'lib/api-error'import { handleApprovalRequired } from 'lib/approvals/utils'+import { ACTIVITY_SEARCH_PARAM } from 'lib/components/ActivityLog/activityLogLogic'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { FEATURE_FLAGS } from 'lib/constants'@@ -33,13 +34,15 @@ import { scrollToFormError } from 'lib/forms/scrollToFormError'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'+import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { stringifyWithBigInts } from 'lib/utils/json'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { objectsEqual } from 'lib/utils/objects'import { slugify } from 'lib/utils/strings'import { experimentLogic } from 'scenes/experiments/experimentLogic'-import { FeatureFlagsTab, featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'+import { FeatureFlagsTab, featureFlagsLogic, isFeatureFlagsTab } from 'scenes/feature-flags/featureFlagsLogic'import { projectLogic } from 'scenes/projectLogic'import { Scene } from 'scenes/sceneTypes'import { NEW_SURVEY, NewSurvey, SURVEY_CREATED_SOURCE } from 'scenes/surveys/constants'@@ -122,6 +125,8 @@ import { flagToggleKey, updateFlagActiveInProject } from './updateFlagActiveInPrconst VALID_INTENTS: FlagIntent[] = ['local-eval', 'first-page-load']+const TAB_SEARCH_PARAM = 'tab'+export function hasDirectFlagDependency(featureFlag: FeatureFlagType): boolean {const groups = featureFlag.filters?.groupsif (!Array.isArray(groups)) {@@ -705,6 +710,7 @@ export interface featureFlagLogicValues {activeTab: FeatureFlagsTabaggregationTargetName: stringareVariantRolloutsValid: boolean+ availableTabs: FeatureFlagsTab[]breadcrumbs: Breadcrumb[]canCreateEarlyAccessFeature: booleancanCreatePairedSchedule: boolean@@ -876,6 +882,7 @@ export interface featureFlagLogicValues {repeatsValue: RecurrenceInterval | 'cron' | 'none'roleBasedAccessEnabled: booleanscheduleDateMarker: any+ scheduleDefaultsAppliedFromFlag: booleanschedulePayload: ScheduleFlagPayloadschedulePayloadErrors: anyschedulePreset: PairedPresetKey | null@@ -884,6 +891,7 @@ export interface featureFlagLogicValues {scheduledChangeOperation: ScheduledChangeOperationTypescheduledChanges: ScheduledChangeType[]scheduledChangesLoading: boolean+ selectedTab: FeatureFlagsTabshowFeatureFlagErrors: booleanshowImplementation: booleansidePanelContext: SidePanelSceneContext | null@@ -921,6 +929,9 @@ export interface featureFlagLogicActions {addVariant: () => {value: true}+ applyScheduleDefaultsFromFlag: () => {+ value: true+ }applyTemplate: (templateId: string) => {templateId: string}@@ -1357,9 +1368,6 @@ export interface featureFlagLogicActions {setAccessDeniedToFeatureFlag: () => {value: true}- setActiveTab: (tab: FeatureFlagsTab) => {- tab: FeatureFlagsTab- }setBucketingIdentifier: (bucketingIdentifier: FeatureFlagBucketingIdentifier | null) => {bucketingIdentifier: FeatureFlagBucketingIdentifier | null}@@ -1543,6 +1551,9 @@ export interface featureFlagLogicActions {setScheduledChangeOperation: (changeType: ScheduledChangeOperationType) => {changeType: ScheduledChangeOperationType}+ setSelectedTab: (tab: FeatureFlagsTab) => {+ tab: FeatureFlagsTab+ }setShowImplementation: (show: boolean) => {show: boolean}@@ -1860,6 +1871,8 @@ export interface featureFlagLogicMeta {}__keaTypeGenInternalSelectorTypes: {props: (arg: any) => any+ availableTabs: (featureFlag: FeatureFlagType, props: any) => FeatureFlagsTab[]+ activeTab: (selectedTab: FeatureFlagsTab, availableTabs: FeatureFlagsTab[]) => FeatureFlagsTabhasUnsavedChanges: (featureFlag: FeatureFlagType, originalFeatureFlag: FeatureFlagType | null) => booleanisFormDirty: (originalFeatureFlag: FeatureFlagType | null,@@ -1979,7 +1992,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions({setFeatureFlag: (featureFlag: FeatureFlagType) => ({ featureFlag }),setFeatureFlagFilters: (filters: FeatureFlagType['filters'], errors: any) => ({ filters, errors }),- setActiveTab: (tab: FeatureFlagsTab) => ({ tab }),+ setSelectedTab: (tab: FeatureFlagsTab) => ({ tab }),setFeatureFlagMissing: true,deleteFeatureFlag: (featureFlag: Partial<FeatureFlagType>) => ({ featureFlag }),restoreFeatureFlag: (featureFlag: Partial<FeatureFlagType>) => ({ featureFlag }),@@ -2057,6 +2070,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([applyTemplate: (templateId: string) => ({ templateId }),setFlagIntent: (intent: FlagIntent | null) => ({ intent }),applyUrlIntent: true,+ applyScheduleDefaultsFromFlag: true,}),forms(({ actions, values }) => ({featureFlag: {@@ -2344,10 +2358,10 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},},],- activeTab: [+ selectedTab: [FeatureFlagsTab.OVERVIEW as FeatureFlagsTab,{- setActiveTab: (_, { tab }) => tab,+ setSelectedTab: (_, { tab }) => tab,},],featureFlagMissing: [false, { setFeatureFlagMissing: () => true }],@@ -2584,6 +2598,16 @@ export const featureFlagLogic = kea<featureFlagLogicType>([loadFeatureFlag: () => false,},],+ // Unlike urlTemplateApplied/urlIntentApplied, this does not reset on loadFeatureFlag:+ // it corrects the schedule form's default exactly once, the first time the real flag+ // loads. Resetting it on every load would let a later reload (e.g. clicking Edit)+ // reapply the default and wipe a scheduled change the user is still drafting.+ scheduleDefaultsAppliedFromFlag: [+ false,+ {+ applyScheduleDefaultsFromFlag: () => true,+ },+ ],flagIntent: [null as FlagIntent | null,{@@ -3619,6 +3643,24 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},loadFeatureFlagSuccess: async ({ featureFlag }) => {+ // A ?tab=schedule deep link selects the tab before this load finishes, so the+ // schedule form's default was computed against the NEW_FLAG placeholder. Correct+ // it once against the loaded flag; only on the first load, so a later reload (e.g.+ // clicking Edit) does not overwrite a scheduled change the user is still drafting.+ if (+ featureFlag &&+ values.selectedTab === FeatureFlagsTab.SCHEDULE &&+ !values.scheduleDefaultsAppliedFromFlag+ ) {+ actions.setSchedulePayload(NEW_FLAG.filters, !featureFlag.active, {}, null, null)+ // An unsaved flag has no id to scope the request to, and the scheduled-changes+ // endpoint drops an empty record_id filter and returns every flag's scheduled+ // changes for the project instead of none+ if (featureFlag.id) {+ actions.loadScheduledChanges()+ }+ actions.applyScheduleDefaultsFromFlag()+ }if (values.copyDestinationProject) {actions.loadCopyDependencyRequirements()}@@ -3805,13 +3847,18 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions.setSchedulePayload(NEW_FLAG.filters, NEW_FLAG.active, {}, null, null)}},- setActiveTab: ({ tab }) => {+ setSelectedTab: ({ tab }) => {// Reset payload when opening schedule tab. The default operation is UpdateStatus,// so default active to the opposite of the current flag state.if (tab === FeatureFlagsTab.SCHEDULE) {const oppositeActive = !values.featureFlag.activeactions.setSchedulePayload(NEW_FLAG.filters, oppositeActive, {}, null, null)- actions.loadScheduledChanges()+ // An unsaved flag has no id to scope the request to, and the scheduled-changes+ // endpoint drops an empty record_id filter and returns every flag's scheduled+ // changes for the project instead of none+ if (values.featureFlag.id) {+ actions.loadScheduledChanges()+ }}},createScheduledChangeFailure: ({ error }) => {@@ -4015,6 +4062,34 @@ export const featureFlagLogic = kea<featureFlagLogicType>([})),selectors({props: [() => [(_, props) => props], (props) => props],+ // Which tabs the flag offers; FeatureFlag.tsx renders exactly this set+ availableTabs: [+ (s) => [s.featureFlag, s.props],+ (featureFlag: FeatureFlagType, props: FeatureFlagLogicProps): FeatureFlagsTab[] => {+ const tabs = [FeatureFlagsTab.OVERVIEW]+ if (props.id) {+ tabs.push(FeatureFlagsTab.USAGE, FeatureFlagsTab.PROJECTS, FeatureFlagsTab.SCHEDULE)+ }+ if (featureFlag.id) {+ tabs.push(FeatureFlagsTab.HISTORY)+ }+ if (featureFlag.can_edit) {+ tabs.push(FeatureFlagsTab.PERMISSIONS)+ }+ tabs.push(FeatureFlagsTab.FEEDBACK, FeatureFlagsTab.EXPERIMENTS)+ if (props.id) {+ tabs.push(FeatureFlagsTab.TESTING)+ }+ return tabs+ },+ ],+ // Clamped in a selector rather than in urlToAction so it re-derives when the flag+ // loads (a deep-linked tab can arrive before `can_edit` is known)+ activeTab: [+ (s) => [s.selectedTab, s.availableTabs],+ (selectedTab: FeatureFlagsTab, availableTabs: FeatureFlagsTab[]): FeatureFlagsTab =>+ availableTabs.includes(selectedTab) ? selectedTab : FeatureFlagsTab.OVERVIEW,+ ],hasUnsavedChanges: [(s) => [s.featureFlag, s.originalFeatureFlag],(featureFlag: FeatureFlagType, originalFeatureFlag: FeatureFlagType | null): boolean => {@@ -4411,6 +4486,32 @@ export const featureFlagLogic = kea<featureFlagLogicType>([],],}),+ trackedActionToUrl(({ props, values }) => ({+ setSelectedTab: () => {+ // The logic outlives the scene in places (e.g. the flag is embedded elsewhere),+ // so only rewrite the URL while we're actually on this flag's page+ if (removeProjectIdIfPresent(router.values.location.pathname) !== urls.featureFlag(props.id ?? 'new')) {+ return+ }++ // The URL carries selectedTab (the requested tab), not the clamped activeTab, so the+ // write round-trips with what urlToAction reads and never depends on availableTabs,+ // which is provisional until the flag loads. A deep link to a tab the user cannot see+ // yet (e.g. permissions before `can_edit` is known) stays in the URL this way.+ const searchParams = { ...router.values.searchParams }+ if (values.selectedTab === FeatureFlagsTab.OVERVIEW) {+ delete searchParams[TAB_SEARCH_PARAM]+ } else {+ searchParams[TAB_SEARCH_PARAM] = values.selectedTab+ }+ // `activity` deep-links to one activity item, which only exists on the history tab+ if (values.selectedTab !== FeatureFlagsTab.HISTORY) {+ delete searchParams[ACTIVITY_SEARCH_PARAM]+ }++ return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]+ },+ })),urlToAction(({ actions, props, values }) => ({[urls.featureFlag(props.id ?? 'new')]: (_, searchParams, ___, { method, initial }) => {// Don't disturb in-progress edits when a same-pathname PUSH slips through@@ -4430,9 +4531,16 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// If the URL was pushed (user clicked on a link), reset the scene's data.// This avoids resetting form fields if you click back/forward.- // Open the History tab when deep-linking to a specific activity item- if (searchParams.activity != null) {- actions.setActiveTab(FeatureFlagsTab.HISTORY)+ // The URL is the source of truth for the selected tab, so `?tab=usage` deep-links+ // and survives a reload. `?activity=` still implies the history tab.+ const tabFromUrl = searchParams[TAB_SEARCH_PARAM]+ const targetTab = isFeatureFlagsTab(tabFromUrl)+ ? tabFromUrl+ : searchParams[ACTIVITY_SEARCH_PARAM] != null+ ? FeatureFlagsTab.HISTORY+ : FeatureFlagsTab.OVERVIEW+ if (targetTab !== values.selectedTab) {+ actions.setSelectedTab(targetTab)}if (method === 'PUSH') {@@ -4489,11 +4597,6 @@ export const featureFlagLogic = kea<featureFlagLogicType>([})),afterMount(({ props, actions }) => {- // Open the History tab when deep-linking to a specific activity item on initial page load- if (router.values.searchParams.activity != null) {- actions.setActiveTab(FeatureFlagsTab.HISTORY)- }-if (props.id === 'new' &&(router.values.searchParams.sourceId ||diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.tsindex a54d20277c69..88cfbafa0bf7 100644--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts@@ -122,6 +122,10 @@ export enum FeatureFlagsTab {TESTING = 'testing',}+export function isFeatureFlagsTab(tab: unknown): tab is FeatureFlagsTab {+ return typeof tab === 'string' && (Object.values(FeatureFlagsTab) as string[]).includes(tab)+}+export interface FeatureFlagsResult extends CountedPaginatedResponse<FeatureFlagType> {/* not in the API response */filters?: FeatureFlagsFilters | null