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.

8.1 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'
import posthog from 'posthog-js'

import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import {
    AI_COMPOSER_MODE_VALUE,
    EDITOR_MODE_PARAM,
    EDITOR_MODE_VALUE,
    aiComposerAvailable,
    isAiFirstVariant,
} from 'scenes/max/aiFirstCreate/aiFirstMode'
import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'
import { urls } from 'scenes/urls'

import { attachedContextItemKey } from '~/layout/ai/attachedContext'
import type { AttachedContextItem } from '~/layout/ai/attachedContext'
import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'

import {
    PICKED_TEMPLATE_DISMISS_GROUP,
    buildNewTemplateComposerContext,
    pickedTemplateContextItem,
} from './templateAgentContext'
import { MessageTemplate } from './types'

function isNewTemplateRoute(pathname: string): boolean {
    return removeProjectIdIfPresent(pathname) === urls.workflowsLibraryTemplateNew()
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newTemplateAgentLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    location: {
        pathname: string
        search: string
        hash: string
    } // router
    searchParams: Record<string, any> // router
    sceneIntegrationEnabled: boolean // sceneAgentPanelLogic
    agentContextItems: AttachedContextItem[]
    aiComposerAvailable: boolean
    aiFirstNewEnabled: boolean
    pickedTemplate: MessageTemplate | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newTemplateAgentLogicActions {
    dismissContext: (
        key: string,
        dismissGroup?: string | undefined
    ) => {
        dismissGroup: string | undefined
        key: string
    } // attachedContextLogic
    undismissContext: (
        key: string,
        dismissGroup?: string | undefined
    ) => {
        dismissGroup: string | undefined
        key: string
    } // attachedContextLogic
    locationChanged: ({
        method,
        pathname,
        search,
        searchParams,
        hash,
        hashParams,
        initial,
        url,
        routerState,
    }: LocationChangedPayload) => {
        hash: string
        hashParams: Record<string, any>
        initial: boolean
        method: 'POP' | 'PUSH' | 'REPLACE'
        pathname: string
        routerState: Record<string, any>
        search: string
        searchParams: Record<string, any>
        url: string
    } // router
    openEditorFromAiComposer: () => {
        value: true
    }
    setPickedTemplate: (template: MessageTemplate | null) => {
        template: MessageTemplate | null
    }
    startNewTemplate: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newTemplateAgentLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        aiFirstNewEnabled: (featureFlags: FeatureFlagsSet, sceneIntegrationEnabled: boolean) => boolean
        aiComposerAvailable: (
            featureFlags: FeatureFlagsSet,
            sceneIntegrationEnabled: boolean,
            searchParams: Record<string, any>,
            location: {
                hash: string
                pathname: string
                search: string
            }
        ) => boolean
        agentContextItems: (pickedTemplate: MessageTemplate | null) => AttachedContextItem[]
    }
}

export type newTemplateAgentLogicType = MakeLogicType<
    newTemplateAgentLogicValues,
    newTemplateAgentLogicActions,
    Record<string, any>,
    newTemplateAgentLogicMeta
>

/** Entry, mode and picked starting point for the AI-first "New template" page. */
export const newTemplateAgentLogic = kea<newTemplateAgentLogicType>([
    path(['products', 'workflows', 'frontend', 'library', 'newTemplateAgentLogic']),
    connect(() => ({
        values: [
            featureFlagLogic,
            ['featureFlags'],
            sceneAgentPanelLogic,
            ['sceneIntegrationEnabled'],
            router,
            ['searchParams', 'location'],
        ],
        actions: [attachedContextLogic, ['dismissContext', 'undismissContext'], router, ['locationChanged']],
    })),
    actions({
        startNewTemplate: true,
        openEditorFromAiComposer: true,
        setPickedTemplate: (template: MessageTemplate | null) => ({ template }),
    }),
    reducers({
        pickedTemplate: [
            null as MessageTemplate | null,
            {
                setPickedTemplate: (_, { template }) => template,
            },
        ],
    }),
    selectors({
        // Same gate as the scene integration. Only the `test` variant, or a plain boolean rollout, qualifies.
        aiFirstNewEnabled: [
            (s) => [s.featureFlags, s.sceneIntegrationEnabled],
            (featureFlags: FeatureFlagsSet, sceneIntegrationEnabled: boolean): boolean =>
                sceneIntegrationEnabled && isAiFirstVariant(FEATURE_FLAGS.EMAIL_TEMPLATES_AI_FIRST_NEW, featureFlags),
        ],
        // A template started from a sent message has its starting point already, so it stays on the editor.
        aiComposerAvailable: [
            (s) => [s.featureFlags, s.sceneIntegrationEnabled, s.searchParams, s.location],
            (
                featureFlags: FeatureFlagsSet,
                sceneIntegrationEnabled: boolean,
                searchParams: Record<string, any>,
                location: { pathname: string }
            ): boolean =>
                aiComposerAvailable(
                    FEATURE_FLAGS.EMAIL_TEMPLATES_AI_FIRST_NEW,
                    featureFlags,
                    sceneIntegrationEnabled,
                    searchParams,
                    isNewTemplateRoute(location.pathname) && !searchParams.messageId
                ),
        ],
        agentContextItems: [
            (s) => [s.pickedTemplate],
            (pickedTemplate: MessageTemplate | null): AttachedContextItem[] =>
                buildNewTemplateComposerContext(pickedTemplate),
        ],
    }),
    listeners(({ actions, values }) => ({
        startNewTemplate: () => {
            // Exposure is recorded at the click, and only when the composer could answer it.
            if (values.sceneIntegrationEnabled) {
                posthog.getFeatureFlag(FEATURE_FLAGS.EMAIL_TEMPLATES_AI_FIRST_NEW)
            }
            router.actions.push(
                urls.workflowsLibraryTemplateNew(),
                values.aiFirstNewEnabled ? { [EDITOR_MODE_PARAM]: AI_COMPOSER_MODE_VALUE } : {}
            )
        },
        // The editor URL keeps the composer from rendering again, and the editor opens its picker for it.
        openEditorFromAiComposer: () => {
            router.actions.push(urls.workflowsLibraryTemplateNew(), { [EDITOR_MODE_PARAM]: EDITOR_MODE_VALUE })
        },
        setPickedTemplate: ({ template }) => {
            if (!template) {
                return
            }
            // An attachment removed earlier in this session keeps its group dismissed, so a new pick lifts that first.
            actions.undismissContext(
                attachedContextItemKey(pickedTemplateContextItem(template)),
                PICKED_TEMPLATE_DISMISS_GROUP
            )
            posthog.capture('email template ai composer template picked', { template_id: template.id })
        },
        // Removing the attachment is how the person un-picks; the context item is gone, so the state follows.
        dismissContext: ({ dismissGroup }) => {
            if (dismissGroup === PICKED_TEMPLATE_DISMISS_GROUP && values.pickedTemplate) {
                actions.setPickedTemplate(null)
            }
        },
        // The pick belongs to one visit of the page. The library keeps this logic mounted, so leaving has to clear it.
        locationChanged: ({ pathname }) => {
            if (values.pickedTemplate && !isNewTemplateRoute(pathname)) {
                actions.setPickedTemplate(null)
            }
        },
    })),
])