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.

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

import api from 'lib/api'
import { JSONContent } from 'lib/components/RichContentEditor/types'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { addProductIntent } from 'lib/utils/product-intents'
import { retryImport } from 'lib/utils/retryImport'
import { withBackLink } from 'scenes/analytics/analyticsBackLink'
import type { notebookLogicType } from 'scenes/notebooks/Notebook/notebookLogic'
import { notebookPanelLogic } from 'scenes/notebooks/NotebookPanel/notebookPanelLogic'
import { LOCAL_NOTEBOOK_TEMPLATES } from 'scenes/notebooks/NotebookTemplates/notebookTemplates'
import { NotebookListItemType, NotebookNodeType, NotebookTarget } from 'scenes/notebooks/types'
import { defaultNotebookContent } from 'scenes/notebooks/utils'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'

import { deleteFromTree, getLastNewFolder, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { InsightVizNode, Node, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { DashboardType } from '~/types'

import type { NotebookType } from '../scenes/notebooks/types'

// Queue for operations that arrive before the Notebook component mounts its
// kea logic. `openNotebook` pushes here; `notebookLogic.afterMount` drains.
const pendingNotebookOperations = new Map<string, ((logic: BuiltLogic<notebookLogicType>) => void)[]>()

export function drainPendingNotebookOperations(shortId: string, logic: BuiltLogic<notebookLogicType>): void {
    const ops = pendingNotebookOperations.get(shortId)
    if (!ops?.length) {
        return
    }
    pendingNotebookOperations.delete(shortId)
    for (const op of ops) {
        op(logic)
    }
}

export const SCRATCHPAD_NOTEBOOK: NotebookListItemType = {
    id: 'scratchpad',
    short_id: 'scratchpad',
    title: 'My scratchpad',
    created_at: '',
    created_by: null,
}

export const openNotebook = async (
    notebookId: string,
    target: NotebookTarget,
    onOpen?: (logic: BuiltLogic<notebookLogicType>) => void
): Promise<void> => {
    const thePanelLogic = notebookPanelLogic.findMounted()

    if (thePanelLogic && target === NotebookTarget.Popover) {
        thePanelLogic.actions.selectNotebook(notebookId)
    } else {
        if (router.values.location.pathname === urls.notebook('new')) {
            router.actions.replace(withBackLink(urls.notebook(notebookId)))
        } else {
            router.actions.push(withBackLink(urls.notebook(notebookId)))
        }
    }

    if (onOpen) {
        // Queued before the import, so a failed import still leaves the callback for the logic to drain on mount.
        const ops = pendingNotebookOperations.get(notebookId) || []
        ops.push(onOpen)
        pendingNotebookOperations.set(notebookId, ops)
        // A dynamic import keeps the notebook editor and its rich text stack out of every scene that can open a notebook.
        const { notebookLogic } = await retryImport(() => import('scenes/notebooks/Notebook/notebookLogic'))
        const mountedLogic = notebookLogic.findMounted({ shortId: notebookId })
        if (mountedLogic) {
            drainPendingNotebookOperations(notebookId, mountedLogic)
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebooksModelValues {
    currentProjectId: number | null // projectLogic
    notebookTemplates: NotebookType[]
    notebookTemplatesLoading: boolean
    notebooks: NotebookListItemType[]
    notebooksLoading: boolean
    scratchpadNotebook: NotebookListItemType
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebooksModelActions {
    createNotebook: (
        location: NotebookTarget,
        title?: string,
        content?: JSONContent[],
        onCreate?: (notebook: BuiltLogic<notebookLogicType>) => void,
        shortId?: string
    ) => {
        content: JSONContent[] | undefined
        location: NotebookTarget
        onCreate: ((notebook: BuiltLogic<notebookLogicType>) => void) | undefined
        shortId: string | undefined
        title: string | undefined
    }
    createNotebookFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createNotebookFromDashboard: (dashboard: DashboardType) => {
        dashboard: DashboardType
    }
    createNotebookSuccess: (
        notebooks: NotebookListItemType[],
        payload?: {
            content: JSONContent[] | undefined
            location: NotebookTarget
            onCreate: ((notebook: BuiltLogic<notebookLogicType>) => void) | undefined
            shortId: string | undefined
            title: string | undefined
        }
    ) => {
        notebooks: NotebookListItemType[]
        payload?: {
            content: JSONContent[] | undefined
            location: NotebookTarget
            onCreate: ((notebook: BuiltLogic<notebookLogicType>) => void) | undefined
            shortId: string | undefined
            title: string | undefined
        }
    }
    deleteNotebook: (
        shortId: NotebookListItemType['short_id'],
        title?: string
    ) => {
        shortId: string
        title: string | undefined
    }
    deleteNotebookFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteNotebookSuccess: (
        notebooks: NotebookListItemType[],
        payload?: {
            shortId: string
            title: string | undefined
        }
    ) => {
        notebooks: NotebookListItemType[]
        payload?: {
            shortId: string
            title: string | undefined
        }
    }
    loadNotebooks: () => {
        value: true
    }
    receiveNotebookUpdate: (notebook: NotebookListItemType) => {
        notebook: NotebookListItemType
    }
    receiveNotebookUpdateFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    receiveNotebookUpdateSuccess: (
        notebooks: NotebookListItemType[],
        payload?: {
            notebook: NotebookListItemType
        }
    ) => {
        notebooks: NotebookListItemType[]
        payload?: {
            notebook: NotebookListItemType
        }
    }
}

export type notebooksModelType = MakeLogicType<notebooksModelValues, notebooksModelActions>

export const notebooksModel = kea<notebooksModelType>([
    path(['scenes', 'notebooks', 'Notebook', 'notebooksModel']),
    actions({
        createNotebook: (
            location: NotebookTarget,
            title?: string,
            content?: JSONContent[],
            onCreate?: (notebook: BuiltLogic<notebookLogicType>) => void,
            shortId?: string
        ) => ({
            title,
            location,
            content,
            onCreate,
            shortId,
        }),
        receiveNotebookUpdate: (notebook: NotebookListItemType) => ({ notebook }),
        loadNotebooks: true,
        deleteNotebook: (shortId: NotebookListItemType['short_id'], title?: string) => ({ shortId, title }),
        createNotebookFromDashboard: (dashboard: DashboardType) => ({ dashboard }),
    }),
    connect(() => ({
        values: [projectLogic, ['currentProjectId']],
    })),

    reducers({
        scratchpadNotebook: [SCRATCHPAD_NOTEBOOK],
    }),

    loaders(({ values }) => ({
        notebooks: [
            [] as NotebookListItemType[],
            {
                createNotebook: async ({ title, location, content, onCreate, shortId }) => {
                    const notebook = await api.notebooks.create({
                        title,
                        content: defaultNotebookContent(title, content),
                        _create_in_folder: getLastNewFolder(),
                        ...(shortId ? { short_id: shortId } : {}),
                    })

                    await openNotebook(notebook.short_id, location, (logic) => {
                        onCreate?.(logic)
                    })

                    // Client-scoped name on purpose: the server-side `notebook created` event
                    // (emitted for every creation path) is the source of truth for counts. This
                    // one keeps the browser/session context for UI-funnel analysis without
                    // double-counting UI creations.
                    posthog.capture(`notebook created (client)`, {
                        short_id: notebook.short_id,
                        is_markdown: true,
                    })

                    void addProductIntent({
                        product_type: ProductKey.NOTEBOOKS,
                        intent_context: ProductIntentContext.NOTEBOOK_CREATED,
                    })

                    return [notebook, ...values.notebooks]
                },

                deleteNotebook: async ({ shortId, title }) => {
                    await deleteWithUndo({
                        endpoint: `projects/${values.currentProjectId}/notebooks`,
                        object: { name: title || shortId, id: shortId },
                        callback: (undo) => {
                            if (undo) {
                                refreshTreeItem('notebook', shortId)
                            } else {
                                deleteFromTree('notebook', shortId)
                            }
                        },
                    })

                    const panelLogic = notebookPanelLogic.findMounted()

                    if (panelLogic && panelLogic.values.selectedNotebook === shortId) {
                        panelLogic.actions.selectNotebook(SCRATCHPAD_NOTEBOOK.short_id, { silent: true })
                    }

                    return values.notebooks.filter((n) => n.short_id !== shortId)
                },

                receiveNotebookUpdate: ({ notebook }) => {
                    if (notebook.is_template) {
                        return values.notebooks
                    }
                    return values.notebooks.filter((n) => n.short_id !== notebook.short_id).concat([notebook])
                },
            },
        ],
        notebookTemplates: [
            LOCAL_NOTEBOOK_TEMPLATES,
            {
                // In the future we can load these from remote
            },
        ],
    })),

    listeners(({ asyncActions }) => ({
        createNotebookFromDashboard: async ({ dashboard }) => {
            // TODO(widgets): Dashboard widget tiles are intentionally skipped: notebook query nodes only support
            // insight-backed HogQL queries today, not run_widgets widget types/config.
            const queries = dashboard.tiles.reduce(
                (acc, tile) => {
                    if (!tile.insight) {
                        return acc
                    }
                    acc.push({
                        title: tile.insight.name,
                        query: tile.insight.query,
                    })
                    return acc
                },
                [] as { title: string; query: InsightVizNode | Node | null }[]
            )

            const resources = queries.map((x) => ({
                type: NotebookNodeType.Query,
                attrs: {
                    title: x.title,
                    query: x.query,
                },
            }))

            await asyncActions.createNotebook(NotebookTarget.Scene, dashboard.name + ' (copied)', resources)
        },
    })),
])