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.

23.6 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import api, { ApiConfig } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { getRecentSlackChannelIds, slackChannelId } from 'lib/integrations/slackChannel'
import { preflightLogic } from 'lib/logic/preflightLogic'

import { SlackChannelType } from '~/types'

import { integrationsChannelsRetrieve, integrationsUsersRetrieve } from 'products/integrations/frontend/generated/api'
import type { SlackUserApi, SlackUsersResponseApi } from 'products/integrations/frontend/generated/api.schemas'

import type { PreflightStatus } from '../../types'

export const SLACK_CHANNELS_MIN_REFRESH_INTERVAL_SECONDS = 30

// Matches the backend `SlackIntegrationInactiveError.default_code`. When the workspace token is
// revoked/expired the channels endpoint returns this instead of a 500, so we can surface guidance
// inline in the picker rather than spamming a generic error toast on every refresh/search.
export const SLACK_INTEGRATION_INACTIVE_ERROR_CODE = 'slack_integration_inactive'
const SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE =
    'Your Slack connection is no longer active. Reconnect Slack to load channels and pick a destination.'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface slackIntegrationLogicValues {
    preflight: PreflightStatus | null // preflightLogic
    siteUrlMisconfigured: boolean // preflightLogic
    _fetchedSlackChannels: SlackChannelType[]
    _fetchedSlackChannelsById: Record<string, SlackChannelType>
    _fetchedSlackUsersById: Record<string, SlackUserApi>
    allSlackChannels: {
        channels: SlackChannelType[]
        has_more?: boolean
        lastRefreshedAt: string
    } | null
    allSlackChannelsLoading: boolean
    allSlackUsers: SlackUsersResponseApi | null
    allSlackUsersLoading: boolean
    attemptedSlackChannelIds: Record<string, true>
    attemptedSlackUserIds: Record<string, true>
    channelListGeneration: number
    getChannelRefreshButtonDisabledReason: () => string
    getUsersRefreshButtonDisabledReason: () => string
    isMemberOfSlackChannel: (channel: string) => boolean | null
    isPrivateChannelWithoutAccess: (channel: string) => boolean
    recentlySubscribedChannelIds: string[]
    slackChannelById: SlackChannelType | null
    slackChannelByIdLoading: boolean
    slackChannels: SlackChannelType[]
    slackChannelsForPicker: SlackChannelType[]
    slackIntegrationInactiveMessage: string | null
    slackUserById: SlackUserApi | null
    slackUserByIdLoading: boolean
    slackUsers: SlackUserApi[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface slackIntegrationLogicActions {
    loadAllSlackChannels: (
        forceRefresh?: boolean,
        search?: string
    ) => {
        forceRefresh: boolean
        search: string
    }
    loadAllSlackChannelsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAllSlackChannelsSuccess: (
        allSlackChannels: {
            channels: SlackChannelType[]
            has_more?: boolean | undefined
            lastRefreshedAt: string
        } | null,
        payload?: {
            forceRefresh: boolean
            search: string
        }
    ) => {
        allSlackChannels: {
            channels: SlackChannelType[]
            has_more?: boolean | undefined
            lastRefreshedAt: string
        } | null
        payload?: {
            forceRefresh: boolean
            search: string
        }
    }
    loadAllSlackUsers: (
        forceRefresh?: boolean,
        search?: string
    ) => {
        forceRefresh: boolean
        search: string
    }
    loadAllSlackUsersFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAllSlackUsersSuccess: (
        allSlackUsers: SlackUsersResponseApi | null,
        payload?: {
            forceRefresh: boolean
            search: string
        }
    ) => {
        allSlackUsers: SlackUsersResponseApi | null
        payload?: {
            forceRefresh: boolean
            search: string
        }
    }
    loadSlackChannelById: (
        channelId: string,
        forceRefresh?: boolean
    ) => {
        channelId: string
        forceRefresh: boolean
    }
    loadSlackChannelByIdFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSlackChannelByIdSuccess: (
        slackChannelById: SlackChannelType | null,
        payload?: {
            channelId: string
            forceRefresh: boolean
        }
    ) => {
        slackChannelById: SlackChannelType | null
        payload?: {
            channelId: string
            forceRefresh: boolean
        }
    }
    loadSlackUserById: (userId: string) => {
        userId: string
    }
    loadSlackUserByIdFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSlackUserByIdSuccess: (
        slackUserById: SlackUserApi | null,
        payload?: {
            userId: string
        }
    ) => {
        slackUserById: SlackUserApi | null
        payload?: {
            userId: string
        }
    }
    recheckSlackChannelMembership: (channelIds: string[]) => {
        channelIds: string[]
    }
    setRecentlySubscribedChannelIds: (channelIds: string[]) => {
        channelIds: string[]
    }
    setSlackIntegrationInactive: (message: string | null) => {
        message: string | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface slackIntegrationLogicProps {
    id: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface slackIntegrationLogicMeta {
    key: number
    __keaTypeGenInternalSelectorTypes: {
        slackChannels: (
            _fetchedSlackChannels: SlackChannelType[],
            _fetchedSlackChannelsById: Record<string, SlackChannelType>
        ) => SlackChannelType[]
        slackUsers: (
            allSlackUsers: SlackUsersResponseApi | null,
            _fetchedSlackUsersById: Record<string, SlackUserApi>
        ) => SlackUserApi[]
        getUsersRefreshButtonDisabledReason: (allSlackUsers: SlackUsersResponseApi | null) => () => string
        slackChannelsForPicker: (
            slackChannels: SlackChannelType[],
            recentlySubscribedChannelIds: string[]
        ) => SlackChannelType[]
        isMemberOfSlackChannel: (slackChannels: SlackChannelType[]) => (channel: string) => boolean | null
        isPrivateChannelWithoutAccess: (slackChannels: SlackChannelType[]) => (channel: string) => boolean
        getChannelRefreshButtonDisabledReason: (
            allSlackChannels: {
                channels: SlackChannelType[]
                has_more?: boolean
                lastRefreshedAt: string
            } | null
        ) => () => string
    }
}

export type slackIntegrationLogicType = MakeLogicType<
    slackIntegrationLogicValues,
    slackIntegrationLogicActions,
    slackIntegrationLogicProps,
    slackIntegrationLogicMeta
>

export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
    props({} as { id: number }),
    key((props) => props.id),
    path((key) => ['lib', 'integrations', 'slackIntegrationLogic', key]),
    connect(() => ({
        values: [preflightLogic, ['siteUrlMisconfigured', 'preflight']],
    })),
    actions({
        loadAllSlackChannels: (forceRefresh: boolean = false, search: string = '') => ({ forceRefresh, search }),
        loadAllSlackUsers: (forceRefresh: boolean = false, search: string = '') => ({ forceRefresh, search }),
        loadSlackUserById: (userId: string) => ({ userId }),
        loadSlackChannelById: (channelId: string, forceRefresh: boolean = false) => ({ channelId, forceRefresh }),
        recheckSlackChannelMembership: (channelIds: string[]) => ({ channelIds }),
        setRecentlySubscribedChannelIds: (channelIds: string[]) => ({ channelIds }),
        setSlackIntegrationInactive: (message: string | null) => ({ message }),
    }),

    loaders(({ props, values, actions }) => ({
        allSlackChannels: [
            null as { channels: SlackChannelType[]; lastRefreshedAt: string; has_more?: boolean } | null,
            {
                loadAllSlackChannels: async ({ forceRefresh, search }, breakpoint) => {
                    if (search) {
                        await breakpoint(300)
                    }
                    try {
                        const response = await api.integrations.slackChannels(props.id, forceRefresh, { search })
                        if (forceRefresh) {
                            // Only a forced refresh provably reached Slack (a plain load can be
                            // served from the backend cache), so only it may hide the reconnect banner.
                            actions.setSlackIntegrationInactive(null)
                        }
                        return response
                    } catch (e: any) {
                        if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {
                            // Keep whatever we had and surface guidance inline instead of throwing,
                            // so kea-loaders doesn't fire its generic failure toast on every retry.
                            actions.setSlackIntegrationInactive(e.detail ?? SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE)
                            return values.allSlackChannels
                        }
                        throw e
                    }
                },
            },
        ],
        allSlackUsers: [
            null as SlackUsersResponseApi | null,
            {
                loadAllSlackUsers: async ({ forceRefresh, search }, breakpoint) => {
                    if (search) {
                        await breakpoint(300)
                    }
                    try {
                        const response = await integrationsUsersRetrieve(
                            String(ApiConfig.getCurrentProjectId()),
                            props.id,
                            {
                                ...(search ? { search } : {}),
                                ...(forceRefresh ? { force_refresh: true } : {}),
                            }
                        )
                        // A slower earlier search must not overwrite a newer one's results.
                        breakpoint()
                        if (forceRefresh) {
                            // Matches the channels loader: a cached-served search proves nothing
                            // about the token, so only a forced refresh clears the banner.
                            actions.setSlackIntegrationInactive(null)
                        }
                        return response
                    } catch (e: any) {
                        if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {
                            actions.setSlackIntegrationInactive(e.detail ?? SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE)
                            return values.allSlackUsers
                        }
                        throw e
                    }
                },
            },
        ],
        slackUserById: [
            null as SlackUserApi | null,
            {
                loadSlackUserById: async ({ userId }) => {
                    try {
                        const response = await integrationsUsersRetrieve(
                            String(ApiConfig.getCurrentProjectId()),
                            props.id,
                            { user_id: userId }
                        )
                        return response.users[0] ?? null
                    } catch (e: any) {
                        if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {
                            actions.setSlackIntegrationInactive(e.detail ?? SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE)
                            return values.slackUserById
                        }
                        throw e
                    }
                },
            },
        ],
        slackChannelById: [
            null as SlackChannelType | null,
            {
                loadSlackChannelById: async ({ channelId, forceRefresh }) => {
                    const generation = values.channelListGeneration
                    try {
                        const res = await integrationsChannelsRetrieve(
                            String(ApiConfig.getCurrentProjectId()),
                            props.id,
                            {
                                channel_id: channelId,
                                ...(forceRefresh ? { force_refresh: true } : {}),
                            }
                        )
                        if (values.channelListGeneration !== generation) {
                            // A forced refresh landed while this lookup was in flight. Its list is
                            // the newer answer, and a non-forced lookup can be served from the
                            // backend cache the refresh just replaced, so drop this one whole: null
                            // keeps the by-id record untouched, and returning before the clear below
                            // keeps whatever the refresh said about the connection.
                            return null
                        }
                        if (forceRefresh) {
                            // Matches the list loader: only a forced lookup provably reached Slack,
                            // so only it may hide the reconnect banner. A plain lookup can be served
                            // from the backend's cached list while the token is still revoked.
                            actions.setSlackIntegrationInactive(null)
                        }
                        return res.channels[0] || null
                    } catch (e: any) {
                        if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {
                            actions.setSlackIntegrationInactive(e.detail ?? SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE)
                            return values.slackChannelById
                        }
                        throw e
                    }
                },
            },
        ],
    })),

    reducers(({ props }) => ({
        _fetchedSlackChannels: [
            [] as SlackChannelType[],
            {
                // allSlackChannels is null when an inactive-integration load resolves with the
                // (empty) prior state instead of throwing — keep the existing channels in that case.
                loadAllSlackChannelsSuccess: (prev, { allSlackChannels }) => allSlackChannels?.channels ?? prev,
            },
        ],
        attemptedSlackChannelIds: [
            {} as Record<string, true>,
            {
                loadSlackChannelById: (state, { channelId }) => ({ ...state, [channelId]: true }),
                loadAllSlackChannels: (state, { forceRefresh }) => (forceRefresh ? {} : state),
            },
        ],
        channelListGeneration: [
            0,
            {
                // Counts forced refreshes so a by-id lookup can tell whether the list moved under
                // it while it was in flight. Read in the loader, never rendered.
                loadAllSlackChannels: (state, { forceRefresh }) => (forceRefresh ? state + 1 : state),
            },
        ],
        _fetchedSlackChannelsById: [
            {} as Record<string, SlackChannelType>,
            {
                loadSlackChannelByIdSuccess: (state, { slackChannelById }) =>
                    slackChannelById ? { ...state, [slackChannelById.id]: slackChannelById } : state,
                // Cleared with `attemptedSlackChannelIds`, which the picker reads to decide whether a
                // channel still needs a lookup. Holding a channel here while its marker is gone left
                // the stale copy answering the membership check with nothing able to replace it, so
                // "Check again" could never clear the warning for a channel the app had just joined.
                loadAllSlackChannels: (state, { forceRefresh }) => (forceRefresh ? {} : state),
            },
        ],
        attemptedSlackUserIds: [
            {} as Record<string, true>,
            {
                loadSlackUserById: (state, { userId }) => ({ ...state, [userId]: true }),
                // A failed lookup keeps its marker: the picker's resolver effect fires whenever a
                // saved id is unmarked, so dropping it on failure would retry in an unbounded loop.
                // "Refresh members" is the explicit retry, and it clears the whole map.
                loadAllSlackUsers: (state, { forceRefresh }) => (forceRefresh ? {} : state),
            },
        ],
        _fetchedSlackUsersById: [
            {} as Record<string, SlackUserApi>,
            {
                loadSlackUserByIdSuccess: (state, { slackUserById, payload }) =>
                    slackUserById && payload ? { ...state, [payload.userId]: slackUserById } : state,
            },
        ],
        recentlySubscribedChannelIds: [
            getRecentSlackChannelIds(props.id),
            {
                setRecentlySubscribedChannelIds: (_, { channelIds }) => channelIds,
            },
        ],
        slackIntegrationInactiveMessage: [
            null as string | null,
            {
                // Only cleared by requests that provably reached Slack (forced refreshes, live
                // by-id lookups) — the loaders dispatch the clear themselves. A cache-served search
                // succeeding must not hide the banner while the token is still revoked.
                setSlackIntegrationInactive: (_, { message }) => message,
            },
        ],
    })),

    listeners(({ props, actions }) => ({
        loadAllSlackChannelsSuccess: () => {
            actions.setRecentlySubscribedChannelIds(getRecentSlackChannelIds(props.id))
        },
        // Re-reads the picked channels straight from Slack, which is one call each, rather than
        // enumerating the workspace. That keeps the re-check off the full list's refresh cooldown,
        // so someone who has just invited the app does not wait out a cooldown to see it worked.
        recheckSlackChannelMembership: ({ channelIds }) => {
            for (const channelId of channelIds) {
                actions.loadSlackChannelById(channelId, true)
            }
        },
    })),

    selectors({
        slackChannels: [
            (s) => [s._fetchedSlackChannels, s._fetchedSlackChannelsById],
            (
                _fetchedSlackChannels: SlackChannelType[],
                _fetchedSlackChannelsById: Record<string, SlackChannelType>
            ): SlackChannelType[] => {
                const listedIds = new Set(_fetchedSlackChannels.map((channel) => channel.id))
                return [
                    // A by-id lookup is the newest word on that channel, because the map is cleared
                    // whenever the list is force-refreshed. Let it override the listed copy so a live
                    // re-check of one channel's membership is not shadowed by the cached list.
                    ..._fetchedSlackChannels.map((channel) => _fetchedSlackChannelsById[channel.id] ?? channel),
                    ...Object.values(_fetchedSlackChannelsById).filter((channel) => !listedIds.has(channel.id)),
                ]
            },
        ],
        slackUsers: [
            (s) => [s.allSlackUsers, s._fetchedSlackUsersById],
            (
                allSlackUsers: SlackUsersResponseApi | null,
                _fetchedSlackUsersById: Record<string, SlackUserApi>
            ): SlackUserApi[] => {
                const listed = allSlackUsers?.users ?? []
                const listedIds = new Set(listed.map((user) => user.id))
                // Members resolved by direct lookup (saved recipients beyond the listed page, or
                // bare ids saved over the API) join the pool so their chips render a name.
                return [...listed, ...Object.values(_fetchedSlackUsersById).filter((user) => !listedIds.has(user.id))]
            },
        ],
        getUsersRefreshButtonDisabledReason: [
            (s) => [s.allSlackUsers],
            (allSlackUsers: SlackUsersResponseApi | null) => (): string => {
                const now = dayjs()
                if (allSlackUsers?.lastRefreshedAt) {
                    const earliestRefresh = dayjs(allSlackUsers.lastRefreshedAt).add(
                        SLACK_CHANNELS_MIN_REFRESH_INTERVAL_SECONDS,
                        'seconds'
                    )
                    if (now.isBefore(earliestRefresh)) {
                        const secondsLeft = Math.ceil(earliestRefresh.diff(now) / 1000)
                        return `You can refresh the members again in ${secondsLeft} second${
                            secondsLeft === 1 ? '' : 's'
                        }`
                    }
                }
                return ''
            },
        ],
        slackChannelsForPicker: [
            (s) => [s.slackChannels, s.recentlySubscribedChannelIds],
            (slackChannels: SlackChannelType[], recentlySubscribedChannelIds: string[]): SlackChannelType[] => {
                const recencyIndex = new Map(recentlySubscribedChannelIds.map((id, idx) => [id, idx]))
                return [...slackChannels].sort((a, b) => {
                    const aRecency = recencyIndex.get(a.id) ?? Number.POSITIVE_INFINITY
                    const bRecency = recencyIndex.get(b.id) ?? Number.POSITIVE_INFINITY
                    if (aRecency !== bRecency) {
                        return aRecency - bRecency
                    }
                    // Private channels the bot can't access come back from Slack without a name,
                    // so guard the comparator instead of assuming a string.
                    return (a.name ?? '').localeCompare(b.name ?? '')
                })
            },
        ],
        isMemberOfSlackChannel: [
            (s) => [s.slackChannels],
            (slackChannels: SlackChannelType[]) => {
                return (channel: string): boolean | null => {
                    const found = slackChannels.find((x) => x.id === slackChannelId(channel))
                    // Null when unknown so the picker's strict `=== false` membership gate doesn't fire spuriously.
                    return found ? (found.is_member ?? false) : null
                }
            },
        ],
        isPrivateChannelWithoutAccess: [
            (s) => [s.slackChannels],
            (slackChannels: SlackChannelType[]) => {
                return (channel: string) =>
                    slackChannels.find((x) => x.id === slackChannelId(channel))?.is_private_without_access ?? false
            },
        ],
        getChannelRefreshButtonDisabledReason: [
            (s) => [s.allSlackChannels],
            (allSlackChannels: { channels: SlackChannelType[]; lastRefreshedAt: string } | null) => (): string => {
                const now = dayjs()
                if (allSlackChannels) {
                    const earliestRefresh = dayjs(allSlackChannels.lastRefreshedAt).add(
                        SLACK_CHANNELS_MIN_REFRESH_INTERVAL_SECONDS,
                        'seconds'
                    )
                    if (now.isBefore(earliestRefresh)) {
                        const secondsLeft = Math.ceil(earliestRefresh.diff(now) / 1000)
                        return `You can refresh the channels again in ${secondsLeft} second${
                            secondsLeft === 1 ? '' : 's'
                        }`
                    }
                }
                return ''
            },
        ],
    }),
])