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.

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

import { toast } from '@posthog/quill'

import { ApiError, readableErrorMessage } from 'lib/api-error'
import { fullName } from 'lib/utils/strings'
import { writeToClipboard } from 'lib/utils/writeToClipboard'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { UserBasicType } from '~/types'

import {
    tasksHandoffCreate,
    tasksPartialUpdate,
    tasksPinCreate,
    tasksRunsAnalyzeCreate,
    tasksRunsCancelCreate,
} from 'products/tasks/frontend/generated/api'
import { PatchedTaskWriteApi } from 'products/tasks/frontend/generated/api.schemas'

import { todaySpacesLogic } from './todaySpacesLogic'

export type TodaySessionSurface = 'sidebar' | 'feed'

export function sessionUrl(sessionId: string): string {
    return urls.absolute(urls.currentProject(urls.aiTask(sessionId)))
}

function serverMessage(error: unknown): string | undefined {
    return error instanceof ApiError ? readableErrorMessage(error.data) : undefined
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todaySessionMenuLogicValues {
    currentTeamId: number | null // teamLogic
    archiveConfirmMenuId: string | null
    handoffMenuId: string | null
    handoffUser: UserBasicType | null
    pendingSessionIds: string[]
    renaming: {
        sessionId: string
        surface: TodaySessionSurface
    } | null
    sessionDialogOpen: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todaySessionMenuLogicActions {
    loadPinnedTasks: () => any // todaySpacesLogic
    loadRecentTasks: (_?: void | undefined) => void // todaySpacesLogic
    analyzeSession: (
        sessionId: string,
        runId: string
    ) => {
        runId: string
        sessionId: string
    }
    archiveSession: (
        sessionId: string,
        archived: boolean
    ) => {
        archived: boolean
        sessionId: string
    }
    closeArchiveConfirm: () => {
        value: true
    }
    closeHandoff: () => {
        value: true
    }
    confirmArchive: (
        sessionId: string,
        runId: string
    ) => {
        runId: string
        sessionId: string
    }
    copyBranchName: (branch: string) => {
        branch: string
    }
    copySessionLink: (sessionId: string) => {
        sessionId: string
    }
    handOffSession: (
        sessionId: string,
        user: UserBasicType
    ) => {
        sessionId: string
        user: UserBasicType
    }
    openHandoff: (menuId: string) => {
        menuId: string
    }
    openSessionInNewTab: (sessionId: string) => {
        sessionId: string
    }
    renameSession: (
        sessionId: string,
        title: string
    ) => {
        sessionId: string
        title: string
    }
    requestArchive: (
        sessionId: string,
        menuId: string,
        activeRunId: string | null
    ) => {
        activeRunId: string | null
        menuId: string
        sessionId: string
    }
    sessionUpdateFailed: (sessionId: string) => {
        sessionId: string
    }
    sessionUpdated: (sessionId: string) => {
        sessionId: string
    }
    setHandoffUser: (user: UserBasicType | null) => {
        user: UserBasicType | null
    }
    setSessionPinned: (
        sessionId: string,
        pinned: boolean
    ) => {
        pinned: boolean
        sessionId: string
    }
    startRenaming: (
        sessionId: string,
        surface: TodaySessionSurface
    ) => {
        sessionId: string
        surface: TodaySessionSurface
    }
    stopRenaming: () => {
        value: true
    }
    stopSession: (
        sessionId: string,
        runId: string
    ) => {
        runId: string
        sessionId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todaySessionMenuLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        sessionDialogOpen: (handoffMenuId: string | null, archiveConfirmMenuId: string | null) => boolean
    }
}

export type todaySessionMenuLogicType = MakeLogicType<
    todaySessionMenuLogicValues,
    todaySessionMenuLogicActions,
    Record<string, any>,
    todaySessionMenuLogicMeta
>

export const todaySessionMenuLogic = kea<todaySessionMenuLogicType>([
    path(['layout', 'today', 'todaySessionMenuLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamId']],
        actions: [todaySpacesLogic, ['loadPinnedTasks', 'loadRecentTasks']],
    })),
    actions({
        setSessionPinned: (sessionId: string, pinned: boolean) => ({ sessionId, pinned }),
        renameSession: (sessionId: string, title: string) => ({ sessionId, title }),
        archiveSession: (sessionId: string, archived: boolean) => ({ sessionId, archived }),
        sessionUpdated: (sessionId: string) => ({ sessionId }),
        sessionUpdateFailed: (sessionId: string) => ({ sessionId }),
        startRenaming: (sessionId: string, surface: TodaySessionSurface) => ({ sessionId, surface }),
        stopRenaming: true,
        openHandoff: (menuId: string) => ({ menuId }),
        closeHandoff: true,
        setHandoffUser: (user: UserBasicType | null) => ({ user }),
        handOffSession: (sessionId: string, user: UserBasicType) => ({ sessionId, user }),
        analyzeSession: (sessionId: string, runId: string) => ({ sessionId, runId }),
        openSessionInNewTab: (sessionId: string) => ({ sessionId }),
        copyBranchName: (branch: string) => ({ branch }),
        copySessionLink: (sessionId: string) => ({ sessionId }),
        stopSession: (sessionId: string, runId: string) => ({ sessionId, runId }),
        requestArchive: (sessionId: string, menuId: string, activeRunId: string | null) => ({
            sessionId,
            menuId,
            activeRunId,
        }),
        closeArchiveConfirm: true,
        confirmArchive: (sessionId: string, runId: string) => ({ sessionId, runId }),
    }),
    reducers({
        renaming: [
            null as { sessionId: string; surface: TodaySessionSurface } | null,
            {
                startRenaming: (_, { sessionId, surface }) => ({ sessionId, surface }),
                stopRenaming: () => null,
                renameSession: () => null,
            },
        ],
        handoffMenuId: [
            null as string | null,
            {
                openHandoff: (_, { menuId }) => menuId,
                closeHandoff: () => null,
            },
        ],
        archiveConfirmMenuId: [
            null as string | null,
            {
                requestArchive: (state, { menuId, activeRunId }) => (activeRunId ? menuId : state),
                closeArchiveConfirm: () => null,
            },
        ],
        handoffUser: [
            null as UserBasicType | null,
            {
                openHandoff: () => null,
                closeHandoff: () => null,
                setHandoffUser: (_, { user }) => user,
            },
        ],
        pendingSessionIds: [
            [] as string[],
            {
                setSessionPinned: (state, { sessionId }) => [...state, sessionId],
                renameSession: (state, { sessionId }) => [...state, sessionId],
                archiveSession: (state, { sessionId }) => [...state, sessionId],
                handOffSession: (state, { sessionId }) => [...state, sessionId],
                analyzeSession: (state, { sessionId }) => [...state, sessionId],
                stopSession: (state, { sessionId }) => [...state, sessionId],
                confirmArchive: (state, { sessionId }) => [...state, sessionId],
                sessionUpdated: (state, { sessionId }) => state.filter((id) => id !== sessionId),
                sessionUpdateFailed: (state, { sessionId }) => state.filter((id) => id !== sessionId),
            },
        ],
    }),
    selectors({
        // The hover card stays shut while one of these is up, so it can't open over the dialog.
        sessionDialogOpen: [
            (s) => [s.handoffMenuId, s.archiveConfirmMenuId],
            (handoffMenuId: string | null, archiveConfirmMenuId: string | null): boolean =>
                handoffMenuId !== null || archiveConfirmMenuId !== null,
        ],
    }),
    listeners(({ actions, values }) => {
        const update = async (sessionId: string, patch: PatchedTaskWriteApi, failure: string): Promise<boolean> => {
            try {
                await tasksPartialUpdate(String(values.currentTeamId), sessionId, patch)
                actions.sessionUpdated(sessionId)
                return true
            } catch {
                toast.error({ title: failure })
                actions.sessionUpdateFailed(sessionId)
                return false
            }
        }

        const archive = async (sessionId: string, archived: boolean): Promise<boolean> => {
            const done = await update(
                sessionId,
                { archived },
                `Couldn’t ${archived ? 'archive' : 'restore'} this session. Try again.`
            )
            if (done && archived) {
                toast.success({
                    title: 'Session archived',
                    action: { label: 'Undo', onClick: () => actions.archiveSession(sessionId, false) },
                })
            }
            return done
        }

        return {
            setSessionPinned: async ({ sessionId, pinned }) => {
                try {
                    await tasksPinCreate(String(values.currentTeamId), sessionId, { pinned })
                    actions.sessionUpdated(sessionId)
                } catch {
                    toast.error({ title: `Couldn’t ${pinned ? 'pin' : 'unpin'} this session. Try again.` })
                    actions.sessionUpdateFailed(sessionId)
                }
            },
            renameSession: async ({ sessionId, title }) => {
                await update(sessionId, { title, title_manually_set: true }, 'Couldn’t rename this session. Try again.')
            },
            archiveSession: async ({ sessionId, archived }) => {
                await archive(sessionId, archived)
            },
            requestArchive: ({ sessionId, activeRunId }) => {
                if (!activeRunId) {
                    actions.archiveSession(sessionId, true)
                }
            },
            confirmArchive: async ({ sessionId, runId }) => {
                // Archiving alone leaves the cloud run going, so stop it first, as the confirm says.
                try {
                    await tasksRunsCancelCreate(String(values.currentTeamId), sessionId, runId)
                } catch (error) {
                    toast.error({ title: serverMessage(error) ?? 'Couldn’t stop this session. Try again.' })
                    actions.sessionUpdateFailed(sessionId)
                    return
                }
                if (await archive(sessionId, true)) {
                    actions.closeArchiveConfirm()
                }
            },
            stopSession: async ({ sessionId, runId }) => {
                try {
                    await tasksRunsCancelCreate(String(values.currentTeamId), sessionId, runId)
                    toast.success({ title: 'Stop requested' })
                    actions.sessionUpdated(sessionId)
                } catch (error) {
                    toast.error({ title: serverMessage(error) ?? 'Couldn’t stop this session. Try again.' })
                    actions.sessionUpdateFailed(sessionId)
                }
            },
            openSessionInNewTab: ({ sessionId }) => {
                window.open(sessionUrl(sessionId), '_blank', 'noopener')
            },
            copyBranchName: async ({ branch }) => {
                const outcome = await writeToClipboard(branch)
                if (outcome === 'copied') {
                    toast.success({ title: 'Branch name copied' })
                } else {
                    toast.error({ title: 'Couldn’t copy the branch name. Try again.' })
                }
            },
            copySessionLink: async ({ sessionId }) => {
                const outcome = await writeToClipboard(sessionUrl(sessionId))
                if (outcome === 'copied') {
                    toast.success({ title: 'Link copied' })
                } else {
                    toast.error({ title: 'Couldn’t copy the link. Try again.' })
                }
            },
            handOffSession: async ({ sessionId, user }) => {
                try {
                    await tasksHandoffCreate(String(values.currentTeamId), sessionId, { user: user.id })
                    toast.success({ title: `Session handed off to ${fullName(user)}` })
                    actions.closeHandoff()
                    actions.sessionUpdated(sessionId)
                } catch (error) {
                    toast.error({ title: serverMessage(error) ?? 'Couldn’t hand off this session. Try again.' })
                    actions.sessionUpdateFailed(sessionId)
                }
            },
            analyzeSession: async ({ sessionId, runId }) => {
                try {
                    const { analysis_task_id, created } = await tasksRunsAnalyzeCreate(
                        String(values.currentTeamId),
                        sessionId,
                        runId
                    )
                    actions.sessionUpdated(sessionId)
                    toast.success({
                        title: created ? 'Analysis started' : 'This run already has an analysis',
                        action: { label: 'Open', onClick: () => router.actions.push(urls.aiTask(analysis_task_id)) },
                    })
                } catch (error) {
                    toast.error({ title: serverMessage(error) ?? 'Couldn’t analyze this run. Try again.' })
                    actions.sessionUpdateFailed(sessionId)
                }
            },
            sessionUpdated: () => {
                actions.loadPinnedTasks()
                actions.loadRecentTasks()
            },
        }
    }),
])