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(taxonomic-filter): bring rebuild menu to legacy telemetry + stale-event parity (#62043)

Paul D'Ambra42c74c71d52f
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.test.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.test.ts
new file mode 100644
index 000000000000..5bcf9c039f45
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.test.ts
@@ -0,0 +1,38 @@
+import { TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { fetchTaxonomicListPage } from './fetchTaxonomicListPage'
+
+jest.mock('lib/api', () => ({
+ __esModule: true,
+ default: { get: jest.fn().mockResolvedValue({ results: [], count: 0 }) },
+}))
+
+const apiGet = jest.requireMock('lib/api').default.get as jest.Mock
+
+function group(type: TaxonomicFilterGroupType): TaxonomicFilterGroup {
+ return { type, name: type, endpoint: `api/projects/1/${type}`, searchAlias: 'search' } as TaxonomicFilterGroup
+}
+
+describe('fetchTaxonomicListPage exclude_stale', () => {
+ beforeEach(() => apiGet.mockClear())
+
+ const cases: [string, TaxonomicFilterGroupType, boolean, boolean][] = [
+ ['events + excludeStale', TaxonomicFilterGroupType.Events, true, true],
+ ['custom-events + excludeStale', TaxonomicFilterGroupType.CustomEvents, true, true],
+ ['events without excludeStale', TaxonomicFilterGroupType.Events, false, false],
+ ['non-event group + excludeStale', TaxonomicFilterGroupType.EventProperties, true, false],
+ ]
+ it.each(cases)('%s -> exclude_stale present=%s', async (_label, groupType, excludeStale, present) => {
+ await fetchTaxonomicListPage({
+ group: group(groupType),
+ searchQuery: 'foo',
+ offset: 0,
+ limit: 100,
+ isExpanded: false,
+ excludeStale,
+ })
+
+ const url = apiGet.mock.calls[0][0] as string
+ expect(url.includes('exclude_stale=true')).toBe(present)
+ })
+})
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts
index 546ea2bd553a..bd2936038525 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts
@@ -8,7 +8,7 @@
import { combineUrl } from 'kea-router'
import api from 'lib/api'
-import { ListStorage, TaxonomicFilterGroup } from 'lib/components/TaxonomicFilter/types'
+import { ListStorage, TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
export interface FetchTaxonomicPageParams {
group: TaxonomicFilterGroup
@@ -18,6 +18,9 @@ export interface FetchTaxonomicPageParams {
isExpanded: boolean
showNumericalPropsOnly?: boolean
hideBehavioralCohorts?: boolean
+ /** Exclude event definitions not ingested within the staleness window. Only
+ * applies to the event / custom-event endpoints (mirrors legacy `exclude_stale`). */
+ excludeStale?: boolean
signal?: AbortSignal
}
@@ -31,6 +34,7 @@ export async function fetchTaxonomicListPage({
isExpanded,
showNumericalPropsOnly,
hideBehavioralCohorts,
+ excludeStale,
signal,
}: FetchTaxonomicPageParams): Promise<ListStorage> {
const remoteEndpoint = group.endpoint
@@ -63,6 +67,11 @@ export async function fetchTaxonomicListPage({
if (hideBehavioralCohorts) {
baseParams.hide_behavioral_cohorts = 'true'
}
+ const isEventGroup =
+ group.type === TaxonomicFilterGroupType.Events || group.type === TaxonomicFilterGroupType.CustomEvents
+ if (excludeStale && isEventGroup) {
+ baseParams.exclude_stale = 'true'
+ }
const useScoped = group.scopedEndpoint && !isExpanded
const primaryUrl = useScoped ? group.scopedEndpoint! : remoteEndpoint
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
index f9a085f6fa97..69fbf981373d 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
@@ -55,6 +55,9 @@ export interface UseGroupListInput {
* numeric-only items locally for DataWarehousePersonProperties. */
showNumericalPropsOnly?: boolean
hideBehavioralCohorts?: boolean
+ /** Exclude event definitions not seen within the staleness window (event /
+ * custom-event endpoints only). Mirrors legacy's default-on `exclude_stale`. */
+ excludeStale?: boolean
/** Override per-group minSearchQueryLength. */
minSearchQueryLength?: number
/** Pagination page size. */
@@ -109,6 +112,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
optionsFromProp,
showNumericalPropsOnly = false,
hideBehavioralCohorts = false,
+ excludeStale = false,
minSearchQueryLength: minSearchOverride,
limit = DEFAULT_LIMIT,
allowNonCapturedEvents = false,
@@ -200,6 +204,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
limit,
showNumericalPropsOnly,
hideBehavioralCohorts,
+ excludeStale,
],
[
group.type,
@@ -210,6 +215,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
limit,
showNumericalPropsOnly,
hideBehavioralCohorts,
+ excludeStale,
]
)
@@ -224,6 +230,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
isExpanded,
showNumericalPropsOnly,
hideBehavioralCohorts,
+ excludeStale,
signal,
}),
// Long staleTime for client-filtered groups — the cached first page
@@ -260,6 +267,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
limit,
showNumericalPropsOnly,
hideBehavioralCohorts,
+ excludeStale,
],
[
group.type,
@@ -270,6 +278,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
limit,
showNumericalPropsOnly,
hideBehavioralCohorts,
+ excludeStale,
]
)
@@ -284,6 +293,7 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
isExpanded,
showNumericalPropsOnly,
hideBehavioralCohorts,
+ excludeStale,
signal,
}),
{ enabled: serverSearchEnabled, staleTime: 60_000, keepPreviousData: true }
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
index edd5e09c2cb7..70096d3af889 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
@@ -14,12 +14,17 @@ import { initKeaTests } from '~/test/init'
import { TaxonomicFilterHeadless } from '../headless'
import { __clearTaxonomicResourceCache } from '../hooks/useTaxonomicResource'
import { TaxonomicFilterGroupType } from '../types'
-import { MenuFilterCombobox } from './Combobox'
+import { MenuFilterCombobox, SEARCH_QUERY_DEBOUNCE_MS } from './Combobox'
jest.mock('~/queries/query', () => ({
performQuery: jest.fn(),
}))
+jest.mock('posthog-js', () => ({
+ __esModule: true,
+ default: { capture: jest.fn() },
+}))
+
jest.mock('lib/api', () => {
const emptyPaginated = (): Promise<{ results: any[]; count: number; next: null }> =>
Promise.resolve({ results: [], count: 0, next: null })
@@ -38,6 +43,7 @@ jest.mock('lib/api', () => {
})
const apiGet = jest.requireMock('lib/api').default.get as jest.MockedFunction<any>
+const captureMock = jest.requireMock('posthog-js').default.capture as jest.Mock
function renderCombobox(): ReturnType<typeof render> {
return render(
@@ -66,6 +72,7 @@ function renderAll(options: {
recentEntries?: any[]
pinnedEntries?: any[]
searchQuery?: string
+ onCommit?: any
}): ReturnType<typeof render> {
return render(
<Provider>
@@ -78,7 +85,7 @@ function renderAll(options: {
drillTo="all"
recentEntries={options.recentEntries}
pinnedEntries={options.pinnedEntries}
- onCommit={jest.fn()}
+ onCommit={options.onCommit ?? jest.fn()}
onBack={jest.fn()}
/>
</TaxonomicFilterHeadless.Root>
@@ -96,6 +103,7 @@ describe('MenuFilterCombobox', () => {
beforeEach(() => {
__clearTaxonomicResourceCache()
apiGet.mockReset()
+ captureMock.mockClear()
;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })
useMocks({})
initKeaTests()
@@ -401,4 +409,192 @@ describe('MenuFilterCombobox', () => {
expect(await screen.findByRole('option', { name: 'Recent' })).toBeInTheDocument()
expect(screen.getByRole('option', { name: 'Pinned' })).toBeInTheDocument()
})
+
+ it('forwards row selection context on commit and does not emit the legacy event itself', async () => {
+ const user = userEvent.setup()
+ apiGet.mockResolvedValue({ results: [], count: 0 })
+ const onCommit = jest.fn()
+
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events],
+ recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'pageview', 'Events')],
+ onCommit,
+ })
+
+ await waitFor(() => expect(document.querySelector('[data-slot="taxonomic-filter-menu-row"]')).toBeTruthy())
+ await user.click(document.querySelector('[data-slot="taxonomic-filter-menu-row"]') as HTMLElement)
+
+ expect(onCommit).toHaveBeenCalledWith(
+ expect.objectContaining({ group: expect.objectContaining({ type: TaxonomicFilterGroupType.Events }) }),
+ undefined,
+ // groupType is undefined for the 'all' meta scope; the final-commit funnel
+ // (TaxonomicFilterMenu) turns this context into the legacy event.
+ {
+ groupType: undefined,
+ position: 0,
+ wasFromRecents: true,
+ wasFromPinnedList: false,
+ }
+ )
+ // The combobox no longer fires the legacy event on row click — that moved to
+ // the final-commit funnel so cancelable DWH table picks are not counted.
+ expect(captureMock).not.toHaveBeenCalledWith('taxonomic filter item selected', expect.anything())
+ })
+
+ it('forwards wasFromPinnedList=true in the commit context for a pinned row', async () => {
+ const user = userEvent.setup()
+ apiGet.mockResolvedValue({ results: [], count: 0 })
+ const onCommit = jest.fn()
+
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.EventProperties],
+ pinnedEntries: [makeEntry(TaxonomicFilterGroupType.EventProperties, 'plan', 'Event properties')],
+ onCommit,
+ })
+
+ await waitFor(() => expect(document.querySelector('[data-slot="taxonomic-filter-menu-row"]')).toBeTruthy())
+ await user.click(document.querySelector('[data-slot="taxonomic-filter-menu-row"]') as HTMLElement)
+
+ expect(onCommit).toHaveBeenCalledWith(
+ expect.anything(),
+ undefined,
+ expect.objectContaining({ wasFromPinnedList: true, wasFromRecents: false })
+ )
+ })
+
+ it('captures debounced `taxonomic_filter_search_query` for a typed query', async () => {
+ // Fake timers only here — the rest of the suite drives real async via
+ // userEvent/waitFor. Scoped so advancing the debounce is deterministic and
+ // instant instead of blocking on a real 500 ms timeout.
+ jest.useFakeTimers()
+ try {
+ apiGet.mockResolvedValue({ results: [], count: 0 })
+
+ renderAll({ groupTypes: [TaxonomicFilterGroupType.Events], searchQuery: 'pageview' })
+
+ await act(async () => {
+ // Flush the data-fetch microtasks the debounce effect rides behind…
+ await Promise.resolve()
+ // …then fire the debounce timer.
+ jest.advanceTimersByTime(SEARCH_QUERY_DEBOUNCE_MS)
+ })
+
+ expect(captureMock).toHaveBeenCalledWith(
+ 'taxonomic_filter_search_query',
+ expect.objectContaining({
+ surface: 'rebuild-menu',
+ searchQuery: 'pageview',
+ inputMode: 'typed',
+ pastedFraction: 0,
+ // Stale events hidden by default → excludeStale reads true at search time.
+ excludeStale: true,
+ })
+ )
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('captures `taxonomic filter empty result` for a no-match search', async () => {
+ apiGet.mockResolvedValue({ results: [], count: 0 })
+
+ renderAll({ groupTypes: [TaxonomicFilterGroupType.Events], searchQuery: 'zzz_no_match' })
+
+ await waitFor(() =>
+ expect(captureMock).toHaveBeenCalledWith(
+ 'taxonomic filter empty result',
+ expect.objectContaining({ searchQuery: 'zzz_no_match' })
+ )
+ )
+ })
+
+ it('fires `taxonomic filter empty result` exactly once per scope+query (dedup)', async () => {
+ apiGet.mockResolvedValue({ results: [], count: 0 })
+
+ renderAll({ groupTypes: [TaxonomicFilterGroupType.Events], searchQuery: 'zzz_no_match' })
+
+ await waitFor(() =>
+ expect(captureMock).toHaveBeenCalledWith(
+ 'taxonomic filter empty result',
+ expect.objectContaining({ searchQuery: 'zzz_no_match' })
+ )
+ )
+
+ const emptyResultCalls = captureMock.mock.calls.filter(
+ ([event, props]: [string, any]) =>
+ event === 'taxonomic filter empty result' && props?.searchQuery === 'zzz_no_match'
+ )
+ expect(emptyResultCalls).toHaveLength(1)
+ })
+
+ it('re-fires empty result for a query revisited after a different one (last-key dedup, matches legacy)', async () => {
+ apiGet.mockResolvedValue({ results: [], count: 0 })
+ const emptyFor = (q: string): number =>
+ captureMock.mock.calls.filter(
+ ([event, props]: [string, any]) => event === 'taxonomic filter empty result' && props?.searchQuery === q
+ ).length
+ const tree = (q: string): JSX.Element => (
+ <Provider>
+ <TaxonomicFilterHeadless.Root
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}
+ onChange={jest.fn()}
+ searchQuery={q}
+ >
+ <MenuFilterCombobox drillTo="all" onCommit={jest.fn()} onBack={jest.fn()} />
+ </TaxonomicFilterHeadless.Root>
+ </Provider>
+ )
+
+ const { rerender } = render(tree('aaa'))
+ await waitFor(() => expect(emptyFor('aaa')).toBe(1))
+
+ rerender(tree('bbb'))
+ await waitFor(() => expect(emptyFor('bbb')).toBe(1))
+
+ // Returning to "aaa" re-fires — an unbounded set would have suppressed it.
+ rerender(tree('aaa'))
+ await waitFor(() => expect(emptyFor('aaa')).toBe(2))
+ })
+
+ it('hides stale events by default and refetches including them when the empty-state button is clicked', async () => {
+ const user = userEvent.setup()
+ apiGet.mockResolvedValue({ results: [], count: 0 })
+
+ render(
+ <Provider>
+ <TaxonomicFilterHeadless.Root
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}
+ onChange={jest.fn()}
+ searchQuery="zzz_no_match"
+ >
+ <MenuFilterCombobox
+ drillTo={TaxonomicFilterGroupType.Events}
+ onCommit={jest.fn()}
+ onBack={jest.fn()}
+ />
+ </TaxonomicFilterHeadless.Root>
+ </Provider>
+ )
+
+ // Default: the events fetch hides stale definitions.
+ await waitFor(() =>
+ expect(apiGet.mock.calls.some(([url]: [string]) => url.includes('exclude_stale=true'))).toBe(true)
+ )
+
+ const callsBeforeOptIn = apiGet.mock.calls.length
+ await user.click(await screen.findByRole('button', { name: 'Include stale events' }))
+
+ // Opting in emits the legacy toggle event…
+ expect(captureMock).toHaveBeenCalledWith(
+ 'taxonomic filter include stale toggled',
+ expect.objectContaining({ surface: 'rebuild-menu', includeStaleEvents: true })
+ )
+
+ // …and refetches the events list without the stale exclusion.
+ await waitFor(() => {
+ const newUrls: string[] = apiGet.mock.calls.slice(callsBeforeOptIn).map(([url]: [string]) => url)
+ expect(newUrls.length).toBeGreaterThan(0)
+ expect(newUrls.every((url: string) => !url.includes('exclude_stale=true'))).toBe(true)
+ })
+ })
})
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
index 6131a951aee1..5004130996c2 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
@@ -18,6 +18,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { IconCheck, IconChevronRight, IconClock, IconPinFilled } from '@posthog/icons'
import {
Badge,
+ Button,
cn,
InputGroup,
InputGroupAddon,
@@ -45,7 +46,7 @@ import { TaxonomicDefinitionTypes, TaxonomicFilterGroup, TaxonomicFilterGroupTyp
import { promoteMatchingBy } from '../utils/promoteProperties'
import { MenuFilterHeader } from './Header'
import { PreviewPane } from './PreviewPane'
-import { CommitFn, DrillCategory, MenuFilterEntry } from './types'
+import { CommitFn, CommitSelectionContext, DrillCategory, MenuFilterEntry, TAXONOMIC_FILTER_SURFACE } from './types'
import { VerificationBadge } from './VerificationBadge'
// `threshold` + `ignoreDiacritics` come from `createFuse` defaults; we
@@ -80,6 +81,10 @@ const HIDDEN_FROM_CHIPS: ReadonlySet<TaxonomicFilterGroupType> = new Set([
* the pill variant's top-3 face. */
const RECENT_PINNED_PREFIX_LIMIT = 3
+/** Debounce before emitting `taxonomic_filter_search_query` — matches the
+ * legacy picker so the search telemetry is comparable across variants. */
+export const SEARCH_QUERY_DEBOUNCE_MS = 500
+
/** Identity for an entry's underlying definition — source group + value.
* Uses `::` as separator to serve as a dedup key (distinct from DOM ids). */
function entryKey(entry: MenuFilterEntry): string {
@@ -145,6 +150,10 @@ export function MenuFilterCombobox({
}
return drillTo
})
+ // The scope the user is actually looking at: the active chip when chips show
+ // (drillTo='all'), otherwise the drilled-to category. Single source for the
+ // telemetry group type, empty state, stale-toggle gating, and reset trigger.
+ const activeScope: DrillCategory = drillTo === 'all' ? activeChip : 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
@@ -159,6 +168,21 @@ export function MenuFilterCombobox({
const [highlightedEntry, setHighlightedEntry] = useState<MenuFilterEntry | null>(selectedEntry ?? null)
const inputRef = useRef<HTMLInputElement | null>(null)
+ // Stale events (event definitions not ingested within the staleness window)
+ // are hidden by default to match the legacy picker. The opt-in is per-search:
+ // reset whenever the query or active scope changes so stale results never
+ // carry across unrelated searches (mirrors legacy `setSearchQuery`/`setActiveTab`).
+ const [includeStaleEvents, setIncludeStaleEvents] = useState(false)
+ useEffect(() => {
+ setIncludeStaleEvents(false)
+ }, [searchQuery, activeScope])
+ // Read inside the debounced search-query capture without re-triggering it on
+ // toggle (the toggle changes results, not the query).
+ const includeStaleEventsRef = useRef(includeStaleEvents)
+ useEffect(() => {
+ includeStaleEventsRef.current = includeStaleEvents
+ }, [includeStaleEvents])
+
// Stable DOM id for the selected row — derived via `rowDomId` to stay in
// sync with `Row`'s `stableId` and the `filtered` selected-promotion logic.
const selectedRowId = useMemo<string | null>(() => {
@@ -236,16 +260,15 @@ export function MenuFilterCombobox({
// Resolve which groups feed the visible list, based on the active chip
// (or the drill scope when chips are hidden).
const targetGroups = useMemo<TaxonomicFilterGroup[]>(() => {
- const scope = showChips ? activeChip : drillTo
- if (scope === 'all') {
+ if (activeScope === 'all') {
return visibleChipGroups
}
- if (scope === 'recent' || scope === 'pinned') {
+ if (activeScope === 'recent' || activeScope === 'pinned') {
return [] // items come from `drillItems`
}
- const g = groups.find((gr) => gr.type === scope)
+ const g = groups.find((gr) => gr.type === activeScope)
return g ? [g] : []
- }, [showChips, activeChip, drillTo, groups, visibleChipGroups])
+ }, [activeScope, groups, visibleChipGroups])
// Mount + subscribe so `$survey_response_<question-id>` keys resolve to the
// actual question text. `getFriendlyLabel` reads through `getCoreFilterDefinition`,
@@ -423,6 +446,15 @@ export function MenuFilterCombobox({
return base
}, [indexed, searchQuery, selectedRowId, recentsPinnedPrefix, showChips, activeChip, drillTo])
+ // O(1) row -> rendered-position lookup, rebuilt with `filtered`. Avoids an
+ // O(n) `indexOf` per commit and the stale-index risk if `filtered`'s identity
+ // shifts between render and click.
+ const positionByEntry = useMemo<Map<MenuFilterEntry, number>>(() => {
+ const map = new Map<MenuFilterEntry, number>()
+ filtered.forEach((entry, position) => map.set(entry, position))
+ return map
+ }, [filtered])
+
// Active-chip-aware placeholder. When the user has narrowed to a
// specific category, use that group's `searchPlaceholder` so the
// input reflects the search scope ("Search events" vs. the broad
@@ -471,10 +503,9 @@ export function MenuFilterCombobox({
if (isAnyLoading) {
return null
}
- const scope = showChips ? activeChip : drillTo
const singleGroup =
- scope !== 'all' && scope !== 'recent' && scope !== 'pinned'
- ? (groups.find((g) => g.type === scope) ?? null)
+ activeScope !== 'all' && activeScope !== 'recent' && activeScope !== 'pinned'
+ ? (groups.find((g) => g.type === activeScope) ?? null)
: null
const minLen = singleGroup?.minSearchQueryLength ?? 0
const trimmedLen = searchQuery.trim().length
@@ -485,7 +516,7 @@ export function MenuFilterCombobox({
body: `Type at least ${minLen} characters to search ${description} we have seen.`,
}
}
- const categoryLabel = singleGroup?.name ?? (showChips ? null : null)
+ const categoryLabel = singleGroup?.name ?? null
if (trimmedLen > 0) {
return {
title: categoryLabel ? `No "${categoryLabel}" found` : 'No matches',
@@ -494,7 +525,107 @@ export function MenuFilterCombobox({
return {
title: categoryLabel ? `No "${categoryLabel}" found` : 'No items',
}
- }, [filtered.length, showChips, activeChip, drillTo, groups, searchQuery, isAnyLoading])
+ }, [filtered.length, activeScope, groups, searchQuery, isAnyLoading])
+
+ // --- Telemetry parity ---------------------------------------------------
+ // Emit the legacy `taxonomic filter *` contract so the rebuild is
+ // comparable to the control/pill variants by feature-flag value (PostHog
+ // auto-attaches the active flag to every event). The meta scopes
+ // (all/recent/pinned) have no single source group, so groupType is
+ // undefined there — matching how legacy reports the active content tab.
+ const telemetryGroupType = useMemo<TaxonomicFilterGroupType | undefined>(() => {
+ return activeScope === 'all' || activeScope === 'recent' || activeScope === 'pinned' ? undefined : activeScope
+ }, [activeScope])
+
+ const pastedCharsRef = useRef(0)
+
+ // `taxonomic_filter_search_query` — debounced; `inputMode`/`pastedFraction`
+ // distinguish typed vs pasted input. `excludeStale` mirrors legacy: stale events
+ // are hidden by default (so it reads true at search time, since the per-search
+ // opt-in resets on every query change).
+ useEffect(() => {
+ const trimmed = searchQuery.trim()
+ if (!trimmed) {
+ pastedCharsRef.current = 0
+ return
+ }
+ const timer = setTimeout(() => {
+ const pastedChars = pastedCharsRef.current
+ pastedCharsRef.current = 0
+ const totalLength = searchQuery.length
+ // Mirrors the legacy `taxonomicFilterLogic` classifier (kept in sync until the legacy picker is retired).
+ const inputMode = classifyInputMode(pastedChars, totalLength)
+ posthog.capture('taxonomic_filter_search_query', {
+ surface: TAXONOMIC_FILTER_SURFACE,
+ searchQuery,
+ groupType: telemetryGroupType,
+ inputMode,
+ pastedFraction: totalLength > 0 ? Math.min(1, pastedChars / totalLength) : 0,
+ excludeStale: !includeStaleEventsRef.current,
+ })
+ }, SEARCH_QUERY_DEBOUNCE_MS)
+ return () => clearTimeout(timer)
+ }, [searchQuery, telemetryGroupType])
+
+ // `taxonomic filter empty result` — once per scope+query when a real search
+ // returns nothing. `emptyState.body` marks the "type more" prompt, which is
+ // not an empty result.
+ // `groupType` is `undefined` for the meta scopes (All/Recent/Pinned) because there's no single content group there
+ // (legacy fires per-group).
+ // Dedup mirrors legacy `lastEmptyResultDedupeKey`: remember only the most
+ // recent fired key so re-typing the same dead-end after an intervening query
+ // re-fires (an unbounded set would under-count repeated dead-ends vs legacy).
+ const lastEmptyResultKeyRef = useRef<string | null>(null)
+ useEffect(() => {
+ const trimmed = searchQuery.trim()
+ if (!emptyState || emptyState.body || !trimmed) {
+ return
+ }
+ const key = `${telemetryGroupType ?? 'all'}::${trimmed}`
+ if (lastEmptyResultKeyRef.current === key) {
+ return
+ }
+ lastEmptyResultKeyRef.current = key
+ posthog.capture('taxonomic filter empty result', {
+ surface: TAXONOMIC_FILTER_SURFACE,
+ groupType: telemetryGroupType,
+ searchQuery: trimmed,
+ })
+ }, [emptyState, searchQuery, telemetryGroupType])
+
+ // Offered in the empty state whenever an event/custom-event group is among
+ // the visible targets (drilled Events/CustomEvents, or the merged All surface
+ // where stale events are also hidden) — mirrors legacy's recovery button:
+ // no matches behind the default stale filter -> let the user opt in and
+ // refetch with stale definitions included.
+ const eventGroupInScope = targetGroups.some(
+ (g) => g.type === TaxonomicFilterGroupType.Events || g.type === TaxonomicFilterGroupType.CustomEvents
+ )
+ const canOfferStaleToggle = !includeStaleEvents && !!searchQuery.trim() && eventGroupInScope
+ const handleIncludeStaleEvents = useCallback((): void => {
+ setIncludeStaleEvents(true)
+ posthog.capture('taxonomic filter include stale toggled', {
+ surface: TAXONOMIC_FILTER_SURFACE,
+ includeStaleEvents: true,
+ groupType: telemetryGroupType,
+ searchQuery: searchQuery || undefined,
+ })
+ }, [telemetryGroupType, searchQuery])
+
+ const selectionContextFor = useCallback(
+ (entry: MenuFilterEntry): CommitSelectionContext => {
+ const key = entryKey(entry)
+ return {
+ groupType: telemetryGroupType,
+ // Rendered-row index; absent (not a sentinel) if the entry somehow
+ // isn't in `filtered` — `position` then drops out of the payload.
+ position: positionByEntry.get(entry),
+ wasFromRecents: recentKeys.has(key),
+ wasFromPinnedList: pinnedKeys.has(key),
+ }
+ },
+ [telemetryGroupType, recentKeys, pinnedKeys, positionByEntry]
+ )
const headerTitle =
title ??
@@ -585,6 +716,9 @@ export function MenuFilterCombobox({
data-attr="menu-filter-search"
placeholder={activePlaceholder}
onKeyDown={handleInputKeyDown}
+ onPaste={(e: React.ClipboardEvent<HTMLInputElement>) => {
+ pastedCharsRef.current += e.clipboardData.getData('text').length
+ }}
/>
}
value={searchQuery}
@@ -643,7 +777,13 @@ export function MenuFilterCombobox({
</div>
{!drillItems &&
targetGroups.map((g) => (
- <Fetcher key={g.type} group={g} onItems={reportItems} onLoadingChange={reportLoading} />
+ <Fetcher
+ key={g.type}
+ group={g}
+ excludeStale={!includeStaleEvents}
+ 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">
@@ -662,6 +802,16 @@ export function MenuFilterCombobox({
{emptyState.body}
</div>
)}
+ {canOfferStaleToggle && !emptyState.body && (
+ <Button
+ variant="outline"
+ size="sm"
+ data-attr="menu-filter-include-stale-events"
+ onClick={handleIncludeStaleEvents}
+ >
+ Include stale events
+ </Button>
+ )}
</div>
)
)}
@@ -690,7 +840,7 @@ export function MenuFilterCombobox({
// signal that with a chevron.
opensSubmenu={drillTo === TaxonomicFilterGroupType.DataWarehouse}
selectedRowId={selectedRowId}
- onCommit={onCommit}
+ onSelect={() => onCommit(entry, undefined, selectionContextFor(entry))}
/>
)}
</Autocomplete.Collection>
@@ -718,7 +868,8 @@ interface RowProps {
opensSubmenu?: boolean
/** DOM id of the currently-selected row (for the trailing checkmark). */
selectedRowId?: string | null
- onCommit: CommitFn
+ /** Commit this row (also fires item-selected telemetry). */
+ onSelect: () => void
}
/**
@@ -745,7 +896,7 @@ function resolveRowCells(entry: MenuFilterEntry): { name: string; value?: string
return { name: entry.name, category: entry.group.name }
}
-function Row({ entry, showCategory, recency, opensSubmenu, selectedRowId, onCommit }: RowProps): JSX.Element {
+function Row({ entry, showCategory, recency, opensSubmenu, selectedRowId, onSelect }: RowProps): JSX.Element {
const { name, value, category } = resolveRowCells(entry)
const stableId = rowDomId(entry)
const isSelected = selectedRowId === stableId
@@ -754,7 +905,7 @@ function Row({ entry, showCategory, recency, opensSubmenu, selectedRowId, onComm
value={entry}
onClick={(e) => {
e.preventDefault()
- onCommit(entry)
+ onSelect()
}}
data-slot="taxonomic-filter-menu-row"
className={cn(
@@ -806,17 +957,20 @@ function Row({ entry, showCategory, recency, opensSubmenu, selectedRowId, onComm
*/
function Fetcher({
group,
+ excludeStale,
onItems,
onLoadingChange,
}: {
group: TaxonomicFilterGroup
+ /** Hide stale event definitions (event / custom-event groups only). */
+ excludeStale: boolean
onItems: (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))
+ const list = useGroupList({ ...getGroupListInput(group), excludeStale })
useEffect(() => {
onItems(group.type, list.items)
}, [group.type, list.items, onItems])
@@ -891,3 +1045,8 @@ function getFriendlyLabel(item: TaxonomicDefinitionTypes, group: TaxonomicFilter
}
return getCoreFilterDefinition(raw, group.type)?.label
}
+
+// Mirrors the legacy `taxonomicFilterLogic` classifier (kept in sync until the legacy picker is retired).
+function classifyInputMode(pastedChars: number, totalLength: number): 'typed' | 'mixed' | 'pasted' {
+ return pastedChars >= totalLength && pastedChars > 0 ? 'pasted' : pastedChars > 0 ? 'mixed' : 'typed'
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.test.ts b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.test.ts
new file mode 100644
index 000000000000..c91e0fd404fa
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.test.ts
@@ -0,0 +1,17 @@
+import { TaxonomicFilterGroupType } from '../types'
+import { eventSelectionWasStale } from './TaxonomicFilterMenu'
+
+describe('eventSelectionWasStale', () => {
+ const staleEvent = { name: 'old', last_seen_at: '2000-01-01T00:00:00Z' } as any
+ const freshEvent = { name: 'new', last_seen_at: new Date().toISOString() } as any
+
+ it.each([
+ ['stale event definition', TaxonomicFilterGroupType.Events, staleEvent, true],
+ ['fresh event definition', TaxonomicFilterGroupType.Events, freshEvent, false],
+ ['stale custom-event definition', TaxonomicFilterGroupType.CustomEvents, staleEvent, true],
+ ['non-event group', TaxonomicFilterGroupType.EventProperties, staleEvent, undefined],
+ ['event row without last_seen_at', TaxonomicFilterGroupType.Events, { name: 'x' }, undefined],
+ ])('%s -> %s', (_label, groupType, item, expected) => {
+ expect(eventSelectionWasStale(groupType as TaxonomicFilterGroupType, item)).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx
index 19545637b39d..f04c265448cb 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx
@@ -39,18 +39,28 @@ import {
PopoverTrigger,
} from '@posthog/quill'
+import { isDefinitionStale } from 'lib/utils/definitions'
+
import { getCoreFilterDefinition } from '~/taxonomy/helpers'
+import { EventDefinition } from '~/types'
import { useTaxonomicFilterContext } from '../headless/context'
import { recentTaxonomicFiltersLogic } from '../recentTaxonomicFiltersLogic'
import { taxonomicFilterPinnedPropertiesLogic } from '../taxonomicFilterPinnedPropertiesLogic'
-import { META_GROUP_TYPES, TaxonomicDefinitionTypes, TaxonomicFilterGroupType } from '../types'
+import { isQuickFilterItem, META_GROUP_TYPES, TaxonomicDefinitionTypes, TaxonomicFilterGroupType } from '../types'
import { filterPinnedForContext, filterRecentsForContext } from '../utils/suggestedContextFilters'
import { MenuFilterCombobox } from './Combobox'
import { MenuFilterDwhConfig } from './DwhFlow'
import { MenuFilterHogQLEditor } from './HogQLEditor'
import { taxonomicTriggerWrapperClassName } from './triggerLayout'
-import { CommitFn, DrillCategory, MenuFilterEntry, MenuFilterState, TaxonomicFilterGroup } from './types'
+import {
+ CommitFn,
+ DrillCategory,
+ MenuFilterEntry,
+ MenuFilterState,
+ TAXONOMIC_FILTER_SURFACE,
+ TaxonomicFilterGroup,
+} from './types'
export interface TaxonomicFilterMenuProps {
/** Default trigger label when nothing is selected. */
@@ -112,6 +122,21 @@ type MenuOption = 'new' | 'recent' | 'pinned' | 'dwh' | 'hogql'
let lastMenuClosedAtMs: number | null = null
const QUICK_REOPEN_MS = 3000
+/** Mirrors legacy `taxonomicFilterLogic`: staleness only applies to event /
+ * custom-event definitions that carry `last_seen_at`; `undefined` for every
+ * other selection so the field reads identically across the A/B arms. */
+export function eventSelectionWasStale(
+ sourceGroupType: TaxonomicFilterGroupType,
+ item: TaxonomicDefinitionTypes
+): boolean | undefined {
+ const isEventSelection =
+ sourceGroupType === TaxonomicFilterGroupType.Events || sourceGroupType === TaxonomicFilterGroupType.CustomEvents
+ if (!isEventSelection || !item || typeof item !== 'object' || !('last_seen_at' in item)) {
+ return undefined
+ }
+ return isDefinitionStale(item as unknown as EventDefinition)
+}
+
export function TaxonomicFilterMenu({
triggerLabel,
selected,
@@ -158,11 +183,21 @@ export function TaxonomicFilterMenu({
})
} else if (previous !== 'closed' && next === 'closed') {
const closedAt = Date.now()
+ const dwellMs = openedAtRef.current ? closedAt - openedAtRef.current : null
posthog.capture('taxonomic filter menu closed', {
- dwellMs: openedAtRef.current ? closedAt - openedAtRef.current : null,
+ dwellMs,
hadCommit: hadCommitRef.current,
lastState: previous,
})
+ // Legacy `taxonomic filter *` contract — emitted alongside the
+ // menu-specific events so the rebuild is comparable to the
+ // control/pill variants by feature-flag value.
+ // Legacy's `groupType: activeTab` is omitted because the menu has no single active tab at close time.
+ posthog.capture('taxonomic filter closed', {
+ surface: TAXONOMIC_FILTER_SURFACE,
+ dwellMs,
+ hadSelection: hadCommitRef.current,
+ })
lastMenuClosedAtMs = closedAt
openedAtRef.current = null
}
@@ -270,7 +305,7 @@ export function TaxonomicFilterMenu({
// -- Commit -- routes through orchestrator's `selectItem` AND the
// consumer's `onCommit` callback. Closes everything.
const handleCommit = useCallback<CommitFn>(
- (entry, extra) => {
+ (entry, extra, selection) => {
const mergedItem = extra
? ({ ...(entry.item as unknown as object), ...extra } as unknown as TaxonomicDefinitionTypes)
: entry.item
@@ -286,6 +321,33 @@ export function TaxonomicFilterMenu({
// committing this item.
msSinceOpen: openedAtRef.current ? Date.now() - openedAtRef.current : null,
})
+ // Legacy contract, fired from this final-commit funnel rather than on
+ // row click so it counts only committed selections — a DWH table pick
+ // that opens (and is then cancelled from) the config form never reaches
+ // here, while a config-form or HogQL commit does. `groupType` is the
+ // active scope (mirrors legacy `activeTab`); `sourceGroupType` is the
+ // row's origin group — they differ for a recent/pinned row on the All
+ // surface. `selection` is absent for non-row commits (DWH form, HogQL).
+ // `wasStale` mirrors legacy for event/custom-event selections; `wasQuickFilter`
+ // uses the same predicate as legacy, though the menu surfaces no quick-filter
+ // items so it is false in practice and the legacy quick-filter field spread
+ // never applies here.
+ // `position` is the rendered row index (same coordinate as legacy's
+ // `meta.position`): directly comparable on single-group scopes, and
+ // surface-relative on the merged "All" scope, which leads with the
+ // recents/pinned prefix and has no single-tab legacy equivalent.
+ posthog.capture('taxonomic filter item selected', {
+ surface: TAXONOMIC_FILTER_SURFACE,
+ groupType: selection?.groupType,
+ sourceGroupType: entry.group.type,
+ wasFromRecents: selection?.wasFromRecents ?? false,
+ wasFromPinnedList: selection?.wasFromPinnedList ?? false,
+ wasQuickFilter: isQuickFilterItem(entry.item),
+ hadSearchInput: !!searchQuery,
+ position: selection?.position,
+ query: searchQuery || undefined,
+ wasStale: eventSelectionWasStale(entry.group.type, entry.item),
+ })
selectItem(entry.group, itemValue, mergedItem)
onCommit?.({ ...entry, item: mergedItem }, extra)
closeAll()
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/types.ts b/frontend/src/lib/components/TaxonomicFilter/menu/types.ts
index 4667c7789627..defe779d5e2d 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/types.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/types.ts
@@ -10,6 +10,11 @@ import {
TaxonomicFilterValue,
} from '../types'
+/** Stamped on the legacy `taxonomic filter *` telemetry events so the A/B arms
+ * are distinguishable by an explicit property rather than a feature-flag join.
+ * Legacy emits `legacy-control` / `legacy-pill`. */
+export const TAXONOMIC_FILTER_SURFACE = 'rebuild-menu'
+
/** A single selectable entry — what the picker commits when chosen. */
export interface MenuFilterEntry {
item: TaxonomicDefinitionTypes
@@ -47,6 +52,24 @@ export interface PageHeader {
onBack: () => void
}
-export type CommitFn = (entry: MenuFilterEntry, extra?: Record<string, unknown>) => void
+/** Row context the combobox forwards on commit so the legacy `taxonomic filter
+ * item selected` event (emitted from the final-commit funnel, not on row click)
+ * can still carry the row's position and origin. Absent for commits that don't
+ * originate from a combobox row (DWH config form, HogQL editor). */
+export interface CommitSelectionContext {
+ /** Active scope chip the row sat under (legacy `activeTab`); undefined on the All/Recent/Pinned meta scopes. */
+ groupType: TaxonomicFilterGroupType | undefined
+ /** Zero-based row position in the rendered list; undefined if the committed
+ * entry isn't in the rendered list (kept absent rather than a sentinel). */
+ position: number | undefined
+ wasFromRecents: boolean
+ wasFromPinnedList: boolean
+}
+
+export type CommitFn = (
+ entry: MenuFilterEntry,
+ extra?: Record<string, unknown>,
+ selection?: CommitSelectionContext
+) => void
export type { TaxonomicFilterGroup, TaxonomicFilterGroupType, TaxonomicFilterValue, TaxonomicDefinitionTypes }