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.

10.5 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    beforeUnmount,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'

import { projectLogic } from 'scenes/projectLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import type { TeamPublicType, TeamType, UserType } from '../../../../frontend/src/types'
import { CANVAS_EVENTS, canvasErrorType } from '../canvasAnalytics'
import { canvasesReportErrorCreate } from '../generated/api'
import { CanvasActionConfirmation, CanvasConnectorPermissionRequest, CanvasDataBridge } from './canvasDataBridge'
import { CanvasNavIntent, isSafeGitHubPullRequestUrl } from './canvasProtocol'

export interface CanvasHostLogicProps {
    canvasId: string
    /** The canvas's space. Supplied by the host, never by the iframe. */
    spaceId: string | null
    /** The source version the running code came from. */
    sourceVersionId: string | null
}

export type CanvasHostPrompt =
    | { kind: 'connector'; id: string; request: CanvasConnectorPermissionRequest }
    | { kind: 'agent-request'; id: string; prompt: string }
    | { kind: 'action'; id: string; request: CanvasActionConfirmation }
    | { kind: 'external-link'; id: string; url: string }

type CanvasHostPromptInput = CanvasHostPrompt extends infer P
    ? P extends CanvasHostPrompt
        ? Omit<P, 'id'>
        : never
    : never

let promptSequence = 0

export function canvasHasUserActivation(): boolean {
    return navigator.userActivation?.isActive === true
}

function openInNewTab(url: string): void {
    window.open(url, '_blank', 'noopener,noreferrer')
}

