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.

5.2 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { createPollLoop, isPermanentPollError } from 'lib/wizard-sync/pollLoop'

import { oauthConnectedAppsList } from '~/generated/core/api'
import type { ConnectedAppApi } from '~/generated/core/api.schemas'

const POLL_INTERVAL_MS = 3000

/**
 * Whether the user has an agent connected to PostHog. MCP clients register themselves when they
 * sign in over OAuth, so a self-registered connection stands in for a connected agent.
 *
 * Not foolproof: any OAuth client can register itself, and an MCP client that PostHog registered
 * by hand is missed. Nothing records which connections serve the MCP server, so this is the
 * closest signal available for now.
 */
export function hasAgentConnection(connectedApps: ConnectedAppApi[]): boolean {
    return connectedApps.some((app) => app.is_self_registered)
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface agentConnectionLogicValues {
    connectedApps: ConnectedAppApi[] | null
    connectedAppsLoading: boolean
    hasConnectedAgent: boolean | null
    polling: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface agentConnectionLogicActions {
    loadConnectedApps: (_?: any) => any
    loadConnectedAppsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadConnectedAppsSuccess: (
        connectedApps: ConnectedAppApi[] | null,
        payload?: any
    ) => {
        connectedApps: ConnectedAppApi[] | null
        payload?: any
    }
    setPolling: (polling: boolean) => {
        polling: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface agentConnectionLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        hasConnectedAgent: (connectedApps: ConnectedAppApi[] | null) => boolean | null
    }
}

export type agentConnectionLogicType = MakeLogicType<
    agentConnectionLogicValues,
    agentConnectionLogicActions,
    Record<string, any>,
    agentConnectionLogicMeta
>

/**
 * Promotional surfaces read this instead of `connectedAppsLogic`: a failed lookup stays silent and
 * leaves the answer unknown, rather than raising the settings page's error toast.
 */
export const agentConnectionLogic = kea<agentConnectionLogicType>([
    path(['lib', 'components', 'MCPHint', 'agentConnectionLogic']),
    actions({
        setPolling: (polling: boolean) => ({ polling }),
    }),
    reducers({
        polling: [
            false,
            {
                setPolling: (_, { polling }) => polling,
            },
        ],
    }),
    loaders(({ values }) => ({
        connectedApps: [
            null as ConnectedAppApi[] | null,
            {
                loadConnectedApps: async (_ = undefined, breakpoint) => {
                    let connectedApps: ConnectedAppApi[]
                    try {
                        connectedApps = await oauthConnectedAppsList()
                    } catch {
                        return values.connectedApps
                    }
                    // Drops a slower, older response so it cannot overwrite a newer one.
                    breakpoint()
                    return connectedApps
                },
            },
        ],
    })),
    selectors({
        // `null` until a lookup succeeds, so callers can tell "not connected" from "unknown".
        hasConnectedAgent: [
            (s) => [s.connectedApps],
            (connectedApps: ConnectedAppApi[] | null): boolean | null =>
                connectedApps === null ? null : hasAgentConnection(connectedApps),
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        setPolling: ({ polling }) => {
            if (!polling) {
                cache.disposables.dispose('poll')
                return
            }
            cache.disposables.add(
                createPollLoop({
                    intervalMs: POLL_INTERVAL_MS,
                    tick: async () => {
                        // A load already in flight (the mount's or a focus refresh) answers this tick.
                        if (!values.connectedAppsLoading) {
                            actions.loadConnectedAppsSuccess(await oauthConnectedAppsList())
                        }
                        return values.hasConnectedAgent ? 'terminal' : 'ok'
                    },
                    onError: (error) => (isPermanentPollError(error) ? 'stop' : 'retry'),
                    shouldStop: () => !values.polling || !!values.hasConnectedAgent,
                }),
                'poll'
            )
        },
    })),
    afterMount(({ actions, values, cache }) => {
        actions.loadConnectedApps()
        // An agent is usually authorized in another tab, so check again when the user comes back.
        cache.disposables.add(() => {
            const onFocus = (): void => {
                if (!values.hasConnectedAgent) {
                    actions.loadConnectedApps()
                }
            }
            window.addEventListener('focus', onFocus)
            return () => window.removeEventListener('focus', onFocus)
        }, 'focusRefresh')
    }),
])