: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(ux): self read-only mode flag (#59372)
Paul D'Ambrab34836a265ce
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b2c984f42cfe..b60700d89e3e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1157,9 +1157,9 @@ snapshots:components-search--product-recents-and-starred--light:hash: v1.k794b7964.093365121259b79e33584b3e0042ad3813b0e77f2af285369ab7b2bf98bd9c79.-imuS481bcvyD7kDEeyJ4mfKoQcmD451n4Lxv2IrE3gcomponents-search--searching--dark:- hash: v1.k794b7964.ad396839fe9f33932049672506634e20d59d18b3fadd0a777f40e83ac714698a.xmQ67eu1qjN6DIEu36qXgff2UHGSMhozO_-renm2CRw+ hash: v1.k794b7964.5640d6ceda1c0c42d11d0830ce6f99d435ed755f675c7bcf189625c50c6fb77e.y1r9bx5WquHigHMTHREsnNCKkDLi0SluFC9L48L6NxMcomponents-search--searching--light:- hash: v1.k794b7964.09f7821d34292ac6ae488cf6e77283ee604f033dbffd6c91bf7ae2b5ffe9c4f2.o44oJ2GJt3eMDzIWZJJDLpWSHM8fL3aR2hN22PD1UpU+ hash: v1.k794b7964.00eec8365eb2b8e99781a485440555fdde5a1ed86e73254e927075b30d97a8cb.Vo_QisoIzatCT6K0G9D63ScY4y_-Y22PxQMJ4Kv64S4components-sentencelist--full-sentence--dark:hash: v1.k794b7964.9d72ed5224f75be3f53f1ba8edc2547978e519aa46a57cc97eef9087b403cb7d.3yHHiA7NW-p6vVSlM-2nPx7Nbk7wuTr5SA9Av2nW--gcomponents-sentencelist--full-sentence--light:@@ -1944,6 +1944,10 @@ snapshots:hash: v1.k794b7964.cceda34139de55690cb1f2f14761662ef08924c55ceca45ca8b5f5c6a0258205.ch26jJwCUwqT-mTrhgV1tD-q0vMD1-RudedDkXutxkklayout-project-tree-custom-products--narrow-size--light:hash: v1.k794b7964.3b389565f50c05f0b0da55364d924dc92588b1e8c2259aa03a32b45362d2ae87.tx2-aAbUAS1qgaJT0xhsY2gS7KTKYN0yMTGIsa6U5hk+ layout-self-read-only-notice--read-only--dark:+ hash: v1.k794b7964.aa0aa21d822475834eece4c6c6dad9c297226ae363d3e5afd94bdc50e1a4bfd2.X79V0CguV6lenAm3u3zau-mer7JRj8dpNFUkMh7Sazs+ layout-self-read-only-notice--read-only--light:+ hash: v1.k794b7964.307252675f3509cc07b81778815a7da674f5bb7b4cfb40770f1dd2dacb78bfde.6RCP91PpdJ_f7x7N2thEthlHQBlU4JH09NbnPkv7OWMlemon-ui-code-snippet--compact-with-long-text--dark:hash: v1.k794b7964.094aa56a38595b85e806267bd286c5ab883943297f2d3df19178ec6280b20140.9sOQ0vykr2nvS1UbyNuNp3JLZA3QLuJXlWktrtX2uyIlemon-ui-code-snippet--compact-with-long-text--light:diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.stories.tsx b/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.stories.tsxnew file mode 100644index 000000000000..d74f71ab971e--- /dev/null+++ b/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.stories.tsx@@ -0,0 +1,58 @@+import { Meta, StoryFn } from '@storybook/react'+import { useActions } from 'kea'+import { useEffect } from 'react'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { SelfReadOnlyNotice } from './SelfReadOnlyNotice'++const meta: Meta<typeof SelfReadOnlyNotice> = {+ title: 'Layout/Self Read-Only Notice',+ component: SelfReadOnlyNotice,+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ // The global `withFeatureFlags` decorator reads this and resets it+ // between stories, so the read-only flag never leaks into other+ // stories' visual snapshots.+ featureFlags: [FEATURE_FLAGS.READ_ONLY_MODE],+ },+}+export default meta++function FakeScene(): JSX.Element {+ return (+ <div className="h-screen w-screen bg-default p-8">+ <h1 className="text-2xl font-semibold">A pretend scene</h1>+ <p className="text-secondary mt-2">+ The floating Self Read-Only notice should be visible in the bottom-right corner.+ </p>+ </div>+ )+}++export const ReadOnly: StoryFn = () => {+ // Also populate kea's featureFlagLogic directly. `parameters.featureFlags`+ // sets the persisted-flags window context for posthog-js, but the kea+ // store needs an explicit `setFeatureFlags` call to react in the same tick+ // the widget mounts.+ const { setFeatureFlags } = useActions(featureFlagLogic)+ useEffect(() => {+ try {+ localStorage.removeItem('self-read-only-notice-position')+ } catch {+ // storybook iframe may restrict storage access+ }+ setFeatureFlags([FEATURE_FLAGS.READ_ONLY_MODE], {+ [FEATURE_FLAGS.READ_ONLY_MODE]: true,+ })+ }, [setFeatureFlags])++ return (+ <>+ <FakeScene />+ <SelfReadOnlyNotice />+ </>+ )+}diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.tsx b/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.tsxnew file mode 100644index 000000000000..b1b1a7398aee--- /dev/null+++ b/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.tsx@@ -0,0 +1,159 @@+// Experiment widget — intentionally reuses ImpersonationNotice's SCSS classes so we can+// iterate on UX cheaply. If this graduates from experiment, promote to a shared+// `FloatingNotice` primitive (or copy the styles into a sibling .scss).+import '../ImpersonationNotice/ImpersonationNotice.scss'++import { useActions, useValues } from 'kea'+import { useEffect, useRef, useState } from 'react'++import { IconCollapse, IconWarning } from '@posthog/icons'+import { LemonButton, Tooltip } from '@posthog/lemon-ui'++import { DraggableWithSnapZones, DraggableWithSnapZonesRef } from 'lib/components/DraggableWithSnapZones'+import { FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'+import { usePageVisibility } from 'lib/hooks/usePageVisibility'+import { IconDragHandle } from 'lib/lemon-ui/icons'+import { cn } from 'lib/utils/css-classes'++import { ESCALATION_OPTIONS, selfReadOnlyModeLogic } from './selfReadOnlyModeLogic'++// Storybook keeps the same iframe across story switches, and the kea+// `featureFlags` state leaks once any story sets the flag. The global+// `withFeatureFlags` decorator does reset `persisted_feature_flags` per story,+// so use that as a second gate when running in storybook.+function isFlagPersistedInStorybook(): boolean {+ if (typeof window === 'undefined' || !('__mockServiceWorker' in window)) {+ return true // not storybook — defer to the kea-state gate above+ }+ const persisted = (window as { POSTHOG_APP_CONTEXT?: { persisted_feature_flags?: string[] } }).POSTHOG_APP_CONTEXT+ ?.persisted_feature_flags+ return Array.isArray(persisted) && persisted.includes(FEATURE_FLAGS.READ_ONLY_MODE)+}++function CountDown({ until }: { until: number }): JSX.Element {+ const [now, setNow] = useState(() => Date.now())+ const { isVisible } = usePageVisibility()++ useEffect(() => {+ if (!isVisible) {+ return+ }+ setNow(Date.now())+ const interval = setInterval(() => setNow(Date.now()), 1000)+ return () => clearInterval(interval)+ }, [isVisible])++ const remainingMs = Math.max(0, until - now)+ const duration = dayjs.duration(remainingMs)+ const text = duration.hours() > 0 ? duration.format('HH:mm:ss') : duration.format('mm:ss')++ return <span className="tabular-nums text-warning">{text}</span>+}++export function SelfReadOnlyNotice(): JSX.Element | null {+ const { isFlagEnabled, isReadOnly, isEscalated, escalatedUntil } = useValues(selfReadOnlyModeLogic)+ const { escalate, endEscalation } = useActions(selfReadOnlyModeLogic)++ const [isMinimized, setIsMinimized] = useState(false)+ const [isDragging, setIsDragging] = useState(false)+ const draggableRef = useRef<DraggableWithSnapZonesRef>(null)++ if (!isFlagEnabled || !isFlagPersistedInStorybook()) {+ return null+ }++ const title = isReadOnly ? 'Read-only mode' : 'Writes allowed (temporary)'++ return (+ <DraggableWithSnapZones+ ref={draggableRef}+ handle=".ImpersonationNotice__sidebar"+ defaultSnapPosition="bottom-right"+ persistKey="self-read-only-notice-position"+ onDragStart={() => setIsDragging(true)}+ onDragStop={() => setIsDragging(false)}+ >+ <div+ className={cn(+ 'ImpersonationNotice',+ isDragging && 'ImpersonationNotice--dragging',+ isMinimized && 'ImpersonationNotice--minimized',+ isReadOnly ? 'ImpersonationNotice--read-only' : 'ImpersonationNotice--read-write'+ )}+ >+ <div className="ImpersonationNotice__sidebar">+ <IconDragHandle className="ImpersonationNotice__drag-handle" />+ </div>+ {isMinimized && (+ <Tooltip title={`${title} — click to expand`}>+ <div className="ImpersonationNotice__minimized-content" onClick={() => setIsMinimized(false)}>+ <IconWarning className="ImpersonationNotice__minimized-icon" />+ </div>+ </Tooltip>+ )}+ {!isMinimized && (+ <div className="ImpersonationNotice__main">+ <div className="ImpersonationNotice__header">+ <IconWarning className="ImpersonationNotice__warning-icon" />+ <span className="ImpersonationNotice__title">{title}</span>+ <LemonButton+ size="xsmall"+ icon={<IconCollapse />}+ onClick={() => {+ setIsMinimized(true)+ draggableRef.current?.trySnapTo('bottom-right')+ }}+ />+ </div>+ <div className="ImpersonationNotice__content">+ {isReadOnly ? (+ <>+ <p className="ImpersonationNotice__message">+ Edits via UI buttons are blocked. Use Max or the MCP to make changes — or+ temporarily allow writes:+ </p>+ <div className="flex gap-2 justify-end">+ {ESCALATION_OPTIONS.map(({ seconds, label }) => (+ <LemonButton+ key={seconds}+ type="secondary"+ size="small"+ data-attr={`self-read-only-escalate-${seconds}s`}+ onClick={() => escalate(seconds)}+ >+ {label}+ </LemonButton>+ ))}+ </div>+ </>+ ) : (+ <>+ <p className="ImpersonationNotice__message">+ Writes allowed for the next{' '}+ {isEscalated && escalatedUntil ? (+ <CountDown until={escalatedUntil} />+ ) : (+ 'moment'+ )}+ .+ </p>+ <div className="flex gap-2 justify-end">+ <LemonButton+ type="secondary"+ size="small"+ data-attr="self-read-only-end-escalation"+ onClick={() => endEscalation()}+ >+ Back to read-only+ </LemonButton>+ </div>+ </>+ )}+ </div>+ </div>+ )}+ </div>+ </DraggableWithSnapZones>+ )+}diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/index.ts b/frontend/src/layout/navigation/SelfReadOnlyNotice/index.tsnew file mode 100644index 000000000000..3f635fd38313--- /dev/null+++ b/frontend/src/layout/navigation/SelfReadOnlyNotice/index.ts@@ -0,0 +1 @@+export { SelfReadOnlyNotice } from './SelfReadOnlyNotice'diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.tsnew file mode 100644index 000000000000..a712bad7685f--- /dev/null+++ b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts@@ -0,0 +1,103 @@+import { actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { lemonToast } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { setReadOnlyGetter, setReadOnlyNotifier } from 'lib/readOnlyGuard'++import type { selfReadOnlyModeLogicType } from './selfReadOnlyModeLogicType'++export const ESCALATION_OPTIONS = [+ { seconds: 30, label: 'Allow for 30s' },+ { seconds: 300, label: 'Allow for 5 min' },+] as const++const METHOD_TO_VERB: Record<string, string> = {+ POST: 'create',+ PUT: 'edit',+ PATCH: 'edit',+ DELETE: 'delete',+}++export const selfReadOnlyModeLogic = kea<selfReadOnlyModeLogicType>([+ path(['layout', 'navigation', 'SelfReadOnlyNotice', 'selfReadOnlyModeLogic']),++ connect(() => ({+ values: [featureFlagLogic, ['featureFlags']],+ })),++ actions({+ escalate: (durationSeconds: number) => ({ durationSeconds }),+ endEscalation: true,+ notifyBlocked: (method: string) => ({ method }),+ }),++ reducers({+ escalatedUntil: [+ null as number | null,+ {+ escalate: (_, { durationSeconds }) => Date.now() + durationSeconds * 1000,+ endEscalation: () => null,+ },+ ],+ }),++ selectors({+ isFlagEnabled: [+ (s) => [s.featureFlags],+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.READ_ONLY_MODE],+ ],+ // isEscalated reads Date.now() inside a selector — selectors aren't time-reactive.+ // It only flips back to false when escalatedUntil is reset by the setTimeout in the+ // `escalate` listener firing `endEscalation`. Acceptable: the timer runs even on+ // hidden tabs (pauseOnPageHidden: false).+ isEscalated: [(s) => [s.escalatedUntil], (until): boolean => until !== null && until > Date.now()],+ isReadOnly: [+ (s) => [s.isFlagEnabled, s.isEscalated],+ (isFlagEnabled, isEscalated): boolean => isFlagEnabled && !isEscalated,+ ],+ }),++ listeners(({ actions, cache }) => ({+ escalate: ({ durationSeconds }) => {+ cache.disposables.add(+ () => {+ const id = setTimeout(() => actions.endEscalation(), durationSeconds * 1000)+ return () => clearTimeout(id)+ },+ 'escalationTimer',+ { pauseOnPageHidden: false }+ )+ posthog.capture?.('read_only_escalated', { duration_seconds: durationSeconds })+ },+ endEscalation: () => {+ cache.disposables.dispose('escalationTimer')+ lemonToast.info('Back to read-only mode.', { toastId: 'read-only-resumed' })+ posthog.capture?.('read_only_ended')+ },+ notifyBlocked: ({ method }) => {+ const verb = METHOD_TO_VERB[method] ?? 'change'+ lemonToast.warning(+ `Read-only mode is on — that ${verb} was blocked. Ask Max or the MCP to make the change for you.`,+ { toastId: 'read-only-blocked' }+ )+ posthog.capture?.('read_only_write_blocked', { method })+ },+ })),++ afterMount(({ actions }) => {+ // Read via `findMounted()` rather than capturing the `values` proxy:+ // the store path can be torn down (HMR, logout, kea resetContext) without+ // our `beforeUnmount` clearing the getter, which would throw a kea+ // "path not in store" error on the next mutation.+ setReadOnlyGetter(() => selfReadOnlyModeLogic.findMounted()?.values.isReadOnly ?? false)+ setReadOnlyNotifier((method) => actions.notifyBlocked(method))+ }),++ beforeUnmount(() => {+ setReadOnlyGetter(null)+ setReadOnlyNotifier(null)+ }),+])diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex c9805b762c91..3b0b54d3767d 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6,6 +6,7 @@ import { ActivityLogProps } from 'lib/components/ActivityLog/ActivityLog'import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'import { dayjs } from 'lib/dayjs'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'+import { assertNotReadOnly } from 'lib/readOnlyGuard'import { humanFriendlyDuration, objectClean, toParams } from 'lib/utils'import { CohortCalculationHistoryResponse } from 'scenes/cohorts/cohortCalculationHistorySceneLogic'import { EventSchema } from 'scenes/data-management/events/eventDefinitionSchemaLogic'@@ -6733,6 +6734,7 @@ const api = {): Promise<T> {url = prepareUrl(url)ensureProjectIdNotInvalid(url)+ assertNotReadOnly(method)const isFormData = data instanceof FormDataconst response = await handleFetch(url, method, async () => {@@ -6768,6 +6770,7 @@ const api = {async createResponse(url: string, data?: any, options?: ApiMethodOptions): Promise<Response> {url = prepareUrl(url)ensureProjectIdNotInvalid(url)+ assertNotReadOnly('POST')const isFormData = data instanceof FormDatareturn await handleFetch(url, 'POST', () =>@@ -6788,6 +6791,7 @@ const api = {async delete(url: string): Promise<any> {url = prepareUrl(url)ensureProjectIdNotInvalid(url)+ assertNotReadOnly('DELETE')return await handleFetch(url, 'DELETE', () =>fetch(url, {method: 'DELETE',diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex aad323e2b090..bf7d5d1c187e 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -439,6 +439,7 @@ export const FEATURE_FLAGS = {PROVISION_MANAGED_WAREHOUSE_BETA: 'provision-managed-warehouse-beta', // owner: @EDsCODE #team-managed-warehouseQUICK_START_PULSE_INDICATOR: 'quick-start-pulse-indicator', // owner: @fercgomes #team-growth multivariate=control,testRBAC_UI_REDESIGN: 'rbac-ui-redesign', // owner: @reece #team-platform-features+ READ_ONLY_MODE: 'read-only-mode', // owner: @pauldambra, experiment: force users into read-only and steer mutations through Max/MCPREAL_TIME_NOTIFICATIONS: 'real-time-notifications', // owner: #team-platform-featuresREALTIME_COHORT_FLAG_TARGETING: 'realtime-cohort-flag-targeting', // owner: @dmarticus #team-feature-flagsRECORDINGS_PLAYER_EVENT_PROPERTY_EXPANSION: 'recordings-player-event-property-expansion', // owner: @pauldambra #team-replay@@ -523,7 +524,15 @@ export const FEATURE_FLAGS = {export type FeatureFlagLookupKey = keyof typeof FEATURE_FLAGSexport type FeatureFlagKey = (typeof FEATURE_FLAGS)[keyof typeof FEATURE_FLAGS]-export const STORYBOOK_FEATURE_FLAGS = Object.values(FEATURE_FLAGS)+// Flags that affect globally-mounted UI (e.g. floating widgets in+// AuthenticatedShell). Scene stories that opt into STORYBOOK_FEATURE_FLAGS+// shouldn't accidentally enable these, because the resulting widgets render+// in every snapshot and pollute visual regression.+const STORYBOOK_OPT_OUT_FLAGS: FeatureFlagKey[] = [FEATURE_FLAGS.READ_ONLY_MODE]++export const STORYBOOK_FEATURE_FLAGS = Object.values(FEATURE_FLAGS).filter(+ (flag) => !STORYBOOK_OPT_OUT_FLAGS.includes(flag)+)export const INSIGHT_VISUAL_ORDER = {trends: 10,diff --git a/frontend/src/lib/readOnlyGuard.ts b/frontend/src/lib/readOnlyGuard.tsnew file mode 100644index 000000000000..11e08066c62c--- /dev/null+++ b/frontend/src/lib/readOnlyGuard.ts@@ -0,0 +1,53 @@+/**+ * Module-level switch for the self-read-only experiment.+ *+ * Lives outside any kea logic so it can be read from `lib/api.ts` without+ * pulling the layout/navigation logic into the lib graph. The kea logic+ * (`selfReadOnlyModeLogic`) registers a getter that reads its current state.+ */++export class ReadOnlyModeError extends Error {+ // Many call sites in the app catch api errors with the shape+ // `lemonToast.error(error.detail || 'Failed to ...')`. Without `detail`,+ // a read-only block would surface as the misleading fallback ("Failed to+ // launch experiment" etc.) on top of the dedicated read-only toast.+ // Setting `detail` here keeps that secondary toast at least truthful.+ detail = 'Read-only mode is on — change blocked. Use Max or the MCP to make this change.'++ constructor(message = 'You are in read-only mode') {+ super(message)+ this.name = 'ReadOnlyModeError'+ }+}++type Notifier = (method: 'PATCH' | 'PUT' | 'POST' | 'DELETE') => void+type Getter = () => boolean++let getter: Getter | null = null+let notifier: Notifier | null = null++export function setReadOnlyGetter(fn: Getter | null): void {+ if (fn && getter) {+ // eslint-disable-next-line no-console+ console.warn(+ '[readOnlyGuard] setReadOnlyGetter called while a getter is already registered — overwriting. This usually means selfReadOnlyModeLogic was mounted twice.'+ )+ }+ getter = fn+}++export function setReadOnlyNotifier(fn: Notifier | null): void {+ notifier = fn+}++export function isReadOnly(): boolean {+ return getter?.() ?? false+}++export function assertNotReadOnly(method: 'PATCH' | 'PUT' | 'POST' | 'DELETE'): void {+ if (!isReadOnly()) {+ return+ }+ notifier?.(method)+ throw new ReadOnlyModeError()+}diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxindex 7ea2adaa718c..fe8d5a4be4c6 100644--- a/frontend/src/scenes/AuthenticatedShell.tsx+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -17,6 +17,7 @@ import { Navigation } from '~/layout/navigation-3000/Navigation'import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'import { ImpersonationNotice } from '~/layout/navigation/ImpersonationNotice'+import { SelfReadOnlyNotice } from '~/layout/navigation/SelfReadOnlyNotice'import { sceneLogic } from './sceneLogic'@@ -41,6 +42,7 @@ export default function AuthenticatedShell({ children }: { children: React.React<Command /><PostOnboardingModal /><ImpersonationNotice />+ <SelfReadOnlyNotice />{featureFlags[FEATURE_FLAGS.EXPERIMENTS_DW_AA_TEST] === 'test' && (<div data-attr="experiments-dw-aa-test-variant" className="hidden" />)}