: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
chore(taxonomic-filter): refresh skill with product reality and tighten (#57378)
Paul D'Ambra22ec3392bcb4
diff --git a/.agents/skills/modifying-taxonomic-filter/SKILL.md b/.agents/skills/modifying-taxonomic-filter/SKILL.mdindex b42e0c349b05..94cda95dec97 100644--- a/.agents/skills/modifying-taxonomic-filter/SKILL.md+++ b/.agents/skills/modifying-taxonomic-filter/SKILL.md@@ -1,127 +1,108 @@---name: modifying-taxonomic-filter-description: Guides safe modification of the TaxonomicFilter component — PostHog's multi-tab search/filter for selecting events, actions, properties, cohorts, and more. Covers the component hierarchy, kea logic architecture, RTL testing workflow, and common pitfalls learned from prior changes. Use when adding features, fixing bugs, or refactoring TaxonomicFilter or its sub-components.+description: Guides safe modification of the TaxonomicFilter — PostHog's multi-tab picker for events, actions, properties, cohorts, and more. Front-loads the empirical product reality (what users actually pick and search for) so changes can be judged against real behavior, not architectural taste. Use when adding features, fixing bugs, or refactoring TaxonomicFilter.---# Modifying the TaxonomicFilter-The TaxonomicFilter is one of PostHog's most complex frontend components.-It powers event/action/property/cohort selection across the entire app.-Changes here have a high blast radius — always lock down behavior with tests before modifying.--## Before you change anything--1. **Read the architecture** — understand which logic and component you're touching.- See [references/architecture.md](references/architecture.md).-2. **Write RTL tests first** — capture the current behavior before making changes.- See [references/testing-patterns.md](references/testing-patterns.md).-3. **Check common pitfalls** — avoid mistakes that have burned prior contributors.- See [references/common-pitfalls.md](references/common-pitfalls.md).-4. **Run the existing test suite** to establish a green baseline:-- ```bash- hogli test frontend/src/lib/components/TaxonomicFilter/- ```--## Architecture at a glance--```text-TaxonomicFilter <- entry point, creates logic props-├── TaxonomicFilterSearchInput <- keyboard events, search query-└── InfiniteSelectResults <- tab pills + per-tab lists- └── InfiniteList <- virtualized list per group- └── InfiniteListRow <- individual result row-```--Three kea logics coordinate behavior:--| Logic | Role | Key file |-| ----------------------------- | -------------------------------------------------------- | ---------------------------------------- |-| `taxonomicFilterLogic` | Orchestrator — tabs, search, group ordering, top matches | `taxonomicFilterLogic.tsx` (~1600 lines) |-| `infiniteListLogic` | Per-tab list — search, pagination, property promotion | `infiniteListLogic.ts` |-| `recentTaxonomicFiltersLogic` | Recent selections persisted to localStorage | `recentTaxonomicFiltersLogic.ts` |--Each `infiniteListLogic` instance is keyed by `listGroupType` and connected to the parent `taxonomicFilterLogic`.--## Key concepts--### Group types--`TaxonomicFilterGroupType` is an enum with 40+ members (`Events`, `Actions`, `PersonProperties`, `PageviewUrls`, `SuggestedFilters`, etc.).-Each group type maps to a `TaxonomicFilterGroup` configuration object defining its endpoint, search behavior, display name, and value extraction.--### Tab ordering--Tabs are ordered by `taxonomicGroupTypes` prop order, but some groups get dynamically reordered.-"Shortcut" groups (`PageviewUrls`, `Screens`, `EmailAddresses`, etc.) are promoted after `SuggestedFilters` when present.-The `groupAnalyticsTaxonomicGroupType` selector normalizes group type names for analytics.--### Search redistribution--`redistributeTopMatches()` distributes search results across groups:--- Each group gets `DEFAULT_SLOTS_PER_GROUP` (5) slots-- Empty groups donate their unused slots to `REDISTRIBUTION_PRIORITY_GROUPS` (`CustomEvents`, `PageviewUrls`, `Screens`)-- Maximum `MAX_TOP_MATCHES_PER_GROUP` (10) results per group--### Skeleton rows--While search results load, `SKELETON_ROWS_PER_GROUP` (3) placeholder rows appear.-Use `isSkeletonItem()` to distinguish skeletons from real results.--### Property promotion--`infiniteListLogic` promotes properties matching exact search terms to the top of results.-`PROMOTED_PROPERTIES_BY_SEARCH_TERM` maps terms like `'url'` to `'$current_url'` and `'email'` to `'$email'`.--## Testing workflow--Always write tests **before** modifying behavior. Two levels of testing:--### Component tests (RTL)--Test what users see and interact with. Located in `TaxonomicFilter.test.tsx`.--```typescript-const rendered = renderFilter({ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events] })-await waitFor(() => expect(screen.getByTestId('taxonomic-filter-searchfield')).toBeInTheDocument())-```--Key patterns: `renderFilter()` helper, `expectActiveTab()` helper, `userEvent` for keyboard/click simulation.-See [references/testing-patterns.md](references/testing-patterns.md) for full details.--### Logic tests (kea-test-utils)--Test state transitions and async behavior. Located in `taxonomicFilterLogic.test.ts`.--```typescript-const logic = taxonomicFilterLogic(logicProps)-logic.mount()-await expectLogic(logic, () => logic.actions.setSearchQuery('pageview')).toMatchValues({ searchQuery: 'pageview' })+The TaxonomicFilter is the picker users hit to choose any "thing PostHog+knows about" — events, properties, actions, cohorts, groups. It's the+on-ramp into almost every analytics and replay configuration. Code lives+in `frontend/src/lib/components/TaxonomicFilter/`.++**The unbreakable rule:** changes that demote items users _actually pick_+are regressions, even with all tests passing. Read "Product reality"+before deciding any change is safe. Ordering, promotion, or position-0+changes need explicit human sign-off — don't let an agent decide alone.++## Product reality (last refreshed 2026-05-02, 90-day window)++Ratios from production telemetry. Re-run via+[references/refreshing-product-reality.md](references/refreshing-product-reality.md)+when older than ~3 months.++### How users pick++- **Top three rows carry ~80% of selections** (position 0: ~56%,+ position 1: ~15%, position 2: ~8%). Demoting a popular item out of+ the top three is a real-user regression.+- **~34% selection rate.** Two of every three opens close without a+ pick. p50 dwell ~7s, p90 ~53s — most opens are quick glances.+- **Selection paths**: ~65% via search, ~19% browsed-no-search,+ ~16% from recents, <1% from pinned items.++### What users select++| Source group type | Share |+| ------------------- | ----- |+| `events` | ~40% |+| `event_properties` | ~30% |+| `person_properties` | ~14% |+| `cohorts` | ~2% |+| `email_addresses` | ~2% |+| `actions` | ~2% |+| `pageview_urls` | ~1% |+| everything else | <1% |++### What users search for (share of top-8 terms)++| Term | Share |+| --------- | ----- |+| `email` | ~29% |+| `url` | ~22% |+| `user` | ~12% |+| `utm` | ~10% |+| `page` | ~9% |+| `path` | ~8% |+| `current` | ~6% |+| `country` | ~5% |++`email` and `url` are over half the top-8. They're the entire reason+`PROMOTED_PROPERTIES_BY_SEARCH_TERM` (in `infiniteListLogic.ts`) maps+them to `$email` and `$current_url` at position 0. **Touching+promotion or ordering needs explicit human sign-off.**++### Empty searches++`email`, `url`, `utm`, `path` against `cohorts`, `event_feature_flags`,+`session_properties` produce most empty-result events — users type the+same canonical terms across every tab. Tab order, suggested-filters+aggregation, and shortcut routing are how they get to the right answer.++### Input mode++~93% typed, ~7% pasted. Both feed `inputMode` on `taxonomic_filter_search_query`.++## Telemetry is a contract++Five events validate every change. Treat property shapes as a public API:++- `taxonomic filter closed` — `dwellMs`, `hadSelection`+- `taxonomic filter item selected` — `sourceGroupType`, `wasFromRecents`, `wasFromPinnedList`, `wasQuickFilter`, `hadSearchInput`, `position`, `query`+- `taxonomic_filter_search_query` — `searchQuery`, `groupType`, `inputMode`, `pastedFraction`+- `taxonomic filter empty result` — `groupType`, `searchQuery`+- `taxonomic filter category dropdown opened` — A/B variant++Adding properties: fine. Removing dead ones: fine. **Renaming or+repurposing silently is the worst case** — dashboards keep working and+start lying.++## Variants you might not see locally++`TAXONOMIC_FILTER_CATEGORY_DROPDOWN` resolves to `'control'` (tab pills)+or `'pill'` (suffix dropdown). Bug reports that don't reproduce locally+are usually a variant mismatch. Touching tab rendering means testing both.++## Pre-change checklist++- [ ] Read references when relevant: [architecture](references/architecture.md),+ [common-pitfalls](references/common-pitfalls.md) (X/Y matrix),+ [call-sites](references/call-sites-and-blast-radius.md) (smoke tests),+ [testing-patterns](references/testing-patterns.md)+- [ ] Test both `control` and `pill` dropdown variants if you touched tabs+- [ ] Confirm telemetry payloads still have the same property shape+- [ ] Ordering / promotion / position-0 -> human sign-off, not agent judgement++```bash+hogli test frontend/src/lib/components/TaxonomicFilter/```--Key patterns: `expectLogic()`, `toMatchValues`, `toDispatchActions`, manual mounting of dependent `infiniteListLogic` instances.-See [references/testing-patterns.md](references/testing-patterns.md) for full details.--## File reference--| File | Lines | Purpose |-| -------------------------------------------------------------------------- | ----- | ------------------------------ |-| `frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx` | ~240 | Entry component + search input |-| `frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx` | ~1600 | Core orchestration logic |-| `frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts` | ~500 | Per-tab list logic |-| `frontend/src/lib/components/TaxonomicFilter/types.ts` | ~280 | All type definitions |-| `frontend/src/lib/components/TaxonomicFilter/InfiniteSelectResults.tsx` | ~200 | Tab pills + list container |-| `frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx` | ~300 | Virtualized list |-| `frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.test.tsx` | ~660 | Component-level RTL tests |-| `frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts` | ~710 | Logic-level tests |--## Checklist for changes--- [ ] Read the relevant architecture section-- [ ] Write RTL tests capturing current behavior-- [ ] Make your change-- [ ] Verify all existing tests still pass-- [ ] Add new tests for the changed behavior-- [ ] Test keyboard navigation if you touched search or selection-- [ ] Test with multiple group types if you touched tab orderingdiff --git a/.agents/skills/modifying-taxonomic-filter/references/architecture.md b/.agents/skills/modifying-taxonomic-filter/references/architecture.mdindex a4348e3fa06e..24814b3f18ac 100644--- a/.agents/skills/modifying-taxonomic-filter/references/architecture.md+++ b/.agents/skills/modifying-taxonomic-filter/references/architecture.md@@ -1,158 +1,69 @@# TaxonomicFilter architecture-## Component hierarchy+## Component tree```textTaxonomicFilter-├── TaxonomicFilterSearchInput # search box with debounced input-└── InfiniteSelectResults # tab bar + virtualized list container- ├── Tab buttons # one per visible TaxonomicFilterGroupType- └── InfiniteList # virtualized list for the active tab- └── InfiniteListRow # individual item row (or skeleton)+├── TaxonomicFilterSearchInput # debounced input + paste detection+├── CategoryDropdown # A/B-tested suffix picker (variant: 'pill')+└── InfiniteSelectResults+ ├── Tab buttons # one per visible group, hidden when empty+ ├── TaxonomicFilterEmptyState+ └── InfiniteList # AutoSizer + react-window virtualized list+ └── InfiniteListRow # item / skeleton / pinned / recent```-### File locations+## Logics-| File | Role |-| -------------------------------- | -------------------------------------------------------------------------- |-| `TaxonomicFilter.tsx` | Entry component, keyboard event handler (ArrowUp/Down, Tab, Enter, Escape) |-| `TaxonomicFilterSearchInput.tsx` | Search input with debounce |-| `InfiniteSelectResults.tsx` | Tab bar rendering, delegates to InfiniteList |-| `InfiniteList.tsx` | Virtualized list using AutoSizer + react-window |-| `InfiniteListRow.tsx` | Renders a single item or skeleton row |-| `types.ts` | All TypeScript types and the `TaxonomicFilterGroupType` enum |+| File | Owns |+| ----------------------------------------- | ----------------------------------------------------------------------------------------------------- |+| `taxonomicFilterLogic.tsx` | Search query, active tab, group ordering, telemetry, keyboard nav. Spawns child list logics. |+| `infiniteListLogic.ts` | Per-tab fetch, pagination, selection, property promotion, top-match donation, empty-result telemetry. |+| `recentTaxonomicFiltersLogic.ts` | Recents persisted to localStorage, prefixed by team id. |+| `taxonomicFilterPinnedPropertiesLogic.ts` | Pinned items persisted to localStorage, prefixed by team id. |-## Kea logic hierarchy+Each `infiniteListLogic` is keyed by `taxonomicFilterLogicKey` + `listGroupType`.+Pinning/recents are shared singletons per team.-Three logics cooperate to manage state:+## Things that aren't where you'd guess-| Logic | File | Responsibility |-| ----------------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `taxonomicFilterLogic` | `taxonomicFilterLogic.tsx` (~1600 lines) | Orchestrator. Manages search query, active tab, group ordering, top matches redistribution, keyboard navigation between tabs. Creates child `infiniteListLogic` per group type. |-| `infiniteListLogic` | `infiniteListLogic.ts` (~500 lines) | Per-tab list management. Handles fetching remote items, local filtering, pagination, item selection, and keyboard navigation within a list. One instance per `TaxonomicFilterGroupType`. |-| `recentTaxonomicFiltersLogic` | `recentTaxonomicFiltersLogic.ts` | Persists recently selected items to localStorage. Shared across filter instances. |+- **Suggested-filters aggregation lives in `infiniteListLogic`**, not+ the parent. See `topMatchesForQuery`, `isSuggestedFilters`, `results`.+ The parent only collects matches via `appendTopMatches` on+ `infiniteListResultsReceived`.+- **`PROMOTED_PROPERTIES_BY_SEARCH_TERM` is in `infiniteListLogic.ts`**,+ not in `taxonomicFilterLogic.tsx`.+- **Pinned/recent rows carry `_pinnedContext` / `_recentContext`** so+ `selectItem` records the _original_ `sourceGroupType` in telemetry,+ not "Pinned" or "Recents".-### Logic instantiation--`taxonomicFilterLogic` is keyed by `taxonomicFilterLogicKey` (a string prop).-Each child `infiniteListLogic` is keyed by the same key plus the `listGroupType`.+## Data flow on search```text-taxonomicFilterLogic({ taxonomicFilterLogicKey: 'my-filter', ... })- ├── infiniteListLogic({ ..., listGroupType: Events })- ├── infiniteListLogic({ ..., listGroupType: Actions })- ├── infiniteListLogic({ ..., listGroupType: PersonProperties })- └── ...one per group type in taxonomicGroupTypes prop+user types+ -> taxonomicFilterLogic.setSearchQuery+ -> debounce -> infiniteListLogic[X].setSearchQuery (per group)+ -> API fetch -> loadRemoteItemsSuccess+ -> empty? fire 'taxonomic filter empty result'+ -> infiniteListResultsReceived(groupType, results)+ -> taxonomicFilterLogic.appendTopMatches(...)+universe of matches -> infiniteListLogic[SuggestedFilters].results+ (via redistributeTopMatches)```-## Key concepts--### TaxonomicFilterGroupType--An enum with 40+ members defining every category the filter can display.-Each group type maps to a data source (API endpoint or local data) and has-its own rendering logic.--Common group types:--- `Events`, `Actions`, `PersonProperties`, `EventProperties`-- `PageviewUrls`, `Screens`, `EmailAddresses` (shortcut property types)-- `SuggestedFilters` (cross-group search results)-- `Cohorts`, `CohortsWithAllUsers`-- `HogQLExpression`, `SessionProperties`--### Group ordering and tab visibility--The `taxonomicGroupTypes` prop controls which tabs appear and their order.-Some groups are dynamically reordered based on search:--- **Shortcut groups** (`PageviewUrls`, `Screens`, `EmailAddresses`, etc.)- are promoted after `SuggestedFilters` when a search matches them-- Empty groups are hidden from the tab bar-- `tabRight()` and `tabLeft()` actions skip empty groups--### Search flow--1. User types → `setSearchQuery` action on `taxonomicFilterLogic`-2. Logic debounces and dispatches to each child `infiniteListLogic`-3. Each list logic fetches remote items from its API endpoint-4. Results populate `remoteItems` in each list logic-5. `taxonomicFilterLogic` aggregates counts via `infiniteListCounts` selector-6. If `SuggestedFilters` group exists, `appendTopMatches` collects top results- from all groups and `redistributeTopMatches` distributes them evenly--### `redistributeTopMatches`--A pure function that distributes suggested filter results across groups:+`redistributeTopMatches` is a pure function — test in isolation.+Constants: `DEFAULT_SLOTS_PER_GROUP=5`, `MAX_TOP_MATCHES_PER_GROUP=10`,+`SKELETON_ROWS_PER_GROUP=3`. Empty groups donate slots to+`REDISTRIBUTION_PRIORITY_GROUPS` (`CustomEvents`, `PageviewUrls`, `Screens`).-- `DEFAULT_SLOTS_PER_GROUP`: 5 items per group initially-- `MAX_TOP_MATCHES_PER_GROUP`: 10 items maximum per group-- Groups with fewer results give their unused slots to groups with more+## Selectors worth knowing-### Skeleton rows--While data is loading, `SKELETON_ROWS_PER_GROUP` (3) placeholder rows-are shown. These are `SkeletonItem` objects (with `is_skeleton: true`)-that render as animated loading placeholders.--### Property promotion--`PROMOTED_PROPERTIES_BY_SEARCH_TERM` maps common search terms to specific-properties. For example, searching "url" promotes `$current_url` to the top-of results. This is handled inside `taxonomicFilterLogic`.--### Shortcut group types--`SHORTCUT_TO_PROPERTY_FILTER_GROUP_TYPES` defines group types that are-"shortcuts" to specific property filter types:--- `PageviewUrls`, `PageviewEvents`-- `Screens`, `ScreenEvents`-- `EmailAddresses`, `AutocaptureEvents`--These groups search the same underlying data as property filters but-present a more focused UI for common use cases.--## Data flow diagram--```text-User input- │- ▼-TaxonomicFilter (keyboard handler)- │- ▼-taxonomicFilterLogic- ├── setSearchQuery ──► infiniteListLogic[Events].setSearchQuery- ├──────────────────► infiniteListLogic[Actions].setSearchQuery- ├──────────────────► infiniteListLogic[PersonProperties].setSearchQuery- │ │- │ ▼- │ API fetch (event_definitions, property_definitions, etc.)- │ │- │ ▼- │ loadRemoteItemsSuccess- │ │- ▼ ▼-appendTopMatches ◄──── results from all list logics- │- ▼-redistributeTopMatches (pure function)- │- ▼-SuggestedFilters tab populated-```+`taxonomicFilterLogic`: `activeTab`, `infiniteListCounts`,+`taxonomicGroups`, `topMatchItems` (aggregated via `appendTopMatches`).-## Important selectors+`infiniteListLogic`: `topMatchesForQuery` (per-tab donated slice),+`isSuggestedFilters`, `results` (incl. skeletons, pinned, recents),+`showSuggestedFiltersEmptyState`.-| Logic | Selector | Returns |-| ---------------------- | ---------------------------- | -------------------------------------------- |-| `taxonomicFilterLogic` | `activeTab` | Current `TaxonomicFilterGroupType` |-| `taxonomicFilterLogic` | `searchQuery` | Current search string |-| `taxonomicFilterLogic` | `infiniteListCounts` | `Record<GroupType, number>` of result counts |-| `taxonomicFilterLogic` | `taxonomicGroups` | Ordered array of group configs |-| `taxonomicFilterLogic` | `topMatchItems` | Raw top match items before redistribution |-| `taxonomicFilterLogic` | `redistributedTopMatchItems` | Items after slot redistribution |-| `infiniteListLogic` | `results` | Items for this group |-| `infiniteListLogic` | `totalResultCount` | Total count including remote |-| `infiniteListLogic` | `isLoading` | Whether fetch is in progress |+Reactive prop behavior uses `propsChanged` + `afterMount`, never+kea-subscriptions — see [common-pitfalls.md](common-pitfalls.md).diff --git a/.agents/skills/modifying-taxonomic-filter/references/call-sites-and-blast-radius.md b/.agents/skills/modifying-taxonomic-filter/references/call-sites-and-blast-radius.mdnew file mode 100644index 000000000000..abb23e59cb39--- /dev/null+++ b/.agents/skills/modifying-taxonomic-filter/references/call-sites-and-blast-radius.md@@ -0,0 +1,42 @@+# TaxonomicFilter call sites and blast radius++The TaxonomicFilter is used in dozens of places. Don't try to enumerate+them — they drift. Find the current set with:++```bash+rg -l '<TaxonomicFilter\b|TaxonomicPopover|TaxonomicPropertyFilter' frontend products+```++## Wrappers (touch one, affect many)++- `lib/components/TaxonomicPopover/TaxonomicPopover.tsx` — generic popover wrapper+- `lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx` — property-filter row+- `lib/components/PropertySelect/PropertySelect.tsx` — single-property selector+- `lib/components/EventSelect/EventSelect.tsx` — single-event selector+- `lib/components/FlagSelector.tsx` — feature-flag picker+- `lib/components/QuickFilters/QuickFilterForm.tsx` — quick-filter authoring+- `lib/components/IngestionControls/triggers/EventTrigger.tsx` — capture trigger config++A change ripples through every consumer of these. Run their tests before+shipping anything broad.++## Prop combinations to think about++| Prop | Why it matters |+| ---------------------- | ------------------------------------------------------------------------------------------- |+| `taxonomicGroupTypes` | Drives which tabs appear and their order. Single-group, subset, and full-default all exist. |+| `excludedProperties` | Hides already-selected keys; some scenes hide system-only properties this way. |+| `metadataSource` | Drives whether the property panel queries events / persons / sessions / warehouse. |+| `eventNames` | Insight-series names so per-event property promotion can run; reactive via `propsChanged`. |+| `onChange` / `onEnter` | Both shapes exist; `onEnter` is used for HogQL expression entry without a concrete pick. |+| `optionsFromProp` | Some pickers inject local items instead of fetching from the API. |++## Smoke test before shipping a broad change++- [ ] Add an event filter inside an insight (Trends or Funnel)+- [ ] Add a property breakdown to a Trends insight+- [ ] Add a person property filter on the Persons scene+- [ ] Add a filter inside Replay's universal filter bar+- [ ] Add a cohort field condition+- [ ] Open the property selector inside Web analytics conversion goal+- [ ] Check both `control` and `pill` variants if you touched tab renderingdiff --git a/.agents/skills/modifying-taxonomic-filter/references/common-pitfalls.md b/.agents/skills/modifying-taxonomic-filter/references/common-pitfalls.mdindex b03c3f54f38a..8c82dea70841 100644--- a/.agents/skills/modifying-taxonomic-filter/references/common-pitfalls.md+++ b/.agents/skills/modifying-taxonomic-filter/references/common-pitfalls.md@@ -1,171 +1,37 @@# Common pitfalls when modifying TaxonomicFilter-Lessons learned from 8 PRs of incremental changes to this component.--## Always write tests before changing behavior--The single most important rule. The filter has subtle interdependencies —-changing one thing often breaks another in ways that only surface through-user-visible behavior.--**Workflow:**--1. Write RTL tests that lock down the current behavior you plan to touch-2. Verify the tests pass-3. Make your change-4. Verify both old and new tests pass--Skipping step 1 leads to regressions that are hard to diagnose because you-can't distinguish "my change broke this" from "this was already broken."--## Assertions that look right but don't catch regressions--### Checking existence instead of content--```tsx-// BAD: passes even if the wrong items are shown-expect(screen.getByTestId('prop-filter-events-0')).toBeInTheDocument()--// GOOD: verifies the actual content-expect(screen.getByTestId('prop-filter-events-0')).toHaveTextContent('$pageview')-```--### Not waiting for async updates--```tsx-// BAD: might pass because the old data hasn't been replaced yet-await userEvent.type(searchField, 'new query')-expect(screen.getByTestId('prop-filter-events-0')).toHaveTextContent('old result')--// GOOD: wait for the new data to arrive-await userEvent.type(searchField, 'new query')-await waitFor(() => {- expect(screen.getByTestId('prop-filter-events-0')).toHaveTextContent('new result')-})-```--### Testing logic state instead of rendered output--```tsx-// BAD: tests the implementation, not the behavior-await expectLogic(logic).toMatchValues({ activeTab: 'events' })--// GOOD: tests what the user sees-expectActiveTab('events')-```--Use logic-level tests for internal invariants (e.g., `redistributeTopMatches`-output). Use component tests for anything the user interacts with.--## Group ordering stability--The tab order is driven by `taxonomicGroupTypes` prop and dynamic reordering-in `taxonomicFilterLogic`. Changes to ordering logic can break:--- **Keyboard navigation**: Tab/Shift+Tab cycles through visible tabs in order.- If you change which tabs are visible or their order, keyboard navigation- tests will fail.-- **Default active tab**: The first non-empty group becomes active. Reordering- can change which tab the user sees first.-- **Shortcut group promotion**: When search matches a shortcut group type,- it gets promoted after `SuggestedFilters`. Adding or removing shortcut- types changes the promoted order.--**Safe approach:** If you need to change group ordering, write a parameterized-test covering all the ordering scenarios before changing the logic.--## Error handling for API failures--Each `infiniteListLogic` fetches data independently. A failure in one tab-should not break other tabs. When modifying fetch logic:--- Ensure `loadRemoteItemsFailure` is handled gracefully (empty results, not crash)-- Test that other tabs still work when one tab's API returns an error-- The `SuggestedFilters` tab aggregates from all tabs — it should handle- partial failures (some tabs succeed, some fail)--## Keyboard navigation edge cases--The keyboard handler in `TaxonomicFilter.tsx` handles:--- ArrowUp/ArrowDown: navigate within the current list-- Tab/Shift+Tab: switch between tabs-- Enter: select the highlighted item-- Escape: close the filter--Common mistakes:--- **Not testing empty states**: ArrowDown in an empty list should be a no-op,- not throw an error-- **Focus management**: After Tab switches tabs, focus should stay in the- search input, not jump to the list-- **Tab wrapping**: Tab on the last tab should wrap to the first tab- (and vice versa for Shift+Tab)--## The AutoSizer mock is required--`InfiniteList` uses `AutoSizer` from `react-virtualized-auto-sizer`.-Without the mock, the component renders with zero height and no items-are visible. Every component test file must include the mock. If you-create a new test file for a sub-component, you'll need it there too.--## Search-aware mock handlers--When testing search behavior, your API mocks need to respect the search-query parameter. A static mock that always returns the same results-won't catch bugs in search filtering:--```tsx-// BAD: always returns the same results regardless of search-'/api/projects/:team/event_definitions': mockEventDefinitions--// GOOD: filters based on search parameter-'/api/projects/:team/event_definitions': (req) => {-'/api/projects/:team_id/event_definitions': (req) => {- const search = req.url.searchParams.get('search')- const filtered = search- ? mockEventDefinitions.filter(e => e.name.includes(search))- : mockEventDefinitions- return [200, { results: filtered, count: filtered.length }]-}+Generic engineering rules don't earn space here. This is the+component-specific traps.++## "If you change X, also check Y"++| Change | Verify |+| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Tab ordering or visibility | Keyboard nav (Tab cycles), default active tab, both `control` and `pill` dropdown variants, suggested-filters tab |+| `PROMOTED_PROPERTIES_BY_SEARCH_TERM` or sort order | `$email` and `$current_url` still at position 0 for `email` / `url` searches |+| Selectors feeding `topMatchesForQuery` | Per-tab output **and** parent `appendTopMatches` aggregation; SuggestedFilters tab still populates |+| Search input or paste handling | `inputMode` field on `taxonomic_filter_search_query` still distinguishes typed/pasted/mixed |+| `selectItem` logic | Telemetry payload (`sourceGroupType`, `wasFromRecents`, `wasFromPinnedList`, `wasQuickFilter`, `position`); recents still recorded; `onChange` still fires |+| Persistence keys (recents or pinned) | Team-id prefix still applied; items don't leak across teams |+| Filter open/close lifecycle | `cache.openedAt` / `cache.hadSelection` still set; `taxonomic filter closed` still fires with `dwellMs` and `hadSelection` |+| Adding a `TaxonomicFilterGroupType` | Group config in `taxonomicFilterLogic.tsx`, shortcut routing, telemetry includes the new type, every consumer's `taxonomicGroupTypes` prop updated |+| Reactive prop behavior in any logic | Use `propsChanged` + `afterMount`, not subscriptions (see below) |++Suggested-filters items appear in API-response order; don't assert on+order within that tab unless you control the timing.++## `propsChanged` + `afterMount`, not subscriptions++```typescript+afterMount(({ actions, props }) => {+ if (props.eventNames?.length) actions.ensureLoadedForEvents(props.eventNames)+}),+propsChanged(({ actions, props }, oldProps) => {+ if (props.eventNames !== oldProps.eventNames && props.eventNames?.length) {+ actions.ensureLoadedForEvents(props.eventNames)+ }+}),```-## SuggestedFilters and top matches--The `SuggestedFilters` group is special — it aggregates results from all-other groups. When modifying it:--- `redistributeTopMatches` is a pure function. Test it in isolation with- parameterized tests covering edge cases (empty groups, uneven distribution,- groups at the max limit).-- Skeleton rows (`SKELETON_ROWS_PER_GROUP = 3`) show while data loads.- Test that skeletons appear before results and disappear after.-- `appendTopMatches` collects items as each tab's results arrive. The- order items appear depends on which API responds first — don't assert- on order within the suggested filters tab unless you control the- response timing.--## Modifying the TaxonomicFilterGroupType enum--Adding a new group type touches many places:--1. The `TaxonomicFilterGroupType` enum in `types.ts`-2. Group configuration in `taxonomicFilterLogic.tsx` (the `groups` selector)-3. Potentially `SHORTCUT_TO_PROPERTY_FILTER_GROUP_TYPES` if it's a shortcut type-4. API endpoint configuration for the new type's data source-5. Every place that switches on group type (rendering, icons, labels)--**Safe approach:** Search for an existing similar group type and follow the-same pattern. Add RTL tests for the new tab before wiring it up.--## Don't test `taxonomicFilterLogic` selectors by re-implementing them--The logic has complex derived selectors (e.g., `infiniteListCounts`,-`redistributedTopMatchItems`). Don't duplicate the computation logic in-your test to build expected values. Instead:--- Test the pure functions directly with known inputs/outputs-- Test selectors through their observable effects (what renders, what- actions fire)-- Use `.toMatchValues()` with `expect.objectContaining()` for partial- checks rather than exact matches on complex objects+kea-subscriptions are slower and have re-mount cost. Established by+`perf(taxonomic-filter): replace eventNames subscription with propsChanged + afterMount`.diff --git a/.agents/skills/modifying-taxonomic-filter/references/refreshing-product-reality.md b/.agents/skills/modifying-taxonomic-filter/references/refreshing-product-reality.mdnew file mode 100644index 000000000000..ab987942de46--- /dev/null+++ b/.agents/skills/modifying-taxonomic-filter/references/refreshing-product-reality.md@@ -0,0 +1,153 @@+# Refreshing the Product reality section++Re-run these every ~3 months. **Public OSS repo: convert to ratios before+writing back — never commit absolute event or user counts.** All queries+use a 90-day window; keep that consistent so trends are comparable.++### 1. Selection breakdown by source group type++Computes share of all `taxonomic filter item selected` events grouped+by `sourceGroupType`. Drives the "What users select" table.++```sql+SELECT+ properties.sourceGroupType AS source_group_type,+ count() AS selections,+ round(100 * count() / (+ SELECT count()+ FROM events+ WHERE event = 'taxonomic filter item selected'+ AND timestamp >= now() - INTERVAL 90 DAY+ ), 1) AS share_pct+FROM events+WHERE event = 'taxonomic filter item selected'+ AND timestamp >= now() - INTERVAL 90 DAY+GROUP BY source_group_type+ORDER BY selections DESC+LIMIT 30+```++### 2. Top searches (share of top-N)++Computes the share of each top-N search term among the top 8 only.+Avoids exposing absolute search volume.++```sql+WITH top_terms AS (+ SELECT lower(trim(toString(properties.searchQuery))) AS q, count() AS searches+ FROM events+ WHERE event = 'taxonomic_filter_search_query'+ AND timestamp >= now() - INTERVAL 90 DAY+ AND length(toString(properties.searchQuery)) > 0+ GROUP BY q+ ORDER BY searches DESC+ LIMIT 8+)+SELECT q, round(100 * searches / sum(searches) OVER (), 1) AS share_pct+FROM top_terms+ORDER BY share_pct DESC+```++### 3. Top empty-result searches++Reveals taxonomy gaps. Use the qualitative findings (which terms are empty+in which groups), not absolute counts.++```sql+SELECT+ lower(trim(toString(properties.searchQuery))) AS q,+ properties.groupType AS group_type,+ count() AS empties+FROM events+WHERE event = 'taxonomic filter empty result'+ AND timestamp >= now() - INTERVAL 90 DAY+GROUP BY q, group_type+ORDER BY empties DESC+LIMIT 40+```++### 4. Selection rate and dwell distribution++Drives the "About one in three opens results in a selection" line, plus+the dwell-time bullet.++```sql+SELECT+ round(100 * countIf(toBool(properties.hadSelection)) / count(), 1) AS selection_rate_pct,+ quantile(0.5)(toFloat(properties.dwellMs)) AS p50_dwell_ms,+ quantile(0.9)(toFloat(properties.dwellMs)) AS p90_dwell_ms+FROM events+WHERE event = 'taxonomic filter closed'+ AND timestamp >= now() - INTERVAL 90 DAY+```++### 5. Selection-source mix++Drives the "65% involve search / 19% browsed / 16% from recents / <1%+from pinned" line. Use only the relative shares — drop the absolute counts+before writing back.++```sql+SELECT+ round(100 * countIf(toBool(properties.hadSearchInput)) / count(), 1) AS had_search_pct,+ round(100 * countIf(NOT toBool(properties.hadSearchInput) AND NOT toBool(properties.wasFromRecents) AND NOT toBool(properties.wasFromPinnedList)) / count(), 1) AS browsed_no_search_pct,+ round(100 * countIf(toBool(properties.wasFromRecents)) / count(), 1) AS from_recents_pct,+ round(100 * countIf(toBool(properties.wasFromPinnedList)) / count(), 1) AS from_pinned_pct+FROM events+WHERE event = 'taxonomic filter item selected'+ AND timestamp >= now() - INTERVAL 90 DAY+```++### 6. Position distribution++Drives the "first three rows carry ~80% of selections" line.++```sql+WITH positions AS (+ SELECT toInt(properties.position) AS pos+ FROM events+ WHERE event = 'taxonomic filter item selected'+ AND timestamp >= now() - INTERVAL 90 DAY+ AND properties.position IS NOT NULL+)+SELECT+ pos,+ round(100 * count() / (SELECT count() FROM positions), 1) AS share_pct+FROM positions+GROUP BY pos+ORDER BY pos ASC+LIMIT 10+```++### 7. Input mode mix++Drives the "~93% typed / ~7% pasted" line.++```sql+SELECT+ properties.inputMode AS input_mode,+ round(100 * count() / (+ SELECT count()+ FROM events+ WHERE event = 'taxonomic_filter_search_query'+ AND timestamp >= now() - INTERVAL 90 DAY+ AND properties.inputMode IS NOT NULL+ ), 1) AS share_pct+FROM events+WHERE event = 'taxonomic_filter_search_query'+ AND timestamp >= now() - INTERVAL 90 DAY+ AND properties.inputMode IS NOT NULL+GROUP BY input_mode+ORDER BY share_pct DESC+```++## Updating the doc++1. Run each query above via `posthog:execute-sql` against+ project 2 on us.posthog.com.+2. Convert findings into ratios (drop absolute event and user counts).+3. Update the tables in `SKILL.md` and bump the "last refreshed" date.+4. If the qualitative story changed (e.g. `email` is no longer dominant,+ or pinned-items usage grew significantly), revise the prose above the+ tables — not just the numbers. Big changes deserve a heads-up to whoever+ owns the component, since they may affect ongoing roadmap decisions.diff --git a/.agents/skills/modifying-taxonomic-filter/references/testing-patterns.md b/.agents/skills/modifying-taxonomic-filter/references/testing-patterns.mdindex f6d58fcf018a..36b7e74d76cd 100644--- a/.agents/skills/modifying-taxonomic-filter/references/testing-patterns.md+++ b/.agents/skills/modifying-taxonomic-filter/references/testing-patterns.md@@ -1,13 +1,14 @@# Testing patterns for TaxonomicFilter-## RTL test setup+For boilerplate, copy from existing tests in+`frontend/src/lib/components/TaxonomicFilter/`. This doc only covers+the things that aren't obvious until they bite.-Every component test needs these pieces:+## Required setup (or tests fail silently)-### AutoSizer mock--The virtualized list uses `AutoSizer` which needs a browser layout engine.-Mock it to render children with fixed dimensions:+**AutoSizer mock** — without this the virtualized list renders at zero+height and `getByTestId('prop-filter-…')` returns nothing while tests+appear to pass.```tsxjest.mock('lib/components/AutoSizer', () => ({@@ -16,30 +17,19 @@ jest.mock('lib/components/AutoSizer', () => ({}))```-### API mocks with `useMocks()`--Set up before each test. The filter fetches event definitions, property definitions, actions, and persons:+**Search-aware mock handlers** — a static handler hides search-filtering+bugs. Always read the `search` param:```tsx-useMocks({- get: {- // Event and property definitions live under /api/projects/:team/...- '/api/projects/:team/event_definitions': mockGetEventDefinitions,- '/api/projects/:team/property_definitions': mockGetPropertyDefinitions,- '/api/projects/:team/actions': mockGetActions,- // Person properties are fetched from /api/environments/:team/...- '/api/environments/:team/persons/properties': mockGetPersonsProperties,- },- post: {- // Queries are posted to the environments endpoint- '/api/environments/:team/query': [200, { results: [] }],- },-})+'/api/projects/:team_id/event_definitions': (req) => {+ const search = req.url.searchParams.get('search')+ const filtered = search ? mockEventDefinitions.filter(e => e.name.includes(search)) : mockEventDefinitions+ return [200, { results: filtered, count: filtered.length }]+}```-### Kea initialization--Mount shared models before each test:+**Persons properties live under `/api/environments/:team/`, not `/projects/`.**+Mount shared models in `beforeEach`:```tsxbeforeEach(() => {@@ -49,221 +39,44 @@ beforeEach(() => {})```-### The `renderFilter()` helper--Wrap the component in a kea `<Provider>` with sensible defaults:--```tsx-const renderFilter = (props: Partial<TaxonomicFilterProps> = {}): RenderResult => {- return render(- <Provider>- <TaxonomicFilter- taxonomicFilterLogicKey="test-filter"- taxonomicGroupTypes={[- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- TaxonomicFilterGroupType.PersonProperties,- ]}- onChange={jest.fn()}- {...props}- />- </Provider>- )-}-```--## Component-level test patterns+## Test IDs-### Test IDs to query+| Element | Pattern |+| ------------ | ------------------------------ |+| Search input | `taxonomic-filter-searchfield` |+| Tab buttons | `taxonomic-tab-{groupType}` |+| List items | `prop-filter-{type}-{index}` |-| Element | Test ID pattern | Example |-| ------------ | ------------------------------ | ---------------------------------------------------- |-| Search input | `taxonomic-filter-searchfield` | `screen.getByTestId('taxonomic-filter-searchfield')` |-| Tab buttons | `taxonomic-tab-{groupType}` | `screen.getByTestId('taxonomic-tab-events')` |-| List items | `prop-filter-{type}-{index}` | `screen.getByTestId('prop-filter-events-0')` |+Active tab assertion: `expect(tab).toHaveClass('LemonTag--primary')`.-### Asserting the active tab+## Logic-level integration tests-```tsx-const expectActiveTab = (type: string): void => {- const tab = screen.getByTestId(`taxonomic-tab-${type}`)- expect(tab).toHaveClass('LemonTag--primary')-}-```--### Typing in search+`taxonomicFilterLogic` spawns child `infiniteListLogic` per group type+— mount them all, then await `loadRemoteItemsSuccess` before asserting:```tsx-const searchField = screen.getByTestId('taxonomic-filter-searchfield')-await userEvent.type(searchField, 'pageview')-```--### Waiting for results after search--Search triggers API calls. Wait for the DOM to update:--```tsx-await waitFor(() => {- expect(screen.getByTestId('prop-filter-events-0')).toBeInTheDocument()-})-```--### Switching tabs--```tsx-const actionsTab = screen.getByTestId('taxonomic-tab-actions')-await userEvent.click(actionsTab)-expectActiveTab('actions')-```--### Keyboard navigation--The filter handles ArrowUp, ArrowDown, Tab, Enter, and Escape.-Test keyboard flows end-to-end through the rendered component:--```tsx-await userEvent.keyboard('{ArrowDown}')-await userEvent.keyboard('{ArrowDown}')-await userEvent.keyboard('{Enter}')-expect(onChange).toHaveBeenCalledWith(/* expected group and value */)-```--### Item selection--```tsx-const onChange = jest.fn()-renderFilter({ onChange })--await waitFor(() => {- expect(screen.getByTestId('prop-filter-events-0')).toBeInTheDocument()-})--await userEvent.click(screen.getByTestId('prop-filter-events-0'))-expect(onChange).toHaveBeenCalledWith(- expect.objectContaining({ type: TaxonomicFilterGroupType.Events }),- expect.anything(),- expect.anything()-)-```--### Testing excluded properties--Pass `excludedProperties` and assert the excluded items do not appear:--```tsx-renderFilter({- excludedProperties: { [TaxonomicFilterGroupType.PersonProperties]: ['location'] },-})--await waitFor(() => {- expect(screen.queryByText('location')).not.toBeInTheDocument()-})-```--### Testing property promotion--Certain search terms promote specific properties (e.g., typing "url" promotes `$current_url`).-Search for the term, then assert the promoted property appears in the results:--```tsx-await userEvent.type(searchField, 'url')-await waitFor(() => {- expect(screen.getByText('$current_url')).toBeInTheDocument()-})-```--## Logic-level test patterns--### Mounting the logic with all child logics--The orchestrator logic creates child `infiniteListLogic` instances.-Mount them all for integration-style tests:--```tsx-const logic = taxonomicFilterLogic({- taxonomicFilterLogicKey: 'test',- taxonomicGroupTypes: groupTypes,- onChange: jest.fn(),-})+const logic = taxonomicFilterLogic({ taxonomicFilterLogicKey: 'test', taxonomicGroupTypes, onChange: jest.fn() })logic.mount()--for (const groupType of groupTypes) {+for (const groupType of taxonomicGroupTypes) {infiniteListLogic({ ...logic.props, listGroupType: groupType }).mount()}-```--### `expectLogic().toMatchValues()`--Assert computed values without triggering actions:--```tsx-await expectLogic(logic).toMatchValues({- activeTab: TaxonomicFilterGroupType.Events,- infiniteListCounts: expect.objectContaining({- [TaxonomicFilterGroupType.Events]: expect.any(Number),- }),-})-```--### `expectLogic(logic, () => action).toMatchValues()`--Trigger an action and assert the resulting state:--```tsx-await expectLogic(logic, () => {- logic.actions.setSearchQuery('pageview')-}).toMatchValues({- searchQuery: 'pageview',-})-```--### `toDispatchActions`--Assert that an action dispatches expected follow-up actions:-```tsx-await expectLogic(logic, () => {- logic.actions.setSearchQuery('test')-}).toDispatchActions(['setSearchQuery'])-```--### Waiting for remote results--API calls are async. Use a helper that waits for the success action:--```tsx-const waitForRemoteResults = async (groupType: TaxonomicFilterGroupType): Promise<void> => {- const listLogic = infiniteListLogic({ ...logic.props, listGroupType: groupType })- await expectLogic(listLogic).toDispatchActions(['loadRemoteItemsSuccess'])+for (const groupType of taxonomicGroupTypes) {+ await expectLogic(infiniteListLogic({ ...logic.props, listGroupType: groupType })).toDispatchActions([+ 'loadRemoteItemsSuccess',+ ])}```-### Testing pure functions+## Don't delete the property-promotion test-Functions like `redistributeTopMatches` can be tested directly without kea.-Use parameterized tests with a helper to build test items:+`email` and `url` searches must promote `$email` and `$current_url` to+position 0 (see Product reality in `SKILL.md`):```tsx-const makeItem = (groupType: TaxonomicFilterGroupType, count: number): TaxonomicDefinitionTypes[] =>- Array.from({ length: count }, (_, i) => ({ name: `${groupType}-${i}` }))--it.each([- {- name: 'distributes evenly across groups',- items: { Events: makeItem(Events, 10), Actions: makeItem(Actions, 10) },- expected: { Events: 5, Actions: 5 },- },- // ... more cases-])('$name', ({ items, expected }) => {- const result = redistributeTopMatches(items, groupTypes)- // assert distribution-})+await userEvent.type(searchField, 'url')+await waitFor(() => expect(screen.getByText('$current_url')).toBeInTheDocument())```-## Key testing principles--1. **Test behavior, not implementation** — assert what the user sees (text, elements, callbacks), not internal kea state-2. **Lock down existing behavior before changing it** — write RTL tests for current behavior first, then modify-3. **Prefer component tests over logic tests** for user-facing behavior — logic tests are for internal invariants-4. **Always wait for async results** — the filter fetches data on mount and on search; use `waitFor` or `waitForRemoteResults`-5. **Use `userEvent` not `fireEvent`** — `userEvent` simulates real browser behavior (focus, blur, keydown sequences)+`redistributeTopMatches` is a pure function — test in isolation with+parameterized cases.