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.

32.1 KB
Raw Blame
import FuseClass from 'fuse.js'
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import { FEATURE_FLAGS } from 'lib/constants'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { createFuse } from 'lib/utils/fuseSearch'
import { organizationLogic } from 'scenes/organizationLogic'
import type { Params } from 'scenes/sceneTypes'
import { organizationIntegrationsLogic } from 'scenes/settings/organization/organizationIntegrationsLogic'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'

import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { IntegrationType, PreflightStatus, TeamPublicType, TeamType } from '../../types'
import type { AvailableFeature, OrganizationType, UserType } from '../../types'
import { matchesFlagDefinition, visibleSettingsSections } from './flagGating'
import { findUnavailableSection } from './sectionGating'
import { SETTINGS_MAP } from './SettingsMap'
import {
    FUSE_THRESHOLD,
    GlobalSearchFuse,
    buildSettingsSearchIndex,
    createSettingsSearchFuse,
    searchSettingsIndex,
} from './settingsSearch'
import { SETTINGS_SECTION_SCENES, SettingsPaneLevel } from './settingsSectionScenes'
import {
    Setting,
    SettingId,
    SettingLevelId,
    SettingSection,
    SettingSectionId,
    SettingsLogicProps,
    UnavailableSection,
} from './types'

// Helping kea-typegen navigate the exported default class for Fuse
export interface SettingsFuse extends FuseClass<Setting & { searchValue: string }> {}
export interface SectionsFuse extends FuseClass<
    SettingSection & { searchValue: string; settingsSearchValues: string }
> {}

export interface SearchResult {
    settingId: SettingId
    settingTitle: string
    sectionId: SettingSectionId
    sectionTitle: string
    level: SettingLevelId
}

export interface SearchResultGroup {
    sectionId: SettingSectionId
    sectionTitle: string
    level: SettingLevelId
    results: SearchResult[]
}

const getSettingStringValue = (setting: Setting): string => {
    if (setting.searchTerm) {
        return setting.searchTerm
    }
    if (typeof setting.title === 'string') {
        return setting.title
    }
    return setting.id
}

