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

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

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

import type { StoredLogEntry } from '../types/wireTypes'
import { type RunLog, type RunStatus, isTerminalRunStatus, runStreamLogic } from './runStreamLogic'

export interface RunCancellationLogicProps {
    streamKey: string
}

export type CancellationState = 'waiting' | 'sending' | null

function confirmsAgentReady(entry: StoredLogEntry, runId: string): boolean {
    const { method, params } = entry.notification
    if (entry.source_run_id && entry.source_run_id !== runId) {
        return false
    }
    return (
        (method === '_posthog/progress' &&
            params?.group === `setup:${runId}` &&
            params.step === 'agent' &&
            params.status === 'completed') ||
        (method === '_posthog/run_started' &&
            (params?.runId === runId || (params?.runId === undefined && entry.source_run_id === runId)))
    )
}

function confirmsTurnStarted(entry: StoredLogEntry, runId: string): boolean {
    if (entry.source_run_id !== runId) {
        return false
    }
    const { method, params } = entry.notification
    const update = params?.update as { sessionUpdate?: string } | undefined
    return (
        method === '_posthog/permission_request' ||
        (method === 'session/update' &&
            [
                'user_message_chunk',
                'user_message',
                'agent_message_chunk',
                'agent_message',
                'agent_thought_chunk',
                'tool_call',
                'tool_call_update',
            ].includes(update?.sessionUpdate ?? ''))
    )
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface runCancellationLogicValues {
    currentProjectId: number | null // projectLogic
    bootstrappedRunId: string | null // runStreamLogic
    bootstrappedTaskId: string | null // runStreamLogic
    currentRunStatus: RunStatus | null // runStreamLogic
    log: RunLog // runStreamLogic
    cancellationState: CancellationState
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface runCancellationLogicActions {
    cancelPermissionDelivery: () => {
        value: true
    } // runStreamLogic
    cancelWhenReady: () => {
        value: true
    }
    cancellationFailed: () => {
        value: true
    }
    clearCancellation: () => {
        value: true
    }
    requestCancellation: () => {
        value: true
    }
    setCancellationState: (state: CancellationState) => {
        state: CancellationState
    }
}

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

export type runCancellationLogicType = MakeLogicType<
    runCancellationLogicValues,
    runCancellationLogicActions,
    RunCancellationLogicProps,
    runCancellationLogicMeta
>

export const runCancellationLogic: LogicWrapper<runCancellationLogicType> = kea<runCancellationLogicType>([
    props({} as RunCancellationLogicProps),
    key((props) => props.streamKey),
    path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'runCancellationLogic', key]),
    connect((props: RunCancellationLogicProps) => ({
        values: [
            projectLogic,
            ['currentProjectId'],
            runStreamLogic(props),
            ['bootstrappedRunId', 'bootstrappedTaskId', 'currentRunStatus', 'log'],
        ],
        actions: [runStreamLogic(props), ['cancelPermissionDelivery']],
    })),
    actions({
        requestCancellation: true,
        cancelWhenReady: true,
        setCancellationState: (state: CancellationState) => ({ state }),
        // Its own action, so a listener can tell a failed Stop from the clear that a turn end brings.
        cancellationFailed: true,
        clearCancellation: true,
    }),
    reducers({
        cancellationState: [
            null as CancellationState,
            {
                setCancellationState: (_, { state }) => state,
                cancellationFailed: () => null,
                clearCancellation: () => null,
            },
        ],
    }),
    listeners(({ actions, values, props, cache }) => ({
        requestCancellation: () => {
            if (values.cancellationState || isTerminalRunStatus(values.currentRunStatus)) {
                return
            }
            actions.cancelPermissionDelivery()
            actions.setCancellationState('waiting')
            actions.cancelWhenReady()
        },
        cancelWhenReady: async () => {
            const { bootstrappedRunId: runId, bootstrappedTaskId: taskId, currentProjectId } = values
            if (
                values.cancellationState !== 'waiting' ||
                !runId ||
                !taskId ||
                currentProjectId === null ||
                isTerminalRunStatus(values.currentRunStatus) ||
                !values.log.entries.some(({ entry }) => confirmsAgentReady(entry, runId)) ||
                // Readiness precedes first-message delivery; canceling an idle agent would miss that message.
                !values.log.entries.some(({ entry }) => confirmsTurnStarted(entry, runId))
            ) {
                return
            }
            actions.setCancellationState('sending')
            const disposables = cache.disposables
            const request = (cache.cancelRequest = {})
            try {
                const response = await tasksRunsCommandCreate(String(currentProjectId), taskId, runId, {
                    jsonrpc: '2.0',
                    method: 'cancel',
                })
                if (response.error) {
                    throw new Error('Agent rejected cancellation')
                }
            } catch (error) {
                if (!disposables.isDisposed && cache.cancelRequest === request && values.bootstrappedRunId === runId) {
                    actions.cancellationFailed()
                    lemonToast.error("Couldn't stop this run. Please try again.")
                    posthog.captureException(error)
                }
            }
        },
        cancellationFailed: () => {
            cache.cancelRequest = undefined
        },
        clearCancellation: () => {
            cache.cancelRequest = undefined
        },
        [runStreamLogic(props).actionTypes.appendEntries]: () => {
            if (values.cancellationState === 'waiting') {
                actions.cancelWhenReady()
            }
        },
        [runStreamLogic(props).actionTypes.ingestAcpFrame]: ({ entry, source }) => {
            if (
                source === 'live' &&
                entry.source_run_id === values.bootstrappedRunId &&
                entry.notification.method === '_posthog/turn_complete'
            ) {
                actions.clearCancellation()
            }
        },
        [runStreamLogic(props).actionTypes.handleTerminalStatus]: ({ status }) => {
            if (isTerminalRunStatus(status)) {
                actions.clearCancellation()
            }
        },
        [runStreamLogic(props).actionTypes.reset]: () => actions.clearCancellation(),
        [runStreamLogic(props).actionTypes.closeSse]: () => actions.clearCancellation(),
        [runStreamLogic(props).actionTypes.bootstrapRun]: ({ runId }) => {
            if (cache.cancellationRunId && cache.cancellationRunId !== runId) {
                actions.clearCancellation()
            }
            cache.cancellationRunId = runId
        },
    })),
])