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.

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

import { projectLogic } from 'scenes/projectLogic'

import { llmSkillsList } from 'products/skills/frontend/generated/api'
import type { LLMSkillListApi } from 'products/skills/frontend/generated/api.schemas'

export const SKILL_OPTIONS_PAGE_SIZE = 50
const SEARCH_DEBOUNCE_MS = 300

/**
 * Kept in sync by hand with MAX_ATTACHED_SKILLS in
 * products/tasks/backend/logic/services/workflow_task_skills.py, which is the enforcing copy.
 * A drift here only makes the picker stop short or let a save fail validation, never lets an
 * over-cap list reach a run.
 */
export const MAX_ATTACHED_SKILLS = 10

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskSkillsPickerLogicValues {
    currentProjectId: number | null // projectLogic
    hasLoadedOptions: boolean
    hasMoreSkills: boolean
    search: string
    skillCount: number
    skillOptions: LLMSkillListApi[]
    skillOptionsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskSkillsPickerLogicActions {
    ensureOptionsLoaded: () => {
        value: true
    }
    loadNextPage: () => {
        value: true
    }
    loadOptions: ({ append, debounce, search }: { append?: boolean; debounce?: boolean; search: string }) => {
        append?: boolean
        debounce?: boolean
        search: string
    }
    loadOptionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadOptionsSuccess: (
        skillOptions: LLMSkillListApi[],
        payload?: {
            append?: boolean
            debounce?: boolean
            search: string
        }
    ) => {
        skillOptions: LLMSkillListApi[]
        payload?: {
            append?: boolean
            debounce?: boolean
            search: string
        }
    }
    setSearch: (search: string) => {
        search: string
    }
    setSkillCount: (count: number) => {
        count: number
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskSkillsPickerLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        hasMoreSkills: (skillOptions: LLMSkillListApi[], skillCount: number) => boolean
    }
}

export type taskSkillsPickerLogicType = MakeLogicType<
    taskSkillsPickerLogicValues,
    taskSkillsPickerLogicActions,
    Record<string, any>,
    taskSkillsPickerLogicMeta
>

export const taskSkillsPickerLogic = kea<taskSkillsPickerLogicType>([
    path(['products', 'tasks', 'frontend', 'components', 'TaskSkillsPicker', 'taskSkillsPickerLogic']),

    connect(() => ({
        values: [projectLogic, ['currentProjectId']],
    })),

    actions({
        setSearch: (search: string) => ({ search }),
        setSkillCount: (count: number) => ({ count }),
        ensureOptionsLoaded: true,
        loadNextPage: true,
    }),

    reducers({
        search: ['', { setSearch: (_: string, { search }: { search: string }) => search }],
        hasLoadedOptions: [false, { loadOptionsSuccess: () => true }],
        skillCount: [0, { setSkillCount: (_: number, { count }: { count: number }) => count }],
    }),

    loaders(({ values, actions }) => ({
        skillOptions: [
            [] as LLMSkillListApi[],
            {
                loadOptions: async (
                    { append, debounce, search }: { append?: boolean; debounce?: boolean; search: string },
                    breakpoint
                ): Promise<LLMSkillListApi[]> => {
                    // Debounce keystrokes only. Opening the dropdown should not wait.
                    if (debounce) {
                        await breakpoint(SEARCH_DEBOUNCE_MS)
                    }
                    // A new search starts from the top. Reusing the previous offset would skip
                    // the matches at the front of the new result set.
                    const offset = append ? values.skillOptions.length : 0
                    const response = await llmSkillsList(String(values.currentProjectId), {
                        limit: SKILL_OPTIONS_PAGE_SIZE,
                        offset,
                        search: search || undefined,
                        // Only uncategorized skills. The endpoint reads the parameter's presence,
                        // even when empty, as "uncategorized only", which drops Signals scouts and
                        // ReviewHog perspectives. Those are loaded by their own harnesses and would
                        // otherwise fill the first page on a Signals team. Filtering after the fetch
                        // instead would break paging, because `count` still counts what we dropped.
                        // This relies on the generated `getLlmSkillsListUrl` skipping only
                        // `undefined`, so an empty string still reaches the query string.
                        category: '',
                    })
                    breakpoint()
                    actions.setSkillCount(response.count ?? 0)
                    const results = response.results ?? []
                    return append ? [...values.skillOptions, ...results] : results
                },
            },
        ],
    })),

    selectors({
        hasMoreSkills: [
            (s) => [s.skillOptions, s.skillCount],
            (skillOptions: LLMSkillListApi[], skillCount: number): boolean => skillOptions.length < skillCount,
        ],
    }),

    listeners(({ actions, selectors, values }) => ({
        setSearch: ({ search }, _breakpoint, _action, previousState) => {
            if (search !== selectors.search(previousState)) {
                actions.loadOptions({ debounce: true, search })
            }
        },
        loadNextPage: () => {
            if (!values.skillOptionsLoading && values.hasMoreSkills) {
                actions.loadOptions({ append: true, search: values.search })
            }
        },
        ensureOptionsLoaded: () => {
            if (!values.hasLoadedOptions && !values.skillOptionsLoading) {
                actions.loadOptions({ search: values.search })
            }
        },
    })),
])