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.

7.8 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import posthog from 'posthog-js'

import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { personalCodexIntegrationLogic } from 'scenes/settings/user/personalCodexIntegrationLogic'

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

import { ModelAccessEnumApi, RuntimeAdapterEnumApi } from 'products/tasks/frontend/generated/api.schemas'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface codexBillingLogicValues {
    codexIntegration: UserCodexIntegrationApi | null // personalCodexIntegrationLogic
    effectiveCodexModelAccess: ModelAccessEnumApi
    planConnected: boolean
    preferredCodexModelAccess: ModelAccessEnumApi
    selectPlanAfterConnect: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface codexBillingLogicActions {
    closeConnectModal: () => {
        value: true
    } // personalCodexIntegrationLogic
    connectCodexSuccess: (
        codexIntegration: UserCodexIntegrationApi,
        payload?: import('~/generated/core/api.schemas').UserCodexAuthTokensApi | undefined
    ) => {
        codexIntegration: UserCodexIntegrationApi
        payload?: import('~/generated/core/api.schemas').UserCodexAuthTokensApi
    } // personalCodexIntegrationLogic
    openConnectModal: (opener: string) => {
        opener: string
    } // personalCodexIntegrationLogic
    connectPlan: (opener: string) => {
        opener: string
    }
    setPreferredCodexModelAccess: (codexModelAccess: ModelAccessEnumApi) => {
        codexModelAccess: ModelAccessEnumApi
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface codexBillingLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        planConnected: (codexIntegration: UserCodexIntegrationApi | null) => boolean
        effectiveCodexModelAccess: (
            preferredCodexModelAccess: ModelAccessEnumApi,
            planConnected: boolean
        ) => ModelAccessEnumApi
    }
}

export type codexBillingLogicType = MakeLogicType<
    codexBillingLogicValues,
    codexBillingLogicActions,
    Record<string, any>,
    codexBillingLogicMeta
>

export const codexBillingLogic = kea<codexBillingLogicType>([
    path(['products', 'posthog_ai', 'frontend', 'logics', 'codexBillingLogic']),

    connect(() => ({
        values: [personalCodexIntegrationLogic, ['codexIntegration']],
        actions: [personalCodexIntegrationLogic, ['openConnectModal', 'closeConnectModal', 'connectCodexSuccess']],
    })),

    actions({
        setPreferredCodexModelAccess: (codexModelAccess: ModelAccessEnumApi) => ({ codexModelAccess }),
        connectPlan: (opener: string) => ({ opener }),
    }),

    reducers({
        preferredCodexModelAccess: [
            ModelAccessEnumApi.PosthogGateway as ModelAccessEnumApi,
            { persist: true },
            {
                setPreferredCodexModelAccess: (_, { codexModelAccess }) => codexModelAccess,
            },
        ],
        // Cleared by the plan pick, not by `connectCodexSuccess`: reducers run before listeners, so clearing it
        // there would hide it from the listener that makes the pick.
        selectPlanAfterConnect: [
            false,
            {
                connectPlan: () => true,
                closeConnectModal: () => false,
                setPreferredCodexModelAccess: () => false,
            },
        ],
    }),

    selectors({
        planConnected: [
            (s) => [s.codexIntegration],
            (codexIntegration: UserCodexIntegrationApi | null): boolean =>
                codexIntegration?.status === CodexIntegrationStatusEnumApi.Connected,
        ],
        effectiveCodexModelAccess: [
            (s) => [s.preferredCodexModelAccess, s.planConnected],
            (preferred: ModelAccessEnumApi, planConnected: boolean): ModelAccessEnumApi =>
                planConnected ? preferred : ModelAccessEnumApi.PosthogGateway,
        ],
    }),

    listeners(({ actions, values }) => ({
        setPreferredCodexModelAccess: ({ codexModelAccess }) => {
            posthog.capture('codex billing changed', { billing: codexModelAccess })
        },
        connectPlan: ({ opener }) => {
            actions.openConnectModal(opener)
        },
        connectCodexSuccess: () => {
            if (values.selectPlanAfterConnect) {
                actions.setPreferredCodexModelAccess(ModelAccessEnumApi.OwnSubscription)
            }
        },
    })),
])

function codexBillingEnabled(): boolean {
    return !!featureFlagLogic.values.featureFlags[FEATURE_FLAGS.POSTHOG_CODE_CODEX_OWN_SUBSCRIPTION_CLOUD]
}

/** Whether a run on this harness bills to the ChatGPT plan, as far as the mounted picker knows now. */
export function usesChatGptPlan(runtimeAdapter: string | null | undefined): boolean {
    return (
        codexBillingEnabled() &&
        runtimeAdapter === RuntimeAdapterEnumApi.Codex &&
        codexBillingLogic.findMounted()?.values.effectiveCodexModelAccess === ModelAccessEnumApi.OwnSubscription
    )
}

/**
 * The billing the mounted picker shows now, or `null` to leave the field off. A resume starts from the run
 * composer, whose picker is mounted, so this is enough there and keeps the send synchronous. While the
 * ChatGPT connection still loads, a saved plan is not known to be usable yet, so the field stays off and the
 * resumed run keeps the billing of the run it continues.
 */
export function pickedCodexModelAccess(runtimeAdapter: string | null | undefined): ModelAccessEnumApi | null {
    if (!codexBillingEnabled()) {
        return null
    }
    if (runtimeAdapter !== RuntimeAdapterEnumApi.Codex) {
        return ModelAccessEnumApi.PosthogGateway
    }
    const billing = codexBillingLogic.findMounted()
    if (
        !billing ||
        (billing.values.codexIntegration === null &&
            billing.values.preferredCodexModelAccess === ModelAccessEnumApi.OwnSubscription)
    ) {
        return null
    }
    return billing.values.effectiveCodexModelAccess
}

export class CodexBillingUnresolvedError extends Error {}

/**
 * The billing a new run must state, or `null` to leave the field off because the choice is not offered.
 *
 * When it is offered the choice is always sent: a resumed run otherwise keeps the billing of the run it
 * continues, and the backend refuses a ChatGPT plan on Claude. A seeded task can submit before the picker
 * mounts, so this reads the saved choice and the ChatGPT connection itself.
 */
export async function codexModelAccessForRun(
    resolveRuntimeAdapter: () => Promise<string | null>
): Promise<ModelAccessEnumApi | null> {
    if (!codexBillingEnabled()) {
        return null
    }
    const runtimeAdapter = await resolveRuntimeAdapter()
    if (runtimeAdapter !== null && runtimeAdapter !== RuntimeAdapterEnumApi.Codex) {
        return ModelAccessEnumApi.PosthogGateway
    }
    const unmount = codexBillingLogic.mount()
    try {
        if (codexBillingLogic.values.preferredCodexModelAccess !== ModelAccessEnumApi.OwnSubscription) {
            return ModelAccessEnumApi.PosthogGateway
        }
        if (runtimeAdapter === null) {
            throw new CodexBillingUnresolvedError()
        }
        const integration =
            codexBillingLogic.values.codexIntegration ??
            (await usersIntegrationsCodexRetrieve('@me').catch(() => {
                throw new CodexBillingUnresolvedError()
            }))
        return integration.status === CodexIntegrationStatusEnumApi.Connected
            ? ModelAccessEnumApi.OwnSubscription
            : ModelAccessEnumApi.PosthogGateway
    } finally {
        unmount()
    }
}