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.

13.3 KB
Raw Blame
import { LogicWrapper, MakeLogicType, actions, connect, kea, key, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { projectLogic } from 'scenes/projectLogic'
import { userLogic } from 'scenes/userLogic'

import type { UserType } from '~/types'

import type {
    AlertSuggestionDirection,
    ScoutSuggestionCadence,
    ThreadItem,
    ToolInvocation,
    TurnSuggestion,
} from '../types/streamTypes'
import { AcceptedSuggestion, acceptSuggestion } from '../utils/acceptSuggestion'
import { ConversationBlocks, collectConversationBlocks } from '../utils/conversationNotebook'
import { recordTurnSuggestionResolution } from '../utils/recordTurnSuggestionResolution'
import { captureTurnSuggestionEvent } from '../utils/turnSuggestionEvents'
import { readFullThread, runStreamLogic } from './runStreamLogic'
import { slackDestinationLogic } from './slackDestinationLogic'
import { TurnSuggestionLogicProps, turnSuggestionLogic } from './turnSuggestionLogic'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface suggestionActionLogicValues {
    currentProjectId: number | null // projectLogic
    threadItems: ThreadItem[] // runStreamLogic
    toolInvocations: Map<string, ToolInvocation> // runStreamLogic
    slackChannel: string | null // slackDestinationLogic
    slackChannelLabel: string // slackDestinationLogic
    slackDestinationDisabledReason: string | null // slackDestinationLogic
    slackIntegrationId: number | null // slackDestinationLogic
    suggestion: TurnSuggestion | null // turnSuggestionLogic
    user: UserType | null // userLogic
    acceptDisabledReason: string | null
    acceptFailed: boolean
    accepted: AcceptedSuggestion | null
    acceptedLoading: boolean
    cadence: ScoutSuggestionCadence
    cadenceOverride: ScoutSuggestionCadence | null
    changePercent: number
    changePercentOverride: number | null
    conversationBlocks: ConversationBlocks
    direction: AlertSuggestionDirection
    directionOverride: AlertSuggestionDirection | null
    notebookTitle: string
    scoutBody: string
    scoutBodyOverride: string | null
    titleOverride: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface suggestionActionLogicActions {
    markTurnSuggestionAccepted: (turnIndex: number) => {
        turnIndex: number
    } // runStreamLogic
    accept: () => any
    acceptFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    acceptSuccess: (
        accepted: AcceptedSuggestion | null,
        payload?: any
    ) => {
        accepted: AcceptedSuggestion | null
        payload?: any
    }
    setCadence: (cadence: ScoutSuggestionCadence) => {
        cadence: 'daily' | 'weekly'
    }
    setChangePercent: (changePercent: number) => {
        changePercent: number
    }
    setDirection: (direction: AlertSuggestionDirection) => {
        direction: 'decrease' | 'increase'
    }
    setScoutBody: (scoutBody: string) => {
        scoutBody: string
    }
    setTitle: (title: string) => {
        title: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface suggestionActionLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        cadence: (
            cadenceOverride: 'daily' | 'weekly' | null,
            suggestion: TurnSuggestion | null
        ) => ScoutSuggestionCadence
        direction: (
            directionOverride: 'decrease' | 'increase' | null,
            suggestion: TurnSuggestion | null
        ) => AlertSuggestionDirection
        changePercent: (changePercentOverride: number | null, suggestion: TurnSuggestion | null) => number
        notebookTitle: (titleOverride: string | null, suggestion: TurnSuggestion | null) => string
        scoutBody: (scoutBodyOverride: string | null, suggestion: TurnSuggestion | null) => string
        conversationBlocks: (
            threadItems: ThreadItem[],
            toolInvocations: Map<string, ToolInvocation>
        ) => ConversationBlocks
        acceptDisabledReason: (
            suggestion: TurnSuggestion | null,
            currentProjectId: number | null,
            user: UserType | null,
            slackDestinationDisabledReason: string | null,
            notebookTitle: string,
            changePercent: number,
            scoutBody: string
        ) => string | null
    }
}

export type suggestionActionLogicType = MakeLogicType<
    suggestionActionLogicValues,
    suggestionActionLogicActions,
    TurnSuggestionLogicProps,
    suggestionActionLogicMeta
>

/** Taking the offer: the inputs a card can change, the one request that creates it, and the result. */
export const suggestionActionLogic: LogicWrapper<suggestionActionLogicType> = kea<suggestionActionLogicType>([
    props({} as TurnSuggestionLogicProps),
    key((props) => `${props.streamKey}:${props.turnIndex}`),
    path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'suggestionActionLogic', key]),
    connect((props: TurnSuggestionLogicProps) => ({
        values: [
            turnSuggestionLogic(props),
            ['suggestion'],
            slackDestinationLogic(props),
            ['slackIntegrationId', 'slackChannel', 'slackChannelLabel', 'slackDestinationDisabledReason'],
            runStreamLogic({ streamKey: props.streamKey }),
            ['threadItems', 'toolInvocations'],
            projectLogic,
            ['currentProjectId'],
            userLogic,
            ['user'],
        ],
        actions: [runStreamLogic({ streamKey: props.streamKey }), ['markTurnSuggestionAccepted']],
    })),
    actions({
        setCadence: (cadence: ScoutSuggestionCadence) => ({ cadence }),
        setDirection: (direction: AlertSuggestionDirection) => ({ direction }),
        setChangePercent: (changePercent: number) => ({ changePercent }),
        setTitle: (title: string) => ({ title }),
        setScoutBody: (scoutBody: string) => ({ scoutBody }),
    }),
    loaders(({ actions, values, props }) => ({
        accepted: [
            null as AcceptedSuggestion | null,
            {
                accept: async () => {
                    const { suggestion, currentProjectId } = values
                    if (!suggestion || currentProjectId === null || values.acceptDisabledReason) {
                        return values.accepted
                    }
                    // The request can outlive the card: a message sent while it runs clears `values.suggestion`,
                    // so the outcome is recorded against the suggestion this accept started from.
                    let outcome: Awaited<ReturnType<typeof acceptSuggestion>>
                    try {
                        // The inputs are read before the full-history read: a message sent meanwhile clears the
                        // suggestion, and the title and the other fields derive from it.
                        const input = {
                            suggestion,
                            projectId: currentProjectId,
                            userId: values.user?.id,
                            slackIntegrationId: values.slackIntegrationId,
                            slackChannel: values.slackChannel,
                            cadence: values.cadence,
                            scoutBody: values.scoutBody,
                            direction: values.direction,
                            changePercent: values.changePercent,
                            notebookTitle: values.notebookTitle,
                            conversationBlocks: values.conversationBlocks,
                        }
                        // A chat that loaded only its latest turns reads the full conversation, so the notebook holds
                        // every turn. The loader keeps the button loading while it reads.
                        const fullRead = suggestion.kind === 'notebook' ? readFullThread(props.streamKey) : null
                        const fullThread = fullRead ? await fullRead : null
                        outcome = await acceptSuggestion({
                            ...input,
                            ...(fullThread
                                ? {
                                      conversationBlocks: collectConversationBlocks(
                                          fullThread.threadItems,
                                          fullThread.toolInvocations
                                      ),
                                  }
                                : {}),
                        })
                    } catch (error) {
                        // posthog-js serializes an Error instance as an empty object.
                        captureTurnSuggestionEvent('accept failed', props, suggestion, {
                            error: error instanceof Error ? error.message : String(error),
                        })
                        throw error
                    }
                    captureTurnSuggestionEvent('accepted', props, suggestion, outcome.eventProperties)
                    actions.markTurnSuggestionAccepted(suggestion.turnIndex)
                    recordTurnSuggestionResolution(currentProjectId, props.sessionId, suggestion, 'accepted')
                    return outcome.accepted
                },
            },
        ],
    })),
    reducers({
        cadenceOverride: [null as ScoutSuggestionCadence | null, { setCadence: (_, { cadence }) => cadence }],
        directionOverride: [null as AlertSuggestionDirection | null, { setDirection: (_, { direction }) => direction }],
        changePercentOverride: [null as number | null, { setChangePercent: (_, { changePercent }) => changePercent }],
        titleOverride: [null as string | null, { setTitle: (_, { title }) => title }],
        scoutBodyOverride: [null as string | null, { setScoutBody: (_, { scoutBody }) => scoutBody }],
        acceptFailed: [false, { accept: () => false, acceptFailure: () => true }],
    }),
    selectors({
        cadence: [
            (s) => [s.cadenceOverride, s.suggestion],
            (
                cadenceOverride: ScoutSuggestionCadence | null,
                suggestion: TurnSuggestion | null
            ): ScoutSuggestionCadence => {
                if (cadenceOverride) {
                    return cadenceOverride
                }
                if (suggestion?.kind === 'scout') {
                    return suggestion.scout.cadence
                }
                return suggestion?.kind === 'subscription' ? suggestion.subscription.cadence : 'weekly'
            },
        ],
        direction: [
            (s) => [s.directionOverride, s.suggestion],
            (
                directionOverride: AlertSuggestionDirection | null,
                suggestion: TurnSuggestion | null
            ): AlertSuggestionDirection =>
                directionOverride ?? (suggestion?.kind === 'alert' ? suggestion.alert.direction : 'decrease'),
        ],
        changePercent: [
            (s) => [s.changePercentOverride, s.suggestion],
            (changePercentOverride: number | null, suggestion: TurnSuggestion | null): number =>
                changePercentOverride ?? (suggestion?.kind === 'alert' ? suggestion.alert.changePercent : 20),
        ],
        notebookTitle: [
            (s) => [s.titleOverride, s.suggestion],
            (titleOverride: string | null, suggestion: TurnSuggestion | null): string =>
                titleOverride ?? (suggestion?.kind === 'notebook' ? suggestion.notebook.title : ''),
        ],
        scoutBody: [
            (s) => [s.scoutBodyOverride, s.suggestion],
            (scoutBodyOverride: string | null, suggestion: TurnSuggestion | null): string =>
                scoutBodyOverride ?? (suggestion?.kind === 'scout' ? suggestion.scout.body : ''),
        ],
        conversationBlocks: [
            (s) => [s.threadItems, s.toolInvocations],
            (threadItems: ThreadItem[], toolInvocations: Map<string, ToolInvocation>): ConversationBlocks =>
                collectConversationBlocks(threadItems, toolInvocations),
        ],
        acceptDisabledReason: [
            (s) => [
                s.suggestion,
                s.currentProjectId,
                s.user,
                s.slackDestinationDisabledReason,
                s.notebookTitle,
                s.changePercent,
                s.scoutBody,
            ],
            (
                suggestion: TurnSuggestion | null,
                currentProjectId: number | null,
                user: UserType | null,
                slackDestinationDisabledReason: string | null,
                notebookTitle: string,
                changePercent: number,
                scoutBody: string
            ): string | null => {
                if (currentProjectId === null || !user) {
                    return 'Your project is still loading'
                }
                switch (suggestion?.kind) {
                    case 'scout':
                        return scoutBody.trim() ? slackDestinationDisabledReason : 'Add instructions for the scout'
                    case 'notebook':
                        return notebookTitle.trim() ? null : 'Add a notebook title'
                    case 'alert':
                        return changePercent > 0 ? slackDestinationDisabledReason : 'Enter a percentage above 0'
                    default:
                        return slackDestinationDisabledReason
                }
            },
        ],
    }),
])