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.

11.2 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'

import api from 'lib/api'
import { urls } from 'scenes/urls'

import { MCPMissingCapabilitiesItem, NodeKind } from '~/queries/schema/schema-general'
import { AnyPropertyFilter } from '~/types'

import { mcpAnalyticsFiltersLogic } from '../mcpAnalyticsFiltersLogic'

export interface MCPMissingCapabilitiesDateFilter {
    dateFrom: string | null
    dateTo: string | null
}

// 30 days, matching the window behind the Activity tab's report count (ACTIVITY_WINDOW),
// so following that checklist link never shows fewer reports than the count promised.
const DEFAULT_DATE_FILTER: MCPMissingCapabilitiesDateFilter = { dateFrom: '-30d', dateTo: null }

const SEARCH_DEBOUNCE_MS = 300

// One page of reports. Each "Load more" appends the next page.
export const MISSING_CAPABILITIES_PAGE_SIZE = 50

// This value mirrors mcp_harness.UNIDENTIFIED_HARNESS_LABEL. Keep the two in sync.
export const UNIDENTIFIED_HARNESS_LABEL = 'Unidentified client'

/** Whether a report tells us nothing about which client filed it.
 *
 * The SDK only stamps `$mcp_client_name` on `$mcp_initialize`, so a report may not
 * identify its client.
 */
export function isUnidentifiedClient(harness: string): boolean {
    return !harness || harness === UNIDENTIFIED_HARNESS_LABEL
}