/** Where a viewer connects a connector provider in the web app. */
export function connectorSettingsUrl(provider: string): string {
    return provider === 'github' ? urls.settings('user-personal-integrations') : urls.settings('mcp-servers')
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasHostLogicValues {
    currentProjectId: number | null // projectLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    user: UserType | null // userLogic
    activePrompt: CanvasHostPrompt | null
    prompts: CanvasHostPrompt[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasHostLogicActions {
    canvasErrored: (
        message: string,
        buildId: string | null
    ) => {
        buildId: string | null
        message: string
    }
    canvasRendered: (buildId: string | null) => {
        buildId: string | null
    }
    enqueuePrompt: (prompt: CanvasHostPrompt) => {
        prompt: CanvasHostPrompt
    }
    navigate: (intent: CanvasNavIntent) => {
        intent:
            | {
                  target: 'new-canvas'
              }
            | {
                  target: 'new-task'
              }
            | {
                  dashboardId: string
                  target: 'canvas'
              }
            | {
                  provider: string
                  target: 'connect'
              }
            | {
                  target: 'task'
                  taskId: string
              }
            | {
                  prompt?: string | undefined
                  repository?: string | undefined
                  target: 'compose-task'
              }
    }
    openExternal: (url: string) => {
        url: string
    }
    respondToPrompt: (
        id: string,
        allowed: boolean
    ) => {
        allowed: boolean
        id: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasHostLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        activePrompt: (prompts: CanvasHostPrompt[]) => CanvasHostPrompt | null
    }
}

export type canvasHostLogicType = MakeLogicType<
    canvasHostLogicValues,
    canvasHostLogicActions,
    CanvasHostLogicProps,
    canvasHostLogicMeta
>

/**
 * The trusted host around one rendered canvas: it answers the canvas's data requests,
 * asks the viewer before anything that writes, starts work, or leaves the app, and maps
 * the canvas's allowlisted navigation intents to web routes.
 */
export const canvasHostLogic = kea<canvasHostLogicType>([
    props({} as CanvasHostLogicProps),
    key((props) => props.canvasId),
    path((key) => ['products', 'canvas', 'frontend', 'host', 'canvasHostLogic', key]),
    connect(() => ({
        values: [projectLogic, ['currentProjectId'], teamLogic, ['currentTeam'], userLogic, ['user']],
    })),
    actions({
        enqueuePrompt: (prompt: CanvasHostPrompt) => ({ prompt }),
        respondToPrompt: (id: string, allowed: boolean) => ({ id, allowed }),
        navigate: (intent: CanvasNavIntent) => ({ intent }),
        openExternal: (url: string) => ({ url }),
        canvasRendered: (buildId: string | null) => ({ buildId }),
        canvasErrored: (message: string, buildId: string | null) => ({ message, buildId }),
    }),
    reducers({
        prompts: [
            [] as CanvasHostPrompt[],
            {
                enqueuePrompt: (state, { prompt }) => [...state, prompt],
                respondToPrompt: (state, { id }) => state.filter((prompt) => prompt.id !== id),
            },
        ],
    }),
    selectors({
        activePrompt: [
            (s) => [s.prompts],
            (prompts: CanvasHostPrompt[]): CanvasHostPrompt | null => prompts[0] ?? null,
        ],
    }),
    listeners(({ props, values, cache }) => ({
        respondToPrompt: ({ id, allowed }) => {
            const resolve = (cache.resolvers as Map<string, (allowed: boolean) => void>).get(id)
            cache.resolvers.delete(id)
            resolve?.(allowed)
        },
        openExternal: ({ url }) => {
            // Only a validated GitHub pull request link skips the confirmation.
            if (isSafeGitHubPullRequestUrl(url)) {
                openInNewTab(url)
                return
            }
            void (cache.requestPrompt({ kind: 'external-link', url }) as Promise<boolean>).then((allowed) => {
                if (allowed) {
                    openInNewTab(url)
                }
            })
        },
        navigate: ({ intent }) => {
            switch (intent.target) {
                case 'task':
                    router.actions.push(urls.taskDetail(intent.taskId))
                    break
                case 'canvas':
                    router.actions.push(urls.canvasDetail(intent.dashboardId))
                    break
                case 'new-canvas':
                    router.actions.push(urls.canvasNew(props.spaceId))
                    break
                case 'connect':
                    router.actions.push(connectorSettingsUrl(intent.provider))
                    break
                default:
                    // The web app has no task composer route to prefill, so these are dropped.
                    break
            }
        },
        canvasRendered: ({ buildId }) => {
            posthog.capture(CANVAS_EVENTS.rendered, {
                channel_id: props.spaceId ?? undefined,
                dashboard_id: props.canvasId,
                build_id: buildId ?? undefined,
            })
        },
        canvasErrored: ({ message, buildId }) => {
            // A canvas can throw the same error on every render, so each error is reported once per build.
            const errorKey = `${buildId ?? 'draft'}:${message}`
            if (errorKey === cache.lastRuntimeError) {
                return
            }
            cache.lastRuntimeError = errorKey
            const errorType = canvasErrorType(message)
            posthog.capture(CANVAS_EVENTS.runtimeError, {
                channel_id: props.spaceId ?? undefined,
                dashboard_id: props.canvasId,
                build_id: buildId ?? undefined,
                error_type: errorType,
            })
            // Files the error in the authoring task's thread so its agent hears about it. Only the
            // class name leaves the browser: the message can carry the viewer's data.
            if (buildId && values.currentProjectId) {
                void canvasesReportErrorCreate(String(values.currentProjectId), props.canvasId, {
                    build_id: buildId,
                    error_type: errorType,
                }).catch(() => {
                    // Reporting is best effort. The header still shows the error and a way to ask for a fix.
                })
            }
        },
    })),
    afterMount((logic) => {
        const { actions, values, cache } = logic
        cache.resolvers = new Map<string, (allowed: boolean) => void>()
        cache.requestPrompt = (input: CanvasHostPromptInput): Promise<boolean> =>
            new Promise((resolve) => {
                const id = `canvas-prompt-${++promptSequence}`
                cache.resolvers.set(id, resolve)
                actions.enqueuePrompt({ ...input, id } as CanvasHostPrompt)
            })
        cache.bridge = new CanvasDataBridge(
            () => ({
                projectId: String(values.currentProjectId ?? ''),
                // Read through the logic so a new source version is picked up without a remount.
                canvasId: logic.props.canvasId,
                sourceVersionId: logic.props.sourceVersionId,
                captureToken: values.currentTeam?.api_token ?? null,
                distinctId: values.user?.distinct_id ?? null,
            }),
            {
                confirmAction: (request) => cache.requestPrompt({ kind: 'action', request }),
                confirmAgentRequest: (prompt) => cache.requestPrompt({ kind: 'agent-request', prompt }),
                requestConnectorPermission: (request) => cache.requestPrompt({ kind: 'connector', request }),
                hasUserActivation: canvasHasUserActivation,
            }
        )
    }),
    beforeUnmount(({ cache }) => {
        // A canvas waiting on the viewer gets a denial rather than a promise that never settles.
        for (const resolve of (cache.resolvers as Map<string, (allowed: boolean) => void>).values()) {
            resolve(false)
        }
        cache.resolvers.clear()
    }),
])

/** Resolves a data request through the host's bridge. The logic must be mounted. */
export function handleCanvasDataRequest(
    logic: ReturnType<typeof canvasHostLogic>,
    method: string,
    payload: unknown
): Promise<unknown> {
    return (logic.cache.bridge as CanvasDataBridge).handle(method, payload)
}