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.

11.4 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    beforeUnmount,
    connect,
    kea,
    listeners,
    path,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'

import api from 'lib/api'
import { userLogic } from 'scenes/userLogic'

import { membersLogic } from '~/models/membersLogic'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'
import { toolbarFetch } from '~/toolbar/shared/toolbarFetch'
import { HedgehogConfig, MinimalHedgehogConfig } from '~/types'

import type { OrganizationMemberType, UserType } from '../../../types'
import { sanitizeHedgehogConfig } from './hedgehog-mode-utils'
import { HedgehogModeInterface } from './types'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hedgehogModeLogicValues {
    members: OrganizationMemberType[] | null // membersLogic
    user: UserType | null // userLogic
    hedgehogConfig: HedgehogConfig
    hedgehogMode: HedgehogModeInterface | null
    hedgehogModeEnabled: boolean
    minimalHedgehogConfig: MinimalHedgehogConfig
    remoteConfig: Partial<HedgehogConfig> | null
    remoteConfigLoading: boolean
    remoteConfigUpdateDisabled: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hedgehogModeLogicActions {
    ensureAllMembersLoaded: () => {
        value: true
    } // membersLogic
    loadRemoteConfig: () => {
        value: true
    }
    loadRemoteConfigFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRemoteConfigSuccess: (
        remoteConfig: Partial<HedgehogConfig> | null,
        payload?: {
            value: true
        }
    ) => {
        remoteConfig: Partial<HedgehogConfig> | null
        payload?: {
            value: true
        }
    }
    setHedgehogMode: (hedgeHogMode: HedgehogModeInterface) => {
        hedgeHogMode: HedgehogModeInterface
    }
    setHedgehogModeEnabled: (enabled: boolean) => {
        enabled: boolean
    }
    setRemoteConfigUpdateDisabled: (disabled: boolean) => {
        disabled: boolean
    }
    syncFromState: () => {
        value: true
    }
    syncGame: () => {
        value: true
    }
    toggleHedgehogMode: () => {
        value: true
    }
    updateRemoteConfig: (config: Partial<HedgehogConfig>) => {
        config: Partial<HedgehogConfig>
    }
    updateRemoteConfigFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateRemoteConfigSuccess: (
        remoteConfig: Partial<HedgehogConfig> | null,
        payload?: {
            config: Partial<HedgehogConfig>
        }
    ) => {
        remoteConfig: Partial<HedgehogConfig> | null
        payload?: {
            config: Partial<HedgehogConfig>
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hedgehogModeLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        hedgehogConfig: (remoteConfig: Partial<HedgehogConfig> | null) => HedgehogConfig
        hedgehogModeEnabled: (hedgehogConfig: HedgehogConfig) => boolean
        minimalHedgehogConfig: (hedgehogConfig: HedgehogConfig) => MinimalHedgehogConfig
    }
}

export type hedgehogModeLogicType = MakeLogicType<
    hedgehogModeLogicValues,
    hedgehogModeLogicActions,
    Record<string, any>,
    hedgehogModeLogicMeta
>

export const hedgehogModeLogic = kea<hedgehogModeLogicType>([
    path(['hedgehog', 'hedgehogModeLogic']),
    connect({
        values: [userLogic, ['user'], membersLogic, ['members']],
        actions: [membersLogic, ['ensureAllMembersLoaded']],
    }),
    actions({
        setHedgehogMode: (hedgeHogMode: HedgehogModeInterface) => ({ hedgeHogMode }),
        setHedgehogModeEnabled: (enabled: boolean) => ({ enabled }),
        toggleHedgehogMode: true,
        loadRemoteConfig: true,
        updateRemoteConfig: (config: Partial<HedgehogConfig>) => ({ config }),
        setRemoteConfigUpdateDisabled: (disabled: boolean) => ({ disabled }),
        syncGame: true,
        syncFromState: true,
    }),

    reducers(() => ({
        hedgehogMode: [
            null as HedgehogModeInterface | null,
            {
                setHedgehogMode: (_, { hedgeHogMode }) => hedgeHogMode,
            },
        ],
        remoteConfigUpdateDisabled: [
            false,
            {
                setRemoteConfigUpdateDisabled: (_, { disabled }) => disabled,
            },
        ],
    })),

    loaders(({ values, actions }) => ({
        remoteConfig: [
            null as Partial<HedgehogConfig> | null,
            {
                loadRemoteConfig: async () => {
                    const endpoint = '/api/users/@me/hedgehog_config'
                    const mountedToolbarConfigLogic = toolbarConfigLogic.findMounted()
                    if (mountedToolbarConfigLogic) {
                        // If toolbarConfigLogic is mounted, we're inside the Toolbar.
                        if (!mountedToolbarConfigLogic.values.isAuthenticated) {
                            return null
                        }
                        // The config is cosmetic - on any request failure (network, auth,
                        // non-JSON body) fall back to defaults rather than raising an error.
                        try {
                            const response = await toolbarFetch(endpoint, 'GET')
                            if (!response.ok) {
                                return null
                            }
                            return await response.json()
                        } catch {
                            return null
                        }
                    }
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                    return await api.get<Partial<HedgehogConfig>>(endpoint)
                },

                updateRemoteConfig: async ({ config }) => {
                    const endpoint = '/api/users/@me/hedgehog_config'
                    const payload = {
                        ...values.hedgehogConfig,
                        ...config,
                    }

                    const mountedToolbarConfigLogic = toolbarConfigLogic.findMounted()
                    if (mountedToolbarConfigLogic) {
                        // Inside the Toolbar the OAuth token is scoped to `user:read` only
                        // (TOOLBAR_OAUTH_SCOPES grants no `user:write`), so persisting the hedgehog
                        // config would 403 — and toolbarFetch turns any 403 into a session reset,
                        // kicking the user out of the Toolbar. Keep the config local to this session.
                        return mountedToolbarConfigLogic.values.isAuthenticated ? payload : null
                    }

                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                        const newConfig: Partial<HedgehogConfig> = await api.update(endpoint, payload)
                        return newConfig ?? null
                    } catch (e) {
                        console.error('Failed to update hedgehog remote config', e)
                        actions.setRemoteConfigUpdateDisabled(true)
                        return values.remoteConfig
                    }
                },
            },
        ],
    })),

    selectors({
        hedgehogConfig: [
            (s) => [s.remoteConfig],
            (remoteConfig: Partial<HedgehogConfig> | null): HedgehogConfig => {
                return sanitizeHedgehogConfig({
                    ...remoteConfig,
                })
            },
        ],

        hedgehogModeEnabled: [
            (s) => [s.hedgehogConfig],
            (hedgehogConfig: HedgehogConfig): boolean => {
                return !!hedgehogConfig.enabled
            },
        ],

        minimalHedgehogConfig: [
            (s) => [s.hedgehogConfig],
            (hedgehogConfig: HedgehogConfig): MinimalHedgehogConfig => {
                const forcedHedeghogProfile: MinimalHedgehogConfig = {
                    use_as_profile: true,
                    color: hedgehogConfig?.actor_options?.color,
                    skin: hedgehogConfig?.actor_options?.skin,
                    accessories: hedgehogConfig?.actor_options?.accessories,
                }

                return forcedHedeghogProfile
            },
        ],
    }),

    listeners(({ actions, values }) => ({
        setHedgehogModeEnabled: ({ enabled }) => {
            if (!values.remoteConfigUpdateDisabled) {
                actions.updateRemoteConfig({
                    enabled,
                })
            }

            posthog.capture(enabled ? 'hedgehog mode enabled' : 'hedgehog mode disabled')
        },
        toggleHedgehogMode: () => {
            actions.setHedgehogModeEnabled(!values.hedgehogModeEnabled)
        },

        updateRemoteConfigSuccess: ({ remoteConfig }) => {
            const theUserLogic = userLogic.findMounted()

            if (theUserLogic) {
                userLogic
                    .findMounted()
                    ?.actions.loadUserSuccess({ ...theUserLogic.values.user, hedgehog_config: remoteConfig } as any)
            }
        },

        syncGame: () => {
            const { hedgehogMode, hedgehogConfig } = values
            if (!hedgehogMode || !hedgehogConfig) {
                return
            }

            // Sync the actor options to the game
            hedgehogMode.stateManager?.setHedgehog(hedgehogConfig.actor_options)
        },

        syncFromState: () => {
            const { hedgehogMode, remoteConfigUpdateDisabled } = values
            if (!hedgehogMode || remoteConfigUpdateDisabled) {
                return
            }
            const state = hedgehogMode.stateManager?.getState()
            const player = state?.options

            if (!player) {
                return
            }

            const lastPlayerState = JSON.stringify(values.hedgehogConfig.actor_options)
            const currentPlayerState = JSON.stringify(player)
            if (lastPlayerState !== currentPlayerState) {
                // On change, update the remote config
                actions.updateRemoteConfig({
                    actor_options: player,
                })
            }
        },
    })),

    subscriptions(({ actions, values }) => ({
        hedgehogConfig: () => {
            if (values.hedgehogModeEnabled) {
                actions.ensureAllMembersLoaded()
            }
            actions.syncGame()
        },
        hedgehogMode: () => actions.syncGame(),
    })),

    afterMount(({ actions, cache }) => {
        const loadedUser = userLogic.findMounted()?.values.user
        if (loadedUser) {
            actions.loadRemoteConfigSuccess(loadedUser.hedgehog_config ?? {})
        } else {
            actions.loadRemoteConfig()
        }

        cache.syncInterval = setInterval(() => {
            actions.syncFromState()
        }, 1000)
    }),

    beforeUnmount(({ cache }) => {
        if (cache.syncInterval) {
            clearInterval(cache.syncInterval)
            cache.syncInterval = null
        }
    }),
])