: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 the flags list emptying with an unentered search (#86121)
posthog[bot]2c4f63069989
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.pyindex e420ae086717..be22d05c21f3 100644--- a/ee/hogai/context/entity_search/context.py+++ b/ee/hogai/context/entity_search/context.py@@ -12,6 +12,7 @@ from pydantic import ValidationErrorfrom posthog.schema import ArtifactContentType, InsightVizNodefrom posthog.api.search import (+ FEATURE_FLAG_SEARCH_CONFIG,LIMIT as SEARCH_LIMIT,EntityConfig,search_entities as search_entities_fts,@@ -88,12 +89,7 @@ ENTITY_MAP: dict[str, EntityConfig] = {"extra_fields": ["name", "description"],"filters": {"deleted": False},},- "feature_flag": {- "klass": FeatureFlag,- "search_fields": {"key": "A", "name": "C"},- "extra_fields": ["key", "name"],- "filters": {"deleted": False},- },+ "feature_flag": FEATURE_FLAG_SEARCH_CONFIG,"action": {"klass": Action,"search_fields": {"name": "A", "description": "C"},diff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.pyindex 6e631ceab870..630a337ebaff 100644--- a/ee/hogai/context/entity_search/test/test_context.py+++ b/ee/hogai/context/entity_search/test/test_context.py@@ -260,6 +260,25 @@ class TestEntitySearchContext(NonAtomicBaseTest):assert "deleted_flag" not in result_keysassert "deleted flag" not in result_names+ async def test_feature_flag_filters_exclude_archived(self):+ await FeatureFlag.objects.acreate(+ team=self.team, key="active_flag", name="active flag", archived=False, created_by=self.user+ )+ await FeatureFlag.objects.acreate(+ team=self.team,+ key="archived_flag",+ name="archived flag",+ active=False,+ archived=True,+ created_by=self.user,+ )++ results, _ = await self.context.search_entities({"feature_flag"}, "flag")++ result_keys = [r["extra_fields"].get("key", "") for r in results]+ assert "active_flag" in result_keys+ assert "archived_flag" not in result_keys+async def test_action_filters_exclude_deleted(self):await Action.objects.acreate(team=self.team, name="active action", deleted=False, created_by=self.user)await Action.objects.acreate(team=self.team, name="deleted action", deleted=True, created_by=self.user)diff --git a/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx b/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsxindex 3285bb458e50..a3b07a64376c 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx@@ -5,7 +5,7 @@ import { TagSelect } from 'lib/components/TagSelect'import { FeatureFlagEvaluationRuntime } from '~/types'-import { FeatureFlagsFilters } from './featureFlagsLogic'+import { FEATURE_FLAG_SEARCH_MAX_LENGTH, FeatureFlagsFilters } from './featureFlagsLogic'export interface FeatureFlagFiltersConfig {search?: boolean@@ -50,6 +50,7 @@ export function FeatureFlagFiltersSection({className="w-[335px] !max-w-[335px]"type="search"placeholder={searchPlaceholder}+ maxLength={FEATURE_FLAG_SEARCH_MAX_LENGTH}onChange={(search) => setFeatureFlagsFilters({ search, page: 1 })}value={filters.search || ''}data-attr="feature-flag-search"diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.tsxindex f308869f146f..06f4fef79ee1 100644--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx@@ -3,7 +3,7 @@ import { combineUrl } from 'kea-router'import { useEffect, useRef, useState } from 'react'import { IconArchive, IconLock, IconPlusSmall, IconTrash } from '@posthog/icons'-import { LemonButton, LemonDialog, LemonTag, lemonToast } from '@posthog/lemon-ui'+import { LemonButton, LemonDialog, LemonTag, Link, lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { AccessControlAction } from 'lib/components/AccessControlAction'@@ -368,9 +368,16 @@ export function OverviewTab({const { aggregationLabel } = useValues(groupsModel)const flagLogic = featureFlagsLogic({ flagPrefix })- const { featureFlagsLoading, displayedFlags, pagination, filters, shouldShowEmptyState, filtersChanged } =- useValues(flagLogic)- const { setFeatureFlagsFilters } = useActions(flagLogic)+ const {+ featureFlagsLoading,+ displayedFlags,+ pagination,+ filters,+ shouldShowEmptyState,+ filtersChanged,+ hasActiveFilters,+ } = useValues(flagLogic)+ const { setFeatureFlagsFilters, resetFilters } = useActions(flagLogic)const { currentProjectId } = useValues(projectLogic)const { currentOrganization } = useValues(organizationLogic)@@ -593,7 +600,16 @@ export function OverviewTab({pagination={pagination}nouns={nouns}data-attr="feature-flag-table"- emptyState="No results for this filter, change filter or create a new flag."+ emptyState={+ hasActiveFilters || filtersChanged ? (+ <>+ No feature flags match your filters.{' '}+ <Link onClick={() => resetFilters()}>Clear filters</Link>+ </>+ ) : (+ 'No feature flags yet. Create one to get started.'+ )+ }onSort={(newSorting) =>setFeatureFlagsFilters({order: newSorting ? `${newSorting.order === -1 ? '-' : ''}${newSorting.columnKey}` : undefined,diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.tsindex 3344d74f7258..9a6347232b74 100644--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts@@ -242,6 +242,11 @@ describe('the feature flags logic', () => {let logic: ReturnType<typeof featureFlagsLogic.build>beforeEach(() => {+ useMocks({+ get: {+ '/api/projects/:team_id/feature_flags/': () => [200, { results: [], count: 0 }],+ },+ })initKeaTests()logic = featureFlagsLogic()logic.mount()@@ -285,6 +290,56 @@ describe('the feature flags logic', () => {})})+ describe('hasActiveFilters', () => {+ it('is false on a bare URL where page resolves to undefined', async () => {+ // urlToAction spreads `page: undefined` over DEFAULT_FILTERS (page: 1), so a full-object+ // comparison would wrongly flag the default view as filtered and offer "Clear filters".+ await expectLogic(logic, () => {+ router.actions.push(urls.featureFlags())+ }).toFinishAllListeners()++ expect(logic.values.filters.page).toBeUndefined()+ expect(logic.values.hasActiveFilters).toBe(false)+ expect(logic.values.shouldShowEmptyState).toBe(true)+ })++ it.each<[string, Partial<FeatureFlagsFilters>]>([+ ['a sort order', { order: '-created_at' }],+ ['whitespace-only search', { search: ' ' }],+ ])('is false when only %s is set', async (_, filters) => {+ await expectLogic(logic, () => {+ logic.actions.setFeatureFlagsFilters(filters)+ }).toFinishAllListeners()++ expect(logic.values.hasActiveFilters).toBe(false)+ })++ it.each<[string, Partial<FeatureFlagsFilters>]>([+ ['search', { search: 'checkout' }],+ ['tags', { tags: ['checkout'] }],+ ])('is true when %s is set', async (_, filters) => {+ await expectLogic(logic, () => {+ logic.actions.setFeatureFlagsFilters(filters)+ }).toFinishAllListeners()++ expect(logic.values.hasActiveFilters).toBe(true)+ })++ it('clears active filters without changing the sort order', async () => {+ await expectLogic(logic, () => {+ logic.actions.setFeatureFlagsFilters({ search: 'checkout', order: '-created_at' })+ }).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.resetFilters()+ }).toFinishAllListeners()++ expect(logic.values.filters.search).toBeUndefined()+ expect(logic.values.filters.order).toBe('-created_at')+ expect(logic.values.hasActiveFilters).toBe(false)+ })+ })+it('redirects a disabled usage deep link to overview after flags load', async () => {enabledFeaturesLogic.actions.setFeatureFlags([], {})diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.tsindex 6c6a3de46aae..c5fcaa2ddc0b 100644--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts@@ -23,6 +23,10 @@ import { openFeatureFlagDisableDialog } from './featureFlagDisableDialog'export const FLAGS_PER_PAGE = 100+// The server rejects search terms longer than this (see products/feature_flags/backend/api/feature_flag.py).+// The search input caps at the same length so the client and server agree.+export const FEATURE_FLAG_SEARCH_MAX_LENGTH = 200+export function flagMatchesSearch(flag: FeatureFlagType, search?: string): boolean {if (!search?.trim()) {return true@@ -200,6 +204,7 @@ export interface featureFlagsLogicValues {featureFlagsUpdating: Record<number, boolean>filters: FeatureFlagsFiltersfiltersChanged: boolean+ hasActiveFilters: booleanpagination: PaginationManualparamsFromFilters: {active?: string | undefined@@ -249,6 +254,9 @@ export interface featureFlagsLogicActions {featureFlags: FeatureFlagsResultpayload?: void}+ resetFilters: () => {+ value: true+ }setActiveTab: (tabKey: FeatureFlagsTab) => {tabKey: FeatureFlagsTab}@@ -401,10 +409,11 @@ export interface featureFlagsLogicMeta {tags?: string[] | undefinedtype?: string | undefined}+ hasActiveFilters: (filters: FeatureFlagsFilters) => booleanshouldShowEmptyState: (featureFlagsLoading: boolean,featureFlags: FeatureFlagsResult,- filters: FeatureFlagsFilters+ hasActiveFilters: boolean) => booleanpagination: (filters: FeatureFlagsFilters, featureFlags: FeatureFlagsResult) => PaginationManualdisplayedFlags: (featureFlags: FeatureFlagsResult) => FeatureFlagType[]@@ -437,6 +446,7 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([deleteFlag: (id: number) => ({ id }),setActiveTab: (tabKey: FeatureFlagsTab) => ({ tabKey }),setFeatureFlagsFilters: (filters: Partial<FeatureFlagsFilters>, replace?: boolean) => ({ filters, replace }),+ resetFilters: true,toggleFeatureFlagActive: (id: number, active: boolean) => ({ id, active }),closeEnrichAnalyticsNotice: true,setFeatureFlagUpdating: (id: number, updating: boolean) => ({ id, updating }),@@ -615,13 +625,28 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([},],],- // Check to see if any non-default filters are being used+ // True when a real filter narrows the list. Checks filter values directly rather than+ // comparing the whole object to the defaults: `page` and `order` are not filters, and a+ // bare URL leaves `page` undefined (not 1), so a shape comparison reports the default view+ // as filtered and the empty state offers "Clear filters" when nothing is set.+ hasActiveFilters: [+ (s) => [s.filters],+ (filters: FeatureFlagsFilters): boolean =>+ Boolean(+ filters.search?.trim() ||+ filters.active ||+ filters.archived ||+ filters.type ||+ filters.evaluation_runtime ||+ filters.created_by_id?.length ||+ filters.tags?.length ||+ filters.excluded_tags?.length+ ),+ ],shouldShowEmptyState: [- (s) => [s.featureFlagsLoading, s.featureFlags, s.filters],- (featureFlagsLoading: boolean, featureFlags: FeatureFlagsResult, filters: FeatureFlagsFilters): boolean => {- return (- !featureFlagsLoading && featureFlags.results.length <= 0 && objectsEqual(filters, DEFAULT_FILTERS)- )+ (s) => [s.featureFlagsLoading, s.featureFlags, s.hasActiveFilters],+ (featureFlagsLoading: boolean, featureFlags: FeatureFlagsResult, hasActiveFilters: boolean): boolean => {+ return !featureFlagsLoading && featureFlags.results.length <= 0 && !hasActiveFilters},],pagination: [@@ -710,6 +735,9 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([// Don't carry over pagination from previous tabactions.setFeatureFlagsFilters({ page: 1 }, true)},+ resetFilters: () => {+ actions.setFeatureFlagsFilters({ ...DEFAULT_FILTERS, order: values.filters.order }, true)+ },loadFeatureFlagsSuccess: () => {if (values.featureFlags.results.length > 0) {globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.CreateFeatureFlag)diff --git a/frontend/src/scenes/persons/RelatedFeatureFlags.tsx b/frontend/src/scenes/persons/RelatedFeatureFlags.tsxindex 2d40fa52c82c..c8da6c905608 100644--- a/frontend/src/scenes/persons/RelatedFeatureFlags.tsx+++ b/frontend/src/scenes/persons/RelatedFeatureFlags.tsx@@ -159,7 +159,7 @@ export function RelatedFeatureFlags({ distinctId, groupTypeIndex, groups }: Prop<div className="flex justify-between mb-4 gap-2 flex-wrap"><LemonInputtype="search"- placeholder="Search for feature flags"+ placeholder="Search feature flags"onChange={setSearchTerm}value={searchTerm}/>diff --git a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.test.ts b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.test.tsindex ba6410b14d42..7a5c07bedd1e 100644--- a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.test.ts+++ b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.test.ts@@ -42,10 +42,18 @@ const MOCK_FLAGS: FeatureFlagType[] = [}),]+const OFF_PAGE_FLAG = createMockFlag({+ id: 101,+ key: 'flag-101',+ name: 'Flag 101',+ active: true,+})+const MOCK_EVALUATION_REASONS = {'flag-1': { value: true, evaluation: { reason: 'condition_match', condition_index: 0 } },'flag-2': { value: false, evaluation: { reason: 'no_condition_match' } },'flag-3': { value: true, evaluation: { reason: 'condition_match', condition_index: 1 } },+ 'flag-101': { value: true, evaluation: { reason: 'condition_match', condition_index: 0 } },}describe('relatedFeatureFlagsLogic', () => {@@ -105,13 +113,10 @@ describe('relatedFeatureFlagsLogic', () => {logic.actions.setFilters({ type: FeatureFlagReleaseType.ReleaseToggle })}).toFinishAllListeners()- await expectLogic(flagsLogic).toFinishAllListeners()-- expect(flagsLogic.values.featureFlags.results).toHaveLength(2)- expect(flagsLogic.values.featureFlags.results.map((f) => f.key)).toEqual(['flag-1', 'flag-2'])-+ expect(logic.values.featureFlags.results.map((flag) => flag.key)).toEqual(['flag-1', 'flag-2'])expect(logic.values.mappedRelatedFeatureFlags).toHaveLength(2)expect(logic.values.mappedRelatedFeatureFlags.map((f) => f.key)).toEqual(['flag-1', 'flag-2'])+ expect(flagsLogic.values.filters.type).toBeUndefined()})it('should filter flags by type=multivariant on server side', async () => {@@ -119,11 +124,7 @@ describe('relatedFeatureFlagsLogic', () => {logic.actions.setFilters({ type: FeatureFlagReleaseType.Variants })}).toFinishAllListeners()- await expectLogic(flagsLogic).toFinishAllListeners()-- expect(flagsLogic.values.featureFlags.results).toHaveLength(1)- expect(flagsLogic.values.featureFlags.results[0].key).toEqual('flag-3')-+ expect(logic.values.featureFlags.results.map((flag) => flag.key)).toEqual(['flag-3'])expect(logic.values.mappedRelatedFeatureFlags).toHaveLength(1)expect(logic.values.mappedRelatedFeatureFlags[0].key).toEqual('flag-3')})@@ -133,12 +134,8 @@ describe('relatedFeatureFlagsLogic', () => {logic.actions.setFilters({ active: 'true' })}).toFinishAllListeners()- await expectLogic(flagsLogic).toFinishAllListeners()-- expect(flagsLogic.values.featureFlags.results).toHaveLength(2)- expect(flagsLogic.values.featureFlags.results.map((f) => f.key)).toEqual(['flag-1', 'flag-3'])-- expect(flagsLogic.values.featureFlags.results.every((f) => f.active)).toBe(true)+ expect(logic.values.featureFlags.results.map((flag) => flag.key)).toEqual(['flag-1', 'flag-3'])+ expect(logic.values.featureFlags.results.every((flag) => flag.active)).toBe(true)})it('should filter flags by active=false on server side', async () => {@@ -146,11 +143,8 @@ describe('relatedFeatureFlagsLogic', () => {logic.actions.setFilters({ active: 'false' })}).toFinishAllListeners()- await expectLogic(flagsLogic).toFinishAllListeners()-- expect(flagsLogic.values.featureFlags.results).toHaveLength(1)- expect(flagsLogic.values.featureFlags.results[0].key).toEqual('flag-2')- expect(flagsLogic.values.featureFlags.results[0].active).toBe(false)+ expect(logic.values.featureFlags.results.map((flag) => flag.key)).toEqual(['flag-2'])+ expect(logic.values.featureFlags.results[0].active).toBe(false)})it('should combine multiple filters', async () => {@@ -158,10 +152,7 @@ describe('relatedFeatureFlagsLogic', () => {logic.actions.setFilters({ type: FeatureFlagReleaseType.ReleaseToggle, active: 'true' })}).toFinishAllListeners()- await expectLogic(flagsLogic).toFinishAllListeners()-- expect(flagsLogic.values.featureFlags.results).toHaveLength(1)- expect(flagsLogic.values.featureFlags.results[0].key).toEqual('flag-1')+ expect(logic.values.featureFlags.results.map((flag) => flag.key)).toEqual(['flag-1'])})it('should clear type filter when replace=true and type not in new filters', async () => {@@ -173,15 +164,11 @@ describe('relatedFeatureFlagsLogic', () => {logic.actions.setFilters({ active: 'true' }, true)}).toFinishAllListeners()- await expectLogic(flagsLogic).toFinishAllListeners()-- expect(flagsLogic.values.featureFlags.results).toHaveLength(2)- expect(flagsLogic.values.featureFlags.results.map((f) => f.key)).toEqual(['flag-1', 'flag-3'])+ expect(logic.values.featureFlags.results.map((flag) => flag.key)).toEqual(['flag-1', 'flag-3'])})it('should still apply client-side filtering for reason filter', async () => {setupMocks()- await expectLogic(flagsLogic).toFinishAllListeners()await expectLogic(logic).toFinishAllListeners()await expectLogic(logic, () => {@@ -197,7 +184,7 @@ describe('relatedFeatureFlagsLogic', () => {setupMocks()await expectLogic(logic).toFinishAllListeners()- await expectLogic(flagsLogic, () => {+ await expectLogic(logic, () => {logic.actions.loadRelatedFeatureFlags()}).toDispatchActions(['loadFeatureFlags'])@@ -207,6 +194,63 @@ describe('relatedFeatureFlagsLogic', () => {})})+ describe('isolated server-side search', () => {+ let requestedSearches: (string | null)[]++ const setupMocks = (): void => {+ requestedSearches = []+ // oxlint-disable-next-line react-hooks/rules-of-hooks+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/`]: ({ request }) => {+ const search = new URL(request.url).searchParams.get('search')+ requestedSearches.push(search)+ return search+ ? [200, { results: [OFF_PAGE_FLAG], count: 1 }]+ : [200, { results: MOCK_FLAGS, count: 101 }]+ },+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/evaluation_reasons`]:+ MOCK_EVALUATION_REASONS,+ },+ })+ }++ beforeEach(() => {+ setupMocks()+ flagsLogic = featureFlagsLogic()+ flagsLogic.mount()+ logic = relatedFeatureFlagsLogic({ distinctId: 'test-user' })+ logic.mount()+ })++ it('does not write the search term into the shared featureFlagsLogic', async () => {+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setSearchTerm('flag-1')+ }).toFinishAllListeners()++ expect(logic.values.searchTerm).toEqual('flag-1')+ // The shared list logic must stay on its default search — a leak here surfaced as an+ // empty flags list showing a term the user never typed on that scene.+ expect(flagsLogic.values.filters.search).toBeUndefined()+ })++ it('finds a matching flag outside the loaded page', async () => {+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.mappedRelatedFeatureFlags.map((flag) => flag.key)).not.toContain('flag-101')++ await expectLogic(logic, () => {+ logic.actions.setSearchTerm('flag-101')+ }).toFinishAllListeners()++ expect(requestedSearches).toContain('flag-101')+ expect(logic.values.filteredMappedFlags.map((flag) => flag.key)).toEqual(['flag-101'])+ expect(logic.values.pagination).toEqual(expect.objectContaining({ currentPage: 1, entryCount: 1 }))+ })+ })+describe('load errors', () => {beforeEach(() => {// oxlint-disable-next-line react-hooks/rules-of-hooks@@ -245,11 +289,7 @@ describe('relatedFeatureFlagsLogic', () => {await expectLogic(logic, () => {logic.actions.loadRelatedFeatureFlags()}).toFinishAllListeners()- await expectLogic(flagsLogic).toFinishAllListeners()-expect(logic.values.loadError).toBe(false)- // Server-controlled paging over the full flags list must come back after a retry —- // this table pages through featureFlagsLogic, not through its own rowsexpect(logic.values.pagination).toEqual(expect.objectContaining({ controlled: true, entryCount: MOCK_FLAGS.length }))diff --git a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.tsindex aa7e772186bd..79800685cbb7 100644--- a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts+++ b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts@@ -4,14 +4,13 @@ import { urlToAction } from 'kea-router'import api from 'lib/api'import { toParams } from 'lib/utils/url'-import { FeatureFlagsFilters, featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'+import { FLAGS_PER_PAGE, type FeatureFlagsResult } from 'scenes/feature-flags/featureFlagsLogic'import { projectLogic } from 'scenes/projectLogic'import { urls } from 'scenes/urls'import { FeatureFlagReleaseType, FeatureFlagType } from '~/types'import type { PaginationManual } from '../../../@posthog/lemon-ui/src/index'-import type { FeatureFlagsResult } from '../feature-flags/featureFlagsLogic'import { FeatureFlagMatchReason } from './RelatedFeatureFlags'export interface RelatedFeatureFlag extends FeatureFlagType {@@ -40,9 +39,10 @@ export interface RelatedFlagsFilters {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface relatedFeatureFlagsLogicValues {- featureFlags: FeatureFlagsResult // featureFlagsLogic- featureFlagsLoading: boolean // featureFlagsLogiccurrentProjectId: number | null // projectLogic+ currentPage: number+ featureFlags: FeatureFlagsResult+ featureFlagsLoading: booleanfilteredMappedFlags: RelatedFeatureFlag[]filters: Partial<RelatedFlagsFilters>isLoading: boolean@@ -56,14 +56,21 @@ export interface relatedFeatureFlagsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface relatedFeatureFlagsLogicActions {- loadFeatureFlags: (_?: void | undefined) => void // featureFlagsLogic- setFeatureFlagsFilters: (- filters: Partial<FeatureFlagsFilters>,- replace?: boolean | undefined+ loadFeatureFlags: (_: void) => void+ loadFeatureFlagsFailure: (+ error: string,+ errorObject?: any) => {- filters: Partial<FeatureFlagsFilters>- replace: boolean | undefined- } // featureFlagsLogic+ error: string+ errorObject?: any+ }+ loadFeatureFlagsSuccess: (+ featureFlags: FeatureFlagsResult,+ payload?: void+ ) => {+ featureFlags: FeatureFlagsResult+ payload?: void+ }loadRelatedFeatureFlags: () => {value: true}@@ -92,6 +99,9 @@ export interface relatedFeatureFlagsLogicActions {filters: Partial<RelatedFlagsFilters>replace: boolean | undefined}+ setPage: (page: number) => {+ page: number+ }setSearchTerm: (searchTerm: string) => {searchTerm: string}@@ -119,7 +129,11 @@ export interface relatedFeatureFlagsLogicMeta {mappedRelatedFeatureFlags: RelatedFeatureFlag[],filters: Partial<RelatedFlagsFilters>) => RelatedFeatureFlag[]- pagination: (pagination: PaginationManual, loadError: boolean) => PaginationManual | undefined+ pagination: (+ featureFlags: FeatureFlagsResult,+ currentPage: number,+ loadError: boolean+ ) => PaginationManual | undefined}}@@ -141,18 +155,41 @@ export const relatedFeatureFlagsLogic = kea<relatedFeatureFlagsLogicType>([),key((props) => `${props.distinctId}`),connect(() => ({- values: [projectLogic, ['currentProjectId'], featureFlagsLogic, ['featureFlags', 'featureFlagsLoading']],- actions: [featureFlagsLogic, ['setFeatureFlagsFilters', 'loadFeatureFlags']],+ values: [projectLogic, ['currentProjectId']],})),actions({- setSearchTerm: (searchTerm: string) => {- featureFlagsLogic.actions.setFeatureFlagsFilters({ search: searchTerm })- return { searchTerm }- },+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),setFilters: (filters: Partial<RelatedFlagsFilters>, replace?: boolean) => ({ filters, replace }),+ setPage: (page: number) => ({ page }),loadRelatedFeatureFlags: true,}),loaders(({ values, props, actions }) => ({+ featureFlags: [+ { results: [], count: 0, offset: 0 } as FeatureFlagsResult,+ {+ loadFeatureFlags: async (_: void, breakpoint) => {+ const type =+ values.filters.type === FeatureFlagReleaseType.ReleaseToggle+ ? 'boolean'+ : values.filters.type === FeatureFlagReleaseType.Variants+ ? 'multivariant'+ : undefined+ const params = {+ limit: FLAGS_PER_PAGE,+ offset: (values.currentPage - 1) * FLAGS_PER_PAGE,+ search: values.searchTerm.trim() || undefined,+ active: values.filters.active,+ type,+ }+ const response = await api.get(+ `api/projects/${values.currentProjectId}/feature_flags/?${toParams(params)}`+ )+ breakpoint()++ return { ...response, offset: params.offset }+ },+ },+ ],relatedFeatureFlags: [null as RelatedFeatureFlagResponse | null,{@@ -176,6 +213,15 @@ export const relatedFeatureFlagsLogic = kea<relatedFeatureFlagsLogicType>([setSearchTerm: (_, { searchTerm }) => searchTerm,},],+ currentPage: [+ 1,+ {+ setSearchTerm: () => 1,+ setFilters: (state, { filters, replace }) =>+ replace || 'type' in filters || 'active' in filters ? 1 : state,+ setPage: (_, { page }) => page,+ },+ ],filters: [{} as Partial<RelatedFlagsFilters>,{@@ -200,7 +246,7 @@ export const relatedFeatureFlagsLogic = kea<relatedFeatureFlagsLogicType>([}),selectors(({ props, selectors }) => ({isLoading: [- () => [selectors.relatedFeatureFlagsLoading, featureFlagsLogic.selectors.featureFlagsLoading],+ () => [selectors.relatedFeatureFlagsLoading, selectors.featureFlagsLoading],(relatedLoading: boolean, featureFlagsLoading: boolean): boolean => {return relatedLoading || featureFlagsLoading},@@ -235,12 +281,9 @@ export const relatedFeatureFlagsLogic = kea<relatedFeatureFlagsLogicType>([filteredMappedFlags: [(selectors) => [selectors.mappedRelatedFeatureFlags, selectors.filters],(featureFlags: RelatedFeatureFlag[], filters: Partial<RelatedFlagsFilters>) => {- if (Object.keys(filters).length === 0) {- return featureFlags- }+ let filteredFlags = featureFlagsconst { reason } = filters- let filteredFlags = featureFlagsif (reason) {filteredFlags = filteredFlags.filter((flag) =>reason === 'not matched'@@ -251,54 +294,42 @@ export const relatedFeatureFlagsLogic = kea<relatedFeatureFlagsLogicType>([return filteredFlags},],- // The flags list is server-paginated (100 per page) and this table pages through it via- // the `page` URL param (see urlToAction below), so it reuses featureFlagsLogic's- // controlled pagination. Suppress it while the evaluation_reasons load has failed —- // otherwise the controls advertise the full flags count next to an empty error state.pagination: [- () => [featureFlagsLogic.selectors.pagination, selectors.loadError],- (pagination: PaginationManual, loadError: boolean): PaginationManual | undefined =>- loadError ? undefined : pagination,+ () => [selectors.featureFlags, selectors.currentPage, selectors.loadError],+ (+ featureFlags: FeatureFlagsResult,+ currentPage: number,+ loadError: boolean+ ): PaginationManual | undefined => {+ if (loadError) {+ return undefined+ }+ return {+ controlled: true,+ pageSize: FLAGS_PER_PAGE,+ currentPage,+ entryCount: featureFlags.count,+ }+ },],})),- listeners(({ values, actions }) => ({+ listeners(({ actions }) => ({+ setSearchTerm: async (_, breakpoint) => {+ await breakpoint(300)+ actions.loadFeatureFlags()+ },setFilters: ({ filters, replace }) => {- const apiFilters: FeatureFlagsFilters = {}-- if (replace) {- const currentFilters = values.filters-- if (!('type' in filters) && currentFilters.type) {- apiFilters.type = undefined- }-- if (!('active' in filters) && currentFilters.active) {- apiFilters.active = undefined- }- }-- if ('type' in filters && filters.type !== undefined) {- if (filters.type === FeatureFlagReleaseType.ReleaseToggle) {- apiFilters.type = 'boolean'- } else if (filters.type === FeatureFlagReleaseType.Variants) {- apiFilters.type = 'multivariant'- }- }-- if ('active' in filters && filters.active !== undefined) {- apiFilters.active = filters.active- }-- if (Object.keys(apiFilters).length > 0 || replace) {- actions.setFeatureFlagsFilters({ ...apiFilters, page: 1 }, replace)+ if (replace || 'type' in filters || 'active' in filters) {+ actions.loadFeatureFlags()}},+ setPage: () => actions.loadFeatureFlags(),})),urlToAction(({ actions }) => ({[urls.personByUUID('*', false)]: async (_, searchParams) => {const page = searchParams['page']if (page !== undefined) {- actions.setFeatureFlagsFilters({ page: parseInt(page) })+ actions.setPage(parseInt(page))}},})),diff --git a/posthog/api/search.py b/posthog/api/search.pyindex 5913fe73655a..e18429d96c3c 100644--- a/posthog/api/search.py+++ b/posthog/api/search.py@@ -38,6 +38,14 @@ class EntityConfig(TypedDict, total=False):filters: dict[str, Any]+FEATURE_FLAG_SEARCH_CONFIG: EntityConfig = {+ "klass": FeatureFlag,+ "search_fields": {"key": "A", "name": "C"},+ "extra_fields": ["key", "name"],+ "filters": {"archived": False},+}++ENTITY_MAP: dict[str, EntityConfig] = {"insight": {"klass": Insight,@@ -54,7 +62,7 @@ ENTITY_MAP: dict[str, EntityConfig] = {"search_fields": {"name": "A", "description": "C"},"extra_fields": ["name", "description"],},- "feature_flag": {"klass": FeatureFlag, "search_fields": {"key": "A", "name": "C"}, "extra_fields": ["key", "name"]},+ "feature_flag": FEATURE_FLAG_SEARCH_CONFIG,"notebook": {"klass": Notebook,"search_fields": {"title": "A", "text_content": "C"},diff --git a/posthog/api/test/test_search.py b/posthog/api/test/test_search.pyindex afb89210dac5..b4e5fe9c15ae 100644--- a/posthog/api/test/test_search.py+++ b/posthog/api/test/test_search.py@@ -78,6 +78,18 @@ class TestSearch(APIBaseTest):self.assertEqual(response.json()["counts"]["insight"], 3)self.assertEqual(response.json()["counts"]["notebook"], 2)+ def test_archived_feature_flags_are_excluded(self):+ FeatureFlag.objects.create(+ key="archived-flag", team=self.team, created_by=self.user, archived=True, active=False+ )++ response = self.client.get("/api/projects/@current/search?entities=feature_flag")++ self.assertEqual(response.status_code, 200)+ result_ids = [result["extra_fields"]["key"] for result in response.json()["results"]]+ self.assertNotIn("archived-flag", result_ids)+ self.assertEqual(response.json()["counts"]["feature_flag"], 3)+def test_search_filtered_by_entity(self):response = self.client.get("/api/projects/@current/search?q=sec&entities=insight&entities=dashboard&entities=notebook"