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.

fix(taxonomic-filter): show failed requests with retry (#118188)

Paul D'Ambraac7be4e18b2f
diff --git a/docs/internal/taxonomic-filter-search.md b/docs/internal/taxonomic-filter-search.md
index f3b6afd74766..a73b21da7f39 100644
--- a/docs/internal/taxonomic-filter-search.md
+++ b/docs/internal/taxonomic-filter-search.md
@@ -7,7 +7,10 @@ The classic picker shows its active category in the search input. A person can d
The rail starts undocked. `taxonomic filter category rail toggled` records whether it is docked. `taxonomic filter closed` records the final `categoryRailDocked` state so reports can show which people keep the rail docked.
A category shows results for the current query only. It clears its earlier rows when the current query cannot fetch, such as a query below the category minimum length or a request that failed.
-In the classic picker, a failed search with no usable matches shows an error and a retry action.
+A failed search with no usable matches shows an error in the classic picker and the rebuilt menu.
+The rebuilt menu offers "Try again" to retry the failed result source.
+Pressing Enter or Space on the headless panel's "Try again" button retries without selecting the failed query.
+Retrying a server search does not reload the cached first page.
A failed search does not offer an uncaptured event name, and it does not change the selected form value.
When a caller allows custom event names, a successful empty search offers "Use event name".
Pressing Enter in the search input selects that custom event name.
diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/Panel.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/Panel.tsx
index 524e7de8443a..fa418d94bb75 100644
--- a/frontend/src/lib/components/TaxonomicFilter/headless/Panel.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/Panel.tsx
@@ -1,6 +1,7 @@
-import { ReactNode, useEffect, useRef } from 'react'
+import { ReactNode, useCallback, useEffect, useRef, useState } from 'react'
-import { Empty, EmptyHeader, EmptyTitle, ItemMenuItem, Spinner } from '@posthog/quill'
+import { IconWarning } from '@posthog/icons'
+import { Button, Empty, EmptyHeader, EmptyTitle, ItemMenuItem, Spinner } from '@posthog/quill'
import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'
@@ -70,6 +71,19 @@ function TaxonomicFilterActivePanel({
}: ActivePanelProps): JSX.Element {
const { getGroupListInput, registerActiveList, selectItem } = useTaxonomicFilterContext()
const list: UseGroupListResult = useGroupList(getGroupListInput(group))
+ // `useTaxonomicResource`'s cache only notifies subscribers once a fetch settles, not when
+ // it starts, so `list.isFetching` doesn't flip to true for the duration of an imperative
+ // `refetch()` call here. Track the retry's own in-flight state instead, so the button shows
+ // a loading state and can't be clicked again mid-retry.
+ const [retrying, setRetrying] = useState(false)
+ const handleRetry = useCallback(async (): Promise<void> => {
+ setRetrying(true)
+ try {
+ await list.refetch()
+ } finally {
+ setRetrying(false)
+ }
+ }, [list])
// Register this list as the keyboard target for as long as the panel
// is mounted. We pass a stable getter (`useRef`-backed) instead of
@@ -102,6 +116,29 @@ function TaxonomicFilterActivePanel({
)
}
+ if (list.showErrorState) {
+ return (
+ <div className={className}>
+ <Empty>
+ <EmptyHeader>
+ <IconWarning className="text-5xl text-tertiary" />
+ <EmptyTitle>Couldn't load results</EmptyTitle>
+ </EmptyHeader>
+ <Button
+ variant="outline"
+ size="sm"
+ data-attr="taxonomic-panel-retry"
+ loading={retrying}
+ onKeyDown={(event) => event.stopPropagation()}
+ onClick={handleRetry}
+ >
+ Try again
+ </Button>
+ </Empty>
+ </div>
+ )
+ }
+
if (list.showEmptyState) {
return (
<div className={className}>
diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/headless.test.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/headless.test.tsx
index fa50eabe50e3..4cfc40a92f3f 100644
--- a/frontend/src/lib/components/TaxonomicFilter/headless/headless.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/headless.test.tsx
@@ -153,6 +153,35 @@ describe('TaxonomicFilterHeadless integration', () => {
)
})
+ it.each(['{Enter}', ' '])('retries a failed search with %s without selecting the query', async (key) => {
+ const onEnter = jest.fn()
+ apiGet.mockRejectedValue(new Error('search unavailable'))
+ render(
+ <Provider>
+ <TaxonomicFilterHeadless.Root
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties]}
+ onChange={onChangeMock}
+ onEnter={onEnter}
+ searchQuery="needle"
+ >
+ <TaxonomicFilterHeadless.Panel />
+ </TaxonomicFilterHeadless.Root>
+ </Provider>
+ )
+ await waitFor(() => expect(screen.getByTestId('taxonomic-panel-retry')).toBeInTheDocument())
+ apiGet.mockClear()
+ apiGet.mockResolvedValue({ results: [{ name: 'needle_result' }], count: 1 })
+
+ await user.tab()
+ expect(screen.getByTestId('taxonomic-panel-retry')).toHaveFocus()
+ await user.keyboard(key)
+
+ await waitFor(() => expect(screen.getByText('needle_result')).toBeInTheDocument())
+ expect(apiGet).toHaveBeenCalledTimes(1)
+ expect(onEnter).not.toHaveBeenCalled()
+ expect(onChangeMock).not.toHaveBeenCalled()
+ })
+
it('shows the empty-state slot when local search returns nothing', async () => {
apiGet.mockResolvedValue({ results: [], count: 0 })
renderHeadless()
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx
index 99ba106be7dd..f30520a53722 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx
@@ -138,11 +138,8 @@ describe('useGroupList', () => {
// The exact count is deterministic: fetches fire synchronously from act-flushed
// effects, so both hooks' requests (or cache hits) precede waitFor's first poll.
await waitFor(() => expect(apiGet).toHaveBeenCalledTimes(expectedFetches))
- if (expectedFetches === 2) {
- // The differing params must actually reach the request, not just the cache key.
- const [firstUrl, secondUrl] = apiGet.mock.calls.map(([url]) => url)
- expect(firstUrl).not.toEqual(secondUrl)
- }
+ // The differing params must actually reach the request, not just the cache key.
+ expect(new Set(apiGet.mock.calls.map(([url]) => url)).size).toBe(expectedFetches)
})
it('respects minSearchQueryLength gating', () => {
@@ -172,7 +169,7 @@ describe('useGroupList', () => {
expect(result.current.needsMoreSearchCharacters).toBe(true)
})
- it('drops the previous page when the request for the current query fails', async () => {
+ it('drops the previous page and surfaces an error when the request for the current query fails', async () => {
apiGet
.mockResolvedValueOnce({ results: [{ name: 'alpha' }], count: 1 })
.mockRejectedValueOnce(new Error('search unavailable'))
@@ -186,6 +183,17 @@ describe('useGroupList', () => {
await waitFor(() => expect(result.current.items).toEqual([]))
expect(result.current.isLoading).toBe(false)
+ // Surfaced so the UI can tell "failed" apart from "genuinely empty".
+ expect(result.current.error).toBeInstanceOf(Error)
+ expect(result.current.showErrorState).toBe(true)
+ expect(result.current.showEmptyState).toBe(false)
+
+ apiGet.mockResolvedValueOnce({ results: [{ name: 'beta-result' }], count: 1 })
+ await act(async () => {
+ await result.current.refetch()
+ })
+ expect(result.current.items).toEqual([{ name: 'beta-result' }])
+ expect(result.current.showErrorState).toBe(false)
})
it('refires when searchQuery changes', async () => {
@@ -323,6 +331,46 @@ describe('useGroupList', () => {
rerender({ q: 'needle' })
await waitFor(() => expect(result.current.items.map((i: any) => i.name)).toEqual(['Needle cohort']))
})
+
+ it('surfaces an error (not an empty result) when the server search fails, and refetch retries only it', async () => {
+ const firstPage = Array.from({ length: 100 }, (_, i) => ({ name: `Cohort ${i + 1}` }))
+ apiGet.mockImplementation((url: string) => {
+ if (url.includes('search=needle')) {
+ return Promise.reject(new Error('search unavailable'))
+ }
+ // Empty-query first page: 100 of 150 total.
+ return Promise.resolve({ results: firstPage, count: 150 })
+ })
+ const group = makeGroup({
+ type: TaxonomicFilterGroupType.Cohorts,
+ endpoint: 'api/projects/1/cohorts/',
+ clientFilterFirstPage: true,
+ })
+ const { result, rerender } = renderHook(({ q }: { q: string }) => useGroupList({ group, searchQuery: q }), {
+ initialProps: { q: '' },
+ })
+ await waitFor(() => expect(result.current.totalResultCount).toBe(150))
+ // "needle" matches nothing in the cached first page, so only the (failing)
+ // server search could tell us whether it exists elsewhere in the other 50 rows.
+ rerender({ q: 'needle' })
+ await waitFor(() => expect(result.current.showErrorState).toBe(true))
+ expect(result.current.error).toBeInstanceOf(Error)
+ expect(result.current.showEmptyState).toBe(false)
+ expect(result.current.items).toEqual([])
+
+ // The cached first page is healthy, so a retry must not re-request it: if that
+ // request failed, it would hide the recovered search behind a new error.
+ apiGet.mockImplementation((url: string) =>
+ url.includes('search=needle')
+ ? Promise.resolve({ results: [{ name: 'Needle cohort' }], count: 1 })
+ : Promise.reject(new Error('first page unavailable'))
+ )
+ await act(async () => {
+ await result.current.refetch()
+ })
+ expect(result.current.items.map((i: any) => i.name)).toEqual(['Needle cohort'])
+ expect(result.current.showErrorState).toBe(false)
+ })
})
describe('keyword shortcuts', () => {
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
index 17e6f0add197..2a518d99a401 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
@@ -105,7 +105,14 @@ export interface UseGroupListResult {
isFetching: boolean
needsMoreSearchCharacters: boolean
hasRemoteDataSource: boolean
+ /** The last error from the active remote source for the current query. Can be truthy
+ * even when `items` is non-empty (a cached page still has rows while a later search
+ * fails), so use `showErrorState` when "nothing usable to fall back on" is what matters. */
+ error: unknown
showEmptyState: boolean
+ /** A fetch that failed for the current query. Kept separate from `showEmptyState` so a
+ * timeout or a 5xx doesn't read as "this project has no matching properties". */
+ showErrorState: boolean
showLoadingState: boolean
showNonCapturedEventOption: boolean
@@ -113,7 +120,9 @@ export interface UseGroupListResult {
isExpanded: boolean
expand: () => void
- refetch: () => void
+ /** Retries the failed fetch. Resolves once the retry settles, so a caller can
+ * disable its retry button for the duration. */
+ refetch: () => Promise<unknown>
}
const DEFAULT_LIMIT = 100
@@ -483,12 +492,21 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
return realResults.length === 0
}, [allowNonCapturedEvents, group.type, group.excludedProperties, trimmedSearch, isLoading, items])
+ // A fetch that failed for the *current* query with nothing usable to fall back on.
+ // Mirrors legacy infiniteListLogic's `showErrorState`. When the server search is the
+ // active source (dataset bigger than one cached page), its failure is what must
+ // surface — the cached first page already succeeded, so `remote.error` stays unset
+ // and a failed search would otherwise read as "no results".
+ const error = serverSearchEnabled ? serverSearch.error : remote.error
+ const showErrorState = remoteEnabled && !!error && items.length === 0 && !isLoading
+
// Empty / loading state checks read array length, not the API-reported
// total — a remote tab can have count > 0 while still loading its first
// page, and we don't want to flash an empty state during that window.
const showEmptyState =
- (items.length === 0 && !isLoading && (!!searchQuery || !hasRemoteDataSource) && !showNonCapturedEventOption) ||
- needsMoreSearchCharacters
+ !showErrorState &&
+ ((items.length === 0 && !isLoading && (!!searchQuery || !hasRemoteDataSource) && !showNonCapturedEventOption) ||
+ needsMoreSearchCharacters)
const showLoadingState = isLoading && items.length === 0
@@ -531,17 +549,20 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
isFetching,
needsMoreSearchCharacters,
hasRemoteDataSource,
+ error,
showEmptyState,
+ showErrorState,
showLoadingState,
showNonCapturedEventOption,
isExpandable,
isExpanded,
expand,
refetch: () => {
- remote.refetch()
+ const pending = [serverSearchEnabled ? serverSearch.refetch() : remote.refetch()]
if (remoteEnabled && group.scopedEndpoint && !isExpanded) {
- expandedCount.refetch()
+ pending.push(expandedCount.refetch())
}
+ return Promise.all(pending)
},
}
}
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx
index 9ebfcbe4e5c4..6769c23bbf40 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx
@@ -478,7 +478,9 @@ describe('useTaxonomicFilter', () => {
isFetching: false,
needsMoreSearchCharacters: false,
hasRemoteDataSource: false,
+ error: undefined,
showEmptyState: false,
+ showErrorState: false,
showLoadingState: false,
showNonCapturedEventOption: false,
isExpandable: false,
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
index 651db37285df..c5ab81adf802 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
@@ -191,6 +191,120 @@ describe('MenuFilterCombobox', () => {
expect(screen.getAllByText('Power users').length).toBeGreaterThan(0)
})
+ it('shows an error state with retry when the cohorts fetch fails (not the empty state), captures it once, and retry re-fetches', async () => {
+ const user = userEvent.setup()
+ apiGet.mockImplementation((url: string) =>
+ url.includes('cohorts') ? Promise.reject(new Error('network error')) : emptyPaginated()
+ )
+
+ renderCombobox()
+
+ await waitFor(() => {
+ expect(screen.getByTestId('menu-filter-error')).toBeInTheDocument()
+ })
+ expect(screen.getByText("Couldn't load results")).toBeInTheDocument()
+ expect(screen.queryByTestId('menu-filter-empty')).not.toBeInTheDocument()
+ expect(screen.queryByText(/No "Cohorts" found/)).not.toBeInTheDocument()
+ // Fires once for the failed fetch — mirrors legacy's per-group+query dedup.
+ expect(captureMock).toHaveBeenCalledWith(
+ 'taxonomic filter fetch failed',
+ expect.objectContaining({ groupType: TaxonomicFilterGroupType.Cohorts, searchQuery: '' })
+ )
+ expect(
+ captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')
+ ).toHaveLength(1)
+
+ apiGet.mockResolvedValueOnce({ results: [{ id: 1, name: 'Internal team' }], count: 1 })
+ await user.click(screen.getByText('Try again'))
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('menu-filter-error')).not.toBeInTheDocument()
+ })
+ expect(screen.getAllByText('Internal team').length).toBeGreaterThan(0)
+ })
+
+ it('does not capture a stale `taxonomic filter fetch failed` or show the error block after a failed query is followed by a new one that succeeds', async () => {
+ apiGet.mockImplementation((url: string) =>
+ url.includes('search=fail') ? Promise.reject(new Error('network error')) : emptyPaginated()
+ )
+ const tree = (q: string): JSX.Element => (
+ <Provider>
+ <TaxonomicFilterHeadless.Root
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}
+ onChange={jest.fn()}
+ searchQuery={q}
+ >
+ <MenuFilterCombobox
+ drillTo={TaxonomicFilterGroupType.Events}
+ onCommit={jest.fn()}
+ onBack={jest.fn()}
+ />
+ </TaxonomicFilterHeadless.Root>
+ </Provider>
+ )
+
+ const { rerender } = render(tree('fail'))
+ await waitFor(() => expect(screen.getByTestId('menu-filter-error')).toBeInTheDocument())
+ expect(
+ captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')
+ ).toHaveLength(1)
+ // A failed fetch is not a dead-end search — it must not also inflate the
+ // `taxonomic filter empty result` metric.
+ expect(
+ captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter empty result')
+ ).toHaveLength(0)
+
+ apiGet.mockImplementation((url: string) =>
+ url.includes('search=fail')
+ ? Promise.reject(new Error('network error'))
+ : Promise.resolve({ results: [{ name: 'ok_event' }], count: 1 })
+ )
+ rerender(tree('ok'))
+
+ await waitFor(() => expect(screen.getAllByText('ok_event').length).toBeGreaterThan(0))
+ expect(screen.queryByTestId('menu-filter-error')).not.toBeInTheDocument()
+ // The new query's own fetch never failed, so the dedup count must stay at the one
+ // genuine failure — a stale report for "fail" must not recapture under "ok".
+ expect(
+ captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')
+ ).toHaveLength(1)
+ })
+
+ it('does not recapture `taxonomic filter fetch failed` for a trailing-whitespace edit of the same failing query', async () => {
+ apiGet.mockImplementation((url: string) =>
+ url.includes('search=ab') ? Promise.reject(new Error('network error')) : emptyPaginated()
+ )
+ const tree = (q: string): JSX.Element => (
+ <Provider>
+ <TaxonomicFilterHeadless.Root
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}
+ onChange={jest.fn()}
+ searchQuery={q}
+ >
+ <MenuFilterCombobox
+ drillTo={TaxonomicFilterGroupType.Events}
+ onCommit={jest.fn()}
+ onBack={jest.fn()}
+ />
+ </TaxonomicFilterHeadless.Root>
+ </Provider>
+ )
+
+ const { rerender } = render(tree('ab'))
+ await waitFor(() => expect(screen.getByTestId('menu-filter-error')).toBeInTheDocument())
+ expect(
+ captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')
+ ).toHaveLength(1)
+
+ // A trailing space is a different cache key (and a different raw query tag for one
+ // render) but the same trimmed query — it must not read as a fresh failure.
+ rerender(tree('ab '))
+ await waitFor(() => expect(screen.getByTestId('menu-filter-error')).toBeInTheDocument())
+ expect(
+ captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')
+ ).toHaveLength(1)
+ })
+
it('dedups a synthetic selected entry against the real remote entry (no double checkmark)', async () => {
apiGet.mockResolvedValue({
results: [
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
index 426dd844a2b9..b72f6683cdbd 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
@@ -15,7 +15,7 @@ import { useValues } from 'kea'
import posthog from 'posthog-js'
import { MutableRefObject, ReactElement, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { IconCheck, IconChevronRight, IconClock, IconPinFilled } from '@posthog/icons'
+import { IconCheck, IconChevronRight, IconClock, IconPinFilled, IconWarning } from '@posthog/icons'
import {
Badge,
Button,
@@ -238,6 +238,17 @@ export function MenuFilterCombobox({
// `loadingByType` which is `loading && no-items-yet`). Drives the reveal
// barrier so kept-previous-data refetches still hold the list.
const [fetchingByType, setFetchingByType] = useState<Record<string, { query?: string; fetching: boolean }>>({})
+ // Per-group "failed with nothing to fall back on" flag, reported by `Fetcher`, tagged with
+ // the query it belongs to. Drives the error state (instead of "No results") and gates which
+ // groups `handleRetry` re-fetches. The query tag matters because a group reports its error
+ // asynchronously: typing a new query can change `searchQuery` before the previous query's
+ // failed report clears, and an error reported for a stale query must not read as a failure
+ // of the current one.
+ const [errorByType, setErrorByType] = useState<Record<string, { query?: string; hasError: boolean }>>({})
+ // Latest retry function per group, kept out of state since identity changes every render
+ // and it's only read imperatively from `handleRetry`.
+ const retryFnsRef = useRef<Record<string, () => Promise<unknown>>>({})
+ const [retrying, setRetrying] = useState(false)
// Only engages while actively searching a fetching scope. Recent/Pinned read
// pre-resolved entries (`drillItems` when drilled to, the recents/pinned props
// when picked from the category select) and never fetch, so they're never gated.
@@ -294,6 +305,18 @@ export function MenuFilterCombobox({
)
}, [])
+ const reportError = useCallback(
+ (type: string, hasError: boolean, retry: () => Promise<unknown>, query?: string): void => {
+ retryFnsRef.current[type] = retry
+ setErrorByType((prev) =>
+ prev[type]?.hasError === hasError && prev[type]?.query === query
+ ? prev
+ : { ...prev, [type]: { query, hasError } }
+ )
+ },
+ []
+ )
+
// Chips show only when `drillTo='all'` — drilled scopes lock to one
// category and hide the chip row per spec.
const showChips = drillTo === 'all'
@@ -678,6 +701,30 @@ export function MenuFilterCombobox({
return targetGroups.some((g) => loadingByType[g.type])
}, [drillItems, targetGroups, loadingByType])
+ // True when a visible group's request failed with nothing to fall back on — takes over
+ // from the empty state (below) so a dead backend doesn't read as "no matching results".
+ // Only counts a report tagged with the *current* query — a stale report for a query the
+ // user has already moved on from must not read as a failure of what's on screen now.
+ const anyError = useMemo(() => {
+ if (drillItems) {
+ return false
+ }
+ return targetGroups.some((g) => errorByType[g.type]?.hasError && errorByType[g.type]?.query === searchQuery)
+ }, [drillItems, targetGroups, errorByType, searchQuery])
+
+ const handleRetry = useCallback(async (): Promise<void> => {
+ setRetrying(true)
+ try {
+ await Promise.all(
+ targetGroups
+ .filter((g) => errorByType[g.type]?.hasError && errorByType[g.type]?.query === searchQuery)
+ .map((g) => retryFnsRef.current[g.type]?.())
+ )
+ } finally {
+ setRetrying(false)
+ }
+ }, [targetGroups, errorByType, searchQuery])
+
// ---- Reveal barrier ----------------------------------------------------
// Close synchronously the instant the query changes (React "adjust state
// while rendering" pattern) so a stale list never paints between keystroke
@@ -811,7 +858,11 @@ export function MenuFilterCombobox({
// `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.
+ // not an empty result. A failed fetch is a different outcome (`taxonomic filter
+ // fetch failed`, below), so `anyError` rules it out — and `anyFetching` holds off
+ // capturing until every group has actually reported in: on the first render of a
+ // query, nothing has reported loading yet, so `emptyState` briefly looks like a
+ // genuine empty result before the real outcome (success, empty, or error) is known.
// `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
@@ -820,7 +871,7 @@ export function MenuFilterCombobox({
const lastEmptyResultKeyRef = useRef<string | null>(null)
useEffect(() => {
const trimmed = searchQuery.trim()
- if (!emptyState || emptyState.body || !trimmed) {
+ if (!emptyState || emptyState.body || !trimmed || anyError || anyFetching) {
return
}
const key = `${telemetryGroupType ?? 'all'}::${trimmed}`
@@ -833,7 +884,37 @@ export function MenuFilterCombobox({
groupType: telemetryGroupType,
searchQuery: trimmed,
})
- }, [emptyState, searchQuery, telemetryGroupType])
+ }, [emptyState, searchQuery, telemetryGroupType, anyError, anyFetching])
+
+ // `taxonomic filter fetch failed` — once per scope+query while the visible list's request
+ // keeps failing. Mirrors legacy `lastFetchFailedDedupeKey`: the key is only cleared once the
+ // group settles without an error, so retries that fail again for the same query don't
+ // recapture, but a later genuine failure for a new query does.
+ // Clearing on `!anyFetching` rather than `!isAnyLoading` matters: `isAnyLoading` depends on
+ // the fetch having no cached data yet, so a retry on a key that already holds older data (or
+ // a raw-query tag that hasn't caught up yet, e.g. a trailing-whitespace edit) reads as
+ // "settled" for one render even though the request hasn't actually finished. `anyFetching`
+ // treats that same stale tag as still busy, so the key survives the gap.
+ const lastFetchFailedKeyRef = useRef<string | null>(null)
+ useEffect(() => {
+ const trimmed = searchQuery.trim()
+ if (!anyError) {
+ if (!anyFetching) {
+ lastFetchFailedKeyRef.current = null
+ }
+ return
+ }
+ const key = `${telemetryGroupType ?? 'all'}::${trimmed}`
+ if (lastFetchFailedKeyRef.current === key) {
+ return
+ }
+ lastFetchFailedKeyRef.current = key
+ posthog.capture('taxonomic filter fetch failed', {
+ surface: TAXONOMIC_FILTER_SURFACE,
+ groupType: telemetryGroupType,
+ searchQuery: trimmed,
+ })
+ }, [anyError, anyFetching, 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
@@ -1072,6 +1153,7 @@ export function MenuFilterCombobox({
onItems={reportItems}
onLoadingChange={reportLoading}
onFetchingChange={reportFetching}
+ onErrorChange={reportError}
/>
))}
<ScrollArea className="flex-1 min-h-0 scroll-py-8" alwaysShowScrollbars>
@@ -1079,6 +1161,26 @@ export function MenuFilterCombobox({
<Autocomplete.Empty className="empty:hidden">
{isAnyLoading || barrierClosed ? (
<LoadingRows />
+ ) : anyError ? (
+ <div
+ data-attr="menu-filter-error"
+ className="flex flex-col items-center gap-2 px-4 py-8 text-center"
+ >
+ <IconWarning className="text-5xl text-tertiary" />
+ <div className="text-sm font-semibold">Couldn't load results</div>
+ <Button
+ variant="outline"
+ size="sm"
+ data-attr="menu-filter-retry"
+ loading={retrying}
+ onClick={handleRetry}
+ >
+ Try again
+ </Button>
+ <div className="text-xs text-secondary italic">
+ If it keeps happening, contact support.
+ </div>
+ </div>
) : (
emptyState && (
<div
@@ -1408,6 +1510,7 @@ function Fetcher({
onItems,
onLoadingChange,
onFetchingChange,
+ onErrorChange,
}: {
group: TaxonomicFilterGroup
/** Hide stale event definitions (event / custom-event groups only). */
@@ -1419,6 +1522,10 @@ function Fetcher({
/** Reports `isFetching` (true during background refetches too) so the
* parent's reveal barrier holds the list until every group settles. */
onFetchingChange: (type: string, fetching: boolean, query?: string) => void
+ /** Reports whether this group's request failed with nothing to fall back on, plus a
+ * retry function the parent can call from the error state's "Try again" button, and
+ * the query the report belongs to (so the parent can ignore a stale report). */
+ onErrorChange: (type: string, hasError: boolean, retry: () => Promise<unknown>, query?: string) => void
}): null {
const { getGroupListInput } = useTaxonomicFilterContext()
const input = getGroupListInput(group)
@@ -1432,15 +1539,24 @@ function Fetcher({
useEffect(() => {
onFetchingChange(group.type, list.isFetching, input.searchQuery)
}, [group.type, list.isFetching, input.searchQuery, onFetchingChange])
- // Make sure we flip back to "not loading"/"not fetching" when this group
- // unmounts — otherwise a stale `true` from a previously-active chip would
- // keep the skeleton (or the reveal barrier) stuck after we switch scope.
+ // `refetch`'s identity changes every render — read it through a ref so the effect only
+ // reruns when `showErrorState` itself changes, not on every unrelated re-render.
+ const refetchRef = useRef(list.refetch)
+ refetchRef.current = list.refetch
+ useEffect(() => {
+ onErrorChange(group.type, list.showErrorState, () => refetchRef.current(), input.searchQuery)
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- refetchRef always holds the latest fn
+ }, [group.type, list.showErrorState, input.searchQuery, onErrorChange])
+ // Make sure we flip back to "not loading"/"not fetching"/"not errored" when this group
+ // unmounts — otherwise a stale `true` from a previously-active chip would keep the
+ // skeleton (or the reveal barrier, or the error state) stuck after we switch scope.
useEffect(() => {
return () => {
onLoadingChange(group.type, false)
onFetchingChange(group.type, false)
+ onErrorChange(group.type, false, () => Promise.resolve())
}
- }, [group.type, onLoadingChange, onFetchingChange])
+ }, [group.type, onLoadingChange, onFetchingChange, onErrorChange])
return null
}