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, actions, afterMount, kea, key, listeners, path, props } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'

import api from 'lib/api'
import { hogql } from 'lib/utils/hogql'

import { CLUSTERING_RUNS_LOOKBACK_DAYS, NOISE_CLUSTER_ID } from '../clusters/constants'
import { Cluster } from '../clusters/types'

export interface ClusterInfo {
    runId: string
    runTimestamp: string
    clusterId: number
    clusterTitle: string
    clusterSize: number
    isOutlier: boolean
}

export interface ClustersTabContentLogicProps {
    traceId: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface clustersTabContentLogicValues {
    clusters: ClusterInfo[]
    clustersLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface clustersTabContentLogicActions {
    loadClusters: () => any
    loadClustersFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadClustersSuccess: (
        clusters: ClusterInfo[],
        payload?: any
    ) => {
        clusters: ClusterInfo[]
        payload?: any
    }
    refreshClusters: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface clustersTabContentLogicMeta {
    key: string
}

export type clustersTabContentLogicType = MakeLogicType<
    clustersTabContentLogicValues,
    clustersTabContentLogicActions,
    ClustersTabContentLogicProps,
    clustersTabContentLogicMeta
>

export const clustersTabContentLogic = kea<clustersTabContentLogicType>([
    path(['products', 'ai_observability', 'frontend', 'components', 'clustersTabContentLogic']),
    props({} as ClustersTabContentLogicProps),
    key((props) => props.traceId),

    actions({
        refreshClusters: true,
    }),

    loaders(({ props }) => ({
        clusters: [
            [] as ClusterInfo[],
            {
                loadClusters: async () => {
                    const response = await api.queryHogQL(
                        hogql`
                            SELECT
                                properties.$ai_clustering_run_id as run_id,
                                properties.$ai_clusters as clusters_json,
                                timestamp
                            FROM events
                            WHERE event = '$ai_trace_clusters'
                                AND timestamp >= now() - INTERVAL ${hogql.raw(String(CLUSTERING_RUNS_LOOKBACK_DAYS))} DAY
                            ORDER BY timestamp DESC
                            LIMIT 20
                        `,
                        { productKey: 'llm_analytics', scene: 'AIObservability' },
                        { refresh: 'force_blocking' }
                    )

                    const foundClusters: ClusterInfo[] = []

                    for (const row of response.results || []) {
                        const [runId, clustersJson, timestamp] = row as [string, string, string]
                        try {
                            const clustersData = JSON.parse(clustersJson || '[]') as Cluster[]
                            for (const cluster of clustersData) {
                                if (cluster.traces && props.traceId in cluster.traces) {
                                    foundClusters.push({
                                        runId,
                                        runTimestamp: timestamp,
                                        clusterId: cluster.cluster_id,
                                        clusterTitle: cluster.title || `Cluster ${cluster.cluster_id}`,
                                        clusterSize: cluster.size,
                                        isOutlier: cluster.cluster_id === NOISE_CLUSTER_ID,
                                    })
                                }
                            }
                        } catch {
                            // Skip malformed JSON
                        }
                    }

                    return foundClusters
                },
            },
        ],
    })),

    listeners(({ props: logicProps }) => ({
        loadClustersSuccess: ({ clusters }) => {
            if (clusters.length === 0) {
                posthog.capture('llma clusters empty state shown', {
                    reason: 'trace_not_in_clusters',
                    trace_id: logicProps.traceId,
                })
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.loadClusters()
    }),
])