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.9 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    beforeUnmount,
    connect,
    kea,
    listeners,
    path,
    reducers,
    selectors,
} from 'kea'
import { router } from 'kea-router'

import api from 'lib/api'
import { commandLogic } from 'lib/components/Command/commandLogic'
import { SearchItem, fileSystemEntryToSearchItem } from 'lib/components/Search/searchItems'
import { searchListsLogic } from 'lib/components/Search/searchListsLogic'
import { canOpenInNewTab } from 'lib/components/Search/utils'
import { shortcutLogic } from 'lib/components/Shortcuts/shortcutLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { themeLogic } from 'lib/logic/themeLogic'
import posthog from 'lib/posthog-typed'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { navigateToHref } from 'lib/utils/navigateToHref'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'

import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'
import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { groupsModel } from '~/models/groupsModel'
import { membersLogic } from '~/models/membersLogic'
import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'
import { SidePanelTab } from '~/types'

import type { Noun } from '../../../models/groupsModel'
import type { GroupType, GroupTypeIndex, OrganizationMemberType, UserType } from '../../../types'
import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
import type { CommandOpenSource } from '../Command/commandLogic'
import { askAiQuestionFor } from './commandKAskAi'
import { SearchCorrection, correctedSearch } from './commandKCorrection'
import { buildFilterOptions, viewAllFor } from './commandKFilterOptions'
import { ChipSelection, KeyIntent } from './commandKKeys'
import {
    CursorContext,
    FilterDefinition,
    FilterOptions,
    QueryChip,
    QueryToken,
    ResolvedQuery,
    addChip,
    chipCommittedByEdit,
    chipToText,
    extractChips,
    getCursorContext,
    isRedundantSpace,
    queryAsText,
    removeToken,
    replaceToken,
    resolveQuery,
    tokenAtCursor,
} from './commandKQuery'
import {
    CommandKMode,
    CommandKRow,
    CommandKSection,
    LocalLists,
    RECENTS_LIMIT,
    RemoteSlots,
    SectionsQuery,
    ViewAll,
    buildSections,
    buildSuggestions,
    emptyRemoteSlots,
    isSelectable,
    pickDisplayedQuery,
    resultsSettled,
    themeSearchItem,
} from './commandKSections'
import {
    REMOTE_REQUESTS,
    RemoteContext,
    RemoteResults,
    RemoteSource,
    requestDebounceMs,
    settleRequest,
} from './commandKSources'

const INPUT_HIGHLIGHT_KEY = 'input'

