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.

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

import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'
import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { Conversation, ConversationDetail, SidePanelTab } from '~/types'

import { conversationsDestroy } from 'products/posthog_ai/frontend/generated/api'
import { taskEventsLogic } from 'products/posthog_ai/frontend/logics/taskEventsLogic'
import { tasksLogic } from 'products/posthog_ai/frontend/logics/tasksLogic'

import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { OrganizationType } from '../../types'
import type { SceneConfig } from '../sceneTypes'
import { TOOL_DEFINITIONS, ToolRegistration } from './max-constants'
import { maxLogic, mergeConversationHistory, mergeConversations, sidePanelMaxLogic } from './maxLogic'

// Keep this stored across all projects, only display this once per device
const AI_LIABILITY_NOTICE_STORAGE_KEY = 'posthog_ai_liability_notice_dismissed'

/** Tools available everywhere. These CAN be shadowed by contextual tools for scene-specific handling (e.g. to intercept insight creation). */
export const STATIC_TOOLS: ToolRegistration[] = [
    {
        identifier: 'filter_session_recordings' as const,
        name: TOOL_DEFINITIONS['filter_session_recordings'].name,
        description: TOOL_DEFINITIONS['filter_session_recordings'].description,
    },
    {
        identifier: 'web_search',
        name: TOOL_DEFINITIONS['web_search'].name,
        description: TOOL_DEFINITIONS['web_search'].description,
    },
    {
        identifier: 'search' as const,
        name: TOOL_DEFINITIONS['search'].name,
        description: TOOL_DEFINITIONS['search'].description,
    },
    {
        identifier: 'create_task' as const,
        name: TOOL_DEFINITIONS['create_task'].name,
        description: TOOL_DEFINITIONS['create_task'].description,
    },
    {
        identifier: 'run_task' as const,
        name: TOOL_DEFINITIONS['run_task'].name,
        description: TOOL_DEFINITIONS['run_task'].description,
    },
    {
        identifier: 'get_task_run' as const,
        name: TOOL_DEFINITIONS['get_task_run'].name,
        description: TOOL_DEFINITIONS['get_task_run'].description,
    },
    {
        identifier: 'get_task_run_logs' as const,
        name: TOOL_DEFINITIONS['get_task_run_logs'].name,
        description: TOOL_DEFINITIONS['get_task_run_logs'].description,
    },
    {
        identifier: 'list_tasks' as const,
        name: TOOL_DEFINITIONS['list_tasks'].name,
        description: TOOL_DEFINITIONS['list_tasks'].description,
    },
    {
        identifier: 'list_task_runs' as const,
        name: TOOL_DEFINITIONS['list_task_runs'].name,
        description: TOOL_DEFINITIONS['list_task_runs'].description,
    },
]

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxGlobalLogicValues {
    aiAccessRequested: boolean // aiConsentLogic
    dataProcessingAccepted: boolean // aiConsentLogic
    dataProcessingApprovalDisabledReason: string | null // aiConsentLogic
    dataProcessingDismissed: boolean // aiConsentLogic
    requestingAiAccess: boolean // aiConsentLogic
    effectivePhaiView: PhaiViewMode // aiShellLogic
    isMaxAvailable: boolean // aiShellLogic
    isPhaiSandboxFlagOn: boolean // aiShellLogic
    phaiViewMode: PhaiViewMode // aiShellLogic
    registeredToolMap: Record<string, ToolRegistration> // aiShellLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentOrganization: OrganizationType | null // organizationLogic
    sceneConfig: SceneConfig | null // sceneLogic
    sceneId: string | null // sceneLogic
    selectedTab: SidePanelTab | null // sidePanelStateLogic
    sidePanelOpen: boolean // sidePanelStateLogic
    currentTeamIdStrict: number | string // teamLogic
    availableStaticTools: ToolRegistration[]
    conversationHistory: ConversationDetail[]
    conversationHistoryLoadedAt: number | null
    conversationHistoryLoading: boolean
    currentConversationId: string | null
    editInsightToolRegistered: true
    isOrganizationCreatedRecently: boolean
    liabilityNoticeDismissed: boolean
    shouldShowLiabilityNotice: boolean
    toolMap: {
        [x: string]: ToolRegistration
    }
    toolSuggestions: string[]
    tools: ToolRegistration[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxGlobalLogicActions {
    acceptDataProcessing: (
        testOnlyOverride?: boolean | undefined,
        resumeUrl?: string | undefined
    ) => {
        resumeUrl: string | undefined
        testOnlyOverride: boolean | undefined
    } // aiConsentLogic
    dismissDataProcessing: () => {
        value: true
    } // aiConsentLogic
    requestAiAccess: () => {
        value: true
    } // aiConsentLogic
    askSidePanelMax: (prompt: string) => {
        prompt: string
    } // aiShellLogic
    deregisterTool: (key: string) => {
        key: string
    } // aiShellLogic
    registerTool: (tool: ToolRegistration) => {
        tool: ToolRegistration
    } // aiShellLogic
    setPhaiViewMode: (mode: PhaiViewMode) => {
        mode: PhaiViewMode
    } // aiShellLogic
    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
    openSidePanel: (
        tab: SidePanelTab,
        options?: string | undefined
    ) => {
        options: string | undefined
        tab: SidePanelTab
    } // sidePanelStateLogic
    deleteConversation: (id: string) => {
        id: string
    }
    dismissLiabilityNotice: () => {
        value: true
    }
    loadConversation: (conversationId: string) => string
    loadConversationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadConversationHistory: (_?: {
        /** If true, the current thread will not be updated with the retrieved conversation. */
        doNotUpdateCurrentThread?: boolean
    }) => {
        doNotUpdateCurrentThread?: boolean
    }
    loadConversationHistoryFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadConversationHistorySuccess: (
        conversationHistory: ConversationDetail[],
        payload?: {
            doNotUpdateCurrentThread?: boolean
        }
    ) => {
        conversationHistory: ConversationDetail[]
        payload?: {
            doNotUpdateCurrentThread?: boolean
        }
    }
    loadConversationSuccess: (
        conversationHistory: ConversationDetail[],
        payload?: string
    ) => {
        conversationHistory: ConversationDetail[]
        payload?: string
    }
    openSidePanelMax: (conversationId?: string) => {
        conversationId: string | undefined
    }
    openSidePanelMaxWithTaskBind: (taskId: string) => {
        taskId: string
    }
    prependOrReplaceConversation: (conversation: Conversation | ConversationDetail) => {
        conversation: Conversation | ConversationDetail
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxGlobalLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        currentConversationId: (searchParams: Record<string, any>) => string | null
        isOrganizationCreatedRecently: (currentOrganization: OrganizationType | null) => boolean
        shouldShowLiabilityNotice: (
            isOrganizationCreatedRecently: boolean,
            liabilityNoticeDismissed: boolean
        ) => boolean
        availableStaticTools: (featureFlags: FeatureFlagsSet) => ToolRegistration[]
        toolMap: (
            registeredToolMap: Record<string, ToolRegistration>,
            availableStaticTools: ToolRegistration[]
        ) => {
            [x: string]: ToolRegistration
        }
        tools: (toolMap: { [x: string]: ToolRegistration }) => ToolRegistration[]
        editInsightToolRegistered: (registeredToolMap: Record<string, ToolRegistration>) => true
        toolSuggestions: (tools: ToolRegistration[]) => string[]
    }
}

export type maxGlobalLogicType = MakeLogicType<
    maxGlobalLogicValues,
    maxGlobalLogicActions,
    Record<string, any>,
    maxGlobalLogicMeta
>

export const maxGlobalLogic = kea<maxGlobalLogicType>([
    path(['scenes', 'max', 'maxGlobalLogic']),
    connect(() => ({
        values: [
            aiShellLogic,
            ['effectivePhaiView', 'isMaxAvailable', 'isPhaiSandboxFlagOn', 'phaiViewMode', 'registeredToolMap'],
            organizationLogic,
            ['currentOrganization'],
            sceneLogic,
            ['sceneId', 'sceneConfig'],
            teamLogic,
            ['currentTeamIdStrict'],
            featureFlagLogic,
            ['featureFlags'],
            sidePanelStateLogic,
            ['sidePanelOpen', 'selectedTab'],
            aiConsentLogic,
            [
                'dataProcessingAccepted',
                'dataProcessingDismissed',
                'dataProcessingApprovalDisabledReason',
                'aiAccessRequested',
                'requestingAiAccess',
            ],
        ],
        actions: [
            router,
            ['locationChanged'],
            sidePanelStateLogic,
            ['openSidePanel'],
            aiConsentLogic,
            ['acceptDataProcessing', 'dismissDataProcessing', 'requestAiAccess'],
            aiShellLogic,
            ['setPhaiViewMode', 'askSidePanelMax', 'registerTool', 'deregisterTool'],
        ],
    })),
    actions({
        openSidePanelMax: (conversationId?: string) => ({ conversationId }),
        openSidePanelMaxWithTaskBind: (taskId: string) => ({ taskId }),
        prependOrReplaceConversation: (conversation: ConversationDetail | Conversation) => ({ conversation }),
        deleteConversation: (id: string) => ({ id }),
        dismissLiabilityNotice: true,
    }),

    loaders(({ values }) => ({
        conversationHistory: [
            [] as ConversationDetail[],
            {
                loadConversationHistory: async (
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars -- Used for conversation restoration
                    _?: {
                        /** If true, the current thread will not be updated with the retrieved conversation. */
                        doNotUpdateCurrentThread?: boolean
                    }
                ) => {
                    const response = await api.conversations.list()
                    return response.results.map((conversation) =>
                        mergeConversations(
                            conversation,
                            values.conversationHistory.find((existing) => existing.id === conversation.id)
                        )
                    )
                },

                loadConversation: async (conversationId: string) => {
                    const response = await api.conversations.get(conversationId)
                    if (!response) {
                        // The endpoint can return an empty body; a null in the history crashes consumers
                        return values.conversationHistory
                    }
                    const itemIndex = values.conversationHistory.findIndex((c) => c.id === conversationId)

                    if (itemIndex !== -1) {
                        return [
                            ...values.conversationHistory.slice(0, itemIndex),
                            response,
                            ...values.conversationHistory.slice(itemIndex + 1),
                        ]
                    }
                    return [response, ...values.conversationHistory]
                },
            },
        ],
    })),

    reducers({
        conversationHistory: {
            prependOrReplaceConversation: (state, { conversation }) => {
                return mergeConversationHistory(state, conversation)
            },
        },
        conversationHistoryLoadedAt: [
            null as number | null,
            {
                loadConversationHistorySuccess: () => Date.now(),
            },
        ],
        liabilityNoticeDismissed: [
            false,
            { persist: true, storageKey: AI_LIABILITY_NOTICE_STORAGE_KEY },
            {
                dismissLiabilityNotice: () => true,
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        // A chat and its task are deleted together on the server, so removing a task from the merged
        // list must drop the chat row too, or the chat resurfaces as a row of its own.
        [taskEventsLogic.actionTypes.taskDeleted]: () => {
            actions.loadConversationHistory()
        },
        openSidePanelMax: ({ conversationId }) => {
            if (!values.sidePanelOpen || values.selectedTab !== SidePanelTab.Max) {
                actions.openSidePanel(SidePanelTab.Max)
            }
            if (conversationId) {
                sidePanelMaxLogic().actions.openConversation(conversationId)
            }
        },
        // Open the side panel on a fresh chat bound to a sandbox Task (inbox "Open task" — in-place,
        // not a new tab). The side panel doesn't sync the URL, so the binding is seeded directly here
        // rather than via the `bind_task` param the scene route reads. `setPendingBindTaskId` runs
        // after `startNewConversation`, which clears it.
        openSidePanelMaxWithTaskBind: ({ taskId }) => {
            if (!values.sidePanelOpen || values.selectedTab !== SidePanelTab.Max) {
                actions.openSidePanel(SidePanelTab.Max)
            }
            const logic = sidePanelMaxLogic()
            logic.actions.startNewConversation()
            logic.actions.setPendingBindTaskId(taskId)
        },
        loadConversationHistoryFailure: ({ errorObject }) => {
            lemonToast.error(errorObject?.data?.detail || 'Failed to load conversation history.')
        },
        deleteConversation: async ({ id }) => {
            try {
                await conversationsDestroy(String(values.currentTeamIdStrict), id)
                if (values.currentConversationId === id) {
                    router.actions.push(urls.aiHistory())
                }
                for (const logic of maxLogic.findAllMounted()) {
                    if (logic.values.conversationId === id) {
                        logic.actions.startNewConversation()
                    }
                }
                actions.loadConversationHistory()
                // The chat's task is deleted with it; the merged list must not keep its task row.
                const tasks = tasksLogic.findMounted()
                if (tasks) {
                    tasks.actions.loadTasks(tasks.values.taskListParams)
                }
            } catch {
                lemonToast.error('Failed to delete chat')
            }
        },
    })),
    afterMount(({ actions }) => {
        actions.loadConversationHistory()
    }),

    selectors({
        currentConversationId: [
            () => [router.selectors.searchParams],
            (searchParams: Record<string, any>): string | null => searchParams?.chat ?? null,
        ],
        isOrganizationCreatedRecently: [
            (s) => [s.currentOrganization],
            (currentOrganization: null | import('~/types').OrganizationType): boolean => {
                const orgCreatedAt = currentOrganization?.created_at
                return orgCreatedAt ? dayjs().diff(dayjs(orgCreatedAt), 'day') <= 15 : false
            },
        ],
        shouldShowLiabilityNotice: [
            (s) => [s.isOrganizationCreatedRecently, s.liabilityNoticeDismissed],
            (isOrganizationCreatedRecently: boolean, liabilityNoticeDismissed: boolean): boolean =>
                isOrganizationCreatedRecently && !liabilityNoticeDismissed,
        ],
        availableStaticTools: [
            (s) => [s.featureFlags],
            (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): ToolRegistration[] => {
                const staticTools = STATIC_TOOLS.filter((tool) => {
                    // Only register the static tools that either aren't flagged or have their flag enabled
                    const toolDefinition = TOOL_DEFINITIONS[tool.identifier]
                    return !toolDefinition.flag || featureFlags[toolDefinition.flag]
                })
                return staticTools
            },
        ],
        toolMap: [
            (s) => [s.registeredToolMap, s.availableStaticTools],
            (registeredToolMap: Record<string, ToolRegistration>, availableStaticTools: ToolRegistration[]) => ({
                ...Object.fromEntries(availableStaticTools.map((tool) => [tool.identifier, tool])),
                ...registeredToolMap,
            }),
        ],
        tools: [
            (s) => [s.toolMap],
            (toolMap: { [x: string]: ToolRegistration }): ToolRegistration[] => Object.values(toolMap),
        ],
        editInsightToolRegistered: [
            (s) => [s.registeredToolMap],
            (registeredToolMap: Record<string, ToolRegistration>) => !!registeredToolMap.create_insight,
        ],
        toolSuggestions: [
            (s) => [s.tools],
            (tools: ToolRegistration[]): string[] => {
                const suggestions: string[] = []
                for (const tool of tools) {
                    if (tool.suggestions) {
                        suggestions.push(...tool.suggestions)
                    }
                }
                return suggestions
            },
        ],
    }),
])