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.

45.2 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import type { BreakPointFunction } from 'kea'
import { loaders } from 'kea-loaders'

import api, { isAbortError } from 'lib/api'
import { shortcutLogic } from 'lib/components/Shortcuts/shortcutLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getEntryAccessDisabledReason } from 'lib/utils/accessControlUtils'
import { uuid } from 'lib/utils/dom'
import { GroupQueryResult, mapGroupQueryResponse } from 'lib/utils/groups'
import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'
import { teamLogic } from 'scenes/teamLogic'

import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { isFileSystemEntryTypeEnabled, splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'
import { groupsModel } from '~/models/groupsModel'
import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry, GroupsQueryResponse } from '~/queries/schema/schema-general'
import { GroupTypeIndex, PersonType, SearchResponse } from '~/types'

import { conversationsTicketsList } from 'products/conversations/frontend/generated/api'
import type { TicketApi } from 'products/conversations/frontend/generated/api.schemas'
import { accountsList } from 'products/customer_analytics/frontend/generated/api'
import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'

import type { Noun } from '../../../models/groupsModel'
import type { GroupType } from '../../../types'
import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
import {
    SearchItem,
    accountToSearchItem,
    fileSystemEntryToSearchItem,
    filterNewItems,
    groupToSearchItem,
    personToSearchItem,
    ticketToSearchItem,
    unifiedSearchResultToSearchItem,
} from './searchItems'
import { searchListsLogic } from './searchListsLogic'
import { SEARCH_TAB_CATEGORY, filterSearchItems, shouldSearchTickets } from './utils'

export interface SearchCategory {
    key: string
    items: SearchItem[]
    isLoading: boolean
}

export interface SearchLogicProps {
    logicKey: string
}

export const RECENTS_LIMIT = 5
const SEARCH_LIMIT = 5

/**
 * Re-throw a search error, first handing a run we aborted over to whatever superseded it. A
 * superseded run must not settle its loader: kea-loaders keeps one loading flag per loader, so
 * clearing it here would drop the skeleton the newer run just raised. An abort with nothing behind
 * it falls through to the failure path, which stays silent: initKea's onFailure skips AbortError.
 */
