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.

44.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import type { BuiltLogic } from 'kea'
import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'
import posthog from 'posthog-js'

import { IconBug, IconCheckbox, IconDashboard, IconGraph, IconNotebook } from '@posthog/icons'

import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { objectsEqual } from 'lib/utils/objects'
import type { RefreshStatus } from 'scenes/dashboard/dashboardLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
import { NotebookListItemType } from 'scenes/notebooks/types'
import { sceneLogic } from 'scenes/sceneLogic'

import { dashboardsModel } from '~/models/dashboardsModel'
import { DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'
import { ActionType, DashboardType, EventDefinition, InsightShortId, InsightModel } from '~/types'

import type { Node } from '../../queries/schema/schema-general'
import type { LoadedScene } from '../sceneTypes'
import type { ToolRegistration } from './max-constants'
import { maxGlobalLogic } from './maxGlobalLogic'
import {
    MaxActionContext,
    MaxContextInput,
    MaxContextItem,
    MaxContextTaxonomicFilterOption,
    MaxContextType,
    MaxDashboardContext,
    MaxErrorTrackingIssueContext,
    MaxEvaluationContext,
    MaxEventContext,
    MaxInsightContext,
    MaxNotebookContext,
    MaxUIContext,
    EvaluationRuntime,
} from './maxTypes'
import {
    actionToMaxContextPayload,
    activeSceneLogicHasMaxContext,
    dashboardToMaxContext,
    errorTrackingIssueToMaxContextPayload,
    evaluationToMaxContextPayload,
    eventToMaxContextPayload,
    insightToMaxContext,
    notebookToMaxContextPayload,
} from './utils'

// Type definitions for better reusability
export type TaxonomicItem =
    | DashboardType
    | InsightModel
    | EventDefinition
    | ActionType
    | NotebookListItemType
    | MaxContextTaxonomicFilterOption

export type DashboardItemInfo = { id: number; preloaded: DashboardType | null }
export type InsightItemInfo = { id: InsightShortId; preloaded: InsightModel | null }

type EntityWithIdAndType = { id: string | number; type: string }

const addOrUpdateEntity = <TContext extends EntityWithIdAndType>(state: TContext[], entity: TContext): TContext[] =>
    state.filter((item) => item.id !== entity.id).concat(entity)

const removeEntity = <TContext extends EntityWithIdAndType>(state: TContext[], id: string | number): TContext[] =>
    state.filter((item) => item.id !== id)

const PICKER_GROUP_CONTEXT_TYPES: Partial<Record<TaxonomicFilterGroupType, MaxContextType>> = {
    [TaxonomicFilterGroupType.Events]: MaxContextType.EVENT,
    [TaxonomicFilterGroupType.Actions]: MaxContextType.ACTION,
    [TaxonomicFilterGroupType.Insights]: MaxContextType.INSIGHT,
    [TaxonomicFilterGroupType.Dashboards]: MaxContextType.DASHBOARD,
    [TaxonomicFilterGroupType.Notebooks]: MaxContextType.NOTEBOOK,
    [TaxonomicFilterGroupType.ErrorTrackingIssues]: MaxContextType.ERROR_TRACKING_ISSUE,
}

// A throw while building scene context blanks out ALL of PostHog AI's auto-collected context
// (e.g. PostHog AI reporting it has no dashboard and falling back to search). The selector that
// catches it runs on every read, so dedupe by message to avoid spamming when it keeps
// throwing — but never let the failure stay silent.
const reportedSceneContextErrors = new Set<string>()
const reportSceneContextError = (error: unknown): void => {
    const err = error instanceof Error ? error : new Error(String(error))
    const key = `${err.name}: ${err.message}`
    if (reportedSceneContextErrors.has(key)) {
        return
    }
    // Bound growth in case messages embed dynamic content.
    if (reportedSceneContextErrors.size > 50) {
        reportedSceneContextErrors.clear()
    }
    reportedSceneContextErrors.add(key)
    // eslint-disable-next-line no-console
    console.error(
        '[PostHog AI] Failed to build scene context — it will have no auto-collected context for this scene:',
        err
    )
    posthog.captureException(err, { feature: 'max_scene_context' })
}

export type LoadedEntitiesMap = { dashboard: number[]; insight: string[] }

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxContextLogicValues {
    toolMap: {
        [x: string]: ToolRegistration
    } // maxGlobalLogic
    activeLoadedScene: LoadedScene | null // sceneLogic
    activeSceneId: string | null // sceneLogic
    activeSceneLogic: BuiltLogic | null // sceneLogic
    compiledContext: MaxUIContext | null
    contextActions: MaxActionContext[]
    contextDashboards: MaxDashboardContext[]
    contextErrorTrackingIssues: MaxErrorTrackingIssueContext[]
    contextEvaluations: MaxEvaluationContext[]
    contextEvents: MaxEventContext[]
    contextInsights: MaxInsightContext[]
    contextNotebooks: MaxNotebookContext[]
    contextOptions: MaxContextTaxonomicFilterOption[]
    hasData: boolean
    loadedEntities: LoadedEntitiesMap
    mainTaxonomicGroupType: TaxonomicFilterGroupType
    rawSceneContext: MaxContextItem[]
    sceneContext: MaxContextItem[]
    taxonomicGroupTypes: TaxonomicFilterGroupType[]
    toolContextItems: Array<{
        icon: any
        text: string
    }>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxContextLogicActions {
    locationChanged: ({
        method,
        pathname,
        search,
        searchParams,
        hash,
        hashParams,
        initial,
        url,
        routerState,
    }: LocationChangedPayload) => {
        hash: string
        hashParams: Record<string, any>
        initial: boolean
        method: 'POP' | 'PUSH' | 'REPLACE'
        pathname: string
        routerState: Record<string, any>
        search: string
        searchParams: Record<string, any>
        url: string
    } // router
    addOrUpdateContextAction: (data: ActionType) => {
        data: ActionType
    }
    addOrUpdateContextDashboard: (data: DashboardType) => {
        data: DashboardType
    }
    addOrUpdateContextErrorTrackingIssue: (data: { id: string; name?: string | null }) => {
        data: {
            id: string
            name?: string | null | undefined
        }
    }
    addOrUpdateContextEvaluation: (data: {
        description?: string | null
        evaluation_type: EvaluationRuntime
        hog_source?: string | null
        id: string
        name?: string | null
    }) => {
        data: {
            description?: string | null | undefined
            evaluation_type: EvaluationRuntime
            hog_source?: string | null | undefined
            id: string
            name?: string | null | undefined
        }
    }
    addOrUpdateContextEvent: (data: EventDefinition) => {
        data: EventDefinition
    }
    addOrUpdateContextInsight: (
        data: Partial<InsightModel>,
        filtersOverride?: DashboardFilter,
        variablesOverride?: Record<string, HogQLVariable>
    ) => {
        data: Partial<InsightModel<Node<Record<string, any>>>>
        filtersOverride: DashboardFilter | undefined
        variablesOverride: Record<string, HogQLVariable> | undefined
    }
    addOrUpdateContextNotebook: (data: { short_id: string; title?: string | null }) => {
        data: {
            short_id: string
            title?: string | null | undefined
        }
    }
    handleTaxonomicFilterChange: (
        value: number | string,
        groupType: TaxonomicFilterGroupType,
        item: TaxonomicItem
    ) => {
        groupType: TaxonomicFilterGroupType
        item: TaxonomicItem
        value: number | string
    }
    loadAndProcessDashboard: (data: DashboardItemInfo) => {
        data: DashboardItemInfo
    }
    loadAndProcessInsight: (
        data: InsightItemInfo,
        filtersOverride?: DashboardFilter,
        variablesOverride?: Record<string, HogQLVariable>
    ) => {
        data: InsightItemInfo
        filtersOverride: DashboardFilter | undefined
        variablesOverride: Record<string, HogQLVariable> | undefined
    }
    openContextPicker: () => {
        value: true
    }
    removeContextAction: (id: number | string) => {
        id: number | string
    }
    removeContextDashboard: (id: number | string) => {
        id: number | string
    }
    removeContextErrorTrackingIssue: (id: string) => {
        id: string
    }
    removeContextEvaluation: (id: string) => {
        id: string
    }
    removeContextEvent: (id: number | string) => {
        id: number | string
    }
    removeContextInsight: (id: number | string) => {
        id: number | string
    }
    removeContextNotebook: (id: string) => {
        id: string
    }
    resetContext: () => {
        value: true
    }
    setSelectedContextOption: (value: string) => {
        value: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxContextLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        rawSceneContext: (arg: MaxContextInput[]) => MaxContextItem[]
        sceneContext: (rawSceneContext: any) => MaxContextItem[]
        contextOptions: (sceneContext: any) => MaxContextTaxonomicFilterOption[]
        mainTaxonomicGroupType: (contextOptions: any) => TaxonomicFilterGroupType
        taxonomicGroupTypes: (contextOptions: any) => TaxonomicFilterGroupType[]
        compiledContext: (
            hasData: any,
            contextInsights: any,
            contextDashboards: any,
            contextEvents: any,
            contextActions: any,
            contextErrorTrackingIssues: any,
            contextNotebooks: any,
            contextEvaluations: any,
            sceneContext: any
        ) => MaxUIContext | null
        hasData: (
            contextInsights: any,
            contextDashboards: any,
            contextEvents: any,
            contextActions: any,
            contextErrorTrackingIssues: any,
            contextNotebooks: any,
            contextEvaluations: any,
            sceneContext: any
        ) => boolean
        toolContextItems: (toolMap: any) => Array<{
            icon: any
            text: string
        }>
    }
}

export type maxContextLogicType = MakeLogicType<
    maxContextLogicValues,
    maxContextLogicActions,
    Record<string, any>,
    maxContextLogicMeta
>

export const maxContextLogic = kea<maxContextLogicType>([
    path(['scenes', 'max', 'maxContextLogic']),
    connect(() => ({
        values: [sceneLogic, ['activeSceneId', 'activeSceneLogic', 'activeLoadedScene'], maxGlobalLogic, ['toolMap']],
        actions: [router, ['locationChanged']],
    })),
    actions({
        addOrUpdateContextInsight: (
            data: Partial<InsightModel>,
            filtersOverride?: DashboardFilter,
            variablesOverride?: Record<string, HogQLVariable>
        ) => ({ data, filtersOverride, variablesOverride }),
        addOrUpdateContextDashboard: (data: DashboardType) => ({ data }),
        addOrUpdateContextEvent: (data: EventDefinition) => ({ data }),
        addOrUpdateContextAction: (data: ActionType) => ({ data }),
        addOrUpdateContextErrorTrackingIssue: (data: { id: string; name?: string | null }) => ({ data }),
        addOrUpdateContextNotebook: (data: { short_id: string; title?: string | null }) => ({ data }),
        addOrUpdateContextEvaluation: (data: {
            id: string
            name?: string | null
            description?: string | null
            evaluation_type: EvaluationRuntime
            hog_source?: string | null
        }) => ({ data }),
        removeContextInsight: (id: string | number) => ({ id }),
        removeContextDashboard: (id: string | number) => ({ id }),
        removeContextEvent: (id: string | number) => ({ id }),
        removeContextAction: (id: string | number) => ({ id }),
        removeContextErrorTrackingIssue: (id: string) => ({ id }),
        removeContextNotebook: (id: string) => ({ id }),
        removeContextEvaluation: (id: string) => ({ id }),
        loadAndProcessDashboard: (data: DashboardItemInfo) => ({ data }),
        loadAndProcessInsight: (
            data: InsightItemInfo,
            filtersOverride?: DashboardFilter,
            variablesOverride?: Record<string, HogQLVariable>
        ) => ({ data, filtersOverride, variablesOverride }),
        openContextPicker: true,
        setSelectedContextOption: (value: string) => ({ value }),
        handleTaxonomicFilterChange: (
            value: string | number,
            groupType: TaxonomicFilterGroupType,
            item: TaxonomicItem
        ) => ({ value, groupType, item }),
        resetContext: true,
    }),
    reducers({
        loadedEntities: [
            { dashboard: [], insight: [] } as LoadedEntitiesMap,
            {
                loadAndProcessInsight: (state: LoadedEntitiesMap, { data }: { data: InsightItemInfo }) => ({
                    ...state,
                    insight: [...state.insight, data.id],
                }),
                loadAndProcessDashboard: (state: LoadedEntitiesMap, { data }: { data: DashboardItemInfo }) => ({
                    ...state,
                    dashboard: [...state.dashboard, data.id],
                }),
            },
        ],
        contextInsights: [
            [] as MaxInsightContext[],
            {
                addOrUpdateContextInsight: (state: MaxInsightContext[], { data, filtersOverride, variablesOverride }) =>
                    addOrUpdateEntity(state, insightToMaxContext(data, filtersOverride, variablesOverride)),
                removeContextInsight: (state: MaxInsightContext[], { id }: { id: string | number }) =>
                    removeEntity(state, id),
                resetContext: () => [],
            },
        ],
        contextDashboards: [
            [] as MaxDashboardContext[],
            {
                addOrUpdateContextDashboard: (state: MaxDashboardContext[], { data }: { data: DashboardType }) =>
                    addOrUpdateEntity(state, dashboardToMaxContext(data)),
                removeContextDashboard: (state: MaxDashboardContext[], { id }: { id: string | number }) =>
                    removeEntity(state, id),
                resetContext: () => [],
            },
        ],
        contextEvents: [
            [] as MaxEventContext[],
            {
                addOrUpdateContextEvent: (state: MaxEventContext[], { data }: { data: EventDefinition }) =>
                    addOrUpdateEntity(state, eventToMaxContextPayload(data)),
                removeContextEvent: (state: MaxEventContext[], { id }: { id: string | number }) =>
                    removeEntity(state, id),
                resetContext: () => [],
            },
        ],
        contextActions: [
            [] as MaxActionContext[],
            {
                addOrUpdateContextAction: (state: MaxActionContext[], { data }: { data: ActionType }) =>
                    addOrUpdateEntity(state, actionToMaxContextPayload(data)),
                removeContextAction: (state: MaxActionContext[], { id }: { id: string | number }) =>
                    removeEntity(state, id),
                resetContext: () => [],
            },
        ],
        contextErrorTrackingIssues: [
            [] as MaxErrorTrackingIssueContext[],
            {
                addOrUpdateContextErrorTrackingIssue: (
                    state: MaxErrorTrackingIssueContext[],
                    { data }: { data: { id: string; name?: string | null } }
                ) => addOrUpdateEntity(state, errorTrackingIssueToMaxContextPayload(data)),
                removeContextErrorTrackingIssue: (state: MaxErrorTrackingIssueContext[], { id }: { id: string }) =>
                    removeEntity(state, id),
                resetContext: () => [],
            },
        ],
        contextNotebooks: [
            [] as MaxNotebookContext[],
            {
                addOrUpdateContextNotebook: (
                    state: MaxNotebookContext[],
                    { data }: { data: { short_id: string; title?: string | null } }
                ) => addOrUpdateEntity(state, notebookToMaxContextPayload(data)),
                removeContextNotebook: (state: MaxNotebookContext[], { id }: { id: string }) => removeEntity(state, id),
                resetContext: () => [],
            },
        ],
        contextEvaluations: [
            [] as MaxEvaluationContext[],
            {
                addOrUpdateContextEvaluation: (
                    state: MaxEvaluationContext[],
                    {
                        data,
                    }: {
                        data: {
                            id: string
                            name?: string | null
                            description?: string | null
                            evaluation_type: EvaluationRuntime
                            hog_source?: string | null
                        }
                    }
                ) => addOrUpdateEntity(state, evaluationToMaxContextPayload(data)),
                removeContextEvaluation: (state: MaxEvaluationContext[], { id }: { id: string }) =>
                    removeEntity(state, id),
                resetContext: () => [],
            },
        ],
    }),
    listeners(({ actions, cache, values }) => ({
        openContextPicker: () => {
            posthog.capture('max context picker opened', {
                has_page_context: values.contextOptions.length > 0,
            })
            dashboardsModel.mount()
            dashboardsModel.actions.loadDashboardsIfNeeded()
        },
        locationChanged: () => {
            // Don't reset context if the only change is the side panel opening/closing
            const currentLocation = router.values.location
            const currentHashParams = router.values.hashParams || {}
            const currentSearchParams = router.values.searchParams || {}
            const previousLocation = cache.previousLocation

            cache.previousLocation = {
                location: currentLocation,
                hashParams: currentHashParams,
                searchParams: currentSearchParams,
            }

            if (!previousLocation) {
                return
            }

            const shouldResetContext = (): void => {
                actions.resetContext()
            }

            // Always reset context if pathname changed
            if (currentLocation?.pathname !== previousLocation.location?.pathname) {
                shouldResetContext()
                return
            }

            // Check if search params changed (excluding 'chat' parameter)
            const currentSearchParamsWithoutChat = { ...currentSearchParams }
            delete currentSearchParamsWithoutChat.chat
            const previousSearchParamsWithoutChat = { ...previousLocation.searchParams }
            delete previousSearchParamsWithoutChat.chat

            if (!objectsEqual(currentSearchParamsWithoutChat, previousSearchParamsWithoutChat)) {
                shouldResetContext()
                return
            }

            // Check if only panel parameter changed in hash params
            const currentNonPanelKeys = Object.keys(currentHashParams).filter((k) => k !== 'panel')
            const previousNonPanelKeys = Object.keys(previousLocation.hashParams || {}).filter((k) => k !== 'panel')

            // Check if non-panel keys are the same
            const sameKeys =
                currentNonPanelKeys.length === previousNonPanelKeys.length &&
                currentNonPanelKeys.every(
                    (key) =>
                        previousNonPanelKeys.includes(key) &&
                        currentHashParams[key] === (previousLocation.hashParams || {})[key]
                )

            if (!sameKeys) {
                shouldResetContext()
            }
        },
        loadAndProcessDashboard: async ({ data }: { data: DashboardItemInfo }, breakpoint) => {
            let dashboard = data.preloaded

            if (!dashboard || !dashboard.tiles) {
                const dashboardModule = await import('scenes/dashboard/dashboardLogic').catch((error) => {
                    posthog.captureException(error, { feature: 'max_context_dashboard' })
                    lemonToast.error('Could not load the dashboard. Try again.')
                    return null
                })
                if (!dashboardModule) {
                    return
                }
                const { DashboardLoadAction, dashboardLogic } = dashboardModule
                const dashboardLogicInstance = dashboardLogic.build({ id: data.id })
                dashboardLogicInstance.mount()

                try {
                    dashboardLogicInstance.actions.loadDashboard({ action: DashboardLoadAction.InitialLoad })

                    await breakpoint(50)
                    while (!dashboardLogicInstance.values.dashboard) {
                        await breakpoint(50)
                    }

                    dashboard = dashboardLogicInstance.values.dashboard

                    // Wait for dashboard items to refresh for cached insights
                    while (
                        Object.values(dashboardLogicInstance.values.refreshStatus).some(
                            (status: RefreshStatus) => status.loading
                        )
                    ) {
                        await breakpoint(50)
                    }
                } finally {
                    dashboardLogicInstance.unmount()
                }
            }

            if (dashboard) {
                actions.addOrUpdateContextDashboard(dashboard)
            }
        },
        loadAndProcessInsight: async ({ data, filtersOverride, variablesOverride }, breakpoint) => {
            let insight = data.preloaded

            if (!insight || !insight.query) {
                const insightLogicInstance = insightLogic.build({
                    dashboardItemId: undefined,
                    filtersOverride,
                    variablesOverride,
                })
                insightLogicInstance.mount()

                try {
                    insightLogicInstance.actions.loadInsight(data.id)

                    await breakpoint(50)
                    while (!insightLogicInstance.values.insight.query) {
                        await breakpoint(50)
                    }

                    insight = insightLogicInstance.values.insight as InsightModel
                } finally {
                    insightLogicInstance.unmount()
                }
            }

            if (insight) {
                actions.addOrUpdateContextInsight(insight, filtersOverride, variablesOverride)
            }
        },
        handleTaxonomicFilterChange: async ({
            groupType,
            item,
        }: {
            groupType: TaxonomicFilterGroupType
            item: TaxonomicItem
        }) => {
            posthog.capture('max context added', {
                group_type: groupType,
                context_type:
                    groupType === TaxonomicFilterGroupType.MaxAIContext
                        ? (item as MaxContextTaxonomicFilterOption).type
                        : PICKER_GROUP_CONTEXT_TYPES[groupType],
                from_page_tab: groupType === TaxonomicFilterGroupType.MaxAIContext,
            })
            try {
                if (groupType === TaxonomicFilterGroupType.Events) {
                    actions.addOrUpdateContextEvent(item as EventDefinition)
                    return
                } else if (groupType === TaxonomicFilterGroupType.Actions) {
                    actions.addOrUpdateContextAction(item as ActionType)
                    return
                } else if (groupType === TaxonomicFilterGroupType.ErrorTrackingIssues) {
                    const errorItem = item as { id: string; name?: string }
                    actions.addOrUpdateContextErrorTrackingIssue({
                        id: errorItem.id,
                        name: errorItem.name ?? null,
                    })
                    return
                } else if (groupType === TaxonomicFilterGroupType.Notebooks) {
                    const notebookItem = item as NotebookListItemType
                    actions.addOrUpdateContextNotebook({
                        short_id: notebookItem.short_id,
                        title: notebookItem.title ?? null,
                    })
                    return
                }

                // Parse item information based on selection type
                const itemInfo = (() => {
                    // Handle MaxAI context with string values like "insight_123" or "dashboard_456"
                    if (groupType === TaxonomicFilterGroupType.MaxAIContext) {
                        const _item = item as MaxContextTaxonomicFilterOption
                        if (_item.type === MaxContextType.INSIGHT) {
                            return {
                                type: MaxContextType.INSIGHT,
                                id: _item.value,
                                preloaded: null,
                            }
                        }
                        if (_item.type === MaxContextType.DASHBOARD) {
                            return isNaN(_item.value as number)
                                ? null
                                : {
                                      type: MaxContextType.DASHBOARD,
                                      id: _item.value,
                                      preloaded: null,
                                  }
                        }
                        if (_item.type === MaxContextType.ERROR_TRACKING_ISSUE) {
                            actions.addOrUpdateContextErrorTrackingIssue({
                                id: _item.value as string,
                                name: _item.name ?? null,
                            })
                            return null // Already handled
                        }
                    }

                    // Handle direct selections
                    if (groupType === TaxonomicFilterGroupType.Dashboards) {
                        const dashboard = item as DashboardType
                        return {
                            type: MaxContextType.DASHBOARD,
                            id: dashboard.id,
                            preloaded: dashboard as DashboardType,
                        }
                    }

                    if (groupType === TaxonomicFilterGroupType.Insights) {
                        const insight = item as InsightModel
                        return {
                            type: MaxContextType.INSIGHT,
                            id: insight.short_id,
                            preloaded: insight,
                        }
                    }

                    return null
                })()

                if (!itemInfo) {
                    return
                }

                // Handle dashboard selection
                if (itemInfo.type === MaxContextType.DASHBOARD) {
                    actions.loadAndProcessDashboard({
                        id: itemInfo.id as number,
                        preloaded: itemInfo.preloaded as DashboardType | null,
                    })
                }

                // Handle insight selection
                if (itemInfo.type === MaxContextType.INSIGHT) {
                    let filtersOverride: DashboardFilter | undefined = undefined
                    let variablesOverride: Record<string, HogQLVariable> | undefined = undefined

                    // This is an "on this page" insight selection. Look for and add possible applied filters.
                    if (groupType === TaxonomicFilterGroupType.MaxAIContext) {
                        const logic = insightSceneLogic.findAllMounted().find((l) => l.values.insightId === itemInfo.id)
                        if (logic) {
                            filtersOverride = logic.values.filtersOverride ?? undefined
                            variablesOverride = logic.values.variablesOverride ?? undefined
                        }
                    }

                    actions.loadAndProcessInsight(
                        {
                            id: itemInfo.id as InsightShortId,
                            preloaded: itemInfo.preloaded as InsightModel | null,
                        },
                        filtersOverride,
                        variablesOverride
                    )
                }
            } catch (error) {
                console.error('Error handling taxonomic filter change:', error)
            }
        },
    })),
    selectors({
        // Automatically collect context from active scene logic
        // This selector checks if the current scene logic has a 'maxContext' selector
        // and if so, calls it to get context items for MaxAI
        rawSceneContext: [
            () => [
                // Pass scene selector through to get automatic updates when scene changes
                (state): MaxContextInput[] => {
                    const activeSceneLogic = sceneLogic.selectors.activeSceneLogic(state, {})

                    if (activeSceneLogicHasMaxContext(activeSceneLogic)) {
                        try {
                            const activeLoadedScene = sceneLogic.selectors.activeLoadedScene(state, {})
                            return activeSceneLogic.selectors.maxContext(
                                state,
                                activeLoadedScene?.paramsToProps?.(activeLoadedScene?.sceneParams) || {}
                            )
                        } catch (error) {
                            // A logic caught mid-unmount throws a benign "Can not find path" — treat
                            // that as a transient race and skip it quietly. Surface everything else
                            // so genuine context-build bugs don't get swallowed.
                            if (!(error instanceof Error && error.message.includes('Can not find path'))) {
                                reportSceneContextError(error)
                            }
                        }
                    }
                    return []
                },
            ],
            (context: MaxContextItem[]): MaxContextItem[] => context,
            { resultEqualityCheck: objectsEqual },
        ],
        sceneContext: [
            (s: any) => [s.rawSceneContext],
            (rawSceneContext: MaxContextInput[]): MaxContextItem[] => {
                return rawSceneContext
                    .map((item): MaxContextItem | null => {
                        switch (item.type) {
                            case MaxContextType.INSIGHT:
                                return insightToMaxContext(item.data, item.filtersOverride, item.variablesOverride)
                            case MaxContextType.DASHBOARD:
                                return dashboardToMaxContext(item.data)
                            case MaxContextType.EVENT:
                                return eventToMaxContextPayload(item.data)
                            case MaxContextType.ACTION:
                                return actionToMaxContextPayload(item.data)
                            case MaxContextType.ERROR_TRACKING_ISSUE:
                                return errorTrackingIssueToMaxContextPayload(item.data)
                            case MaxContextType.NOTEBOOK:
                                return notebookToMaxContextPayload(item.data)
                            case MaxContextType.EVALUATION:
                                return evaluationToMaxContextPayload(item.data)
                            default:
                                return null
                        }
                    })
                    .filter((item): item is MaxContextItem => item !== null)
            },
        ],
        contextOptions: [
            (s: any) => [s.sceneContext],
            (sceneContext: MaxContextItem[]): MaxContextTaxonomicFilterOption[] => {
                const options: MaxContextTaxonomicFilterOption[] = []

                sceneContext.forEach((item) => {
                    if (item.type == MaxContextType.INSIGHT) {
                        options.push({
                            id: item.id.toString(),
                            name: item.name || `Insight ${item.id}`,
                            value: item.id,
                            type: MaxContextType.INSIGHT,
                            icon: IconGraph,
                        })
                    } else if (item.type == MaxContextType.DASHBOARD) {
                        options.push({
                            id: item.id.toString(),
                            name: item.name || `Dashboard ${item.id}`,
                            value: item.id,
                            type: MaxContextType.DASHBOARD,
                            icon: IconDashboard,
                        })
                        item.insights.forEach((insight) => {
                            options.push({
                                id: insight.id.toString(),
                                name: insight.name || `Insight ${insight.id}`,
                                value: insight.id,
                                type: MaxContextType.INSIGHT,
                                icon: IconGraph,
                            })
                        })
                    } else if (item.type == MaxContextType.ERROR_TRACKING_ISSUE) {
                        options.push({
                            id: item.id,
                            name: item.name || `Error ${item.id}`,
                            value: item.id,
                            type: MaxContextType.ERROR_TRACKING_ISSUE,
                            icon: IconBug,
                        })
                    } else if (item.type == MaxContextType.NOTEBOOK) {
                        options.push({
                            id: item.id.toString(),
                            name: item.name || `Notebook ${item.id}`,
                            value: item.id,
                            type: MaxContextType.NOTEBOOK,
                            icon: IconNotebook,
                        })
                    } else if (item.type == MaxContextType.EVALUATION) {
                        options.push({
                            id: item.id,
                            name: item.name || `Evaluation ${item.id}`,
                            value: item.id,
                            type: MaxContextType.EVALUATION,
                            icon: IconCheckbox,
                        })
                    }
                })

                return options
            },
        ],
        mainTaxonomicGroupType: [
            (s: any) => [s.contextOptions],
            (contextOptions: MaxContextTaxonomicFilterOption[]): TaxonomicFilterGroupType => {
                return contextOptions.length > 0
                    ? TaxonomicFilterGroupType.MaxAIContext
                    : TaxonomicFilterGroupType.Events
            },
        ],
        taxonomicGroupTypes: [
            (s: any) => [s.contextOptions],
            (contextOptions: MaxContextTaxonomicFilterOption[]): TaxonomicFilterGroupType[] => {
                const groupTypes: TaxonomicFilterGroupType[] = []
                if (contextOptions.length > 0) {
                    groupTypes.push(TaxonomicFilterGroupType.MaxAIContext)
                }
                groupTypes.push(
                    TaxonomicFilterGroupType.Events,
                    TaxonomicFilterGroupType.Actions,
                    TaxonomicFilterGroupType.Insights,
                    TaxonomicFilterGroupType.Dashboards,
                    TaxonomicFilterGroupType.Notebooks,
                    TaxonomicFilterGroupType.ErrorTrackingIssues
                )
                return groupTypes
            },
        ],
        compiledContext: [
            (s: any) => [
                s.hasData,
                s.contextInsights,
                s.contextDashboards,
                s.contextEvents,
                s.contextActions,
                s.contextErrorTrackingIssues,
                s.contextNotebooks,
                s.contextEvaluations,
                s.sceneContext,
            ],
            (
                hasData: boolean,
                contextInsights: MaxInsightContext[],
                contextDashboards: MaxDashboardContext[],
                contextEvents: MaxEventContext[],
                contextActions: MaxActionContext[],
                contextErrorTrackingIssues: MaxErrorTrackingIssueContext[],
                contextNotebooks: MaxNotebookContext[],
                contextEvaluations: MaxEvaluationContext[],
                sceneContext: MaxContextItem[]
            ): MaxUIContext | null => {
                const context: MaxUIContext = {}

                // Helper to filter scene context by type
                const getSceneItems = <T extends MaxContextItem>(type: MaxContextType): T[] =>
                    sceneContext.filter((item): item is T => item.type === type)

                // Add context dashboards (combine manual context + scene context)
                const sceneDashboards = getSceneItems<MaxDashboardContext>(MaxContextType.DASHBOARD)
                const allDashboards = [...contextDashboards, ...sceneDashboards]

                if (allDashboards.length > 0) {
                    context.dashboards = allDashboards
                }

                // Add insights, filtering out those already in dashboards
                // Combine manual context, scene context, and active insights
                const sceneInsights = getSceneItems<MaxInsightContext>(MaxContextType.INSIGHT)
                const allInsights = [...contextInsights, ...sceneInsights]

                if (allInsights.length > 0) {
                    // Get all insight IDs from dashboards to filter out duplicates
                    const dashboardInsightIds = new Set(
                        (context.dashboards || []).flatMap((dashboard) =>
                            dashboard.insights.map((insight) => insight.id)
                        )
                    )

                    // Filter out insights that are already included in dashboards
                    context.insights = allInsights.filter((insight) => !dashboardInsightIds.has(insight.id))
                    if (context.insights.length === 0) {
                        delete context.insights
                    }
                }

                // Deduplicate dashboards by ID
                if (context.dashboards) {
                    const uniqueDashboards = new Map()
                    context.dashboards.forEach((dashboard) => {
                        uniqueDashboards.set(dashboard.id, dashboard)
                    })
                    context.dashboards = Array.from(uniqueDashboards.values())
                }

                // Deduplicate insights by ID
                if (context.insights) {
                    const uniqueInsights = new Map()
                    context.insights.forEach((insight) => {
                        uniqueInsights.set(insight.id, insight)
                    })
                    context.insights = Array.from(uniqueInsights.values())
                }

                // Add events
                const sceneEvents = getSceneItems<MaxEventContext>(MaxContextType.EVENT)
                const allEvents = [...contextEvents, ...sceneEvents]
                if (allEvents.length > 0) {
                    // Deduplicate by ID
                    const uniqueEvents = new Map()
                    allEvents.forEach((event) => uniqueEvents.set(event.id, event))
                    context.events = Array.from(uniqueEvents.values())
                }

                // Add actions
                const sceneActions = getSceneItems<MaxActionContext>(MaxContextType.ACTION)
                const allActions = [...contextActions, ...sceneActions]
                if (allActions.length > 0) {
                    // Deduplicate by ID
                    const uniqueActions = new Map()
                    allActions.forEach((action) => uniqueActions.set(action.id, action))
                    context.actions = Array.from(uniqueActions.values())
                }

                // Add error tracking issues (combine manual selections + auto-added from scene context)
                const sceneErrorTrackingIssues = getSceneItems<MaxErrorTrackingIssueContext>(
                    MaxContextType.ERROR_TRACKING_ISSUE
                )
                const allErrorTrackingIssues = [...contextErrorTrackingIssues, ...sceneErrorTrackingIssues]
                if (allErrorTrackingIssues.length > 0) {
                    // Deduplicate by ID
                    const uniqueIssues = new Map<string, MaxErrorTrackingIssueContext>()
                    allErrorTrackingIssues.forEach((issue) => uniqueIssues.set(issue.id, issue))
                    context.error_tracking_issues = Array.from(uniqueIssues.values())
                }

                // Add notebooks
                const sceneNotebooks = getSceneItems<MaxNotebookContext>(MaxContextType.NOTEBOOK)
                const allNotebooks = [...contextNotebooks, ...sceneNotebooks]
                if (allNotebooks.length > 0) {
                    const uniqueNotebooks = new Map<string, MaxNotebookContext>()
                    allNotebooks.forEach((nb) => uniqueNotebooks.set(nb.id, nb))
                    context.notebooks = Array.from(uniqueNotebooks.values())
                }

                // Add evaluations (combine manual selections + auto-added from scene context)
                const sceneEvaluations = sceneContext.filter(
                    (item): item is MaxEvaluationContext => item.type === MaxContextType.EVALUATION
                )
                const allEvaluations = [...contextEvaluations, ...sceneEvaluations]
                if (allEvaluations.length > 0) {
                    const uniqueEvaluations = new Map<string, MaxEvaluationContext>()
                    allEvaluations.forEach((evaluation) => uniqueEvaluations.set(evaluation.id, evaluation))
                    context.evaluations = Array.from(uniqueEvaluations.values())
                }

                return hasData ? context : null
            },
        ],
        hasData: [
            (s: any) => [
                s.contextInsights,
                s.contextDashboards,
                s.contextEvents,
                s.contextActions,
                s.contextErrorTrackingIssues,
                s.contextNotebooks,
                s.contextEvaluations,
                s.sceneContext,
            ],
            (
                contextInsights: MaxInsightContext[],
                contextDashboards: MaxDashboardContext[],
                contextEvents: MaxEventContext[],
                contextActions: MaxActionContext[],
                contextErrorTrackingIssues: MaxErrorTrackingIssueContext[],
                contextNotebooks: MaxNotebookContext[],
                contextEvaluations: MaxEvaluationContext[],
                sceneContext: MaxContextItem[]
            ): boolean => {
                return [
                    contextInsights,
                    contextDashboards,
                    contextEvents,
                    contextActions,
                    contextErrorTrackingIssues,
                    contextNotebooks,
                    contextEvaluations,
                    sceneContext,
                ].some((arr) => arr.length > 0)
            },
        ],
        toolContextItems: [
            (s: any) => [s.toolMap],
            (toolMap: any): Array<{ text: string; icon: any }> => {
                const items: Array<{ text: string; icon: any }> = []
                const addedNames = new Set<string>()

                // First, add all tool context items (they have precedence)
                Object.values(toolMap).forEach((tool: any) => {
                    if (tool.contextDescription) {
                        const itemName = tool.contextDescription.text.toLowerCase()
                        if (!addedNames.has(itemName)) {
                            items.push(tool.contextDescription)
                            addedNames.add(itemName)
                        }
                    }
                })

                return items
            },
        ],
    }),
    afterMount(({ cache }) => {
        cache.previousLocation = {
            location: router.values.location,
            hashParams: router.values.hashParams,
            searchParams: router.values.searchParams,
        }
    }),
])