export type CommitVia = 'tab' | 'enter' | 'space' | 'paste' | 'click' | 'typed' | 'see-all'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface commandKSearchLogicValues {
    openSource: CommandOpenSource | null // commandLogic
    pendingText: string // commandLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
    groupTypes: Map<GroupTypeIndex, GroupType> // groupsModel
    meFirstMembers: OrganizationMemberType[] // membersLogic
    members: OrganizationMemberType[] | null // membersLogic
    recents: FileSystemEntry[] // 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
    isDarkModeOn: boolean // themeLogic
    user: UserType | null // userLogic
    askAiQuestion: string | null
    chipSelection: ChipSelection
    chips: QueryChip[]
    currentQuery: SectionsQuery
    cursor: number
    cursorContext: CursorContext
    displayedQuery: {
        query: SectionsQuery
        stale: boolean
    }
    expandedGroups: string[]
    filterOptions: FilterOptions
    folders: FileSystemEntry[] | null
    highlightIsFilterRow: boolean
    highlightedKey: string | null
    highlightedRow: CommandKRow | null
    isPaletteEmpty: boolean
    localLists: LocalLists
    localQuery: string
    mode: CommandKMode
    recentItems: SearchItem[]
    remote: RemoteSlots
    remoteContext: RemoteContext
    remoteQueries: Partial<Record<RemoteSource, string>>
    requestQueries: Record<string, string>
    requestedQueries: Record<string, string>
    resolvedQuery: ResolvedQuery
    resultOpened: boolean
    searchCorrection: SearchCorrection | null
    sections: CommandKSection[]
    selectableRows: CommandKRow[]
    shownQuery: SectionsQuery | null
    suggestionsSection: CommandKSection | null
    tabAsksAi: boolean
    text: string
    themeItem: SearchItem | null
    viewAll: ViewAll | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface commandKSearchLogicActions {
    closeCommand: () => {
        value: true
    } // commandLogic
    commandInputReady: () => {
        value: true
    } // commandLogic
    ensureAllMembersLoaded: () => {
        value: true
    } // membersLogic
    clearActiveCreation: () => {
        value: true
    } // runnerPanelLogic
    setHistoryExpanded: (expanded: boolean) => {
        expanded: boolean
    } // runnerPanelLogic
    openSidePanel: (
        tab: SidePanelTab,
        options?: string | undefined
    ) => {
        options: string | undefined
        tab: SidePanelTab
    } // sidePanelStateLogic
    loadCurrentTeamSuccess: (
        currentTeam: null | import('~/types').TeamPublicType,
        payload?: any
    ) => {
        currentTeam: null | import('~/types').TeamPublicType
        payload?: any
    } // teamLogic
    activateRow: (
        row: CommandKRow,
        newTab: boolean,
        via: CommitVia
    ) => {
        newTab: boolean
        row: CommandKRow
        via: CommitVia
    }
    applyCorrection: (correction: SearchCorrection) => {
        correction: SearchCorrection
    }
    applyKeyIntent: (intent: KeyIntent) => {
        intent: KeyIntent
    }
    askAi: () => {
        value: true
    }
    clearQuery: () => {
        value: true
    }
    commitChip: (
        chip: QueryChip,
        token: QueryToken | null,
        via: CommitVia
    ) => {
        chip: QueryChip
        token: QueryToken | null
        via: CommitVia
    }
    completeFilterKey: (
        filter: FilterDefinition,
        negated: boolean
    ) => {
        filter: FilterDefinition
        negated: boolean
    }
    completeHighlighted: () => {
        value: true
    }
    editChip: (index: number) => {
        index: number
    }
    expandGroup: (group: string) => {
        group: string
    }
    foldersLoaded: (folders: FileSystemEntry[]) => {
        folders: FileSystemEntry[]
    }
    inputChanged: (
        text: string,
        cursor: number,
        pasted: boolean
    ) => {
        cursor: number
        pasted: boolean
        text: string
    }
    loadFolders: () => {
        value: true
    }
    markResultOpened: () => {
        value: true
    }
    moveHighlight: (direction: 1 | -1) => {
        direction: 1 | -1
    }
    remoteLoaded: (
        query: string,
        results: RemoteResults,
        failed?: boolean
    ) => {
        failed: boolean
        query: string
        results: Partial<
            Record<
                'accounts' | 'events' | 'groups' | 'persons' | 'properties' | 'results' | 'tickets' | 'workflows',
                SearchItem[]
            >
        >
    }
    requestsStarted: (queries: Record<string, string>) => {
        queries: Record<string, string>
    }
    selectChip: (index: ChipSelection) => {
        index: ChipSelection
    }
    setChipsAndText: (
        chips: QueryChip[],
        text: string,
        cursor: number
    ) => {
        chips: QueryChip[]
        cursor: number
        text: string
    }
    setCursor: (cursor: number) => {
        cursor: number
    }
    setHighlightedKey: (key: string | null) => {
        key: string | null
    }
    showQuery: (query: SectionsQuery) => {
        query: SectionsQuery
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface commandKSearchLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        filterOptions: (
            meFirstMembers: OrganizationMemberType[],
            user: UserType | null,
            folders: FileSystemEntry[] | null
        ) => FilterOptions
        cursorContext: (text: string, cursor: number, chips: QueryChip[]) => CursorContext
        mode: (cursorContext: CursorContext) => CommandKMode
        resolvedQuery: (text: string, chips: QueryChip[], filterOptions: FilterOptions) => ResolvedQuery
        localQuery: (
            resolvedQuery: ResolvedQuery,
            mode: CommandKMode,
            searchCorrection: SearchCorrection | null
        ) => string
        askAiQuestion: (text: string, resolvedQuery: ResolvedQuery) => string | null
        remoteContext: (
            currentTeamId: number | null,
            groupTypes: Map<GroupTypeIndex, GroupType>,
            aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun, // groupsModel
            featureFlags: FeatureFlagsSet
        ) => RemoteContext
        requestQueries: (
            resolvedQuery: ResolvedQuery,
            localQuery: string,
            mode: CommandKMode,
            remoteContext: RemoteContext,
            searchCorrection: SearchCorrection | null
        ) => Record<string, string>
        remoteQueries: (requestQueries: Record<string, string>) => Partial<Record<RemoteSource, string>>
        suggestionsSection: (
            cursorContext: CursorContext,
            filterOptions: FilterOptions,
            members: OrganizationMemberType[] | null,
            folders: FileSystemEntry[] | null
        ) => CommandKSection | null
        recentItems: (recents: FileSystemEntry[]) => SearchItem[]
        localLists: (
            recentItems: SearchItem[],
            starredItems: SearchItem[],
            shortcutItems: SearchItem[],
            productsItems: SearchItem[],
            settingsItems: SearchItem[],
            newItems: SearchItem[],
            dataManagementItems: SearchItem[],
            peopleItems: SearchItem[],
            healthItems: SearchItem[],
            actionItems: SearchItem[]
        ) => LocalLists
        themeItem: (localQuery: string, isDarkModeOn: boolean) => SearchItem | null
        viewAll: (resolvedQuery: ResolvedQuery) => ViewAll | null
        currentQuery: (
            remoteQueries: Partial<
                Record<
                    'accounts' | 'events' | 'groups' | 'persons' | 'properties' | 'results' | 'tickets' | 'workflows',
                    string
                >
            >,
            localQuery: string,
            themeItem: SearchItem | null,
            askAiQuestion: string | null,
            viewAll: ViewAll | null
        ) => SectionsQuery
        displayedQuery: (
            currentQuery: SectionsQuery,
            shownQuery: SectionsQuery | null,
            remote: RemoteSlots
        ) => {
            query: SectionsQuery
            stale: boolean
        }
        sections: (
            mode: CommandKMode,
            cursorContext: CursorContext,
            suggestionsSection: CommandKSection | null,
            localLists: LocalLists,
            remote: RemoteSlots,
            displayedQuery: {
                query: SectionsQuery
                stale: boolean
            },
            searchCorrection: SearchCorrection | null,
            expandedGroups: string[]
        ) => CommandKSection[]
        selectableRows: (sections: CommandKSection[]) => CommandKRow[]
        highlightedRow: (selectableRows: CommandKRow[], highlightedKey: string | null) => CommandKRow | null
        highlightIsFilterRow: (highlightedRow: CommandKRow | null) => boolean
        tabAsksAi: (highlightIsFilterRow: boolean, askAiQuestion: string | null) => boolean
        isPaletteEmpty: (text: string, chips: QueryChip[]) => boolean
    }
}

export type commandKSearchLogicType = MakeLogicType<
    commandKSearchLogicValues,
    commandKSearchLogicActions,
    Record<string, any>,
    commandKSearchLogicMeta
>

const asLiteralPanelPrompt = (question: string): string => ` ${question}`

/**
 * Command K search: parses the input into filters and free text, builds the sections, owns the
 * highlight, and loads remote results. It mounts with the palette and unmounts when the palette
 * closes, which is what scopes every cache and in-flight request to one use of the palette.
 */
const scrollToAnchorOnCurrentPage = (href: string): void => {
    const [path, anchor] = href.split('#')
    const { pathname, hash } = router.values.location
    if (anchor && hash === `#${anchor}` && removeProjectIdIfPresent(pathname) === removeProjectIdIfPresent(path)) {
        document.getElementById(anchor)?.scrollIntoView()
    }
}

export const commandKSearchLogic = kea<commandKSearchLogicType>([
    path(['lib', 'components', 'CommandKSearch', 'commandKSearchLogic']),
    connect(() => ({
        values: [
            commandLogic,
            ['openSource', 'pendingText'],
            searchListsLogic({ commandPalette: true }),
            [
                'starredItems',
                'productsItems',
                'commandKSettingsItems as settingsItems',
                'newItems',
                'dataManagementItems',
                'peopleItems',
                'healthItems',
                'actionItems',
            ],
            recentItemsModel,
            ['recents'],
            membersLogic,
            ['members', 'meFirstMembers'],
            userLogic,
            ['user'],
            teamLogic,
            ['currentTeamId'],
            featureFlagLogic,
            ['featureFlags'],
            groupsModel,
            ['groupTypes', 'aggregationLabel'],
            themeLogic,
            ['isDarkModeOn'],
            shortcutLogic,
            ['shortcutItems'],
        ],
        actions: [
            commandLogic,
            ['closeCommand', 'commandInputReady'],
            membersLogic,
            ['ensureAllMembersLoaded'],
            teamLogic,
            ['loadCurrentTeamSuccess'],
            sidePanelStateLogic,
            ['openSidePanel'],
            runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
            ['clearActiveCreation', 'setHistoryExpanded'],
        ],
    })),
    actions({
        inputChanged: (text: string, cursor: number, pasted: boolean) => ({ text, cursor, pasted }),
        setCursor: (cursor: number) => ({ cursor }),
        setChipsAndText: (chips: QueryChip[], text: string, cursor: number) => ({ chips, text, cursor }),
        commitChip: (chip: QueryChip, token: QueryToken | null, via: CommitVia) => ({ chip, token, via }),
        selectChip: (index: ChipSelection) => ({ index }),
        editChip: (index: number) => ({ index }),
        completeFilterKey: (filter: FilterDefinition, negated: boolean) => ({ filter, negated }),
        applyKeyIntent: (intent: KeyIntent) => ({ intent }),
        moveHighlight: (direction: 1 | -1) => ({ direction }),
        setHighlightedKey: (key: string | null) => ({ key }),
        expandGroup: (group: string) => ({ group }),
        activateRow: (row: CommandKRow, newTab: boolean, via: CommitVia) => ({ row, newTab, via }),
        completeHighlighted: true,
        askAi: true,
        clearQuery: true,
        requestsStarted: (queries: Record<string, string>) => ({ queries }),
        remoteLoaded: (query: string, results: RemoteResults, failed: boolean = false) => ({ query, results, failed }),
        showQuery: (query: SectionsQuery) => ({ query }),
        loadFolders: true,
        foldersLoaded: (folders: FileSystemEntry[]) => ({ folders }),
        markResultOpened: true,
        applyCorrection: (correction: SearchCorrection) => ({ correction }),
    }),
    reducers({
        text: [
            '',
            {
                setChipsAndText: (_, { text }) => text,
            },
        ],
        cursor: [
            0,
            {
                setCursor: (_, { cursor }) => cursor,
                setChipsAndText: (_, { cursor }) => cursor,
            },
        ],
        chips: [
            [] as QueryChip[],
            {
                setChipsAndText: (_, { chips }) => chips,
            },
        ],
        chipSelection: [
            null as ChipSelection,
            {
                selectChip: (_, { index }) => index,
                setChipsAndText: () => null,
            },
        ],
        // Follows identity through result swaps within one query; a new query starts at the first row.
        highlightedKey: [
            null as string | null,
            {
                setHighlightedKey: (_, { key }) => key,
                setChipsAndText: () => null,
            },
        ],
        expandedGroups: [
            [] as string[],
            {
                expandGroup: (state, { group }) => (state.includes(group) ? state : [...state, group]),
                setChipsAndText: () => [],
            },
        ],
        // The query each request last asked for. No selector reads it, so starting a request never re-renders.
        requestedQueries: [
            {} as Record<string, string>,
            {
                requestsStarted: (state, { queries }) => ({ ...state, ...queries }),
            },
        ],
        remote: [
            emptyRemoteSlots(),
            {
                remoteLoaded: (state, { query, results, failed }) => {
                    const next = { ...state }
                    for (const [source, items] of Object.entries(results) as [RemoteSource, SearchItem[]][]) {
                        const { [query]: _, ...stillFailed } = state[source].failed ?? {}
                        next[source] = {
                            cache: { ...state[source].cache, [query]: items },
                            failed: failed ? { ...stillFailed, [query]: true } : stillFailed,
                        }
                    }
                    return next
                },
                requestsStarted: (state, { queries }) => {
                    const retried = Object.entries(queries).flatMap(([requestId, query]) =>
                        (REMOTE_REQUESTS.find((request) => request.id === requestId)?.sources ?? [])
                            .filter((source) => state[source].failed?.[query])
                            .map((source) => [source, query] as const)
                    )
                    if (retried.length === 0) {
                        return state
                    }
                    const next = { ...state }
                    for (const [source, query] of retried) {
                        const { [query]: _items, ...cache } = next[source].cache
                        const { [query]: _failed, ...failed } = next[source].failed ?? {}
                        next[source] = { cache, failed }
                    }
                    return next
                },
            },
        ],
        shownQuery: [
            null as SectionsQuery | null,
            {
                showQuery: (_, { query }) => query,
            },
        ],
        folders: [
            null as FileSystemEntry[] | null,
            {
                foldersLoaded: (_, { folders }) => folders,
            },
        ],
        resultOpened: [
            false,
            {
                markResultOpened: () => true,
            },
        ],
        searchCorrection: [
            null as SearchCorrection | null,
            {
                applyCorrection: (_, { correction }) => correction,
                setChipsAndText: (state, { text }) => (state?.from === text.trim() ? state : null),
            },
        ],
    }),
    selectors({
        filterOptions: [
            (s) => [s.meFirstMembers, s.user, s.folders],
            (
                members: OrganizationMemberType[],
                user: UserType | null,
                folders: FileSystemEntry[] | null
            ): FilterOptions => buildFilterOptions(members, user, folders),
        ],
        cursorContext: [
            (s) => [s.text, s.cursor, s.chips],
            (text: string, cursor: number, chips: QueryChip[]): CursorContext => getCursorContext(text, cursor, chips),
        ],
        mode: [
            (s) => [s.cursorContext],
            (context: CursorContext): CommandKMode => (context.kind === 'text' ? 'search' : context.kind),
        ],
        resolvedQuery: [
            (s) => [s.text, s.chips, s.filterOptions],
            (text: string, chips: QueryChip[], filterOptions: FilterOptions): ResolvedQuery =>
                resolveQuery(text, chips, filterOptions),
        ],
        /** The free text the non-object sections search for. Empty while a filter limits the palette to objects. */
        localQuery: [
            (s) => [s.resolvedQuery, s.mode, s.searchCorrection],
            (resolved: ResolvedQuery, mode: CommandKMode, correction: SearchCorrection | null): string => {
                const query =
                    (mode === 'search' || mode === 'key') && resolved.filters.length === 0
                        ? resolved.freeText.trim()
                        : ''
                return query && correction?.from === query ? correction.to : query
            },
        ],
        askAiQuestion: [
            (s) => [s.text, s.resolvedQuery],
            (text: string, resolved: ResolvedQuery): string | null => askAiQuestionFor(text, resolved),
        ],
        remoteContext: [
            (s) => [s.currentTeamId, s.groupTypes, s.aggregationLabel, s.featureFlags],
            (
                currentTeamId: number | null,
                groupTypes: Map<GroupTypeIndex, GroupType>,
                aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun, // groupsModel
                featureFlags: FeatureFlagsSet
            ): RemoteContext => ({
                currentTeamId,
                groupTypes: Array.from(groupTypes.values()),
                aggregationLabel,
                customerAnalyticsEnabled: !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP],
            }),
        ],
        /** The query each request runs for this input, for the requests that apply to it. */
        requestQueries: [
            (s) => [s.resolvedQuery, s.localQuery, s.mode, s.remoteContext, s.searchCorrection],
            (
                resolved: ResolvedQuery,
                localQuery: string,
                mode: CommandKMode,
                context: RemoteContext,
                correction: SearchCorrection | null
            ): Record<string, string> => {
                // Filters come first in backendSearch, so the corrected words replace its end.
                const corrects =
                    correction?.from === resolved.freeText.trim() && resolved.backendSearch.endsWith(correction.from)
                const objectsQuery = corrects
                    ? resolved.backendSearch.slice(0, -correction.from.length) + correction.to
                    : resolved.backendSearch
                const queries: Record<string, string> = {}
                // Every request searches the current project, so none runs before one is known.
                if (context.currentTeamId === null) {
                    return queries
                }
                for (const request of REMOTE_REQUESTS) {
                    const query = request.query === 'objects' ? (mode === 'empty' ? '' : objectsQuery) : localQuery
                    if (query && (request.enabled?.(query, context) ?? true)) {
                        queries[request.id] = query
                    }
                }
                return queries
            },
        ],
        remoteQueries: [
            (s) => [s.requestQueries],
            (requestQueries: Record<string, string>): Partial<Record<RemoteSource, string>> =>
                Object.fromEntries(
                    REMOTE_REQUESTS.flatMap((request) =>
                        request.id in requestQueries
                            ? request.sources.map((source) => [source, requestQueries[request.id]])
                            : []
                    )
                ),
        ],
        suggestionsSection: [
            (s) => [s.cursorContext, s.filterOptions, s.members, s.folders],
            (
                context: CursorContext,
                filterOptions: FilterOptions,
                members: OrganizationMemberType[] | null,
                folders: FileSystemEntry[] | null
            ): CommandKSection | null =>
                context.kind === 'value'
                    ? buildSuggestions(context, filterOptions, {
                          members: members === null,
                          folders: folders === null,
                      })
                    : null,
        ],
        recentItems: [
            (s) => [s.recents],
            (recents: FileSystemEntry[]): SearchItem[] =>
                recents
                    .slice(0, RECENTS_LIMIT)
                    .map((entry) => fileSystemEntryToSearchItem(entry, { id: entry.path, category: 'recents' })),
        ],
        localLists: [
            (s) => [
                s.recentItems,
                s.starredItems,
                s.shortcutItems,
                s.productsItems,
                s.settingsItems,
                s.newItems,
                s.dataManagementItems,
                s.peopleItems,
                s.healthItems,
                s.actionItems,
            ],
            (
                recents: SearchItem[],
                starred: SearchItem[],
                shortcuts: SearchItem[],
                products: SearchItem[],
                settings: SearchItem[],
                create: SearchItem[],
                dataManagement: SearchItem[],
                people: SearchItem[],
                health: SearchItem[],
                actions: SearchItem[]
            ): LocalLists => ({
                recents,
                starred,
                shortcuts,
                products,
                settings,
                create,
                'data-management': dataManagement,
                people,
                health,
                actions,
            }),
        ],
        themeItem: [
            (s) => [s.localQuery, s.isDarkModeOn],
            (localQuery: string, isDarkModeOn: boolean): SearchItem | null =>
                themeSearchItem(localQuery, isDarkModeOn, {
                    setTheme: (mode) => userLogic.actions.updateUser({ theme_mode: mode }),
                    toggleTheme: () => themeLogic.actions.toggleTheme(),
                }),
        ],
        viewAll: [(s) => [s.resolvedQuery], (resolved: ResolvedQuery): ViewAll | null => viewAllFor(resolved)],
        currentQuery: [
            (s) => [s.remoteQueries, s.localQuery, s.themeItem, s.askAiQuestion, s.viewAll],
            (
                remoteQueries: Partial<Record<RemoteSource, string>>,
                localQuery: string,
                themeItem: SearchItem | null,
                askAiQuestion: string | null,
                viewAll: ViewAll | null
            ): SectionsQuery => ({ remoteQueries, localQuery, themeItem, askAiQuestion, viewAll }),
        ],
        displayedQuery: [
            (s) => [s.currentQuery, s.shownQuery, s.remote],
            (
                current: SectionsQuery,
                shown: SectionsQuery | null,
                remote: RemoteSlots
            ): { query: SectionsQuery; stale: boolean } => pickDisplayedQuery(current, shown, remote),
        ],
        sections: [
            (s) => [
                s.mode,
                s.cursorContext,
                s.suggestionsSection,
                s.localLists,
                s.remote,
                s.displayedQuery,
                s.searchCorrection,
                s.expandedGroups,
            ],
            (
                mode: CommandKMode,
                context: CursorContext,
                suggestions: CommandKSection | null,
                local: LocalLists,
                remote: RemoteSlots,
                displayed: { query: SectionsQuery; stale: boolean },
                searchCorrection: SearchCorrection | null,
                expandedGroups: string[]
            ): CommandKSection[] =>
                buildSections({
                    mode,
                    context,
                    suggestions,
                    local,
                    remote,
                    ...displayed.query,
                    stale: displayed.stale,
                    personsFirst: !!displayed.query.remoteQueries.persons?.includes('@'),
                    expandedGroups,
                    searchCorrection:
                        searchCorrection &&
                        (displayed.query.remoteQueries.results ?? displayed.query.localQuery).endsWith(
                            searchCorrection.to
                        )
                            ? searchCorrection
                            : null,
                }),
        ],
        selectableRows: [
            (s) => [s.sections],
            (sections: CommandKSection[]): CommandKRow[] =>
                sections.flatMap((section) => section.rows).filter(isSelectable),
        ],
        highlightedRow: [
            (s) => [s.selectableRows, s.highlightedKey],
            (rows: CommandKRow[], highlightedKey: string | null): CommandKRow | null =>
                highlightedKey === INPUT_HIGHLIGHT_KEY
                    ? null
                    : (rows.find((row) => row.key === highlightedKey) ?? rows[0] ?? null),
        ],
        highlightIsFilterRow: [
            (s) => [s.highlightedRow],
            (row: CommandKRow | null): boolean => row?.kind === 'filter-key' || row?.kind === 'filter-value',
        ],
        tabAsksAi: [
            (s) => [s.highlightIsFilterRow, s.askAiQuestion],
            (highlightIsFilterRow: boolean, askAiQuestion: string | null): boolean =>
                askAiQuestion !== null && !highlightIsFilterRow,
        ],
        isPaletteEmpty: [
            (s) => [s.text, s.chips],
            (text: string, chips: QueryChip[]): boolean => text === '' && chips.length === 0,
        ],
    }),
    listeners(({ actions, values, cache }) => {
        // Retries a corrected search only once every source has answered and nothing matched.
        const correctWhenEmpty = (): void => {
            const query = values.localQuery
            const corrected = !values.searchCorrection && query ? correctedSearch(query) : null
            const settled = Object.entries(values.remoteQueries).every(
                ([source, sourceQuery]) => !sourceQuery || sourceQuery in values.remote[source as RemoteSource].cache
            )
            const failed = Object.entries(values.remoteQueries).some(
                ([source, sourceQuery]) =>
                    !!sourceQuery && !!values.remote[source as RemoteSource].failed?.[sourceQuery]
            )
            const empty = !values.sections.some((section) => section.rows.some((row) => row.kind === 'item'))
            if (corrected && settled && !failed && !values.displayedQuery.stale && empty) {
                actions.applyCorrection({ from: query, to: corrected })
            }
        }

        const showSettledQuery = (): void => {
            if (values.shownQuery !== values.currentQuery && resultsSettled(values.currentQuery, values.remote)) {
                actions.showQuery(values.currentQuery)
            }
        }

        const trackCommit = (chip: QueryChip, via: CommitVia): void => {
            posthog.capture('command k filter committed', {
                key: chip.key,
                value_kind: values.filterOptions[chip.key].some((option) => option.value === chip.value)
                    ? 'option'
                    : 'free_text',
                negated: chip.negated,
                via,
            })
        }

        const commit = (
            chips: QueryChip[],
            chip: QueryChip,
            token: QueryToken | null,
            text: string,
            via: CommitVia
        ): void => {
            const remaining = token ? removeToken(text, token) : { text, cursor: values.cursor }
            actions.setChipsAndText(addChip(chips, chip), remaining.text, remaining.cursor)
            trackCommit(chip, via)
        }

        const openRow = (row: CommandKRow, newTab: boolean): void => {
            if (row.kind !== 'item' && row.kind !== 'ask-ai') {
                return
            }
            const item = row.kind === 'item' ? row.item : null
            if (item && (item.disabledReason || (newTab && !canOpenInNewTab(item)))) {
                return
            }
            actions.markResultOpened()
            posthog.capture('command k result opened', {
                section: row.kind === 'item' ? row.section : 'ask-ai',
                ranked_section: row.key.split('/')[0],
                position: values.selectableRows.findIndex((candidate) => candidate.key === row.key),
                has_filters: values.chips.length > 0,
                filter_keys: values.chips.map((chip) => chip.key),
                query_length: queryAsText(values.text, values.chips).length,
            })
            actions.closeCommand()
            if (row.kind === 'ask-ai') {
                actions.clearActiveCreation()
                actions.setHistoryExpanded(false)
                actions.openSidePanel(SidePanelTab.Max, asLiteralPanelPrompt(row.question))
            } else if (item?.onSelect) {
                item.onSelect()
            } else if (item?.href && newTab) {
                newInternalTab(item.href)
            } else if (item?.href) {
                scrollToAnchorOnCurrentPage(item.href)
                navigateToHref(item.href)
            }
        }

        // Cached answers arrive inside this loop, so a correction waits until the loop is done.
        const syncRemote = (): void => {
            cache.syncingRemote = true
            startRemoteRequests()
            cache.syncingRemote = false
            correctWhenEmpty()
        }

        const startRemoteRequests = (): void => {
            const started: Record<string, string> = {}
            for (const request of REMOTE_REQUESTS) {
                const query = values.requestQueries[request.id] ?? ''
                if (query !== (values.requestedQueries[request.id] ?? '')) {
                    started[request.id] = query
                }
            }
            if (Object.keys(started).length === 0) {
                showSettledQuery()
                return
            }
            actions.requestsStarted(started)
            for (const request of REMOTE_REQUESTS) {
                if (!(request.id in started)) {
                    continue
                }
                const query = started[request.id]
                if (!query) {
                    // The request no longer applies, so stop it rather than let it hold a query slot.
                    cache.disposables.dispose(`request-${request.id}`)
                    continue
                }
                const cached = request.sources.map((source) => values.remote[source].cache[query])
                if (cached.every(Boolean)) {
                    cache.disposables.dispose(`request-${request.id}`)
                    actions.remoteLoaded(
                        query,
                        Object.fromEntries(request.sources.map((source, index) => [source, cached[index]]))
                    )
                    continue
                }
                const debounceMs = requestDebounceMs(request, query)
                // One disposable per request covers the debounce and the fetch, so a newer query
                // cancels both, and unmounting cancels everything.
                cache.disposables.add(
                    () => {
                        const controller = new AbortController()
                        const timer = setTimeout(() => {
                            void settleRequest(request, query, controller.signal, values.remoteContext).then(
                                (settled) => {
                                    if (settled && values.requestedQueries[request.id] === query) {
                                        actions.remoteLoaded(query, settled.results, settled.failed)
                                    }
                                }
                            )
                        }, debounceMs)
                        return () => {
                            clearTimeout(timer)
                            controller.abort()
                        }
                    },
                    `request-${request.id}`,
                    // Hiding the tab must not abort a search, or its section would sit on stale rows.
                    { pauseOnPageHidden: false }
                )
            }
            showSettledQuery()
        }

        const onQueryChanged = (): void => {
            const context = values.cursorContext
            const keys =
                context.kind === 'key'
                    ? context.matches.map((match) => match.key)
                    : context.kind === 'value'
                      ? [context.filter.key]
                      : null
            const signature = keys ? `${context.kind}:${keys.join(',')}` : null
            if (signature && signature !== cache.lastSuggestion) {
                posthog.capture('command k filter suggested', { stage: context.kind, keys })
            }
            cache.lastSuggestion = signature
            // Value lists load the first time their filter is used, so opening the palette sends no request.
            if (context.kind === 'value' && context.filter.key === 'in') {
                actions.loadFolders()
            }
            if (context.kind === 'value' && context.filter.key === 'createdBy') {
                actions.ensureAllMembersLoaded()
            }
            syncRemote()
        }

        return {
            // Remote searches wait for a project, so a project that loads mid-query starts them.
            loadCurrentTeamSuccess: () => syncRemote(),
            inputChanged: ({ text, cursor, pasted }) => {
                // With everything selected, the edit replaced the chips along with the text.
                const replacedAll = values.chipSelection === 'all'
                const chips = replacedAll ? [] : values.chips
                if (pasted) {
                    const extracted = extractChips(text, chips, values.filterOptions)
                    for (const chip of extracted.chips.filter((chip) => !chips.includes(chip))) {
                        trackCommit(chip, 'paste')
                    }
                    actions.setChipsAndText(extracted.chips, extracted.text, extracted.text.length)
                    return
                }
                const edit = {
                    previousText: replacedAll ? '' : values.text,
                    previousCursor: replacedAll ? 0 : values.cursor,
                    text,
                    cursor,
                }
                if (isRedundantSpace(edit)) {
                    return
                }
                const committed = chipCommittedByEdit(edit, chips, values.filterOptions)
                if (committed) {
                    commit(chips, committed.chip, committed.token, text, committed.via)
                } else {
                    actions.setChipsAndText(chips, text, cursor)
                }
            },
            setCursor: onQueryChanged,
            setChipsAndText: onQueryChanged,
            commitChip: ({ chip, token, via }) => commit(values.chips, chip, token, values.text, via),
            completeFilterKey: ({ filter, negated }) => {
                const token = tokenAtCursor(values.text, values.cursor)
                const replacement = `${negated ? '-' : ''}${filter.key}:`
                const next = token
                    ? replaceToken(values.text, token, replacement)
                    : { text: values.text + replacement, cursor: values.text.length + replacement.length }
                actions.setChipsAndText(values.chips, next.text, next.cursor)
            },
            editChip: ({ index }) => {
                const chip = values.chips[index]
                if (!chip) {
                    return
                }
                const chipText = chipToText(chip)
                actions.setChipsAndText(
                    values.chips.filter((_, i) => i !== index),
                    values.text ? `${chipText} ${values.text}` : chipText,
                    chipText.length
                )
            },
            applyKeyIntent: ({ intent }) => {
                switch (intent.type) {
                    case 'move':
                        actions.moveHighlight(intent.direction)
                        break
                    case 'activate':
                        if (values.highlightedRow) {
                            actions.activateRow(values.highlightedRow, intent.newTab, 'enter')
                        }
                        break
                    case 'complete':
                        actions.completeHighlighted()
                        break
                    case 'select-chip':
                        actions.selectChip(intent.index)
                        break
                    case 'clear':
                        actions.clearQuery()
                        break
                    case 'remove-chip':
                        actions.setChipsAndText(
                            values.chips.filter((_, i) => i !== intent.index),
                            values.text,
                            values.cursor
                        )
                        break
                    case 'edit-chip':
                        actions.editChip(intent.index)
                        break
                    case 'close':
                        actions.closeCommand()
                        break
                }
            },
            moveHighlight: ({ direction }) => {
                const rows = values.selectableRows
                if (rows.length === 0) {
                    return
                }
                const currentIndex = values.highlightedRow ? rows.indexOf(values.highlightedRow) : -1
                const nextIndex = Math.min(currentIndex + direction, rows.length - 1)
                actions.setHighlightedKey(nextIndex < 0 ? INPUT_HIGHLIGHT_KEY : rows[nextIndex].key)
            },
            activateRow: ({ row, newTab, via }) => {
                if (row.kind === 'filter-key') {
                    actions.completeFilterKey(row.filter, row.negated)
                } else if (row.kind === 'filter-value') {
                    const context = values.cursorContext
                    actions.commitChip(
                        { key: row.filter.key, value: row.option.value, label: row.option.label, negated: row.negated },
                        context.kind === 'value' ? context.token : null,
                        via
                    )
                } else if (row.kind === 'expand') {
                    const index = values.selectableRows.findIndex((candidate) => candidate.key === row.key)
                    actions.expandGroup(row.group)
                    const next = values.selectableRows[index]
                    if (next) {
                        actions.setHighlightedKey(next.key)
                    }
                } else if (row.kind === 'scope') {
                    const option = values.filterOptions.is.find((candidate) => candidate.value === row.type)
                    actions.commitChip(
                        { key: 'is', value: row.type, label: option?.label ?? row.type, negated: false },
                        null,
                        'see-all'
                    )
                } else {
                    openRow(row, newTab)
                }
            },
            completeHighlighted: () => {
                if (values.highlightIsFilterRow && values.highlightedRow) {
                    actions.activateRow(values.highlightedRow, false, 'tab')
                } else {
                    actions.askAi()
                }
            },
            askAi: () => {
                if (values.askAiQuestion) {
                    openRow({ kind: 'ask-ai', key: 'ask-ai/ask', question: values.askAiQuestion }, false)
                }
            },
            clearQuery: () => actions.setChipsAndText([], '', 0),
            remoteLoaded: () => {
                showSettledQuery()
                if (!cache.syncingRemote) {
                    correctWhenEmpty()
                }
            },
            applyCorrection: () => syncRemote(),
            loadFolders: async () => {
                if (cache.foldersRequested) {
                    return
                }
                cache.foldersRequested = true
                try {
                    const response = await api.fileSystem.list({ type: 'folder', limit: 1000 })
                    actions.foldersLoaded(response.results)
                } catch {
                    actions.foldersLoaded([])
                }
            },
        }
    }),
    afterMount(({ actions, values }) => {
        posthog.capture('command k search opened', { source: values.openSource })
        if (values.pendingText) {
            actions.inputChanged(values.pendingText, values.pendingText.length, false)
        }
        actions.commandInputReady()
    }),
    beforeUnmount(({ values }) => {
        if (!values.resultOpened) {
            posthog.capture('command k search abandoned', {
                last_mode: values.mode,
                had_filters: values.chips.length > 0,
                had_results: values.sections.some((section) => section.rows.some((row) => row.kind === 'item')),
            })
        }
    }),
])