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.1 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    beforeUnmount,
    kea,
    key,
    listeners,
    path,
    props,
    propsChanged,
    reducers,
    selectors,
} from 'kea'

import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'

import { visionObservationsLabelCreate, visionObservationsLabelDestroy } from '../generated/api'
import type { ReplayObservationLabelApi } from '../generated/api.schemas'

/** The API trims feedback before storing it, so compare on those terms: a draft ending in a newline is
 * already saved, and treating it as unsaved leaves the status stuck on "Saving…" with nothing in flight. */
function normalizeFeedback(feedback: string | null | undefined): string {
    return (feedback ?? '').trim()
}

export interface ObservationLabelLogicProps {
    observationId: string
    /** The label as loaded with the observation; seeds the logic state on mount. */
    initialLabel?: ReplayObservationLabelApi | null
    /** Notified after the server accepts a rating change (set or clear). */
    onChange?: (label: ReplayObservationLabelApi | null) => void
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationLabelLogicValues {
    feedbackDraft: string
    feedbackSynced: boolean
    label: ReplayObservationLabelApi | null
    saveFailed: boolean
    saving: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationLabelLogicActions {
    clearRating: () => {
        value: true
    }
    labelUpdated: (label: ReplayObservationLabelApi | null) => {
        label: ReplayObservationLabelApi | null
    }
    rate: (
        isCorrect: boolean,
        feedback: string
    ) => {
        feedback: string
        isCorrect: boolean
    }
    setFeedbackDraft: (feedback: string) => {
        feedback: string
    }
    setSaveFailed: (saveFailed: boolean) => {
        saveFailed: boolean
    }
    setSaving: (saving: boolean) => {
        saving: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationLabelLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        feedbackSynced: (feedbackDraft: string, label: ReplayObservationLabelApi | null) => boolean
    }
}

export type observationLabelLogicType = MakeLogicType<
    observationLabelLogicValues,
    observationLabelLogicActions,
    ObservationLabelLogicProps,
    observationLabelLogicMeta
>

/** One instance per observation: the team's shared thumbs up/down rating with feedback autosave. */
export const observationLabelLogic = kea<observationLabelLogicType>([
    path(['products', 'replay_vision', 'frontend', 'observations', 'observationLabelLogic']),
    props({} as ObservationLabelLogicProps),
    key((props) => props.observationId),

    actions({
        rate: (isCorrect: boolean, feedback: string) => ({ isCorrect, feedback }),
        clearRating: true,
        labelUpdated: (label: ReplayObservationLabelApi | null) => ({ label }),
        setSaving: (saving: boolean) => ({ saving }),
        setSaveFailed: (saveFailed: boolean) => ({ saveFailed }),
        setFeedbackDraft: (feedback: string) => ({ feedback }),
    }),

    reducers(({ props }) => ({
        label: [
            (props.initialLabel ?? null) as ReplayObservationLabelApi | null,
            {
                labelUpdated: (_, { label }) => label,
            },
        ],
        saving: [
            false,
            {
                setSaving: (_, { saving }) => saving,
            },
        ],
        saveFailed: [
            false,
            {
                setSaveFailed: (_, { saveFailed }) => saveFailed,
                // A fresh edit or rating click is a retry, so the last failure stops being the current state.
                setFeedbackDraft: () => false,
                rate: () => false,
                clearRating: () => false,
            },
        ],
        feedbackDraft: [
            props.initialLabel?.feedback ?? '',
            {
                setFeedbackDraft: (_, { feedback }) => feedback,
                // Keep the working draft while rated so an autosave round-trip can't clobber characters
                // typed while it was in flight. Clear it only when the rating is removed.
                labelUpdated: (state, { label }) => (label ? state : ''),
            },
        ],
    })),

    selectors({
        feedbackSynced: [
            (s) => [s.feedbackDraft, s.label],
            (feedbackDraft: string, label: ReplayObservationLabelApi | null): boolean =>
                normalizeFeedback(feedbackDraft) === normalizeFeedback(label?.feedback),
        ],
    }),

    propsChanged(({ actions, props, values, cache }, oldProps) => {
        // Adopt a label reloaded from the server (e.g. a teammate's change) so a stale local
        // value or pending autosave can't overwrite it.
        const next = props.initialLabel ?? null
        if (JSON.stringify(next) === JSON.stringify(oldProps.initialLabel ?? null)) {
            return
        }
        if (JSON.stringify(next) === JSON.stringify(values.label)) {
            return
        }
        cache.labelEpoch = (cache.labelEpoch ?? 0) + 1
        // The adopted label supersedes anything this viewer sent, so a note saved on unmount keeps its rating.
        cache.lastSentLabel = undefined
        actions.labelUpdated(next)
        actions.setFeedbackDraft(next?.feedback ?? '')
    }),

    listeners(({ actions, props, cache, values }) => ({
        // Autosave feedback once the user pauses typing, so they don't have to remember to press a button.
        setFeedbackDraft: async ({ feedback }, breakpoint) => {
            const label = values.label
            // Feedback only exists on a rated observation and applies to thumbs-up and thumbs-down alike.
            if (!label || normalizeFeedback(label.feedback) === normalizeFeedback(feedback)) {
                return
            }
            const epoch = cache.labelEpoch ?? 0
            await breakpoint(800)
            // A rating/clear click while the debounce was pending wins over the stale autosave.
            if ((cache.labelEpoch ?? 0) !== epoch) {
                return
            }
            actions.rate(label.is_correct, feedback)
        },

        rate: async ({ isCorrect, feedback }) => {
            cache.lastSentLabel = { is_correct: isCorrect, feedback }
            cache.labelEpoch = (cache.labelEpoch ?? 0) + 1
            const epoch = cache.labelEpoch
            const teamId = teamLogic.values.currentTeamId
            if (!teamId) {
                return
            }
            actions.setSaving(true)
            try {
                const label = await visionObservationsLabelCreate(String(teamId), props.observationId, {
                    is_correct: isCorrect,
                    feedback,
                })
                // Thumbs-up then thumbs-down can settle out of order and leave the older rating on screen.
                if ((cache.labelEpoch ?? 0) !== epoch) {
                    return
                }
                actions.labelUpdated(label)
                props.onChange?.(label)
            } catch (error: any) {
                actions.setSaveFailed(true)
                lemonToast.error(`Failed to save rating${error.detail ? `: ${error.detail}` : ''}`)
            } finally {
                actions.setSaving(false)
            }
        },

        clearRating: async () => {
            cache.lastSentLabel = null
            cache.labelEpoch = (cache.labelEpoch ?? 0) + 1
            const epoch = cache.labelEpoch
            const teamId = teamLogic.values.currentTeamId
            if (!teamId) {
                return
            }
            actions.setSaving(true)
            try {
                await visionObservationsLabelDestroy(String(teamId), props.observationId)
                if ((cache.labelEpoch ?? 0) !== epoch) {
                    return
                }
                actions.labelUpdated(null)
                props.onChange?.(null)
            } catch (error: any) {
                actions.setSaveFailed(true)
                lemonToast.error(`Failed to remove rating${error.detail ? `: ${error.detail}` : ''}`)
            } finally {
                actions.setSaving(false)
            }
        },
    })),
    // Unmounting cancels the pending autosave, so a note typed just before leaving the page saves here instead.
    beforeUnmount(({ values, props, cache }) => {
        // A rating still in flight has not reached `label` yet, and a save carrying the older rating could overwrite it.
        const latest: ReplayObservationLabelApi | null =
            cache.lastSentLabel === undefined ? values.label : cache.lastSentLabel
        const teamId = teamLogic.values.currentTeamId
        if (latest && teamId && normalizeFeedback(latest.feedback) !== normalizeFeedback(values.feedbackDraft)) {
            void visionObservationsLabelCreate(String(teamId), props.observationId, {
                is_correct: latest.is_correct,
                feedback: values.feedbackDraft,
            }).catch(() => lemonToast.error('Failed to save your note'))
        }
    }),
])