/** Person email/name the backend packed into the row, for PersonDisplay. */
export function parsePersonProperties(raw: string): Record<string, unknown> {
    try {
        const parsed = JSON.parse(raw || '{}')
        return parsed && typeof parsed === 'object' ? parsed : {}
    } catch {
        return {}
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpMissingCapabilitiesLogicValues {
    filterTestAccounts: boolean // mcpAnalyticsFiltersLogic
    dateFilter: MCPMissingCapabilitiesDateFilter
    hasNext: boolean
    reports: MCPMissingCapabilitiesItem[]
    reportsError: string | null
    reportsLoading: boolean
    search: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpMissingCapabilitiesLogicActions {
    hydrateFilters: (
        filterTestAccountsOverride: boolean | null,
        propertyFilters: AnyPropertyFilter[]
    ) => {
        filterTestAccountsOverride: boolean | null
        propertyFilters: AnyPropertyFilter[]
    } // mcpAnalyticsFiltersLogic
    setFilterTestAccounts: (filterTestAccounts: boolean | null) => {
        filterTestAccounts: boolean | null
    } // mcpAnalyticsFiltersLogic
    loadMoreReports: () => {
        value: true
    }
    loadMoreReportsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadMoreReportsSuccess: (
        reports: MCPMissingCapabilitiesItem[],
        payload?: {
            value: true
        }
    ) => {
        reports: MCPMissingCapabilitiesItem[]
        payload?: {
            value: true
        }
    }
    loadReports: () => {
        value: true
    }
    loadReportsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadReportsSuccess: (
        reports: MCPMissingCapabilitiesItem[],
        payload?: {
            value: true
        }
    ) => {
        reports: MCPMissingCapabilitiesItem[]
        payload?: {
            value: true
        }
    }
    setDateFilter: (
        dateFrom: string | null,
        dateTo: string | null
    ) => {
        dateFrom: string | null
        dateTo: string | null
    }
    setHasNext: (hasNext: boolean) => {
        hasNext: boolean
    }
    setSearch: (search: string) => {
        search: string
    }
}

export type mcpMissingCapabilitiesLogicType = MakeLogicType<
    mcpMissingCapabilitiesLogicValues,
    mcpMissingCapabilitiesLogicActions
>

/**
 * The Missing capabilities tab: every `$mcp_missing_capability` report an agent filed, newest
 * first. The feed stays chronological because exact-text grouping would split similar
 * free-form requests.
 */
export const mcpMissingCapabilitiesLogic = kea<mcpMissingCapabilitiesLogicType>([
    path(['products', 'mcp_analytics', 'frontend', 'missingCapabilities', 'mcpMissingCapabilitiesLogic']),

    // The internal users toggle is shared with the other tabs, so it keeps its value across them.
    connect(() => ({
        values: [mcpAnalyticsFiltersLogic, ['filterTestAccounts']],
        actions: [mcpAnalyticsFiltersLogic, ['hydrateFilters', 'setFilterTestAccounts']],
    })),

    actions({
        // These declarations keep the generated loader actions callable without placeholder arguments.
        loadReports: true,
        loadMoreReports: true,
        setSearch: (search: string) => ({ search }),
        setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
        setHasNext: (hasNext: boolean) => ({ hasNext }),
    }),

    loaders(({ values, actions }) => ({
        reports: [
            [] as MCPMissingCapabilitiesItem[],
            {
                // First page / reset (a filter change). Replaces the list.
                loadReports: async (_, breakpoint) => {
                    if (values.search) {
                        await breakpoint(SEARCH_DEBOUNCE_MS)
                    }
                    const response = (await api.query({
                        kind: NodeKind.MCPMissingCapabilitiesQuery,
                        dateRange: { date_from: values.dateFilter.dateFrom, date_to: values.dateFilter.dateTo },
                        filterTestAccounts: values.filterTestAccounts,
                        search: values.search || undefined,
                        limit: MISSING_CAPABILITIES_PAGE_SIZE,
                        offset: 0,
                    })) as { results?: MCPMissingCapabilitiesItem[]; has_next?: boolean }
                    breakpoint()
                    actions.setHasNext(response.has_next ?? false)
                    return response.results ?? []
                },
                // Load more: append the next page at offset = current length.
                loadMoreReports: async () => {
                    // Snapshot the list and the query before the await: if a reset (a filter
                    // change) lands while this page is in flight, merging against the
                    // post-await list would corrupt it, so we both offset and merge from the
                    // snapshot and drop the page entirely if the query moved underneath us.
                    const baseReports = values.reports
                    const { search, dateFilter, filterTestAccounts } = values
                    const response = (await api.query({
                        kind: NodeKind.MCPMissingCapabilitiesQuery,
                        dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },
                        filterTestAccounts,
                        search: search || undefined,
                        limit: MISSING_CAPABILITIES_PAGE_SIZE,
                        offset: baseReports.length,
                    })) as { results?: MCPMissingCapabilitiesItem[]; has_next?: boolean }
                    if (
                        search !== values.search ||
                        filterTestAccounts !== values.filterTestAccounts ||
                        dateFilter.dateFrom !== values.dateFilter.dateFrom ||
                        dateFilter.dateTo !== values.dateFilter.dateTo
                    ) {
                        return values.reports
                    }
                    actions.setHasNext(response.has_next ?? false)
                    return [...baseReports, ...(response.results ?? [])]
                },
            },
        ],
    })),

    reducers({
        search: [
            '',
            {
                setSearch: (_, { search }): string => search,
            },
        ],
        dateFilter: [
            DEFAULT_DATE_FILTER,
            {
                setDateFilter: (_, { dateFrom, dateTo }): MCPMissingCapabilitiesDateFilter => ({ dateFrom, dateTo }),
            },
        ],
        hasNext: [
            false,
            {
                setHasNext: (_, { hasNext }): boolean => hasNext,
                // Hide "Load more" the moment a reset starts, so it isn't shown (disabled,
                // spinning) during the reset; setHasNext restores it when the page resolves.
                loadReports: (): boolean => false,
            },
        ],
        reportsError: [
            null as string | null,
            {
                loadReports: (): null => null,
                loadMoreReports: (): null => null,
                loadReportsSuccess: (): null => null,
                loadMoreReportsSuccess: (): null => null,
                loadReportsFailure: (_, { error }): string => error,
                loadMoreReportsFailure: (_, { error }): string => error,
            },
        ],
    }),

    listeners(({ actions }) => ({
        // Each filter changes the result set, so each reloads the first page.
        setSearch: () => {
            actions.loadReports()
        },
        setDateFilter: () => {
            actions.loadReports()
        },
        setFilterTestAccounts: () => {
            actions.loadReports()
        },
        hydrateFilters: () => {
            actions.loadReports()
        },
    })),

    // Mirror the filters to the URL so they survive a refresh. date_from / date_to are the
    // product's shared window params; search is the same key the Sessions tab uses.
    actionToUrl(({ values }) => {
        const syncUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {
            const { currentLocation } = router.values
            const searchParams = { ...currentLocation.searchParams }
            const params: Record<string, string | null> = {
                search: values.search || null,
                date_from: values.dateFilter.dateFrom,
                date_to: values.dateFilter.dateTo,
            }
            for (const [key, value] of Object.entries(params)) {
                if (value) {
                    searchParams[key] = value
                } else {
                    delete searchParams[key]
                }
            }
            return [currentLocation.pathname, searchParams, currentLocation.hashParams, { replace: true }]
        }
        return { setSearch: syncUrl, setDateFilter: syncUrl }
    }),

    urlToAction(({ actions, values }) => ({
        [urls.mcpAnalyticsMissingCapabilities()]: (_, searchParams) => {
            const search = typeof searchParams.search === 'string' ? searchParams.search : ''
            if (search !== values.search) {
                actions.setSearch(search)
            }
            const dateFrom =
                typeof searchParams.date_from === 'string' ? searchParams.date_from : values.dateFilter.dateFrom
            const dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : null
            if (dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo) {
                actions.setDateFilter(dateFrom, dateTo)
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.loadReports()
    }),
])