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.

6.2 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'

import api from 'lib/api'
import { HogQLQueryString, escapePropertyAsHogQLIdentifier, hogql } from 'lib/utils/hogql'
import { getTimestampFromUUIDv7 } from 'scenes/sessions/sessionProfileLogic'

import { QueryLogTags } from '~/queries/schema/schema-general'

import { PinnedProperty, observationPinnedPropertiesLogic } from './observationPinnedPropertiesLogic'

const QUERY_TAGS: QueryLogTags = { scene: 'ReplayVisionObservation', productKey: 'replay_vision' }

export interface ObservationSessionPropertiesLogicProps {
    sessionId: string
}

/** Identifies a pin in the response map, since the same key can be pinned from two namespaces. */
export function pinnedPropertyId(property: PinnedProperty): string {
    return `${property.type}:${property.key}`
}

/**
 * A property keeps its own type through HogQL, so a pin like $browser_version comes back as a
 * number and a flag as a boolean. The strip renders text, so everything is stringified here.
 */
export function toDisplayValue(value: unknown): string | null {
    if (value === null || value === undefined || value === '') {
        return null
    }
    if (typeof value === 'string') {
        return value
    }
    if (typeof value === 'number' || typeof value === 'boolean') {
        return String(value)
    }
    return JSON.stringify(value)
}

function selectExpression(property: PinnedProperty): string {
    const identifier = escapePropertyAsHogQLIdentifier(property.key)
    if (property.type === 'session') {
        return `session.${identifier}`
    }
    if (property.type === 'person') {
        return `person.properties.${identifier}`
    }
    return `properties.${identifier}`
}

function buildQuery(sessionId: string, properties: PinnedProperty[]): HogQLQueryString {
    // Positional aliases, because the same key can be pinned from two namespaces and would collide.
    const selects = properties
        .map((property, index) => `any(${selectExpression(property)}) as pinned_${index}`)
        .join(', ')
    const { startDate, endDate } = getTimestampFromUUIDv7(sessionId)
    return hogql`
        SELECT ${hogql.raw(selects)}
        FROM events
        WHERE $session_id = ${sessionId}
            AND timestamp >= toDateTime(${startDate.toISOString()})
            AND timestamp <= toDateTime(${endDate.toISOString()})`
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationSessionPropertiesLogicValues {
    queryablePinnedProperties: PinnedProperty[] // observationPinnedPropertiesLogic
    sessionProperties: Record<string, string | null> | null
    sessionPropertiesLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationSessionPropertiesLogicActions {
    setPinnedProperties: (properties: PinnedProperty[]) => {
        properties: PinnedProperty[]
    } // observationPinnedPropertiesLogic
    loadSessionProperties: (_: any) => any
    loadSessionPropertiesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSessionPropertiesSuccess: (
        sessionProperties: {
            [k: string]: string | null
        } | null,
        payload?: any
    ) => {
        sessionProperties: {
            [k: string]: string | null
        } | null
        payload?: any
    }
}

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

export type observationSessionPropertiesLogicType = MakeLogicType<
    observationSessionPropertiesLogicValues,
    observationSessionPropertiesLogicActions,
    ObservationSessionPropertiesLogicProps,
    observationSessionPropertiesLogicMeta
>

/**
 * Reads the pinned properties for one observed session. One pass over the session's events serves
 * all three namespaces: session columns, event property bags, and the person behind the session.
 */
export const observationSessionPropertiesLogic = kea<observationSessionPropertiesLogicType>([
    path(['products', 'replay_vision', 'frontend', 'observations', 'observationSessionPropertiesLogic']),
    props({} as ObservationSessionPropertiesLogicProps),
    key((props) => props.sessionId),

    connect(() => ({
        values: [observationPinnedPropertiesLogic, ['queryablePinnedProperties']],
        actions: [observationPinnedPropertiesLogic, ['setPinnedProperties']],
    })),

    loaders(({ props, values }) => ({
        sessionProperties: [
            null as Record<string, string | null> | null,
            {
                loadSessionProperties: async (_, breakpoint) => {
                    const properties = values.queryablePinnedProperties
                    if (!props.sessionId || !properties.length) {
                        return null
                    }
                    await breakpoint(100)

                    let response
                    try {
                        response = await api.queryHogQL(buildQuery(props.sessionId, properties), QUERY_TAGS)
                    } catch (e) {
                        // This strip is supplementary context. A failed read should leave it empty, not toast over the result.
                        posthog.captureException(e)
                        return null
                    }
                    breakpoint()

                    const row = response.results?.[0]
                    if (!row) {
                        return null
                    }
                    return Object.fromEntries(
                        // An event carrying the key with an empty value reads the same as never carrying it.
                        properties.map((property, index) => [pinnedPropertyId(property), toDisplayValue(row[index])])
                    )
                },
            },
        ],
    })),

    listeners(({ actions }) => ({
        // A newly pinned property isn't in the last response, so the row has to be read again.
        setPinnedProperties: () => actions.loadSessionProperties(null),
    })),

    afterMount(({ actions }) => {
        actions.loadSessionProperties(null)
    }),
])