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.

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

import { supportLogic } from 'lib/components/Support/supportLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'

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

import type { ContextUsage } from '../types/streamTypes'
import type { AgentCommand } from '../types/wireTypes'
import { captureCommandFeedback } from '../utils/feedbackEvents'
import {
    APP_COMMANDS,
    type AppCommand,
    type AppCommandName,
    type SlashCommand,
    buildSlashCommands,
    getAppCommand,
    parseSlashCommand,
} from '../utils/slashCommands'
import { runInteractionLogic, type RunInteractionLogicProps } from './runInteractionLogic'
import { runStreamLogic } from './runStreamLogic'

/** The output of `/btw` or `/usage`, shown above the composer until dismissed. `body` is null while loading. */
export interface CommandResult {
    title: string
    body: string | null
}

export function formatUsageSummary(usage: ContextUsage | null): string {
    const lines: string[] = []
    const tokens = usage?.tokens
    if (typeof tokens?.inputTokens === 'number') {
        lines.push(`- Input tokens: ${humanFriendlyNumber(tokens.inputTokens)}`)
    }
    if (typeof tokens?.outputTokens === 'number') {
        lines.push(`- Output tokens: ${humanFriendlyNumber(tokens.outputTokens)}`)
    }
    if (typeof tokens?.cachedReadTokens === 'number') {
        lines.push(`- Cached tokens read: ${humanFriendlyNumber(tokens.cachedReadTokens)}`)
    }
    if (typeof tokens?.cachedWriteTokens === 'number') {
        lines.push(`- Cached tokens written: ${humanFriendlyNumber(tokens.cachedWriteTokens)}`)
    }
    if (typeof usage?.used === 'number' && typeof usage.size === 'number' && usage.size > 0) {
        const percentage = Math.min(100, Math.round((usage.used / usage.size) * 100))
        lines.push(
            `- Context window: ${humanFriendlyNumber(usage.used)} of ${humanFriendlyNumber(usage.size)} tokens (${percentage}%)`
        )
    }
    if (typeof usage?.cost === 'number') {
        lines.push(`- Cost: $${usage.cost.toFixed(2)}`)
    }
    return lines.length > 0
        ? lines.join('\n')
        : "This run hasn't reported usage yet. Try again after the agent replies."
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface runSlashCommandsLogicValues {
    currentProjectId: number | null // projectLogic
    composerForm: {
        draft: string
    } // runInteractionLogic
    dataProcessingAccepted: boolean // runInteractionLogic
    isTerminal: boolean // runInteractionLogic
    availableCommands: AgentCommand[] // runStreamLogic
    bootstrappedRunId: string | null // runStreamLogic
    bootstrappedTaskId: string | null // runStreamLogic
    contextUsage: ContextUsage | null // runStreamLogic
    traceId: string | null // runStreamLogic
    appCommands: AppCommand[]
    commandResult: CommandResult | null
    slashCommands: SlashCommand[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface runSlashCommandsLogicActions {
    blockOnConsent: (source?: 'draft' | 'queue' | 'steer' | undefined) => {
        source: 'draft' | 'queue' | 'steer'
    } // runInteractionLogic
    resetComposerForm: (
        values?:
            | {
                  draft: string
              }
            | undefined
    ) => {
        values?: {
            draft: string
        }
    } // runInteractionLogic
    submitComposerForm: () => {
        value: boolean
    } // runInteractionLogic
    openSupportForm: (
        values: Partial<import('lib/components/Support/supportLogic').SupportFormFields> & {
            target?: 'modal' | 'sidePanel'
        }
    ) => Partial<import('lib/components/Support/supportLogic').SupportFormFields> & {
        target?: 'modal' | 'sidePanel' | undefined
    } // supportLogic
    askSideQuestion: (question: string) => {
        question: string
    }
    dismissCommandResult: () => {
        value: true
    }
    runAppCommand: (
        name: AppCommandName,
        args: string
    ) => {
        args: string
        name: AppCommandName
    }
    setCommandResult: (result: CommandResult | null) => {
        result: CommandResult | null
    }
    submitComposer: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface runSlashCommandsLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        appCommands: (isTerminal: boolean, arg: string | null | undefined) => AppCommand[]
        slashCommands: (appCommands: AppCommand[], availableCommands: AgentCommand[]) => SlashCommand[]
    }
}

export type runSlashCommandsLogicType = MakeLogicType<
    runSlashCommandsLogicValues,
    runSlashCommandsLogicActions,
    RunInteractionLogicProps,
    runSlashCommandsLogicMeta
>

/**
 * Slash commands for a run's composer. App commands (`/btw`, `/good`, `/bad`, `/feedback`, `/usage`,
 * `/ticket`) run here and never reach the agent. Every other command goes to the agent as prompt text
 * through `runInteractionLogic`, which already handles `/clear` on a finished run.
 */
export const runSlashCommandsLogic: LogicWrapper<runSlashCommandsLogicType> = kea<runSlashCommandsLogicType>([
    props({} as RunInteractionLogicProps),
    // Same key as `runInteractionLogic`, so the two share one lifetime.
    key((props) => props.interactionKey ?? props.runId),
    path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'runSlashCommandsLogic', key]),
    connect((props: RunInteractionLogicProps) => ({
        values: [
            projectLogic,
            ['currentProjectId'],
            runStreamLogic({ streamKey: props.streamKey ?? props.runId }),
            ['availableCommands', 'bootstrappedRunId', 'bootstrappedTaskId', 'contextUsage', 'traceId'],
            runInteractionLogic(props),
            ['composerForm', 'isTerminal', 'dataProcessingAccepted'],
        ],
        actions: [
            supportLogic,
            ['openSupportForm'],
            runInteractionLogic(props),
            ['resetComposerForm', 'submitComposerForm', 'blockOnConsent'],
        ],
    })),
    actions({
        submitComposer: true,
        runAppCommand: (name: AppCommandName, args: string) => ({ name, args }),
        askSideQuestion: (question: string) => ({ question }),
        setCommandResult: (result: CommandResult | null) => ({ result }),
        dismissCommandResult: true,
    }),
    reducers({
        commandResult: [
            null as CommandResult | null,
            {
                setCommandResult: (_, { result }) => result,
                dismissCommandResult: () => null,
            },
        ],
    }),
    selectors({
        appCommands: [
            (s) => [s.isTerminal, (_, props: RunInteractionLogicProps) => props.currentRuntimeAdapter],
            (isTerminal: boolean, runtimeAdapter: string | null | undefined): AppCommand[] =>
                APP_COMMANDS.filter(
                    // A side question needs a live Claude session: the Codex and Pi harnesses don't answer one.
                    (command) =>
                        command.name !== 'btw' || (!isTerminal && runtimeAdapter === RuntimeAdapterEnumApi.Claude)
                ),
        ],
        slashCommands: [
            (s) => [s.appCommands, s.availableCommands],
            (appCommands: AppCommand[], availableCommands: AgentCommand[]): SlashCommand[] =>
                buildSlashCommands(appCommands, availableCommands),
        ],
    }),
    listeners(({ actions, values, props, cache }) => {
        /** Where a side question would go, or why it cannot run yet. Checked before the draft is cleared. */
        const resolveSideQuestionTarget = ():
            | { projectId: string; taskId: string; runId: string }
            | { error: string } => {
            if (cache.sideQuestionRequest) {
                return { error: 'Wait for your last side question to finish first' }
            }
            const { bootstrappedRunId: runId, bootstrappedTaskId: taskId, currentProjectId } = values
            if (!runId || !taskId || currentProjectId === null) {
                return { error: 'Wait for the agent to start, then ask again' }
            }
            return { projectId: String(currentProjectId), taskId, runId }
        }

        return {
            submitComposer: () => {
                const parsed = parseSlashCommand(values.composerForm.draft)
                const command = parsed ? values.slashCommands.find((c) => c.name === parsed.name) : undefined
                if (parsed && command) {
                    // pinned: analytics event name — renaming breaks dashboards
                    posthog.capture('posthog_ai_slash_command_used', {
                        command: command.name,
                        command_source: command.source,
                        agent_runtime: 'sandbox',
                    })
                }
                const typedAppCommand = parsed ? getAppCommand(parsed.name) : undefined
                if (typedAppCommand && !command) {
                    // The menu hides an app command this run cannot run, but nothing stops someone typing it.
                    // Passing it on would put the text in the transcript, or start a new run to answer it.
                    lemonToast.error(
                        typedAppCommand.unavailableError ?? `/${typedAppCommand.name} is not available here`
                    )
                    return
                }
                const appCommand = command?.source === 'app' ? typedAppCommand : undefined
                if (!parsed || !appCommand) {
                    actions.submitComposerForm()
                    return
                }
                if (appCommand.requiredInputError && !parsed.args) {
                    lemonToast.error(appCommand.requiredInputError)
                    return
                }
                if (appCommand.name === 'btw') {
                    // A side question reaches the model, so it takes the same consent gate as an ordinary send.
                    if (!values.dataProcessingAccepted) {
                        actions.blockOnConsent()
                        return
                    }
                    // Checked here as well as in the listener, so a rejected question keeps the typed draft.
                    const target = resolveSideQuestionTarget()
                    if ('error' in target) {
                        lemonToast.error(target.error)
                        return
                    }
                }
                actions.runAppCommand(appCommand.name, parsed.args)
                actions.resetComposerForm()
            },
            runAppCommand: ({ name, args }) => {
                const taskId = values.bootstrappedTaskId ?? props.taskId
                const run = { taskId, runId: values.bootstrappedRunId ?? props.runId }
                switch (name) {
                    case 'good':
                    case 'bad':
                    case 'feedback':
                        captureCommandFeedback(taskId, values.traceId, name === 'feedback' ? null : name, run, args)
                        lemonToast.success('Thanks for the feedback')
                        return
                    case 'usage':
                        actions.setCommandResult({
                            title: 'Usage for this run',
                            body: formatUsageSummary(values.contextUsage),
                        })
                        return
                    case 'ticket': {
                        const taskUrl = taskId ? urls.absolute(urls.currentProject(urls.taskDetail(taskId))) : null
                        actions.openSupportForm({
                            kind: 'support',
                            target: 'sidePanel',
                            isEmailFormOpen: true,
                            message: [args, taskUrl ? `PostHog AI task: ${taskUrl}` : null]
                                .filter(Boolean)
                                .join('\n\n'),
                            // Attributes the ticket to this run, like the other PostHog AI ticket handovers.
                            ai_conversation_id: taskId ?? null,
                            ai_trace_id: values.traceId,
                        })
                        return
                    }
                    case 'btw':
                        actions.askSideQuestion(args)
                        return
                }
            },
            askSideQuestion: async ({ question }) => {
                const target = resolveSideQuestionTarget()
                if ('error' in target) {
                    lemonToast.error(target.error)
                    return
                }
                const request = (cache.sideQuestionRequest = {})
                actions.setCommandResult({ title: question, body: null })
                const disposables = cache.disposables
                try {
                    const response = await tasksRunsCommandCreate(target.projectId, target.taskId, target.runId, {
                        jsonrpc: '2.0',
                        method: 'side_question',
                        params: { question },
                    })
                    const answer = (response.result as { answer?: unknown } | undefined)?.answer
                    if (response.error || typeof answer !== 'string' || !answer) {
                        throw new Error('Side question produced no answer')
                    }
                    if (!disposables.isDisposed && values.commandResult?.title === question) {
                        actions.setCommandResult({ title: question, body: answer })
                    }
                } catch (error) {
                    if (!disposables.isDisposed) {
                        if (values.commandResult?.title === question && values.commandResult.body === null) {
                            actions.dismissCommandResult()
                        }
                        lemonToast.error("Couldn't answer your side question. Try again.")
                        posthog.captureException(error)
                    }
                } finally {
                    if (cache.sideQuestionRequest === request) {
                        cache.sideQuestionRequest = undefined
                    }
                }
            },
        }
    }),
])