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.6 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import posthog from 'posthog-js'

import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'

import { FeedbackPromptRating, FeedbackPromptTrigger, RunRef, capturePromptFeedback } from '../utils/feedbackEvents'
import { computeTurnTrailers } from '../utils/turnTrailers'
import { runStreamLogic } from './runStreamLogic'

export interface FeedbackPromptConfig {
    cooldownMs: number
    messageInterval: number
    samplingRate: number
    cancelThreshold: number
}

// Shared with the legacy prompt on purpose: one cooldown per browser, whichever runtime showed it.
const LAST_SHOWN_STORAGE_KEY = 'posthog_ai_feedback_last_shown'

export interface FeedbackPromptLogicProps {
    /** Task id backing the sandbox conversation. Lands in `$ai_session_id`. */
    sessionId: string
    /** Key of the live `runStreamLogic` instance this prompt observes. */
    streamKey: string
}

/** What the capture needs from the stream at the moment of rating. */
interface StreamSnapshot {
    traceId: string | null
    turnIndex: number | null
    humanMessageCount: number
    run: RunRef | undefined
}

function readStream(streamKey: string): StreamSnapshot {
    const stream = runStreamLogic.findMounted({ streamKey })
    if (!stream) {
        return { traceId: null, turnIndex: null, humanMessageCount: 0, run: undefined }
    }
    const items = stream.values.threadItems
    const turnBase = stream.values.historyTurnBase
    const trailers = computeTurnTrailers(items, turnBase)
    const lastTurn = [...trailers.values()].find((trailer) => trailer.isLastTurn)
    return {
        // Same trailer as turnIndex, so the two can never describe different turns.
        traceId: lastTurn?.traceId ?? null,
        turnIndex: lastTurn?.turnIndex ?? null,
        humanMessageCount: turnBase + items.filter((item) => item.type === 'human_message').length,
        run: stream.cache.activeRun as RunRef | undefined,
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface feedbackPromptLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    receivedFeatureFlags: boolean // featureFlagLogic
    canShowPrompt: boolean
    cancelCount: number
    currentTriggerType: FeedbackPromptTrigger
    feedbackConfig: FeedbackPromptConfig | null
    isDetailedFeedbackVisible: boolean
    isPromptVisible: boolean
    isThankYouVisible: boolean
    lastTriggeredIntervalIndex: number
    messageInterval: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface feedbackPromptLogicActions {
    cancelRun: (
        run?:
            | {
                  runId: string
                  taskId: string
              }
            | undefined
    ) => {
        run:
            | {
                  runId: string
                  taskId: string
              }
            | undefined
    } // runStreamLogic
    checkShouldShowPrompt: (messageCount: number) => {
        messageCount: number
    }
    completeDetailedFeedback: () => {
        value: true
    }
    hideDetailedFeedback: () => {
        value: true
    }
    hidePrompt: () => {
        value: true
    }
    hideThankYou: () => {
        value: true
    }
    implicitDismissDetailedFeedback: () => {
        value: true
    }
    implicitDismissPrompt: () => {
        value: true
    }
    recordFeedbackShown: () => {
        value: true
    }
    setLastTriggeredIntervalIndex: (index: number) => {
        index: number
    }
    showDetailedFeedback: () => {
        value: true
    }
    showPrompt: (triggerType: FeedbackPromptTrigger) => {
        triggerType: FeedbackPromptTrigger
    }
    showThankYou: () => {
        value: true
    }
    submitDetailedFeedback: (feedbackText?: string) => {
        feedbackText: string | undefined
    }
    submitRating: (rating: FeedbackPromptRating) => {
        rating: FeedbackPromptRating
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface feedbackPromptLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        feedbackConfig: (featureFlags: FeatureFlagsSet, receivedFeatureFlags: boolean) => FeedbackPromptConfig | null
        canShowPrompt: (feedbackConfig: FeedbackPromptConfig | null) => boolean
        messageInterval: (feedbackConfig: FeedbackPromptConfig | null) => number
    }
}

export type feedbackPromptLogicType = MakeLogicType<
    feedbackPromptLogicValues,
    feedbackPromptLogicActions,
    FeedbackPromptLogicProps,
    feedbackPromptLogicMeta
>

/**
 * The periodic "how is PostHog AI doing?" prompt for the sandbox runtime. Same trigger rules and flag
 * config as the legacy Max prompt: every Nth human message, a random sample, or a run of
 * cancelled turns, throttled by a per-browser cooldown. The retry trigger has no sandbox equivalent.
 */
export const feedbackPromptLogic = kea<feedbackPromptLogicType>([
    path(['products', 'posthog_ai', 'frontend', 'logics', 'feedbackPromptLogic']),
    props({} as FeedbackPromptLogicProps),
    key((props) => props.sessionId),

    connect((props: FeedbackPromptLogicProps) => ({
        values: [featureFlagLogic, ['featureFlags', 'receivedFeatureFlags']],
        actions: [runStreamLogic({ streamKey: props.streamKey }), ['cancelRun']],
    })),

    actions({
        submitRating: (rating: FeedbackPromptRating) => ({ rating }),
        submitDetailedFeedback: (feedbackText?: string) => ({ feedbackText }),
        completeDetailedFeedback: true,
        checkShouldShowPrompt: (messageCount: number) => ({ messageCount }),
        showPrompt: (triggerType: FeedbackPromptTrigger) => ({ triggerType }),
        hidePrompt: true,
        showDetailedFeedback: true,
        hideDetailedFeedback: true,
        showThankYou: true,
        hideThankYou: true,
        implicitDismissPrompt: true,
        implicitDismissDetailedFeedback: true,
        recordFeedbackShown: true,
        setLastTriggeredIntervalIndex: (index: number) => ({ index }),
    }),

    reducers({
        isPromptVisible: [
            false,
            {
                showPrompt: () => true,
                hidePrompt: () => false,
                implicitDismissPrompt: () => false,
                showDetailedFeedback: () => false,
                showThankYou: () => false,
            },
        ],
        isDetailedFeedbackVisible: [
            false,
            {
                showDetailedFeedback: () => true,
                hideDetailedFeedback: () => false,
                implicitDismissDetailedFeedback: () => false,
                hidePrompt: () => false,
            },
        ],
        isThankYouVisible: [
            false,
            {
                showThankYou: () => true,
                hideThankYou: () => false,
                showPrompt: () => false,
            },
        ],
        currentTriggerType: [
            'manual' as FeedbackPromptTrigger,
            {
                showPrompt: (_, { triggerType }) => triggerType,
                hidePrompt: () => 'manual' as FeedbackPromptTrigger,
            },
        ],
        lastTriggeredIntervalIndex: [
            0,
            {
                setLastTriggeredIntervalIndex: (_, { index }) => index,
            },
        ],
        // Cancelled turns in this session since the prompt was last answered.
        cancelCount: [
            0,
            {
                cancelRun: (state) => state + 1,
                submitRating: () => 0,
                completeDetailedFeedback: () => 0,
            },
        ],
    }),

    selectors({
        feedbackConfig: [
            (s) => [s.featureFlags, s.receivedFeatureFlags],
            (_featureFlags: FeatureFlagsSet, receivedFeatureFlags: boolean): FeedbackPromptConfig | null => {
                const payload = getFeatureFlagPayload(FEATURE_FLAGS.POSTHOG_AI_CONVERSATION_FEEDBACK_CONFIG)
                if (!payload || typeof payload !== 'object') {
                    // Before flags resolve the payload is simply absent; only a loaded-but-missing payload is a real problem.
                    if (receivedFeatureFlags) {
                        posthog.captureException(
                            new Error('POSTHOG_AI_CONVERSATION_FEEDBACK_CONFIG feature flag is not set'),
                            { tags: { product: 'max_ai' } }
                        )
                    }
                    return null
                }
                return {
                    cooldownMs: payload.cooldownMs,
                    messageInterval: payload.messageInterval,
                    samplingRate: payload.samplingRate,
                    cancelThreshold: payload.cancelThreshold,
                }
            },
        ],
        canShowPrompt: [
            (s) => [s.feedbackConfig],
            (feedbackConfig: FeedbackPromptConfig | null): boolean => {
                if (!feedbackConfig) {
                    return false
                }
                const lastShown = localStorage.getItem(LAST_SHOWN_STORAGE_KEY)
                if (!lastShown) {
                    return true
                }
                return Date.now() - parseInt(lastShown, 10) > feedbackConfig.cooldownMs
            },
        ],
        messageInterval: [
            (s) => [s.feedbackConfig],
            (feedbackConfig: FeedbackPromptConfig | null): number => feedbackConfig?.messageInterval ?? 10,
        ],
    }),

    listeners(({ actions, values, props, cache }) => ({
        submitRating: ({ rating }) => {
            const { currentTriggerType, messageInterval } = values
            const stream = readStream(props.streamKey)

            // "bad" opens the detailed form; the capture happens on submit.
            if (rating === 'bad') {
                actions.showDetailedFeedback()
                return
            }

            capturePromptFeedback(
                props.sessionId,
                stream.traceId,
                rating,
                currentTriggerType,
                stream.turnIndex,
                stream.run
            )
            actions.recordFeedbackShown()

            // Pin the interval index so the same message count cannot re-trigger the prompt.
            actions.setLastTriggeredIntervalIndex(Math.floor(stream.humanMessageCount / messageInterval))

            if (rating === 'dismissed') {
                actions.hidePrompt()
            } else {
                actions.showThankYou()
                cache.disposables.add((): (() => void) => {
                    const timer = window.setTimeout(() => actions.hideThankYou(), 2000)
                    return () => clearTimeout(timer)
                }, 'hide-thank-you')
            }
        },

        submitDetailedFeedback: ({ feedbackText }) => {
            const stream = readStream(props.streamKey)
            capturePromptFeedback(
                props.sessionId,
                stream.traceId,
                'bad',
                values.currentTriggerType,
                stream.turnIndex,
                stream.run,
                feedbackText
            )
            actions.recordFeedbackShown()
        },

        checkShouldShowPrompt: ({ messageCount }) => {
            const { feedbackConfig } = values
            if (!feedbackConfig || values.isPromptVisible) {
                return
            }

            // Read the cooldown directly: the selector is not reactive to localStorage.
            const lastShown = localStorage.getItem(LAST_SHOWN_STORAGE_KEY)
            if (lastShown && Date.now() - parseInt(lastShown, 10) < feedbackConfig.cooldownMs) {
                return
            }

            if (values.cancelCount >= feedbackConfig.cancelThreshold) {
                actions.showPrompt('cancel')
                return
            }

            if (messageCount > 0 && messageCount % feedbackConfig.messageInterval === 0) {
                const currentIntervalIndex = Math.floor(messageCount / feedbackConfig.messageInterval)
                if (currentIntervalIndex > values.lastTriggeredIntervalIndex) {
                    actions.setLastTriggeredIntervalIndex(currentIntervalIndex)
                    actions.showPrompt('message_interval')
                    return
                }
            }

            if (Math.random() < feedbackConfig.samplingRate) {
                actions.showPrompt('random_sample')
            }
        },

        recordFeedbackShown: () => {
            localStorage.setItem(LAST_SHOWN_STORAGE_KEY, Date.now().toString())
        },

        implicitDismissPrompt: () => {
            const stream = readStream(props.streamKey)
            capturePromptFeedback(
                props.sessionId,
                stream.traceId,
                'implicit_dismiss',
                values.currentTriggerType,
                stream.turnIndex,
                stream.run
            )
            actions.recordFeedbackShown()
        },

        implicitDismissDetailedFeedback: () => {
            const stream = readStream(props.streamKey)
            capturePromptFeedback(
                props.sessionId,
                stream.traceId,
                'bad',
                values.currentTriggerType,
                stream.turnIndex,
                stream.run
            )
            actions.recordFeedbackShown()
        },

        completeDetailedFeedback: () => {
            const stream = readStream(props.streamKey)
            actions.setLastTriggeredIntervalIndex(Math.floor(stream.humanMessageCount / values.messageInterval))
            actions.hideDetailedFeedback()
        },
    })),
])