const getSectionStringValue = (section: SettingSection): string => {
    if (section.searchValue) {
        return section.searchValue
    }
    if (typeof section.title === 'string') {
        return section.title
    }
    return section.id
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface settingsLogicValues {
    billingEntryUrl: string | null // billingLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    receivedFeatureFlags: boolean // featureFlagLogic
    organizationIntegrations: IntegrationType[] | null // organizationIntegrationsLogic
    currentOrganization: OrganizationType | null // organizationLogic
    isAdminOrOwner: boolean | null // organizationLogic
    isCloudOrDev: boolean | undefined // preflightLogic
    preflight: PreflightStatus | null // preflightLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
    user: UserType | null // userLogic
    collapsedGroups: Record<string, boolean>
    collapsedLevels: Record<SettingLevelId, boolean>
    defaultSectionId: SettingSectionId | null
    doesMatchFlags: (flagDefinition: Pick<Setting, 'flag'>) => boolean
    filteredLevels: SettingLevelId[]
    filteredSections: SettingSection[]
    globalSearchIndex: GlobalSearchFuse
    isCompactNavigationOpen: boolean
    isSearching: boolean
    levels: SettingLevelId[]
    navLevel: SettingsPaneLevel
    searchResults: SearchResultGroup[]
    searchTerm: string
    sections: SettingSection[]
    sectionsFuse: SectionsFuse
    selectedLevel: SettingLevelId
    selectedLevelRaw: 'environment' | 'organization' | 'project' | 'user'
    selectedSection: SettingSection | null
    selectedSectionId: SettingSectionId | null
    selectedSectionIdRaw: SettingSectionId | null
    selectedSetting: Setting | null
    selectedSettingId: SettingId | null
    settings: Setting[]
    settingsFuse: SettingsFuse
    unavailableSection: UnavailableSection | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface settingsLogicActions {
    closeCompactNavigation: () => {
        value: true
    }
    expandGroup: (group: string) => {
        group: string
    }
    navigateToSetting: (
        sectionId: SettingSectionId,
        settingId: SettingId
    ) => {
        sectionId: SettingSectionId
        settingId: SettingId
    }
    openCompactNavigation: () => {
        value: true
    }
    selectLevel: (level: SettingLevelId) => {
        level: 'environment' | 'organization' | 'project' | 'user'
    }
    selectSection: (
        section: SettingSectionId,
        level: SettingLevelId
    ) => {
        level: 'environment' | 'organization' | 'project' | 'user'
        section: SettingSectionId
    }
    selectSetting: (setting: SettingId) => {
        setting: SettingId
    }
    setNavLevel: (level: SettingsPaneLevel) => {
        level: SettingsPaneLevel
    }
    setSearchTerm: (searchTerm: string) => {
        searchTerm: string
    }
    toggleGroupCollapse: (group: string) => {
        group: string
    }
    toggleLevelCollapse: (level: SettingLevelId) => {
        level: 'environment' | 'organization' | 'project' | 'user'
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface settingsLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        levels: (sections: SettingSection[]) => SettingLevelId[]
        sections: (
            featureFlags: FeatureFlagsSet,
            isCloudOrDev: boolean | undefined,
            currentTeam: TeamPublicType | TeamType | null,
            currentOrganization: OrganizationType | null,
            organizationIntegrations: IntegrationType[] | null,
            preflight: PreflightStatus | null,
            billingEntryUrl: string | null,
            isAdminOrOwner: boolean | null,
            user: UserType | null
        ) => SettingSection[]
        selectedLevel: (
            selectedLevelRaw: 'environment' | 'organization' | 'project' | 'user',
            selectedSectionIdRaw: SettingSectionId | null,
            currentTeam: TeamPublicType | TeamType | null
        ) => SettingLevelId
        selectedSectionId: (selectedSectionIdRaw: SettingSectionId | null) => SettingSectionId | null
        defaultSectionId: (
            sections: SettingSection[],
            selectedLevel: 'environment' | 'organization' | 'project' | 'user'
        ) => SettingSectionId | null
        selectedSection: (
            sections: SettingSection[],
            selectedSectionId: SettingSectionId | null,
            defaultSectionId: SettingSectionId | null
        ) => SettingSection | null
        unavailableSection: (
            sections: SettingSection[],
            selectedSectionId: SettingSectionId | null,
            doesMatchFlags: (flagDefinition: Pick<Setting, 'flag'>) => boolean,
            isAdminOrOwner: boolean | null,
            receivedFeatureFlags: boolean,
            currentOrganization: OrganizationType | null
        ) => UnavailableSection | null
        settings: (
            selectedLevel: 'environment' | 'organization' | 'project' | 'user',
            selectedSectionId: SettingSectionId | null,
            defaultSectionId: SettingSectionId | null,
            sections: SettingSection[],
            doesMatchFlags: (flagDefinition: Pick<Setting, 'flag'>) => boolean,
            preflight: PreflightStatus | null,
            currentTeam: TeamPublicType | TeamType | null,
            isAdminOrOwner: boolean | null,
            user: UserType | null
        ) => Setting[]
        selectedSetting: (settings: Setting[], selectedSettingId: SettingId | null) => Setting | null
        doesMatchFlags: (featureFlags: FeatureFlagsSet) => (flagDefinition: Pick<Setting, 'flag'>) => boolean
        settingsFuse: (settings: Setting[]) => SettingsFuse
        sectionsFuse: (sections: SettingSection[]) => SectionsFuse
        isSearching: (searchTerm: string) => boolean
        globalSearchIndex: (
            sections: SettingSection[],
            doesMatchFlags: (flagDefinition: Pick<Setting, 'flag'>) => boolean,
            preflight: PreflightStatus | null,
            currentTeam: TeamPublicType | TeamType | null,
            isAdminOrOwner: boolean | null,
            user: UserType | null
        ) => GlobalSearchFuse
        searchResults: (searchTerm: string, globalSearchIndex: GlobalSearchFuse) => SearchResultGroup[]
        filteredLevels: (
            levels: ('environment' | 'organization' | 'project' | 'user')[],
            searchResults: SearchResultGroup[],
            isSearching: boolean
        ) => SettingLevelId[]
        filteredSections: (
            sections: SettingSection[],
            searchResults: SearchResultGroup[],
            isSearching: boolean
        ) => SettingSection[]
    }
}

export type settingsLogicType = MakeLogicType<
    settingsLogicValues,
    settingsLogicActions,
    SettingsLogicProps,
    settingsLogicMeta
>

/** The pane lists environment sections under Project, so it has no Environment tab. */
function paneLevel(level: SettingLevelId): SettingsPaneLevel {
    return level === 'environment' ? 'project' : level
}

function withRailNavigationLink(section: SettingSection): SettingSection {
    const scene = SETTINGS_SECTION_SCENES.find((s) => s.sectionId === section.id)
    return scene ? { ...section, to: scene.url } : section
}

export const settingsLogic = kea<settingsLogicType>([
    props({} as SettingsLogicProps),
    key((props) => props.logicKey ?? 'global'),
    path((key) => ['scenes', 'settings', 'settingsLogic', key]),
    connect(() => ({
        values: [
            featureFlagLogic,
            ['featureFlags', 'receivedFeatureFlags'],
            userLogic,
            ['hasAvailableFeature', 'user'],
            preflightLogic,
            ['preflight', 'isCloudOrDev'],
            teamLogic,
            ['currentTeam'],
            organizationLogic,
            ['currentOrganization', 'isAdminOrOwner'],
            organizationIntegrationsLogic,
            ['organizationIntegrations'],
            billingLogic,
            ['billingEntryUrl'],
        ],
    })),

    actions({
        selectLevel: (level: SettingLevelId) => ({ level }),
        selectSection: (section: SettingSectionId, level: SettingLevelId) => ({ section, level }),
        selectSetting: (setting: SettingId) => ({ setting }),
        openCompactNavigation: true,
        closeCompactNavigation: true,
        setSearchTerm: (searchTerm: string) => ({ searchTerm }),
        setNavLevel: (level: SettingsPaneLevel) => ({ level }),
        toggleLevelCollapse: (level: SettingLevelId) => ({ level }),
        toggleGroupCollapse: (group: string) => ({ group }),
        expandGroup: (group: string) => ({ group }),
        navigateToSetting: (sectionId: SettingSectionId, settingId: SettingId) => ({ sectionId, settingId }),
    }),

    reducers(({ props }) => ({
        selectedLevelRaw: [
            props.settingLevelId ?? 'project',
            {
                selectLevel: (_, { level }) => level,
                selectSection: (_, { level }) => level,
            },
        ],
        selectedSectionIdRaw: [
            props.sectionId ?? null,
            {
                selectLevel: () => null,
                selectSection: (_, { section }) => section,
            },
        ],
        selectedSettingId: [
            props.settingId ?? null,
            {
                selectLevel: () => null,
                selectSection: () => null,
                selectSetting: (_, { setting }) => setting,
            },
        ],

        isCompactNavigationOpen: [
            false,
            {
                openCompactNavigation: () => true,
                closeCompactNavigation: () => false,
                selectLevel: () => false,
                selectSection: () => false,
                selectSetting: () => false,
            },
        ],

        navLevel: [
            'project' as SettingsPaneLevel,
            {
                setNavLevel: (_, { level }) => level,
                selectLevel: (_, { level }) => paneLevel(level),
                selectSection: (_, { level }) => paneLevel(level),
            },
        ],

        searchTerm: [
            '',
            {
                setSearchTerm: (_, { searchTerm }) => searchTerm,
            },
        ],

        collapsedLevels: [
            {} as Record<SettingLevelId, boolean>,
            {
                toggleLevelCollapse: (state, { level }) => ({
                    ...state,
                    [level]: !state[level],
                }),
                // Auto-expand when selecting a level
                selectLevel: (state, { level }) => ({
                    ...state,
                    [level]: false,
                }),
                // Auto-expand when selecting a section
                selectSection: (state, { level }) => ({
                    ...state,
                    [level]: false,
                }),
            },
        ],

        collapsedGroups: [
            {} as Record<string, boolean>,
            {
                toggleGroupCollapse: (state, { group }) => ({
                    ...state,
                    [group]: !state[group],
                }),
                // Auto-expand the group that contains a freshly selected section
                expandGroup: (state, { group }) => ({
                    ...state,
                    [group]: false,
                }),
            },
        ],
    })),

    listeners(({ actions, values }) => ({
        selectSection: ({ section, level }) => {
            // Expand the collapsible group containing the selected section so it's visible
            // (e.g. when navigating via URL or settings search into a collapsed group)
            const sectionObj = values.sections.find((s) => s.id === section)
            if (sectionObj?.group) {
                actions.expandGroup(`${level}-${sectionObj.group}`)
            }
            setTimeout(() => {
                const anchorId = router.values.location.hash.slice(1)
                const anchorElement = anchorId ? document.getElementById(anchorId) : null
                if (anchorElement) {
                    anchorElement.scrollIntoView()
                    return
                }
                const mainElement = document.querySelector('main')
                if (mainElement) {
                    mainElement.scrollTo({ top: 0, behavior: 'smooth' })
                }
            }, 100)
        },
        setSearchTerm: async ({ searchTerm }, breakpoint) => {
            // Wait for typing to settle so one search reports once, not once per keystroke.
            await breakpoint(1000)

            const term = searchTerm.trim()
            if (!term) {
                return
            }

            const resultCount = values.searchResults.reduce((count, group) => count + group.results.length, 0)
            posthog.capture('settings search', {
                result_count: resultCount,
                word_count: term.split(/\s+/).length,
                // Only a search that found nothing is worth reading back, because that is what
                // a gap between the words people use and the words the index carries looks like.
                search_term: resultCount === 0 ? term : null,
            })
        },
        navigateToSetting: ({ sectionId, settingId }) => {
            const section = values.sections.find((s) => s.id === sectionId)
            if (section) {
                actions.setSearchTerm('')
                if (section.to) {
                    router.actions.push(section.to)
                } else {
                    actions.selectSection(sectionId, section.level)
                    setTimeout(() => {
                        const element = document.getElementById(settingId)
                        if (element) {
                            element.scrollIntoView({ behavior: 'smooth', block: 'start' })
                        }
                    }, 200)
                }
            }
        },
    })),

    selectors({
        levels: [
            (s) => [s.sections],
            (sections: SettingSection[]): SettingLevelId[] => {
                return sections.reduce<SettingLevelId[]>((acc, section) => {
                    if (!acc.includes(section.level)) {
                        acc.push(section.level)
                    }
                    return acc
                }, [])
            },
        ],
        sections: [
            (s) => [
                s.featureFlags,
                s.isCloudOrDev,
                s.currentTeam,
                s.currentOrganization,
                s.organizationIntegrations,
                s.preflight,
                s.billingEntryUrl,
                s.isAdminOrOwner,
                s.user,
            ],
            (
                featureFlags: FeatureFlagsSet,
                isCloudOrDev: boolean | undefined,
                currentTeam: null | import('../../types').TeamPublicType | import('../../types').TeamType,
                currentOrganization: null | import('../../types').OrganizationType,
                organizationIntegrations: import('../../types').IntegrationType[] | null,
                preflight: null | import('../../types').PreflightStatus,
                billingEntryUrl: string | null,
                isAdminOrOwner: boolean | null,
                user: UserType | null
            ): SettingSection[] =>
                visibleSettingsSections(
                    featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]
                        ? SETTINGS_MAP.map(withRailNavigationLink)
                        : SETTINGS_MAP,
                    {
                        featureFlags,
                        isCloudOrDev,
                        realm: preflight?.realm,
                        currentTeam,
                        currentOrganization,
                        hasOrganizationIntegrations: !!organizationIntegrations?.length,
                        billingEntryUrl,
                        isAdminOrOwner,
                        isStaff: !!user?.is_staff,
                    }
                ),
        ],
        selectedLevel: [
            (s) => [s.selectedLevelRaw, s.selectedSectionIdRaw, s.currentTeam],
            (
                selectedLevelRaw: 'environment' | 'organization' | 'project' | 'user',
                selectedSectionIdRaw: SettingSectionId | null,
                currentTeam: null | import('../../types').TeamPublicType | import('../../types').TeamType
            ): SettingLevelId => {
                if (
                    !selectedSectionIdRaw ||
                    (!selectedSectionIdRaw.endsWith('-details') && !selectedSectionIdRaw.endsWith('-danger-zone'))
                ) {
                    // If there's no current team, default to organization settings
                    if (!currentTeam) {
                        return 'organization'
                    }
                    // Convert environment to project
                    return selectedLevelRaw === 'environment' ? 'project' : selectedLevelRaw
                }
                return selectedLevelRaw
            },
        ],
        selectedSectionId: [
            (s) => [s.selectedSectionIdRaw],
            (selectedSectionIdRaw: SettingSectionId | null): SettingSectionId | null => {
                if (!selectedSectionIdRaw) {
                    return null
                }
                // Convert environment sections to project sections
                if (!selectedSectionIdRaw.endsWith('-details') && !selectedSectionIdRaw.endsWith('-danger-zone')) {
                    return selectedSectionIdRaw.replace(/^environment/, 'project') as SettingSectionId
                }
                return selectedSectionIdRaw
            },
        ],
        defaultSectionId: [
            (s) => [s.sections, s.selectedLevel],
            (sections: SettingSection[], selectedLevel: SettingLevelId): SettingSectionId | null => {
                const firstSection = sections.find((s) => s.level === selectedLevel)
                return firstSection?.id ?? null
            },
        ],
        selectedSection: [
            (s) => [s.sections, s.selectedSectionId, s.defaultSectionId],
            (
                sections: SettingSection[],
                selectedSectionId: SettingSectionId | null,
                defaultSectionId: SettingSectionId | null
            ): SettingSection | null => {
                const effectiveId = selectedSectionId ?? defaultSectionId
                return sections.find((x) => x.id === effectiveId) ?? null
            },
        ],
        unavailableSection: [
            (s) => [
                s.sections,
                s.selectedSectionId,
                s.doesMatchFlags,
                s.isAdminOrOwner,
                s.receivedFeatureFlags,
                s.currentOrganization,
            ],
            (
                sections: SettingSection[],
                selectedSectionId: SettingSectionId | null,
                doesMatchFlags: (flagDefinition: Pick<Setting, 'flag'>) => boolean,
                isAdminOrOwner: boolean | null,
                receivedFeatureFlags: boolean,
                currentOrganization: null | import('../../types').OrganizationType
            ): UnavailableSection | null =>
                findUnavailableSection({
                    sectionId: selectedSectionId,
                    visibleSections: sections,
                    allSections: SETTINGS_MAP,
                    gatesResolved: receivedFeatureFlags && !!currentOrganization?.membership_level,
                    doesMatchFlags,
                    isAdminOrOwner,
                }),
        ],
        settings: [
            (s) => [
                s.selectedLevel,
                s.selectedSectionId,
                s.defaultSectionId,
                s.sections,
                s.doesMatchFlags,
                s.preflight,
                s.currentTeam,
                s.isAdminOrOwner,
                s.user,
            ],
            (
                selectedLevel: SettingLevelId,
                selectedSectionId: SettingSectionId | null,
                defaultSectionId: SettingSectionId | null,
                sections: SettingSection[],
                doesMatchFlags: (flagDefinition: Pick<Setting, 'flag'>) => boolean,
                preflight: null | import('../../types').PreflightStatus,
                currentTeam: null | import('../../types').TeamPublicType | import('../../types').TeamType,
                isAdminOrOwner: boolean | null,
                user: UserType | null
            ): Setting[] => {
                const effectiveSectionId = selectedSectionId ?? defaultSectionId

                let settings: Setting[] = []

                if (effectiveSectionId) {
                    settings = sections.find((x) => x.id === effectiveSectionId)?.settings || []
                } else {
                    settings = sections
                        .filter((section) => section.level === selectedLevel)
                        .reduce((acc, section) => acc.concat(section.settings), [] as Setting[])
                }

                return settings.filter((x) => {
                    if (!doesMatchFlags(x)) {
                        return false
                    }
                    if (preflight?.realm && x.hideOn?.includes(preflight.realm)) {
                        return false
                    }
                    if (x.hideWhenNoSection && !effectiveSectionId) {
                        return false
                    }
                    if (x.organizationAdminOnly && !isAdminOrOwner) {
                        return false
                    }
                    if (x.staffOnly && !user?.is_staff) {
                        return false
                    }
                    if (x.allowForTeam) {
                        return x.allowForTeam(currentTeam)
                    }
                    return true
                })
            },
        ],
        selectedSetting: [
            (s) => [s.settings, s.selectedSettingId],
            (settings: Setting[], selectedSettingId: SettingId | null): Setting | null => {
                return settings.find((s) => s.id === selectedSettingId) ?? null
            },
        ],
        doesMatchFlags: [
            (s) => [s.featureFlags],
            (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet) => {
                return (flagDefinition: Pick<Setting, 'flag'>) =>
                    matchesFlagDefinition(flagDefinition.flag, featureFlags)
            },
        ],

        settingsFuse: [
            (s) => [s.settings],
            (settings: Setting[]): SettingsFuse => {
                const settingsWithSearchValues = settings.map((setting) => ({
                    ...setting,
                    searchValue: getSettingStringValue(setting),
                }))

                return createFuse(settingsWithSearchValues || [], {
                    keys: ['searchValue', 'id'],
                    threshold: FUSE_THRESHOLD,
                })
            },
        ],

        sectionsFuse: [
            (s) => [s.sections],
            (sections: SettingSection[]): SectionsFuse => {
                const sectionsWithSearchValues = sections.map((section) => ({
                    ...section,
                    searchValue: getSectionStringValue(section),
                    settingsSearchValues: section.settings.map(getSettingStringValue).join(' '),
                }))

                return createFuse(sectionsWithSearchValues || [], {
                    keys: ['searchValue', 'settingsSearchValues', 'id'],
                    threshold: FUSE_THRESHOLD,
                })
            },
        ],

        isSearching: [(s) => [s.searchTerm], (searchTerm: string): boolean => searchTerm.trim().length > 0],

        globalSearchIndex: [
            (s) => [s.sections, s.doesMatchFlags, s.preflight, s.currentTeam, s.isAdminOrOwner, s.user],
            (
                sections: SettingSection[],
                doesMatchFlags: (flagDefinition: Pick<Setting, 'flag'>) => boolean,
                preflight: null | import('../../types').PreflightStatus,
                currentTeam: null | import('../../types').TeamPublicType | import('../../types').TeamType,
                isAdminOrOwner: boolean | null,
                user: UserType | null
            ): GlobalSearchFuse => {
                const isSettingVisible = (setting: Setting): boolean => {
                    if (!doesMatchFlags(setting)) {
                        return false
                    }
                    if (preflight?.realm && setting.hideOn?.includes(preflight.realm)) {
                        return false
                    }
                    if (setting.organizationAdminOnly && !isAdminOrOwner) {
                        return false
                    }
                    if (setting.staffOnly && !user?.is_staff) {
                        return false
                    }
                    return !setting.allowForTeam || setting.allowForTeam(currentTeam)
                }

                return createSettingsSearchFuse(buildSettingsSearchIndex(sections, isSettingVisible))
            },
        ],

        searchResults: [
            (s) => [s.searchTerm, s.globalSearchIndex],
            (searchTerm: string, globalSearchIndex: GlobalSearchFuse): SearchResultGroup[] => {
                const results = searchSettingsIndex(globalSearchIndex, searchTerm)
                const groupMap = new Map<SettingSectionId, SearchResultGroup>()

                for (const { sectionId, sectionTitle, level, settingId, settingTitle } of results) {
                    let group = groupMap.get(sectionId)
                    if (!group) {
                        group = { sectionId, sectionTitle, level, results: [] }
                        groupMap.set(sectionId, group)
                    }
                    group.results.push({ settingId, settingTitle, sectionId, sectionTitle, level })
                }

                return Array.from(groupMap.values())
            },
        ],

        filteredLevels: [
            (s) => [s.levels, s.searchResults, s.isSearching],
            (levels: SettingLevelId[], searchResults: SearchResultGroup[], isSearching: boolean): SettingLevelId[] => {
                if (!isSearching) {
                    return levels
                }

                const levelsWithResults = new Set(searchResults.map((g) => g.level))
                return levels.filter((level) => levelsWithResults.has(level))
            },
        ],

        filteredSections: [
            (s) => [s.sections, s.searchResults, s.isSearching],
            (
                sections: SettingSection[],
                searchResults: SearchResultGroup[],
                isSearching: boolean
            ): SettingSection[] => {
                const visibleSections = sections.filter((section) => !section.hideFromNavigation)

                if (!isSearching) {
                    return visibleSections
                }

                const sectionIds = new Set(searchResults.map((g) => g.sectionId))
                return visibleSections.filter((section) => sectionIds.has(section.id))
            },
        ],
    }),
    actionToUrl(({ props }) => ({
        // Skip the URL update in the full settings scene — settingsSceneLogic already pushes
        // the canonical URL with the section path + setting hash. Without this guard, both
        // subscriptions fire on selectSetting and produce two history entries per click.
        // Embedded usages (replay, logs) keep the `selectedSetting` hash for deep-linking.
        selectSetting: ({ setting }) => {
            if (props.logicKey === 'settingsScene') {
                return
            }
            return [
                router.values.location.pathname,
                router.values.searchParams,
                { ...router.values.hashParams, selectedSetting: setting },
            ]
        },
    })),
    urlToAction(({ actions, values, props }) => ({
        // A section with a scene of its own has no section selection, so its route moves the pane to its tab.
        ...Object.fromEntries(
            SETTINGS_SECTION_SCENES.flatMap(({ level, url, legacyUrl }) =>
                [url, legacyUrl]
                    .filter((root): root is string => !!root)
                    .map((root) => [`${root}(/*)`, () => actions.setNavLevel(level)])
            )
        ),
        // The settings scene instance outlives a scene change, and its selectSetting pushes `/settings/...`.
        ...(props.logicKey === 'settingsScene' ? {} : embeddedSettingsRoutes(actions, values)),
    })),
])

function embeddedSettingsRoutes(
    actions: settingsLogicType['actions'],
    values: settingsLogicType['values']
): Record<string, (params: Params, searchParams: Params, hashParams: Params) => void> {
    return {
        ['*/replay/settings']: (_, __, hashParams) => {
            const { selectedSetting } = hashParams
            const selectedSettingId = selectedSetting as SettingId

            if (!selectedSettingId) {
                return
            }

            if (values.selectedSettingId !== selectedSettingId) {
                actions.selectSetting(selectedSettingId)
            }
        },
        ['*/logs']: (_, searchParams, hashParams) => {
            const fromHash = hashParams.selectedSetting as string | undefined
            const fromQuery = typeof searchParams?.setting === 'string' ? searchParams.setting : undefined
            const raw = fromHash ?? fromQuery
            if (!raw) {
                return
            }
            const selectedSettingId = (raw === 'logs-sampling' ? 'logs-drop-rules' : raw) as SettingId

            if (values.selectedSettingId !== selectedSettingId) {
                actions.selectSetting(selectedSettingId)
            }
        },
    }
}