: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(flags): link duplicate-key error toast to existing flag (#80167)
Jordan Mryyan807c4eedc68b
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 497548dead4d..02699344cd17 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -61,6 +61,12 @@ other failures on these actions still toast.*/const ACCESS_DENIED_SELF_HANDLED = new Set(['saveFeatureFlag'])+/*+Write actions whose own logic toasts the duplicate-key 400 (code `unique` on attr `key`), so the+generic toast would be a second one. Owned by featureFlagLogic's saveFeatureFlagFailure listener.+*/+const DUPLICATE_KEY_SELF_HANDLED = new Set(['saveFeatureFlag'])+/*Transient gateway/proxy errors. These are infrastructure-level failures (the gateway can'treach the backend), not application bugs, so we still toast the user a retryable failure but@@ -160,6 +166,10 @@ export function initKea({// with this code is form validation (e.g. inviting an outside-domain email)// and must keep the generic error toast.const isVerifiedDomainError = error.code === 'verified_domain_required' && error.status === 403+ const isFeatureFlagDuplicateKey =+ error.code === 'unique' &&+ error.attr === 'key' &&+ DUPLICATE_KEY_SELF_HANDLED.has(String(actionKey))if (!errorMessage && error.status === 404) {errorMessage = 'URL not found'@@ -172,8 +182,13 @@ export function initKea({) {errorMessage = `Rate limit exceeded. Please try again ${error.formattedRetryAfter}.`}- if (isTwoFactorError || isSensitiveActionError || isVerifiedDomainError) {- // These get their own dedicated toast in apiStatusLogic.+ if (+ isTwoFactorError ||+ isSensitiveActionError ||+ isVerifiedDomainError ||+ isFeatureFlagDuplicateKey+ ) {+ // These are handled by their own dedicated toasts elsewhere.errorMessage = null}if (errorMessage) {diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 642e88ba0132..ed37f58416a0 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -322,6 +322,93 @@ describe('featureFlagLogic', () => {toastSpy.mockRestore()}})++ it('links the duplicate-key toast to the flag already using that key', async () => {+ useMocks({+ patch: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [+ 400,+ {+ type: 'validation_error',+ code: 'unique',+ attr: 'key',+ detail: 'There is already a feature flag with this key.',+ },+ ],+ },+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/`]: () => [+ 200,+ { results: [{ ...MOCK_FEATURE_FLAG, id: 42 }], count: 1 },+ ],+ },+ })+ const toastSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')+ const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null)+ try {+ await expectLogic(logic, () => {+ logic.actions.saveFeatureFlag(logic.values.featureFlag)+ })+ .toDispatchActions(['saveFeatureFlagFailure'])+ .toFinishAllListeners()++ // One toast means the generic loaders toast stayed suppressed (initKea.ts) and this+ // listener produced the only message; two would mean the suppression broke.+ expect(toastSpy).toHaveBeenCalledTimes(1)+ const [message, options] = toastSpy.mock.calls[0] as [+ string,+ { button?: { label: string; action: () => void } } | undefined,+ ]+ expect(message).toBe('Save feature flag failed: There is already a feature flag with this key.')+ expect(options?.button?.label).toBe('View existing flag')++ options?.button?.action()+ expect(openSpy).toHaveBeenCalledWith(urls.featureFlag(42), '_blank')+ } finally {+ toastSpy.mockRestore()+ openSpy.mockRestore()+ }+ })++ it.each([+ ['the list returns no matching flag', 200, { results: [], count: 0 }],+ ['the lookup request fails', 500, { type: 'server_error', detail: 'boom' }],+ ])('shows a plain duplicate-key toast when %s', async (_desc, listStatus, listBody) => {+ useMocks({+ patch: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [+ 400,+ {+ type: 'validation_error',+ code: 'unique',+ attr: 'key',+ detail: 'There is already a feature flag with this key.',+ },+ ],+ },+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/`]: () => [listStatus, listBody],+ },+ })+ const toastSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')+ const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null)+ try {+ await expectLogic(logic, () => {+ logic.actions.saveFeatureFlag(logic.values.featureFlag)+ })+ .toDispatchActions(['saveFeatureFlagFailure'])+ .toFinishAllListeners()++ expect(toastSpy).toHaveBeenCalledTimes(1)+ expect(toastSpy).toHaveBeenCalledWith(+ 'Save feature flag failed: There is already a feature flag with this key.'+ )+ expect(openSpy).not.toHaveBeenCalled()+ } finally {+ toastSpy.mockRestore()+ openSpy.mockRestore()+ }+ })})describe('saveFeatureFlag navigation', () => {diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex ae10433371b4..bd2d5cc968da 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -91,6 +91,7 @@ import { TEMPLATE_NAMES } from 'products/feature_flags/frontend/featureFlagTemplimport {featureFlagsCopyFlagsCreate,featureFlagsCopyFlagsDependencyRequirementsCreate,+ featureFlagsList,} from 'products/feature_flags/frontend/generated/api'import type { CopyFlagsDependencyRequirementsResponseApi } from 'products/feature_flags/frontend/generated/api.schemas'@@ -2898,6 +2899,8 @@ export const featureFlagLogic = kea<featureFlagLogicType>(["You don't have permission to edit this feature flag. Contact your administrator to request editing rights.")}+ // Duplicate-key (`unique`/`key`) is toasted in the saveFeatureFlagFailure listener so+ // the throw runs immediately and the form doesn't stay skeletoned during the lookup.throw error}},@@ -3512,7 +3515,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// Set all completed tasks at once to avoid conflictsglobalSetupLogic.findMounted()?.actions.markTaskAsCompleted(completedTasks)},- saveFeatureFlagFailure: ({ errorObject }) => {+ saveFeatureFlagFailure: async ({ errorObject }) => {if (values.featureFlag.id && handleApprovalRequired(errorObject, 'feature_flag', values.featureFlag.id)) {if (isOnFeatureFlagPage(props.id)) {// Redirect to detail page so user can see the CR banner@@ -3521,6 +3524,32 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}return}++ if (errorObject?.code !== 'unique' || errorObject?.attr !== 'key') {+ return+ }+ const message = `Save feature flag failed: ${errorObject.detail}`+ const key = values.featureFlag.key+ if (!key) {+ lemonToast.error(message)+ return+ }+ // The backend rejects on an exact key match, so pick the exact match out of the+ // case-insensitive list rather than trusting its newest-first ordering.+ const existing = await featureFlagsList(String(values.currentProjectId), { key }).catch(() => null)+ const existingFlagId = existing?.results?.find((flag) => flag.key === key)?.id ?? null+ if (existingFlagId) {+ lemonToast.error(message, {+ button: {+ label: 'View existing flag',+ action: () => {+ window.open(urls.featureFlag(existingFlagId), '_blank')+ },+ },+ })+ } else {+ lemonToast.error(message)+ }},updateFeatureFlagActiveSuccess: ({ featureFlagActiveUpdate }) => {if (featureFlagActiveUpdate) {