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.

16.7 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'

import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import posthog from 'lib/posthog-typed'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { autoRunMaxPrompt } from 'scenes/max/maxPrompt'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import { SidePanelTab } from '~/types'

import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'
import { mcpAnalyticsSessionsActivityOverview } from '../generated/api'
import type { MCPActivityRecentCallApi } from '../generated/api.schemas'
import { mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'
import type { MCPOnboardingSignals, MCPOnboardingState } from '../mcpAnalyticsOnboardingLogic'
import {
    type MCPSetupExitReason,
    type MCPSetupPath,
    type MCPSetupStep,
    type MCPSetupTrigger,
    SETUP_PARAM,
    SETUP_STEP_PARAM,
    connectStateFor,
    parseSetupPath,
    setupStepFor,
} from './setupMode'
import type { MCPConnectState } from './setupMode'

/** The two calls the reveal shows as cards, plus the newer ones its calls panel lists beside them. */
const RECENT_CALLS = 7

// Faster than the onboarding logic's own poll: someone in setup mode is watching for the moment
// their server answers. Both queries stay cheap while the project has a handful of events.
const CONNECT_POLL_MS = 5000
const FIRST_CALL_POLL_MS = 10000

// The gate swaps the empty state for the scene when the first call lands, which remounts this
// logic, and a reload remounts it too. Module scope keeps "opened" and "step viewed" to one event
// per real change across those remounts, the way the wizard-sync telemetry guards do.
const tracking = {
    opened: false,
    lastViewedStep: null as string | null,
    // What an exit event reports when setup mode closes through the URL, after its own params are gone.
    lastViewed: null as { path: MCPSetupPath | null; step: MCPSetupStep | null } | null,
}

function resetTracking(): void {
    tracking.opened = false
    tracking.lastViewedStep = null
    tracking.lastViewed = null
}

export function resetSetupModeTrackingForTests(): void {
    resetTracking()
}

/** What setup mode polls for while it is open: the signals until a call lands, then the calls themselves. */
type SetupPollTarget = 'signals' | 'calls' | null

function capture(event: string, properties: Record<string, unknown>): void {
    if (userLogic.findMounted()?.values.user?.is_impersonated) {
        return
    }
    posthog.captureRaw(event, properties)
}

function withoutSetupParams(searchParams: Record<string, any>): Record<string, any> {
    const { [SETUP_PARAM]: _path, [SETUP_STEP_PARAM]: _step, ...rest } = searchParams
    return rest
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpSetupModeLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    onboardingState: MCPOnboardingState | null // mcpAnalyticsOnboardingLogic
    signals: MCPOnboardingSignals | null // mcpAnalyticsOnboardingLogic
    signalsLoading: boolean // mcpAnalyticsOnboardingLogic
    location: {
        pathname: string
        search: string
        hash: string
    } // router
    searchParams: Record<string, any> // router
    currentProjectId: number | string // teamLogic
    connectState: MCPConnectState
    isEnabled: boolean
    isOpen: boolean
    pollTarget: SetupPollTarget
    recentCalls: MCPActivityRecentCallApi[] | null
    recentCallsFailed: boolean
    recentCallsLoading: boolean
    setupPath: MCPSetupPath | null
    step: MCPSetupStep | null
    viewedStep: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpSetupModeLogicActions {
    loadSignals: (_?: void | undefined) => void // mcpAnalyticsOnboardingLogic
    reportSetupInteraction: (
        action: string,
        mode: import('../../../../frontend/src/lib/components/ProductEmptyState/types').ProductEmptyStateMode,
        route?: null | import('lib/components/ProductEmptyState/productSetupStatusLogic').ProductSetupRoute | undefined,
        preview?: boolean | undefined,
        wizardSession?:
            | {
                  phase: string
                  session_id: string
              }
            | undefined
    ) => {
        action: string
        mode: import('../../../../frontend/src/lib/components/ProductEmptyState/types').ProductEmptyStateMode
        preview: boolean
        route: null | import('lib/components/ProductEmptyState/productSetupStatusLogic').ProductSetupRoute
        wizardSession:
            | {
                  phase: string
                  session_id: string
              }
            | undefined
    } // productSetupStatusLogic
    askPostHogAI: (prompt: string) => {
        prompt: string
    }
    exitSetupMode: (reason: MCPSetupExitReason) => {
        reason: MCPSetupExitReason
    }
    goToUsefulStep: () => {
        value: true
    }
    loadRecentCalls: (_: void) => void
    loadRecentCallsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRecentCallsSuccess: (
        recentCalls: MCPActivityRecentCallApi[] | null,
        payload?: void
    ) => {
        recentCalls: MCPActivityRecentCallApi[] | null
        payload?: void
    }
    openSetupMode: (
        path: MCPSetupPath,
        trigger: MCPSetupTrigger
    ) => {
        path: MCPSetupPath
        trigger: MCPSetupTrigger
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpSetupModeLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        isEnabled: (featureFlags: FeatureFlagsSet) => boolean
        setupPath: (isEnabled: boolean, searchParams: Record<string, any>) => MCPSetupPath | null
        isOpen: (setupPath: MCPSetupPath | null) => boolean
        step: (
            setupPath: MCPSetupPath | null,
            signals: MCPOnboardingSignals | null,
            searchParams: Record<string, any>
        ) => MCPSetupStep | null
        viewedStep: (setupPath: MCPSetupPath | null, step: MCPSetupStep | null) => string | null
        connectState: (onboardingState: MCPOnboardingState | null) => MCPConnectState
        pollTarget: (isOpen: boolean, step: MCPSetupStep | null) => SetupPollTarget
    }
}

export type mcpSetupModeLogicType = MakeLogicType<
    mcpSetupModeLogicValues,
    mcpSetupModeLogicActions,
    Record<string, any>,
    mcpSetupModeLogicMeta
>

export const mcpSetupModeLogic = kea<mcpSetupModeLogicType>([
    path(['products', 'mcp_analytics', 'frontend', 'setupMode', 'mcpSetupModeLogic']),
    connect(() => ({
        values: [
            router,
            ['searchParams', 'location'],
            featureFlagLogic,
            ['featureFlags'],
            mcpAnalyticsOnboardingLogic,
            ['signals', 'signalsLoading', 'onboardingState'],
            teamLogic,
            ['currentProjectId'],
        ],
        actions: [
            productSetupStatusLogic({ productKey: ProductKey.MCP_ANALYTICS }),
            ['reportSetupInteraction'],
            mcpAnalyticsOnboardingLogic,
            ['loadSignals'],
        ],
    })),
    actions({
        openSetupMode: (path: MCPSetupPath, trigger: MCPSetupTrigger) => ({ path, trigger }),
        goToUsefulStep: true,
        exitSetupMode: (reason: MCPSetupExitReason) => ({ reason }),
        askPostHogAI: (prompt: string) => ({ prompt }),
    }),
    loaders(({ values }) => ({
        recentCalls: [
            null as MCPActivityRecentCallApi[] | null,
            {
                loadRecentCalls: async (_: void, breakpoint): Promise<MCPActivityRecentCallApi[] | null> => {
                    // The overview resolves each call's client to a harness label and pulls the readable
                    // message out of a failed call's response, both of which only the backend knows how to do.
                    // `refresh` skips the overview's shared five-minute cache, which would hide the calls that follow the first.
                    const overview = await mcpAnalyticsSessionsActivityOverview(String(values.currentProjectId), {
                        refresh: true,
                    })
                    breakpoint()
                    return overview.recent_calls.slice(0, RECENT_CALLS)
                },
            },
        ],
    })),
    reducers({
        recentCallsFailed: [
            false,
            {
                loadRecentCallsSuccess: () => false,
                loadRecentCallsFailure: () => true,
            },
        ],
    }),
    selectors({
        isEnabled: [
            (s) => [s.featureFlags],
            (featureFlags: Record<string, unknown>): boolean => !!featureFlags[FEATURE_FLAGS.MCP_ANALYTICS_SETUP_MODE],
        ],
        setupPath: [
            (s) => [s.isEnabled, s.searchParams],
            (isEnabled: boolean, searchParams: Record<string, unknown>): MCPSetupPath | null =>
                isEnabled ? parseSetupPath(searchParams[SETUP_PARAM]) : null,
        ],
        isOpen: [(s) => [s.setupPath], (setupPath: MCPSetupPath | null): boolean => setupPath !== null],
        /** `null` until the onboarding signals answer, so a reload never flashes the wrong step. */
        step: [
            (s) => [s.setupPath, s.signals, s.searchParams],
            (
                setupPath: MCPSetupPath | null,
                signals: { hasToolCall: boolean } | null,
                searchParams: Record<string, unknown>
            ): MCPSetupStep | null => {
                if (!setupPath || !signals) {
                    return null
                }
                const requested = searchParams[SETUP_STEP_PARAM]
                return setupStepFor({
                    hasToolCall: signals.hasToolCall,
                    requestedStep: typeof requested === 'string' ? requested : null,
                })
            },
        ],
        viewedStep: [
            (s) => [s.setupPath, s.step],
            (setupPath: MCPSetupPath | null, step: MCPSetupStep | null): string | null =>
                setupPath && step ? `${setupPath}:${step}` : null,
        ],
        connectState: [
            (s) => [s.onboardingState],
            (onboardingState: MCPOnboardingState | null): MCPConnectState => connectStateFor(onboardingState),
        ],
        // An unknown step (the first signals query failed) polls the signals too, so a retry comes quickly.
        pollTarget: [
            (s) => [s.isOpen, s.step],
            (isOpen: boolean, step: MCPSetupStep | null): SetupPollTarget =>
                !isOpen
                    ? null
                    : step === null || step === 'connect'
                      ? 'signals'
                      : step === 'first-call'
                        ? 'calls'
                        : null,
        ],
    }),
    listeners(({ actions, values }) => ({
        reportSetupInteraction: ({ action, preview }) => {
            if (preview) {
                return
            }
            if (action === 'wizard command copied') {
                actions.openSetupMode('wizard', 'wizard_copy')
            } else if (action === 'agent prompt copied') {
                actions.openSetupMode('agent', 'agent_copy')
            }
        },
        openSetupMode: ({ path, trigger }) => {
            if (!values.isEnabled || values.isOpen) {
                return
            }
            tracking.opened = true
            capture('mcp analytics setup mode opened', { path, trigger })
            router.actions.push(values.location.pathname, {
                ...withoutSetupParams(values.searchParams),
                [SETUP_PARAM]: path,
            })
        },
        askPostHogAI: ({ prompt }) => {
            // The side panel opens under the fullscreen setup mode, so close setup mode first.
            actions.exitSetupMode('ask_ai')
            sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, autoRunMaxPrompt(prompt))
        },
        goToUsefulStep: () => {
            router.actions.replace(values.location.pathname, { ...values.searchParams, [SETUP_STEP_PARAM]: 'useful' })
        },
        exitSetupMode: ({ reason }) => {
            if (!values.isOpen) {
                return
            }
            capture('mcp analytics setup mode exited', { path: values.setupPath, step: values.step, reason })
            resetTracking()
            const searchParams = withoutSetupParams(values.searchParams)
            if (reason === 'finished' || reason === 'ask_ai') {
                router.actions.push(urls.mcpAnalyticsActivity(), searchParams)
            } else {
                router.actions.replace(values.location.pathname, searchParams)
            }
        },
    })),
    subscriptions(({ actions, values, cache }) => ({
        isOpen: (isOpen: boolean) => {
            // On the window rather than the modal, because the modal only hears keys while focus is inside
            // it, and a step change replaces the focused button.
            if (isOpen) {
                cache.disposables.add(() => {
                    const onKeyDown = (event: KeyboardEvent): void => {
                        if (event.key === 'Escape' && !event.defaultPrevented) {
                            actions.exitSetupMode('escape')
                        }
                    }
                    window.addEventListener('keydown', onKeyDown)
                    return () => window.removeEventListener('keydown', onKeyDown)
                }, 'escape')
            } else {
                cache.disposables.dispose('escape')
                // Still marked open means it closed without `exitSetupMode`: browser history or a link out.
                if (tracking.opened) {
                    capture('mcp analytics setup mode exited', { ...tracking.lastViewed, reason: 'navigated' })
                    resetTracking()
                }
            }
            // Anything that opens setup mode without `openSetupMode` came in through the URL: a reload,
            // a shared link, or browser history.
            if (isOpen && !tracking.opened) {
                tracking.opened = true
                capture('mcp analytics setup mode opened', { path: values.setupPath, trigger: 'url' })
            }
        },
        step: (step: MCPSetupStep | null) => {
            if (step === 'first-call') {
                // Only the scene keeps a setup mode host once the product has data, so on the welcome page the
                // reveal would unmount with the empty state. The onboarding step redirects itself, because it must
                // complete onboarding first.
                const path = removeProjectIdIfPresent(values.location.pathname)
                if (!path.startsWith(urls.mcpAnalytics()) && !path.startsWith(urls.onboarding())) {
                    router.actions.replace(urls.mcpAnalytics(), values.searchParams)
                }
            }
        },
        pollTarget: (pollTarget: SetupPollTarget) => {
            cache.disposables.dispose('setupPoll')
            // Each poll skips while the last request is in flight. A request slower than the interval
            // would otherwise be cancelled by the next one, forever.
            if (pollTarget === 'signals') {
                cache.disposables.add(() => {
                    const id = window.setInterval(
                        () => !values.signalsLoading && actions.loadSignals(),
                        CONNECT_POLL_MS
                    )
                    return () => clearInterval(id)
                }, 'setupPoll')
            } else if (pollTarget === 'calls') {
                actions.loadRecentCalls()
                cache.disposables.add(() => {
                    const id = window.setInterval(
                        () => !values.recentCallsLoading && actions.loadRecentCalls(),
                        FIRST_CALL_POLL_MS
                    )
                    return () => clearInterval(id)
                }, 'setupPoll')
            }
        },
        viewedStep: (viewedStep: string | null) => {
            if (viewedStep && viewedStep !== tracking.lastViewedStep) {
                tracking.lastViewedStep = viewedStep
                tracking.lastViewed = { path: values.setupPath, step: values.step }
                capture('mcp analytics setup mode step viewed', { step: values.step, path: values.setupPath })
            }
        },
    })),
])