: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(flags): stop a failed load from reading as "feature flag not found" (#103245)
posthog[bot]6c351957ed3f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6c4105295aba..3408ee87a8c9 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10480,6 +10480,10 @@ snapshots:hash: v1.k794b7964.7c1812f3bae81f2ec5f88bdd8981269c9ab1db8de052f62261b6a526078e1db1.lLPRMvHcm3J30ZNs_Uv27aiYvPrYiEkQ9v9jzeGl4Rwscenes-app-feature-flags--edit-rules-v-2-feature-flag--light:hash: v1.k794b7964.6d2f9704f59bf6e3d61b811d92c7ecfc3d4a5263096d0e57181c2bce6dc4dc97.RTb3YQ69UQA3cySea7dGUkkZhOnIDrzoqgk7t0HpMXI+ scenes-app-feature-flags--feature-flag-load-failed--dark:+ hash: v1.k794b7964.78c0cc612dbea90f7040fdc919c91d37255bd3c1a5d149a26a7968e86bcd1649.ZSqbZArI-ot3gRLxJErCln6BkMjyS8my3F7ILlT9qX0+ scenes-app-feature-flags--feature-flag-load-failed--light:+ hash: v1.k794b7964.78afb799eb165b132bfb6310a7fd4356040e98955d6ee7a051d76b24a0eb290d.81OytD3WSL06BSsRwjMis1NVd27K8lL9FqZtwh5pn20scenes-app-feature-flags--feature-flag-not-found--dark:hash: v1.k794b7964.4f1e063fd0ea193507fc461100835138a210c677172cf02c4e6a1d3ca85053af.QLMBnXZd8GFY-ERfzWmRUW-eFybjMBVuSeT9PLkOnzIscenes-app-feature-flags--feature-flag-not-found--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 298767352a72..9945124a0e77 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -1,4 +1,4 @@-import { KeaPlugin, resetContext } from 'kea'+import { BuiltLogic, KeaPlugin, resetContext } from 'kea'import { disposablesPlugin } from 'kea-disposables'import { formsPlugin } from 'kea-forms'import { loadersPlugin } from 'kea-loaders'@@ -101,6 +101,20 @@ const ERROR_FILTER_ALLOW_LIST = ['loadCredentialAccounts', // Fires while the user types credentials; the account picker shows the error under the field]+/*+Like ERROR_FILTER_ALLOW_LIST, but for an action name that other logics also use. Only the logic+whose path is given here handles its own failures, so the same action elsewhere still toasts.+*/+const ERROR_FILTER_ALLOW_LIST_BY_LOGIC_PATH: Record<string, string> = {+ loadFeatureFlag: 'scenes.feature-flags.featureFlagLogic', // A retry banner, or a retry toast once the flag is on screen+}++// A keyed logic's path ends with its key, so match the owner path as a prefix.+function isErrorSelfHandledByLogic(actionKey: string, logicPath: string): boolean {+ const ownerPath = ERROR_FILTER_ALLOW_LIST_BY_LOGIC_PATH[actionKey]+ return !!ownerPath && (logicPath === ownerPath || logicPath.startsWith(`${ownerPath}.`))+}+/*Write actions that show their own friendly message for access-denied 403s(code `permission_denied`), so the generic toast would be a duplicate.@@ -202,7 +216,17 @@ export function initKea({}),formsPlugin,loadersPlugin({- onFailure({ error, reducerKey, actionKey }: { error: any; reducerKey: string; actionKey: string }) {+ onFailure({+ error,+ reducerKey,+ actionKey,+ logic,+ }: {+ error: any+ reducerKey: string+ actionKey: string+ logic: BuiltLogic+ }) {// A request aborted by us (superseded query, unmount, manual cancel) is not a// failure — don't toast, log, or report it.if (error?.name === 'AbortError') {@@ -220,6 +244,7 @@ export function initKea({isAccessDeniedError(error) && (isLoadAction || ACCESS_DENIED_SELF_HANDLED.has(String(actionKey)))if (!ERROR_FILTER_ALLOW_LIST.includes(actionKey) &&+ !isErrorSelfHandledByLogic(actionKey, logic.pathString) &&error?.status !== undefined &&![200, 201, 204, 401, 409].includes(error.status) && // 401 is handled by api.ts and the userLogic; 409 conflict flows surface their own UI!(isLoadAction && error.status === 403) && // 403 access denied is handled by sceneLogic gatesdiff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsxindex 5b3401de0eac..dc78d5e0e389 100644--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx@@ -93,6 +93,7 @@ import { openFeatureFlagDeleteDialog } from './featureFlagDeleteDialog'import { FeatureFlagEvaluationContexts } from './FeatureFlagEvaluationContexts'import { ExperimentsTab } from './FeatureFlagExperimentsTab'import { FeedbackTab } from './FeatureFlagFeedbackTab'+import { FeatureFlagLoadError } from './FeatureFlagLoadError'import { FeatureFlagLogicProps, featureFlagLogic } from './featureFlagLogic'import { FeatureFlagOverview } from './FeatureFlagOverview'import FeatureFlagProjects from './FeatureFlagProjects'@@ -138,6 +139,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {featureFlag,featureFlagLoading,featureFlagMissing,+ featureFlagLoadFailed,activeTab,availableTabs,accessDeniedToFeatureFlag,@@ -268,6 +270,11 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {return <NotFound object="feature flag" />}+ // Before the form branch below: an edit session whose flag never loaded has nothing to edit.+ if (featureFlagLoadFailed) {+ return <FeatureFlagLoadError id={props.id} />+ }+if (featureFlagLoading) {return <FeatureFlagFormSkeleton />}diff --git a/frontend/src/scenes/feature-flags/FeatureFlagLoadError.tsx b/frontend/src/scenes/feature-flags/FeatureFlagLoadError.tsxnew file mode 100644index 000000000000..8eee681cb306--- /dev/null+++ b/frontend/src/scenes/feature-flags/FeatureFlagLoadError.tsx@@ -0,0 +1,30 @@+import { useActions, useValues } from 'kea'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'++import { FeatureFlagLogicProps, featureFlagLogic } from './featureFlagLogic'++/**+ * Shown when the flag could not be loaded for a reason that says nothing about whether it exists.+ * A live flag must never read as deleted, so this offers a retry instead of the not-found screen.+ */+export function FeatureFlagLoadError({ id }: FeatureFlagLogicProps): JSX.Element {+ const logic = featureFlagLogic({ id })+ const { featureFlagLoading } = useValues(logic)+ const { loadFeatureFlag } = useActions(logic)++ return (+ <div className="p-4">+ <LemonBanner+ type="error"+ action={{+ children: 'Try again',+ loading: featureFlagLoading,+ onClick: () => loadFeatureFlag(),+ }}+ >+ We couldn't load this feature flag. Check your connection, then try again.+ </LemonBanner>+ </div>+ )+}diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsxindex 5371ade24b61..ca0552912ac0 100644--- a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx@@ -51,6 +51,14 @@ const meta: Meta = {detail: 'Not found.',},],+ '/api/projects/:team_id/feature_flags/2222222222222/': [+ 500,+ {+ type: 'server_error',+ code: 'error',+ detail: 'Something went wrong.',+ },+ ],'/api/projects/:team_id/feature_flags/:flagId/': ({ params }) => {const flag = featureFlags.results.find((r) => r.id === Number(params['flagId']))if (flag?.id === DELETED_FLAG_ID) {@@ -258,6 +266,12 @@ export const FeatureFlagNotFound: Story = {},}+export const FeatureFlagLoadFailed: Story = {+ parameters: {+ pageUrl: urls.featureFlag(2222222222222),+ },+}+const waitForMountedFeatureFlagLogic = async (): Promise<ReturnType<typeof featureFlagLogic.build>> => {return waitFor(() => {diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex f5abd234b668..eaf0293e7f46 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -16,7 +16,8 @@ import { toast } from 'react-toastify'import { lemonToast as sharedLemonToast } from '@posthog/lemon-ui'import api from 'lib/api'-import { ApiError } from 'lib/api-error'+import { ApiError, NetworkError } from 'lib/api-error'+import { flagTriggerLogic } from 'lib/components/IngestionControls/triggers/FlagTrigger/flagTriggerLogic'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'@@ -709,6 +710,175 @@ describe('featureFlagLogic', () => {})})+ describe('load failure handling', () => {+ const RELOAD_FAILED_MESSAGE = "We couldn't reload this feature flag. The page may not show its saved version."++ async function remount(): Promise<void> {+ logic.unmount()+ logic = featureFlagLogic({ id: MOCK_FEATURE_FLAG.id })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ }++ // A server error carries a status, so initKea would toast it. A dropped connection carries+ // none, so initKea never toasts it.+ const LOAD_FAILURES: [string, () => () => void][] = [+ [+ 'a server error',+ () => {+ useMocks({ get: { [FLAG_URL]: () => [500, SERVER_ERROR_BODY] } })+ return () => {}+ },+ ],+ [+ 'a dropped connection',+ () => {+ const get = jest.spyOn(api, 'get').mockRejectedValue(new NetworkError('network'))+ return () => get.mockRestore()+ },+ ],+ ]++ let toastSpy: jest.SpyInstance++ beforeEach(() => {+ silenceKeaLoadersErrors()+ toastSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')+ })++ afterEach(() => {+ toastSpy.mockRestore()+ resumeKeaLoadersErrors()+ })++ it('reads a 404 as a missing flag', async () => {+ useMocks({ get: { [FLAG_URL]: () => [404, { detail: 'Not found.' }] } })+ await remount()++ expect(logic.values.featureFlagMissing).toBe(true)+ expect(logic.values.featureFlagLoadFailed).toBe(false)+ })++ it.each(LOAD_FAILURES)(+ 'offers the retry banner, and no toast, when the first load hits %s',+ async (_desc, fail) => {+ const restore = fail()+ try {+ await remount()++ expect(logic.values.featureFlagMissing).toBe(false)+ expect(logic.values.featureFlagLoadFailed).toBe(true)+ expect(toastSpy).not.toHaveBeenCalled()+ } finally {+ restore()+ }+ }+ )++ it.each(LOAD_FAILURES)('keeps a loaded flag and toasts a retry when a reload hits %s', async (_desc, fail) => {+ const restore = fail()+ try {+ await expectLogic(logic, () => logic.actions.loadFeatureFlag()).toDispatchActions([+ 'loadFeatureFlagFailure',+ ])++ expect(logic.values.featureFlagLoadFailed).toBe(false)+ expect(logic.values.featureFlagMissing).toBe(false)+ expect(logic.values.featureFlag.key).toBe(MOCK_FEATURE_FLAG.key)+ // One call means initKea's generic toast stayed off and this is the only notice.+ expect(toastSpy).toHaveBeenCalledTimes(1)+ expect(toastSpy).toHaveBeenCalledWith(+ RELOAD_FAILED_MESSAGE,+ expect.objectContaining({ button: expect.objectContaining({ label: 'Try again' }) })+ )+ } finally {+ restore()+ }+ })++ it('offers the retry banner when the flag to duplicate fails to load', async () => {+ useMocks({+ get: { [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/42/`]: () => [500, SERVER_ERROR_BODY] },+ })+ router.actions.push(`${urls.featureFlag('new')}?sourceId=42`)+ const duplicateLogic = featureFlagLogic({ id: 'new' })+ try {+ await expectLogic(duplicateLogic, () => {+ duplicateLogic.mount()+ }).toDispatchActions(['loadFeatureFlagFailure'])++ expect(duplicateLogic.values.featureFlagLoadFailed).toBe(true)+ } finally {+ duplicateLogic.unmount()+ }+ })++ it('still toasts when a logic outside the flag scene fails to load a flag', async () => {+ useMocks({ get: { [FLAG_URL]: () => [500, SERVER_ERROR_BODY] } })+ const triggerLogic = flagTriggerLogic({+ logicKey: 'test',+ flag: { id: MOCK_FEATURE_FLAG.id, key: MOCK_FEATURE_FLAG.key, variant: null },+ onChange: () => {},+ })+ try {+ await expectLogic(triggerLogic, () => {+ triggerLogic.mount()+ }).toDispatchActions(['loadFeatureFlagFailure'])++ expect(toastSpy).toHaveBeenCalledWith(`Load feature flag failed: ${SERVER_ERROR_BODY.detail}`)+ } finally {+ triggerLogic.unmount()+ }+ })++ it.each([+ ['a server error', 500],+ ['a missing flag', 404],+ ])('clears %s when a retry loads the flag', async (_desc, status) => {+ useMocks({ get: { [FLAG_URL]: () => [status, SERVER_ERROR_BODY] } })+ await remount()+ expect(logic.values.featureFlagMissing || logic.values.featureFlagLoadFailed).toBe(true)++ useMocks({ get: { [FLAG_URL]: () => [200, MOCK_FEATURE_FLAG] } })+ // Wait for the listeners, because the history already holds the success from the first mount.+ await expectLogic(logic, () => logic.actions.loadFeatureFlag()).toFinishAllListeners()++ expect(logic.values.featureFlagLoadFailed).toBe(false)+ expect(logic.values.featureFlagMissing).toBe(false)+ })++ it('separates a missing flag from a failed load in what it captures', async () => {+ const capture = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ try {+ useMocks({ get: { [FLAG_URL]: () => [404, { detail: 'Not found.' }] } })+ await remount()+ expect(capture).toHaveBeenCalledWith('feature flag not found')++ capture.mockClear()+ useMocks({ get: { [FLAG_URL]: () => [500, { detail: 'boom' }] } })+ await remount()+ expect(capture).toHaveBeenCalledWith('feature flag load failed', { status: 500 })+ } finally {+ capture.mockRestore()+ }+ })++ it('counts a failed load once per mount, however many retries fail', async () => {+ const capture = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ try {+ useMocks({ get: { [FLAG_URL]: () => [500, { detail: 'boom' }] } })+ await remount()+ await expectLogic(logic, () => logic.actions.loadFeatureFlag()).toDispatchActions([+ 'loadFeatureFlagFailure',+ ])++ expect(capture.mock.calls.filter(([event]) => event === 'feature flag load failed')).toHaveLength(1)+ } finally {+ capture.mockRestore()+ }+ })+ })+describe('saveFeatureFlag error handling', () => {it('shows the friendly permission toast on a save-time 403', async () => {useMocks({@@ -753,6 +923,41 @@ describe('featureFlagLogic', () => {}})+ it('offers a retry that saves the form as it is when clicked', async () => {+ silenceKeaLoadersErrors()+ const update = jest.spyOn(api, 'update').mockRejectedValue(new NetworkError('network'))+ const toastSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')+ try {+ await expectLogic(logic, () => logic.actions.editFeatureFlag(true)).toFinishAllListeners()+ logic.actions.setFeatureFlag({ ...logic.values.featureFlag, name: 'edited' })+ await expectLogic(logic, () => {+ logic.actions.submitFeatureFlag()+ }).toDispatchActions(['saveFeatureFlagFailure'])++ expect(toastSpy).toHaveBeenCalledWith(+ "We couldn't save this feature flag. Your changes are still here.",+ expect.objectContaining({ button: expect.objectContaining({ label: 'Try again' }) })+ )+ expect(logic.values.featureFlag.name).toBe('edited')++ // An edit made after the failure must not be lost when the retry saves.+ logic.actions.setFeatureFlag({ ...logic.values.featureFlag, name: 'edited again' })+ update.mockResolvedValue({ ...MOCK_FEATURE_FLAG, name: 'edited again' })+ await expectLogic(logic, () => {+ toastSpy.mock.calls[0][1]?.button?.action?.()+ }).toDispatchActions(['saveFeatureFlagSuccess'])++ expect(update).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({ name: 'edited again' })+ )+ } finally {+ update.mockRestore()+ toastSpy.mockRestore()+ resumeKeaLoadersErrors()+ }+ })+it('links the duplicate-key toast to the flag already using that key', async () => {useMocks({patch: {diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 548e034b4dba..26af1798f5ac 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -1029,6 +1029,7 @@ export interface featureFlagLogicValues {>featureFlagHasErrors: booleanfeatureFlagKey: string+ featureFlagLoadFailed: booleanfeatureFlagLoading: booleanfeatureFlagManualErrors: Record<string, any>featureFlagMissing: boolean@@ -1685,6 +1686,9 @@ export interface featureFlagLogicActions {errors: anyfilters: FeatureFlagFilters}+ setFeatureFlagLoadFailed: () => {+ value: true+ }setFeatureFlagManualErrors: (errors: Record<string, any>) => {errors: Record<string, any>}@@ -2312,6 +2316,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([setFeatureFlagFilters: (filters: FeatureFlagFilters, errors: any) => ({ filters, errors }),setSelectedTab: (tab: FeatureFlagsTab) => ({ tab }),setFeatureFlagMissing: true,+ setFeatureFlagLoadFailed: true,deleteFeatureFlag: (featureFlag: Partial<FeatureFlagType>) => ({ featureFlag }),setRemoteConfigEnabled: (enabled: boolean) => ({ enabled }),// The rules v2 editor keeps its draft in its own logic; this mirrors whether it has unsaved edits.@@ -2711,7 +2716,17 @@ export const featureFlagLogic = kea<featureFlagLogicType>([setSelectedTab: (_, { tab }) => tab,},],- featureFlagMissing: [false, { setFeatureFlagMissing: () => true }],+ featureFlagMissing: [false, { setFeatureFlagMissing: () => true, loadFeatureFlagSuccess: () => false }],+ // A retry does not clear this, so the retry banner stays mounted and shows its spinner.+ featureFlagLoadFailed: [+ false,+ {+ setFeatureFlagLoadFailed: () => true,+ setFeatureFlagMissing: () => false,+ setAccessDeniedToFeatureFlag: () => false,+ loadFeatureFlagSuccess: () => false,+ },+ ],isEditingFlag: [false,{@@ -3097,13 +3112,33 @@ export const featureFlagLogic = kea<featureFlagLogicType>([loadFeatureFlag: async () => {const sourceId = router.values.searchParams.sourceId+ // Only a 404 means the flag is gone. Any other failure says nothing about whether the+ // flag exists, so a page with no server state yet gets a retry banner instead.+ const getFlag = async (fetchFlag: () => Promise<FeatureFlagType>): Promise<FeatureFlagType> => {+ try {+ return await fetchFlag()+ } catch (e: any) {+ if (isAccessDeniedError(e)) {+ actions.setAccessDeniedToFeatureFlag()+ } else if (e?.status === 404) {+ actions.setFeatureFlagMissing()+ } else if (!values.originalFeatureFlag) {+ actions.setFeatureFlagLoadFailed()+ }+ throw e+ }+ }+// Used when "duplicating a feature flag". This populates the form with the source flag's data.const sourceFlag =props.id === 'new' && sourceId- ? ((await featureFlagsRetrieve(- String(values.currentProjectId),- Number(sourceId)- )) as unknown as FeatureFlagType)+ ? await getFlag(+ async () =>+ (await featureFlagsRetrieve(+ String(values.currentProjectId),+ Number(sourceId)+ )) as unknown as FeatureFlagType+ ): nullif (sourceFlag && !isV1FeatureFlagConfig(sourceFlag.filters)) {// The form edits only v1 documents, so a duplicate link to another version starts a blank flag.@@ -3141,30 +3176,28 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}if (props.id && props.id !== 'new' && props.id !== 'link') {- try {- // Get the flag first to check if it has an experiment- const retrievedFlag: FeatureFlagType = await api.featureFlags.get(props.id)-- // If there's an experiment, load it concurrently before returning to prevent UI flicker- if (retrievedFlag.experiment_set && retrievedFlag.experiment_set.length > 0) {- try {- const experiment = await api.experiments.get(retrievedFlag.experiment_set[0])- actions.loadExperimentSuccess(experiment)- } catch (error) {- // If experiment load fails, don't block the flag from loading- console.warn('Failed to load experiment:', error)- }- }+ // Get the flag first to check if it has an experiment+ const flagId = props.id+ const retrievedFlag = await getFlag(+ async () =>+ (await featureFlagsRetrieve(+ String(values.currentProjectId),+ flagId+ )) as unknown as FeatureFlagType+ )- return variantKeyToIndexFeatureFlagPayloads(retrievedFlag)- } catch (e: any) {- if (isAccessDeniedError(e)) {- actions.setAccessDeniedToFeatureFlag()- } else {- actions.setFeatureFlagMissing()+ // If there's an experiment, load it concurrently before returning to prevent UI flicker+ if (retrievedFlag.experiment_set && retrievedFlag.experiment_set.length > 0) {+ try {+ const experiment = await api.experiments.get(retrievedFlag.experiment_set[0])+ actions.loadExperimentSuccess(experiment)+ } catch (error) {+ // If experiment load fails, don't block the flag from loading+ console.warn('Failed to load experiment:', error)}- throw e}++ return variantKeyToIndexFeatureFlagPayloads(retrievedFlag)}// For new flags, load default evaluation contexts and set default tagsif (props.id === 'new') {@@ -4074,6 +4107,24 @@ export const featureFlagLogic = kea<featureFlagLogicType>([return}+ // initKea only toasts errors that carry a status, so a request that never reached the+ // server needs its own toast.+ if (errorObject?.status === undefined) {+ posthog.capture('feature flag save failed', { reason: errorObject?.name ?? null })+ // A form save retries through the form, so edits made after this failure are saved too.+ // Other saves (sidebar tags) are not in the working copy, so they resend their payload.+ const isFormSave = values.isEditingFlag || props.id === 'new'+ const failedPayload = cache.lastSaveAttempt+ lemonToast.error("We couldn't save this feature flag. Your changes are still here.", {+ button: {+ label: 'Try again',+ action: () =>+ isFormSave ? actions.submitFeatureFlag() : actions.saveFeatureFlag(failedPayload),+ },+ })+ return+ }+if (errorObject?.code !== 'unique' || errorObject?.attr !== 'key') {return}@@ -4227,9 +4278,8 @@ export const featureFlagLogic = kea<featureFlagLogicType>([toast.dismiss(agentChangeToastId(props.id))cache.agentRefreshFailedAttempt = (cache.agentRefreshFailedAttempt ?? 0) + 1cache.agentRefreshFailedToastId = agentRefreshFailedToastId(props.id, cache.agentRefreshFailedAttempt)- // The button retries this refresh rather than running the full loader, which marks the- // flag missing on any error except access denied. Nothing resets that state, so the scene- // would show Not Found over the flag and any unsaved edits until it remounts.+ // The button retries this refresh rather than running the full loader, because the full+ // loader replaces the working copy and discards any unsaved edits.lemonToast.error('PostHog AI changed this flag, but the page could not load the new values. It still shows the old ones.',{@@ -4315,6 +4365,41 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions.setMultivariateOptions(null)}},+ loadFeatureFlagFailure: ({ errorObject }) => {+ // Count each dead end once per mount, because a retry that fails again is the same dead end.+ if (values.featureFlagMissing) {+ if (!cache.hasCapturedFlagMissing) {+ cache.hasCapturedFlagMissing = true+ posthog.capture('feature flag not found')+ }+ return+ }+ if (values.featureFlagLoadFailed) {+ if (!cache.hasCapturedFlagLoadFailure) {+ cache.hasCapturedFlagLoadFailure = true+ // `status` separates a transport failure (no status) from a server one.+ posthog.capture('feature flag load failed', { status: errorObject?.status ?? null })+ }+ return+ }+ if (values.accessDeniedToFeatureFlag) {+ return+ }+ // A reload of a flag already on screen failed, and initKea does not toast this action.+ // kea-loaders keeps the previous working copy, so after Cancel it still shows the+ // discarded edits as if they were saved.+ lemonToast.error("We couldn't reload this feature flag. The page may not show its saved version.", {+ toastId: `feature-flag-reload-failed-${props.id}`,+ button: {+ label: 'Try again',+ action: () => actions.loadFeatureFlag(),+ },+ })+ },+ // The payload a non-form save retries with. Read in saveFeatureFlagFailure.+ saveFeatureFlag: (updatedFlag) => {+ cache.lastSaveAttempt = updatedFlag+ },loadFeatureFlagSuccess: async ({ featureFlag }) => {dismissAgentNotices(props.id, cache)// A ?tab=schedule deep link selects the tab before this load finishes, so thediff --git a/frontend/src/scenes/feature-flags/featureFlagNotebookWidgetViews.tsx b/frontend/src/scenes/feature-flags/featureFlagNotebookWidgetViews.tsxindex 283f738bf598..6887ce76527d 100644--- a/frontend/src/scenes/feature-flags/featureFlagNotebookWidgetViews.tsx+++ b/frontend/src/scenes/feature-flags/featureFlagNotebookWidgetViews.tsx@@ -18,6 +18,7 @@ import {import { FeatureFlagConfigReadonlyNotice } from 'products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice'import { FeatureFlagCodeExample } from './FeatureFlagCodeExample'+import { FeatureFlagLoadError } from './FeatureFlagLoadError'import { FeatureFlagLogicProps, featureFlagLogic } from './featureFlagLogic'import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'@@ -109,11 +110,16 @@ function FeatureFlagCompactSummary({attributes,}: NotebookNodeProps<FeatureFlagNotebookWidgetAttributes>): JSX.Element {const { id } = attributes- const { featureFlag, featureFlagLoading, featureFlagMissing } = useValues(featureFlagLogic({ id }))+ const { featureFlag, featureFlagLoading, featureFlagMissing, featureFlagLoadFailed } = useValues(+ featureFlagLogic({ id })+ )if (featureFlagMissing) {return <NotFound object="feature flag" />}+ if (featureFlagLoadFailed) {+ return <FeatureFlagLoadError id={id} />+ }if (featureFlagLoading && !featureFlag.id) {return <FeatureFlagWidgetLoading />}@@ -154,11 +160,16 @@ function FeatureFlagReleaseConditionsWidget({attributes,}: NotebookNodeProps<FeatureFlagNotebookWidgetAttributes>): JSX.Element {const { id } = attributes- const { featureFlag, featureFlagLoading, featureFlagMissing } = useValues(featureFlagLogic({ id }))+ const { featureFlag, featureFlagLoading, featureFlagMissing, featureFlagLoadFailed } = useValues(+ featureFlagLogic({ id })+ )if (featureFlagMissing) {return <NotFound object="feature flag" />}+ if (featureFlagLoadFailed) {+ return <FeatureFlagLoadError id={id} />+ }if (featureFlagLoading && !featureFlag.id) {return <FeatureFlagWidgetLoading />}@@ -182,11 +193,16 @@ function FeatureFlagImplementationWidget({attributes,}: NotebookNodeProps<FeatureFlagNotebookWidgetAttributes>): JSX.Element {const { id } = attributes- const { featureFlag, featureFlagLoading, featureFlagMissing } = useValues(featureFlagLogic({ id }))+ const { featureFlag, featureFlagLoading, featureFlagMissing, featureFlagLoadFailed } = useValues(+ featureFlagLogic({ id })+ )if (featureFlagMissing) {return <NotFound object="feature flag" />}+ if (featureFlagLoadFailed) {+ return <FeatureFlagLoadError id={id} />+ }if (featureFlagLoading && !featureFlag.id) {return <FeatureFlagWidgetLoading />}@@ -207,6 +223,7 @@ function FeatureFlagCompactEditor({ attributes }: NotebookNodeProps<FeatureFlagNfeatureFlag,featureFlagLoading,featureFlagMissing,+ featureFlagLoadFailed,hasUnsavedChanges,nonEmptyVariants,hasEarlyAccessFeatures,@@ -216,6 +233,9 @@ function FeatureFlagCompactEditor({ attributes }: NotebookNodeProps<FeatureFlagNif (featureFlagMissing) {return <NotFound object="feature flag" />}+ if (featureFlagLoadFailed) {+ return <FeatureFlagLoadError id={id} />+ }if (featureFlagLoading && !featureFlag.id) {return <FeatureFlagWidgetLoading />}diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsxindex b18a914558ff..5c1c3a2b0f32 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsx@@ -6,6 +6,7 @@ import { IconFlag, IconRocket } from '@posthog/icons'import { NotFound } from 'lib/components/NotFound'import { JSONContent } from 'lib/components/RichContentEditor/types'import { IconRecording, IconSurveys } from 'lib/lemon-ui/icons'+import { FeatureFlagLoadError } from 'scenes/feature-flags/FeatureFlagLoadError'import { FeatureFlagLogicProps, featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'import {FEATURE_FLAG_NOTEBOOK_WIDGET_VIEWS,@@ -116,12 +117,15 @@ function FeatureFlagNotebookActions({ attributes }: NotebookNodeProps<FeatureFlaconst Component = ({ attributes }: NotebookNodeProps<FeatureFlagNotebookWidgetAttributes>): JSX.Element => {const { id } = attributes- const { featureFlag, featureFlagMissing } = useValues(featureFlagLogic({ id }))+ const { featureFlag, featureFlagMissing, featureFlagLoadFailed } = useValues(featureFlagLogic({ id }))const { expanded } = useValues(notebookNodeLogic)if (featureFlagMissing) {return <NotFound object="feature flag" />}+ if (featureFlagLoadFailed) {+ return <FeatureFlagLoadError id={id} />+ }return (<>diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlagCodeExample.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlagCodeExample.tsxindex 72ee74bf252e..c61d7ecc4dc1 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlagCodeExample.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlagCodeExample.tsx@@ -4,6 +4,7 @@ import { useEffect } from 'react'import { NotFound } from 'lib/components/NotFound'import { JSONContent } from 'lib/components/RichContentEditor/types'import { FeatureFlagCodeExample } from 'scenes/feature-flags/FeatureFlagCodeExample'+import { FeatureFlagLoadError } from 'scenes/feature-flags/FeatureFlagLoadError'import { FeatureFlagLogicProps, featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'import { urls } from 'scenes/urls'@@ -13,7 +14,7 @@ import { notebookNodeLogic } from './notebookNodeLogic'const Component = ({ attributes }: NotebookNodeProps<NotebookNodeFlagCodeExampleAttributes>): JSX.Element => {const { id } = attributes- const { featureFlag, featureFlagMissing } = useValues(featureFlagLogic({ id }))+ const { featureFlag, featureFlagMissing, featureFlagLoadFailed } = useValues(featureFlagLogic({ id }))const { expanded } = useValues(notebookNodeLogic)const { setTitlePlaceholder } = useActions(notebookNodeLogic)@@ -25,6 +26,9 @@ const Component = ({ attributes }: NotebookNodeProps<NotebookNodeFlagCodeExampleif (featureFlagMissing) {return <NotFound object="feature flag" />}+ if (featureFlagLoadFailed) {+ return <FeatureFlagLoadError id={id} />+ }return <div className="p-2">{expanded && <FeatureFlagCodeExample featureFlag={featureFlag} />}</div>}