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.

9.4 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'

import { lemonToast } from '@posthog/lemon-ui'

import { ApiConfig } from 'lib/api'

import {
    mcpAnalyticsCustomHarnessesCreate,
    mcpAnalyticsCustomHarnessesDestroy,
    mcpAnalyticsCustomHarnessesList,
    mcpAnalyticsCustomHarnessesPartialUpdate,
} from '../generated/api'
import type { MCPCustomHarnessApi } from '../generated/api.schemas'

const projectId = (): string => String(ApiConfig.getCurrentProjectId())

export interface CustomHarnessFormValues {
    name: string
    match_pattern: string
    icon: string
}

const EMPTY_FORM: CustomHarnessFormValues = { name: '', match_pattern: '', icon: '' }

// Mirrors the server check in custom_harness_icons.py, so most mistakes show before a save.
// Matching the whole value keeps the preview mask to one data URI.
const MAX_ICON_BYTES = 16 * 1024
const ICON_DATA_URI = /^data:image\/(png|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/

function iconError(icon: string): string | undefined {
    if (!icon) {
        return undefined
    }
    if (!ICON_DATA_URI.test(icon)) {
        return 'Paste a PNG, GIF or WebP image as a data URI.'
    }
    const base64 = icon.slice(icon.indexOf(',') + 1)
    const padding = base64.length - base64.replace(/=+$/, '').length
    const decodedBytes = (base64.length * 3) / 4 - padding
    return decodedBytes > MAX_ICON_BYTES ? 'The icon must be 16 KB or smaller.' : undefined
}

/** The id of the harness being edited, `'new'` while adding one, or null when no form is open. */
export type EditingHarnessId = string | 'new' | null

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpCustomHarnessesLogicValues {
    customHarnessForm: CustomHarnessFormValues
    customHarnessFormAllErrors: Record<string, any>
    customHarnessFormChanged: boolean
    customHarnessFormErrors: DeepPartialMap<CustomHarnessFormValues, ValidationErrorType>
    customHarnessFormHasErrors: boolean
    customHarnessFormManualErrors: Record<string, any>
    customHarnessFormTouched: boolean
    customHarnessFormTouches: Record<string, boolean>
    customHarnessFormValidationErrors: DeepPartialMap<CustomHarnessFormValues, ValidationErrorType>
    customHarnessIcons: Map<string, string>
    customHarnesses: MCPCustomHarnessApi[] | null
    customHarnessesLoading: boolean
    deletingHarnessId: string | null
    editingHarnessId: EditingHarnessId
    isCustomHarnessFormSubmitting: boolean
    isCustomHarnessFormValid: boolean
    saveInProgressReason: string | null
    showCustomHarnessFormErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpCustomHarnessesLogicActions {
    cancelEditingHarness: () => {
        value: true
    }
    deleteCustomHarness: (id: string) => {
        id: string
    }
    deleteCustomHarnessFinished: () => {
        value: true
    }
    loadCustomHarnesses: () => any
    loadCustomHarnessesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCustomHarnessesSuccess: (
        customHarnesses: MCPCustomHarnessApi[],
        payload?: any
    ) => {
        customHarnesses: MCPCustomHarnessApi[]
        payload?: any
    }
    resetCustomHarnessForm: (values?: CustomHarnessFormValues) => {
        values?: CustomHarnessFormValues
    }
    setCustomHarnessFormManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setCustomHarnessFormValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setCustomHarnessFormValues: (values: DeepPartial<CustomHarnessFormValues>) => {
        values: DeepPartial<CustomHarnessFormValues>
    }
    startAddingHarness: () => {
        value: true
    }
    startEditingHarness: (harness: MCPCustomHarnessApi) => {
        harness: MCPCustomHarnessApi
    }
    submitCustomHarnessForm: () => {
        value: boolean
    }
    submitCustomHarnessFormFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitCustomHarnessFormRequest: (customHarnessForm: CustomHarnessFormValues) => {
        customHarnessForm: CustomHarnessFormValues
    }
    submitCustomHarnessFormSuccess: (customHarnessForm: CustomHarnessFormValues) => {
        customHarnessForm: CustomHarnessFormValues
    }
    touchCustomHarnessFormField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpCustomHarnessesLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        customHarnessIcons: (customHarnesses: MCPCustomHarnessApi[] | null) => Map<string, string>
        saveInProgressReason: (isCustomHarnessFormSubmitting: boolean) => string | null
    }
}

export type mcpCustomHarnessesLogicType = MakeLogicType<
    mcpCustomHarnessesLogicValues,
    mcpCustomHarnessesLogicActions,
    Record<string, any>,
    mcpCustomHarnessesLogicMeta
>

export const mcpCustomHarnessesLogic = kea<mcpCustomHarnessesLogicType>([
    path(['products', 'mcp_analytics', 'frontend', 'settings', 'mcpCustomHarnessesLogic']),
    actions({
        startAddingHarness: true,
        startEditingHarness: (harness: MCPCustomHarnessApi) => ({ harness }),
        cancelEditingHarness: true,
        deleteCustomHarness: (id: string) => ({ id }),
        deleteCustomHarnessFinished: true,
    }),
    reducers({
        editingHarnessId: [
            null as EditingHarnessId,
            {
                startAddingHarness: () => 'new',
                startEditingHarness: (_, { harness }) => harness.id,
                cancelEditingHarness: () => null,
                submitCustomHarnessFormSuccess: () => null,
            },
        ],
        deletingHarnessId: [
            null as string | null,
            {
                deleteCustomHarness: (_, { id }) => id,
                deleteCustomHarnessFinished: () => null,
            },
        ],
    }),
    loaders({
        customHarnesses: [
            null as MCPCustomHarnessApi[] | null,
            {
                loadCustomHarnesses: async () => await mcpAnalyticsCustomHarnessesList(projectId()),
            },
        ],
    }),
    selectors({
        customHarnessIcons: [
            (s) => [s.customHarnesses],
            (customHarnesses: MCPCustomHarnessApi[] | null): Map<string, string> =>
                new Map((customHarnesses ?? []).filter((h) => h.icon).map((h) => [h.name, h.icon as string])),
        ],
    }),
    forms(({ actions, values }) => ({
        customHarnessForm: {
            defaults: EMPTY_FORM,
            errors: ({ name, match_pattern, icon }) => ({
                name: name.trim() ? undefined : 'Enter a name',
                match_pattern: match_pattern.trim() ? undefined : 'Enter the text to match',
                icon: iconError(icon.trim()),
            }),
            submit: async ({ name, match_pattern, icon }) => {
                const harness = { name: name.trim(), match_pattern, icon: icon.trim() }
                const editingId = values.editingHarnessId
                try {
                    if (editingId && editingId !== 'new') {
                        await mcpAnalyticsCustomHarnessesPartialUpdate(projectId(), editingId, harness)
                    } else {
                        await mcpAnalyticsCustomHarnessesCreate(projectId(), harness)
                    }
                } catch (error) {
                    lemonToast.error(
                        (error as { detail?: string })?.detail ||
                            'Could not save the custom harness. Check the name and text, then try again.'
                    )
                    throw error
                }
                posthog.capture(editingId === 'new' ? 'mcp custom harness created' : 'mcp custom harness updated')
                actions.loadCustomHarnesses()
            },
        },
    })),
    selectors({
        saveInProgressReason: [
            (s) => [s.isCustomHarnessFormSubmitting],
            (isSubmitting: boolean): string | null => (isSubmitting ? 'Wait for the save to finish' : null),
        ],
    }),
    listeners(({ actions }) => ({
        startAddingHarness: () => {
            actions.resetCustomHarnessForm(EMPTY_FORM)
        },
        startEditingHarness: ({ harness }) => {
            actions.resetCustomHarnessForm({
                name: harness.name,
                match_pattern: harness.match_pattern,
                icon: harness.icon ?? '',
            })
        },
        cancelEditingHarness: () => {
            actions.resetCustomHarnessForm(EMPTY_FORM)
        },
        deleteCustomHarness: async ({ id }) => {
            try {
                await mcpAnalyticsCustomHarnessesDestroy(projectId(), id)
            } catch {
                lemonToast.error('Could not delete the custom harness. Try again.')
                return
            } finally {
                actions.deleteCustomHarnessFinished()
            }
            posthog.capture('mcp custom harness deleted')
            actions.loadCustomHarnesses()
        },
    })),
    afterMount(({ actions }) => {
        actions.loadCustomHarnesses()
    }),
])