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.

7.2 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
import posthog from 'posthog-js'

import { ApiConfig } from 'lib/api'
import type { NotebookJupyterCommand } from 'lib/components/MarkdownNotebook/jupyterMode'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast'

import { notebooksKernelRestartCreate } from 'products/notebooks/frontend/generated/api'

import { kernelActionErrorMessage, notebookKernelInfoLogic } from './notebookKernelInfoLogic'
import { notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'
import { notebookRunLogic } from './notebookRunLogic'

const UNTRACKED_COMMANDS: ReadonlySet<NotebookJupyterCommand> = new Set<NotebookJupyterCommand>([
    'enter-edit-mode',
    'enter-command-mode',
    'select-previous',
    'select-next',
    'extend-selection-up',
    'extend-selection-down',
])

export interface NotebookJupyterLogicProps {
    shortId: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookJupyterLogicValues {
    executionCounter: number
    executionCounts: Record<string, number>
    isActive: boolean
    isRestartingKernel: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookJupyterLogicActions {
    nodeRunFinished: (
        nodeId: string,
        status: import('./notebookNodeStalenessLogic').NotebookNodeRunTerminalStatus,
        content: null | import('lib/components/RichContentEditor/types').JSONContent
    ) => {
        content: null | import('lib/components/RichContentEditor/types').JSONContent
        nodeId: string
        status: import('./notebookNodeStalenessLogic').NotebookNodeRunTerminalStatus
    } // notebookNodeStalenessLogic
    assignExecutionCount: (
        nodeId: string,
        count: number
    ) => {
        count: number
        nodeId: string
    }
    requestKernelRestart: (runAll?: boolean) => {
        runAll: boolean
    }
    resetExecutionCounter: () => {
        value: true
    }
    restartKernel: (runAll: boolean) => {
        runAll: boolean
    }
    setIsActive: (isActive: boolean) => {
        isActive: boolean
    }
    setIsRestartingKernel: (isRestartingKernel: boolean) => {
        isRestartingKernel: boolean
    }
    trackCommand: (command: NotebookJupyterCommand) => {
        command: NotebookJupyterCommand
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookJupyterLogicMeta {
    key: string
}

export type notebookJupyterLogicType = MakeLogicType<
    notebookJupyterLogicValues,
    notebookJupyterLogicActions,
    NotebookJupyterLogicProps,
    notebookJupyterLogicMeta
>

/**
 * Jupyter's execution counter: every finished cell run takes the next number, shown as the cell's
 * `In [n]:` prompt. Like a kernel's counter it starts again at 1 after a restart, and like a saved
 * `.ipynb` the numbers a cell already shows survive a reload.
 *
 * `isActive` says whether this notebook renders in Jupyter mode. The renderer sets it, and the
 * cells read it, so a notebook outside Jupyter mode keeps its own run behavior and counts nothing.
 */
export const notebookJupyterLogic = kea<notebookJupyterLogicType>([
    props({} as NotebookJupyterLogicProps),
    key((props) => props.shortId),
    path((key) => ['scenes', 'notebooks', 'Notebook', 'notebookJupyterLogic', key]),
    connect((props: NotebookJupyterLogicProps) => ({
        actions: [notebookNodeStalenessLogic({ shortId: props.shortId }), ['nodeRunFinished']],
    })),
    actions({
        assignExecutionCount: (nodeId: string, count: number) => ({ nodeId, count }),
        resetExecutionCounter: true,
        requestKernelRestart: (runAll: boolean = false) => ({ runAll }),
        restartKernel: (runAll: boolean) => ({ runAll }),
        setIsRestartingKernel: (isRestartingKernel: boolean) => ({ isRestartingKernel }),
        setIsActive: (isActive: boolean) => ({ isActive }),
        trackCommand: (command: NotebookJupyterCommand) => ({ command }),
    }),
    reducers({
        isActive: [false, { setIsActive: (_, { isActive }) => isActive }],
        executionCounter: [
            0,
            { persist: true },
            {
                assignExecutionCount: (_, { count }) => count,
                resetExecutionCounter: () => 0,
            },
        ],
        executionCounts: [
            {} as Record<string, number>,
            { persist: true },
            {
                assignExecutionCount: (counts, { nodeId, count }) => ({ ...counts, [nodeId]: count }),
            },
        ],
        isRestartingKernel: [
            false,
            {
                restartKernel: () => true,
                setIsRestartingKernel: (_, { isRestartingKernel }) => isRestartingKernel,
            },
        ],
    }),
    listeners(({ actions, values, props }) => ({
        nodeRunFinished: ({ nodeId }) => {
            if (values.isActive) {
                actions.assignExecutionCount(nodeId, values.executionCounter + 1)
            }
        },
        trackCommand: ({ command }) => {
            // Moving between cells and modes happens on most key presses, and says nothing about which features people use.
            if (!UNTRACKED_COMMANDS.has(command)) {
                posthog.capture('notebook jupyter command', { command, notebook_short_id: props.shortId })
            }
        },
        requestKernelRestart: ({ runAll }) => {
            if (values.isRestartingKernel) {
                return
            }
            LemonDialog.open({
                title: runAll ? 'Restart the kernel and run all cells?' : 'Restart the kernel?',
                description: 'All variables in the kernel will be lost.',
                primaryButton: {
                    children: runAll ? 'Restart and run all' : 'Restart',
                    status: 'danger',
                    onClick: () => actions.restartKernel(runAll),
                    'data-attr': runAll ? 'notebook-jupyter-restart-run-all' : 'notebook-jupyter-restart',
                },
                secondaryButton: { children: 'Cancel' },
            })
        },
        restartKernel: async ({ runAll }) => {
            try {
                // Awaited here rather than dispatched to the kernel logic, so "run all" starts only
                // once the fresh kernel is up.
                await notebooksKernelRestartCreate(String(ApiConfig.getCurrentTeamId()), props.shortId)
                posthog.capture('notebook jupyter kernel restarted', {
                    run_all: runAll,
                    notebook_short_id: props.shortId,
                })
                actions.resetExecutionCounter()
                if (runAll) {
                    notebookRunLogic.findMounted({ shortId: props.shortId })?.actions.startRun()
                }
            } catch (error) {
                lemonToast.error(kernelActionErrorMessage(error, 'The kernel could not be restarted. Try again.'))
            } finally {
                actions.setIsRestartingKernel(false)
                notebookKernelInfoLogic.findMounted({ shortId: props.shortId })?.actions.loadKernelInfo()
            }
        },
    })),
])