Skip to content

: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.

feat(flags): allow hiding stale evaluation context suggestions (#61719)

Gustavo H. Strassburger9f117e83bd5c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2704d5546242..eba28d9f4b37 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5995,9 +5995,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-error-tracking-configuration--light:
hash: v1.k794b7964.1da10a4331fb41fd378fad352c416601d4eedf888bf9aae5e270b1074468b957.RU3clHXF0srO7U8dAFNMBVfuvSYvXcj2NAnY2uJvG9Y
scenes-app-settings-environment--settings-environment-feature-flags--dark:
- hash: v1.k794b7964.da57f09dc2a46281190694062da7cf44a9c528eb27f834f2ae01b0ea940ff824.Uwfj_zKUG9Vian6Csuup4e9enicLXIapt-2IUAYReXk
+ hash: v1.k794b7964.4a627c125b4196ab9adfe9389e8fa20e9ba68c9110af68d1087ac9b6325da406.WVq_ojXXs-K3q725sJPCE3y4bmi1S_bf1T72JHY5vvE
scenes-app-settings-environment--settings-environment-feature-flags--light:
- hash: v1.k794b7964.2212126acb7ca31bd1b12dbc3a005e5432e04cafd7e12d0c6ce837ce71e3eb02.XtoRCdGDDADO1yjqHCQnnUhLQBYNZ4Anub3Y-WqpUzY
+ hash: v1.k794b7964.92334bc6fd2dd55af190426919a3b9e4d4adbfc11fb5b403c43e41ff5c807e0f.7rSxSA5cE1O6khSCYNePcBiM4iSKmdKYTzDOIbT-C3A
scenes-app-settings-environment--settings-environment-heatmaps--dark:
hash: v1.k794b7964.c5ae4e689d776785d04e8bde3a6675b2c0fc0ceeb813ad432d07bacd9facccc3.owsMNyDWX9zci-keIbmIuPyrbcpcucyoljX1RDy0n8g
scenes-app-settings-environment--settings-environment-heatmaps--light:
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts
index 066ca917d4ed..fc9f9393cda9 100644
--- a/frontend/src/mocks/handlers.ts
+++ b/frontend/src/mocks/handlers.ts
@@ -237,6 +237,7 @@ export const defaultMocks: Mocks = {
'/api/environments/:team_id/default_evaluation_contexts/': {
default_evaluation_contexts: [],
available_contexts: [],
+ hidden_contexts: [],
enabled: false,
},
'/api/environments/:team_id/file_system/unfiled/': { count: 0 },
diff --git a/frontend/src/scenes/feature-flags/EvaluationContextSuggestions.tsx b/frontend/src/scenes/feature-flags/EvaluationContextSuggestions.tsx
new file mode 100644
index 000000000000..c15b5895b242
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/EvaluationContextSuggestions.tsx
@@ -0,0 +1,87 @@
+import { useActions, useValues } from 'kea'
+
+import { IconUndo, IconX } from '@posthog/icons'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { defaultEvaluationContextsLogic } from './defaultEvaluationContextsLogic'
+
+export function EvaluationContextSuggestions(): JSX.Element | null {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { availableContexts, hiddenContexts, pendingContextName } = useValues(defaultEvaluationContextsLogic)
+ const { hideContext, unhideContext } = useActions(defaultEvaluationContextsLogic)
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+
+ if (!featureFlags[FEATURE_FLAGS.FLAG_EVALUATION_TAGS]) {
+ return null
+ }
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-muted">
+ These names are suggested when scoping a flag to evaluation contexts. Hiding a name only removes it from
+ the suggestion list — flags already using it keep working, and hidden names stay hidden until restored
+ from this settings page.
+ </p>
+
+ <div className="flex flex-col gap-2">
+ <h4 className="mb-0">Suggested contexts</h4>
+ {availableContexts.length === 0 ? (
+ <div className="text-sm text-muted italic">No suggested evaluation contexts.</div>
+ ) : (
+ <div className="flex flex-wrap gap-2 items-center">
+ {availableContexts.map((name) => (
+ <LemonTag key={name} type="default">
+ <span className="flex items-center gap-1">
+ {name}
+ <LemonButton
+ size="xsmall"
+ icon={<IconX />}
+ tooltip={`Hide "${name}" from suggestions`}
+ onClick={() => hideContext(name)}
+ disabledReason={
+ restrictedReason ?? (pendingContextName ? 'Saving…' : undefined)
+ }
+ loading={pendingContextName === name}
+ />
+ </span>
+ </LemonTag>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {hiddenContexts.length > 0 && (
+ <div className="flex flex-col gap-2">
+ <h4 className="mb-0">Hidden from suggestions</h4>
+ <div className="flex flex-wrap gap-2 items-center">
+ {hiddenContexts.map((name) => (
+ <LemonTag key={name} type="muted">
+ <span className="flex items-center gap-1">
+ {name}
+ <LemonButton
+ size="xsmall"
+ icon={<IconUndo />}
+ tooltip="Restore to suggestions"
+ onClick={() => unhideContext(name)}
+ disabledReason={
+ restrictedReason ?? (pendingContextName ? 'Saving…' : undefined)
+ }
+ loading={pendingContextName === name}
+ />
+ </span>
+ </LemonTag>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSettings.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSettings.tsx
index 5359133ab601..c04b3ae56151 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagSettings.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagSettings.tsx
@@ -183,7 +183,7 @@ export function FlagsSecureApiKeys(): JSX.Element {
</p>
</>
) : (
- <p className="text-xs text-muted mt-2">
+ <p className="text-xs text-muted mt-2 mb-0">
Rotating the key will move this primary key to backup so you can migrate safely.
</p>
)}
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
index 92462f38544f..0e1b0f2e2497 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
@@ -47,6 +47,7 @@ const meta: Meta = {
'/api/environments/:team_id/default_evaluation_contexts/': {
default_evaluation_contexts: [],
available_contexts: [],
+ hidden_contexts: [],
enabled: false,
},
},
diff --git a/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.test.ts b/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.test.ts
index dd880ef973b5..a7c5d6fb1da5 100644
--- a/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.test.ts
@@ -15,6 +15,7 @@ describe('defaultEvaluationContextsLogic', () => {
mockResponse = {
default_evaluation_contexts: [],
available_contexts: [],
+ hidden_contexts: [],
enabled: false,
}
@@ -31,11 +32,23 @@ describe('defaultEvaluationContextsLogic', () => {
name: contextName,
}
mockResponse.default_evaluation_contexts.push(newContext)
+ // Adding a default unhides the name, mirroring the admin backend behavior.
+ mockResponse.hidden_contexts = mockResponse.hidden_contexts.filter((c) => c !== contextName)
if (!mockResponse.available_contexts.includes(contextName)) {
mockResponse.available_contexts.push(contextName)
mockResponse.available_contexts.sort()
}
- return [200, { ...newContext, created: true }]
+ return [200, { ...newContext, created: true, hidden_from_suggestions: false }]
+ },
+ '/api/environments/:team_id/evaluation_context_suggestions/': async (req) => {
+ const body = await req.json()
+ const contextName = body.context_name
+ mockResponse.available_contexts = mockResponse.available_contexts.filter((c) => c !== contextName)
+ if (!mockResponse.hidden_contexts.includes(contextName)) {
+ mockResponse.hidden_contexts.push(contextName)
+ mockResponse.hidden_contexts.sort()
+ }
+ return [200, { success: true, name: contextName, hidden_from_suggestions: true }]
},
},
delete: {
@@ -46,6 +59,15 @@ describe('defaultEvaluationContextsLogic', () => {
)
return [200, { success: true }]
},
+ '/api/environments/:team_id/evaluation_context_suggestions/': (req) => {
+ const contextName = req.url.searchParams.get('context_name')
+ mockResponse.hidden_contexts = mockResponse.hidden_contexts.filter((c) => c !== contextName)
+ if (contextName && !mockResponse.available_contexts.includes(contextName)) {
+ mockResponse.available_contexts.push(contextName)
+ mockResponse.available_contexts.sort()
+ }
+ return [200, { success: true, name: contextName, hidden_from_suggestions: false }]
+ },
},
patch: {
'/api/environments/:team_id/': async (req) => {
@@ -73,6 +95,7 @@ describe('defaultEvaluationContextsLogic', () => {
defaultEvaluationContexts: {
default_evaluation_contexts: [],
available_contexts: [],
+ hidden_contexts: [],
enabled: false,
},
contexts: [],
@@ -81,6 +104,86 @@ describe('defaultEvaluationContextsLogic', () => {
})
})
+ describe('hiding and restoring suggestions', () => {
+ it('should hide a context from suggestions', async () => {
+ mockResponse.available_contexts = ['production', 'staging']
+
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadDefaultEvaluationContextsSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.hideContext('production')
+ })
+ .toDispatchActions(['hideContext', 'hideContextSuccess'])
+ .toMatchValues({
+ availableContexts: ['staging'],
+ hiddenContexts: ['production'],
+ })
+ })
+
+ it('should restore a hidden context to suggestions', async () => {
+ mockResponse.available_contexts = ['staging']
+ mockResponse.hidden_contexts = ['production']
+
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadDefaultEvaluationContextsSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.unhideContext('production')
+ })
+ .toDispatchActions(['unhideContext', 'unhideContextSuccess'])
+ .toMatchValues({
+ availableContexts: ['production', 'staging'],
+ hiddenContexts: [],
+ })
+ })
+
+ it('should leave availableContexts unchanged when hideContext API call fails', async () => {
+ mockResponse.available_contexts = ['production', 'staging']
+
+ useMocks({
+ post: {
+ '/api/environments/:team_id/evaluation_context_suggestions/': () => [400, { error: 'Bad request' }],
+ },
+ })
+
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadDefaultEvaluationContextsSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.hideContext('production')
+ })
+ .toDispatchActions(['hideContext', 'hideContextFailure'])
+ .toMatchValues({
+ availableContexts: ['production', 'staging'],
+ hiddenContexts: [],
+ })
+ })
+
+ it('should leave hiddenContexts unchanged when unhideContext API call fails', async () => {
+ mockResponse.available_contexts = ['staging']
+ mockResponse.hidden_contexts = ['production']
+
+ useMocks({
+ delete: {
+ '/api/environments/:team_id/evaluation_context_suggestions/': () => [400, { error: 'Bad request' }],
+ },
+ })
+
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadDefaultEvaluationContextsSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.unhideContext('production')
+ })
+ .toDispatchActions(['unhideContext', 'unhideContextFailure'])
+ .toMatchValues({
+ availableContexts: ['staging'],
+ hiddenContexts: ['production'],
+ })
+ })
+ })
+
describe('adding contexts', () => {
it('should add a new context', async () => {
logic.mount()
@@ -95,6 +198,22 @@ describe('defaultEvaluationContextsLogic', () => {
})
})
+ it('should drop a name from hiddenContexts when adding it unhides it', async () => {
+ mockResponse.hidden_contexts = ['production']
+
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadDefaultEvaluationContextsSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.addContext('production')
+ })
+ .toDispatchActions(['addContext', 'addContextSuccess'])
+ .toMatchValues({
+ availableContexts: ['production'],
+ hiddenContexts: [],
+ })
+ })
+
it('should clear input after adding context', async () => {
logic.mount()
await expectLogic(logic).toFinishAllListeners()
diff --git a/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.ts b/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.ts
index cd790fc20f53..54ec563ae372 100644
--- a/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.ts
+++ b/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.ts
@@ -15,6 +15,7 @@ export interface DefaultEvaluationContext {
export interface DefaultEvaluationContextsResponse {
default_evaluation_contexts: DefaultEvaluationContext[]
available_contexts: string[]
+ hidden_contexts: string[]
enabled: boolean
}
@@ -30,6 +31,8 @@ export const defaultEvaluationContextsLogic = kea<defaultEvaluationContextsLogic
loadDefaultEvaluationContexts: true,
addContext: (contextName: string) => ({ contextName }),
removeContext: (contextName: string) => ({ contextName }),
+ hideContext: (contextName: string) => ({ contextName }),
+ unhideContext: (contextName: string) => ({ contextName }),
toggleEnabled: (enabled: boolean) => ({ enabled }),
setNewContextInput: (value: string) => ({ value }),
setIsAdding: (isAdding: boolean) => ({ isAdding }),
@@ -50,6 +53,17 @@ export const defaultEvaluationContextsLogic = kea<defaultEvaluationContextsLogic
addContext: () => false,
},
],
+ pendingContextName: [
+ null as string | null,
+ {
+ hideContext: (_, { contextName }) => contextName,
+ unhideContext: (_, { contextName }) => contextName,
+ hideContextSuccess: () => null,
+ hideContextFailure: () => null,
+ unhideContextSuccess: () => null,
+ unhideContextFailure: () => null,
+ },
+ ],
}),
loaders(({ values }) => ({
@@ -83,6 +97,11 @@ export const defaultEvaluationContextsLogic = kea<defaultEvaluationContextsLogic
}
if (response.created) {
+ // The server unhides the name when an admin adds it as a default, so drop it
+ // from hidden_contexts when the response reports it's no longer hidden.
+ const hiddenContexts = response.hidden_from_suggestions
+ ? currentData.hidden_contexts
+ : currentData.hidden_contexts.filter((name) => name !== response.name)
return {
...currentData,
default_evaluation_contexts: [
@@ -90,6 +109,7 @@ export const defaultEvaluationContextsLogic = kea<defaultEvaluationContextsLogic
{ id: response.id, name: response.name },
],
available_contexts: [...currentData.available_contexts, response.name].sort(),
+ hidden_contexts: hiddenContexts,
}
}
@@ -127,6 +147,60 @@ export const defaultEvaluationContextsLogic = kea<defaultEvaluationContextsLogic
throw error
}
},
+
+ hideContext: async ({ contextName }) => {
+ const teamId = values.currentTeam?.id
+ if (!teamId) {
+ throw new Error('No team selected')
+ }
+
+ try {
+ await api.create(`/api/environments/${teamId}/evaluation_context_suggestions/`, {
+ context_name: contextName,
+ })
+
+ const currentData = values.defaultEvaluationContexts
+ if (!currentData) {
+ return currentData
+ }
+
+ return {
+ ...currentData,
+ available_contexts: currentData.available_contexts.filter((name) => name !== contextName),
+ hidden_contexts: [...currentData.hidden_contexts, contextName].sort(),
+ }
+ } catch (error: any) {
+ lemonToast.error(error.error || error.detail || 'Failed to hide suggestion')
+ throw error
+ }
+ },
+
+ unhideContext: async ({ contextName }) => {
+ const teamId = values.currentTeam?.id
+ if (!teamId) {
+ throw new Error('No team selected')
+ }
+
+ try {
+ await api.delete(
+ `/api/environments/${teamId}/evaluation_context_suggestions/?context_name=${encodeURIComponent(contextName)}`
+ )
+
+ const currentData = values.defaultEvaluationContexts
+ if (!currentData) {
+ return currentData
+ }
+
+ return {
+ ...currentData,
+ available_contexts: [...currentData.available_contexts, contextName].sort(),
+ hidden_contexts: currentData.hidden_contexts.filter((name) => name !== contextName),
+ }
+ } catch (error: any) {
+ lemonToast.error(error.error || error.detail || 'Failed to restore suggestion')
+ throw error
+ }
+ },
},
],
})),
@@ -145,6 +219,14 @@ export const defaultEvaluationContextsLogic = kea<defaultEvaluationContextsLogic
removeContextSuccess: () => {
lemonToast.success('Context removed from default evaluation contexts')
},
+
+ hideContextSuccess: () => {
+ lemonToast.success('Context hidden from suggestions')
+ },
+
+ unhideContextSuccess: () => {
+ lemonToast.success('Context restored to suggestions')
+ },
})),
selectors({
@@ -155,6 +237,8 @@ export const defaultEvaluationContextsLogic = kea<defaultEvaluationContextsLogic
availableContexts: [(s) => [s.defaultEvaluationContexts], (data): string[] => data?.available_contexts || []],
+ hiddenContexts: [(s) => [s.defaultEvaluationContexts], (data): string[] => data?.hidden_contexts || []],
+
isEnabled: [(s) => [s.currentTeam], (team): boolean => team?.default_evaluation_contexts_enabled || false],
canAddMoreContexts: [(s) => [s.contexts], (contexts): boolean => contexts.length < 10],
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 5fa9c2badc06..3588cf41ff86 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -78,6 +78,7 @@ import { ExperimentRecalculationTime } from './environment/ExperimentRecalculati
import {
DefaultEvaluationContexts,
DefaultReleaseConditions,
+ EvaluationContextSuggestions,
FlagChangeConfirmationSettings,
FlagPersistenceSettings,
FlagsSecureApiKeys,
@@ -661,6 +662,16 @@ export const SETTINGS_MAP: SettingSection[] = [
component: <DefaultReleaseConditions />,
keywords: ['release', 'conditions', 'default', 'rollout', 'groups'],
},
+ {
+ id: 'feature-flag-evaluation-context-suggestions',
+ title: 'Evaluation context suggestions',
+ description:
+ 'Manage which evaluation context names are suggested when scoping a feature flag. Hide stale or mistyped names from the suggestion list without affecting flags that already use them.',
+ docsUrl: 'https://posthog.com/docs/feature-flags/evaluation-contexts',
+ flag: 'FLAG_EVALUATION_TAGS',
+ component: <EvaluationContextSuggestions />,
+ keywords: ['evaluation', 'context', 'suggestion', 'hide', 'tag'],
+ },
{
id: 'feature-flag-secure-api-key',
title: 'Feature flags secure API key',
diff --git a/frontend/src/scenes/settings/environment/FeatureFlagSettings.tsx b/frontend/src/scenes/settings/environment/FeatureFlagSettings.tsx
index 8f29b0b50de8..1e8b42a041c9 100644
--- a/frontend/src/scenes/settings/environment/FeatureFlagSettings.tsx
+++ b/frontend/src/scenes/settings/environment/FeatureFlagSettings.tsx
@@ -4,5 +4,6 @@ export {
FlagsSecureApiKeys,
} from 'scenes/feature-flags/FeatureFlagSettings'
export { RequireEvaluationContexts } from 'scenes/feature-flags/RequireEvaluationContexts'
+export { EvaluationContextSuggestions } from 'scenes/feature-flags/EvaluationContextSuggestions'
export { DefaultEvaluationContexts } from 'scenes/feature-flags/DefaultEvaluationContexts'
export { DefaultReleaseConditions } from 'scenes/feature-flags/DefaultReleaseConditions'
diff --git a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
index 70397c28504d..a9a73614ebc3 100644
--- a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
@@ -44,6 +44,7 @@ const meta: Meta<StoryProps> = {
'/api/environments/:id/default_evaluation_contexts/': {
default_evaluation_contexts: [],
available_contexts: [],
+ hidden_contexts: [],
enabled: false,
},
},
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 4061ab6d79b2..ff715fe9a4ea 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -152,6 +152,7 @@ export type SettingId =
| 'feature-flag-confirmation'
| 'feature-flag-default-evaluation-contexts'
| 'feature-flag-default-release-conditions'
+ | 'feature-flag-evaluation-context-suggestions'
| 'feature-flag-require-evaluation-contexts'
| 'feature-flag-secure-api-key'
| 'feature-flags-interface'
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 51d35f282a8b..c269af9878d7 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -12,7 +12,8 @@ from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.dateparse import parse_datetime
-from drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_view
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
from loginas.utils import is_impersonated_session
from opentelemetry import trace
from pydantic import TypeAdapter
@@ -1582,6 +1583,24 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
)
+class EvaluationContextSuggestionRequestSerializer(serializers.Serializer):
+ context_name = serializers.CharField(
+ max_length=255,
+ help_text=(
+ "Name of the evaluation context to hide from (POST) or restore to (DELETE) "
+ "the flag editor's suggestion list. Case-insensitive and whitespace-trimmed."
+ ),
+ )
+
+
+class EvaluationContextSuggestionResponseSerializer(serializers.Serializer):
+ success = serializers.BooleanField(help_text="Whether the suggestion visibility change was applied.")
+ name = serializers.CharField(help_text="Normalized name of the affected evaluation context.")
+ hidden_from_suggestions = serializers.BooleanField(
+ help_text="Whether the context is now hidden from the flag editor's suggestion list."
+ )
+
+
class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
"""
Projects for the current organization.
@@ -1593,6 +1612,13 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
lookup_field = "id"
ordering = "-created_by"
+ # Actions whose scope is downgraded to project:read for session auth on all methods.
+ # TeamMemberLightManagementPermission still applies, so DELETE requires admin.
+ MEMBER_READABLE_CONFIG_ACTIONS = ("default_release_conditions", "default_evaluation_contexts")
+
+ # Actions whose GET is downgraded to project:read for session auth; mutating methods stay on project:write/admin.
+ GET_DOWNGRADE_ACTIONS = ("evaluation_context_suggestions",)
+
def safely_get_queryset(self, queryset):
user = cast(User, self.request.user)
# IMPORTANT: This is actually what ensures that a user cannot read/update a project for which they don't have permission
@@ -1633,7 +1659,13 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
# Team-level config actions that any member should be able to edit via the UI.
# Only downgrade for session auth to preserve read-only API key semantics.
- if self.action in ("default_release_conditions", "default_evaluation_contexts"):
+ if self.action in self.MEMBER_READABLE_CONFIG_ACTIONS:
+ is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
+ if is_session_auth:
+ return ["project:read"]
+
+ # Read-only access for member-readable actions — only downgrade GET, not writes.
+ if self.action in self.GET_DOWNGRADE_ACTIONS and request.method == "GET":
is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
if is_session_auth:
return ["project:read"]
@@ -1663,8 +1695,14 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
else:
permissions.append(OrganizationMemberPermissions)
elif self.action != "list":
- # Skip TeamMemberAccessPermission for list action, as list is serialized with limited TeamBasicSerializer
- permissions.append(TeamMemberLightManagementPermission)
+ # Skip TeamMemberAccessPermission for list action, as list is serialized with limited TeamBasicSerializer.
+ # GET_DOWNGRADE_ACTIONS writes stay admin-gated via TeamMemberStrictManagementPermission.
+ if self.action in self.GET_DOWNGRADE_ACTIONS:
+ if self.request.method != "GET":
+ # Writes need strict (admin for all non-safe methods), not light (which only gates DELETE).
+ permissions.append(TeamMemberStrictManagementPermission)
+ else:
+ permissions.append(TeamMemberLightManagementPermission)
return [permission() for permission in permissions]
@@ -1894,17 +1932,26 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
def default_evaluation_contexts(self, request: request.Request, id: str, **kwargs) -> response.Response:
"""Manage default evaluation contexts for a team."""
team = self.get_object()
+ # Feature flags persist contexts under the project root team (RootTeamMixin), so scope
+ # context lookups to the root team — otherwise flag-used contexts are invisible from
+ # child environments.
+ root_team = team.parent_team or team
if request.method == "GET":
- defaults = TeamDefaultEvaluationContext.objects.filter(team=team).select_related("evaluation_context")
+ defaults = TeamDefaultEvaluationContext.objects.filter(team=root_team).select_related("evaluation_context")
defaults_data = [{"id": d.id, "name": d.evaluation_context.name} for d in defaults]
- all_contexts = list(
- EvaluationContext.objects.filter(team=team).values_list("name", flat=True).order_by("name")
+ all_contexts_qs = list(
+ EvaluationContext.objects.filter(team=root_team)
+ .values_list("name", "hidden_from_suggestions")
+ .order_by("name")
)
+ all_contexts = [name for name, hidden in all_contexts_qs if not hidden]
+ hidden_contexts = [name for name, hidden in all_contexts_qs if hidden]
return response.Response(
{
"default_evaluation_contexts": defaults_data,
"available_contexts": all_contexts,
+ "hidden_contexts": hidden_contexts,
"enabled": team.default_evaluation_contexts_enabled,
}
)
@@ -1920,13 +1967,18 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
return response.Response({"error": "context_name must be at most 255 characters"}, status=400)
with transaction.atomic():
- existing = list(TeamDefaultEvaluationContext.objects.filter(team=team).select_for_update())
+ existing = list(TeamDefaultEvaluationContext.objects.filter(team=root_team).select_for_update())
if len(existing) >= 10:
return response.Response({"error": "Maximum of 10 default evaluation contexts allowed"}, status=400)
- ctx, _ = EvaluationContext.objects.get_or_create(name=context_name, team=team)
+ ctx, _ = EvaluationContext.objects.get_or_create(name=context_name, team=root_team)
+ if ctx.hidden_from_suggestions:
+ level = self.user_permissions.team(team).effective_membership_level
+ if level is not None and level >= OrganizationMembership.Level.ADMIN:
+ ctx.hidden_from_suggestions = False
+ ctx.save(update_fields=["hidden_from_suggestions"])
default_ctx, created = TeamDefaultEvaluationContext.objects.get_or_create(
- team=team, evaluation_context=ctx
+ team=root_team, evaluation_context=ctx
)
if created:
@@ -1938,7 +1990,14 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
request=request,
)
- return response.Response({"id": default_ctx.id, "name": ctx.name, "created": created})
+ return response.Response(
+ {
+ "id": default_ctx.id,
+ "name": ctx.name,
+ "created": created,
+ "hidden_from_suggestions": ctx.hidden_from_suggestions,
+ }
+ )
else: # DELETE
context_name = request.data.get("context_name", "") or request.GET.get("context_name", "")
@@ -1950,9 +2009,9 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
with transaction.atomic():
try:
- ctx = EvaluationContext.objects.get(name=context_name, team=team)
+ ctx = EvaluationContext.objects.get(name=context_name, team=root_team)
deleted_count, _ = TeamDefaultEvaluationContext.objects.filter(
- team=team, evaluation_context=ctx
+ team=root_team, evaluation_context=ctx
).delete()
if deleted_count > 0:
@@ -1968,6 +2027,69 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
except EvaluationContext.DoesNotExist:
return response.Response({"error": "Evaluation context not found"}, status=404)
+ @extend_schema(
+ methods=["POST"],
+ request=EvaluationContextSuggestionRequestSerializer,
+ responses={200: EvaluationContextSuggestionResponseSerializer},
+ extensions={"x-product": "feature_flags"},
+ )
+ @extend_schema(
+ methods=["DELETE"],
+ parameters=[
+ OpenApiParameter(
+ name="context_name",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Name of the evaluation context to restore to suggestions.",
+ )
+ ],
+ responses={200: EvaluationContextSuggestionResponseSerializer},
+ extensions={"x-product": "feature_flags"},
+ )
+ @action(
+ methods=["POST", "DELETE"],
+ detail=True,
+ permission_classes=[IsAuthenticated],
+ )
+ def evaluation_context_suggestions(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ """Hide an evaluation context name from the flag editor's suggestion list, or restore it.
+
+ POST hides the name; DELETE restores it. The underlying context row and any flags already
+ using it are never modified — this only controls what gets suggested.
+ """
+ team = self.get_object()
+ # Contexts are persisted under the project root team (see default_evaluation_contexts).
+ root_team = team.parent_team or team
+
+ context_name = request.data.get("context_name", "") or request.GET.get("context_name", "")
+ if not isinstance(context_name, str):
+ return response.Response({"error": "context_name must be a string"}, status=400)
+ context_name = normalize_context_name(context_name)
+ if not context_name:
+ return response.Response({"error": "context_name is required"}, status=400)
+
+ hidden = request.method == "POST"
+
+ with transaction.atomic():
+ try:
+ ctx = EvaluationContext.objects.select_for_update().get(name=context_name, team=root_team)
+ except EvaluationContext.DoesNotExist:
+ return response.Response({"error": "Evaluation context not found"}, status=404)
+
+ if ctx.hidden_from_suggestions != hidden:
+ ctx.hidden_from_suggestions = hidden
+ ctx.save(update_fields=["hidden_from_suggestions"])
+ report_user_action(
+ cast(User, request.user),
+ "evaluation context suggestion hidden" if hidden else "evaluation context suggestion restored",
+ {"team_id": team.id, "context_name": context_name},
+ team=team,
+ request=request,
+ )
+
+ return response.Response({"success": True, "name": context_name, "hidden_from_suggestions": hidden})
+
@action(
methods=["GET"],
detail=True,
diff --git a/posthog/models/team/util.py b/posthog/models/team/util.py
index ecd221f87bcb..c77d871eaa27 100644
--- a/posthog/models/team/util.py
+++ b/posthog/models/team/util.py
@@ -20,6 +20,8 @@ actions_that_require_current_team = [
"generate_conversations_public_token",
"default_release_conditions",
"experiments_config",
+ "default_evaluation_contexts",
+ "evaluation_context_suggestions",
]
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index 0b92f2bd4697..66c5bfa77122 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -3023,7 +3023,8 @@
"posthog_evaluationcontext"."id",
"posthog_evaluationcontext"."name",
"posthog_evaluationcontext"."team_id",
- "posthog_evaluationcontext"."created_at"
+ "posthog_evaluationcontext"."created_at",
+ "posthog_evaluationcontext"."hidden_from_suggestions"
FROM "posthog_featureflagevaluationcontext"
INNER JOIN "posthog_evaluationcontext" ON ("posthog_featureflagevaluationcontext"."evaluation_context_id" = "posthog_evaluationcontext"."id")
WHERE "posthog_featureflagevaluationcontext"."feature_flag_id" IN (1,
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
index cc670fca62f8..6438cfa519c3 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
@@ -4167,7 +4167,8 @@
"posthog_evaluationcontext"."id",
"posthog_evaluationcontext"."name",
"posthog_evaluationcontext"."team_id",
- "posthog_evaluationcontext"."created_at"
+ "posthog_evaluationcontext"."created_at",
+ "posthog_evaluationcontext"."hidden_from_suggestions"
FROM "posthog_featureflagevaluationcontext"
INNER JOIN "posthog_evaluationcontext" ON ("posthog_featureflagevaluationcontext"."evaluation_context_id" = "posthog_evaluationcontext"."id")
WHERE "posthog_featureflagevaluationcontext"."feature_flag_id" = 99999
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py b/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py
index 26ebdcf6d99d..c4bdec47b939 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py
@@ -1,9 +1,17 @@
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from parameterized import parameterized
from rest_framework import status
-from products.feature_flags.backend.models.evaluation_context import EvaluationContext, TeamDefaultEvaluationContext
+from posthog.models import Team
+from posthog.models.organization import OrganizationMembership
+
+from products.feature_flags.backend.models.evaluation_context import (
+ EvaluationContext,
+ FeatureFlagEvaluationContext,
+ TeamDefaultEvaluationContext,
+)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -205,3 +213,222 @@ class TestFeatureFlagDefaultEnvironments(APIBaseTest):
flag = FeatureFlag.objects.get(key="test-flag-no-defaults", team=self.team)
self.assertEqual(flag.tagged_items.count(), 0)
self.assertEqual(flag.flag_evaluation_contexts.count(), 0)
+
+
+class TestEvaluationContextSuggestions(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.url = "/api/environments/@current/evaluation_context_suggestions/"
+ self.get_url = "/api/environments/@current/default_evaluation_contexts/"
+
+ def _create_context(self, name: str) -> EvaluationContext:
+ ctx, _ = EvaluationContext.objects.get_or_create(name=name, team=self.team)
+ return ctx
+
+ def test_hide_context_removes_it_from_suggestions(self):
+ self._create_context("production")
+ self._create_context("staging")
+
+ response = self.client.post(self.url, {"context_name": "production"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True, "name": "production", "hidden_from_suggestions": True})
+
+ data = self.client.get(self.get_url).json()
+ self.assertEqual(data["available_contexts"], ["staging"])
+ self.assertEqual(data["hidden_contexts"], ["production"])
+
+ def test_restore_hidden_context(self):
+ ctx = self._create_context("production")
+ ctx.hidden_from_suggestions = True
+ ctx.save()
+
+ response = self.client.delete(self.url + "?context_name=production")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True, "name": "production", "hidden_from_suggestions": False})
+
+ ctx.refresh_from_db()
+ self.assertFalse(ctx.hidden_from_suggestions)
+
+ data = self.client.get(self.get_url).json()
+ self.assertEqual(data["available_contexts"], ["production"])
+ self.assertEqual(data["hidden_contexts"], [])
+
+ def test_hiding_preserves_row_and_flag_links(self):
+ ctx = self._create_context("production")
+ flag = FeatureFlag.objects.create(key="my-flag", name="My Flag", team=self.team, created_by=self.user)
+ link = FeatureFlagEvaluationContext.objects.create(feature_flag=flag, evaluation_context=ctx)
+
+ response = self.client.post(self.url, {"context_name": "production"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ self.assertTrue(EvaluationContext.objects.filter(id=ctx.id).exists())
+ self.assertTrue(FeatureFlagEvaluationContext.objects.filter(id=link.id).exists())
+ ctx.refresh_from_db()
+ self.assertTrue(ctx.hidden_from_suggestions)
+
+ def test_hide_normalizes_name(self):
+ self._create_context("production")
+
+ response = self.client.post(self.url, {"context_name": " PRODUCTION "}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertTrue(EvaluationContext.objects.get(name="production", team=self.team).hidden_from_suggestions)
+
+ def test_hide_nonexistent_context_returns_404(self):
+ response = self.client.post(self.url, {"context_name": "ghost"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_hide_requires_context_name(self):
+ response = self.client.post(self.url, {"context_name": " "}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_cannot_hide_context_from_another_team(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+ EvaluationContext.objects.create(name="secret", team=other_team)
+
+ response = self.client.post(self.url, {"context_name": "secret"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertFalse(EvaluationContext.objects.get(name="secret", team=other_team).hidden_from_suggestions)
+
+ def test_hide_is_idempotent(self):
+ self._create_context("production")
+
+ with patch("posthog.api.team.report_user_action") as mock_report:
+ self.client.post(self.url, {"context_name": "production"}, format="json")
+ self.assertEqual(mock_report.call_count, 1)
+
+ response = self.client.post(self.url, {"context_name": "production"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(mock_report.call_count, 1)
+
+ def test_restore_is_idempotent(self):
+ ctx = self._create_context("production")
+ ctx.hidden_from_suggestions = True
+ ctx.save()
+
+ with patch("posthog.api.team.report_user_action") as mock_report:
+ response = self.client.delete(self.url + "?context_name=production")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(mock_report.call_count, 1)
+
+ response = self.client.delete(self.url + "?context_name=production")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(mock_report.call_count, 1)
+
+ def test_member_cannot_write_evaluation_context_suggestions(self):
+ self._create_context("production")
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ response = self.client.post(self.url, {"context_name": "production"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ ctx = self._create_context("staging")
+ ctx.hidden_from_suggestions = True
+ ctx.save()
+ response = self.client.delete(self.url + "?context_name=staging")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_member_can_read_default_evaluation_contexts(self):
+ self._create_context("production")
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ response = self.client.get(self.get_url)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_adding_hidden_context_as_default_unhides_it(self):
+ ctx = self._create_context("production")
+ ctx.hidden_from_suggestions = True
+ ctx.save()
+
+ response = self.client.post(self.get_url, {"context_name": "production"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertTrue(response.json()["created"])
+
+ ctx.refresh_from_db()
+ self.assertFalse(ctx.hidden_from_suggestions)
+
+ data = self.client.get(self.get_url).json()
+ self.assertIn("production", data["available_contexts"])
+ self.assertNotIn("production", data["hidden_contexts"])
+
+ def test_member_adding_hidden_context_as_default_does_not_unhide_it(self):
+ ctx = self._create_context("production")
+ ctx.hidden_from_suggestions = True
+ ctx.save()
+
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ response = self.client.post(self.get_url, {"context_name": "production"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertTrue(response.json()["created"])
+
+ ctx.refresh_from_db()
+ self.assertTrue(ctx.hidden_from_suggestions)
+
+ data = self.client.get(self.get_url).json()
+ self.assertNotIn("production", data["available_contexts"])
+ self.assertIn("production", data["hidden_contexts"])
+
+ def test_member_can_post_but_not_delete_default_evaluation_contexts(self):
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ response = self.client.post(self.get_url, {"context_name": "production"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ response = self.client.delete(self.get_url, {"context_name": "production"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+
+class TestEvaluationContextRootTeamScoping(APIBaseTest):
+ """Flags persist contexts under the project root team, so contexts must be visible and
+ manageable from any child environment of the same project — not just the root."""
+
+ def setUp(self):
+ super().setUp()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ # self.team is the project root (no parent_team); add a sibling child environment.
+ self.child_env = Team.objects.create(
+ organization=self.organization,
+ parent_team=self.team,
+ name="child-env",
+ )
+ self.get_url = f"/api/environments/{self.child_env.id}/default_evaluation_contexts/"
+ self.suggestions_url = f"/api/environments/{self.child_env.id}/evaluation_context_suggestions/"
+
+ @parameterized.expand(
+ [
+ ("visible", False, "available_contexts"),
+ ("hidden", True, "hidden_contexts"),
+ ]
+ )
+ def test_root_team_context_visible_from_child_environment(self, _name, hidden, bucket):
+ EvaluationContext.objects.create(name="production", team=self.team, hidden_from_suggestions=hidden)
+
+ data = self.client.get(self.get_url).json()
+ self.assertEqual(data[bucket], ["production"])
+
+ def test_hide_and_restore_root_team_context_from_child_environment(self):
+ ctx = EvaluationContext.objects.create(name="production", team=self.team)
+
+ hide = self.client.post(self.suggestions_url, {"context_name": "production"}, format="json")
+ self.assertEqual(hide.status_code, status.HTTP_200_OK)
+ ctx.refresh_from_db()
+ self.assertTrue(ctx.hidden_from_suggestions)
+
+ restore = self.client.delete(self.suggestions_url + "?context_name=production")
+ self.assertEqual(restore.status_code, status.HTTP_200_OK)
+ ctx.refresh_from_db()
+ self.assertFalse(ctx.hidden_from_suggestions)
+
+ def test_adding_default_from_child_environment_persists_under_root_team(self):
+ response = self.client.post(self.get_url, {"context_name": "production"}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ self.assertTrue(EvaluationContext.objects.filter(name="production", team=self.team).exists())
+ self.assertFalse(EvaluationContext.objects.filter(name="production", team=self.child_env).exists())
diff --git a/products/feature_flags/backend/migrations/0003_evaluationcontext_hidden_from_suggestions.py b/products/feature_flags/backend/migrations/0003_evaluationcontext_hidden_from_suggestions.py
new file mode 100644
index 000000000000..1c1eb5c23dd4
--- /dev/null
+++ b/products/feature_flags/backend/migrations/0003_evaluationcontext_hidden_from_suggestions.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("feature_flags", "0002_migrate_feature_flags_models"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="evaluationcontext",
+ name="hidden_from_suggestions",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/feature_flags/backend/migrations/max_migration.txt b/products/feature_flags/backend/migrations/max_migration.txt
index ba97bd43605d..8340a5df9e39 100644
--- a/products/feature_flags/backend/migrations/max_migration.txt
+++ b/products/feature_flags/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0002_migrate_feature_flags_models
+0003_evaluationcontext_hidden_from_suggestions
diff --git a/products/feature_flags/backend/models/evaluation_context.py b/products/feature_flags/backend/models/evaluation_context.py
index d7a2908c6f68..3465d19e849e 100644
--- a/products/feature_flags/backend/models/evaluation_context.py
+++ b/products/feature_flags/backend/models/evaluation_context.py
@@ -27,6 +27,9 @@ class EvaluationContext(UUIDModel):
name = models.CharField(max_length=255)
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="evaluation_context_set")
created_at = models.DateTimeField(auto_now_add=True)
+ # When True, this context name is hidden from the flag editor's suggestion list. The row and any
+ # flags already using it are left untouched — this only affects what gets suggested.
+ hidden_from_suggestions = models.BooleanField(default=False, db_default=False)
class Meta:
unique_together = [["team", "name"]]
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 012990f20aed..ffbda077a08e 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -50,6 +50,23 @@ export interface CopyFlagsResponseApi {
failed: CopyFlagsResultApi[]
}
+export interface EvaluationContextSuggestionRequestApi {
+ /**
+ * Name of the evaluation context to hide from (POST) or restore to (DELETE) the flag editor's suggestion list. Case-insensitive and whitespace-trimmed.
+ * @maxLength 255
+ */
+ context_name: string
+}
+
+export interface EvaluationContextSuggestionResponseApi {
+ /** Whether the suggestion visibility change was applied. */
+ success: boolean
+ /** Normalized name of the affected evaluation context. */
+ name: string
+ /** Whether the context is now hidden from the flag editor's suggestion list. */
+ hidden_from_suggestions: boolean
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
@@ -1322,6 +1339,13 @@ export interface PatchedScheduledChangeApi {
readonly timezone?: string | null
}
+export type EnvironmentsEvaluationContextSuggestionsDestroyParams = {
+ /**
+ * Name of the evaluation context to restore to suggestions.
+ */
+ context_name: string
+}
+
export type FeatureFlagsListParams = {
active?: FeatureFlagsListActive
/**
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index 7c2106022001..35eeccf5fe04 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -19,6 +19,9 @@ import type {
CopyFlagsRequestApi,
CopyFlagsResponseApi,
DependentFlagApi,
+ EnvironmentsEvaluationContextSuggestionsDestroyParams,
+ EvaluationContextSuggestionRequestApi,
+ EvaluationContextSuggestionResponseApi,
FeatureFlagApi,
FeatureFlagCreateRequestSchemaApi,
FeatureFlagStatusResponseApi,
@@ -92,6 +95,74 @@ export const featureFlagsCopyFlagsCreate = async (
})
}
+export const getEnvironmentsEvaluationContextSuggestionsCreateUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/environments/${id}/evaluation_context_suggestions/`
+}
+
+/**
+ * Hide an evaluation context name from the flag editor's suggestion list, or restore it.
+
+POST hides the name; DELETE restores it. The underlying context row and any flags already
+using it are never modified — this only controls what gets suggested.
+ */
+export const environmentsEvaluationContextSuggestionsCreate = async (
+ projectId: string,
+ id: number,
+ evaluationContextSuggestionRequestApi: EvaluationContextSuggestionRequestApi,
+ options?: RequestInit
+): Promise<EvaluationContextSuggestionResponseApi> => {
+ return apiMutator<EvaluationContextSuggestionResponseApi>(
+ getEnvironmentsEvaluationContextSuggestionsCreateUrl(projectId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(evaluationContextSuggestionRequestApi),
+ }
+ )
+}
+
+export const getEnvironmentsEvaluationContextSuggestionsDestroyUrl = (
+ projectId: string,
+ id: number,
+ params: EnvironmentsEvaluationContextSuggestionsDestroyParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/environments/${id}/evaluation_context_suggestions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/environments/${id}/evaluation_context_suggestions/`
+}
+
+/**
+ * Hide an evaluation context name from the flag editor's suggestion list, or restore it.
+
+POST hides the name; DELETE restores it. The underlying context row and any flags already
+using it are never modified — this only controls what gets suggested.
+ */
+export const environmentsEvaluationContextSuggestionsDestroy = async (
+ projectId: string,
+ id: number,
+ params: EnvironmentsEvaluationContextSuggestionsDestroyParams,
+ options?: RequestInit
+): Promise<EvaluationContextSuggestionResponseApi> => {
+ return apiMutator<EvaluationContextSuggestionResponseApi>(
+ getEnvironmentsEvaluationContextSuggestionsDestroyUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'DELETE',
+ }
+ )
+}
+
export const getFeatureFlagsListUrl = (projectId: string, params?: FeatureFlagsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index 77577c3833c2..56b08708fd48 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -33,6 +33,23 @@ export const FeatureFlagsCopyFlagsCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Hide an evaluation context name from the flag editor's suggestion list, or restore it.
+
+POST hides the name; DELETE restores it. The underlying context row and any flags already
+using it are never modified — this only controls what gets suggested.
+ */
+export const environmentsEvaluationContextSuggestionsCreateBodyContextNameMax = 255
+
+export const EnvironmentsEvaluationContextSuggestionsCreateBody = /* @__PURE__ */ zod.object({
+ context_name: zod
+ .string()
+ .max(environmentsEvaluationContextSuggestionsCreateBodyContextNameMax)
+ .describe(
+ "Name of the evaluation context to hide from (POST) or restore to (DELETE) the flag editor's suggestion list. Case-insensitive and whitespace-trimmed."
+ ),
+})
+
/**
* Create, read, update and delete feature flags. [See docs](https://posthog.com/docs/feature-flags) for more information on feature flags.
*
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index 14250577953b..6cde8fd8885b 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -64,6 +64,12 @@ tools:
id:
cast: string-int
soft_delete: true
+ environments-evaluation-context-suggestions-create:
+ operation: environments_evaluation_context_suggestions_create
+ enabled: false
+ environments-evaluation-context-suggestions-destroy:
+ operation: environments_evaluation_context_suggestions_destroy
+ enabled: false
feature-flag-get-all:
operation: feature_flags_list
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ed002ff429b0..6c7d00847620 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16902,6 +16902,23 @@ export namespace Schemas {
key_id: string;
}
+ export interface EvaluationContextSuggestionRequest {
+ /**
+ * Name of the evaluation context to hide from (POST) or restore to (DELETE) the flag editor's suggestion list. Case-insensitive and whitespace-trimmed.
+ * @maxLength 255
+ */
+ context_name: string;
+ }
+
+ export interface EvaluationContextSuggestionResponse {
+ /** Whether the suggestion visibility change was applied. */
+ success: boolean;
+ /** Normalized name of the affected evaluation context. */
+ name: string;
+ /** Whether the context is now hidden from the flag editor's suggestion list. */
+ hidden_from_suggestions: boolean;
+ }
+
export interface EvaluationPattern {
title: string;
description: string;
@@ -50641,6 +50658,13 @@ export namespace Schemas {
offset?: number;
};
+ export type EnvironmentsEvaluationContextSuggestionsDestroyParams = {
+ /**
+ * Name of the evaluation context to restore to suggestions.
+ */
+ context_name: string;
+ };
+
export type ErrorTrackingAssignmentRulesListParams = {
/**
* Number of results to return per page.