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.

8.3 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'

import { lemonToast } from '@posthog/lemon-ui'

import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import * as alertsApi from 'products/alerts/frontend/generated/api'
import type { AlertApi } from 'products/alerts/frontend/generated/api.schemas'
import { signalSourcesLogic } from 'products/signals/frontend/inbox/signalSourcesLogic'
import type { SignalSourceConfig } from 'products/signals/frontend/inbox/types'

import { listAllEvaluationReports } from '../evaluations/evaluationsApi'
import type { EvaluationReportApi } from '../generated/api.schemas'
import { listAllPages } from '../listAllPages'
import {
    AI_OBSERVABILITY_SCOUT_TAG,
    type AIObservabilityScoutTemplateKey,
    findAIObservabilityScoutTemplate,
} from './aiObservabilityScoutTemplates'

const ANOMALY_ALERTS_PAGE_SIZE = 100

export const AI_OBSERVABILITY_SELF_DRIVING_SECTIONS = {
    SCOUTS: 'scouts',
    EVAL_REPORTS: 'eval-reports',
    ANOMALY_ALERT_INVESTIGATIONS: 'anomaly-alert-investigations',
} as const

export type AIObservabilitySelfDrivingSection =
    (typeof AI_OBSERVABILITY_SELF_DRIVING_SECTIONS)[keyof typeof AI_OBSERVABILITY_SELF_DRIVING_SECTIONS]

const DEFAULT_EXPANDED_SECTIONS: AIObservabilitySelfDrivingSection[] = [
    AI_OBSERVABILITY_SELF_DRIVING_SECTIONS.SCOUTS,
    AI_OBSERVABILITY_SELF_DRIVING_SECTIONS.EVAL_REPORTS,
    AI_OBSERVABILITY_SELF_DRIVING_SECTIONS.ANOMALY_ALERT_INVESTIGATIONS,
]

