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.

13.5 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { isAbortError } from 'lib/api'
import { ApiError, NetworkError, isTransientServerError } from 'lib/api-error'
import { userHasAccess } from 'lib/utils/accessControlUtils'
import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { teamLogic } from 'scenes/teamLogic'

import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'

import { EnrichedTraceTreeNode } from '../aiObservabilityTraceDataLogic'
import { llmAnalyticsSummarizationCreate } from '../generated/api'
import type { StructuredSummaryApi, SummarizeRequestApi, SummarizeResponseApi } from '../generated/api.schemas'
import { getSummarizationLookupDateRange } from '../utils'

export type SummaryMode = NonNullable<SummarizeRequestApi['mode']>

type SummaryData = Pick<SummarizeResponseApi, 'summary' | 'text_repr'>

export interface SummaryViewLogicProps {
    trace?: LLMTrace
    event?: LLMTraceEvent
    tree?: EnrichedTraceTreeNode[]
    autoGenerate?: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface summaryViewLogicValues {
    dataProcessingAccepted: boolean // maxGlobalLogic
    currentTeamId: number | null // teamLogic
    entityId: string | null
    isFlowExpanded: boolean
    isNotesExpanded: boolean
    isSummaryExpanded: boolean
    summaryData: SummaryData | null
    summaryDataLoading: boolean
    summaryError: string | null
    summaryMode: SummaryMode
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface summaryViewLogicActions {
    generateSummary: ({ mode, forceRefresh }: { forceRefresh?: boolean; mode: SummaryMode }) => {
        mode: SummaryMode
        forceRefresh?: boolean
    }
    generateSummaryFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    generateSummarySuccess: (
        summaryData: {
            summary: StructuredSummaryApi
            text_repr: string
        },
        payload?: {
            mode: SummaryMode
            forceRefresh?: boolean
        }
    ) => {
        summaryData: {
            summary: StructuredSummaryApi
            text_repr: string
        }
        payload?: {
            mode: SummaryMode
            forceRefresh?: boolean
        }
    }
    loadCachedSummary: () => {
        value: true
    }
    regenerateSummary: () => {
        value: true
    }
    setSummaryMode: (mode: SummaryMode) => {
        mode: SummaryMode
    }
    toggleFlowExpanded: () => {
        value: true
    }
    toggleNotesExpanded: () => {
        value: true
    }
    toggleSummaryExpanded: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface summaryViewLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        entityId: (arg: any) => string | null
    }
}

export type summaryViewLogicType = MakeLogicType<
    summaryViewLogicValues,
    summaryViewLogicActions,
    SummaryViewLogicProps,
    summaryViewLogicMeta
>

/**
 * Summarizing is a POST, so access control asks for the write level on `llm_analytics`, while
 * reading the trace asks only for the read level. A user who can open the trace can still be
 * refused here.
 */
function canSummarize(): boolean {
    return userHasAccess(AccessControlResourceType.LlmAnalytics, AccessControlLevel.Editor)
}

const GENERIC_SUMMARY_ERROR = "Couldn't generate a summary. Try again, and if it keeps happening contact support."

const NETWORK_SUMMARY_ERROR = 'Lost the connection while generating this summary. Check your connection and try again.'

/** Aborting with an `AbortError` keeps the cancellation out of toasts and error tracking. */
const SUPERSEDED_SUMMARY_REQUEST = 'a newer summary request started'

function bodylessStatusMessage(error: ApiError): string {
    if (error.status === 413) {
        return 'This trace is too large to summarize. Open a single generation and summarize that instead.'
    }
    if (error.status === 504) {
        return 'Generating this summary took too long. Try again in a moment.'
    }
    if (isTransientServerError(error)) {
        return 'The summary service is busy right now. Try again in a moment.'
    }
    return GENERIC_SUMMARY_ERROR
}

/**
 * Build the sentence the panel shows, rather than rewriting the rejected error into a new one.
 * The error object continues to error tracking, and a `NetworkError` carries its failure reason in
 * its own `name` and message, which is all `dropUnactionableNetworkExceptions` can match on.
 * Rebuilding it as a plain `ApiError` erased both, so a request the browser dropped filed an issue
 * that read as though summarization itself had broken.
 */
function summaryErrorMessage(errorObject: unknown, fallback: string | null): string {
    if (errorObject instanceof NetworkError) {
        return NETWORK_SUMMARY_ERROR
    }
    // `ApiError` falls back to `API request failed with status: 413` when the response carries no
    // body. A response that does carry a `detail` says more than any status-keyed guess.
    if (errorObject instanceof ApiError && !errorObject.detail) {
        return bodylessStatusMessage(errorObject)
    }
    return fallback || GENERIC_SUMMARY_ERROR
}

export const summaryViewLogic = kea<summaryViewLogicType>([
    path(['products', 'ai_observability', 'frontend', 'summary-view', 'summaryViewLogic']),
    props({} as SummaryViewLogicProps),
    connect(() => ({
        values: [maxGlobalLogic, ['dataProcessingAccepted'], teamLogic, ['currentTeamId']],
    })),
    key((props) => {
        // Use trace ID or event ID as the key
        if (props.trace) {
            return `trace-${props.trace.id}`
        }
        if (props.event) {
            return `event-${props.event.id}`
        }
        return 'unknown'
    }),
    actions({
        setSummaryMode: (mode: SummaryMode) => ({ mode }),
        regenerateSummary: true,
        toggleFlowExpanded: true,
        toggleSummaryExpanded: true,
        toggleNotesExpanded: true,
        loadCachedSummary: true,
    }),
    reducers({
        summaryMode: [
            'minimal' as SummaryMode,
            {
                setSummaryMode: (_, { mode }) => mode,
            },
        ],
        isFlowExpanded: [
            false,
            {
                toggleFlowExpanded: (state) => !state,
            },
        ],
        isSummaryExpanded: [
            true,
            {
                toggleSummaryExpanded: (state) => !state,
            },
        ],
        isNotesExpanded: [
            true,
            {
                toggleNotesExpanded: (state) => !state,
            },
        ],
        summaryData: [
            null as SummaryData | null,
            {
                generateSummary: () => null,
            },
        ],
        // kea-loaders dispatches `generateSummaryFailure` but keeps no value, so the failure has to
        // be held here for the view to show it.
        summaryError: [
            null as string | null,
            {
                generateSummary: () => null,
                generateSummarySuccess: () => null,
                // A cancelled request is expected control flow, so it leaves the panel as the
                // request that replaced it found it.
                generateSummaryFailure: (state, { error, errorObject }) =>
                    isAbortError(errorObject) ? state : summaryErrorMessage(errorObject, error),
            },
        ],
    }),
    selectors({
        entityId: [
            () => [(_, props) => props],
            (props: SummaryViewLogicProps): string | null => {
                if (props.trace) {
                    return props.trace.id
                }
                if (props.event) {
                    return props.event.id
                }
                return null
            },
        ],
    }),
    loaders(({ props, values, cache }) => ({
        summaryData: {
            generateSummary: async (
                { mode, forceRefresh }: { mode: SummaryMode; forceRefresh?: boolean },
                breakpoint
            ) => {
                // Initialize here rather than in the function signature to avoid TS2371
                // Kea should be fixed to avoid including the default value in the function signature
                if (forceRefresh === undefined) {
                    forceRefresh = false
                }

                // Check data processing consent before making API call
                if (!values.dataProcessingAccepted) {
                    throw new Error('AI data processing must be approved before generating summaries')
                }

                const teamId = values.currentTeamId
                if (!teamId) {
                    throw new Error('Team ID not available')
                }

                // Ask for the trace or event by ID: the endpoint reads it back from ClickHouse itself,
                // so a trace with large prompts no longer has to fit in a request body.
                const entity = props.trace ?? props.event
                if (!entity) {
                    throw new Error('Nothing to summarize')
                }
                const request: SummarizeRequestApi = {
                    mode,
                    force_refresh: forceRefresh,
                    ...(props.trace ? { trace_id: entity.id } : { generation_id: entity.id }),
                    ...getSummarizationLookupDateRange(entity.createdAt),
                }

                // Summarizing runs a model call, so the request outlives the tab strip: someone can
                // switch modes or leave the trace long before it answers. Registering the controller
                // as a disposable cancels it on unmount, and re-adding the key cancels the request
                // the new one replaces, instead of leaving both to finish and race.
                const abortController = new AbortController()
                cache.disposables.add(
                    () => () => abortController.abort(new DOMException(SUPERSEDED_SUMMARY_REQUEST, 'AbortError')),
                    'summaryRequest',
                    // A hidden tab must not cancel a summary the user is waiting on.
                    { pauseOnPageHidden: false }
                )

                const data = await llmAnalyticsSummarizationCreate(String(teamId), request, {
                    signal: abortController.signal,
                }).catch((error: unknown) => {
                    // The request that replaced this one owns the outcome now. kea-loaders keeps
                    // one loading flag per loader, so settling this invocation as a failure would
                    // clear the flag the replacement just set, and the panel would fall back to its
                    // empty state for the rest of the model call. The breakpoint drops this
                    // invocation instead of reporting it.
                    if (isAbortError(error)) {
                        breakpoint()
                    }
                    throw error
                })
                // Discard a response the user has already moved past.
                breakpoint()

                // The endpoint can resolve to an empty body (e.g. no summary available yet),
                // so guard before reading fields to avoid a null dereference.
                if (!data || !data.summary) {
                    throw new Error('No summary available for this trace yet')
                }

                return {
                    summary: data.summary,
                    text_repr: data.text_repr,
                }
            },
        },
    })),
    listeners(({ actions, values }) => ({
        loadCachedSummary: async () => {
            // Try to load cached summary - requires consent since we're hitting the summarization API
            // which will return cached data if available (forceRefresh: false)
            if (!values.dataProcessingAccepted) {
                return
            }

            const entityId = values.entityId
            if (!entityId) {
                return
            }

            // Use generateSummary with forceRefresh: false - backend returns cached data if available
            actions.generateSummary({ mode: values.summaryMode, forceRefresh: false })
        },
        regenerateSummary: () => {
            // Regenerate with current mode but force refresh to bust cache
            actions.generateSummary({ mode: values.summaryMode, forceRefresh: true })
        },
        setSummaryMode: ({ mode }) => {
            // Generate summary for new mode if we don't have data yet
            if (values.summaryData) {
                actions.generateSummary({ mode, forceRefresh: false })
            }
        },
    })),
    afterMount(({ props, actions, values }) => {
        // The cached-summary lookup is a POST too, so a user without the write level gets a denial
        // on a trace they opened to read. Leave the panel on its empty state instead.
        if (!values.dataProcessingAccepted || !canSummarize()) {
            return
        }
        if (props.autoGenerate) {
            // Auto-generate was requested (e.g., from URL param)
            actions.generateSummary({ mode: values.summaryMode, forceRefresh: false })
        } else {
            // Try to load cached summary on mount (will use cache if available)
            actions.loadCachedSummary()
        }
    }),
])