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.

13.8 KB
Raw Blame
import {
    LogicWrapper,
    MakeLogicType,
    actions,
    afterMount,
    connect,
    getContext,
    kea,
    key,
    listeners,
    path,
    props,
    propsChanged,
    reducers,
    selectors,
} from 'kea'
import posthog, { Survey, SurveyQuestionType, SurveyType } from 'posthog-js'

import { SURVEY_RATING_SCALE } from 'scenes/surveys/constants'

import { SurveyEventName, SurveyEventProperties } from '~/types'

import {
    MCPAnalyticsFeedbackPromptConfig,
    MCP_ANALYTICS_FEEDBACK_RATINGS,
    MCP_ANALYTICS_USEFULNESS_SURVEY_ID,
} from './constants'
import { mcpAnalyticsFeedbackCooldownLogic } from './mcpAnalyticsFeedbackCooldownLogic'

export const FEEDBACK_PROMPT_DELAY_MS = 30_000
export const FEEDBACK_PROMPT_COOLDOWN_MS = 30 * 24 * 60 * 60 * 1000

export interface MCPAnalyticsFeedbackLogicProps {
    userId: string
    contextKey: string
    prompt: MCPAnalyticsFeedbackPromptConfig
    isImpersonated: boolean
    eligible?: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpAnalyticsFeedbackLogicValues {
    lastPromptAt: number // mcpAnalyticsFeedbackCooldownLogic
    answer: string
    completed: boolean
    detail: string
    error: boolean
    impressionRecorded: boolean
    prompt: MCPAnalyticsFeedbackPromptConfig
    submissionId: string
    submitting: boolean
    survey: Survey | null
    surveyEventProperties: Record<string, unknown>
    visible: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpAnalyticsFeedbackLogicActions {
    recordPrompt: (timestamp: number) => {
        timestamp: number
    } // mcpAnalyticsFeedbackCooldownLogic
    captureStarted: () => {
        value: true
    }
    dismissPrompt: () => {
        value: true
    }
    hidePrompt: () => {
        value: true
    }
    impressionRecorded: () => {
        value: true
    }
    recordImpression: () => {
        value: true
    }
    responseFailed: () => {
        value: true
    }
    responseQueued: (
        answer: string,
        completed: boolean
    ) => {
        answer: string
        completed: boolean
    }
    schedulePrompt: (survey: Survey | null) => {
        survey: Survey | null
    }
    setDetail: (detail: string) => {
        detail: string
    }
    showPrompt: (
        survey: Survey,
        timestamp: number,
        submissionId: string
    ) => {
        submissionId: string
        survey: Survey
        timestamp: number
    }
    submitResponse: (
        answer: string,
        completed: boolean
    ) => {
        answer: string
        completed: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpAnalyticsFeedbackLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        surveyEventProperties: (
            survey: Survey | null,
            submissionId: string,
            prompt: MCPAnalyticsFeedbackPromptConfig
        ) => Record<string, unknown>
    }
}

export type mcpAnalyticsFeedbackLogicType = MakeLogicType<
    mcpAnalyticsFeedbackLogicValues,
    mcpAnalyticsFeedbackLogicActions,
    MCPAnalyticsFeedbackLogicProps,
    mcpAnalyticsFeedbackLogicMeta
>

function hasFeedbackQuestions(survey: Survey): boolean {
    const [choice, detail] = survey.questions
    return (
        survey.questions.length === 2 &&
        choice.type === SurveyQuestionType.Rating &&
        !!choice.id &&
        choice.scale === SURVEY_RATING_SCALE.THUMB_2_POINT &&
        choice.display === 'emoji' &&
        detail.type === SurveyQuestionType.Open &&
        !!detail.id &&
        !!detail.optional
    )
}

export const mcpAnalyticsFeedbackLogic: LogicWrapper<mcpAnalyticsFeedbackLogicType> =
    kea<mcpAnalyticsFeedbackLogicType>([
        props({ eligible: true } as MCPAnalyticsFeedbackLogicProps),
        key(({ userId, contextKey, prompt }) => JSON.stringify([userId, prompt.entryPoint, contextKey])),
        path((key) => ['products', 'mcp_analytics', 'frontend', 'feedback', 'mcpAnalyticsFeedbackLogic', key]),
        connect(({ userId }: MCPAnalyticsFeedbackLogicProps) => ({
            values: [mcpAnalyticsFeedbackCooldownLogic({ userId }), ['lastPromptAt']],
            actions: [mcpAnalyticsFeedbackCooldownLogic({ userId }), ['recordPrompt']],
        })),
        actions({
            schedulePrompt: (survey: Survey | null) => ({ survey }),
            showPrompt: (survey: Survey, timestamp: number, submissionId: string) => ({
                survey,
                timestamp,
                submissionId,
            }),
            recordImpression: true,
            impressionRecorded: true,
            dismissPrompt: true,
            hidePrompt: true,
            setDetail: (detail: string) => ({ detail }),
            submitResponse: (answer: string, completed: boolean) => ({ answer, completed }),
            responseQueued: (answer: string, completed: boolean) => ({ answer, completed }),
            responseFailed: true,
            captureStarted: true,
        }),
        reducers(({ props }) => ({
            prompt: [props.prompt, { showPrompt: () => ({ ...props.prompt }) }],
            visible: [false, { showPrompt: () => true, hidePrompt: () => false }],
            impressionRecorded: [false, { impressionRecorded: () => true }],
            survey: [null as Survey | null, { showPrompt: (_, { survey }) => survey }],
            submissionId: ['', { showPrompt: (_, { submissionId }) => submissionId }],
            answer: ['', { responseQueued: (_, { answer }) => answer }],
            detail: ['', { setDetail: (_, { detail }) => detail }],
            completed: [false, { responseQueued: (_, { completed }) => completed }],
            submitting: [
                false,
                { captureStarted: () => true, responseQueued: () => false, responseFailed: () => false },
            ],
            error: [false, { captureStarted: () => false, responseFailed: () => true }],
        })),
        selectors({
            surveyEventProperties: [
                (s) => [s.survey, s.submissionId, s.prompt],
                (
                    survey: Survey | null,
                    submissionId: string,
                    prompt: MCPAnalyticsFeedbackPromptConfig
                ): Record<string, unknown> => ({
                    feedback_surface: 'mcp_analytics',
                    feedback_entry_point: prompt.entryPoint,
                    mcp_analytics_tab: prompt.tab,
                    feedback_question_version: prompt.version,
                    feedback_question: prompt.question,
                    feedback_followup_question: prompt.followUpQuestion,
                    [SurveyEventProperties.SURVEY_ID]: survey?.id,
                    $survey_name: survey?.name,
                    [SurveyEventProperties.SURVEY_SUBMISSION_ID]: submissionId,
                    $survey_questions: survey?.questions.map(({ id }, index) => ({
                        id,
                        question: index === 0 ? prompt.question : prompt.followUpQuestion,
                    })),
                }),
            ],
        }),
        listeners(({ actions, values, props, cache }) => ({
            schedulePrompt: ({ survey }) => {
                cache.matchingSurvey = survey
                if (
                    props.eligible === false ||
                    !props.userId ||
                    props.isImpersonated ||
                    values.visible ||
                    !survey ||
                    survey.type !== SurveyType.API ||
                    !survey.start_date ||
                    survey.end_date ||
                    !hasFeedbackQuestions(survey) ||
                    !posthog.is_capturing() ||
                    Date.now() - values.lastPromptAt < FEEDBACK_PROMPT_COOLDOWN_MS
                ) {
                    cache.disposables.dispose('prompt-delay')
                    cache.pendingSurvey = null
                    return
                }
                const alreadyPending =
                    cache.pendingSurvey?.id === survey.id && cache.disposables.registry.has('prompt-delay')
                cache.pendingSurvey = survey
                if (alreadyPending) {
                    return
                }
                const context = getContext()
                cache.disposables.add(() => {
                    const timer = window.setTimeout(() => {
                        if (getContext() !== context) {
                            return
                        }
                        const surveyToShow: Survey | null = cache.pendingSurvey
                        if (
                            surveyToShow &&
                            posthog.is_capturing() &&
                            Date.now() - values.lastPromptAt >= FEEDBACK_PROMPT_COOLDOWN_MS
                        ) {
                            actions.showPrompt(surveyToShow, Date.now(), crypto.randomUUID())
                        }
                        cache.pendingSurvey = null
                        cache.disposables.dispose('prompt-delay')
                    }, FEEDBACK_PROMPT_DELAY_MS)
                    return () => window.clearTimeout(timer)
                }, 'prompt-delay')
            },
            recordImpression: () => {
                if (!values.visible || values.impressionRecorded || document.hidden || !posthog.is_capturing()) {
                    return
                }
                if (Date.now() - values.lastPromptAt < FEEDBACK_PROMPT_COOLDOWN_MS) {
                    actions.hidePrompt()
                    return
                }
                actions.impressionRecorded()
                actions.recordPrompt(Date.now())
                posthog.capture(SurveyEventName.SHOWN, values.surveyEventProperties)
            },
            recordPrompt: () => {
                if (!values.impressionRecorded) {
                    actions.hidePrompt()
                    cache.disposables.dispose('prompt-delay')
                }
            },
            dismissPrompt: () => {
                if (!values.visible) {
                    return
                }
                actions.recordImpression()
                if (values.impressionRecorded && values.survey && !values.completed) {
                    posthog.capture(SurveyEventName.DISMISSED, {
                        ...values.surveyEventProperties,
                        [SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED]: !!values.answer,
                    })
                }
                actions.hidePrompt()
            },
            submitResponse: ({ answer, completed }) => {
                const { survey } = values
                const duplicateAnswer = !completed && !!values.answer
                const mismatchedCompletion = completed && (!values.answer || answer !== values.answer)
                if (
                    !values.visible ||
                    !survey ||
                    values.completed ||
                    values.submitting ||
                    duplicateAnswer ||
                    mismatchedCompletion ||
                    !hasFeedbackQuestions(survey) ||
                    (answer !== MCP_ANALYTICS_FEEDBACK_RATINGS.UP && answer !== MCP_ANALYTICS_FEEDBACK_RATINGS.DOWN)
                ) {
                    return
                }
                actions.recordImpression()
                if (!values.impressionRecorded) {
                    return
                }
                actions.captureStarted()
                try {
                    const queued = posthog.capture(SurveyEventName.SENT, {
                        ...values.surveyEventProperties,
                        [SurveyEventProperties.SURVEY_COMPLETED]: completed,
                        [`${SurveyEventProperties.SURVEY_RESPONSE}_${survey.questions[0].id}`]: answer,
                        ...(completed && values.detail.trim()
                            ? {
                                  [`${SurveyEventProperties.SURVEY_RESPONSE}_${survey.questions[1].id}`]:
                                      values.detail.trim(),
                              }
                            : {}),
                    })
                    if (queued) {
                        actions.responseQueued(answer, completed)
                    } else {
                        actions.responseFailed()
                    }
                } catch {
                    actions.responseFailed()
                }
            },
        })),
        propsChanged(({ actions, props, cache, values }, previousProps) => {
            if (props.eligible !== previousProps.eligible) {
                if (props.eligible === false && !values.impressionRecorded) {
                    actions.hidePrompt()
                }
                actions.schedulePrompt(cache.matchingSurvey ?? null)
            }
        }),
        afterMount(({ actions, cache }) => {
            const context = getContext()
            cache.disposables.add(() =>
                posthog.onSurveysLoaded((_, surveyContext) => {
                    if (surveyContext?.isLoaded) {
                        cache.disposables.add(
                            () =>
                                posthog.onFeatureFlags(() => {
                                    posthog.getActiveMatchingSurveys((surveys) => {
                                        if (!cache.disposables.isDisposed && getContext() === context) {
                                            actions.schedulePrompt(
                                                surveys.find(({ id }) => id === MCP_ANALYTICS_USEFULNESS_SURVEY_ID) ??
                                                    null
                                            )
                                        }
                                    })
                                }),
                            'survey-flags'
                        )
                    }
                })
            )
        }),
    ])