: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
fix(feature-previews): stop the enrollment toggle from lying on self-hosted (#75938)
posthog[bot]b8fdf69d00db
diff --git a/frontend/src/layout/FeaturePreviews/FeaturePreviews.test.tsx b/frontend/src/layout/FeaturePreviews/FeaturePreviews.test.tsxnew file mode 100644index 000000000000..1cb35ef14d77--- /dev/null+++ b/frontend/src/layout/FeaturePreviews/FeaturePreviews.test.tsx@@ -0,0 +1,135 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import { useActions, useAsyncActions, useValues } from 'kea'++import { preflightLogic } from 'lib/logic/preflightLogic'+import { userLogic } from 'scenes/userLogic'++import { FeaturePreviews } from './FeaturePreviews'+import { EnrichedEarlyAccessFeature, featurePreviewsLogic } from './featurePreviewsLogic'++jest.mock('posthog-js')++jest.mock('kea', () => ({+ ...jest.requireActual('kea'),+ useValues: jest.fn(),+ useActions: jest.fn(),+ useAsyncActions: jest.fn(),+}))++jest.mock('lib/hooks/useAnchor', () => ({+ useAnchor: jest.fn(),+}))++jest.mock('lib/components/Cards/BasicCard', () => ({+ BasicCard: ({ children }: { children: React.ReactNode }) => <div data-attr="basic-card">{children}</div>,+}))++const mockedUseValues = useValues as jest.Mock+const mockedUseActions = useActions as jest.Mock+const mockedUseAsyncActions = useAsyncActions as jest.Mock++const BETA_FEATURE: EnrichedEarlyAccessFeature = {+ flagKey: 'customer-analytics-roadmap',+ name: 'Customer analytics',+ description: 'Get context about your customers.',+ stage: 'beta',+ enabled: false,+ documentationUrl: '',+ payload: undefined,+}++const CONCEPT_FEATURE: EnrichedEarlyAccessFeature = { ...BETA_FEATURE, flagKey: 'some-concept', stage: 'concept' }++const BANNER_TEXT = /controlled by the PERSISTED_FEATURE_FLAGS environment variable, not the toggles below/++function setupMocks({+ cloud = true,+ isDebug = false,+ features = [BETA_FEATURE],+}: { cloud?: boolean; isDebug?: boolean; features?: EnrichedEarlyAccessFeature[] } = {}): void {+ mockedUseValues.mockImplementation((logic: unknown) => {+ if (logic === featurePreviewsLogic) {+ return {+ filteredEarlyAccessFeatures: features,+ rawEarlyAccessFeaturesLoading: false,+ searchTerm: '',+ activeFeedbackFlagKey: null,+ activeFeedbackFlagKeyLoading: false,+ }+ }+ if (logic === userLogic) {+ return { hasAvailableFeature: () => true }+ }+ if (logic === preflightLogic) {+ return { preflight: { cloud, is_debug: isDebug } }+ }+ return {}+ })++ mockedUseActions.mockImplementation(() => ({+ loadEarlyAccessFeatures: jest.fn(),+ setSearchTerm: jest.fn(),+ beginEarlyAccessFeatureFeedback: jest.fn(),+ cancelEarlyAccessFeatureFeedback: jest.fn(),+ updateEarlyAccessFeatureEnrollment: jest.fn(),+ copyExternalFeaturePreviewLink: jest.fn(),+ }))++ mockedUseAsyncActions.mockImplementation(() => ({+ submitEarlyAccessFeatureFeedback: jest.fn(),+ }))+}++describe('FeaturePreviews', () => {+ afterEach(() => {+ cleanup()+ jest.clearAllMocks()+ })++ test.each([+ [false, false, false],+ [true, false, true],+ [false, true, true],+ ])('with cloud=%s and is_debug=%s the toggle switch is enabled: %s', (cloud, isDebug, expectedEnabled) => {+ setupMocks({ cloud, isDebug })++ render(<FeaturePreviews />)++ const toggle = screen.getByRole('switch')+ if (expectedEnabled) {+ expect(toggle).toBeEnabled()+ } else {+ expect(toggle).toBeDisabled()+ }+ })++ test.each([+ [false, false, true],+ [true, false, false],+ [false, true, false],+ ])(+ 'with cloud=%s and is_debug=%s the PERSISTED_FEATURE_FLAGS banner is shown: %s',+ (cloud, isDebug, expectedVisible) => {+ setupMocks({ cloud, isDebug })++ render(<FeaturePreviews />)++ const banner = screen.queryByText(BANNER_TEXT)+ if (expectedVisible) {+ expect(banner).toBeInTheDocument()+ } else {+ expect(banner).not.toBeInTheDocument()+ }+ }+ )++ test('hides the banner when the instance has only concept previews, which this list does not render', () => {+ setupMocks({ cloud: false, features: [CONCEPT_FEATURE] })++ render(<FeaturePreviews />)++ expect(screen.queryByText(BANNER_TEXT)).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsx b/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsxindex 1c410adf0ed0..2869a33514e0 100644--- a/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsx+++ b/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsx@@ -9,6 +9,8 @@ import { FEATURE_FLAGS } from 'lib/constants'import { useAnchor } from 'lib/hooks/useAnchor'import { IconLink } from 'lib/lemon-ui/icons'import { SpinnerOverlay } from 'lib/lemon-ui/Spinner'+import { FEATURE_PREVIEW_SELF_HOSTED_DISABLED_REASON, areClientFeatureFlagsHonored } from 'lib/logic/featureFlagLogic'+import { preflightLogic } from 'lib/logic/preflightLogic'import { Label } from 'lib/ui/Label/Label'import { userLogic } from 'scenes/userLogic'@@ -43,6 +45,7 @@ const hasPosthogJsFailedToLoadFeaturePreviews = (): boolean => !!window.POSTHOG_export function FeaturePreviews(): JSX.Element {const { filteredEarlyAccessFeatures, rawEarlyAccessFeaturesLoading, searchTerm } = useValues(featurePreviewsLogic)const { hasAvailableFeature } = useValues(userLogic)+ const { preflight } = useValues(preflightLogic)const { loadEarlyAccessFeatures, setSearchTerm } = useActions(featurePreviewsLogic)useLayoutEffect(() => loadEarlyAccessFeatures(), [loadEarlyAccessFeatures])@@ -55,9 +58,16 @@ export function FeaturePreviews(): JSX.Element {const shouldShowEmptyState =filteredEarlyAccessFeatures.length === 0 && !rawEarlyAccessFeaturesLoading && !searchTermconst failedToLoadFeaturePreviews = shouldShowEmptyState && hasPosthogJsFailedToLoadFeaturePreviews()+ const flagsHonored = areClientFeatureFlagsHonored(preflight)return (<div className="flex flex-col gap-2">+ {!flagsHonored && betaFeatures.length > 0 && (+ <LemonBanner type="info" className="mb-2">+ Feature previews on this instance are controlled by the PERSISTED_FEATURE_FLAGS environment+ variable, not the toggles below.+ </LemonBanner>+ )}{failedToLoadFeaturePreviews && (<LemonBanner type="warning" className="mb-2"><div className="flex flex-col gap-2">@@ -262,6 +272,8 @@ interface FeaturePreviewProps {function FeaturePreview({ feature, warning }: FeaturePreviewProps): JSX.Element {const { activeFeedbackFlagKey, activeFeedbackFlagKeyLoading } = useValues(featurePreviewsLogic)+ const { preflight } = useValues(preflightLogic)+ const flagsHonored = areClientFeatureFlagsHonored(preflight)const {beginEarlyAccessFeatureFeedback,cancelEarlyAccessFeatureFeedback,@@ -289,9 +301,13 @@ function FeaturePreview({ feature, warning }: FeaturePreviewProps): JSX.Elementfeature={feature}title={<div className="flex items-center gap-1">- <Label className="flex items-center gap-2 cursor-pointer" htmlFor={`${feature.flagKey}-switch`}>+ <Label+ className={`flex items-center gap-2 ${flagsHonored ? 'cursor-pointer' : 'cursor-default'}`}+ htmlFor={`${feature.flagKey}-switch`}+ ><LemonSwitchchecked={enabled}+ disabledReason={!flagsHonored && FEATURE_PREVIEW_SELF_HOSTED_DISABLED_REASON}onChange={(newChecked) =>updateEarlyAccessFeatureEnrollment(flagKey, newChecked, feature.stage)}diff --git a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsxindex 920051898619..f5aa337f7783 100644--- a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx+++ b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx@@ -100,11 +100,13 @@ function setupMocks({activeSceneId = null,featureFlags = {},cloud = true,+ isDebug = false,}: {earlyAccessFeatures?: Array<{ flagKey: string; enabled: boolean; stage?: string }>activeSceneId?: string | nullfeatureFlags?: Record<string, boolean | string>cloud?: boolean+ isDebug?: boolean} = {}): void {mockedUseMountedLogic.mockReturnValue({})@@ -119,7 +121,7 @@ function setupMocks({return { featureFlags }}if (isPreflightLogicRef(logic)) {- return { preflight: { cloud } }+ return { preflight: { cloud, is_debug: isDebug } }}return {}})@@ -260,6 +262,47 @@ describe('FeaturePreviewSceneGate', () => {expect(screen.getByText('Open feature previews')).toBeInTheDocument()expect(screen.queryByRole('switch')).not.toBeInTheDocument()})++ test.each([+ [false, false, false],+ [true, false, true],+ [false, true, true],+ ])('with cloud=%s and is_debug=%s the toggle switch is enabled: %s', (cloud, isDebug, expectedEnabled) => {+ setupMocks({+ earlyAccessFeatures: [{ flagKey: BASE_CONFIG.flag, enabled: false }],+ cloud,+ isDebug,+ })++ render(<FeaturePreviewSceneGate config={BASE_CONFIG}>{CHILDREN}</FeaturePreviewSceneGate>)++ const toggle = screen.getByRole('switch')+ if (expectedEnabled) {+ expect(toggle).toBeEnabled()+ } else {+ expect(toggle).toBeDisabled()+ }+ })++ test.each([+ [false, false, true],+ [true, false, false],+ [false, true, false],+ ])(+ 'with cloud=%s and is_debug=%s the PERSISTED_FEATURE_FLAGS note is shown: %s',+ (cloud, isDebug, expectedVisible) => {+ setupMocks({ earlyAccessFeatures: [], cloud, isDebug })++ render(<FeaturePreviewSceneGate config={BASE_CONFIG}>{CHILDREN}</FeaturePreviewSceneGate>)++ const note = screen.queryByText(/controlled by the PERSISTED_FEATURE_FLAGS environment variable/)+ if (expectedVisible) {+ expect(note).toBeInTheDocument()+ } else {+ expect(note).not.toBeInTheDocument()+ }+ }+ )})describe('request access', () => {diff --git a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsxindex f9ddd6ce9cef..36902702ebe8 100644--- a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx+++ b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx@@ -5,7 +5,11 @@ import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'import { supportLogic } from 'lib/components/Support/supportLogic'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import {+ FEATURE_PREVIEW_SELF_HOSTED_DISABLED_REASON,+ areClientFeatureFlagsHonored,+ featureFlagLogic,+} from 'lib/logic/featureFlagLogic'import { preflightLogic } from 'lib/logic/preflightLogic'import { sceneLogic } from 'scenes/sceneLogic'import { sceneConfigurations } from 'scenes/scenes'@@ -45,6 +49,7 @@ function FeaturePreviewGateContent({ config }: { config: FeaturePreviewGateConficonst feature = earlyAccessFeatures.find((f) => f.flagKey === config.flag)const sceneConfig = activeSceneId ? sceneConfigurations[activeSceneId] : undefined+ const flagsHonored = areClientFeatureFlagsHonored(preflight)return (<SceneContent>@@ -63,9 +68,13 @@ function FeaturePreviewGateContent({ config }: { config: FeaturePreviewGateConfiisEmptyactionElementOverride={feature ? (- <label className="flex items-center gap-2 cursor-pointer" htmlFor="feature-preview-gate-switch">+ <label+ className={`flex items-center gap-2 ${flagsHonored ? 'cursor-pointer' : 'cursor-default'}`}+ htmlFor="feature-preview-gate-switch"+ ><LemonSwitchchecked={feature.enabled}+ disabledReason={!flagsHonored && FEATURE_PREVIEW_SELF_HOSTED_DISABLED_REASON}onChange={(checked) =>updateEarlyAccessFeatureEnrollment(feature.flagKey, checked, feature.stage)}@@ -74,22 +83,30 @@ function FeaturePreviewGateContent({ config }: { config: FeaturePreviewGateConfi<span className="font-semibold">Enable feature preview</span></label>) : (- <div className="flex items-center gap-2">- <LemonButton type="primary" to={urls.featurePreview(config.flag)}>- Open feature previews- </LemonButton>- {config.offerRequestAccess && preflight?.cloud && (- <LemonButton- type="secondary"- onClick={() =>- openSupportForm({- kind: 'support',- message: `I'd like to request access to ${config.title}.`,- })- }- >- Request access+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <LemonButton type="primary" to={urls.featurePreview(config.flag)}>+ Open feature previews</LemonButton>+ {config.offerRequestAccess && preflight?.cloud && (+ <LemonButton+ type="secondary"+ onClick={() =>+ openSupportForm({+ kind: 'support',+ message: `I'd like to request access to ${config.title}.`,+ })+ }+ >+ Request access+ </LemonButton>+ )}+ </div>+ {!flagsHonored && (+ <span className="text-secondary text-xs">+ On self-hosted instances, feature previews are controlled by the+ PERSISTED_FEATURE_FLAGS environment variable.+ </span>)}</div>)diff --git a/frontend/src/lib/logic/featureFlagLogic.test.ts b/frontend/src/lib/logic/featureFlagLogic.test.tsnew file mode 100644index 000000000000..8d6617fa5e7e--- /dev/null+++ b/frontend/src/lib/logic/featureFlagLogic.test.ts@@ -0,0 +1,13 @@+import { areClientFeatureFlagsHonored } from './featureFlagLogic'++describe('areClientFeatureFlagsHonored', () => {+ it.each([+ [null, false],+ [{ cloud: false, is_debug: false }, false],+ [{ cloud: true, is_debug: false }, true],+ [{ cloud: false, is_debug: true }, true],+ [{ cloud: true, is_debug: true }, true],+ ])('preflight %s returns %s', (preflight, expected) => {+ expect(areClientFeatureFlagsHonored(preflight)).toBe(expected)+ })+})diff --git a/frontend/src/lib/logic/featureFlagLogic.ts b/frontend/src/lib/logic/featureFlagLogic.tsindex 03495606530e..56b073493702 100644--- a/frontend/src/lib/logic/featureFlagLogic.ts+++ b/frontend/src/lib/logic/featureFlagLogic.ts@@ -4,12 +4,25 @@ import posthog from 'posthog-js'import { FeatureFlagKey } from 'lib/constants'import { getAppContext } from 'lib/utils/getAppContext'-import { AppContext } from '~/types'+import { AppContext, PreflightStatus } from '~/types'export type FeatureFlagsSet = {[flag in FeatureFlagKey]?: boolean | string}+/**+ * Whether `posthog-js`-resolved flag values actually reach `featureFlagLogic.featureFlags` (see+ * `spyOnFeatureFlags` below). On self-hosted, non-debug instances they're discarded in favor of+ * the server-configured `PERSISTED_FEATURE_FLAGS` baseline, so anything that enrolls a user into+ * a flag client-side (e.g. early access feature enrollment) has no visible effect there.+ */+export function areClientFeatureFlagsHonored(preflight: Pick<PreflightStatus, 'cloud' | 'is_debug'> | null): boolean {+ return !!preflight?.cloud || !!preflight?.is_debug+}++export const FEATURE_PREVIEW_SELF_HOSTED_DISABLED_REASON =+ 'This toggle has no effect on self-hosted instances. Feature previews here are controlled by the PERSISTED_FEATURE_FLAGS environment variable.'+const eventsNotified: Record<string, boolean> = {}function notifyFlagIfNeeded(flag: string, flagState: string | boolean | undefined): void {if (!eventsNotified[flag]) {@@ -40,7 +53,7 @@ function spyOnFeatureFlags(featureFlags: FeatureFlagsSet): FeatureFlagsSet {const appContext = getAppContext()const persistedFlags = getPersistedFeatureFlags(appContext)const availableFlags =- appContext?.preflight?.cloud || appContext?.preflight?.is_debug || process.env.NODE_ENV === 'test'+ areClientFeatureFlagsHonored(appContext?.preflight ?? null) || process.env.NODE_ENV === 'test'? { ...persistedFlags, ...featureFlags }: persistedFlagsdiff --git a/frontend/src/toolbar/shims/featureFlagLogic.ts b/frontend/src/toolbar/shims/featureFlagLogic.tsindex ddab85839607..51121db9cff4 100644--- a/frontend/src/toolbar/shims/featureFlagLogic.ts+++ b/frontend/src/toolbar/shims/featureFlagLogic.ts@@ -6,6 +6,14 @@ export function getFeatureFlagPayload(_flag: string): undefined {return undefined}+// The toolbar never runs against a self-hosted PERSISTED_FEATURE_FLAGS baseline, so client-resolved+// flags are always honored there.+export function areClientFeatureFlagsHonored(): boolean {+ return true+}++export const FEATURE_PREVIEW_SELF_HOSTED_DISABLED_REASON = ''+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface featureFlagLogicValues {featureFlags: Record<string, boolean | string>