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.

4.6 KB
Raw Blame
import { MakeLogicType, connect, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'

import { projectLogic } from 'scenes/projectLogic'

import { getCurrentTeamIdOrNone } from '~/lib/utils/getAppContext'

import { evaluationsList } from './generated/api'
import type { EvaluationApi } from './generated/api.schemas'

const SENTIMENT_EVALUATIONS_PAGE_SIZE = 100
/** Backstop so a runaway pager can't spin forever */
const SENTIMENT_EVALUATIONS_MAX = 1000

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sentimentEvaluationAvailabilityLogicValues {
    currentProjectId: number | null // projectLogic
    hasLoadedSentimentEvaluations: boolean
    hasSentimentEvaluations: boolean
    sentimentEvaluations: EvaluationApi[]
    sentimentEvaluationsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sentimentEvaluationAvailabilityLogicActions {
    loadSentimentEvaluations: () => any
    loadSentimentEvaluationsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSentimentEvaluationsSuccess: (
        sentimentEvaluations: EvaluationApi[],
        payload?: any
    ) => {
        sentimentEvaluations: EvaluationApi[]
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sentimentEvaluationAvailabilityLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        hasSentimentEvaluations: (sentimentEvaluations: EvaluationApi[]) => boolean
    }
}

export type sentimentEvaluationAvailabilityLogicType = MakeLogicType<
    sentimentEvaluationAvailabilityLogicValues,
    sentimentEvaluationAvailabilityLogicActions,
    Record<string, any>,
    sentimentEvaluationAvailabilityLogicMeta
>

export const sentimentEvaluationAvailabilityLogic = kea<sentimentEvaluationAvailabilityLogicType>([
    path(['products', 'ai_observability', 'frontend', 'sentimentEvaluationAvailabilityLogic']),
    connect(() => ({
        values: [projectLogic, ['currentProjectId']],
    })),

    loaders(({ values }) => ({
        sentimentEvaluations: [
            [] as EvaluationApi[],
            {
                loadSentimentEvaluations: async () => {
                    // Bootstrap may not have resolved the project yet. Reading it as "none
                    // available" hides the optional picker, where asking anyway would throw.
                    const currentTeamId = getCurrentTeamIdOrNone()
                    if (!currentTeamId) {
                        return values.sentimentEvaluations
                    }

                    const teamId = String(currentTeamId)
                    const evaluations: EvaluationApi[] = []

                    // Page through so the picker lists every evaluation, not just the first page.
                    // The list endpoint already excludes soft-deleted ones.
                    while (evaluations.length < SENTIMENT_EVALUATIONS_MAX) {
                        const response = await evaluationsList(teamId, {
                            evaluation_type: 'sentiment',
                            limit: SENTIMENT_EVALUATIONS_PAGE_SIZE,
                            offset: evaluations.length,
                            order_by: ['name'],
                        })
                        const results = response.results || []
                        evaluations.push(...results)
                        if (!response.next || results.length === 0) {
                            break
                        }
                    }

                    return evaluations
                },
            },
        ],
    })),

    reducers({
        hasLoadedSentimentEvaluations: [
            false as boolean,
            {
                loadSentimentEvaluationsSuccess: () => true,
                loadSentimentEvaluationsFailure: () => true,
            },
        ],
    }),

    selectors({
        hasSentimentEvaluations: [
            (s) => [s.sentimentEvaluations],
            (sentimentEvaluations: EvaluationApi[]): boolean => sentimentEvaluations.length > 0,
        ],
    }),

    // Fires on mount with the current value and again when the project resolves, so the
    // availability check waits for bootstrap instead of settling on "no evaluations".
    subscriptions(({ actions }) => ({
        currentProjectId: (currentProjectId: number | null) => {
            if (currentProjectId) {
                actions.loadSentimentEvaluations()
            }
        },
    })),
])