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.

10.1 KB
Raw Blame
import { MakeLogicType, actions, events, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'

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

import {
    usersIntegrationsCodexCreate,
    usersIntegrationsCodexDestroy,
    usersIntegrationsCodexRetrieve,
} from '~/generated/core/api'
import {
    CodexIntegrationStatusEnumApi,
    type UserCodexAuthTokensApi,
    type UserCodexIntegrationApi,
} from '~/generated/core/api.schemas'

import { parseCodexAuthFile } from './codexAuthFile'
import { type CodexLoginPlatform, browserCodexLoginPlatform } from './codexLoginCommands'

const CONNECT_ERROR_FALLBACK = 'Could not connect Codex. Run the command again, then paste the new sign-in.'
const CLIPBOARD_BLOCKED_ERROR = 'Your browser blocked clipboard access. Click the field and paste with your keyboard.'

async function clearClipboard(): Promise<void> {
    try {
        await navigator.clipboard.writeText('')
    } catch {
        lemonToast.warning('Could not clear your clipboard. Copy something else to remove the sign-in from it.')
    }
}

function describeConnectError(error: unknown): string {
    const detail = error && typeof error === 'object' ? (error as { detail?: unknown }).detail : undefined
    return typeof detail === 'string' && detail ? detail : CONNECT_ERROR_FALLBACK
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personalCodexIntegrationLogicValues {
    authFileText: string
    codexIntegration: UserCodexIntegrationApi | null
    codexIntegrationLoadFailed: boolean
    codexIntegrationLoading: boolean
    codexMutationCount: number
    connectError: string | null
    connectModalOpener: string | null
    connectModalSession: number
    connecting: boolean
    loginPlatform: CodexLoginPlatform
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personalCodexIntegrationLogicActions {
    closeConnectModal: () => {
        value: true
    }
    commandCopied: () => {
        value: true
    }
    connectCodex: (tokens: UserCodexAuthTokensApi) => UserCodexAuthTokensApi
    connectCodexFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    connectCodexSuccess: (
        codexIntegration: UserCodexIntegrationApi,
        payload?: UserCodexAuthTokensApi
    ) => {
        codexIntegration: UserCodexIntegrationApi
        payload?: UserCodexAuthTokensApi
    }
    disconnectCodex: () => any
    disconnectCodexFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    disconnectCodexSuccess: (
        codexIntegration: UserCodexIntegrationApi,
        payload?: any
    ) => {
        codexIntegration: UserCodexIntegrationApi
        payload?: any
    }
    loadCodexIntegration: () => any
    loadCodexIntegrationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCodexIntegrationSuccess: (
        codexIntegration: UserCodexIntegrationApi | null,
        payload?: any
    ) => {
        codexIntegration: UserCodexIntegrationApi | null
        payload?: any
    }
    openConnectModal: (opener: string) => {
        opener: string
    }
    pasteAuthFile: (authFileText: string) => {
        authFileText: string
    }
    pasteFromClipboard: () => {
        value: true
    }
    rejectAuthFile: (error: string) => {
        error: string
    }
    setConnectError: (connectError: string | null) => {
        connectError: string | null
    }
    setLoginPlatform: (loginPlatform: CodexLoginPlatform) => {
        loginPlatform: CodexLoginPlatform
    }
    submitAuthFile: () => {
        value: true
    }
}

export type personalCodexIntegrationLogicType = MakeLogicType<
    personalCodexIntegrationLogicValues,
    personalCodexIntegrationLogicActions
>

export const personalCodexIntegrationLogic = kea<personalCodexIntegrationLogicType>([
    path(['scenes', 'settings', 'user', 'personalCodexIntegrationLogic']),

    actions({
        openConnectModal: (opener: string) => ({ opener }),
        closeConnectModal: true,
        setLoginPlatform: (loginPlatform: CodexLoginPlatform) => ({ loginPlatform }),
        commandCopied: true,
        pasteAuthFile: (authFileText: string) => ({ authFileText }),
        pasteFromClipboard: true,
        setConnectError: (connectError: string | null) => ({ connectError }),
        submitAuthFile: true,
        rejectAuthFile: (error: string) => ({ error }),
    }),

    loaders(({ values }) => ({
        codexIntegration: [
            null as UserCodexIntegrationApi | null,
            {
                loadCodexIntegration: async () => {
                    const mutationCount = values.codexMutationCount
                    const integration = await usersIntegrationsCodexRetrieve('@me')
                    // A connect or disconnect that started meanwhile is newer than this read.
                    return values.codexMutationCount === mutationCount ? integration : values.codexIntegration
                },
                connectCodex: async (tokens: UserCodexAuthTokensApi) =>
                    await usersIntegrationsCodexCreate('@me', { tokens }),
                disconnectCodex: async (): Promise<UserCodexIntegrationApi> => {
                    await usersIntegrationsCodexDestroy('@me')
                    return { status: CodexIntegrationStatusEnumApi.NotConnected }
                },
            },
        ],
    })),

    reducers({
        codexMutationCount: [
            0,
            {
                connectCodex: (count) => count + 1,
                disconnectCodex: (count) => count + 1,
            },
        ],
        connectModalSession: [
            0,
            {
                openConnectModal: (session) => session + 1,
                closeConnectModal: (session) => session + 1,
                connectCodexSuccess: (session) => session + 1,
            },
        ],
        connectModalOpener: [
            null as string | null,
            {
                openConnectModal: (_, { opener }) => opener,
                closeConnectModal: () => null,
                connectCodexSuccess: () => null,
            },
        ],
        loginPlatform: [
            browserCodexLoginPlatform(),
            {
                setLoginPlatform: (_, { loginPlatform }) => loginPlatform,
            },
        ],
        authFileText: [
            '',
            {
                pasteAuthFile: (_, { authFileText }) => authFileText,
                rejectAuthFile: () => '',
                openConnectModal: () => '',
                closeConnectModal: () => '',
                connectCodexSuccess: () => '',
            },
        ],
        connectError: [
            null as string | null,
            {
                setConnectError: (_, { connectError }) => connectError,
                rejectAuthFile: (_, { error }) => error,
                pasteAuthFile: () => null,
                openConnectModal: () => null,
            },
        ],
        connecting: [
            false,
            {
                connectCodex: () => true,
                connectCodexSuccess: () => false,
                connectCodexFailure: () => false,
            },
        ],
        codexIntegrationLoadFailed: [
            false,
            {
                loadCodexIntegrationFailure: () => true,
                loadCodexIntegrationSuccess: () => false,
            },
        ],
    }),

    listeners(({ actions, values }) => ({
        openConnectModal: ({ opener }) => {
            posthog.capture('personal integration connect clicked', {
                integration_kind: 'codex',
                surface: opener.split(':')[0],
            })
        },
        commandCopied: () => {
            posthog.capture('codex connect command copied', { operating_system: values.loginPlatform })
        },
        pasteAuthFile: () => {
            actions.submitAuthFile()
        },
        pasteFromClipboard: async () => {
            const session = values.connectModalSession
            let text: string
            try {
                text = await navigator.clipboard.readText()
            } catch {
                actions.setConnectError(CLIPBOARD_BLOCKED_ERROR)
                return
            }
            // The read can outlive the dialog it came from. A closed or reopened dialog must not connect.
            if (values.connectModalSession === session && values.connectModalOpener !== null) {
                actions.pasteAuthFile(text)
            }
        },
        submitAuthFile: () => {
            // A second clipboard read can land while the first connect runs. Its refresh token is single-use.
            if (values.connecting) {
                return
            }
            const result = parseCodexAuthFile(values.authFileText)
            if (result.tokens === null) {
                posthog.capture('codex subscription connect failed', { reason: 'invalid_auth_file' })
                actions.rejectAuthFile(result.error)
                return
            }
            void clearClipboard()
            actions.connectCodex(result.tokens)
        },
        connectCodexSuccess: () => {
            lemonToast.success('Codex connected')
        },
        connectCodexFailure: ({ errorObject }) => {
            actions.setConnectError(describeConnectError(errorObject))
        },
        disconnectCodexSuccess: () => {
            lemonToast.success('Codex disconnected')
        },
        disconnectCodexFailure: () => {
            lemonToast.error('Could not disconnect Codex. Try again.')
        },
    })),

    events(({ actions, cache }) => ({
        afterMount: () => {
            actions.loadCodexIntegration()
            cache.disposables.add(
                () => {
                    const onFocus = (): void => actions.loadCodexIntegration()
                    window.addEventListener('focus', onFocus)
                    return () => window.removeEventListener('focus', onFocus)
                },
                'focusRefetch',
                { pauseOnPageHidden: false }
            )
        },
    })),
])