: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
chore(ux): remove self read-only mode (#88652)
Paul D'Ambraab4c5ec1531c
diff --git a/.semgrep/rules/devex/no-environments-api-urls-frontend.yaml b/.semgrep/rules/devex/no-environments-api-urls-frontend.yamlindex 0e7ad86f6aaf..f96cf13f30a3 100644--- a/.semgrep/rules/devex/no-environments-api-urls-frontend.yaml+++ b/.semgrep/rules/devex/no-environments-api-urls-frontend.yaml@@ -60,7 +60,6 @@ rules:- '/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts'- '/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx'- '/frontend/src/lib/logic/eventIngestionRestrictionLogic.ts'- - '/frontend/src/lib/readOnlyGuard.ts'- '/frontend/src/models/dashboardsModel.tsx'- '/frontend/src/models/propertyDefinitionsModel.ts'- '/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts'diff --git a/common/storybook/storybook-timings.json b/common/storybook/storybook-timings.jsonindex f34a09b3f52f..925a3a84865a 100644--- a/common/storybook/storybook-timings.json+++ b/common/storybook/storybook-timings.json@@ -31,10 +31,6 @@"chromium": 11.725,"webkit": 1.981},- "frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.stories.tsx": {- "chromium": 5.614,- "webkit": 1.513- },"frontend/src/layout/panel-layout/InstallationStatusNavButton.stories.tsx": {"chromium": 28.015,"webkit": 3.879diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1a599338eb13..dbdef3e05091 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3152,10 +3152,6 @@ snapshots:hash: v1.k794b7964.c60b7cc22ee408a25b2d52e7ec8f594c57eb651424271c2f2cc77c234f76f53c.xf566pilxp_C5a2yyZphsoYxyZXaSJdPs3takrmpy3Ylayout-project-tree--narrow-size--light:hash: v1.k794b7964.716fcd78b6a40ec110eeed0abf685e671e52dbd55751eddb33db49505b5eb419.PgpbTIsUSGQj9jl4rDFX7eh6VzwVxhUN7ZpH9qmOCoE- layout-self-read-only-notice--read-only--dark:- hash: v1.k794b7964.2291df1c07f8675d53d36c1f0516a60c60f33ed88fab9257a460fe828c8200ec.Nfl4joUsH-5tXPjTEOJMbPrtVi_gnG-4TpSUv6BPdHM- layout-self-read-only-notice--read-only--light:- hash: v1.k794b7964.de08c65dbf336504f32f7df899ce6c8d9a04c7e3ec81cafda9e5247a277b888f.Hr--w3O12T3WNSYFV-NG3ImkffayrI_6HSfVtxWFwJklemon-ui-code-snippet--compact-with-long-text--dark:hash: v1.k794b7964.24ef8dbf676262fd459d035788973a4f00794e9f44094a50fa75d3b290e16614.HctoklkKb9cteQHNOAmiWzf2u1pie4IMoEMnn8ih3WElemon-ui-code-snippet--compact-with-long-text--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 998d93c7eef6..d8dd285a4db8 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -132,19 +132,13 @@ export function initKea({if (error?.name === 'AbortError') {return}- // Read-only mode (`ReadOnlyModeError`) flows through this path unchanged:- // it extends `ApiError` with `status=403`, so the `!(isLoadAction && error.status === 403)`- // condition already suppresses the toast for load actions, and write actions- // get a toast with the read-only `detail` as the message. The- // `posthog.captureException` event is dropped by the central- // `before_send` filter in `selfReadOnlyModeLogic`.// Toast if it's a fetch error or a specific API update errorconst isLoadAction = typeof actionKey === 'string' && /^(load|get|fetch)[A-Z]/.test(actionKey)// Access-denied 403s (code `permission_denied`) are suppressed only where the// owning UI surfaces them itself: load actions (AccessDenied scene gates) and the// self-handled write actions above. Other writes keep the generic toast, since- // most write flows have no failure handling of their own. Read-only mode uses- // distinct codes (`read_only_blocked`, `impersonation_read_only`) and still toasts.+ // most write flows have no failure handling of their own. Read-only impersonation+ // uses the distinct `impersonation_read_only` code and still toasts.const isAccessDenied =isAccessDeniedError(error) && (isLoadAction || ACCESS_DENIED_SELF_HANDLED.has(String(actionKey)))if (diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.stories.tsx b/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.stories.tsxdeleted file mode 100644index d74f71ab971e..000000000000--- a/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.stories.tsx+++ /dev/null@@ -1,58 +0,0 @@-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.tsxdeleted file mode 100644index b1b1a7398aee..000000000000--- a/frontend/src/layout/navigation/SelfReadOnlyNotice/SelfReadOnlyNotice.tsx+++ /dev/null@@ -1,159 +0,0 @@-// 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.tsdeleted file mode 100644index 3f635fd38313..000000000000--- a/frontend/src/layout/navigation/SelfReadOnlyNotice/index.ts+++ /dev/null@@ -1 +0,0 @@-export { SelfReadOnlyNotice } from './SelfReadOnlyNotice'diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.ts b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.tsdeleted file mode 100644index 2e7bcf41501c..000000000000--- a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.ts+++ /dev/null@@ -1,211 +0,0 @@-import { NETWORK_ERROR_MESSAGES } from 'lib/api-error'--import {- dropHandledAuthGateExceptions,- dropInjectedScriptReferenceErrors,- dropReadOnlyExceptions,- dropUnactionableNetworkExceptions,-} from './selfReadOnlyModeLogic'--describe('dropReadOnlyExceptions', () => {- it('passes non-exception events through unchanged', () => {- const event = { event: '$pageview', properties: { $current_url: '/foo' } }- expect(dropReadOnlyExceptions(event)).toBe(event)- })-- it('passes $exception events without ReadOnlyModeError through', () => {- const event = {- event: '$exception',- properties: {- $exception_list: [{ type: 'TypeError', value: 'x is not a function' }],- },- }- expect(dropReadOnlyExceptions(event)).toBe(event)- })-- it('drops $exception events whose top-level type is ReadOnlyModeError', () => {- const event = {- event: '$exception',- properties: {- $exception_list: [{ type: 'ReadOnlyModeError', value: 'You are in read-only mode' }],- },- }- expect(dropReadOnlyExceptions(event)).toBeNull()- })-- it('drops wrapped errors where ReadOnlyModeError lives in the cause chain', () => {- // posthog-js serializes `new Error('wrapper', { cause: readOnlyErr })`- // by appending the cause to `$exception_list`. The filter walks the- // whole list so wrappers do not slip through.- const event = {- event: '$exception',- properties: {- $exception_list: [- { type: 'Error', value: 'reverseProxyCheckerLogic: query failed' },- { type: 'ReadOnlyModeError', value: 'You are in read-only mode' },- ],- },- }- expect(dropReadOnlyExceptions(event)).toBeNull()- })-- it('tolerates missing properties and missing exception list', () => {- expect(dropReadOnlyExceptions({ event: '$exception' })).toEqual({ event: '$exception' })- expect(dropReadOnlyExceptions({ event: '$exception', properties: {} })).toEqual({- event: '$exception',- properties: {},- })- })-- it('returns null when handed null (matching posthog-js before_send contract)', () => {- expect(dropReadOnlyExceptions(null)).toBeNull()- })-})--describe('dropHandledAuthGateExceptions', () => {- it('passes real crashes through', () => {- const event = {- event: '$exception',- properties: { $exception_list: [{ type: 'TypeError', value: 'x is not a function' }] },- }- expect(dropHandledAuthGateExceptions(event)).toBe(event)- })-- // Each value is the message `ApiError` sets from the backend `detail` for a handled auth gate,- // so a rejected request is expected control flow rather than a bug to report.- it.each([- ['2FA setup required'],- ['2FA verification required'],- ['This action requires you to be recently authenticated.'],- ])('drops the handled auth-gate exception with message "%s"', (value) => {- const event = { event: '$exception', properties: { $exception_list: [{ type: 'Error', value }] } }- expect(dropHandledAuthGateExceptions(event)).toBeNull()- })-- it('drops the gate even when it sits deeper in the exception list', () => {- const event = {- event: '$exception',- properties: {- $exception_list: [- { type: 'Error', value: 'reverseProxyCheckerLogic: query failed' },- { type: 'Error', value: '2FA setup required' },- ],- },- }- expect(dropHandledAuthGateExceptions(event)).toBeNull()- })-- it('tolerates missing properties and a missing exception list', () => {- expect(dropHandledAuthGateExceptions({ event: '$exception' })).toEqual({ event: '$exception' })- expect(dropHandledAuthGateExceptions(null)).toBeNull()- })-})--describe('dropUnactionableNetworkExceptions', () => {- const exceptionWith = (value: string, type = 'NetworkError'): { event: string; properties: any } => ({- event: '$exception',- properties: { $exception_list: [{ type, value }] },- })-- // The asymmetry is the whole point of the filter: the first two say something about the client's- // situation, the third says a request failed while the user was online and staying put.- it.each([- ['device is offline', NETWORK_ERROR_MESSAGES.offline, true],- ['page was closing', NETWORK_ERROR_MESSAGES.navigating, true],- ['an unexplained connection failure', NETWORK_ERROR_MESSAGES.network, false],- ])('given %s, drops the event: %s', (_desc, value, dropped) => {- const event = exceptionWith(value)- expect(dropUnactionableNetworkExceptions(event)).toBe(dropped ? null : event)- })-- it('keeps an unrelated error that happens to carry a network message', () => {- // Matching on the message alone would let any `Error` with this text be silenced- const event = exceptionWith(NETWORK_ERROR_MESSAGES.offline, 'Error')- expect(dropUnactionableNetworkExceptions(event)).toBe(event)- })-- it('drops the failure even when it sits deeper in the exception list', () => {- // posthog-js appends the wrapped cause, so `NetworkError` is not always first- const event = {- event: '$exception',- properties: {- $exception_list: [- { type: 'Error', value: 'loadSavedHeatmaps failed' },- { type: 'NetworkError', value: NETWORK_ERROR_MESSAGES.navigating },- ],- },- }- expect(dropUnactionableNetworkExceptions(event)).toBeNull()- })-- it('tolerates missing properties and a missing exception list', () => {- expect(dropUnactionableNetworkExceptions({ event: '$exception' })).toEqual({ event: '$exception' })- expect(dropUnactionableNetworkExceptions(null)).toBeNull()- })-})--describe('dropInjectedScriptReferenceErrors', () => {- const injected = (value: string): { event: string; properties: any } => ({- event: '$exception',- properties: {- $exception_list: [{ type: 'ReferenceError', value, mechanism: { type: 'generic', handled: false } }],- },- })-- // Real user-reported injected identifiers, in both the WebKit and the V8/SpiderMonkey wording.- it.each([- ["Can't find variable: pos"],- ["Can't find variable: __firefox__"],- ["Can't find variable: WeixinJSBridge"],- ['zaloJSV2 is not defined'],- ['chrome is not defined'],- ['Rt is not defined'],- ['ehrMain is not defined'],- ])('drops the unhandled, frameless ReferenceError "%s"', (value) => {- expect(dropInjectedScriptReferenceErrors(injected(value))).toBeNull()- })-- it('keeps a ReferenceError from our own bundle, which carries a stack', () => {- const event = {- event: '$exception',- properties: {- $exception_list: [- {- type: 'ReferenceError',- value: 'foo is not defined',- mechanism: { type: 'generic', handled: false },- stacktrace: { frames: [{ source: 'https://us.posthog.com/static/chunk.js' }] },- },- ],- },- }- expect(dropInjectedScriptReferenceErrors(event)).toBe(event)- })-- it('keeps a handled ReferenceError, which some code path already recovered from', () => {- const event = {- event: '$exception',- properties: {- $exception_list: [- { type: 'ReferenceError', value: 'foo is not defined', mechanism: { handled: true } },- ],- },- }- expect(dropInjectedScriptReferenceErrors(event)).toBe(event)- })-- it('keeps a non-ReferenceError that happens to match the message shape', () => {- const event = {- event: '$exception',- properties: {- $exception_list: [{ type: 'TypeError', value: 'foo is not defined', mechanism: { handled: false } }],- },- }- expect(dropInjectedScriptReferenceErrors(event)).toBe(event)- })-- it('tolerates missing properties and a missing exception list', () => {- expect(dropInjectedScriptReferenceErrors({ event: '$exception' })).toEqual({ event: '$exception' })- expect(dropInjectedScriptReferenceErrors(null)).toBeNull()- })-})diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.tsdeleted file mode 100644index c2d6f0daf896..000000000000--- a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts+++ /dev/null@@ -1,282 +0,0 @@-import {- MakeLogicType,- actions,- afterMount,- beforeUnmount,- connect,- kea,- listeners,- path,- reducers,- selectors,-} from 'kea'-import posthog from 'posthog-js'--import { lemonToast } from '@posthog/lemon-ui'--import { UNACTIONABLE_NETWORK_ERROR_MESSAGES } from 'lib/api-error'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { setReadOnlyGetter, setReadOnlyNotifier } from 'lib/readOnlyGuard'--import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'--export const ESCALATION_OPTIONS = [- { seconds: 30, label: 'Allow for 30s' },- { seconds: 300, label: 'Allow for 5 min' },-] as const--// Filters `$exception` events whose chain contains a ReadOnlyModeError so the-// read-only feature doesn't spam error tracking for blocks-by-design. The-// chain walk catches wrapped errors (e.g. `new Error('...', { cause: e })`).-// Exported for unit testing.-export function dropReadOnlyExceptions<T extends { event?: string; properties?: Record<string, any> } | null>(- event: T-): T | null {- if (!event || event.event !== '$exception') {- return event- }- const list = (event.properties?.$exception_list ?? []) as Array<{ type?: string }>- if (list.some((ex) => ex?.type === 'ReadOnlyModeError')) {- return null- }- return event-}--// Detail messages the backend sends with the three handled auth-gate 403s. The frontend already-// recovers from each of them in `apiStatusLogic` (it opens the 2FA setup modal, shows the-// re-verification toast, or prompts a re-auth), so a rejected request is expected control flow,-// not a bug. posthog-js's error conversion keeps only the error type, message, and stack in-// `$exception_list` — the DRF `code` never reaches `before_send` — so we match on the message,-// which `ApiError` sets from the response `detail`.-//-// two_factor_setup_required — posthog/helpers/two_factor_session.py-// two_factor_verification_required — posthog/helpers/two_factor_session.py-// sensitive_action_required_reauth — posthog/permissions.py (TimeSensitiveActionPermission)-const HANDLED_AUTH_GATE_MESSAGES = new Set([- '2FA setup required',- '2FA verification required',- 'This action requires you to be recently authenticated.',-])--// Filters `$exception` events that are really a handled auth gate, not a crash. When an org-// enforces 2FA, or an action needs recent re-authentication, the API returns a 403 that-// `apiStatusLogic` turns into the setup/verify flow. The many call sites that also-// `captureException` the rejection — kea loaders via `initKea`, and direct captures like-// `reverseProxyCheckerLogic` — would each file it as a fresh error tracking issue, so drop-// them centrally here. Exported for unit testing.-export function dropHandledAuthGateExceptions<T extends { event?: string; properties?: Record<string, any> } | null>(- event: T-): T | null {- if (!event || event.event !== '$exception') {- return event- }- const list = (event.properties?.$exception_list ?? []) as Array<{ value?: string }>- if (list.some((ex) => ex?.value != null && HANDLED_AUTH_GATE_MESSAGES.has(ex.value))) {- return null- }- return event-}--// Filters `$exception` events for requests the browser never sent because the client was offline or-// the document was being torn down. Neither is a defect, and both arrive as unhandled rejections-// from whichever logic happened to be fetching, so each one fingerprints against a different stack-// and files its own error tracking issue. `NetworkError` with reason `network` is deliberately kept:-// a request that failed while the user was online and staying put is worth seeing. Exported for-// unit testing.-export function dropUnactionableNetworkExceptions<- T extends { event?: string; properties?: Record<string, any> } | null,->(event: T): T | null {- if (!event || event.event !== '$exception') {- return event- }- const list = (event.properties?.$exception_list ?? []) as Array<{ type?: string; value?: string }>- if (- list.some(- (ex) =>- ex?.type === 'NetworkError' && ex?.value != null && UNACTIONABLE_NETWORK_ERROR_MESSAGES.has(ex.value)- )- ) {- return null- }- return event-}--// Browser engines word an unknown-identifier ReferenceError in one of two ways: WebKit says-// "Can't find variable: X", V8 and SpiderMonkey say "X is not defined". Both name a single-// identifier. Our own bundle never leaves such an identifier undefined at runtime.-const UNKNOWN_IDENTIFIER_REFERENCE_ERROR = /^(Can't find variable: \S+|\S+ is not defined)$/--// Filters `$exception` events that a browser extension or an in-app browser injected into the page.-// Each one is an unhandled ReferenceError for an identifier our code never defines (for example-// `WeixinJSBridge`, `__firefox__`, or `Can't find variable: pos`), and posthog-js captures it-// through the global handler with no stack frames because the throwing script is not ours. A real-// ReferenceError in our own bundle carries a stack, so the empty-stack check keeps those. Each-// injected variant fingerprints to its own error tracking issue, so drop the whole class here.-// Exported for unit testing.-export function dropInjectedScriptReferenceErrors<- T extends { event?: string; properties?: Record<string, any> } | null,->(event: T): T | null {- if (!event || event.event !== '$exception') {- return event- }- const list = (event.properties?.$exception_list ?? []) as Array<{- type?: string- value?: string- mechanism?: { handled?: boolean }- stacktrace?: { frames?: unknown[] }- }>- const hasFrames = list.some((ex) => (ex?.stacktrace?.frames?.length ?? 0) > 0)- const isUnhandled = list.every((ex) => ex?.mechanism?.handled === false)- const isUnknownIdentifierReferenceError = list.some(- (ex) => ex?.type === 'ReferenceError' && ex?.value != null && UNKNOWN_IDENTIFIER_REFERENCE_ERROR.test(ex.value)- )- if (!hasFrames && isUnhandled && isUnknownIdentifierReferenceError) {- return null- }- return event-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface selfReadOnlyModeLogicValues {- featureFlags: FeatureFlagsSet // featureFlagLogic- escalatedUntil: number | null- isEscalated: boolean- isFlagEnabled: boolean- isReadOnly: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface selfReadOnlyModeLogicActions {- endEscalation: () => {- value: true- }- escalate: (durationSeconds: number) => {- durationSeconds: number- }- notifyBlocked: (method: string) => {- method: string- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface selfReadOnlyModeLogicMeta {- __keaTypeGenInternalSelectorTypes: {- isFlagEnabled: (featureFlags: FeatureFlagsSet) => boolean- isEscalated: (escalatedUntil: number | null) => boolean- isReadOnly: (isFlagEnabled: boolean, isEscalated: boolean) => boolean- }-}--export type selfReadOnlyModeLogicType = MakeLogicType<- selfReadOnlyModeLogicValues,- selfReadOnlyModeLogicActions,- Record<string, any>,- selfReadOnlyModeLogicMeta->--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: import('lib/logic/featureFlagLogic').FeatureFlagsSet): 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: number | null): boolean => until !== null && until > Date.now(),- ],- isReadOnly: [- (s) => [s.isFlagEnabled, s.isEscalated],- (isFlagEnabled: boolean, isEscalated: boolean): 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')- },- // Analytics-only — the user-visible toast is no longer fired here. Catch blocks- // that match `e instanceof ApiError` already surface `ReadOnlyModeError.detail`.- notifyBlocked: ({ method }) => {- 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))-- // Central error-tracking filter chain — drops `$exception` events for a ReadOnlyModeError- // (a block by design), for the handled auth gates (2FA setup/verify, re-auth), for the- // network failures that only describe the client's situation, and for the ReferenceErrors- // that browser extensions and in-app browsers inject. Catches direct captures *and* wrapped- // errors (`new Error('...', { cause: readOnlyErr })`). This logic mounts in the authenticated- // app, where every gated request happens, and no other code that runs there sets- // `before_send`, so we own this config slot.- posthog.set_config({- before_send: [- dropReadOnlyExceptions,- dropHandledAuthGateExceptions,- dropUnactionableNetworkExceptions,- dropInjectedScriptReferenceErrors,- ],- })-- // The user-facing toast for blocked writes is shown by the standard- // `e instanceof ApiError → lemonToast.error(e.detail)` pattern that- // every write call-site already implements. ReadOnlyModeError extends- // ApiError and carries a method-specific `detail`, so no extra hook- // is needed.- }),-- beforeUnmount(() => {- setReadOnlyGetter(null)- setReadOnlyNotifier(null)- // Releasing ownership of `before_send` — this clears the whole filter chain set on mount.- posthog.set_config({ before_send: undefined })- }),-])diff --git a/frontend/src/lib/api-error.test.ts b/frontend/src/lib/api-error.test.tsindex 77d9a8a37594..5d4315fa79d7 100644--- a/frontend/src/lib/api-error.test.ts+++ b/frontend/src/lib/api-error.test.ts@@ -94,10 +94,8 @@ describe('api-error', () => {['a 502', { status: 502 }, false],['a 503', { status: 503 }, false],['a 504', { status: 504 }, false],- // Only the listed codes are excused: a 403 the app does not recover from is still a- // signal, and read-only mode is dropped later by its own `before_send` filter.+ // Only the listed codes are excused: a 403 the app does not recover from is still a signal.['a 403 with no code', { status: 403 }, true],- ['a read-only-mode 403', { status: 403, code: 'read_only_blocked' }, true],['a 409 that is not an approvals gate', { status: 409, data: {} }, true],['a 500 backend exception', { status: 500 }, true],['a 400 validation error', { status: 400 }, true],diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex b693ca787ce6..87d48c230eec 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -12,7 +12,6 @@ import { ActivityLogProps } from 'lib/components/ActivityLog/ActivityLog'import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'import { getBackendHost, getStoredSession, isOAuthMode, refreshAccessToken } from 'lib/oauth/oauthClient'-import { assertNotReadOnly } from 'lib/readOnlyGuard'import { objectClean } from 'lib/utils/objects'import { toParams } from 'lib/utils/url'import { CohortCalculationHistoryResponse } from 'scenes/cohorts/cohortCalculationHistorySceneLogic'@@ -7172,7 +7171,6 @@ const api = {): Promise<T> {url = prepareUrl(url)ensureProjectIdNotInvalid(url)- assertNotReadOnly(method, url)const isFormData = data instanceof FormDataconst response = await handleFetch(url, method, async () => {@@ -7209,7 +7207,6 @@ const api = {async createResponse(url: string, data?: any, options?: ApiMethodOptions): Promise<Response> {url = prepareUrl(url)ensureProjectIdNotInvalid(url)- assertNotReadOnly('POST', url)const isFormData = data instanceof FormDatareturn await handleFetch(url, 'POST', async () =>@@ -7231,7 +7228,6 @@ const api = {async delete(url: string): Promise<any> {url = prepareUrl(url)ensureProjectIdNotInvalid(url)- assertNotReadOnly('DELETE', url)return await handleFetch(url, 'DELETE', async () =>fetch(url, {method: 'DELETE',diff --git a/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.test.ts b/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.test.tsindex 6a6df0a12bb4..f17f3fc234a6 100644--- a/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.test.ts+++ b/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.test.ts@@ -106,9 +106,6 @@ describe('reverseProxyCheckerLogic', () => {})expect(toastErrorSpy).not.toHaveBeenCalled()- // The error is captured directly (not wrapped) so its type is preserved at the- // top of `$exception_list` — that lets the central `before_send` filter recognise- // `ReadOnlyModeError` without depending on cause-chain serialization.expect(captureExceptionSpy).toHaveBeenCalledWith(expect.objectContaining({ status: 500 }),expect.objectContaining({ posthog_source: 'reverseProxyCheckerLogic.loadHasReverseProxy' })diff --git a/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.ts b/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.tsindex 6b41c848b32a..c10eea335f7e 100644--- a/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.ts+++ b/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.ts@@ -75,12 +75,6 @@ export const reverseProxyCheckerLogic = kea<reverseProxyCheckerLogicType>([// This check is advisory (used only to auto-complete a setup task).// Swallow errors so kea-loaders does not surface a user-visible toast// on every scene that mounts ProductSetupButton.- //- // Capturing the original `error` directly (rather than wrapping it- // in `new Error('...', { cause })`) keeps the error type at the top- // of `$exception_list`, so the central `before_send` filter in- // `selfReadOnlyModeLogic` can drop `ReadOnlyModeError` without- // assuming posthog-js serialises the cause chain.posthog.captureException(error, {posthog_source: 'reverseProxyCheckerLogic.loadHasReverseProxy',})diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 678dc46a5ef3..805b9ecb21fd 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -462,7 +462,6 @@ export const FEATURE_FLAGS = {PULSE: 'pulse', // owner: #team-analytics-platformQUICK_START_PULSE_INDICATOR: 'quick-start-pulse-indicator', // owner: @fercgomes #team-growth multivariate=control,testQUILL_DATE_PICKER: 'quill-date-picker', // owner: @pauldambra, flips the lib/components/DatePicker seam from LemonUI to Quill- 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@@ -570,15 +569,7 @@ export const FEATURE_FLAGS = {export type FeatureFlagLookupKey = keyof typeof FEATURE_FLAGSexport type FeatureFlagKey = (typeof FEATURE_FLAGS)[keyof typeof 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 STORYBOOK_FEATURE_FLAGS = Object.values(FEATURE_FLAGS)export const INSIGHT_VISUAL_ORDER = {trends: 10,diff --git a/frontend/src/lib/readOnlyGuard.test.ts b/frontend/src/lib/readOnlyGuard.test.tsdeleted file mode 100644index b6e84900bb1f..000000000000--- a/frontend/src/lib/readOnlyGuard.test.ts+++ /dev/null@@ -1,223 +0,0 @@-import { ApiError } from 'lib/api-error'-import {- assertNotReadOnly,- isReadOnly,- ReadOnlyModeError,- setReadOnlyGetter,- setReadOnlyNotifier,-} from 'lib/readOnlyGuard'--describe('readOnlyGuard', () => {- afterEach(() => {- // Tear down module-level state so each test starts from a clean slate.- setReadOnlyGetter(null)- setReadOnlyNotifier(null)- })-- describe('isReadOnly()', () => {- it('returns false when no getter is registered', () => {- expect(isReadOnly()).toBe(false)- })-- it.each([- ['getter returns true', true, true],- ['getter returns false', false, false],- ])('reflects the registered getter when %s', (_label, getterReturn, expected) => {- setReadOnlyGetter(() => getterReturn)- expect(isReadOnly()).toBe(expected)- })- })-- describe('assertNotReadOnly()', () => {- describe('when not in read-only mode', () => {- it.each([- ['POST', '/api/environments/2/dashboards/'],- ['PATCH', '/api/environments/2/dashboards/1/'],- ['PUT', '/api/environments/2/dashboards/1/'],- ['DELETE', '/api/environments/2/dashboards/1/'],- ['POST', '/api/environments/2/query/'],- ] as const)('lets %s %s through silently', (method, url) => {- setReadOnlyGetter(() => false)- const notifier = jest.fn()- setReadOnlyNotifier(notifier)-- expect(() => assertNotReadOnly(method, url)).not.toThrow()- expect(notifier).not.toHaveBeenCalled()- })- })-- describe('when in read-only mode', () => {- beforeEach(() => {- setReadOnlyGetter(() => true)- })-- it.each([- ['POST', '/api/environments/2/dashboards/'],- ['PATCH', '/api/environments/2/dashboards/1/'],- ['PUT', '/api/environments/2/dashboards/1/'],- ['DELETE', '/api/environments/2/dashboards/1/'],- ] as const)('blocks %s %s with a ReadOnlyModeError', (method, url) => {- expect(() => assertNotReadOnly(method, url)).toThrow(ReadOnlyModeError)- })-- it('calls the notifier with the blocked method', () => {- const notifier = jest.fn()- setReadOnlyNotifier(notifier)- expect(() => assertNotReadOnly('POST', '/api/environments/2/dashboards/')).toThrow(ReadOnlyModeError)- expect(notifier).toHaveBeenCalledTimes(1)- expect(notifier).toHaveBeenCalledWith('POST')- })-- it('does not throw when no notifier is registered', () => {- // Notifier is optional — guard should still block but stay quiet.- expect(() => assertNotReadOnly('POST', '/api/environments/2/dashboards/')).toThrow(ReadOnlyModeError)- })-- // Reads-disguised-as-writes (e.g. HogQL/trends/funnels via POST to /query/)- // must pass through even in read-only mode — otherwise the app becomes- // unusable.- it.each([- ['plain query', 'POST', '/api/environments/2/query/'],- ['query with id', 'POST', '/api/environments/2/query/abc-123/'],- ['query upgrade', 'POST', '/api/environments/2/query/upgrade'],- ['query log', 'POST', '/api/environments/2/query/abc-123/log'],- ['query with trailing query string', 'POST', '/api/environments/2/query/?refresh=true'],- ['delete on query path', 'DELETE', '/api/environments/2/query/abc-123/'],- ['file system log view', 'POST', '/api/environments/2/file_system/log_view/'],- ['log view with query string', 'POST', '/api/environments/2/file_system/log_view/?foo=bar'],- ['insights viewed (no trailing slash)', 'POST', '/api/environments/2/insights/viewed'],- ['insights viewed with trailing slash', 'POST', '/api/environments/2/insights/viewed/'],- ['insights viewed with query string', 'POST', '/api/environments/2/insights/viewed/?foo=bar'],- ['insights timing (no trailing slash)', 'POST', '/api/projects/2/insights/timing'],- ['insights timing with trailing slash', 'POST', '/api/projects/2/insights/timing/'],- ['metalytics (no trailing slash)', 'POST', '/api/projects/2/metalytics'],- ['metalytics with trailing slash', 'POST', '/api/projects/2/metalytics/'],- ['new AI conversation', 'POST', '/api/environments/2/conversations'],- ['new AI conversation with trailing slash', 'POST', '/api/environments/2/conversations/'],- ['AI conversation by id', 'PATCH', '/api/environments/2/conversations/abc-123/'],- ['AI conversation delete', 'DELETE', '/api/environments/2/conversations/abc-123/'],- ['AI conversation queue', 'POST', '/api/environments/2/conversations/abc-123/queue'],- ['AI conversation queue clear', 'POST', '/api/environments/2/conversations/abc-123/queue/clear'],- ['AI conversation append message', 'POST', '/api/environments/2/conversations/abc-123/append_message'],- ['AI conversation cancel', 'PATCH', '/api/environments/2/conversations/abc-123/cancel/'],- ['signals report viewed', 'POST', '/api/projects/2/signals/reports/abc-123/viewed/'],- [- 'signals report viewed with query string',- 'POST',- '/api/projects/2/signals/reports/abc-123/viewed/?foo=bar',- ],- ['session replay export create', 'POST', '/api/environments/2/exports/'],- ['session replay export create (projects)', 'POST', '/api/projects/2/exports/'],- ['export create with query string', 'POST', '/api/environments/2/exports/?export_format=video/mp4'],- // markViewed PATCH /session_recordings/:id — passive view-tracking- // telemetry. DELETE on the same path is destructive and stays blocked- // (see the blocked-list below).- ['session recording markViewed', 'PATCH', '/api/environments/2/session_recordings/abc-123/'],- [- 'session recording markViewed with query string',- 'PATCH',- '/api/environments/2/session_recordings/abc-123/?foo=bar',- ],- ] as const)('lets %s through (%s %s)', (_label, method, url) => {- const notifier = jest.fn()- setReadOnlyNotifier(notifier)- expect(() => assertNotReadOnly(method, url)).not.toThrow()- expect(notifier).not.toHaveBeenCalled()- })-- it.each([- ['endpoint that just contains the word query in a name', 'POST', '/api/environments/2/queryless/'],- ['similar prefix without slash', 'POST', '/api/environments/2/queryteam/'],- ['file system entity write blocked', 'POST', '/api/environments/2/file_system/'],- ['file system non-log_view blocked', 'POST', '/api/environments/2/file_system/abc-123/move'],- ['insight create blocked', 'POST', '/api/environments/2/insights/'],- ['insight non-viewed sub-action blocked', 'POST', '/api/environments/2/insights/123/viewed_by'],- ['insight non-timing sub-action blocked', 'POST', '/api/environments/2/insights/123/timing_breakdown'],- ['metalytics-like prefix blocked', 'POST', '/api/projects/2/metalyticsfoo/'],- // Only the passive viewed telemetry passes; rating a report is an active write.- ['signals report feedback blocked', 'POST', '/api/projects/2/signals/reports/abc-123/feedback/'],- ['ticket saved views write blocked', 'POST', '/api/environments/2/conversations/views/'],- [- 'ticket saved views write blocked (no trailing slash)',- 'POST',- '/api/environments/2/conversations/views',- ],- ['ticket saved view detail write blocked', 'PATCH', '/api/environments/2/conversations/views/abc/'],- ['support tickets write blocked (under projects)', 'POST', '/api/projects/2/conversations/tickets/'],- [- 'support tickets write blocked (under environments)',- 'POST',- '/api/environments/2/conversations/tickets/',- ],- ['conversations-like prefix blocked', 'POST', '/api/environments/2/conversationsfoo/'],- ['export detail write blocked', 'DELETE', '/api/environments/2/exports/123/'],- ['exports-like prefix blocked', 'POST', '/api/environments/2/exportsfoo/'],- // /session_recordings/:id allows PATCH only — DELETE is the destructive- // recording-delete endpoint and must stay blocked. POST/PUT are not- // used by markViewed either and stay blocked as defense in depth.- ['session recording DELETE blocked', 'DELETE', '/api/environments/2/session_recordings/abc-123/'],- ['session recording POST blocked', 'POST', '/api/environments/2/session_recordings/abc-123/'],- ['session recording PUT blocked', 'PUT', '/api/environments/2/session_recordings/abc-123/'],- ] as const)('still blocks %s (%s %s) — only allowlisted paths pass', (_l, method, url) => {- expect(() => assertNotReadOnly(method, url)).toThrow(ReadOnlyModeError)- })- })- })-- describe('ReadOnlyModeError', () => {- it('is an ApiError so existing catch blocks surface its detail', () => {- const err = new ReadOnlyModeError('POST')- expect(err).toBeInstanceOf(ApiError)- expect(err.status).toBe(403)- expect(err.code).toBe('read_only_blocked')- expect(err.name).toBe('ReadOnlyModeError')- })-- it.each([- ['POST', 'create'],- ['PUT', 'edit'],- ['PATCH', 'edit'],- ['DELETE', 'delete'],- ] as const)('personalises the detail for %s (verb: %s)', (method, verb) => {- const err = new ReadOnlyModeError(method)- expect(err.detail).toBe(- `Read-only mode is on — that ${verb} was blocked. Ask Max or the MCP to make the change for you.`- )- })-- it('falls back to a generic detail when constructed without a method', () => {- const err = new ReadOnlyModeError()- expect(err.detail).toContain('that change was blocked')- })- })-- describe('setReadOnlyGetter', () => {- let warnSpy: jest.SpyInstance-- beforeEach(() => {- warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => undefined)- })-- afterEach(() => {- warnSpy.mockRestore()- })-- it('warns when overwriting an existing getter (double-mount detection)', () => {- setReadOnlyGetter(() => true)- setReadOnlyGetter(() => false)- expect(warnSpy).toHaveBeenCalledTimes(1)- expect(warnSpy.mock.calls[0][0]).toContain('setReadOnlyGetter')- })-- it('does not warn when clearing the getter', () => {- setReadOnlyGetter(() => true)- setReadOnlyGetter(null)- expect(warnSpy).not.toHaveBeenCalled()- })-- it('does not warn on first registration', () => {- setReadOnlyGetter(() => true)- expect(warnSpy).not.toHaveBeenCalled()- })- })-})diff --git a/frontend/src/lib/readOnlyGuard.ts b/frontend/src/lib/readOnlyGuard.tsdeleted file mode 100644index 0ec4c0cb1780..000000000000--- a/frontend/src/lib/readOnlyGuard.ts+++ /dev/null@@ -1,116 +0,0 @@-/**- * 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.- */--import { ApiError } from 'lib/api-error'--export type ReadOnlyMethod = 'PATCH' | 'PUT' | 'POST' | 'DELETE'--const METHOD_TO_VERB: Record<ReadOnlyMethod, string> = {- POST: 'create',- PUT: 'edit',- PATCH: 'edit',- DELETE: 'delete',-}--function detailFor(method?: ReadOnlyMethod): string {- const verb = method ? METHOD_TO_VERB[method] : 'change'- return `Read-only mode is on — that ${verb} was blocked. Ask Max or the MCP to make the change for you.`-}--// Extends ApiError so the existing `e instanceof ApiError → lemonToast.error(e.detail)`-// pattern surfaces the read-only message naturally, without per-callsite checks.-// status=403 mirrors the Django response if this ever round-trips from the server.-export class ReadOnlyModeError extends ApiError {- constructor(method?: ReadOnlyMethod) {- super('You are in read-only mode', 403, undefined, {- detail: detailFor(method),- code: 'read_only_blocked',- })- this.name = 'ReadOnlyModeError'- }-}--type Notifier = (method: ReadOnlyMethod) => 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-}--// An entry is either a bare regex (matches any write method on a path that is-// only used for reads/passive telemetry — DELETE is safe because no destructive-// DELETE exists on the same path), or `{ pattern, methods }` for paths where-// some methods are passive telemetry but others would mutate (e.g. PATCH is-// view-tracking but DELETE destroys the resource — only PATCH may pass).-type AllowedPattern = RegExp | { pattern: RegExp; methods: ReadonlyArray<ReadOnlyMethod> }--// Writes that should pass through in read-only mode. Three categories:-// 1. Reads disguised as writes — /query serves HogQL / trends / funnels /-// retention via POST because the payload is too large for a query string.-// Block-listing it would make the entire app unusable.-// 2. Passive telemetry that fires automatically on view/mount and should not-// raise: /file_system/log_view, /insights/viewed, /insights/timing-// (time-to-see-data), /metalytics (side-panel scene view tracking), and-// PATCH /session_recordings/:id (markViewed view-tracking — restricted to-// PATCH because DELETE on the same path is the destructive recording-// delete endpoint and must stay blocked).-// 3. PostHog AI (Max) conversations — the read-only toast tells users to-// "Use Max or the MCP to make this change", so Max must remain usable.-// Matches /conversations except the two ticket sub-features (`views` and-// `tickets`). Mount-path-agnostic — works under /environments/ or-// /projects/ — so the discriminator is the sub-feature, not the prefix.-// 4. Exports — POST creates a render job (session replay MP4, insight PNG, etc.)-// but does not mutate product data; blocking it breaks download workflows.-const READ_ONLY_ALLOWED_PATTERNS: ReadonlyArray<AllowedPattern> = [- /\/query(?:\/|$|\?)/, // /api/environments/:team_id/query, /api/environments/:team_id/query/:queryId/log, etc.- /\/file_system\/log_view(?:\/|$|\?)/, // /api/environments/:team_id/file_system/log_view- /\/insights\/viewed(?:\/|$|\?)/, // /api/environments/:team_id/insights/viewed — passive "recently viewed" telemetry- /\/insights\/timing(?:\/|$|\?)/, // /api/projects/:team_id/insights/timing — time-to-see-data telemetry fired after every dashboard/insight load- /\/metalytics(?:\/|$|\?)/, // /api/projects/:team_id/metalytics — side-panel scene view tracking (only accepts metric_name=viewed)- /\/signals\/reports\/[^/]+\/viewed(?:\/|$|\?)/, // POST /api/projects/:team_id/signals/reports/:id/viewed — inbox report-open tracking; the consumption evidence keeping read scouts from auto-pausing- /\/conversations(?!\/(?:views|tickets))(?:\/|$|\?)/, // /api/.../conversations[/:id[/queue|/append_message|/cancel|...]] — PostHog AI (Max), excluding /conversations/views and /conversations/tickets- /\/exports\/?(?:\?|$)/, // /api/.../exports[/] — create export jobs only; detail paths like /exports/:id/ stay blocked- { pattern: /\/session_recordings\/[^/]+(?:\/|$|\?)/, methods: ['PATCH'] }, // PATCH /api/.../session_recordings/:id — markViewed view-tracking ({viewed: true, ...} then {analyzed: true, ...}). DELETE on the same path stays blocked.-]--function isReadDisguisedAsWrite(method: ReadOnlyMethod, url: string): boolean {- return READ_ONLY_ALLOWED_PATTERNS.some((entry) => {- if (entry instanceof RegExp) {- return entry.test(url)- }- return entry.methods.includes(method) && entry.pattern.test(url)- })-}--export function assertNotReadOnly(method: ReadOnlyMethod, url: string): void {- if (!isReadOnly()) {- return- }- if (isReadDisguisedAsWrite(method, url)) {- return- }- notifier?.(method)- throw new ReadOnlyModeError(method)-}diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxindex f142149bd6cc..54c0df60ab60 100644--- a/frontend/src/scenes/AuthenticatedShell.tsx+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -18,7 +18,6 @@ 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,7 +40,6 @@ export default function AuthenticatedShell({ children }: { children: React.React<GlobalShortcuts /><Command /><ImpersonationNotice />- <SelfReadOnlyNotice /><WizardSyncFab />{/* Separate from the FAB: the FAB stands down while an inline panel shows the run,but the doc dialog must be able to open from any surface. */}diff --git a/posthog/management/commands/sync_feature_flags.py b/posthog/management/commands/sync_feature_flags.pyindex 2b77df2a75ad..6c0b91ec221a 100644--- a/posthog/management/commands/sync_feature_flags.py+++ b/posthog/management/commands/sync_feature_flags.py@@ -27,7 +27,6 @@ INACTIVE_FLAGS = ["webhooks-denylist","insight-horizontal-controls","flagged-feature-indicator",- "read-only-mode",]diff --git a/products/dashboards/frontend/widgets/addWidgetModalUtils.ts b/products/dashboards/frontend/widgets/addWidgetModalUtils.tsindex c029a7e73b0e..0c18cada4aa6 100644--- a/products/dashboards/frontend/widgets/addWidgetModalUtils.ts+++ b/products/dashboards/frontend/widgets/addWidgetModalUtils.ts@@ -1,5 +1,3 @@-import { isReadOnly } from 'lib/readOnlyGuard'-import { DASHBOARD_WIDGET_CATALOG, type DashboardWidgetCatalogKey } from '../widget_types/catalog'export type AddWidgetPayload = {@@ -18,9 +16,6 @@ export function getAddWidgetDisabledReason(loading: boolean | undefined, selecteif (loading) {return 'Adding widgets…'}- if (isReadOnly()) {- return 'Read-only mode is on — allow writes temporarily to add widgets'- }if (selectedCount === 0) {return 'Select at least one widget type'}