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.

6.7 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { starredSpaces, todaySpacesLogic } from '~/layout/today/todaySpacesLogic'
import { Breadcrumb } from '~/types'

import { ChannelDTOApi } from '../generated/api.schemas'
import { SpaceComposerRepositoryConfig, spaceComposerRepositoryConfig } from './spaceSceneLogic'

/** The `{ value, items }` shape is what the combobox reads as a group. */
export interface NewSessionSpaceGroup {
    value: string
    items: string[]
}

/** `route` is a space's own New session, or a pick in the heading. `last_used` and `personal` are the generic default. */
export type NewSessionSpaceSource = 'route' | 'last_used' | 'personal' | 'first'

export interface NewSessionSpaceChoice {
    space: ChannelDTOApi | null
    source: NewSessionSpaceSource | null
}

/** Like PostHog Desktop: the space in the URL, else the last space the person was in, else their personal space. */
export function newSessionSpace(
    spaces: ChannelDTOApi[],
    routeSpaceId: string | null,
    lastSpaceId: string | null
): NewSessionSpaceChoice {
    const candidates: [NewSessionSpaceSource, ChannelDTOApi | undefined][] = [
        ['route', spaces.find((space) => space.id === routeSpaceId)],
        ['last_used', spaces.find((space) => space.id === lastSpaceId)],
        ['personal', spaces.find((space) => space.system_role === 'personal')],
        ['first', spaces[0]],
    ]
    const [source, space] = candidates.find(([, candidate]) => candidate) ?? [null, null]
    return { space: space ?? null, source }
}

/** The personal and starred spaces first, then the rest, under the same headings as the Spaces page. */
export function newSessionSpaceGroups(spaces: ChannelDTOApi[]): NewSessionSpaceGroup[] {
    const starredIds = starredSpaces(spaces).map((space) => space.id)
    const restIds = spaces.filter((space) => !starredIds.includes(space.id)).map((space) => space.id)
    return [
        { value: 'Starred', items: starredIds },
        { value: 'Spaces', items: restIds },
    ].filter((group) => group.items.length > 0)
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newSessionSceneLogicValues {
    lastSpaceId: string | null // todaySpacesLogic
    sortedSpaces: ChannelDTOApi[] // todaySpacesLogic
    spacesLoading: boolean // todaySpacesLogic
    spacesUnavailable: boolean // todaySpacesLogic
    breadcrumbs: Breadcrumb[]
    composerRepositoryConfig: SpaceComposerRepositoryConfig
    routeSpaceId: string | null
    space: ChannelDTOApi | null
    spaceChoice: NewSessionSpaceChoice
    spaceGroups: NewSessionSpaceGroup[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newSessionSceneLogicActions {
    loadSpaces: () => any // todaySpacesLogic
    pickSpace: (spaceId: string) => {
        spaceId: string
    }
    sessionStarted: (sessionId: string) => {
        sessionId: string
    }
    setRouteSpaceId: (spaceId: string | null) => {
        spaceId: string | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newSessionSceneLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        spaceChoice: (
            sortedSpaces: ChannelDTOApi[],
            routeSpaceId: string | null,
            lastSpaceId: string | null
        ) => NewSessionSpaceChoice
        space: (spaceChoice: NewSessionSpaceChoice) => ChannelDTOApi | null
        spaceGroups: (sortedSpaces: ChannelDTOApi[]) => NewSessionSpaceGroup[]
        composerRepositoryConfig: (space: ChannelDTOApi | null) => SpaceComposerRepositoryConfig
    }
}

export type newSessionSceneLogicType = MakeLogicType<
    newSessionSceneLogicValues,
    newSessionSceneLogicActions,
    Record<string, any>,
    newSessionSceneLogicMeta
>

export const newSessionSceneLogic = kea<newSessionSceneLogicType>([
    path(['products', 'tasks', 'spaces', 'newSessionSceneLogic']),
    connect(() => ({
        values: [todaySpacesLogic, ['sortedSpaces', 'spacesLoading', 'spacesUnavailable', 'lastSpaceId']],
        actions: [todaySpacesLogic, ['loadSpaces']],
    })),
    actions({
        pickSpace: (spaceId: string) => ({ spaceId }),
        setRouteSpaceId: (spaceId: string | null) => ({ spaceId }),
        sessionStarted: (sessionId: string) => ({ sessionId }),
    }),
    reducers({
        routeSpaceId: [null as string | null, { setRouteSpaceId: (_, { spaceId }) => spaceId }],
    }),
    selectors({
        spaceChoice: [
            (s) => [s.sortedSpaces, s.routeSpaceId, s.lastSpaceId],
            (
                sortedSpaces: ChannelDTOApi[],
                routeSpaceId: string | null,
                lastSpaceId: string | null
            ): NewSessionSpaceChoice => newSessionSpace(sortedSpaces, routeSpaceId, lastSpaceId),
        ],
        space: [
            (s) => [s.spaceChoice],
            (spaceChoice: NewSessionSpaceChoice): ChannelDTOApi | null => spaceChoice.space,
        ],
        spaceGroups: [
            (s) => [s.sortedSpaces],
            (sortedSpaces: ChannelDTOApi[]): NewSessionSpaceGroup[] => newSessionSpaceGroups(sortedSpaces),
        ],
        composerRepositoryConfig: [
            (s) => [s.space],
            (space: ChannelDTOApi | null): SpaceComposerRepositoryConfig => spaceComposerRepositoryConfig(space),
        ],
        breadcrumbs: [
            () => [],
            (): Breadcrumb[] => [
                { key: Scene.TaskSpaces, name: 'Spaces', path: urls.taskSpaces(), iconType: 'task' },
                { key: Scene.TaskNewSession, name: 'New session', path: urls.taskNewSession(), iconType: 'task' },
            ],
        ],
    }),
    listeners(({ actions, values }) => ({
        // Like PostHog Desktop, a pick moves to that space's own New session, so it becomes the last space too.
        pickSpace: ({ spaceId }) => {
            router.actions.push(urls.taskSpaceNewSession(spaceId))
        },
        sessionStarted: ({ sessionId }) => {
            // pinned: analytics event name and properties. Renaming them breaks dashboards.
            posthog.capture('today new session started', {
                space_role: values.space?.system_role ?? null,
                space_source: values.spaceChoice.source,
            })
            if (!values.space) {
                actions.loadSpaces()
            }
            router.actions.push(urls.aiTask(sessionId))
        },
    })),
    urlToAction(({ actions }) => ({
        [urls.taskNewSession()]: () => actions.setRouteSpaceId(null),
        [urls.taskSpaceNewSession(':id')]: ({ id }) => actions.setRouteSpaceId(id ?? null),
    })),
])