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.

3.8 KB
Raw Blame
import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'

export type MessageRating = 'good' | 'bad'
export type MessageRatingOrNull = MessageRating | null

const MAX_STORED_RATINGS = 1000

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface messageRatingsLogicValues {
    ratingForKey: (key: string | null | undefined) => MessageRatingOrNull
    ratingsByKey: Record<string, MessageRating>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface messageRatingsLogicActions {
    clearAllRatings: () => {
        value: true
    }
    clearRating: (payload: { key: string }) => {
        key: string
    }
    pruneOldRatings: () => {
        value: true
    }
    setRating: (payload: { key: string; rating: MessageRating }) => {
        key: string
        rating: MessageRating
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface messageRatingsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        ratingForKey: (
            ratingsByKey: Record<string, MessageRating>
        ) => (key: string | null | undefined) => MessageRatingOrNull
    }
}

export type messageRatingsLogicType = MakeLogicType<
    messageRatingsLogicValues,
    messageRatingsLogicActions,
    Record<string, any>,
    messageRatingsLogicMeta
>

/**
 * Persists PostHog AI answer ratings ("good"/"bad") in localStorage.
 *
 * Keys are trace ids. A sandbox turn without a trace id uses `<conversationId>:turn-<n>`.
 */
export const messageRatingsLogic = kea<messageRatingsLogicType>([
    path(['scenes', 'max', 'logics', 'messageRatingsLogic']),

    actions({
        setRating: (payload: { key: string; rating: MessageRating }) => ({
            key: payload.key.trim(),
            rating: payload.rating,
        }),
        clearRating: (payload: { key: string }) => ({ key: payload.key.trim() }),
        clearAllRatings: true,
        pruneOldRatings: true,
    }),

    reducers({
        ratingsByKey: [
            {} as Record<string, MessageRating>,
            // storageKey predates the key-based rename — changing it would silently drop users' saved ratings.
            { persist: true, storageKey: 'posthog_ai_ratings' },
            {
                setRating: (state, { key, rating }) => ({
                    ...state,
                    [key]: rating,
                }),
                clearRating: (state, { key }) => {
                    if (!(key in state)) {
                        return state
                    }
                    const next = { ...state }
                    delete next[key]
                    return next
                },
                clearAllRatings: () => ({}),
                pruneOldRatings: (state) => {
                    const entries = Object.entries(state)
                    if (entries.length <= MAX_STORED_RATINGS) {
                        return state
                    }
                    return Object.fromEntries(entries.slice(-MAX_STORED_RATINGS))
                },
            },
        ],
    }),

    selectors({
        ratingForKey: [
            (s) => [s.ratingsByKey],
            (ratingsByKey: Record<string, MessageRating>) => {
                return (key: string | null | undefined): MessageRatingOrNull => {
                    if (!key) {
                        return null
                    }
                    return ratingsByKey[key] ?? null
                }
            },
        ],
    }),

    listeners(({ actions, values }) => ({
        setRating: () => {
            // Prune old ratings if we've exceeded the limit
            if (Object.keys(values.ratingsByKey).length > MAX_STORED_RATINGS) {
                actions.pruneOldRatings()
            }
        },
    })),
])