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

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { urls } from 'scenes/urls'

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

import { isApiNotFound, loadErrorMessage } from '../lib/load-error'
import { phDebugQueryParams } from '../lib/ph-debug'
import { Task, type TaskUpsertProps } from '../types/taskTypes'
import { tasksLogic } from './tasksLogic'

export interface TaskLogicProps {
    taskId: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskLogicValues {
    confirmedTask: Task | null
    runTaskInFlight: boolean
    task: Task | null
    taskError: string | null
    taskLoading: boolean
    taskNotFound: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskLogicActions {
    deleteTask: (params?: { leavePage?: boolean }) => {
        leavePage?: boolean
    }
    deleteTaskFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteTaskSuccess: (
        task: null,
        payload?: {
            leavePage?: boolean
        }
    ) => {
        task: null
        payload?: {
            leavePage?: boolean
        }
    }
    loadTask: () => any
    loadTaskFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTaskSuccess: (
        task: Task | null,
        payload?: any
    ) => {
        task: Task | null
        payload?: any
    }
    runTask: () => any
    runTaskFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    runTaskSuccess: (
        task: Task,
        payload?: any
    ) => {
        task: Task
        payload?: any
    }
    updateTask: ({ data }: { data: TaskUpsertProps }) => {
        data: TaskUpsertProps
    }
    updateTaskFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateTaskSuccess: (
        task: Task,
        payload?: {
            data: TaskUpsertProps
        }
    ) => {
        task: Task
        payload?: {
            data: TaskUpsertProps
        }
    }
}

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

export type taskLogicType = MakeLogicType<taskLogicValues, taskLogicActions, TaskLogicProps, taskLogicMeta>

export const taskLogic = kea<taskLogicType>([
    path(['products', 'posthog_ai', 'frontend', 'logics', 'taskLogic']),
    props({} as TaskLogicProps),
    key((props) => props.taskId),
    loaders(({ props, values, actions }) => ({
        task: [
            null as Task | null,
            {
                loadTask: async () => {
                    try {
                        return await api.tasks.get(props.taskId, phDebugQueryParams())
                    } catch (errorObject) {
                        actions.loadTaskFailure(loadErrorMessage('', errorObject), errorObject)
                        return isApiNotFound(errorObject) ? null : values.task
                    }
                },
                runTask: async () => {
                    // Interactive, not the default background: this run starts from the detail page the user
                    // is watching, and the agent-server only relays AskUserQuestion (and other approval
                    // prompts) to the client on non-background runs.
                    return await api.tasks.run(props.taskId, {
                        mode: TaskExecutionModeEnumApi.Interactive,
                        // The agent-server self-delivers `pending_user_message` from run state on boot, and
                        // interactive runs skip the workflow's forwarding path — nothing falls back to the
                        // task description. Without it the sandbox boots with no first turn and just idles.
                        ...(values.task?.description ? { pending_user_message: values.task.description } : {}),
                    })
                },
                // `leavePage: false` is for a host that shows the task outside its page, such as the PostHog AI panel.
                deleteTask: async (params?: { leavePage?: boolean }) => {
                    await api.tasks.delete(props.taskId)
                    // Reload each mounted list with its own active filter — a bare `loadTasks()`
                    // defaults to `{}`, which drops "For you"'s scout exclusion (and any other
                    // filter) and shows the whole visible set until the next filter/search change.
                    tasksLogic.findAllMounted().forEach((logic) => logic.actions.loadTasks(logic.values.taskListParams))
                    // The archived task has no page left, so send the user to the list of the host they
                    // are already in: the task page came from `/tasks`, but the shared AI workspace
                    // renders the same detail under `/ai` and must not eject them to another product.
                    if (params?.leavePage !== false) {
                        router.actions.push(
                            removeProjectIdIfPresent(router.values.location.pathname) === urls.ai()
                                ? urls.ai()
                                : urls.taskTracker()
                        )
                    }
                    return null
                },
                updateTask: async ({ data }: { data: TaskUpsertProps }) => {
                    const updatedTask = await api.tasks.update(props.taskId, data)
                    tasksLogic.findAllMounted().forEach((logic) => logic.actions.loadTasks(logic.values.taskListParams))
                    return updatedTask
                },
            },
        ],
    })),
    reducers({
        // A rename shows its new title at once. Only `title` applies early; other fields wait for the server.
        task: {
            updateTask: (state, { data }) =>
                state && data.title !== undefined ? { ...state, title: data.title } : state,
        },
        // The last task the server returned, so a rejected rename rolls back without another request.
        confirmedTask: [
            null as Task | null,
            {
                loadTaskSuccess: (_, { task }) => task,
                runTaskSuccess: (_, { task }) => task,
                updateTaskSuccess: (_, { task }) => task,
            },
        ],
        taskNotFound: [
            false,
            {
                loadTask: () => false,
                loadTaskFailure: (_, { errorObject }) => isApiNotFound(errorObject),
            },
        ],
        // The run loader shares the `task` loader's `taskLoading`, which is also true for plain
        // reloads — the Run button needs its own in-flight flag so it can't be clicked into the void.
        runTaskInFlight: [
            false,
            {
                runTask: () => true,
                runTaskSuccess: () => false,
                runTaskFailure: () => false,
            },
        ],
        taskError: [
            null as string | null,
            {
                loadTask: () => null,
                loadTaskFailure: (_, { error, errorObject }) =>
                    isApiNotFound(errorObject) ? null : loadErrorMessage(error, errorObject),
            },
        ],
    }),
    listeners(({ props, values, actions }) => {
        const syncToTaskList = (): void => {
            if (values.task) {
                tasksLogic.findMounted()?.actions.updateTask(values.task)
            }
        }
        return {
            loadTaskSuccess: syncToTaskList,
            // The sidebar rename writes through tasksLogic, so mirror the result onto this detail
            // logic. Without it the header keeps the old title until the next full load.
            [tasksLogic.actionTypes.renameTaskSuccess]: ({
                tasks,
                payload,
            }: {
                tasks: Task[]
                payload?: { taskId: string; title: string }
            }) => {
                if (payload?.taskId !== props.taskId) {
                    return
                }
                const renamed = tasks.find((task) => task.id === props.taskId)
                if (renamed) {
                    actions.loadTaskSuccess(renamed)
                }
            },
            runTaskSuccess: syncToTaskList,
            runTaskFailure: ({ error, errorObject }) => {
                const message = loadErrorMessage(error, errorObject)
                lemonToast.error(message || 'Failed to start the run')
                // Previously a rejected run changed nothing on screen, so the failure rate was
                // unmeasurable — capture it rather than leaving it to session recordings.
                posthog.capture('task_run_start_failed', { task_id: props.taskId, error: message })
            },
            updateTask: syncToTaskList,
            updateTaskSuccess: syncToTaskList,
            updateTaskFailure: ({ error, errorObject }) => {
                lemonToast.error(loadErrorMessage(error, errorObject) || "Couldn't save the task. Try again.")
                if (values.confirmedTask) {
                    actions.loadTaskSuccess(values.confirmedTask)
                }
            },
        }
    }),
])