: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
feat(taxonomic-filter): cache + skeleton + key-only rows in rebuilt menu (#59855)
Adam Leithcb55a737a195
diff --git a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsxindex ea079f716e95..f26424569fb7 100644--- a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx+++ b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx@@ -296,16 +296,16 @@ export function TaxonomicPropertyFilter({// away via `showInitialSearchInline`; `disablePopover` still renders a// button + dropdown here, so it's fine to swap.//- // `selectingKeyOnly` rows keep the classic filter — the rebuilt menu- // doesn't model key-only selection semantics yet, and silently swapping- // would change what `onChange` commits.+ // Key-only rows route through the rebuilt menu too — the picker fires+ // the same `taxonomicOnChange` callback in either mode, so the commit+ // shape is identical (cohort id → `setFilter` with `type: 'cohort'`).//// The rebuilt menu carries its own toggle inside its trigger wrapper, so// it needs no extra DOM and inherits the row's layout exactly. The// legacy path gets a thin positioned wrapper to host the floating toggle.const editablePicker = !menuRebuildEnabled ? (legacyDropdown- ) : useNewMenu && !isKeyOnlyRow ? (+ ) : useNewMenu ? (<TaxonomicPopoverMenugroupType={filterTaxonomicGroupType ?? groupTypes[0]}value={cohortOrOtherValue}diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.tsindex ffcff812b18c..d12e41b8edef 100644--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts@@ -181,6 +181,14 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {const remoteEnabled = hasRemoteDataSource && !needsMoreSearchCharacters+ // `clientFilterFirstPage` groups (e.g. Cohorts) pin the remote query to+ // the empty-search first page and let local Fuse handle keystroke+ // filtering — gives the same snappy feel as a local-only group while+ // still picking up server-side hidden/excluded filtering. The cache+ // key drops `searchQuery` so every keystroke hits the same entry.+ const clientFilter = !!group.clientFilterFirstPage+ const remoteSearchQuery = clientFilter ? '' : searchQuery+const remoteKey = useMemo(() => ['taxonomic-list',@@ -188,7 +196,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {group.endpoint,group.scopedEndpoint ?? null,isExpanded,- searchQuery,+ remoteSearchQuery,limit,showNumericalPropsOnly,hideBehavioralCohorts,@@ -198,7 +206,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {group.endpoint,group.scopedEndpoint,isExpanded,- searchQuery,+ remoteSearchQuery,limit,showNumericalPropsOnly,hideBehavioralCohorts,@@ -210,7 +218,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {({ signal }) =>fetchTaxonomicListPage({group,- searchQuery,+ searchQuery: remoteSearchQuery,offset: 0,limit,isExpanded,@@ -218,10 +226,43 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {hideBehavioralCohorts,signal,}),- { enabled: remoteEnabled, staleTime: 60_000, keepPreviousData: true }+ // Long staleTime for client-filtered groups — the cached first page+ // is the single source of truth for the whole typing session.+ // Cohort create/update should invalidate via `invalidateTaxonomicResource`+ // (TODO) so a fresh fetch picks up the new item.+ {+ enabled: remoteEnabled,+ staleTime: clientFilter ? 5 * 60_000 : 60_000,+ keepPreviousData: true,+ })- const remoteItems: ListStorage = remote.data ?? EMPTY_LIST_STORAGE+ const remoteItemsRaw: ListStorage = remote.data ?? EMPTY_LIST_STORAGE++ // Per-fetch Fuse index over the cached first page. Built lazily on+ // first non-empty query, then re-used across keystrokes until the+ // page changes (refetch / invalidate).+ const remoteFuse = useMemo(() => {+ if (!clientFilter || remoteItemsRaw.results.length === 0) {+ return null+ }+ const haystack = remoteItemsRaw.results.map((item) => {+ const name = group.getName?.(item) ?? ('name' in item ? (item as { name?: string }).name : '') ?? ''+ const posthogName = getCoreFilterDefinition(name, group.type)?.label+ return { name, posthogName, item }+ })+ return createFuse(haystack, { keys: ['name', 'posthogName'], ignoreLocation: true })+ }, [clientFilter, remoteItemsRaw, group])++ const remoteItems: ListStorage = useMemo(() => {+ if (!clientFilter || !trimmedSearch) {+ return remoteItemsRaw+ }+ const filtered = remoteFuse+ ? (remoteFuse.search(trimmedSearch).map((r: any) => r.item.item) as TaxonomicDefinitionTypes[])+ : []+ return { results: filtered, searchQuery, count: filtered.length }+ }, [clientFilter, trimmedSearch, remoteItemsRaw, remoteFuse, searchQuery])// ---- Combined items + keyword shortcuts --------------------------------const keywordShortcuts: QuickFilterItem[] = useMemo(() => {diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.test.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.test.tsindex a62c5c002775..4d8207e82174 100644--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.test.ts@@ -3,6 +3,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'import {__clearTaxonomicResourceCache,invalidateTaxonomicResource,+ invalidateTaxonomicResourcesWhere,peekTaxonomicResource,useTaxonomicResource,} from './useTaxonomicResource'@@ -212,6 +213,33 @@ describe('useTaxonomicResource', () => {expect(fn).toHaveBeenCalledTimes(2)})+ it('invalidateTaxonomicResourcesWhere() invalidates every key matching the predicate', async () => {+ const fnA = jest.fn().mockResolvedValueOnce('a1').mockResolvedValueOnce('a2')+ const fnB = jest.fn().mockResolvedValueOnce('b1').mockResolvedValueOnce('b2')+ const fnC = jest.fn().mockResolvedValueOnce('c1')++ const ra = renderHook(() => useTaxonomicResource(['taxonomic-list', 'cohorts', 'k1'], fnA))+ const rb = renderHook(() => useTaxonomicResource(['taxonomic-list', 'cohorts', 'k2'], fnB))+ const rc = renderHook(() => useTaxonomicResource(['taxonomic-list', 'events', 'k3'], fnC))++ await waitFor(() => expect(ra.result.current.data).toBe('a1'))+ await waitFor(() => expect(rb.result.current.data).toBe('b1'))+ await waitFor(() => expect(rc.result.current.data).toBe('c1'))++ // Invalidate only the cohort entries — events stays cached.+ invalidateTaxonomicResourcesWhere((key) => key[0] === 'taxonomic-list' && key[1] === 'cohorts')++ ra.rerender()+ rb.rerender()+ rc.rerender()++ await waitFor(() => expect(ra.result.current.data).toBe('a2'))+ await waitFor(() => expect(rb.result.current.data).toBe('b2'))+ expect(fnA).toHaveBeenCalledTimes(2)+ expect(fnB).toHaveBeenCalledTimes(2)+ expect(fnC).toHaveBeenCalledTimes(1)+ })+it('peekTaxonomicResource() returns current cached value', async () => {const fn = jest.fn().mockResolvedValue({ items: [1, 2] })const { result } = renderHook(() => useTaxonomicResource(['peek'], fn))diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.tsindex d8d467fae0bb..060fc049b545 100644--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.ts+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.ts@@ -253,6 +253,30 @@ export function invalidateTaxonomicResource(key: ReadonlyArray<unknown>): void {}}+/**+ * Invalidate every cached entry whose key matches a predicate. Used by+ * domain models (e.g. cohortsModel) to flush taxonomic cache slices when+ * the underlying data mutates. The hash is the JSON-stringified key so+ * we re-parse to feed structured input back to the predicate — keys are+ * always plain arrays of JSON-safe values so the round-trip is lossless.+ */+export function invalidateTaxonomicResourcesWhere(predicate: (key: unknown[]) => boolean): void {+ for (const [hash, entry] of cache) {+ let key: unknown[]+ try {+ key = JSON.parse(hash) as unknown[]+ } catch {+ continue+ }+ if (!predicate(key)) {+ continue+ }+ entry.ts = 0+ entry.error = undefined+ notify(entry)+ }+}+/** Subscribe to a key without rendering. Returns an unsubscribe fn. */export function subscribeTaxonomicResource(key: ReadonlyArray<unknown>, listener: () => void): () => void {const entry = getEntry(hashKey(key))diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsxnew file mode 100644index 000000000000..9431e4f4c8aa--- /dev/null+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx@@ -0,0 +1,234 @@+import '@testing-library/jest-dom'++import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'+import { Provider } from 'kea'+import { useState } from 'react'++import { useMocks } from '~/mocks/jest'+import { actionsModel } from '~/models/actionsModel'+import { groupsModel } from '~/models/groupsModel'+import { performQuery } from '~/queries/query'+import { initKeaTests } from '~/test/init'++import { TaxonomicFilterHeadless } from '../headless'+import { __clearTaxonomicResourceCache } from '../hooks/useTaxonomicResource'+import { TaxonomicFilterGroupType } from '../types'+import { MenuFilterCombobox } from './Combobox'++jest.mock('~/queries/query', () => ({+ performQuery: jest.fn(),+}))++jest.mock('lib/api', () => {+ const emptyPaginated = (): Promise<{ results: any[]; count: number; next: null }> =>+ Promise.resolve({ results: [], count: 0, next: null })+ return {+ __esModule: true,+ default: {+ get: jest.fn().mockImplementation(emptyPaginated),+ actions: { list: jest.fn().mockImplementation(emptyPaginated) },+ dataWarehouseSavedQueries: { list: jest.fn().mockImplementation(emptyPaginated) },+ dataWarehouseTables: { list: jest.fn().mockImplementation(emptyPaginated) },+ queryTabState: { list: jest.fn().mockImplementation(emptyPaginated) },+ dashboards: { list: jest.fn().mockImplementation(emptyPaginated) },+ cohorts: { listPaginated: jest.fn().mockImplementation(emptyPaginated) },+ },+ }+})++const apiGet = jest.requireMock('lib/api').default.get as jest.MockedFunction<any>++function renderCombobox(): ReturnType<typeof render> {+ return render(+ <Provider>+ <TaxonomicFilterHeadless.Root taxonomicGroupTypes={[TaxonomicFilterGroupType.Cohorts]} onChange={jest.fn()}>+ <MenuFilterCombobox+ drillTo={TaxonomicFilterGroupType.Cohorts}+ onCommit={jest.fn()}+ onBack={jest.fn()}+ />+ </TaxonomicFilterHeadless.Root>+ </Provider>+ )+}++describe('MenuFilterCombobox loading vs empty state', () => {+ beforeEach(() => {+ __clearTaxonomicResourceCache()+ apiGet.mockReset()+ ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })+ useMocks({})+ initKeaTests()+ actionsModel.mount()+ groupsModel.mount()+ })++ afterEach(() => cleanup())++ it('shows a loading skeleton while the cohorts fetch is in flight (not the empty state)', async () => {+ // Hold the request open so the component sees `isLoading=true`.+ let resolveFetch!: (value: { results: any[]; count: number }) => void+ apiGet.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveFetch = resolve+ })+ )++ renderCombobox()++ // While loading: skeleton present, no "No Cohorts found" copy.+ await waitFor(() => {+ expect(screen.getByTestId('menu-filter-loading')).toBeInTheDocument()+ })+ expect(screen.queryByTestId('menu-filter-empty')).not.toBeInTheDocument()+ expect(screen.queryByText(/No "Cohorts" found/)).not.toBeInTheDocument()++ // Resolve to an empty list: skeleton disappears, empty state takes over.+ resolveFetch({ results: [], count: 0 })+ await waitFor(() => {+ expect(screen.getByTestId('menu-filter-empty')).toBeInTheDocument()+ })+ expect(screen.queryByTestId('menu-filter-loading')).not.toBeInTheDocument()+ expect(within(screen.getByTestId('menu-filter-empty')).getByText(/No "Cohorts" found/)).toBeInTheDocument()+ })++ it('renders results once the fetch resolves with items', async () => {+ apiGet.mockResolvedValue({+ results: [+ { id: 1, name: 'Internal team' },+ { id: 2, name: 'Power users' },+ ],+ count: 2,+ })++ renderCombobox()++ await waitFor(() => {+ expect(screen.queryByTestId('menu-filter-loading')).not.toBeInTheDocument()+ })+ // Skeleton gone + empty state not shown — items must have rendered.+ expect(screen.queryByTestId('menu-filter-empty')).not.toBeInTheDocument()+ // Row text appears inside the result rows.+ expect(screen.getAllByText('Internal team').length).toBeGreaterThan(0)+ expect(screen.getAllByText('Power users').length).toBeGreaterThan(0)+ })++ it('dedups a synthetic selected entry against the real remote entry (no double checkmark)', async () => {+ apiGet.mockResolvedValue({+ results: [+ { id: 5, name: 'Internal team' },+ { id: 6, name: 'Power users' },+ ],+ count: 2,+ })++ // Simulate what TaxonomicPopoverMenu builds: a synthetic entry with+ // `name: String(value)` and a getValue that returns name-or-id. The+ // real Cohorts group returns `cohort.id` (number) — without string+ // coercion in the dedup check, both rows would render side by side.+ const syntheticSelected = {+ item: { id: '5', name: '5' },+ group: {+ type: TaxonomicFilterGroupType.Cohorts,+ getName: (t: any) => t?.name,+ getValue: (t: any) => t?.name ?? t?.id,+ },+ name: '5',+ } as any++ render(+ <Provider>+ <TaxonomicFilterHeadless.Root+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Cohorts]}+ onChange={jest.fn()}+ >+ <MenuFilterCombobox+ drillTo={TaxonomicFilterGroupType.Cohorts}+ selectedEntry={syntheticSelected}+ onCommit={jest.fn()}+ onBack={jest.fn()}+ />+ </TaxonomicFilterHeadless.Root>+ </Provider>+ )++ await waitFor(() => {+ expect(screen.getAllByText('Internal team').length).toBeGreaterThan(0)+ })+ const rowEls = document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]')+ expect(rowEls.length).toBe(2)+ // No row should be the synthetic placeholder ("5" / N/A) — the real+ // cohort with id 5 must absorb the selected state.+ const rowsText = Array.from(rowEls)+ .map((el) => el.textContent ?? '')+ .join('\n')+ expect(rowsText).toContain('Internal team')+ expect(rowsText).toContain('Power users')+ })++ it('caches the cohorts first page and filters typed queries locally (no per-keystroke refetch)', async () => {+ // Track every cohorts request — there must be exactly one even after+ // typing, because client-side fuse takes over after the first page.+ let cohortCalls = 0+ apiGet.mockImplementation((url: string) => {+ if (url.includes('/cohorts/')) {+ cohortCalls += 1+ return Promise.resolve({+ results: [+ { id: 1, name: 'Internal team' },+ { id: 2, name: 'Power users' },+ { id: 3, name: 'Zzzbeta cohort' },+ ],+ count: 3,+ })+ }+ return Promise.resolve({ results: [], count: 0 })+ })++ // Wrap in a stateful host so we can change the controlled+ // searchQuery without remounting the Root (a remount would reset+ // kea state and force a fresh request even with the cache fix).+ let setQuery!: (q: string) => void+ function Host(): JSX.Element {+ const [q, setQ] = useState('')+ setQuery = setQ+ return (+ <Provider>+ <TaxonomicFilterHeadless.Root+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Cohorts]}+ onChange={jest.fn()}+ searchQuery={q}+ >+ <MenuFilterCombobox+ drillTo={TaxonomicFilterGroupType.Cohorts}+ onCommit={jest.fn()}+ onBack={jest.fn()}+ />+ </TaxonomicFilterHeadless.Root>+ </Provider>+ )+ }++ render(<Host />)++ await waitFor(() => expect(cohortCalls).toBe(1))+ // Initial render shows all three items.+ await waitFor(() => expect(screen.getAllByText('Zzzbeta cohort').length).toBeGreaterThan(0))++ // Now "type" a query — fuse should filter the cached page in place.+ act(() => setQuery('zzzbeta'))++ await waitFor(() => {+ const rowsText = Array.from(document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]'))+ .map((el) => el.textContent ?? '')+ .join('\n')+ expect(rowsText).toContain('Zzzbeta cohort')+ expect(rowsText).not.toContain('Internal team')+ expect(rowsText).not.toContain('Power users')+ })++ // The crucial assertion — no additional fetch fired for the typed query.+ expect(cohortCalls).toBe(1)+ })+})diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsxindex 6f585c641133..625abeb67754 100644--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx@@ -29,6 +29,7 @@ import {SelectTrigger,SelectValue,Separator,+ Skeleton,} from '@posthog/quill'import { createFuse } from 'lib/utils/fuseSearch'@@ -113,6 +114,11 @@ export function MenuFilterCombobox({return drillTo})const [itemsByType, setItemsByType] = useState<Record<string, TaxonomicDefinitionTypes[]>>({})+ // Per-group loading flags reported up by `Fetcher`. We need this in the+ // parent so the empty-state vs. skeleton decision sees the freshest+ // fetch status across every visible (target) group, not just the one+ // whose `useGroupList` hook last rendered.+ const [loadingByType, setLoadingByType] = useState<Record<string, boolean>>({})// Seed the highlight with the committed selection so the preview// pane shows the right definition before any row hovers fire. Once// the list mounts, `autoHighlight="always"` + the reordered@@ -168,6 +174,10 @@ export function MenuFilterCombobox({setItemsByType((prev) => (prev[type] === next ? prev : { ...prev, [type]: next }))}, [])+ const reportLoading = useCallback((type: string, loading: boolean): void => {+ setLoadingByType((prev) => (prev[type] === loading ? prev : { ...prev, [type]: loading }))+ }, [])+// Chips show only when `drillTo='all'` — drilled scopes lock to one// category and hide the chip row per spec.const showChips = drillTo === 'all'@@ -246,11 +256,18 @@ export function MenuFilterCombobox({scope === 'pinned' ||scope === 'suggested'if (fitsScope) {- const selectedValue = selectedEntry.group.getValue?.(selectedEntry.item) ?? selectedEntry.name+ // Stringify both sides so a synthetic `selected` shimmed in+ // by callers like `TaxonomicPopoverMenu` (where the value+ // arrives as e.g. `'5'`) dedups against the real entry+ // returned by the endpoint (`cohort.id === 5`). Without this+ // coercion the two land side-by-side with two checkmarks —+ // the stableId path below already coerces, so matching here+ // keeps the prepend logic aligned with how rows are keyed.+ const selectedValue = String(selectedEntry.group.getValue?.(selectedEntry.item) ?? selectedEntry.name)const present = merged.some((e) =>e.group.type === selectedEntry.group.type &&- (e.group.getValue?.(e.item) ?? e.name) === selectedValue+ String(e.group.getValue?.(e.item) ?? e.name) === selectedValue)if (!present) {merged.unshift(selectedEntry)@@ -316,6 +333,18 @@ export function MenuFilterCombobox({return phrase ? `Search ${phrase}…` : (placeholder ?? 'Search…')}, [activeChip, groups, placeholder])+ // True while any visible group is fetching its first page (or refetching+ // with no kept-previous-data) — drives the skeleton fallback so the user+ // doesn't see "No X found" before the request resolves. Drilled+ // scopes that read from pre-resolved `drillItems` / `suggestedItems`+ // never fetch and stay at `false`.+ const isAnyLoading = useMemo(() => {+ if (drillItems) {+ return false+ }+ return targetGroups.some((g) => loadingByType[g.type])+ }, [drillItems, targetGroups, loadingByType])+// Empty-state message. Three branches:// - "needs more characters" — when the active chip resolves to a// single group with `minSearchQueryLength` and the search query@@ -330,6 +359,12 @@ export function MenuFilterCombobox({if (filtered.length > 0) {return null}+ // Suppress empty-state copy while a remote fetch is in flight —+ // the skeleton fallback below takes its place so we don't flash+ // "No X found" before the response resolves.+ if (isAnyLoading) {+ return null+ }const scope = showChips ? activeChip : drillToconst singleGroup =scope !== 'all' && scope !== 'recent' && scope !== 'pinned'@@ -353,7 +388,7 @@ export function MenuFilterCombobox({return {title: categoryLabel ? `No "${categoryLabel}" found` : 'No items',}- }, [filtered.length, showChips, activeChip, drillTo, groups, searchQuery])+ }, [filtered.length, showChips, activeChip, drillTo, groups, searchQuery, isAnyLoading])const headerTitle =title ??@@ -485,19 +520,28 @@ export function MenuFilterCombobox({</InputGroup></div>{!drillItems &&- targetGroups.map((g) => <Fetcher key={g.type} group={g} onItems={reportItems} />)}+ targetGroups.map((g) => (+ <Fetcher key={g.type} group={g} onItems={reportItems} onLoadingChange={reportLoading} />+ ))}<ScrollArea className="flex-1 min-h-0 scroll-py-8" alwaysShowScrollbars><Autocomplete.List data-quill className="p-2 scroll-py-8"><Autocomplete.Empty className="empty:hidden">- {emptyState && (- <div className="flex flex-col items-center gap-2 px-4 py-8 text-center">- <div className="text-sm font-semibold">{emptyState.title}</div>- {emptyState.body && (- <div className="text-xs text-secondary leading-relaxed">- {emptyState.body}- </div>- )}- </div>+ {isAnyLoading ? (+ <LoadingRows />+ ) : (+ emptyState && (+ <div+ data-attr="menu-filter-empty"+ className="flex flex-col items-center gap-2 px-4 py-8 text-center"+ >+ <div className="text-sm font-semibold">{emptyState.title}</div>+ {emptyState.body && (+ <div className="text-xs text-secondary leading-relaxed">+ {emptyState.body}+ </div>+ )}+ </div>+ ))}</Autocomplete.Empty><Autocomplete.Collection>@@ -626,18 +670,50 @@ function Row({ entry, showCategory, opensSubmenu, selectedRowId, onCommit }: Rowfunction Fetcher({group,onItems,+ onLoadingChange,}: {group: TaxonomicFilterGrouponItems: (type: string, items: TaxonomicDefinitionTypes[]) => void+ /** Reports `isLoading` (no items yet) so the parent can show a skeleton+ * instead of "No X found" during the first fetch. */+ onLoadingChange: (type: string, loading: boolean) => void}): null {const { getGroupListInput } = useTaxonomicFilterContext()const list = useGroupList(getGroupListInput(group))useEffect(() => {onItems(group.type, list.items)}, [group.type, list.items, onItems])+ useEffect(() => {+ onLoadingChange(group.type, list.showLoadingState)+ }, [group.type, list.showLoadingState, onLoadingChange])+ // Make sure we flip back to "not loading" when this group unmounts —+ // otherwise a stale `true` from a previously-active chip would keep+ // the skeleton on screen after we switch scope.+ useEffect(() => {+ return () => {+ onLoadingChange(group.type, false)+ }+ }, [group.type, onLoadingChange])return null}+/** Skeleton placeholder shown in place of the result list while a remote+ * fetch is in flight and we have nothing to show yet. Matches the row+ * layout (two-line label + tag stub) so the popover height doesn't jump+ * when results arrive. */+function LoadingRows(): JSX.Element {+ return (+ <div className="flex flex-col gap-1 p-2" data-attr="menu-filter-loading">+ {[0, 1, 2, 3, 4].map((i) => (+ <div key={i} className="flex flex-col gap-1 px-2 py-1">+ <Skeleton className="h-3.5 w-2/3 rounded" />+ <Skeleton className="h-3 w-1/3 rounded" />+ </div>+ ))}+ </div>+ )+}+/*** Parse a URL-shaped string into `{ host, pathTail }` for two-line row* rendering. Returns `null` for anything that isn't a `http(s)://` URL ordiff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsxindex 6d7daa7e9f31..1bdf4577c438 100644--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx@@ -1111,6 +1111,11 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([type: TaxonomicFilterGroupType.Cohorts,endpoint: combineUrl(`api/projects/${projectId}/cohorts/`).url,value: 'cohorts',+ // Cohort populations comfortably fit in one page for+ // the overwhelming majority of teams — cache the+ // first 100 once and fuse-filter typed queries+ // locally instead of round-tripping per keystroke.+ clientFilterFirstPage: true,getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,getValue: (cohort: CohortType) => cohort.id,getPopoverHeader: (cohort: CohortType) => `${cohort.is_static ? 'Static' : 'Dynamic'} Cohort`,@@ -1130,6 +1135,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([searchPlaceholder: 'cohorts',type: TaxonomicFilterGroupType.CohortsWithAllUsers,endpoint: combineUrl(`api/projects/${projectId}/cohorts/`).url,+ clientFilterFirstPage: true,options: COHORTS_WITH_ALL_USERS_OPTIONS,getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,getValue: (cohort: CohortType) => cohort.id,diff --git a/frontend/src/lib/components/TaxonomicFilter/types.ts b/frontend/src/lib/components/TaxonomicFilter/types.tsindex a59544440a4a..b2afb655891c 100644--- a/frontend/src/lib/components/TaxonomicFilter/types.ts+++ b/frontend/src/lib/components/TaxonomicFilter/types.ts@@ -261,6 +261,15 @@ export interface TaxonomicFilterGroup {* Returned items are QuickFilterItems and flow through existing isQuickFilterItem* handling in consumer onChange handlers. */keywordShortcuts?: (searchQuery: string) => QuickFilterItem[]+ /**+ * Pre-fetch the first page (empty-query) once, cache it, and filter+ * subsequent typed queries client-side via Fuse rather than firing a+ * fresh request per keystroke. Used by groups whose total population+ * comfortably fits in a single page (e.g. Cohorts) where the snappy+ * local feel is worth losing access to results past the first page.+ * Per-keystroke remote fetches are suppressed when this is on.+ */+ clientFilterFirstPage?: boolean}export enum TaxonomicFilterGroupType {diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsxindex cab6974d6038..8507d8b1e2ec 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx@@ -656,6 +656,10 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomitype: TaxonomicFilterGroupType.Cohorts,endpoint: combineUrl(`api/projects/${projectId}/cohorts/`).url,value: 'cohorts',+ // See taxonomicFilterLogic — cohort populations comfortably fit+ // in one page; cache the first 100 and fuse-filter typed+ // queries locally to avoid per-keystroke round-trips.+ clientFilterFirstPage: true,getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,getValue: (cohort: CohortType) => cohort.id,getPopoverHeader: (cohort: CohortType) => `${cohort.is_static ? 'Static' : 'Dynamic'} Cohort`,@@ -675,6 +679,7 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): TaxonomisearchPlaceholder: 'cohorts',type: TaxonomicFilterGroupType.CohortsWithAllUsers,endpoint: combineUrl(`api/projects/${projectId}/cohorts/`).url,+ clientFilterFirstPage: true,options: COHORTS_WITH_ALL_USERS_OPTIONS,getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,getValue: (cohort: CohortType) => cohort.id,@@ -954,6 +959,9 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomitype: 'filters',order: '-last_modified_at',}).url,+ // Recording playlists are tiny per team — cache the first page+ // and let fuse handle keystrokes locally.+ clientFilterFirstPage: true,render: SavedFiltersTaxonomicGroup,getName: (filter: SessionRecordingPlaylistType) => filter.name || filter.derived_name || 'Unnamed',getValue: (filter: SessionRecordingPlaylistType) => filter.short_id,diff --git a/frontend/src/models/cohortsModel.ts b/frontend/src/models/cohortsModel.tsindex a0f9b20077e6..5158ea627bef 100644--- a/frontend/src/models/cohortsModel.ts+++ b/frontend/src/models/cohortsModel.ts@@ -4,6 +4,8 @@ import { router } from 'kea-router'import { v4 as uuidv4 } from 'uuid'import api, { CountedPaginatedResponse } from 'lib/api'+import { invalidateTaxonomicResourcesWhere } from 'lib/components/TaxonomicFilter/hooks/useTaxonomicResource'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { permanentlyMount } from 'lib/utils/kea-logic-builders'import { COHORT_EVENT_TYPES_WITH_EXPLICIT_DATETIME } from 'scenes/cohorts/CohortFilters/constants'@@ -112,6 +114,20 @@ function processCohortCriteria(criteria: AnyCohortCriteriaType): AnyCohortCriterreturn processedCriteria}+/**+ * Predicate for `invalidateTaxonomicResourcesWhere` — matches the cache+ * entries belonging to the `Cohorts` / `CohortsWithAllUsers` taxonomic+ * groups. The key shape is set in `useGroupList`:+ * ['taxonomic-list', groupType, endpoint, scopedEndpoint, isExpanded,+ * searchQuery, limit, showNumericalPropsOnly, hideBehavioralCohorts]+ */+function isCohortTaxonomicListKey(key: unknown[]): boolean {+ if (key[0] !== 'taxonomic-list') {+ return false+ }+ return key[1] === TaxonomicFilterGroupType.Cohorts || key[1] === TaxonomicFilterGroupType.CohortsWithAllUsers+}+export const cohortsModel = kea<cohortsModelType>([path(['models', 'cohortsModel']),connect(() => ({@@ -245,6 +261,17 @@ export const cohortsModel = kea<cohortsModelType>([count: [(selectors) => [selectors.cohorts], (cohorts) => cohorts.count],}),listeners(({ actions }) => ({+ // Flush the TaxonomicFilter cohort cache whenever cohorts mutate+ // so the next open of the cohort picker re-fetches the first page.+ // The picker pins its request to `?search=&limit=100` and runs+ // fuse client-side — invalidation here is what keeps that snappy+ // local cache honest after create / update / delete.+ cohortCreated: () => {+ invalidateTaxonomicResourcesWhere(isCohortTaxonomicListKey)+ },+ updateCohort: () => {+ invalidateTaxonomicResourcesWhere(isCohortTaxonomicListKey)+ },loadCohortsSuccess: async ({ cohorts }: { cohorts: CountedPaginatedResponse<CohortType> }) => {const is_calculating = cohorts.results.filter((cohort) => cohort.is_calculating).length > 0if (!is_calculating || !router.values.location.pathname.includes(urls.cohorts())) {@@ -260,6 +287,7 @@ export const cohortsModel = kea<cohortsModelType>([actions.setPollTimeout(window.setTimeout(actions.loadAllCohorts, POLL_TIMEOUT))},deleteCohort: async ({ cohort }) => {+ invalidateTaxonomicResourcesWhere(isCohortTaxonomicListKey)await deleteWithUndo({endpoint: api.cohorts.determineDeleteEndpoint(),object: cohort,