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.4 KB
Raw Blame
import { LogicWrapper, MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'

import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { userLogic } from 'scenes/userLogic'

import { IntegrationType, UserType } from '~/types'

export interface SlackConnectLogicProps {
    connectKey: string
    onConnected?: (integrationId: number) => void
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface slackConnectLogicValues {
    slackIntegrations: IntegrationType[] | undefined // integrationsLogic
    user: UserType | null // userLogic
    waitingForSlack: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface slackConnectLogicActions {
    loadIntegrationsSuccess: (
        integrations: IntegrationType[],
        payload?: any
    ) => {
        integrations: IntegrationType[]
        payload?: any
    } // integrationsLogic
    startPolling: () => {
        value: true
    } // integrationsLogic
    stopPolling: () => {
        value: true
    } // integrationsLogic
    connectSlackClicked: () => {
        value: true
    }
    slackConnectTimedOut: () => {
        value: true
    }
    slackConnected: (integrationId: number) => {
        integrationId: number
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface slackConnectLogicMeta {
    key: string
}

export type slackConnectLogicType = MakeLogicType<
    slackConnectLogicValues,
    slackConnectLogicActions,
    SlackConnectLogicProps,
    slackConnectLogicMeta
>

/**
 * Connecting Slack runs OAuth in another tab, so the page keeps what the user was filling in. The new
 * workspace reaches this tab only through the integrations poller, which also refetches on focus.
 */
// An abandoned OAuth tab never reports back, so stop polling after this long and let the user retry.
export const SLACK_CONNECT_TIMEOUT_MS = 10 * 60 * 1000

export const slackConnectLogic: LogicWrapper<slackConnectLogicType> = kea<slackConnectLogicType>([
    props({} as SlackConnectLogicProps),
    key((props) => props.connectKey),
    path((key) => ['lib', 'integrations', 'slackConnectLogic', key]),
    connect(() => ({
        values: [integrationsLogic, ['slackIntegrations'], userLogic, ['user']],
        actions: [integrationsLogic, ['startPolling', 'stopPolling', 'loadIntegrationsSuccess']],
    })),
    actions({
        connectSlackClicked: true,
        slackConnected: (integrationId: number) => ({ integrationId }),
        slackConnectTimedOut: true,
    }),
    reducers({
        waitingForSlack: [
            false,
            {
                connectSlackClicked: () => true,
                slackConnected: () => false,
                slackConnectTimedOut: () => false,
            },
        ],
    }),
    listeners(({ actions, values, props, cache }) => ({
        connectSlackClicked: () => {
            // Before the first successful load there is nothing to compare against, so the next load sets the baseline.
            cache.knownSlackIntegrationIds = values.slackIntegrations
                ? new Set(values.slackIntegrations.map((integration) => integration.id))
                : null
            // The poller counts subscribers, so the same key keeps a second click from adding one that
            // nothing stops. It keeps running while this tab is hidden, because the user is in the
            // Slack tab then and the focus refetch is what brings the workspace back.
            cache.disposables.add(
                () => {
                    actions.startPolling()
                    return () => actions.stopPolling()
                },
                'integrationsPolling',
                { pauseOnPageHidden: false }
            )
            cache.disposables.add(
                () => {
                    const timeout = window.setTimeout(() => actions.slackConnectTimedOut(), SLACK_CONNECT_TIMEOUT_MS)
                    return () => window.clearTimeout(timeout)
                },
                'slackConnectTimeout',
                { pauseOnPageHidden: false }
            )
        },
        loadIntegrationsSuccess: () => {
            if (!values.waitingForSlack) {
                return
            }
            // The reducer of integrationsLogic holds the loaded list by now.
            const slackIntegrations = values.slackIntegrations ?? []
            const known: Set<number> | null = cache.knownSlackIntegrationIds
            if (!known) {
                cache.knownSlackIntegrationIds = new Set(slackIntegrations.map((integration) => integration.id))
                return
            }
            // Another member can add a workspace to the project meanwhile; only this user's OAuth counts.
            const workspace = slackIntegrations.find(
                (integration) =>
                    !known.has(integration.id) && !!values.user && integration.created_by?.uuid === values.user.uuid
            )
            if (workspace) {
                actions.slackConnected(workspace.id)
            }
        },
        slackConnected: ({ integrationId }) => {
            cache.disposables.dispose('integrationsPolling')
            cache.disposables.dispose('slackConnectTimeout')
            props.onConnected?.(integrationId)
        },
        slackConnectTimedOut: () => {
            cache.disposables.dispose('integrationsPolling')
        },
    })),
])