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.

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

import { toast } from '@posthog/quill'

import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { withBackLink } from 'scenes/analytics/analyticsBackLink'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'

import { Breadcrumb } from '~/types'

import { CANVAS_EVENTS } from '../canvasAnalytics'
import { CanvasSpace, loadCanvasSpaces } from '../canvasTasksApi'
import { FREEFORM_TEMPLATE_ID, UNTITLED_CANVAS_NAME } from '../canvasTemplates'
import { canvasCapabilities, blankCanvasFiles } from '../editing/blockLibrary/blockProject'
import { canvasesCreate, canvasesPublishCreate, canvasesSourceRetrieve } from '../generated/api'
import type { CanvasApi, CanvasCapabilitiesApi } from '../generated/api.schemas'
import { startCanvasGeneration } from '../startCanvasGeneration'

// pinned: `starter_id` of the create event for a canvas started without a prompt, shared with PostHog Desktop's starters
const BLANK_STARTER_ID = 'blank'

/** A prompt whose canvas exists but whose build did not start. The canvas page picks it up. */
export interface CanvasStartHandoff {
    canvasId: string
    instruction: string
    fromSuggestion: boolean
}

function pickCanvasSpaceId(
    spaces: CanvasSpace[] | null,
    chosen: string | null,
    requested: string | null
): string | null {
    if (!spaces) {
        return null
    }
    const has = (id: string | null): id is string => !!id && spaces.some((space) => space.id === id)
    if (has(chosen)) {
        return chosen
    }
    if (has(requested)) {
        return requested
    }
    return (spaces.find((space) => space.system_role === 'personal') ?? spaces[0])?.id ?? null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasNewLogicValues {
    currentProjectId: number | null // projectLogic
    breadcrumbs: Breadcrumb[]
    chosenSpaceId: string | null
    editHandoff: string | null
    fromSuggestion: boolean
    instruction: string
    requestedSpaceId: string | null
    selectedSpace: CanvasSpace | null
    selectedSpaceId: string | null
    sendDisabledReason: string | null
    sending: boolean
    spaces: CanvasSpace[] | null
    spacesLoading: boolean
    spacesUnavailable: boolean
    startBlankDisabledReason: string | null
    startHandoff: CanvasStartHandoff | null
    startingBlank: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasNewLogicActions {
    clearEditHandoff: () => {
        value: true
    }
    clearStartHandoff: () => {
        value: true
    }
    handOffEdit: (canvasId: string) => {
        canvasId: string
    }
    handOffStart: (handoff: CanvasStartHandoff) => {
        handoff: CanvasStartHandoff
    }
    loadSpaces: () => any
    loadSpacesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSpacesSuccess: (
        spaces: CanvasSpace[],
        payload?: any
    ) => {
        spaces: CanvasSpace[]
        payload?: any
    }
    send: () => {
        value: true
    }
    sendFinished: () => {
        value: true
    }
    sendStarted: () => {
        value: true
    }
    sent: () => {
        value: true
    }
    setInstruction: (
        instruction: string,
        fromSuggestion: boolean
    ) => {
        fromSuggestion: boolean
        instruction: string
    }
    setRequestedSpaceId: (spaceId: string | null) => {
        spaceId: string | null
    }
    setSelectedSpaceId: (spaceId: string) => {
        spaceId: string
    }
    startBlank: () => {
        value: true
    }
    startBlankFinished: () => {
        value: true
    }
    startBlankStarted: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasNewLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        selectedSpaceId: (
            spaces: CanvasSpace[] | null,
            chosenSpaceId: string | null,
            requestedSpaceId: string | null
        ) => string | null
        selectedSpace: (spaces: CanvasSpace[] | null, selectedSpaceId: string | null) => CanvasSpace | null
        startBlankDisabledReason: (
            spaces: CanvasSpace[] | null,
            spacesUnavailable: boolean,
            selectedSpaceId: string | null
        ) => string | null
        sendDisabledReason: (startBlankDisabledReason: string | null, instruction: string) => string | null
    }
}

export type canvasNewLogicType = MakeLogicType<
    canvasNewLogicValues,
    canvasNewLogicActions,
    Record<string, any>,
    canvasNewLogicMeta
>

/**
 * The new canvas start page: a prompt and a space. Sending creates the canvas, starts the
 * agent that builds it, and replaces the page with the canvas, so Back skips the empty start page.
 * Start blank creates the canvas from blocks instead and opens it in edit mode.
 */
export const canvasNewLogic = kea<canvasNewLogicType>([
    path(['products', 'canvas', 'frontend', 'newCanvas', 'canvasNewLogic']),
    connect(() => ({
        values: [projectLogic, ['currentProjectId']],
    })),
    actions({
        setInstruction: (instruction: string, fromSuggestion: boolean) => ({ instruction, fromSuggestion }),
        setRequestedSpaceId: (spaceId: string | null) => ({ spaceId }),
        setSelectedSpaceId: (spaceId: string) => ({ spaceId }),
        send: true,
        sendStarted: true,
        sendFinished: true,
        sent: true,
        handOffStart: (handoff: CanvasStartHandoff) => ({ handoff }),
        clearStartHandoff: true,
        startBlank: true,
        startBlankStarted: true,
        startBlankFinished: true,
        /** A blank canvas to open in edit mode. The canvas page picks it up. */
        handOffEdit: (canvasId: string) => ({ canvasId }),
        clearEditHandoff: true,
    }),
    loaders(({ values }) => ({
        spaces: [
            null as CanvasSpace[] | null,
            {
                loadSpaces: async () =>
                    values.currentProjectId ? await loadCanvasSpaces(String(values.currentProjectId)) : [],
            },
        ],
    })),
    reducers({
        instruction: [
            '',
            {
                setInstruction: (_, { instruction }) => instruction,
                sent: () => '',
                handOffStart: () => '',
            },
        ],
        fromSuggestion: [
            false,
            {
                setInstruction: (_, { fromSuggestion }) => fromSuggestion,
                sent: () => false,
                handOffStart: () => false,
            },
        ],
        requestedSpaceId: [
            null as string | null,
            {
                setRequestedSpaceId: (_, { spaceId }) => spaceId,
            },
        ],
        chosenSpaceId: [
            null as string | null,
            {
                setRequestedSpaceId: () => null,
                setSelectedSpaceId: (_, { spaceId }) => spaceId,
            },
        ],
        sending: [
            false,
            {
                sendStarted: () => true,
                sendFinished: () => false,
            },
        ],
        startingBlank: [
            false,
            {
                startBlankStarted: () => true,
                startBlankFinished: () => false,
            },
        ],
        editHandoff: [
            null as string | null,
            {
                handOffEdit: (_, { canvasId }) => canvasId,
                clearEditHandoff: () => null,
            },
        ],
        spacesUnavailable: [
            false,
            {
                loadSpaces: () => false,
                loadSpacesFailure: () => true,
            },
        ],
        startHandoff: [
            null as CanvasStartHandoff | null,
            {
                handOffStart: (_, { handoff }) => handoff,
                clearStartHandoff: () => null,
            },
        ],
    }),
    selectors({
        selectedSpaceId: [
            (s) => [s.spaces, s.chosenSpaceId, s.requestedSpaceId],
            (spaces: CanvasSpace[] | null, chosen: string | null, requested: string | null): string | null =>
                pickCanvasSpaceId(spaces, chosen, requested),
        ],
        selectedSpace: [
            (s) => [s.spaces, s.selectedSpaceId],
            (spaces: CanvasSpace[] | null, selectedSpaceId: string | null): CanvasSpace | null =>
                spaces?.find((space) => space.id === selectedSpaceId) ?? null,
        ],
        startBlankDisabledReason: [
            (s) => [s.spaces, s.spacesUnavailable, s.selectedSpaceId],
            (
                spaces: CanvasSpace[] | null,
                spacesUnavailable: boolean,
                selectedSpaceId: string | null
            ): string | null => {
                if (spacesUnavailable) {
                    return 'Your spaces didn’t load. Try again to pick one.'
                }
                if (!spaces) {
                    return 'Loading your spaces'
                }
                if (!selectedSpaceId) {
                    return 'You don’t have a space to put a canvas in yet'
                }
                return null
            },
        ],
        sendDisabledReason: [
            (s) => [s.startBlankDisabledReason, s.instruction],
            (startBlankDisabledReason: string | null, instruction: string): string | null => {
                if (startBlankDisabledReason) {
                    return startBlankDisabledReason
                }
                if (!instruction.trim()) {
                    return 'Describe the canvas first'
                }
                return null
            },
        ],
        breadcrumbs: [
            () => [],
            (): Breadcrumb[] => [
                { key: 'analytics', name: 'Analytics', path: urls.analyticsList() },
                { key: 'CanvasNew', name: 'New canvas' },
            ],
        ],
    }),
    listeners(({ actions, values }) => {
        const createCanvas = async (
            projectId: string,
            spaceId: string,
            starterId?: string
        ): Promise<CanvasApi | null> => {
            try {
                const canvas = await canvasesCreate(projectId, {
                    channel_id: spaceId,
                    name: UNTITLED_CANVAS_NAME,
                    template_id: FREEFORM_TEMPLATE_ID,
                })
                posthog.capture(CANVAS_EVENTS.dashboardAction, {
                    action_type: 'create',
                    surface: 'web_new_canvas_page',
                    channel_id: spaceId,
                    dashboard_id: canvas.id,
                    template_id: FREEFORM_TEMPLATE_ID,
                    ...(starterId ? { starter_id: starterId } : {}),
                })
                return canvas
            } catch (error) {
                toast.error({
                    title: "Couldn't create the canvas",
                    description: error instanceof Error ? error.message : 'Try again in a moment.',
                })
                return null
            }
        }
        return {
            send: async () => {
                const projectId = values.currentProjectId ? String(values.currentProjectId) : null
                const space = values.selectedSpace
                const instruction = values.instruction.trim()
                const fromSuggestion = values.fromSuggestion
                if (values.sending || values.startingBlank || values.sendDisabledReason || !projectId || !space) {
                    return
                }
                actions.sendStarted()
                const stillOnStartPage = (): boolean =>
                    removeProjectIdIfPresent(router.values.location.pathname) === urls.canvasNew()
                try {
                    const canvas = await createCanvas(projectId, space.id)
                    if (!canvas) {
                        return
                    }
                    try {
                        await startCanvasGeneration({
                            projectId,
                            canvas,
                            spaceName: space.name,
                            instruction,
                            fromSuggestion,
                            surface: 'web_new_canvas_page',
                        })
                        actions.sent()
                    } catch (error) {
                        // The canvas exists, so the person lands on it with the prompt kept, ready to send again.
                        actions.handOffStart({ canvasId: canvas.id, instruction, fromSuggestion })
                        toast.error({
                            title: "Couldn't start building the canvas",
                            description: error instanceof Error ? error.message : 'Try again in a moment.',
                        })
                    }
                    if (stillOnStartPage()) {
                        router.actions.replace(withBackLink(urls.canvasDetail(canvas.id)))
                    }
                } finally {
                    actions.sendFinished()
                }
            },
            startBlank: async () => {
                const projectId = values.currentProjectId ? String(values.currentProjectId) : null
                const space = values.selectedSpace
                if (values.sending || values.startingBlank || values.startBlankDisabledReason || !projectId || !space) {
                    return
                }
                actions.startBlankStarted()
                try {
                    const canvas = await createCanvas(projectId, space.id, BLANK_STARTER_ID)
                    if (!canvas) {
                        return
                    }
                    try {
                        // The new canvas's source carries the platform's pinned dependencies, so only the files change.
                        const source = await canvasesSourceRetrieve(projectId, canvas.id)
                        const files = blankCanvasFiles()
                        await canvasesPublishCreate(projectId, canvas.id, {
                            project: {
                                ...source.project,
                                files,
                                capabilities: canvasCapabilities(source.project.capabilities, files) as
                                    | CanvasCapabilitiesApi
                                    | undefined,
                            },
                            prompt: 'Started a blank canvas',
                            expected_current_version_id: source.current_version_id,
                        })
                        actions.handOffEdit(canvas.id)
                    } catch {
                        // The canvas exists, so the person lands on it and can describe it to the agent instead.
                        toast.error({
                            title: "The canvas was created, but its blank layout didn't save",
                            description: 'Describe the canvas to have the agent build it.',
                        })
                    }
                    if (removeProjectIdIfPresent(router.values.location.pathname) === urls.canvasNew()) {
                        router.actions.replace(withBackLink(urls.canvasDetail(canvas.id)))
                    }
                } finally {
                    actions.startBlankFinished()
                }
            },
        }
    }),
    urlToAction(({ actions, values }) => ({
        [urls.canvasNew()]: (_, searchParams) => {
            if (values.sending || values.startingBlank) {
                return
            }
            actions.setRequestedSpaceId(typeof searchParams.space === 'string' ? searchParams.space : null)
            actions.loadSpaces()
        },
    })),
])