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, beforeUnmount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'

import { getOrganizationsProjectsRetrieveUrl, getUsersRetrieveUrl } from '~/generated/core/api'
import type {
    ProjectBackwardCompatApi,
    ToolbarEntitlementsApiEntitlements,
    UserApi,
} from '~/generated/core/api.schemas'
import { canonicalizeUiHost } from '~/toolbar/shared/toolbarConfigLogic'
import { fetchToolbarEntitlements } from '~/toolbar/shared/toolbarEntitlementsLogic'
import { toolbarPosthogJS } from '~/toolbar/shared/toolbarPosthogJS'
import { joinWithUiHost, safeFetch } from '~/toolbar/shared/utils'

import {
    getActiveTab,
    getStoredUiHost,
    hasHostPermission,
    onActiveTabChange,
    openTab,
    requestHostPermission,
    setStoredUiHost,
} from '../../browser/extensionBrowser'
import type { ExtensionFeatureKey } from '../../components/panel/extensionPageTools'
import {
    ExtensionPanelState,
    SessionUserResult,
    ToolbarAccessResult,
    getExtensionPanelState,
} from './extensionPanelState'

const DEFAULT_UI_HOST = 'https://us.posthog.com'

// The project setting's default, used until the project loads.
const DEFAULT_DATA_ATTRIBUTES = ['data-attr']

// Matches the toolbar's entitlements request timeout.
const REQUEST_TIMEOUT_MS = 5000

const REFRESH_ON_TAB_CHANGE_MS = 30 * 1000

const RECHECK_ON_TAB_CHANGE: ExtensionPanelState['kind'][] = [
    'signed-out',
    'no-toolbar-access',
    'unauthorized-url',
    'error',
]

// States the user may fix with the project or host settings, for example a session on the other cloud region.
const OPEN_SETTINGS_IN: ExtensionPanelState['kind'][] = [
    'host-permission-needed',
    'signed-out',
    'no-toolbar-access',
    'error',
]

/** Sends the PostHog session cookie, like the toolbar's own entitlements request. */
async function fetchWithSession(uiHost: string, path: string): Promise<{ status: number; data: unknown }> {
    return await readResponse(
        safeFetch(`${uiHost}${path}`, { credentials: 'include', signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) })
    )
}

