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.

2.0 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { useState } from 'react'

import { type MessageRatingOrNull, messageRatingsLogic } from '../logics/messageRatingsLogic'
import { captureTurnFeedbackText, captureTurnRating } from '../utils/feedbackEvents'
import type { TurnRatingTarget } from './turnFeedbackTypes'

export type TurnFeedbackInputStatus = 'hidden' | 'pending' | 'submitted'

export function useTurnRating({ sessionId, turnIndex, run, traceId }: TurnRatingTarget): {
    rating: MessageRatingOrNull
    submitRating: (rating: 'good' | 'bad') => void
    feedback: string
    setFeedback: (feedback: string) => void
    feedbackInputStatus: TurnFeedbackInputStatus
    closeFeedback: () => void
    submitFeedback: () => void
} {
    const { ratingForKey } = useValues(messageRatingsLogic)
    const { setRating } = useActions(messageRatingsLogic)
    // A trace id names one turn however the thread numbers its turns, so a stored rating stays on its answer.
    const ratingKey = traceId ?? `${sessionId}:turn-${turnIndex}`
    const rating = ratingForKey(ratingKey)
    const [feedback, setFeedback] = useState<string>('')
    const [feedbackInputStatus, setFeedbackInputStatus] = useState<TurnFeedbackInputStatus>('hidden')

    return {
        rating,
        submitRating: (newRating) => {
            if (rating) {
                return // Already rated
            }
            setRating({ key: ratingKey, rating: newRating })
            captureTurnRating(sessionId, traceId ?? null, newRating, turnIndex, run)
            if (newRating === 'bad') {
                setFeedbackInputStatus('pending')
            }
        },
        feedback,
        setFeedback,
        feedbackInputStatus,
        closeFeedback: () => setFeedbackInputStatus('hidden'),
        submitFeedback: () => {
            if (!feedback) {
                return // Input is empty
            }
            captureTurnFeedbackText(sessionId, traceId ?? null, feedback, turnIndex, run)
            setFeedbackInputStatus('submitted')
        },
    }
}