async function listAllAnomalyAlertInvestigations(projectId: string): Promise<AlertApi[]> {
    return listAllPages((offset) =>
        alertsApi.alertsList(projectId, {
            has_detector: true,
            insight_tag: AI_OBSERVABILITY_SCOUT_TAG,
            limit: ANOMALY_ALERTS_PAGE_SIZE,
            offset,
        })
    )
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiObservabilitySelfDrivingLogicValues {
    sourceConfigs: SignalSourceConfig[] | null // signalSourcesLogic
    sourceConfigsLoading: boolean // signalSourcesLogic
    anomalyAlertInvestigations: AlertApi[] | null
    anomalyAlertInvestigationsLoading: boolean
    evaluationReports: EvaluationReportApi[] | null
    evaluationReportsByEvaluationId: Record<string, EvaluationReportApi> | null
    evaluationReportsLoading: boolean
    expandedSections: AIObservabilitySelfDrivingSection[]
    openScoutTemplateKey: AIObservabilityScoutTemplateKey | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiObservabilitySelfDrivingLogicActions {
    loadSourceConfigs: () => any // signalSourcesLogic
    loadAnomalyAlertInvestigations: () => any
    loadAnomalyAlertInvestigationsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAnomalyAlertInvestigationsSuccess: (
        anomalyAlertInvestigations: AlertApi[],
        payload?: any
    ) => {
        anomalyAlertInvestigations: AlertApi[]
        payload?: any
    }
    loadSelfDrivingEvaluationReports: () => any
    loadSelfDrivingEvaluationReportsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSelfDrivingEvaluationReportsSuccess: (
        evaluationReports: EvaluationReportApi[],
        payload?: any
    ) => {
        evaluationReports: EvaluationReportApi[]
        payload?: any
    }
    setExpandedSections: (expandedSections: AIObservabilitySelfDrivingSection[]) => {
        expandedSections: AIObservabilitySelfDrivingSection[]
    }
    setOpenScoutTemplateKey: (openScoutTemplateKey: AIObservabilityScoutTemplateKey | null) => {
        openScoutTemplateKey: AIObservabilityScoutTemplateKey | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiObservabilitySelfDrivingLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        evaluationReportsByEvaluationId: (
            evaluationReports: EvaluationReportApi[] | null
        ) => Record<string, EvaluationReportApi> | null
    }
}

export type aiObservabilitySelfDrivingLogicType = MakeLogicType<
    aiObservabilitySelfDrivingLogicValues,
    aiObservabilitySelfDrivingLogicActions,
    Record<string, any>,
    aiObservabilitySelfDrivingLogicMeta
>

export const aiObservabilitySelfDrivingLogic = kea<aiObservabilitySelfDrivingLogicType>([
    path(['products', 'ai_observability', 'selfDriving', 'aiObservabilitySelfDrivingLogic']),

    connect(() => ({
        values: [signalSourcesLogic, ['sourceConfigs', 'sourceConfigsLoading']],
        actions: [signalSourcesLogic, ['loadSourceConfigs']],
    })),

    actions({
        setExpandedSections: (expandedSections: AIObservabilitySelfDrivingSection[]) => ({ expandedSections }),
        setOpenScoutTemplateKey: (openScoutTemplateKey: AIObservabilityScoutTemplateKey | null) => ({
            openScoutTemplateKey,
        }),
    }),

    loaders({
        anomalyAlertInvestigations: [
            null as AlertApi[] | null,
            {
                loadAnomalyAlertInvestigations: async () => {
                    const teamId = teamLogic.values.currentTeamId
                    return teamId ? await listAllAnomalyAlertInvestigations(teamId.toString()) : []
                },
            },
        ],
        evaluationReports: [
            null as EvaluationReportApi[] | null,
            {
                loadSelfDrivingEvaluationReports: async () => {
                    const teamId = teamLogic.values.currentTeamId
                    return teamId ? await listAllEvaluationReports(teamId.toString()) : []
                },
            },
        ],
    }),

    reducers({
        expandedSections: [
            DEFAULT_EXPANDED_SECTIONS,
            { persist: true },
            {
                setExpandedSections: (_, { expandedSections }) => expandedSections,
            },
        ],
        openScoutTemplateKey: [
            null as AIObservabilityScoutTemplateKey | null,
            {
                setOpenScoutTemplateKey: (_, { openScoutTemplateKey }) => openScoutTemplateKey,
            },
        ],
    }),

    selectors({
        evaluationReportsByEvaluationId: [
            (selectors) => [selectors.evaluationReports],
            (reports: EvaluationReportApi[] | null): Record<string, EvaluationReportApi> | null =>
                reports
                    ? Object.fromEntries(
                          reports.filter((report) => !report.deleted).map((report) => [report.evaluation, report])
                      )
                    : null,
        ],
    }),

    // `#template=<key>` opens that template's create modal, so a posthog.com pocket guide can hand
    // someone straight into it. The fragment is stripped on arrival: it carries no config of its
    // own (the template does), and leaving it in the URL would reopen the modal on every refresh.
    urlToAction(({ actions }) => ({
        [urls.aiObservabilitySelfDriving()]: (_, __, hashParams) => {
            if (hashParams?.['template'] === undefined) {
                return
            }
            const { template, ...remainingHashParams } = hashParams
            router.actions.replace(router.values.location.pathname, router.values.searchParams, remainingHashParams)
            const matched = findAIObservabilityScoutTemplate(template)
            if (matched) {
                actions.setOpenScoutTemplateKey(matched.key)
            } else {
                // The fragment is already stripped, so staying silent would leave the reader with
                // nothing to look at and nothing to report. `inboxSceneLogic` toasts here too.
                lemonToast.error("That link points to a scout template that doesn't exist. Pick one below.")
            }
        },
    })),

    afterMount(({ actions, values }) => {
        actions.loadAnomalyAlertInvestigations()
        actions.loadSelfDrivingEvaluationReports()
        // signalSourcesLogic only loads these behind the inbox's own flag, and the signal source
        // switches in this tab need the rows either way.
        if (values.sourceConfigs === null && !values.sourceConfigsLoading) {
            actions.loadSourceConfigs()
        }
    }),
])