: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): say why a save stops on an incomplete release condition (#102441)
posthog[bot]cfd726f714b5
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.incompleteFilterOnSave.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.incompleteFilterOnSave.test.tsxnew file mode 100644index 000000000000..88f837e1a217--- /dev/null+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.incompleteFilterOnSave.test.tsx@@ -0,0 +1,140 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { Provider } from 'kea'+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { mockGetEventDefinitions, mockGetPropertyDefinitions } from '~/test/mocks'+import { FeatureFlagGroupType, FeatureFlagType, PropertyFilterType, PropertyOperator } from '~/types'++import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'+import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'+import { featureFlagReleaseConditionsLogic } from './featureFlagReleaseConditionsLogic'++jest.mock('lib/components/AutoSizer', () => ({+ AutoSizer: ({ renderProp }: { renderProp: (size: { height: number; width: number }) => React.ReactNode }) =>+ renderProp({ height: 400, width: 400 }),+}))++const INCOMPLETE_FILTER_MESSAGE = 'Add a value or remove this filter'++// A property picked from the taxonomic list starts with a null value, and the form blocks the save+// while that half-built row is on the flag.+function buildFilters(planValue: string | null = null): FeatureFlagType['filters'] {+ const groups: FeatureFlagGroupType[] = [+ {+ properties: [+ {+ key: 'email',+ value: 'is_set',+ operator: PropertyOperator.IsSet,+ type: PropertyFilterType.Person,+ },+ ],+ rollout_percentage: 100,+ variant: null,+ sort_key: 'group-1',+ },+ {+ properties: [+ {+ key: 'plan',+ value: planValue,+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Person,+ },+ ],+ rollout_percentage: 100,+ variant: null,+ sort_key: 'group-2',+ },+ ]+ return { groups, multivariate: null, payloads: {} }+}++describe('a save blocked by a collapsed condition set', () => {+ let logic: ReturnType<typeof featureFlagLogic.build>++ beforeEach(() => {+ initKeaTests()+ useMocks({+ get: {+ '/api/projects/:team/event_definitions': mockGetEventDefinitions,+ '/api/projects/:team/property_definitions': mockGetPropertyDefinitions,+ '/api/projects/:team/feature_flags/1234/': {+ id: 1234,+ key: 'test-flag',+ filters: { groups: [], multivariate: null, payloads: {} },+ },+ '/api/projects/:team/feature_flags/1234/status': { status: 'active', reason: 'mock reason' },+ '/api/projects/:team/actions': { results: [] },+ },+ post: {+ '/api/environments/:team/query': { results: [] },+ '/api/projects/:team/feature_flags/user_blast_radius': () => [200, { affected: 0, total: 2 }],+ },+ })+ logic = featureFlagLogic({ id: 1234 })+ logic.mount()+ })++ afterEach(() => {+ cleanup()+ logic.unmount()+ })++ it('opens the set that holds the value-less filter, and only that set', async () => {+ const filters = buildFilters()+ logic.actions.setFeatureFlag({ ...NEW_FLAG, id: 1234, key: 'test-flag', filters } as FeatureFlagType)+ render(+ <Provider>+ <FeatureFlagReleaseConditionsCollapsible+ id="1234"+ flagId={1234}+ filters={filters}+ onChange={logic.actions.setFeatureFlagFilters}+ />+ </Provider>+ )++ // Both sets start collapsed, which renders neither the inline error nor a scroll target.+ await waitFor(() => expect(screen.getByLabelText('Toggle condition 2 details')).toBeInTheDocument())+ expect(document.body).not.toHaveTextContent(INCOMPLETE_FILTER_MESSAGE)++ await expectLogic(logic, () => {+ logic.actions.submitFeatureFlag()+ }).toFinishAllListeners()++ await waitFor(() => expect(document.body).toHaveTextContent(INCOMPLETE_FILTER_MESSAGE))+ expect(featureFlagReleaseConditionsLogic.findMounted({ id: '1234' })?.values.openConditions).toEqual([+ 'condition-group-2',+ ])+ })++ it('blocks the save when a person removes the last value from a filter', async () => {+ const filters = buildFilters('free')+ logic.actions.setFeatureFlag({ ...NEW_FLAG, id: 1234, key: 'test-flag', filters } as FeatureFlagType)+ render(+ <Provider>+ <FeatureFlagReleaseConditionsCollapsible+ id="1234"+ flagId={1234}+ filters={filters}+ onChange={logic.actions.setFeatureFlagFilters}+ />+ </Provider>+ )++ fireEvent.click(await screen.findByLabelText('Toggle condition 2 details'))+ const valueChip = (await screen.findByTitle('free')).parentElement as HTMLElement+ fireEvent.click(valueChip.querySelector('.LemonSnack__close button') as HTMLElement)++ await expectLogic(logic, () => {+ logic.actions.submitFeatureFlag()+ }).toFinishAllListeners()++ await waitFor(() => expect(document.body).toHaveTextContent(INCOMPLETE_FILTER_MESSAGE))+ })+})diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsxindex ffc608557d9b..754b777f8bee 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx@@ -650,6 +650,7 @@ const ConditionContent = ({)}taxonomicFilterOptionsFromProp={filtersTaxonomicOptions}hasRowOperator={false}+ sendAllKeyUpdateserrorMessages={getPropertySelectErrorMessages(propertySelectErrors, index)}hideBehavioralCohorts={!realtimeCohortFlagTargeting}showCohortFlagTargetingdiff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 688b94072927..9dfa41d5cacf 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -126,12 +126,14 @@ import { uniformAggregationGroupTypeIndex } from './defaultReleaseConditionsUtilimport { FeatureFlagArchivedSource, reportFeatureFlagArchived } from './featureFlagArchiveDialog'import { checkFeatureFlagConfirmation } from './featureFlagConfirmationLogic'import type { FlagIntent } from './featureFlagIntentWarningLogic'+import { featureFlagReleaseConditionsLogic } from './featureFlagReleaseConditionsLogic'import {ProjectSelectOption,aggregateCopyResponse,errorMessageFrom,projectSelectOptions,} from './flagSelectionLogic'+import { PropertySelectError, getConditionSetErrors } from './propertySelectErrorMessages'import {ScheduleOccurrence,expandScheduleOccurrences,@@ -152,6 +154,22 @@ function reportFeatureFlagScheduleSuccess(): void {posthog.capture('feature flag scheduled')}+// A collapsed condition-set panel renders none of its children, so an inline release-condition+// error has no element to render into and `scrollToFormError` has nothing to scroll to. Open every+// set that holds a blocking error before the scroll runs.+function openConditionSets(flagId: string, conditionSetErrors: { index: number }[]): void {+ const releaseConditionsLogic = featureFlagReleaseConditionsLogic.findMounted({ id: flagId })+ if (!releaseConditionsLogic) {+ return+ }+ for (const { index } of conditionSetErrors) {+ const sortKey = releaseConditionsLogic.values.filters.groups[index]?.sort_key+ if (sortKey) {+ releaseConditionsLogic.actions.openCondition(sortKey)+ }+ }+}+const VALID_INTENTS: FlagIntent[] = ['local-eval', 'first-page-load']const TAB_SEARCH_PARAM = 'tab'@@ -3879,13 +3897,17 @@ export const featureFlagLogic = kea<featureFlagLogicType>([if (formErrors?.tags && !values.advancedPanelOpen) {actions.setAdvancedExpanded(true)}+ const conditionSetErrors = getConditionSetErrors(filtersErrors?.groups as PropertySelectError[] | undefined)+ openConditionSets(String(props.id), conditionSetErrors)// Yield so React flushes the expand-actions re-render before scrollToFormError schedules// its requestAnimationFrame callback — otherwise on browsers/scheduler combinations where// the render lands after RAF, `.Field--error` isn't in the DOM yet and the fallback toast// fires instead of scrolling to the error.await Promise.resolve()scrollToFormError({- fallbackErrorMessage: 'This flag has validation errors. Please review the highlighted fields above.',+ fallbackErrorMessage: conditionSetErrors.length+ ? `Condition set ${conditionSetErrors[0].index + 1} needs a fix: ${conditionSetErrors[0].message}`+ : 'This flag has validation errors. Please review the highlighted fields above.',})},updateFeatureFlagActiveFailure: ({ errorObject }) => {diff --git a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.tsindex 92108224a921..2c5f3d3c0422 100644--- a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts@@ -91,7 +91,7 @@ export function getBlastRadiusErrorMessage(error: BlastRadiusError, pluralName:// surfaced inline instead of failing with an opaque 400 on submit.function getPropertyValueError(property: AnyPropertyFilter): string | undefined {if (isEmptyProperty(property)) {- return "Property filters can't be empty"+ return 'Add a value or remove this filter'}if (isPropertyFilterWithOperator(property) && isOperatorSemver(property.operator)) {const allowWildcard = property.operator === PropertyOperator.SemverWildcarddiff --git a/frontend/src/scenes/feature-flags/propertySelectErrorMessages.tsx b/frontend/src/scenes/feature-flags/propertySelectErrorMessages.tsxindex 9a166f719f31..8b341f136eb1 100644--- a/frontend/src/scenes/feature-flags/propertySelectErrorMessages.tsx+++ b/frontend/src/scenes/feature-flags/propertySelectErrorMessages.tsx@@ -35,3 +35,15 @@ export function getPropertySelectErrorMessages(})return hasError ? messages : null}++// Condition sets that hold a blocking error, with the first message for each. A blocked save uses+// this to open the sets it has to open, and to name one when it can't scroll to the field.+export function getConditionSetErrors(+ propertySelectErrors: PropertySelectError[] | null | undefined+): { index: number; message: string }[] {+ return (propertySelectErrors ?? []).flatMap((error, index) => {+ const propertyMessage = error?.properties?.find((property) => typeof property?.value === 'string')?.value+ const message = propertyMessage ?? error?.rollout_percentage+ return message ? [{ index, message }] : []+ })+}