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.

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

import { uuid } from 'lib/utils/dom'
import { teamLogic } from 'scenes/teamLogic'

import {
    EventTriggerConfig,
    SessionRecordingTriggerGroup,
    SessionRecordingTriggerGroupsConfig,
} from '~/lib/components/IngestionControls/types'

import type { TeamPublicType, TeamType } from '../../../../../types'

/**
 * A conditionless group at 100% sample rate matches every session, so it's the explicit "record
 * everything" state in V2. We keep teams on this rather than dropping to zero groups (which would
 * fall back to legacy V1 config) so V2 stays the source of truth.
 */
export function buildRecordEverythingGroup(): SessionRecordingTriggerGroup {
    return {
        id: uuid(),
        name: 'Record all sessions',
        sampleRate: 1,
        conditions: { matchType: 'all' },
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface replayTriggersV2LogicValues {
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    _savingState: boolean | null
    _savingStateLoading: boolean
    deleteModalGroupId: string | null
    editingGroupId: string | null
    hasLegacyTriggers: boolean
    hasV2Config: boolean
    isAddingGroup: boolean
    previewLegacyGroups: SessionRecordingTriggerGroup[]
    shouldShowMigrationBanner: boolean
    showLegacyModal: boolean
    triggerGroups: SessionRecordingTriggerGroup[]
    triggerGroupsConfig: SessionRecordingTriggerGroupsConfig | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface replayTriggersV2LogicActions {
    updateCurrentTeam: (payload: Partial<TeamType>) => Partial<TeamType> // teamLogic
    addMultipleTriggerGroups: (groups: SessionRecordingTriggerGroup[]) => {
        groups: SessionRecordingTriggerGroup[]
    }
    addTriggerGroup: (group: SessionRecordingTriggerGroup) => {
        group: SessionRecordingTriggerGroup
    }
    confirmCreateFromLegacy: () => {
        value: true
    }
    confirmCreateFromLegacyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    confirmCreateFromLegacySuccess: (
        _savingState: boolean,
        payload?: {
            value: true
        }
    ) => {
        _savingState: boolean
        payload?: {
            value: true
        }
    }
    deleteTriggerGroup: (id: string) => {
        id: string
    }
    hideCreateFromLegacyModal: () => {
        value: true
    }
    saveConfig: () => any
    saveConfigFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    saveConfigSuccess: (
        _savingState: boolean,
        payload?: any
    ) => {
        _savingState: boolean
        payload?: any
    }
    setDeleteModalGroupId: (id: string | null) => {
        id: string | null
    }
    setEditingGroupId: (id: string | null) => {
        id: string | null
    }
    setIsAddingGroup: (isAdding: boolean) => {
        isAdding: boolean
    }
    setTriggerGroupsConfig: (config: SessionRecordingTriggerGroupsConfig | null) => {
        config: SessionRecordingTriggerGroupsConfig | null
    }
    showCreateFromLegacyModal: () => {
        value: true
    }
    updateTriggerGroup: (
        id: string,
        updates: Partial<SessionRecordingTriggerGroup>
    ) => {
        id: string
        updates: Partial<SessionRecordingTriggerGroup>
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface replayTriggersV2LogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        triggerGroups: (
            triggerGroupsConfig: SessionRecordingTriggerGroupsConfig | null
        ) => SessionRecordingTriggerGroup[]
        hasV2Config: (triggerGroupsConfig: SessionRecordingTriggerGroupsConfig | null) => boolean
        hasLegacyTriggers: (currentTeam: TeamPublicType | TeamType | null) => boolean
        shouldShowMigrationBanner: (
            triggerGroups: SessionRecordingTriggerGroup[],
            hasLegacyTriggers: boolean
        ) => boolean
        previewLegacyGroups: (currentTeam: TeamPublicType | TeamType | null) => SessionRecordingTriggerGroup[]
    }
}

export type replayTriggersV2LogicType = MakeLogicType<
    replayTriggersV2LogicValues,
    replayTriggersV2LogicActions,
    Record<string, any>,
    replayTriggersV2LogicMeta
>

export const replayTriggersV2Logic = kea<replayTriggersV2LogicType>([
    path(['lib', 'components', 'IngestionControls', 'triggers', 'triggerGroups', 'replayTriggersV2Logic']),
    connect({
        values: [teamLogic, ['currentTeam']],
        actions: [teamLogic, ['updateCurrentTeam']],
    }),
    actions({
        setTriggerGroupsConfig: (config: SessionRecordingTriggerGroupsConfig | null) => ({ config }),
        addTriggerGroup: (group: SessionRecordingTriggerGroup) => ({ group }),
        addMultipleTriggerGroups: (groups: SessionRecordingTriggerGroup[]) => ({ groups }),
        deleteTriggerGroup: (id: string) => ({ id }),
        updateTriggerGroup: (id: string, updates: Partial<SessionRecordingTriggerGroup>) => ({ id, updates }),
        setIsAddingGroup: (isAdding: boolean) => ({ isAdding }),
        setEditingGroupId: (id: string | null) => ({ id }),
        setDeleteModalGroupId: (id: string | null) => ({ id }),
        showCreateFromLegacyModal: true,
        hideCreateFromLegacyModal: true,
        confirmCreateFromLegacy: true,
    }),
    loaders(({ values, actions }) => ({
        _savingState: [
            null as boolean | null,
            {
                saveConfig: async () => {
                    // Save to backend via teamLogic
                    await teamLogic.asyncActions.updateCurrentTeam({
                        session_recording_trigger_groups: values.triggerGroupsConfig,
                    })
                    return true
                },
                confirmCreateFromLegacy: async () => {
                    const groups = values.previewLegacyGroups
                    if (groups.length === 0) {
                        return false
                    }

                    // Add all groups
                    actions.addMultipleTriggerGroups(groups)
                    return true
                },
            },
        ],
    })),
    reducers({
        triggerGroupsConfig: [
            null as SessionRecordingTriggerGroupsConfig | null,
            {
                setTriggerGroupsConfig: (_, { config }) => config,
                addTriggerGroup: (state, { group }) => {
                    if (!state) {
                        // Initialize with new group
                        return {
                            version: 2 as const,
                            groups: [group],
                        }
                    }
                    return {
                        ...state,
                        groups: [...state.groups, group],
                    }
                },
                addMultipleTriggerGroups: (state, { groups }) => {
                    if (!state) {
                        return {
                            version: 2 as const,
                            groups,
                        }
                    }
                    return {
                        ...state,
                        groups: [...state.groups, ...groups],
                    }
                },
                deleteTriggerGroup: (state, { id }) => {
                    if (!state) {
                        return state
                    }
                    const groups = state.groups.filter((g) => g.id !== id)
                    // Stay on V2 when the last group is removed: a record-everything group keeps the
                    // team on trigger groups (record all) instead of falling back to legacy V1 config.
                    return {
                        ...state,
                        groups: groups.length === 0 ? [buildRecordEverythingGroup()] : groups,
                    }
                },
                updateTriggerGroup: (state, { id, updates }) => {
                    if (!state) {
                        return state
                    }
                    return {
                        ...state,
                        groups: state.groups.map((g) => (g.id === id ? { ...g, ...updates } : g)),
                    }
                },
            },
        ],
        isAddingGroup: [
            false,
            {
                setIsAddingGroup: (_, { isAdding }) => isAdding,
                addTriggerGroup: () => false, // Close form after adding
            },
        ],
        editingGroupId: [
            null as string | null,
            {
                setEditingGroupId: (_, { id }) => id,
                updateTriggerGroup: () => null, // Close form after updating
            },
        ],
        showLegacyModal: [
            false,
            {
                showCreateFromLegacyModal: () => true,
                hideCreateFromLegacyModal: () => false,
                confirmCreateFromLegacySuccess: () => false,
            },
        ],
        deleteModalGroupId: [
            null as string | null,
            {
                setDeleteModalGroupId: (_, { id }) => id,
                deleteTriggerGroup: () => null, // Close modal after deleting
            },
        ],
    }),
    selectors({
        triggerGroups: [
            (s) => [s.triggerGroupsConfig],
            (config: SessionRecordingTriggerGroupsConfig | null): SessionRecordingTriggerGroup[] => {
                return config?.groups || []
            },
        ],
        hasV2Config: [
            (s) => [s.triggerGroupsConfig],
            (config: SessionRecordingTriggerGroupsConfig | null): boolean => {
                return config !== null && config.version === 2
            },
        ],
        hasLegacyTriggers: [
            (s) => [s.currentTeam],
            (
                team: null | import('../../../../../types').TeamPublicType | import('../../../../../types').TeamType
            ): boolean => {
                if (!team) {
                    return false
                }
                const hasUrlTriggers = (team.session_recording_url_trigger_config?.length ?? 0) > 0
                const hasEventTriggers = (team.session_recording_event_trigger_config?.length ?? 0) > 0
                const hasFeatureFlag = !!team.session_recording_linked_flag
                const hasSampling = !!(
                    team.session_recording_sample_rate && parseFloat(team.session_recording_sample_rate) < 1
                )
                return hasUrlTriggers || hasEventTriggers || hasFeatureFlag || hasSampling
            },
        ],
        shouldShowMigrationBanner: [
            (s) => [s.triggerGroups, s.hasLegacyTriggers],
            (triggerGroups: SessionRecordingTriggerGroup[], hasLegacyTriggers: boolean): boolean => {
                // Show banner if there are legacy triggers configured but no V2 groups
                return hasLegacyTriggers && triggerGroups.length === 0
            },
        ],
        previewLegacyGroups: [
            (s) => [s.currentTeam],
            (
                team: null | import('../../../../../types').TeamPublicType | import('../../../../../types').TeamType
            ): SessionRecordingTriggerGroup[] => {
                if (!team) {
                    return []
                }

                const sampleRate = team.session_recording_sample_rate
                    ? parseFloat(team.session_recording_sample_rate)
                    : 1
                const minDurationMs = team.session_recording_minimum_duration_milliseconds ?? undefined
                const matchType = team.session_recording_trigger_match_type_config || 'all'

                const events: EventTriggerConfig[] | undefined =
                    team.session_recording_event_trigger_config &&
                    team.session_recording_event_trigger_config.length > 0
                        ? team.session_recording_event_trigger_config
                              .filter((e): e is string => typeof e === 'string' && e.length > 0)
                              .map((name) => ({ name }))
                        : undefined

                const urls =
                    team.session_recording_url_trigger_config && team.session_recording_url_trigger_config.length > 0
                        ? team.session_recording_url_trigger_config
                        : undefined

                const flag = team.session_recording_linked_flag
                    ? typeof team.session_recording_linked_flag === 'string'
                        ? team.session_recording_linked_flag
                        : team.session_recording_linked_flag.key
                    : undefined

                const hasAnyTriggers = urls || events || flag
                const hasSampling = sampleRate < 1

                // If "ANY" match type with triggers AND sampling, create 2 groups:
                // 1. Combined triggers group with 100% sampling
                // 2. Baseline sampling group (no conditions)
                if (matchType === 'any' && hasAnyTriggers && hasSampling) {
                    return [
                        // Group 1: All triggers combined with ANY match type
                        {
                            id: uuid(),
                            name: 'Migrated trigger conditions',
                            sampleRate: 1,
                            minDurationMs,
                            conditions: {
                                matchType: 'any',
                                urls,
                                events,
                                flag,
                            },
                        },
                        // Group 2: Baseline sampling (no conditions)
                        {
                            id: uuid(),
                            name: 'Migrated baseline sampling',
                            sampleRate,
                            minDurationMs,
                            conditions: {
                                matchType: 'all',
                            },
                        },
                    ]
                }

                // Otherwise, create a single group
                return [
                    {
                        id: uuid(),
                        name: 'Migrated trigger conditions',
                        sampleRate,
                        minDurationMs,
                        conditions: {
                            matchType,
                            events,
                            urls,
                            flag,
                        },
                    },
                ]
            },
        ],
    }),
    listeners(({ asyncActions }) => ({
        addTriggerGroup: async () => {
            // Auto-save after adding
            await asyncActions.saveConfig()
        },
        addMultipleTriggerGroups: async () => {
            // Auto-save after adding multiple
            await asyncActions.saveConfig()
        },
        deleteTriggerGroup: async () => {
            // Auto-save after deleting
            await asyncActions.saveConfig()
        },
        updateTriggerGroup: async () => {
            // Auto-save after updating
            await asyncActions.saveConfig()
        },
    })),
    // Load config from currentTeam on mount
    afterMount(({ actions, values }) => {
        if (values.currentTeam?.session_recording_trigger_groups) {
            actions.setTriggerGroupsConfig(values.currentTeam.session_recording_trigger_groups)
        }
    }),
])