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.0 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    beforeUnmount,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import posthog from 'posthog-js'

import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
import {
    FEATURE_FLAG_CLEANUP_ASSESSMENT_PROMPT,
    featureFlagCleanupAssessmentContextItems,
} from 'scenes/feature-flags/featureFlagAiContext'
import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'

import { MAX_SIDE_PANEL_ID, type PhaiViewMode } from '~/layout/ai/aiPanelIds'
import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { SidePanelTab } from '~/types'

import { composerSeedLogic, type ComposerSeed } from 'products/posthog_ai/frontend/api/logics'

export interface FeatureFlagCleanupAssessmentLogicProps {
    id: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagCleanupAssessmentLogicValues {
    seed: ComposerSeed | null // composerSeedLogic
    featureFlags: FeatureFlagsSet // enabledFeaturesLogic
    dataProcessingAccepted: boolean // maxGlobalLogic
    effectivePhaiView: PhaiViewMode // maxGlobalLogic
    isMaxAvailable: boolean // maxGlobalLogic
    assessmentStarted: boolean
    isCleanupAvailable: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagCleanupAssessmentLogicActions {
    consumeSeed: () => {
        value: true
    } // composerSeedLogic
    setSeed: (seed: ComposerSeed) => {
        seed: ComposerSeed
    } // composerSeedLogic
    clearActiveCreation: () => {
        value: true
    } // runnerPanelLogic
    setHistoryExpanded: (expanded: boolean) => {
        expanded: boolean
    } // runnerPanelLogic
    openSidePanel: (
        tab: SidePanelTab,
        options?: string | undefined
    ) => {
        options: string | undefined
        tab: SidePanelTab
    } // sidePanelStateLogic
    markAssessmentStarted: () => {
        value: true
    }
    resetAssessmentStarted: () => {
        value: true
    }
    startAssessment: (
        flagKey: string,
        projectId: number | null
    ) => {
        flagKey: string
        projectId: number | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagCleanupAssessmentLogicMeta {
    key: number
    __keaTypeGenInternalSelectorTypes: {
        isCleanupAvailable: (
            isMaxAvailable: boolean,
            effectivePhaiView: PhaiViewMode,
            featureFlags: FeatureFlagsSet
        ) => boolean
    }
}

export type featureFlagCleanupAssessmentLogicType = MakeLogicType<
    featureFlagCleanupAssessmentLogicValues,
    featureFlagCleanupAssessmentLogicActions,
    FeatureFlagCleanupAssessmentLogicProps,
    featureFlagCleanupAssessmentLogicMeta
>

export const featureFlagCleanupAssessmentLogic = kea<featureFlagCleanupAssessmentLogicType>([
    path((key) => ['products', 'feature_flags', 'frontend', 'featureFlagCleanupAssessmentLogic', key]),
    props({} as FeatureFlagCleanupAssessmentLogicProps),
    key((props) => props.id),

    connect(() => ({
        values: [
            maxGlobalLogic,
            ['isMaxAvailable', 'effectivePhaiView', 'dataProcessingAccepted'],
            enabledFeaturesLogic,
            ['featureFlags'],
            composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }),
            ['seed'],
        ],
        actions: [
            composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }),
            ['setSeed', 'consumeSeed'],
            runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
            ['clearActiveCreation', 'setHistoryExpanded'],
            sidePanelStateLogic,
            ['openSidePanel'],
        ],
    })),

    actions({
        startAssessment: (flagKey: string, projectId: number | null) => ({ flagKey, projectId }),
        markAssessmentStarted: true,
        resetAssessmentStarted: true,
    }),

    reducers({
        assessmentStarted: [
            false,
            {
                markAssessmentStarted: () => true,
                resetAssessmentStarted: () => false,
            },
        ],
    }),

    selectors({
        // Scoped to the new sandbox view: legacy Max chat does not run in the agent sandbox, so the
        // cleanup skill bundled into that image is not present there.
        isCleanupAvailable: [
            (s) => [s.isMaxAvailable, s.effectivePhaiView, s.featureFlags],
            (isMaxAvailable: boolean, effectivePhaiView: PhaiViewMode, featureFlags: FeatureFlagsSet): boolean =>
                isMaxAvailable &&
                effectivePhaiView === 'new' &&
                !!featureFlags[FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT],
        ],
    }),

    listeners(({ actions, values, cache, props }) => {
        const cancelAssessment = (): void => {
            if (!values.assessmentStarted) {
                return
            }
            if (values.seed && values.seed === cache.pendingSeed) {
                actions.consumeSeed()
            }
            actions.resetAssessmentStarted()
        }

        return {
            startAssessment: ({ flagKey, projectId }) => {
                if (values.assessmentStarted || !values.isCleanupAvailable) {
                    return
                }
                actions.markAssessmentStarted()
                const contextItems = featureFlagCleanupAssessmentContextItems({ id: props.id, key: flagKey }, projectId)
                // Do not resume whatever the panel was already showing - a run in progress, history, or an
                // unrelated draft - so this action never appends to an unrelated task.
                actions.clearActiveCreation()
                actions.setHistoryExpanded(false)
                cache.pendingSeed = {
                    prompt: FEATURE_FLAG_CLEANUP_ASSESSMENT_PROMPT,
                    autoSubmit: values.dataProcessingAccepted,
                    contextItems,
                }
                actions.setSeed(cache.pendingSeed)
                actions.openSidePanel(SidePanelTab.Max)
                posthog.capture('feature flag stale banner review cleanup with ai clicked', {
                    flag_id: props.id,
                    flag_key: flagKey,
                })
            },
            [sidePanelStateLogic.actionTypes.setSidePanelOpen]: ({ open }) => {
                if (!open) {
                    cancelAssessment()
                }
            },
            [sidePanelStateLogic.actionTypes.openSidePanel]: ({ tab }) => {
                if (tab !== SidePanelTab.Max) {
                    cancelAssessment()
                }
            },
        }
    }),

    beforeUnmount(({ actions, values, cache }) => {
        // The runner can mount after this logic unmounts because its chunk loads lazily.
        if (values.seed && values.seed === cache.pendingSeed) {
            actions.consumeSeed()
        }
    }),
])