async function readResponse(request: Promise<Response>): Promise<{ status: number; data: unknown }> {
    try {
        const response = await request
        const data = response.ok ? await response.json() : null
        return { status: response.status, data }
    } catch {
        // 0 keeps a network failure apart from every HTTP status.
        return { status: 0, data: null }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPanelLogicValues {
    authorizedUrls: string[] | 'error' | null
    authorizedUrlsLoading: boolean
    dataAttributes: string[]
    entitlements: ToolbarEntitlementsApiEntitlements | null
    hostPermission: boolean | null
    panelState: ExtensionPanelState
    projectSwitchFailed: boolean
    projectUrl: (path: string) => string
    sessionUser: SessionUserResult | null
    sessionUserLoading: boolean
    settingsExpanded: boolean
    settingsNeeded: boolean
    tabId: number | null
    tabUrl: string | null | undefined
    toolbarAccess: ToolbarAccessResult | null
    toolbarAccessLoading: boolean
    uiHost: string
    user: UserApi | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPanelLogicActions {
    loadAuthorizedUrls: ({ organizationId, projectId }: { organizationId: string; projectId: number }) => {
        organizationId: string
        projectId: number
    }
    loadAuthorizedUrlsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAuthorizedUrlsSuccess: (
        authorizedUrls: string[] | 'error' | null,
        payload?: {
            organizationId: string
            projectId: number
        }
    ) => {
        authorizedUrls: string[] | 'error' | null
        payload?: {
            organizationId: string
            projectId: number
        }
    }
    loadSessionUser: () => any
    loadSessionUserFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSessionUserSuccess: (
        sessionUser: SessionUserResult | null,
        payload?: any
    ) => {
        sessionUser: SessionUserResult | null
        payload?: any
    }
    loadToolbarAccess: () => any
    loadToolbarAccessFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadToolbarAccessSuccess: (
        toolbarAccess: ToolbarAccessResult | null,
        payload?: any
    ) => {
        toolbarAccess: ToolbarAccessResult | null
        payload?: any
    }
    openFeature: (
        feature: ExtensionFeatureKey,
        path: string
    ) => {
        feature: ExtensionFeatureKey
        path: string
    }
    openPostHogPath: (path: string) => {
        path: string
    }
    openProjectPath: (path: string) => {
        path: string
    }
    requestHostPermission: () => {
        value: true
    }
    retry: () => {
        value: true
    }
    setDataAttributes: (dataAttributes: string[]) => {
        dataAttributes: string[]
    }
    setHostPermission: (granted: boolean) => {
        granted: boolean
    }
    setProjectSwitchFailed: (failed: boolean) => {
        failed: boolean
    }
    setSettingsExpanded: (expanded: boolean) => {
        expanded: boolean
    }
    setTab: (
        tabId: number | null,
        tabUrl: string | null
    ) => {
        tabId: number | null
        tabUrl: string | null
    }
    setUiHost: (uiHost: string) => {
        uiHost: string
    }
    switchProject: (teamId: number) => {
        teamId: number
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPanelLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        user: (sessionUser: SessionUserResult | null) => UserApi | null
        projectUrl: (uiHost: string, user: UserApi | null) => (path: string) => string
        entitlements: (toolbarAccess: ToolbarAccessResult | null) => ToolbarEntitlementsApiEntitlements | null
        panelState: (
            tabUrl: string | null | undefined,
            uiHost: string,
            hostPermission: boolean | null,
            sessionUser: SessionUserResult | null,
            toolbarAccess: ToolbarAccessResult | null,
            authorizedUrls: string[] | 'error' | null
        ) => ExtensionPanelState
        settingsNeeded: (panelState: ExtensionPanelState, projectSwitchFailed: boolean) => boolean
    }
}

export type extensionPanelLogicType = MakeLogicType<
    extensionPanelLogicValues,
    extensionPanelLogicActions,
    Record<string, any>,
    extensionPanelLogicMeta
>

export const extensionPanelLogic = kea<extensionPanelLogicType>([
    path(['toolbar', 'extension', 'extensionPanelLogic']),
    actions({
        setTab: (tabId: number | null, tabUrl: string | null) => ({ tabId, tabUrl }),
        setDataAttributes: (dataAttributes: string[]) => ({ dataAttributes }),
        setUiHost: (uiHost: string) => ({ uiHost }),
        setHostPermission: (granted: boolean) => ({ granted }),
        requestHostPermission: true,
        switchProject: (teamId: number) => ({ teamId }),
        openPostHogPath: (path: string) => ({ path }),
        openProjectPath: (path: string) => ({ path }),
        openFeature: (feature: ExtensionFeatureKey, path: string) => ({ feature, path }),
        retry: true,
        setProjectSwitchFailed: (failed: boolean) => ({ failed }),
        setSettingsExpanded: (expanded: boolean) => ({ expanded }),
    }),
    reducers({
        tabId: [null as number | null, { setTab: (_, { tabId }) => tabId }],
        tabUrl: [undefined as string | null | undefined, { setTab: (_, { tabUrl }) => tabUrl }],
        dataAttributes: [DEFAULT_DATA_ATTRIBUTES, { setDataAttributes: (_, { dataAttributes }) => dataAttributes }],
        uiHost: [DEFAULT_UI_HOST as string, { setUiHost: (_, { uiHost }) => uiHost }],
        projectSwitchFailed: [
            false,
            { setProjectSwitchFailed: (_, { failed }) => failed, switchProject: () => false, setUiHost: () => false },
        ],
        hostPermission: [
            null as boolean | null,
            { setUiHost: () => null, setHostPermission: (_, { granted }) => granted },
        ],
        settingsExpanded: [false, { setSettingsExpanded: (_, { expanded }) => expanded }],
    }),
    loaders(({ actions, values }) => ({
        sessionUser: [
            null as SessionUserResult | null,
            {
                loadSessionUser: async (): Promise<SessionUserResult | null> => {
                    const uiHost = values.uiHost
                    const { status, data } = await fetchWithSession(uiHost, getUsersRetrieveUrl('@me'))
                    if (values.uiHost !== uiHost) {
                        return null
                    }
                    if (status === 401 || status === 403) {
                        return { status: 'signed-out' }
                    }
                    const user = data as UserApi | null
                    if (status !== 200 || !user?.team) {
                        return { status: 'error' }
                    }
                    return { status: 'signed-in', user }
                },
            },
        ],
        toolbarAccess: [
            null as ToolbarAccessResult | null,
            {
                loadToolbarAccess: async (): Promise<ToolbarAccessResult | null> => {
                    const uiHost = values.uiHost
                    const { status, data } = await readResponse(fetchToolbarEntitlements(uiHost))
                    if (values.uiHost !== uiHost) {
                        return null
                    }
                    if (status === 200) {
                        const entitlements = (data as { entitlements?: ToolbarEntitlementsApiEntitlements } | null)
                            ?.entitlements
                        return { status: 'allowed', entitlements: entitlements ?? null }
                    }
                    if (status === 401) {
                        return { status: 'signed-out' }
                    }
                    return status === 403 ? { status: 'denied' } : { status: 'error' }
                },
            },
        ],
        authorizedUrls: [
            null as string[] | 'error' | null,
            {
                loadAuthorizedUrls: async ({
                    organizationId,
                    projectId,
                }: {
                    organizationId: string
                    projectId: number
                }): Promise<string[] | 'error' | null> => {
                    const uiHost = values.uiHost
                    const { status, data } = await fetchWithSession(
                        uiHost,
                        getOrganizationsProjectsRetrieveUrl(organizationId, projectId)
                    )
                    if (values.uiHost !== uiHost) {
                        return null
                    }
                    if (status !== 200 || !data) {
                        return 'error'
                    }
                    const project = data as ProjectBackwardCompatApi
                    if (Array.isArray(project.data_attributes)) {
                        actions.setDataAttributes(
                            project.data_attributes.filter(
                                (attribute): attribute is string => typeof attribute === 'string'
                            )
                        )
                    }
                    return (project.app_urls ?? []).filter(
                        (url): url is string => typeof url === 'string' && url.length > 0
                    )
                },
            },
        ],
    })),
    reducers({
        sessionUser: { setUiHost: () => null, switchProject: () => null, retry: () => null },
        toolbarAccess: { setUiHost: () => null, switchProject: () => null, retry: () => null },
        authorizedUrls: { setUiHost: () => null, switchProject: () => null, retry: () => null },
    }),
    selectors({
        user: [
            (s) => [s.sessionUser],
            (sessionUser: SessionUserResult | null): UserApi | null =>
                sessionUser?.status === 'signed-in' ? sessionUser.user : null,
        ],
        projectUrl: [
            (s) => [s.uiHost, s.user],
            (uiHost: string, user: UserApi | null) =>
                (path: string): string =>
                    joinWithUiHost(uiHost, user ? `/project/${user.team.id}${path}` : path),
        ],
        entitlements: [
            (s) => [s.toolbarAccess],
            (toolbarAccess: ToolbarAccessResult | null): ToolbarEntitlementsApiEntitlements | null =>
                toolbarAccess?.status === 'allowed' ? toolbarAccess.entitlements : null,
        ],
        panelState: [
            (s) => [s.tabUrl, s.uiHost, s.hostPermission, s.sessionUser, s.toolbarAccess, s.authorizedUrls],
            (
                tabUrl: string | null | undefined,
                uiHost: string,
                hostPermission: boolean | null,
                sessionUser: SessionUserResult | null,
                toolbarAccess: ToolbarAccessResult | null,
                authorizedUrls: string[] | 'error' | null
            ): ExtensionPanelState =>
                getExtensionPanelState({
                    tabUrl,
                    uiHost,
                    hostPermission,
                    sessionStatus: sessionUser?.status ?? null,
                    toolbarAccess,
                    authorizedUrls,
                }),
        ],
        settingsNeeded: [
            (s) => [s.panelState, s.projectSwitchFailed],
            (panelState: ExtensionPanelState, projectSwitchFailed: boolean): boolean =>
                projectSwitchFailed || OPEN_SETTINGS_IN.includes(panelState.kind),
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        setUiHost: async ({ uiHost }) => {
            void setStoredUiHost(uiHost)
            actions.setHostPermission(await hasHostPermission(uiHost))
        },
        requestHostPermission: async () => {
            // No await before this call: the prompt needs the click's user gesture.
            const granted = await requestHostPermission(values.uiHost)
            actions.setHostPermission(granted)
        },
        setHostPermission: ({ granted }) => {
            if (granted) {
                actions.loadSessionUser()
                actions.loadToolbarAccess()
            }
        },
        retry: () => {
            if (values.hostPermission) {
                actions.loadSessionUser()
                actions.loadToolbarAccess()
            }
        },
        setTab: () => {
            // The panel stays open while the user logs in, switches project or adds an authorized URL in another
            // tab, so check again when the user comes back.
            if (RECHECK_ON_TAB_CHANGE.includes(values.panelState.kind)) {
                actions.retry()
                return
            }
            if (values.hostPermission && Date.now() - (cache.lastRefresh ?? 0) > REFRESH_ON_TAB_CHANGE_MS) {
                cache.lastRefresh = Date.now()
                actions.loadSessionUser()
                actions.loadToolbarAccess()
                toolbarPosthogJS.reloadFeatureFlags()
            }
        },
        loadSessionUserSuccess: ({ sessionUser }) => {
            if (sessionUser?.status !== 'signed-in') {
                return
            }
            const { user } = sessionUser
            if (user.distinct_id) {
                // Evaluates toolbar rollout flags for this person, as the floating toolbar does.
                toolbarPosthogJS.identify(user.distinct_id)
            }
            actions.loadAuthorizedUrls({ organizationId: user.organization.id, projectId: user.team.project_id })
        },
        switchProject: async ({ teamId }) => {
            // The app's project-switch path moves the session's current project, which is the project
            // toolbar authentication uses.
            const { status } = await fetchWithSession(values.uiHost, `/project/${teamId}`)
            if (status >= 200 && status < 300) {
                toolbarPosthogJS.capture('toolbar extension project switched')
            } else {
                actions.setProjectSwitchFailed(true)
            }
            actions.loadSessionUser()
            actions.loadToolbarAccess()
        },
        openPostHogPath: ({ path }) => {
            void openTab(joinWithUiHost(values.uiHost, path))
        },
        openProjectPath: ({ path }) => {
            void openTab(values.projectUrl(path))
        },
        openFeature: ({ feature, path }) => {
            toolbarPosthogJS.capture('toolbar extension feature opened', { feature })
            actions.openProjectPath(path)
        },
    })),
    subscriptions(({ actions }) => ({
        settingsNeeded: (settingsNeeded: boolean, previous: boolean | undefined) => {
            // Opens the settings when a problem starts and closes them when it ends, so the user can still toggle
            // them in between.
            if (settingsNeeded || previous) {
                actions.setSettingsExpanded(settingsNeeded)
            }
        },
        panelState: (panelState: ExtensionPanelState, previous: ExtensionPanelState | undefined) => {
            if (panelState.kind === 'checking' || panelState.kind === previous?.kind) {
                return
            }
            // pinned: analytics event name, renaming it breaks the extension adoption insights
            toolbarPosthogJS.capture('toolbar extension panel state', {
                state: panelState.kind,
                unsupported_reason: panelState.kind === 'unsupported-page' ? panelState.reason : undefined,
            })
        },
    })),
    afterMount(({ actions, cache }) => {
        toolbarPosthogJS.opt_in_capturing()
        void getStoredUiHost().then((stored) => actions.setUiHost(canonicalizeUiHost(stored) ?? DEFAULT_UI_HOST))
        void getActiveTab().then(
            (tab) => actions.setTab(tab?.id ?? null, tab?.url ?? null),
            () => actions.setTab(null, null)
        )
        cache.removeActiveTabListener = onActiveTabChange((tab) => actions.setTab(tab?.id ?? null, tab?.url ?? null))
    }),
    beforeUnmount(({ cache }) => {
        cache.removeActiveTabListener?.()
    }),
])