const rethrowSearchError = (error: unknown, breakpoint: BreakPointFunction): never => {
    if (isAbortError(error)) {
        breakpoint()
    }
    throw error
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface searchLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
    groupTypes: Map<GroupTypeIndex, GroupType> // groupsModel
    shortcutDataHasLoaded: boolean // projectTreeDataLogic
    cachedRecents: FileSystemEntry[] // recentItemsModel
    recentsHasLoaded: boolean // recentItemsModel
    sceneLogViewsHasLoaded: boolean // recentItemsModel
    actionItems: SearchItem[] // searchListsLogic
    dataManagementItems: SearchItem[] // searchListsLogic
    healthItems: SearchItem[] // searchListsLogic
    newItems: SearchItem[] // searchListsLogic
    peopleItems: SearchItem[] // searchListsLogic
    productsItems: SearchItem[] // searchListsLogic
    settingsItems: SearchItem[] // searchListsLogic
    starredItems: SearchItem[] // searchListsLogic
    shortcutItems: SearchItem[] // shortcutLogic
    currentTeamId: number | null // teamLogic
    accountItems: SearchItem[]
    accountSearchResults: AccountApi[]
    accountSearchResultsLoading: boolean
    allCategories: SearchCategory[]
    customerItems: {
        accountItems: SearchItem[]
        ticketItems: SearchItem[]
    }
    groupItems: SearchItem[]
    groupSearchResults: Partial<Record<GroupTypeIndex, GroupQueryResult[]>>
    groupSearchResultsLoading: boolean
    isSearching: boolean
    loadingStates: {
        accountSearchResultsLoading: boolean
        groupSearchResultsLoading: boolean
        isProductsLoading: boolean
        personSearchResultsLoading: boolean
        playlistSearchResultsLoading: boolean
        recentsHasLoaded: boolean
        recentsLoading: boolean
        starredHasLoaded: boolean
        starredLoading: boolean
        ticketSearchResultsLoading: boolean
        unifiedSearchResultsLoading: boolean
    }
    personItems: SearchItem[]
    personSearchResults: PersonType[]
    personSearchResultsLoading: boolean
    playlistItems: SearchItem[]
    playlistSearchResults: FileSystemEntry[]
    playlistSearchResultsLoading: boolean
    recentItems: SearchItem[]
    search: string
    searchPending: boolean
    searchedRecents: FileSystemEntry[] | null
    searchedRecentsLoading: boolean
    shortcutAndActionItems: SearchItem[]
    ticketItems: SearchItem[]
    ticketSearchResults: TicketApi[]
    ticketSearchResultsLoading: boolean
    unifiedSearchItems: Record<string, SearchItem[]>
    unifiedSearchResults: SearchResponse | null
    unifiedSearchResultsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface searchLogicActions {
    loadAccountSearchResults: ({ searchTerm }: { searchTerm: string }) => {
        searchTerm: string
    }
    loadAccountSearchResultsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAccountSearchResultsSuccess: (
        accountSearchResults: AccountApi[],
        payload?: {
            searchTerm: string
        }
    ) => {
        accountSearchResults: AccountApi[]
        payload?: {
            searchTerm: string
        }
    }
    loadGroupSearchResults: ({ searchTerm }: { searchTerm: string }) => {
        searchTerm: string
    }
    loadGroupSearchResultsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadGroupSearchResultsSuccess: (
        groupSearchResults: Partial<Record<GroupTypeIndex, GroupQueryResult[]>>,
        payload?: {
            searchTerm: string
        }
    ) => {
        groupSearchResults: Partial<Record<GroupTypeIndex, GroupQueryResult[]>>
        payload?: {
            searchTerm: string
        }
    }
    loadPersonSearchResults: ({ searchTerm }: { searchTerm: string }) => {
        searchTerm: string
    }
    loadPersonSearchResultsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPersonSearchResultsSuccess: (
        personSearchResults: PersonType[],
        payload?: {
            searchTerm: string
        }
    ) => {
        personSearchResults: PersonType[]
        payload?: {
            searchTerm: string
        }
    }
    loadPlaylistSearchResults: ({ searchTerm }: { searchTerm: string }) => {
        searchTerm: string
    }
    loadPlaylistSearchResultsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPlaylistSearchResultsSuccess: (
        playlistSearchResults: FileSystemEntry[],
        payload?: {
            searchTerm: string
        }
    ) => {
        playlistSearchResults: FileSystemEntry[]
        payload?: {
            searchTerm: string
        }
    }
    loadTicketSearchResults: ({ searchTerm }: { searchTerm: string }) => {
        searchTerm: string
    }
    loadTicketSearchResultsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTicketSearchResultsSuccess: (
        ticketSearchResults: TicketApi[],
        payload?: {
            searchTerm: string
        }
    ) => {
        ticketSearchResults: TicketApi[]
        payload?: {
            searchTerm: string
        }
    }
    loadUnifiedSearchResults: ({ searchTerm }: { searchTerm: string }) => {
        searchTerm: string
    }
    loadUnifiedSearchResultsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadUnifiedSearchResultsSuccess: (
        unifiedSearchResults: SearchResponse | null,
        payload?: {
            searchTerm: string
        }
    ) => {
        unifiedSearchResults: SearchResponse | null
        payload?: {
            searchTerm: string
        }
    }
    searchRecents: ({ search }: { search: string }) => {
        search: string
    }
    searchRecentsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    searchRecentsSuccess: (
        searchedRecents: FileSystemEntry[] | null,
        payload?: {
            search: string
        }
    ) => {
        searchedRecents: FileSystemEntry[] | null
        payload?: {
            search: string
        }
    }
    setSearch: (search: string) => {
        search: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface searchLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        isSearching: (
            searchedRecentsLoading: boolean,
            unifiedSearchResultsLoading: boolean,
            groupSearchResultsLoading: boolean,
            personSearchResultsLoading: boolean,
            accountSearchResultsLoading: boolean,
            ticketSearchResultsLoading: boolean,
            playlistSearchResultsLoading: boolean,
            searchPending: boolean,
            search: string
        ) => boolean
        recentItems: (
            searchedRecents: FileSystemEntry[] | null,
            cachedRecents: FileSystemEntry[],
            search: string
        ) => SearchItem[]
        groupItems: (
            groupSearchResults: Partial<Record<GroupTypeIndex, GroupQueryResult[]>>,
            aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
        ) => SearchItem[]
        personItems: (personSearchResults: PersonType[]) => SearchItem[]
        accountItems: (accountSearchResults: AccountApi[]) => SearchItem[]
        ticketItems: (ticketSearchResults: TicketApi[]) => SearchItem[]
        customerItems: (
            accountItems: SearchItem[],
            ticketItems: SearchItem[]
        ) => {
            accountItems: SearchItem[]
            ticketItems: SearchItem[]
        }
        playlistItems: (playlistSearchResults: FileSystemEntry[]) => SearchItem[]
        unifiedSearchItems: (unifiedSearchResults: SearchResponse | null) => Record<string, SearchItem[]>
        loadingStates: (
            unifiedSearchResultsLoading: boolean,
            recentsHasLoaded: boolean,
            shortcutDataHasLoaded: boolean,
            sceneLogViewsHasLoaded: boolean,
            personSearchResultsLoading: boolean,
            groupSearchResultsLoading: boolean,
            accountSearchResultsLoading: boolean,
            ticketSearchResultsLoading: boolean,
            playlistSearchResultsLoading: boolean
        ) => {
            accountSearchResultsLoading: boolean
            groupSearchResultsLoading: boolean
            isProductsLoading: boolean
            personSearchResultsLoading: boolean
            playlistSearchResultsLoading: boolean
            recentsHasLoaded: boolean
            recentsLoading: boolean
            starredHasLoaded: boolean
            starredLoading: boolean
            ticketSearchResultsLoading: boolean
            unifiedSearchResultsLoading: boolean
        }
        shortcutAndActionItems: (shortcutItems: SearchItem[], actionItems: SearchItem[]) => SearchItem[]
        allCategories: (
            recentItems: SearchItem[],
            starredItems: SearchItem[],
            productsItems: SearchItem[],
            dataManagementItems: SearchItem[],
            peopleItems: SearchItem[],
            healthItems: SearchItem[],
            shortcutAndActionItems: SearchItem[],
            settingsItems: SearchItem[],
            newItems: SearchItem[],
            personItems: SearchItem[],
            groupItems: SearchItem[],
            customerItems: {
                accountItems: SearchItem[]
                ticketItems: SearchItem[]
            },
            playlistItems: SearchItem[],
            unifiedSearchItems: Record<string, SearchItem[]>,
            loadingStates: {
                accountSearchResultsLoading: boolean
                groupSearchResultsLoading: boolean
                isProductsLoading: boolean
                personSearchResultsLoading: boolean
                playlistSearchResultsLoading: boolean
                recentsHasLoaded: boolean
                recentsLoading: boolean
                starredHasLoaded: boolean
                starredLoading: boolean
                ticketSearchResultsLoading: boolean
                unifiedSearchResultsLoading: boolean
            },
            search: string
        ) => SearchCategory[]
    }
}

export type searchLogicType = MakeLogicType<searchLogicValues, searchLogicActions, SearchLogicProps, searchLogicMeta>

export const searchLogic = kea<searchLogicType>([
    path((logicKey) => ['lib', 'components', 'Search', 'searchLogic', logicKey]),
    props({} as SearchLogicProps),
    key((props) => props.logicKey),
    connect((props: SearchLogicProps) => ({
        values: [
            searchListsLogic({ commandPalette: props.logicKey === 'command' }),
            [
                'starredItems',
                'productsItems',
                'dataManagementItems',
                'newItems',
                'peopleItems',
                'healthItems',
                'actionItems',
                'settingsItems',
            ],
            groupsModel,
            ['groupTypes', 'aggregationLabel'],
            featureFlagLogic,
            ['featureFlags'],
            teamLogic,
            ['currentTeamId'],
            recentItemsModel,
            ['recents as cachedRecents', 'recentsHasLoaded', 'sceneLogViewsHasLoaded'],
            projectTreeDataLogic,
            ['shortcutDataHasLoaded'],
            shortcutLogic,
            ['shortcutItems'],
        ],
    })),
    actions({
        setSearch: (search: string) => ({ search }),
    }),
    loaders(({ values, cache }) => ({
        searchedRecents: [
            null as FileSystemEntry[] | null,
            {
                searchRecents: async ({ search }: { search: string }, breakpoint) => {
                    const searchTerm = search.trim()
                    if (!searchTerm) {
                        return null
                    }
                    try {
                        const response = await api.fileSystem.list({
                            search: searchTerm,
                            limit: RECENTS_LIMIT + 1,
                            orderBy: '-last_viewed_at',
                            notType: 'folder',
                            signal: cache.searchAbortController?.signal,
                        })
                        breakpoint()
                        return response.results
                            .filter((entry) => isFileSystemEntryTypeEnabled(entry, values.featureFlags))
                            .slice(0, RECENTS_LIMIT)
                    } catch (error) {
                        return rethrowSearchError(error, breakpoint)
                    }
                },
            },
        ],
        unifiedSearchResults: [
            null as SearchResponse | null,
            {
                loadUnifiedSearchResults: async ({ searchTerm }: { searchTerm: string }, breakpoint) => {
                    const trimmed = searchTerm.trim()

                    if (trimmed === '') {
                        return null
                    }

                    try {
                        const response = await api.search.list(
                            {
                                q: trimmed,
                                include_counts: false,
                            },
                            { signal: cache.searchAbortController?.signal }
                        )
                        breakpoint()

                        return response
                    } catch (error) {
                        return rethrowSearchError(error, breakpoint)
                    }
                },
            },
        ],
        groupSearchResults: [
            {} as Partial<Record<GroupTypeIndex, GroupQueryResult[]>>,
            {
                loadGroupSearchResults: async ({ searchTerm }: { searchTerm: string }, breakpoint) => {
                    const trimmed = searchTerm.trim()

                    if (trimmed === '') {
                        return {}
                    }

                    const groupTypesList = Array.from(values.groupTypes.values())
                    if (groupTypesList.length === 0) {
                        return {}
                    }

                    const results = await Promise.allSettled(
                        groupTypesList.map((groupType) =>
                            api.groups.listClickhouse(
                                {
                                    group_type_index: groupType.group_type_index,
                                    search: trimmed,
                                    limit: SEARCH_LIMIT,
                                },
                                { signal: cache.searchAbortController?.signal }
                            )
                        )
                    )

                    // allSettled never rejects, so an abort lands here instead of in a catch: the
                    // breakpoint hands a superseded run over, and the filter below drops the rest.
                    breakpoint()

                    return Object.fromEntries(
                        results
                            .map((result, index) => [groupTypesList[index], result] as const)
                            .filter(([, result]) => result.status === 'fulfilled')
                            .map(([groupType, result]) => [
                                groupType.group_type_index,
                                mapGroupQueryResponse((result as PromiseFulfilledResult<GroupsQueryResponse>).value),
                            ])
                    ) as Record<GroupTypeIndex, GroupQueryResult[]>
                },
            },
        ],
        personSearchResults: [
            [] as PersonType[],
            {
                loadPersonSearchResults: async ({ searchTerm }: { searchTerm: string }, breakpoint) => {
                    const trimmed = searchTerm.trim()

                    if (trimmed === '') {
                        return []
                    }

                    const clientQueryId: string | null = cache.personSearchQueryId
                    try {
                        const response = await api.persons.list(
                            { search: trimmed, limit: SEARCH_LIMIT, client_query_id: clientQueryId ?? undefined },
                            { signal: cache.searchAbortController?.signal }
                        )
                        breakpoint()

                        return response.results
                    } catch (error) {
                        return rethrowSearchError(error, breakpoint)
                    } finally {
                        // The request is over, so there is no ClickHouse query left to cancel.
                        if (cache.personSearchQueryId === clientQueryId) {
                            cache.personSearchQueryId = null
                        }
                    }
                },
            },
        ],
        accountSearchResults: [
            [] as AccountApi[],
            {
                loadAccountSearchResults: async ({ searchTerm }: { searchTerm: string }, breakpoint) => {
                    const trimmed = searchTerm.trim()

                    if (trimmed === '' || !values.currentTeamId) {
                        return []
                    }

                    try {
                        const response = await accountsList(
                            String(values.currentTeamId),
                            {
                                search: trimmed,
                                limit: SEARCH_LIMIT,
                                include_churned: true,
                                include_ignored: true,
                                inactive_last: true,
                            },
                            { signal: cache.searchAbortController?.signal }
                        )
                        breakpoint()

                        return response.results
                    } catch (error) {
                        return rethrowSearchError(error, breakpoint)
                    }
                },
            },
        ],
        // Support tickets come from the Conversations list endpoint rather than the unified
        // search API: that endpoint already resolves a bare number to one ticket and matches the
        // customer's name and email, the subject, and message content, none of which the
        // full-text `ENTITY_MAP` entry over ticket columns would cover. It answers newest-active
        // first (`-updated_at`), which is the order a support lookup wants.
        ticketSearchResults: [
            [] as TicketApi[],
            {
                loadTicketSearchResults: async ({ searchTerm }: { searchTerm: string }, breakpoint) => {
                    const trimmed = searchTerm.trim()

                    // Returning early also clears the rows a longer query left behind, so a query
                    // too short to search never shows results that no longer match what is typed.
                    if (!shouldSearchTickets(trimmed) || !values.currentTeamId) {
                        return []
                    }

                    try {
                        const response = await conversationsTicketsList(
                            String(values.currentTeamId),
                            {
                                search: trimmed,
                                limit: SEARCH_LIMIT,
                            },
                            { signal: cache.searchAbortController?.signal }
                        )
                        breakpoint()

                        return response.results
                    } catch (error) {
                        return rethrowSearchError(error, breakpoint)
                    }
                },
            },
        ],
        playlistSearchResults: [
            [] as FileSystemEntry[],
            {
                loadPlaylistSearchResults: async ({ searchTerm }: { searchTerm: string }, breakpoint) => {
                    const trimmed = searchTerm.trim()

                    if (trimmed === '') {
                        return []
                    }

                    try {
                        const response = await api.fileSystem.list({
                            search: trimmed,
                            type: 'session_recording_playlist',
                            limit: SEARCH_LIMIT,
                            signal: cache.searchAbortController?.signal,
                        })
                        breakpoint()

                        return response.results
                    } catch (error) {
                        return rethrowSearchError(error, breakpoint)
                    }
                },
            },
        ],
    })),
    reducers({
        search: [
            '',
            {
                setSearch: (_, { search }) => search,
            },
        ],
        searchPending: [
            false,
            {
                setSearch: (_, { search }) => search.trim() !== '',
                loadUnifiedSearchResultsSuccess: () => false,
                loadUnifiedSearchResultsFailure: () => false,
            },
        ],
    }),
    selectors({
        isSearching: [
            (s) => [
                s.searchedRecentsLoading,
                s.unifiedSearchResultsLoading,
                s.groupSearchResultsLoading,
                s.personSearchResultsLoading,
                s.accountSearchResultsLoading,
                s.ticketSearchResultsLoading,
                s.playlistSearchResultsLoading,
                s.searchPending,
                s.search,
            ],
            (
                searchedRecentsLoading: boolean,
                unifiedSearchResultsLoading: boolean,
                groupSearchResultsLoading: boolean,
                personSearchResultsLoading: boolean,
                accountSearchResultsLoading: boolean,
                ticketSearchResultsLoading: boolean,
                playlistSearchResultsLoading: boolean,
                searchPending: boolean,
                search: string
            ): boolean =>
                (searchedRecentsLoading ||
                    unifiedSearchResultsLoading ||
                    groupSearchResultsLoading ||
                    personSearchResultsLoading ||
                    accountSearchResultsLoading ||
                    ticketSearchResultsLoading ||
                    playlistSearchResultsLoading ||
                    searchPending) &&
                search.trim() !== '',
        ],
        recentItems: [
            (s) => [s.searchedRecents, s.cachedRecents, s.search],
            (
                searchedRecents: FileSystemEntry[] | null,
                cachedRecents: FileSystemEntry[],
                search: string
            ): SearchItem[] => {
                const source = search.trim() ? (searchedRecents ?? []) : cachedRecents.slice(0, RECENTS_LIMIT)
                return source.map((item) => fileSystemEntryToSearchItem(item, { id: item.path, category: 'recents' }))
            },
        ],
        groupItems: [
            (s) => [s.groupSearchResults, s.aggregationLabel],
            (
                groupSearchResults: Partial<Record<GroupTypeIndex, GroupQueryResult[]>>,
                aggregationLabel: (
                    groupTypeIndex: number | null | undefined,
                    deferToUserWording?: boolean
                ) => import('~/models/groupsModel').Noun
            ): SearchItem[] => {
                const items: SearchItem[] = []
                for (const [groupTypeIndexString, groups] of Object.entries(groupSearchResults)) {
                    const groupTypeIndex = parseInt(groupTypeIndexString, 10) as GroupTypeIndex
                    const noun = aggregationLabel(groupTypeIndex).singular
                    for (const group of groups as GroupQueryResult[]) {
                        items.push(groupToSearchItem(group, groupTypeIndex, noun))
                    }
                }
                return items
            },
        ],
        personItems: [
            (s) => [s.personSearchResults],
            (personSearchResults: PersonType[]): SearchItem[] => {
                return personSearchResults
                    .filter((person): person is PersonType & { uuid: string } => !!person.uuid) // Skip persons without uuid to avoid invalid URLs
                    .map(personToSearchItem)
            },
        ],
        accountItems: [
            (s) => [s.accountSearchResults],
            (accountSearchResults: AccountApi[]): SearchItem[] => accountSearchResults.map(accountToSearchItem),
        ],
        ticketItems: [
            (s) => [s.ticketSearchResults],
            (ticketSearchResults: TicketApi[]): SearchItem[] => ticketSearchResults.map(ticketToSearchItem),
        ],
        // Accounts and support tickets, handed to allCategories as one value. kea types a
        // selector's dependency list up to 16 entries and allCategories sits on that limit, so the
        // two customer-scoped lists ride in together rather than one of them being dropped.
        customerItems: [
            (s) => [s.accountItems, s.ticketItems],
            (
                accountItems: SearchItem[],
                ticketItems: SearchItem[]
            ): { accountItems: SearchItem[]; ticketItems: SearchItem[] } => ({ accountItems, ticketItems }),
        ],
        playlistItems: [
            (s) => [s.playlistSearchResults],
            (playlistSearchResults: FileSystemEntry[]): SearchItem[] => {
                return playlistSearchResults.map((item) => {
                    const name = splitPath(item.path).pop()
                    return {
                        id: `playlist-${item.id}`,
                        name: name ? unescapePath(name) : item.path,
                        category: 'session_recording_playlist',
                        href: item.href || PLACEHOLDER_HREF,
                        itemType: 'session_recording_playlist',
                        disabledReason: getEntryAccessDisabledReason(item),
                        record: item as unknown as Record<string, unknown>,
                    }
                })
            },
        ],
        unifiedSearchItems: [
            (s) => [s.unifiedSearchResults],
            (unifiedSearchResults: SearchResponse | null): Record<string, SearchItem[]> => {
                if (!unifiedSearchResults) {
                    return {}
                }

                const categoryItems: Record<string, SearchItem[]> = {}

                for (const result of unifiedSearchResults.results) {
                    const category = result.type
                    if (!categoryItems[category]) {
                        categoryItems[category] = []
                    }
                    categoryItems[category].push(unifiedSearchResultToSearchItem(result))
                }

                return categoryItems
            },
        ],
        loadingStates: [
            (s) => [
                s.unifiedSearchResultsLoading,
                s.recentsHasLoaded,
                s.shortcutDataHasLoaded,
                s.sceneLogViewsHasLoaded,
                s.personSearchResultsLoading,
                s.groupSearchResultsLoading,
                s.accountSearchResultsLoading,
                s.ticketSearchResultsLoading,
                s.playlistSearchResultsLoading,
            ],
            (
                unifiedSearchResultsLoading: boolean,
                recentsHasLoaded: boolean,
                shortcutDataHasLoaded: boolean,
                sceneLogViewsHasLoaded: boolean,
                personSearchResultsLoading: boolean,
                groupSearchResultsLoading: boolean,
                accountSearchResultsLoading: boolean,
                ticketSearchResultsLoading: boolean,
                playlistSearchResultsLoading: boolean
            ) => ({
                unifiedSearchResultsLoading,
                recentsLoading: !recentsHasLoaded,
                recentsHasLoaded,
                starredLoading: !shortcutDataHasLoaded,
                starredHasLoaded: shortcutDataHasLoaded,
                isProductsLoading: !sceneLogViewsHasLoaded,
                personSearchResultsLoading,
                groupSearchResultsLoading,
                accountSearchResultsLoading,
                ticketSearchResultsLoading,
                playlistSearchResultsLoading,
            }),
        ],
        shortcutAndActionItems: [
            (s) => [s.shortcutItems, s.actionItems],
            (shortcutItems: SearchItem[], actionItems: SearchItem[]): SearchItem[] => [
                ...shortcutItems,
                ...actionItems,
            ],
        ],
        allCategories: [
            (s) => [
                s.recentItems,
                s.starredItems,
                s.productsItems,
                s.dataManagementItems,
                s.peopleItems,
                s.healthItems,
                s.shortcutAndActionItems,
                s.settingsItems,
                s.newItems,
                s.personItems,
                s.groupItems,
                s.customerItems,
                s.playlistItems,
                s.unifiedSearchItems,
                s.loadingStates,
                s.search,
            ],
            (
                recentItems: SearchItem[],
                starredItems: SearchItem[],
                productsItems: SearchItem[],
                dataManagementItems: SearchItem[],
                peopleItems: SearchItem[],
                healthItems: SearchItem[],
                shortcutAndActionItems: SearchItem[],
                settingsItems: SearchItem[],
                newItems: SearchItem[],
                personItems: SearchItem[],
                groupItems: SearchItem[],
                customerItems: { accountItems: SearchItem[]; ticketItems: SearchItem[] },
                playlistItems: SearchItem[],
                unifiedSearchItems: Record<string, SearchItem[]>,
                loadingStates: {
                    unifiedSearchResultsLoading: boolean
                    recentsLoading: boolean
                    recentsHasLoaded: boolean
                    starredLoading: boolean
                    starredHasLoaded: boolean
                    isProductsLoading: boolean
                    personSearchResultsLoading: boolean
                    groupSearchResultsLoading: boolean
                    accountSearchResultsLoading: boolean
                    ticketSearchResultsLoading: boolean
                    playlistSearchResultsLoading: boolean
                },
                search: string
            ): SearchCategory[] => {
                const {
                    unifiedSearchResultsLoading,
                    recentsLoading,
                    recentsHasLoaded,
                    starredLoading,
                    starredHasLoaded,
                    isProductsLoading,
                    personSearchResultsLoading,
                    groupSearchResultsLoading,
                    accountSearchResultsLoading,
                    ticketSearchResultsLoading,
                    playlistSearchResultsLoading,
                } = loadingStates

                const { accountItems, ticketItems } = customerItems

                const categories: SearchCategory[] = []
                const hasSearch = search.trim() !== ''

                // Filter items by search term using Fuse.js fuzzy search
                const filterBySearch = (items: SearchItem[]): SearchItem[] => {
                    if (!hasSearch) {
                        return items
                    }
                    return filterSearchItems(items, search)
                }

                // Always show recents first - show loading skeleton until first load completes
                const isRecentsLoading = recentsLoading || !recentsHasLoaded
                categories.push({
                    key: 'recents',
                    items: recentItems,
                    isLoading: isRecentsLoading,
                })

                const isStarredLoading = starredLoading || !starredHasLoaded
                categories.push({
                    key: 'starred',
                    items: starredItems,
                    isLoading: isStarredLoading,
                })

                // Filter products and data management by search
                const isSearchTab = (item: SearchItem): boolean => item.category === SEARCH_TAB_CATEGORY
                const withoutSearchTabs = (items: SearchItem[]): SearchItem[] =>
                    items.filter((item) => !isSearchTab(item))
                const filteredProducts = filterBySearch(withoutSearchTabs(productsItems))
                const filteredDataManagement = filterBySearch(withoutSearchTabs(dataManagementItems))

                // Show products if not searching or has matching results
                if (!hasSearch || filteredProducts.length > 0) {
                    categories.push({
                        key: 'tools',
                        items: isProductsLoading ? [] : filteredProducts,
                        isLoading: isProductsLoading,
                    })
                }

                // Show data management if not searching or has matching results
                if (!hasSearch || filteredDataManagement.length > 0) {
                    categories.push({
                        key: 'data-management',
                        items: isProductsLoading ? [] : filteredDataManagement,
                        isLoading: isProductsLoading,
                    })
                }

                // Show people items (persons, cohorts, group types) if searching with matching results
                const filteredPeople = filterBySearch(peopleItems)
                if (hasSearch && filteredPeople.length > 0) {
                    categories.push({
                        key: 'people',
                        items: filteredPeople,
                        isLoading: false,
                    })
                }

                const filteredSearchTabs = filterBySearch(
                    [...productsItems, ...dataManagementItems].filter(isSearchTab)
                )
                if (hasSearch && filteredSearchTabs.length > 0) {
                    categories.push({
                        key: SEARCH_TAB_CATEGORY,
                        items: isProductsLoading ? [] : filteredSearchTabs,
                        isLoading: isProductsLoading,
                    })
                }

                // Show health items if searching with matching results
                const filteredHealth = filterBySearch(healthItems)
                if (hasSearch && filteredHealth.length > 0) {
                    categories.push({
                        key: 'health',
                        items: filteredHealth,
                        isLoading: false,
                    })
                }

                // Show action items if searching with matching results
                const filteredActions = filterBySearch(
                    shortcutAndActionItems.filter((item) => item.category === 'actions')
                )
                if (hasSearch && filteredActions.length > 0) {
                    categories.push({
                        key: 'actions',
                        items: filteredActions,
                        isLoading: false,
                    })
                }

                // Filter and show settings if searching with matching results
                const filteredSettings = filterBySearch(settingsItems)
                if (hasSearch && filteredSettings.length > 0) {
                    categories.push({
                        key: 'settings',
                        items: filteredSettings,
                        isLoading: false,
                    })
                }

                // Show "create" category only when searching and matching "new" or relevant keywords
                if (hasSearch) {
                    const filteredNewItems = filterNewItems(newItems, search)

                    if (filteredNewItems.length > 0) {
                        categories.push({
                            key: 'create',
                            items: filteredNewItems,
                            isLoading: false,
                        })
                    }
                }

                // Only show unified search results when searching
                if (hasSearch) {
                    const unifiedLoading = unifiedSearchResultsLoading

                    // Add unified search categories
                    const categoryOrder = [
                        'insight',
                        'dashboard',
                        'data_warehouse_view',
                        'endpoint',
                        'feature_flag',
                        'experiment',
                        'early_access_feature',
                        'survey',
                        'notebook',
                        'cohort',
                        'action',
                        'event_definition',
                        'property_definition',
                        'hog_flow',
                    ]

                    for (const category of categoryOrder) {
                        const items = unifiedSearchItems[category] || []
                        if (items.length > 0 || unifiedLoading) {
                            categories.push({
                                key: category,
                                items,
                                isLoading: unifiedLoading && items.length === 0,
                            })
                        }
                    }

                    // Add session recording playlists
                    if (playlistItems.length > 0 || playlistSearchResultsLoading) {
                        categories.push({
                            key: 'session_recording_playlist',
                            items: playlistItems,
                            isLoading: playlistSearchResultsLoading,
                        })
                    }

                    // Add accounts
                    if (accountItems.length > 0 || accountSearchResultsLoading) {
                        categories.push({
                            key: 'accounts',
                            items: accountItems,
                            isLoading: accountSearchResultsLoading,
                        })
                    }

                    // Add support tickets
                    if (ticketItems.length > 0 || ticketSearchResultsLoading) {
                        categories.push({
                            key: 'tickets',
                            items: ticketItems,
                            isLoading: ticketSearchResultsLoading,
                        })
                    }

                    // Add persons
                    if (personItems.length > 0 || personSearchResultsLoading) {
                        categories.push({
                            key: 'persons',
                            items: personItems,
                            isLoading: personSearchResultsLoading,
                        })
                    }

                    // Add groups
                    if (groupItems.length > 0 || groupSearchResultsLoading) {
                        categories.push({
                            key: 'groups',
                            items: groupItems,
                            isLoading: groupSearchResultsLoading,
                        })
                    }
                }

                const filteredShortcuts = filterBySearch(
                    shortcutAndActionItems.filter((item) => item.category === 'shortcuts')
                )
                if (filteredShortcuts.length > 0) {
                    categories.push({
                        key: 'shortcuts',
                        items: filteredShortcuts,
                        isLoading: false,
                    })
                }

                return categories
            },
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        setSearch: async ({ search }, breakpoint) => {
            if (search.trim() === '') {
                // An empty term means the palette closed or the box was cleared, so no later run
                // will replace what is in flight. Stop it now, because a person search can run for
                // a minute and nobody is waiting on the answer.
                cache.disposables.dispose('searchAbortController')
                return
            }

            await breakpoint(150)

            // Registering under the same key aborts the previous term's requests. The new ones go
            // out in the same tick, so each superseded run sees its replacement when it wakes up.
            cache.disposables.add(
                () => {
                    const controller = new AbortController()
                    const clientQueryId = uuid()
                    cache.searchAbortController = controller
                    cache.personSearchQueryId = clientQueryId
                    return () => {
                        const personSearchRunning = cache.personSearchQueryId === clientQueryId
                        cache.searchAbortController = null
                        cache.personSearchQueryId = null
                        controller.abort()
                        if (personSearchRunning) {
                            // Dropping the request does not reach ClickHouse, so the person search
                            // would keep scanning and holding a query slot. Kill it by name.
                            api.cancelQuery(clientQueryId).catch((error) =>
                                console.warn('Failed cancelling person search', error)
                            )
                        }
                    }
                },
                'searchAbortController',
                // This controller belongs to one set of requests. Hiding the tab must not abort
                // them, or showing it again would arm a fresh controller over nothing.
                { pauseOnPageHidden: false }
            )

            actions.searchRecents({ search })
            actions.loadUnifiedSearchResults({ searchTerm: search })
            actions.loadPersonSearchResults({ searchTerm: search })
            actions.loadGroupSearchResults({ searchTerm: search })
            if (values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {
                actions.loadAccountSearchResults({ searchTerm: search })
            }
            actions.loadTicketSearchResults({ searchTerm: search })
            actions.loadPlaylistSearchResults({ searchTerm: search })
        },
    })),
])