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.

17.0 KB
Raw Blame
import { MakeLogicType, actions, afterMount, isBreakpoint, kea, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'

import { objectsEqual } from 'lib/utils/objects'

import { ApiConfig, ApiError } from '~/lib/api'
import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'
import { trackedActionToUrl } from '~/lib/logic/scenes/trackedActionToUrl'
import { urls } from '~/scenes/urls'

import { INBOX_CONFIG_TAB_KEY } from 'products/signals/frontend/inbox/types'
import { storeCommunityScoutCreateTemplate } from 'products/signals/frontend/inbox/utils/scoutTemplateDeepLink'

import {
    communitySkillsInstallCreate,
    communitySkillsList,
    communitySkillsRenderCreate,
    communitySkillsVoteCreate,
} from './generated/api'
import { CommunitySkillKindEnumApi, CommunitySkillTrustTierEnumApi } from './generated/api.schemas'
import type { CommunitySkillListApi, PaginatedCommunitySkillListListApi } from './generated/api.schemas'

export const COMMUNITY_SKILLS_PER_PAGE = 30

const TRUST_TIERS = Object.values(CommunitySkillTrustTierEnumApi)
const KINDS = Object.values(CommunitySkillKindEnumApi)

export interface CommunitySkillFilters {
    page: number
    search: string
    order_by: string
    tag: string
    trust_tier: CommunitySkillTrustTierEnumApi | ''
    kind: CommunitySkillKindEnumApi | ''
}

// Filters can arrive from the URL, so anything that isn't a known tier falls back to "all tiers".
function cleanTrustTier(value: unknown): CommunitySkillTrustTierEnumApi | '' {
    return TRUST_TIERS.find((tier) => tier === value) ?? ''
}

// Filters can arrive from the URL, so anything that isn't a known kind falls back to "everything".
function cleanKind(value: unknown): CommunitySkillKindEnumApi | '' {
    return KINDS.find((kind) => kind === value) ?? ''
}

function cleanFilters(values: Partial<CommunitySkillFilters>): CommunitySkillFilters {
    const kind = cleanKind(values.kind)
    return {
        page: parseInt(String(values.page)) || 1,
        search: String(values.search || ''),
        order_by: values.order_by || (kind === CommunitySkillKindEnumApi.Scout ? '-vote_count' : '-install_count'),
        tag: String(values.tag || ''),
        trust_tier: cleanTrustTier(values.trust_tier),
        kind,
    }
}

function cleanFilterUrlParams(filters: CommunitySkillFilters): Record<string, unknown> {
    return {
        page: filters.page === 1 ? undefined : filters.page,
        search: filters.search || undefined,
        order_by:
            filters.order_by === (filters.kind === CommunitySkillKindEnumApi.Scout ? '-vote_count' : '-install_count')
                ? undefined
                : filters.order_by,
        tag: filters.tag || undefined,
        trust_tier: filters.trust_tier || undefined,
        kind: filters.kind || undefined,
    }
}

export type CommunitySkillsLogicProps = Record<string, never>

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface communitySkillsLogicValues {
    count: number
    displaySkills: CommunitySkillListApi[]
    filters: CommunitySkillFilters
    installingSlugs: Record<string, boolean>
    pagination: PaginationManual
    rawFilters: Partial<CommunitySkillFilters> | null
    settingUpSlugs: Record<string, boolean>
    skills: PaginatedCommunitySkillListListApi
    skillsLoading: boolean
    voteOverrides: Record<
        string,
        {
            has_voted: boolean
            vote_count: number
        }
    >
    votingSlugs: Record<string, boolean>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface communitySkillsLogicActions {
    installSkill: (
        slug: string,
        newName?: string,
        variables?: Record<string, string>
    ) => {
        newName: string | undefined
        slug: string
        variables: Record<string, string> | undefined
    }
    installSkillFailure: (slug: string) => {
        slug: string
    }
    installSkillSuccess: (slug: string) => {
        slug: string
    }
    loadSkills: (debounce?: boolean) => {
        debounce: boolean
    }
    loadSkillsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSkillsSuccess: (
        skills: PaginatedCommunitySkillListListApi,
        payload?: {
            debounce: boolean
        }
    ) => {
        skills: PaginatedCommunitySkillListListApi
        payload?: {
            debounce: boolean
        }
    }
    setFilters: (
        filters: Partial<CommunitySkillFilters>,
        merge?: boolean,
        debounce?: boolean
    ) => {
        debounce: boolean
        filters: Partial<CommunitySkillFilters>
        merge: boolean
    }
    setUpScout: (
        slug: string,
        variables?: Record<string, string>
    ) => {
        slug: string
        variables: Record<string, string> | undefined
    }
    setUpScoutFailure: (slug: string) => {
        slug: string
    }
    setUpScoutSuccess: (slug: string) => {
        slug: string
    }
    toggleVote: (slug: string) => {
        slug: string
    }
    toggleVoteFailure: (slug: string) => {
        slug: string
    }
    toggleVoteSuccess: (
        slug: string,
        voteResult: {
            has_voted: boolean
            vote_count: number
        }
    ) => {
        slug: string
        voteResult: {
            has_voted: boolean
            vote_count: number
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface communitySkillsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        filters: (rawFilters: Partial<CommunitySkillFilters> | null) => CommunitySkillFilters
        count: (skills: PaginatedCommunitySkillListListApi) => number
        displaySkills: (
            skills: PaginatedCommunitySkillListListApi,
            voteOverrides: Record<
                string,
                {
                    has_voted: boolean
                    vote_count: number
                }
            >
        ) => CommunitySkillListApi[]
        pagination: (filters: CommunitySkillFilters, count: number) => PaginationManual
    }
}

export type communitySkillsLogicType = MakeLogicType<
    communitySkillsLogicValues,
    communitySkillsLogicActions,
    CommunitySkillsLogicProps,
    communitySkillsLogicMeta
>

export const communitySkillsLogic = kea<communitySkillsLogicType>([
    path(['scenes', 'skills', 'communitySkillsLogic']),
    props({} as CommunitySkillsLogicProps),

    actions({
        setFilters: (filters: Partial<CommunitySkillFilters>, merge: boolean = true, debounce: boolean = true) => ({
            filters,
            merge,
            debounce,
        }),
        loadSkills: (debounce: boolean = true) => ({ debounce }),
        installSkill: (slug: string, newName?: string, variables?: Record<string, string>) => ({
            slug,
            newName,
            variables,
        }),
        installSkillSuccess: (slug: string) => ({ slug }),
        installSkillFailure: (slug: string) => ({ slug }),
        setUpScout: (slug: string, variables?: Record<string, string>) => ({ slug, variables }),
        setUpScoutSuccess: (slug: string) => ({ slug }),
        setUpScoutFailure: (slug: string) => ({ slug }),
        toggleVote: (slug: string) => ({ slug }),
        toggleVoteSuccess: (slug: string, voteResult: { has_voted: boolean; vote_count: number }) => ({
            slug,
            voteResult,
        }),
        toggleVoteFailure: (slug: string) => ({ slug }),
    }),

    reducers({
        rawFilters: [
            null as Partial<CommunitySkillFilters> | null,
            {
                setFilters: (state, { filters, merge }) =>
                    cleanFilters({
                        ...(merge ? state || {} : {}),
                        ...filters,
                        ...('page' in filters ? {} : { page: 1 }),
                    }),
            },
        ],
        // Optimistic per-slug vote state keyed by slug, merged over the server values for snappy UI.
        voteOverrides: [
            {} as Record<string, { has_voted: boolean; vote_count: number }>,
            {
                toggleVoteSuccess: (state, { slug, voteResult }) => ({ ...state, [slug]: voteResult }),
            },
        ],
        installingSlugs: [
            {} as Record<string, boolean>,
            {
                installSkill: (state, { slug }) => ({ ...state, [slug]: true }),
                installSkillSuccess: (state, { slug }) => ({ ...state, [slug]: false }),
                installSkillFailure: (state, { slug }) => ({ ...state, [slug]: false }),
            },
        ],
        settingUpSlugs: [
            {} as Record<string, boolean>,
            {
                setUpScout: (state, { slug }) => ({ ...state, [slug]: true }),
                setUpScoutSuccess: (state, { slug }) => ({ ...state, [slug]: false }),
                setUpScoutFailure: (state, { slug }) => ({ ...state, [slug]: false }),
            },
        ],
        votingSlugs: [
            {} as Record<string, boolean>,
            {
                toggleVote: (state, { slug }) => ({ ...state, [slug]: true }),
                toggleVoteSuccess: (state, { slug }) => ({ ...state, [slug]: false }),
                toggleVoteFailure: (state, { slug }) => ({ ...state, [slug]: false }),
            },
        ],
    }),

    loaders(({ values }) => ({
        skills: [
            { results: [], count: 0 } as PaginatedCommunitySkillListListApi,
            {
                loadSkills: async ({ debounce }, breakpoint) => {
                    // The delay debounces typing and filter changes. Mount and URL entry pass
                    // debounce=false so the first load isn't held back by it.
                    await breakpoint(debounce ? 300 : 0)
                    const { filters } = values
                    const response = await communitySkillsList(String(ApiConfig.getCurrentTeamId()), {
                        search: filters.search,
                        order_by: filters.order_by,
                        tag: filters.tag,
                        trust_tier: filters.trust_tier || undefined,
                        kind: filters.kind || undefined,
                        offset: Math.max(0, (filters.page - 1) * COMMUNITY_SKILLS_PER_PAGE),
                        limit: COMMUNITY_SKILLS_PER_PAGE,
                    })
                    // Discard this response if newer filters started another load while it was in flight.
                    breakpoint()
                    return response
                },
            },
        ],
    })),

    selectors({
        filters: [
            (s) => [s.rawFilters],
            (rawFilters: Partial<CommunitySkillFilters> | null): CommunitySkillFilters =>
                cleanFilters(rawFilters || {}),
        ],
        count: [(s) => [s.skills], (skills: PaginatedCommunitySkillListListApi) => skills.count],
        // Server results with optimistic vote overrides applied.
        displaySkills: [
            (s) => [s.skills, s.voteOverrides],
            (
                skills: PaginatedCommunitySkillListListApi,
                voteOverrides: Record<string, { has_voted: boolean; vote_count: number }>
            ): CommunitySkillListApi[] =>
                skills.results.map((skill) => {
                    const override = voteOverrides[skill.slug]
                    return override ? { ...skill, ...override } : skill
                }),
        ],
        pagination: [
            (s) => [s.filters, s.count],
            (filters: CommunitySkillFilters, count: number): PaginationManual => ({
                controlled: true,
                pageSize: COMMUNITY_SKILLS_PER_PAGE,
                currentPage: filters.page,
                entryCount: count,
            }),
        ],
    }),

    listeners(({ actions, asyncActions, values, selectors }) => ({
        setFilters: async ({ debounce }, _, __, previousState) => {
            const oldFilters = selectors.filters(previousState)
            if (!objectsEqual(oldFilters, values.filters)) {
                await asyncActions.loadSkills(debounce)
            }
        },

        installSkill: async ({ slug, newName, variables }) => {
            try {
                await communitySkillsInstallCreate(String(ApiConfig.getCurrentTeamId()), slug, {
                    new_name: newName,
                    variables,
                })
                lemonToast.success(`Installed "${newName || slug}" into your project.`)
                actions.installSkillSuccess(slug)
                router.actions.push(urls.skill(newName || slug))
            } catch (e) {
                console.error('Failed to install community skill', e)
                const detail = e instanceof ApiError ? e.detail : null
                lemonToast.error(detail || 'Could not install the skill. Try again in a moment.')
                actions.installSkillFailure(slug)
            }
        },

        // A scout can't be installed as a skill — it runs on a schedule under privileged scopes. So
        // render it server-side, then hand the result to the scout form, where a person reviews the
        // schedule and submits it.
        setUpScout: async ({ slug, variables }, breakpoint) => {
            try {
                const rendered = await communitySkillsRenderCreate(String(ApiConfig.getCurrentTeamId()), slug, {
                    variables,
                })
                // A newer setup supersedes this one, so a slow render cannot replace the form the
                // person asked for last, or pull them back after they moved on.
                breakpoint()
                // The catalog syncs hourly, so an open card can name an entry that is no longer a
                // scout. The render response is the authority: without this the store would hand
                // ordinary skill instructions to the form that creates an auto-running scout.
                if (rendered.kind !== CommunitySkillKindEnumApi.Scout) {
                    lemonToast.error('This entry is no longer a scout. Refresh the store and try again.')
                    actions.setUpScoutFailure(slug)
                    return
                }
                const template = storeCommunityScoutCreateTemplate({
                    // The display name travels, the skill name does not: the create endpoint derives
                    // an identifier from the display name and adds a suffix when the project already
                    // holds that slug, so a local name clash resolves itself instead of returning
                    // 409 against a field the form never shows.
                    display_name: rendered.name,
                    description: rendered.description,
                    body: rendered.body,
                    config: rendered.scout_config,
                })
                actions.setUpScoutSuccess(slug)
                router.actions.push(urls.inbox(INBOX_CONFIG_TAB_KEY), {}, { createScout: template })
            } catch (e) {
                if (e instanceof Error && isBreakpoint(e)) {
                    // Superseded: clear this card so it stops spinning, and let the newer setup navigate.
                    actions.setUpScoutFailure(slug)
                    throw e
                }
                console.error('Failed to set up community scout', e)
                const detail = e instanceof ApiError ? e.detail : null
                lemonToast.error(detail || 'Could not open this scout. Try again in a moment.')
                actions.setUpScoutFailure(slug)
            }
        },

        toggleVote: async ({ slug }) => {
            try {
                const result = await communitySkillsVoteCreate(String(ApiConfig.getCurrentTeamId()), slug)
                actions.toggleVoteSuccess(slug, result)
            } catch (e) {
                console.error('Failed to vote on community skill', e)
                const detail = e instanceof ApiError ? e.detail : null
                lemonToast.error(detail || 'Could not save your vote. Try again in a moment.')
                actions.toggleVoteFailure(slug)
            }
        },
    })),

    trackedActionToUrl(({ values }) => {
        const changeUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] | void => {
            const nextValues = cleanFilterUrlParams(values.filters)
            const urlValues = cleanFilters(router.values.searchParams)
            if (!objectsEqual(values.filters, urlValues)) {
                return [urls.communitySkills(), nextValues, {}, { replace: true }]
            }
        }
        return { setFilters: changeUrl }
    }),

    urlToAction(({ actions, values }) => ({
        [urls.communitySkills()]: (_, searchParams) => {
            const newFilters = cleanFilters(searchParams)
            if (!objectsEqual(values.filters, newFilters)) {
                actions.setFilters(newFilters, false, false)
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.loadSkills(false)
    }),
])