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.

22.1 KB
Raw Blame
import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'

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

import api, { PaginatedResponse } from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { addProductIntent } from 'lib/utils/product-intents'
import { userLogic } from 'scenes/userLogic'

import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'

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

import type { UserType } from '../../../../frontend/src/types'
import { loadErrorMessage } from '../lib/load-error'
import { OriginProduct, Task, TaskAssigneeFilter, TaskListParams, TaskUpsertProps } from '../types/taskTypes'
import { taskEventsLogic } from './taskEventsLogic'
import { taskHistoryLogic } from './taskHistoryLogic'

function hasTasksFlag(featureFlags: FeatureFlagsSet): boolean {
    return !!(featureFlags[FEATURE_FLAGS.TASKS] || featureFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE])
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tasksLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    user: UserType | null // userLogic
    assigneeFilter: TaskAssigneeFilter
    hasRequestedTasks: boolean
    isStaffUser: boolean
    pendingSearchQuery: string | null
    repositories: string[]
    repositoriesLoading: boolean
    searchQuery: string
    taskListParams: TaskListParams
    taskListParamsReady: boolean
    tasks: Task[]
    tasksError: string | null
    tasksLoading: boolean
    tasksLoadingMore: boolean
    tasksNext: string | null
    tasksSearchPending: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tasksLogicActions {
    setPhaiViewMode: (mode: PhaiViewMode) => {
        mode: PhaiViewMode
    } // aiShellLogic
    setFeatureFlags: (
        flags: string[],
        variants: Record<string, boolean | string>
    ) => {
        flags: string[]
        variants: Record<string, boolean | string>
    } // featureFlagLogic
    taskDeleted: () => {
        value: true
    } // taskEventsLogic
    loadUserSuccess: (
        user: UserType | null,
        payload?:
            | {
                  resetOnFailure: boolean | undefined
              }
            | undefined
    ) => {
        payload?: {
            resetOnFailure: boolean | undefined
        }
        user: UserType | null
    } // userLogic
    createTask: ({ data }: { data: TaskUpsertProps }) => {
        data: TaskUpsertProps
    }
    createTaskFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createTaskSuccess: (
        tasks: Task[],
        payload?: {
            data: TaskUpsertProps
        }
    ) => {
        tasks: Task[]
        payload?: {
            data: TaskUpsertProps
        }
    }
    deleteTask: ({ taskId }: { taskId: string }) => {
        taskId: string
    }
    deleteTaskFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteTaskSuccess: (
        tasks: Task[],
        payload?: {
            taskId: string
        }
    ) => {
        tasks: Task[]
        payload?: {
            taskId: string
        }
    }
    loadMoreTasks: (_: void) => void
    loadMoreTasksFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadMoreTasksSuccess: (
        tasks: Task[],
        payload?: void
    ) => {
        tasks: Task[]
        payload?: void
    }
    loadRepositories: () => any
    loadRepositoriesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRepositoriesSuccess: (
        repositories: string[],
        payload?: any
    ) => {
        repositories: string[]
        payload?: any
    }
    loadTasks: (params?: TaskListParams) => TaskListParams
    loadTasksFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTasksSuccess: (
        tasks: Task[],
        payload?: TaskListParams
    ) => {
        tasks: Task[]
        payload?: TaskListParams
    }
    openTask: (taskId: Task['id']) => {
        taskId: string
    }
    renameTask: ({ taskId, title }: { taskId: string; title: string }) => {
        taskId: string
        title: string
    }
    renameTaskFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    renameTaskSuccess: (
        tasks: Task[],
        payload?: {
            taskId: string
            title: string
        }
    ) => {
        tasks: Task[]
        payload?: {
            taskId: string
            title: string
        }
    }
    setAssigneeFilter: (assigneeFilter: TaskAssigneeFilter) => {
        assigneeFilter: TaskAssigneeFilter
    }
    setSearchQuery: (search: string) => {
        search: string
    }
    setTasksNext: (next: string | null) => {
        next: string | null
    }
    updateTask: (task: Task) => {
        task: Task
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tasksLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        isStaffUser: (user: UserType | null) => boolean
        tasksSearchPending: (pendingSearchQuery: string | null) => boolean
        taskListParams: (
            searchQuery: string,
            assigneeFilter: TaskAssigneeFilter,
            user: UserType | null
        ) => TaskListParams
        taskListParamsReady: (assigneeFilter: TaskAssigneeFilter, user: UserType | null) => boolean
    }
}

