: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(shortcuts): let staff leave the posthog team cohort (#109600)
Rafael Audibert452e14b685a0
diff --git a/frontend/src/globals.d.ts b/frontend/src/globals.d.tsindex 99f955d8b499..7e797e56ff32 100644--- a/frontend/src/globals.d.ts+++ b/frontend/src/globals.d.ts@@ -49,8 +49,8 @@ declare global {ESBUILD_PENDING_CHUNK_SCENES: string[] | nullPOSTHOG_EXPORTED_DATA: ExportedDataPOSTHOG_USER_IDENTITY_WITH_FLAGS?: {- distinctID: string- isIdentifiedID: boolean+ distinctID?: string+ isIdentifiedID?: booleanfeatureFlags: Record<string, boolean | string>}IMPERSONATED_SESSION?: booleandiff --git a/frontend/src/layout/GlobalShortcuts.tsx b/frontend/src/layout/GlobalShortcuts.tsxindex c2001e567dab..01013c48a413 100644--- a/frontend/src/layout/GlobalShortcuts.tsx+++ b/frontend/src/layout/GlobalShortcuts.tsx@@ -21,7 +21,8 @@ import { themeLogic } from './navigation-3000/themeLogic'import { sceneLayoutLogic } from './scenes/sceneLayoutLogic'export function GlobalShortcuts(): null {- const { superpowersEnabled } = useValues(superpowersLogic)+ const { superpowersEnabled, user, excludedFromPostHogTeamCohort } = useValues(superpowersLogic)+ const { setExcludedFromPostHogTeamCohort } = useActions(superpowersLogic)const { shortcutMenuOpen } = useValues(shortcutLogic)const { scenePanelIsPresent } = useValues(sceneLayoutLogic)const { setShortcutMenuOpen } = useActions(shortcutLogic)@@ -74,6 +75,15 @@ export function GlobalShortcuts(): null {disabled: !superpowersEnabled,})+ useShortcut({+ name: 'TogglePostHogTeamCohort',+ keybind: [],+ intent: 'Toggle PostHog Team cohort',+ interaction: 'function',+ callback: () => setExcludedFromPostHogTeamCohort(!excludedFromPostHogTeamCohort),+ disabled: !user?.is_staff,+ })+useShortcut({name: 'ZenMode',keybind: [keyBinds.zenMode],diff --git a/frontend/src/lib/components/Superpowers/superpowersLogic.ts b/frontend/src/lib/components/Superpowers/superpowersLogic.tsindex c0d29d56d5ea..4275dfdb5e61 100644--- a/frontend/src/lib/components/Superpowers/superpowersLogic.ts+++ b/frontend/src/lib/components/Superpowers/superpowersLogic.ts@@ -1,4 +1,7 @@-import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { lemonToast } from '@posthog/lemon-ui'import { mcpHintLogic } from 'lib/components/MCPHint/mcpHintLogic'import { preflightLogic } from 'lib/logic/preflightLogic'@@ -10,12 +13,16 @@ import type { PreflightStatus, UserType } from '../../../types'export type FakeStatusOverride = 'none' | 'operational' | 'degraded_performance' | 'partial_outage' | 'major_outage'export type FakeBillingAlert = 'none' | 'info' | 'warning' | 'error'+// The PostHog Team cohort in PostHog's own project excludes people with this person property set to true.+export const EXCLUDED_FROM_POSTHOG_TEAM_COHORT_PROPERTY = 'excluded_from_posthog_team_cohort'+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface superpowersLogicValues {dismissedSurfaces: Record<string, true> // mcpHintLogiceffectiveOptOut: boolean // mcpHintLogicpreflight: PreflightStatus | null // preflightLogicuser: UserType | null // userLogic+ excludedFromPostHogTeamCohort: booleanfakeBillingAlert: FakeBillingAlertfakeStatusOverride: FakeStatusOverrideisSuperpowersOpen: boolean@@ -34,6 +41,9 @@ export interface superpowersLogicActions {openSuperpowers: () => {value: true}+ setExcludedFromPostHogTeamCohort: (excluded: boolean) => {+ excluded: boolean+ }setFakeBillingAlert: (alert: FakeBillingAlert) => {alert: FakeBillingAlert}@@ -75,6 +85,7 @@ export const superpowersLogic = kea<superpowersLogicType>([closeSuperpowers: true,setFakeStatusOverride: (status: FakeStatusOverride) => ({ status }),setFakeBillingAlert: (alert: FakeBillingAlert) => ({ alert }),+ setExcludedFromPostHogTeamCohort: (excluded: boolean) => ({ excluded }),}),reducers({isSuperpowersOpen: [@@ -96,6 +107,26 @@ export const superpowersLogic = kea<superpowersLogicType>([setFakeBillingAlert: (_, { alert }) => alert,},],+ excludedFromPostHogTeamCohort: [+ false,+ { persist: true },+ {+ setExcludedFromPostHogTeamCohort: (_, { excluded }) => excluded,+ },+ ],+ }),+ listeners({+ setExcludedFromPostHogTeamCohort: ({ excluded }) => {+ // Set false instead of unsetting. unsetPersonProperties also drops the property from the+ // overrides posthog-js sends to /flags, so the flags reload reads the stored person, which+ // still has true until ingestion processes the $unset.+ posthog.setPersonProperties({ [EXCLUDED_FROM_POSTHOG_TEAM_COHORT_PROPERTY]: excluded })+ lemonToast.success(+ excluded+ ? 'You left the PostHog Team cohort. Flags that target it are now off for you.'+ : 'You rejoined the PostHog Team cohort. Flags that target it are back on for you.'+ )+ },}),selectors({superpowersEnabled: [diff --git a/frontend/src/loadPostHogJS.test.ts b/frontend/src/loadPostHogJS.test.tsindex ea0ae502e531..db47a793f717 100644--- a/frontend/src/loadPostHogJS.test.ts+++ b/frontend/src/loadPostHogJS.test.ts@@ -1,9 +1,49 @@import posthog from 'posthog-js'import { sampleOnProperty } from 'posthog-js/lib/src/extensions/sampling'-import { isInDeferredInitSample, loadPostHogJS } from './loadPostHogJS'+import { LastSeenFeatureFlags, isInDeferredInitSample, loadPostHogJS, withLastSeenFeatureFlags } from './loadPostHogJS'describe('loadPostHogJS', () => {+ describe('withLastSeenFeatureFlags', () => {+ const serverFlags = { 'server-decided': false, variant: 'control' }++ it.each<{+ case: string+ lastSeen: LastSeenFeatureFlags | null+ bootstrapFlags: LastSeenFeatureFlags['featureFlags']+ expected: LastSeenFeatureFlags['featureFlags']+ }>([+ {+ case: 'fills flags the server left out, and server values win',+ lastSeen: { distinctId: 'user-a', featureFlags: { 'server-decided': true, 'staff-only': true } },+ bootstrapFlags: serverFlags,+ expected: { 'server-decided': false, variant: 'control', 'staff-only': true },+ },+ {+ case: 'ignores flags another user saw on this browser',+ lastSeen: { distinctId: 'user-b', featureFlags: { 'staff-only': true } },+ bootstrapFlags: serverFlags,+ expected: serverFlags,+ },+ {+ case: 'keeps an empty bootstrap empty so posthog-js uses its own persisted flags',+ lastSeen: { distinctId: 'user-a', featureFlags: { 'staff-only': true } },+ bootstrapFlags: {},+ expected: {},+ },+ {+ case: 'keeps the server flags when nothing is cached',+ lastSeen: null,+ bootstrapFlags: serverFlags,+ expected: serverFlags,+ },+ ])('$case', ({ lastSeen, bootstrapFlags, expected }) => {+ expect(withLastSeenFeatureFlags({ featureFlags: bootstrapFlags }, lastSeen, 'user-a').featureFlags).toEqual(+ expected+ )+ })+ })+describe('isInDeferredInitSample', () => {it.each(['', 'a', '0198f1e2-9c3b-7a1d-8f4e-2b6c9d0e1f23', 'session-one', 'session-two', 'session-three'])('keeps the posthog-js sampling verdict for session %p',diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsxindex 4ca2b9c1d47b..e985c05394b0 100644--- a/frontend/src/loadPostHogJS.tsx+++ b/frontend/src/loadPostHogJS.tsx@@ -3,6 +3,7 @@ import posthog, { BeforeSendFn, BrowserMetricsConfig, SessionRecordingOptions }import { FEATURE_FLAGS } from 'lib/constants'import { isOAuthMode } from 'lib/oauth/oauthClient'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'+import { getAppContext } from 'lib/utils/getAppContext'import { startDetachedElementTracking } from './detachedElementTracker'@@ -19,6 +20,54 @@ export function isInDeferredInitSample(sessionId: string): boolean {return Math.abs(hash) % 100 < 50}+const LAST_SEEN_FEATURE_FLAGS_KEY = 'posthog-app-last-seen-feature-flags'++export interface LastSeenFeatureFlags {+ distinctId: string+ featureFlags: Record<string, boolean | string>+}++type UserIdentityWithFlags = NonNullable<Window['POSTHOG_USER_IDENTITY_WITH_FLAGS']>++/**+ * The Django bootstrap leaves out every flag it cannot evaluate locally, for example a flag whose+ * cohort reads a person property that Django does not send. posthog-js treats a flag that is not in+ * the bootstrap as off until /flags responds, so the first render drops those flags and then shows+ * them again. This fills only the missing keys from the last flags this same user saw, so server+ * values still win and a different user on the same browser never gets them.+ *+ * `distinctId` is the user Django evaluated the bootstrap for. The bootstrap itself carries no+ * distinct ID, so it cannot identify the user.+ */+export function withLastSeenFeatureFlags(+ bootstrap: UserIdentityWithFlags,+ lastSeen: LastSeenFeatureFlags | null,+ distinctId: string | undefined+): UserIdentityWithFlags {+ // An empty bootstrap makes posthog-js use its own persisted flags, which are already complete.+ if (!lastSeen || !distinctId || lastSeen.distinctId !== distinctId || !Object.keys(bootstrap.featureFlags).length) {+ return bootstrap+ }+ return { ...bootstrap, featureFlags: { ...lastSeen.featureFlags, ...bootstrap.featureFlags } }+}++function readLastSeenFeatureFlags(): LastSeenFeatureFlags | null {+ try {+ const stored = window.localStorage.getItem(LAST_SEEN_FEATURE_FLAGS_KEY)+ return stored ? JSON.parse(stored) : null+ } catch {+ return null+ }+}++function writeLastSeenFeatureFlags(lastSeen: LastSeenFeatureFlags): void {+ try {+ window.localStorage.setItem(LAST_SEEN_FEATURE_FLAGS_KEY, JSON.stringify(lastSeen))+ } catch {+ // Storage can be full or blocked. The cache only smooths the first render, so skip it.+ }+}+export interface LoadPostHogJSOptions {/*** Hook posthog-js's `before_send` so the caller can mutate or drop events before they leave@@ -51,7 +100,13 @@ export function loadPostHogJS(options: LoadPostHogJSOptions = {}): void {cookie_persisted_properties: ['prod_interest', // posthog.com sets these based on what docs were browsed],- bootstrap: window.POSTHOG_USER_IDENTITY_WITH_FLAGS ? window.POSTHOG_USER_IDENTITY_WITH_FLAGS : {},+ bootstrap: window.POSTHOG_USER_IDENTITY_WITH_FLAGS+ ? withLastSeenFeatureFlags(+ window.POSTHOG_USER_IDENTITY_WITH_FLAGS,+ readLastSeenFeatureFlags(),+ getAppContext()?.current_user?.distinct_id+ )+ : {},opt_in_site_apps: true,disable_surveys: window.IMPERSONATED_SESSION,disable_product_tours: true,@@ -176,7 +231,11 @@ export function loadPostHogJS(options: LoadPostHogJSOptions = {}): void {identity_hash: window.JS_POSTHOG_IDENTITY_HASH,})- posthog.onFeatureFlags((_flags, _variants, context) => {+ posthog.onFeatureFlags((_flags, variants, context) => {+ if (!context?.errorsLoading) {+ writeLastSeenFeatureFlags({ distinctId: posthog.get_distinct_id(), featureFlags: variants })+ }+if (inStorybook() || inStorybookTestRunner() || !context?.errorsLoading) {return}