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.

9.2 KB
Raw Blame
import { LogicWrapper, MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'

import { lemonToast } from 'lib/lemon-ui/LemonToast'

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

import {
    composerSeedLogic,
    getToolOutputRecord,
    resolveToolCall,
    toolStreamEventsLogic,
} from 'products/posthog_ai/frontend/api/logics'
import type { ComposerSeed } from 'products/posthog_ai/frontend/api/logics'
import type { ToolStreamEvent } from 'products/posthog_ai/frontend/api/types'

export interface AiFirstHandoffLogicProps {
    /** MCP tool whose completed call means the entity exists. One handoff instance per tool. */
    toolName: string
    /**
     * Fallback for a completed call whose output carries no created record. Finds the entity from the
     * call's parsed input. Returns null when it cannot say which one.
     */
    findCreatedId: (innerInput: Record<string, unknown> | undefined) => Promise<string | null>
    /** The editor page for the created entity. */
    urlFor: (id: string) => string
    /** Toast for a saved entity the page could not open. Say where to find it. */
    notOpenedMessage: string
    // pinned: analytics event names. The surface's events are `${eventPrefix} viewed`, `${eventPrefix} submitted`,
    // `${eventPrefix} escape hatch clicked`, `${eventPrefix} banner dismissed`, and `createdEvent` with the id
    // under `createdIdProperty`.
    eventPrefix: string
    createdEvent: string
    createdIdProperty: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiFirstHandoffLogicValues {
    activeCreation: ActiveCreation | null // runnerPanelLogic
    selectedTab: SidePanelTab | null // sidePanelStateLogic
    sidePanelOpen: boolean // sidePanelStateLogic
    bannerDismissed: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiFirstHandoffLogicActions {
    setSeed: (seed: ComposerSeed) => {
        seed: ComposerSeed
    } // composerSeedLogic
    clearActiveCreation: () => {
        value: true
    } // runnerPanelLogic
    setActiveCreation: (creation: ActiveCreation) => {
        creation: ActiveCreation
    } // runnerPanelLogic
    setHistoryExpanded: (expanded: boolean) => {
        expanded: boolean
    } // runnerPanelLogic
    closeSidePanel: (tab?: SidePanelTab | undefined) => {
        tab: SidePanelTab | undefined
    } // sidePanelStateLogic
    openSidePanel: (
        tab: SidePanelTab,
        options?: string | undefined
    ) => {
        options: string | undefined
        tab: SidePanelTab
    } // sidePanelStateLogic
    emitToolEvent: (event: ToolStreamEvent) => {
        event: ToolStreamEvent
    } // toolStreamEventsLogic
    composerShown: () => {
        value: true
    }
    dismissBanner: () => {
        value: true
    }
    escapeHatchClicked: () => {
        value: true
    }
    fillComposer: (prompt: string) => {
        prompt: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiFirstHandoffLogicMeta {
    key: string
}

export type aiFirstHandoffLogicType = MakeLogicType<
    aiFirstHandoffLogicValues,
    aiFirstHandoffLogicActions,
    AiFirstHandoffLogicProps,
    aiFirstHandoffLogicMeta
>

/**
 * The MCP exec path keeps the created record on the result's metadata for PostHog AI runs, even when the
 * text the model reads is truncated. Its `id` is the only exact correlation; a name lookup is a guess.
 */
function createdIdFromOutput(event: ToolStreamEvent): string | null {
    const record = getToolOutputRecord({ rawOutput: event.invocation.output, status: event.invocation.status })
    return typeof record?.id === 'string' && record.id ? record.id : null
}

/**
 * The AI-first "new entity" page is the side panel's own runner rendered full page. A completed create
 * call for `toolName` on this run opens the panel and routes to the created entity, so the same thread
 * continues against its editor.
 */
export const aiFirstHandoffLogic: LogicWrapper<aiFirstHandoffLogicType> = kea<aiFirstHandoffLogicType>([
    props({} as AiFirstHandoffLogicProps),
    key(({ toolName }) => toolName),
    path((key) => ['scenes', 'max', 'aiFirstCreate', 'aiFirstHandoffLogic', key]),
    connect(() => ({
        values: [
            runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
            ['activeCreation'],
            sidePanelStateLogic,
            ['sidePanelOpen', 'selectedTab'],
        ],
        actions: [
            runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
            ['setActiveCreation', 'clearActiveCreation', 'setHistoryExpanded'],
            sidePanelStateLogic,
            ['openSidePanel', 'closeSidePanel'],
            toolStreamEventsLogic,
            ['emitToolEvent'],
            composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }),
            ['setSeed'],
        ],
    })),
    actions({
        composerShown: true,
        escapeHatchClicked: true,
        dismissBanner: true,
        fillComposer: (prompt: string) => ({ prompt }),
    }),
    reducers({
        // pinned: persisted under the logic path, so the toolName key keeps one dismissal per surface.
        bannerDismissed: [false, { persist: true }, { dismissBanner: () => true }],
    }),
    listeners(({ actions, cache, props, values }) => ({
        // Runs after the previous scene left the panel registry, so its close is not read as dismissing the auto-open.
        composerShown: () => {
            // The panel is shared with the side panel: a run or history list left open there must not replace the composer.
            actions.clearActiveCreation()
            actions.setHistoryExpanded(false)
            // An unsent prompt typed in the panel is still in the shared form. An empty seed is how a host clears it.
            actions.setSeed({ prompt: '', autoSubmit: false })
            if (values.sidePanelOpen && values.selectedTab === SidePanelTab.Max) {
                actions.closeSidePanel()
            }
            posthog.capture(`${props.eventPrefix} viewed`)
        },
        escapeHatchClicked: () => {
            posthog.capture(`${props.eventPrefix} escape hatch clicked`)
        },
        dismissBanner: () => {
            posthog.capture(`${props.eventPrefix} banner dismissed`)
        },
        // A suggestion only fills the composer (no auto-submit) so the prompt can be tweaked before the agent starts.
        fillComposer: ({ prompt }) => {
            actions.setSeed({ prompt, autoSubmit: false })
            const textarea = document.querySelector<HTMLTextAreaElement>('[data-attr="task-composer-input"]')
            textarea?.focus()
            textarea?.setSelectionRange(prompt.length, prompt.length)
        },
        setActiveCreation: ({ creation }, _breakpoint, _action, previousState) => {
            // The first set for a stream key is the send; later ones attach the task and run ids.
            const previous = runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }).selectors.activeCreation(previousState)
            if (previous?.streamKey !== creation.streamKey) {
                posthog.capture(`${props.eventPrefix} submitted`)
            }
        },
        emitToolEvent: async ({ event }) => {
            if (
                event.source !== 'live' ||
                event.phase !== 'completed' ||
                event.toolName !== props.toolName ||
                event.streamKey !== values.activeCreation?.streamKey ||
                cache.handedOff
            ) {
                return
            }
            // Held from while the logic is alive: a remount puts a live manager back on the cache.
            const disposables = cache.disposables
            let createdId = createdIdFromOutput(event)
            if (!createdId) {
                try {
                    createdId = await props.findCreatedId(resolveToolCall(event.invocation).innerInput)
                } catch {
                    // A rejected lookup reads like no match: the entity is saved and the run stays on screen.
                    createdId = null
                }
            }
            // The page can be left, or the composer cleared or re-sent, while the lookup is in flight. The
            // shared panel logic outlives this page, so a left page must not read values or route from here.
            if (disposables.isDisposed || cache.handedOff || event.streamKey !== values.activeCreation?.streamKey) {
                return
            }
            if (!createdId) {
                lemonToast.error(props.notOpenedMessage)
                return
            }
            cache.handedOff = true
            posthog.capture(props.createdEvent, { [props.createdIdProperty]: createdId })
            // Open the panel before leaving the page so the runner instance stays mounted with its run.
            actions.openSidePanel(SidePanelTab.Max)
            router.actions.push(props.urlFor(createdId))
        },
    })),
])