export type tasksLogicType = MakeLogicType<tasksLogicValues, tasksLogicActions, Record<string, any>, tasksLogicMeta>

export const tasksLogic = kea<tasksLogicType>([
    path(['products', 'posthog_ai', 'frontend', 'logics', 'tasksLogic']),

    connect(() => ({
        values: [userLogic, ['user'], featureFlagLogic, ['featureFlags']],
        actions: [
            featureFlagLogic,
            ['setFeatureFlags'],
            aiShellLogic,
            ['setPhaiViewMode'],
            taskEventsLogic,
            ['taskDeleted'],
            userLogic,
            ['loadUserSuccess'],
        ],
    })),

    actions({
        openTask: (taskId: Task['id']) => ({ taskId }),
        updateTask: (task: Task) => ({ task }),
        setSearchQuery: (search: string) => ({ search }),
        setAssigneeFilter: (assigneeFilter: TaskAssigneeFilter) => ({ assigneeFilter }),
        setTasksNext: (next: string | null) => ({ next }),
    }),

    loaders(({ actions, values, cache }) => ({
        tasks: [
            [] as Task[],
            {
                // `breakpoint` cancels this invocation if a newer `loadTasks` action has been
                // dispatched, so filter changes don't overwrite state with stale responses.
                // A caller that passes nothing wants a plain refresh, not an unfiltered list: refresh
                // sites like `taskLogic`'s update/delete reload every mounted list without knowing what
                // it is showing, and `{}` there would swap the active filter for the whole visible set.
                // The default is evaluated per call, so it picks up the filter active at refresh time.
                loadTasks: async (params: TaskListParams = values.taskListParams, breakpoint) => {
                    cache.tasksLoadPending = !values.taskListParamsReady
                    if (cache.tasksLoadPending) {
                        return values.tasks
                    }
                    let response: PaginatedResponse<Task>
                    try {
                        response = await api.tasks.list(params)
                    } catch (error) {
                        // A superseded run must not settle the loader on the error path either. Its
                        // failure would raise the navigation's error banner over the results a newer
                        // run has already delivered, and only another `loadTasks` clears that value.
                        // `breakpoint` throws for a superseded run and does nothing for the newest
                        // one, whose failure does need to surface.
                        breakpoint()
                        throw error
                    }
                    breakpoint()
                    actions.setTasksNext(response.next ?? null)
                    return response.results
                },
                // Appends the next page for infinite scroll. The cursor is the absolute `next`
                // URL from the previous response, so it carries the active filters forward.
                loadMoreTasks: async (_: void, breakpoint) => {
                    const next = values.tasksNext
                    if (!next) {
                        return values.tasks
                    }
                    // `next` is an opaque absolute cursor URL from the previous response, not a static
                    // endpoint — the generated `tasksList` takes structured params, not a raw URL.
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                    const response = await api.get<PaginatedResponse<Task>>(next)
                    breakpoint()
                    // `breakpoint` only cancels a second `loadMoreTasks` call, not a `loadTasks` triggered
                    // by a filter change while this page was in flight. A fresh `loadTasks` resets
                    // `tasksNext` to null synchronously on dispatch, so a mismatch here means this page
                    // belongs to a filter that's no longer active — discard it instead of appending.
                    if (values.tasksNext !== next) {
                        return values.tasks
                    }
                    actions.setTasksNext(response.next ?? null)
                    // The server pages by offset over an activity order that streaming runs keep
                    // moving, so a row already loaded can come back on the next page. Keep the first
                    // copy: a repeated row would collide with its own key in the list.
                    const loadedIds = new Set(values.tasks.map((task) => task.id))
                    return [...values.tasks, ...response.results.filter((task) => !loadedIds.has(task.id))]
                },
                createTask: async ({ data }: { data: TaskUpsertProps }) => {
                    const newTask = await api.tasks.create(data)
                    void addProductIntent({
                        product_type: ProductKey.TASKS,
                        intent_context: ProductIntentContext.TASK_CREATED,
                    })
                    return [...values.tasks, newTask]
                },
                deleteTask: async ({ taskId }: { taskId: string }) => {
                    await api.tasks.delete(taskId)
                    return values.tasks.filter((t) => t.id !== taskId)
                },
                renameTask: async ({ taskId, title }: { taskId: string; title: string }) => {
                    const renamed = await api.tasks.update(taskId, { title })
                    return values.tasks.map((t) => (t.id === taskId ? renamed : t))
                },
            },
        ],
        repositories: [
            [] as string[],
            {
                // Repositories are loaded via a dedicated endpoint instead of being derived
                // from `tasks` so the picker is not constrained by list pagination or by the
                // filter currently applied to the task list.
                loadRepositories: async () => {
                    const response = await api.tasks.repositories()
                    return response.repositories
                },
            },
        ],
    })),

    reducers({
        tasks: {
            updateTask: (state, { task }) => state.map((t) => (t.id === task.id ? task : t)),
        },
        searchQuery: [
            '' as string,
            {
                setSearchQuery: (_, { search }) => search,
            },
        ],
        assigneeFilter: [
            'for_you' as TaskAssigneeFilter,
            {
                setAssigneeFilter: (_, { assigneeFilter }) => assigneeFilter,
            },
        ],
        // Whether the first list request has been dispatched, so a feature-flag payload arriving
        // after mount doesn't fire a second one (`onFeatureFlags` can fire repeatedly).
        hasRequestedTasks: [
            false,
            {
                loadTasks: () => true,
            },
        ],
        // The search the loaded rows don't answer yet, null once they do. `tasksLoading` misses the
        // 300ms debounce in front of the request, and that gap is when a consumer filtering the
        // cached rows would report "nothing found" for a search whose matches are still on the
        // server. A load that was already in flight when the user typed answers the previous query,
        // so only a response carrying this term ends the wait. A failure carries no term, and
        // holding the wait open on one would leave a spinner over the error instead.
        pendingSearchQuery: [
            null as string | null,
            {
                setSearchQuery: (_, { search }) => search,
                loadTasksSuccess: (state, { payload }) => ((payload?.search ?? '') === (state ?? '') ? null : state),
                loadTasksFailure: () => null,
            },
        ],
        tasksError: [
            null as string | null,
            {
                loadTasks: () => null,
                loadTasksFailure: (_, { error, errorObject }) => loadErrorMessage(error, errorObject),
            },
        ],
        // Cursor for the next page; null once the list is exhausted. Reset on every fresh load so a
        // filter/search change starts from page one.
        tasksNext: [
            null as string | null,
            {
                loadTasks: () => null,
                setTasksNext: (_, { next }) => next,
                // Deliberately survives `loadMoreTasksFailure`: the cursor is what renders the manual
                // "Load more" control, so dropping it on a transient failure would take the retry away
                // for the rest of the session. The failure listener raises a toast instead.
            },
        ],
        // Distinct from `tasksLoading` (which also flips for `loadMoreTasks`) so the infinite-scroll
        // trigger can guard against firing again while a page is already in flight.
        tasksLoadingMore: [
            false,
            {
                loadMoreTasks: () => true,
                loadMoreTasksSuccess: () => false,
                loadMoreTasksFailure: () => false,
            },
        ],
    }),

    selectors({
        // The "all team" filter is staff-only; expose it so the menu can conditionally show it.
        isStaffUser: [(s) => [s.user], (user: null | import('~/types').UserType): boolean => !!user?.is_staff],
        // Whether the visible rows still lag the typed search (see `pendingSearchQuery`).
        tasksSearchPending: [
            (s) => [s.pendingSearchQuery],
            (pendingSearchQuery: string | null): boolean => pendingSearchQuery !== null,
        ],
        // Combined list filters: search term + the assignee toggle. A scout run is created by the user
        // the scout executes as, so "for you" and "my scouts" are the two halves of that user's
        // `created_by` rows: those runs are what clutters their list, so they are what the split has to
        // move. Keying "my scouts" on scout ownership (`LLMSkillOwner`) instead would hide the runs from
        // the person actually seeing them, since the executing identity and the owner can differ.
        // "Team scouts" is every scout task on the team. "All team" drops the `created_by` pin, so the
        // list widens to every task the user can read. It is not a team-wide read: the server bypasses
        // the visibility filter in local development only (see `all_team_tasks` in `TaskListParams`).
        taskListParams: [
            (s) => [s.searchQuery, s.assigneeFilter, s.user],
            (
                searchQuery: string,
                assigneeFilter: TaskAssigneeFilter,
                user: null | import('~/types').UserType
            ): TaskListParams => {
                // Activity order, not the server's `-created_at` default: this list is presented as
                // recent activity, and a task can stream for hours without its row being edited.
                const base: TaskListParams = {
                    search: searchQuery || undefined,
                    ordering: TasksListOrdering.LastActivityAt,
                }
                // Guard here too: only the staff-gated menu item may send `all_team_tasks`, so a
                // non-staff caller falls back to their own tasks instead of sending a parameter the
                // server would discard.
                if (assigneeFilter === 'all_team' && user?.is_staff) {
                    return { ...base, all_team_tasks: true }
                }
                if (assigneeFilter === 'team_scouts') {
                    return { ...base, origin_product: OriginProduct.SIGNALS_SCOUT }
                }
                if (assigneeFilter === 'my_scouts') {
                    return { ...base, origin_product: OriginProduct.SIGNALS_SCOUT, created_by: user?.id }
                }
                if (assigneeFilter === 'posthog_ai' || assigneeFilter === 'slack') {
                    return { ...base, origin_product: assigneeFilter, created_by: user?.id }
                }
                if (assigneeFilter === 'desktop') {
                    return { ...base, client_provenance: 'posthog_desktop', created_by: user?.id }
                }
                return { ...base, created_by: user?.id, exclude_origin_product: OriginProduct.SIGNALS_SCOUT }
            },
        ],
        // Every filter except "team scouts" reads the user: `created_by` pins the list to them, and
        // "all team" is staff-gated. A request sent before the user lands carries no pin, so the
        // server answers with every task the caller can read, shared ones from other people
        // included. Hold the request until then; `loadUserSuccess` sends it.
        taskListParamsReady: [
            (s) => [s.assigneeFilter, s.user],
            (assigneeFilter: TaskAssigneeFilter, user: null | import('~/types').UserType): boolean =>
                assigneeFilter === 'team_scouts' || !!user?.id,
        ],
    }),

    listeners(({ actions, values, cache }) => {
        const loadTasksWhenReady = (): void => {
            cache.tasksLoadPending = !values.taskListParamsReady
            if (!cache.tasksLoadPending) {
                actions.loadTasks(values.taskListParams)
            }
        }
        // The app renders once the feature-flag request times out (3s), so this logic can mount
        // before the flags land — and it's an unkeyed singleton, so `afterMount` never runs again.
        // Without this the nav would sit on an empty list, showing "no tasks" rather than loading.
        // The user can land late as well (see `taskListParamsReady`), in either order with the
        // flags, so the first request goes out from whichever arrives last.
        const loadInitialTasks = (): void => {
            if (!values.hasRequestedTasks && hasTasksFlag(values.featureFlags) && values.taskListParamsReady) {
                actions.loadTasks(values.taskListParams)
            }
        }
        return {
            openTask: ({ taskId }) => {
                router.actions.push(`/tasks/${taskId}`)
            },
            // Debounce typing before hitting the server; the loader's own `breakpoint` then drops any
            // response that a newer query has already superseded.
            setSearchQuery: async (_, breakpoint) => {
                await breakpoint(300)
                loadTasksWhenReady()
            },
            setAssigneeFilter: loadTasksWhenReady,
            loadMoreTasksFailure: ({ error, errorObject }) => {
                lemonToast.error(`Couldn't load more tasks: ${loadErrorMessage(error, errorObject)}`)
            },
            // Every surface that archives goes through this loader, so sync the independent panel
            // history here instead of asking each one to remember. Only when it's already mounted:
            // building it would fetch a list nobody is showing, and a later mount loads it fresh.
            deleteTaskSuccess: ({ payload }) => {
                if (payload) {
                    taskHistoryLogic.findMounted()?.actions.taskArchived(payload.taskId)
                }
                actions.taskDeleted()
            },
            renameTaskFailure: ({ error, errorObject }) => {
                lemonToast.error(`Couldn't rename the task: ${loadErrorMessage(error, errorObject)}`)
            },
            setFeatureFlags: loadInitialTasks,
            // The task list only loads on mount. A chat made on the legacy view has a task copy by the
            // time the user switches, and the merged list shows it as that task once it is loaded.
            setPhaiViewMode: ({ mode }) => {
                if (mode === 'new') {
                    actions.loadTasks(values.taskListParams)
                }
            },
            loadUserSuccess: () => {
                if (cache.tasksLoadPending) {
                    loadTasksWhenReady()
                } else {
                    loadInitialTasks()
                }
            },
        }
    }),

    events(({ actions, values }) => ({
        afterMount: () => {
            if (hasTasksFlag(values.featureFlags) && values.taskListParamsReady) {
                actions.loadTasks(values.taskListParams)
            }
        },
    })),
])