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.6 KB
Raw Blame
import { useActions, useMountedLogic, useValues } from 'kea'
import { useCallback } from 'react'

import { IconPlayFilled } from '@posthog/icons'

import { usePublishNotebookComponentRunHandler } from 'lib/components/MarkdownNotebook/componentRunHandlers'
import type { NotebookComponentToolbarProps } from 'lib/components/MarkdownNotebook/types'
import { getSerializableProps } from 'lib/components/MarkdownNotebook/utils'
import { IconCancel } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'

import { notebookCodeCellLogic } from 'products/notebooks/frontend/notebookCodeCellLogic'

import { notebookJupyterLogic } from '../../Notebook/notebookJupyterLogic'
import { notebookLogic } from '../../Notebook/notebookLogic'
import type { NotebookNodeSQLV2Result } from '../NotebookNodeSQLV2'
import { type NotebookNodeSQLV2LogicProps, type RunNodeOverrides } from '../notebookNodeSQLV2Logic'
import { getNotebookSqlEditorTabId } from './NotebookSQLEditor'

/**
 * Run/Cancel for a revamped code cell (SQL or Python), rendered in the block's top row.
 *
 * It sits in the shell toolbar rather than in the code editor so that reading a notebook is
 * enough to rerun a cell: in view mode there is no editor on screen, and in edit mode the
 * editor may be collapsed. The shell mounts this outside the panels, so the run state stays
 * live either way.
 */
export function NotebookCodeCellRunButton({ node, updateProps }: NotebookComponentToolbarProps): JSX.Element | null {
    const mountedNotebookLogic = useMountedLogic(notebookLogic)
    const { isShared, canEditNotebook, shortId } = useValues(mountedNotebookLogic)
    // Cells persist their own id; a parsed markdown block id is a content fingerprint that drifts
    // as soon as a run writes runId/result, so it is only the fallback for a never-run cell.
    const nodeId = typeof node.props.nodeId === 'string' && node.props.nodeId ? node.props.nodeId : node.id
    const updateAttributes = useCallback<NotebookNodeSQLV2LogicProps['updateAttributes']>(
        (attributes) => updateProps(getSerializableProps(attributes)),
        [updateProps]
    )

    const dataLogic = notebookCodeCellLogic(
        nodeId,
        mountedNotebookLogic,
        {
            runId: typeof node.props.runId === 'string' ? node.props.runId : null,
            result: node.props.result as NotebookNodeSQLV2Result | undefined,
        },
        updateAttributes
    )
    const {
        isRunning: isRunningNow,
        isQueued,
        isInterrupting,
        operationBlockReason,
        isJupyterModeActive,
        runError,
        result: runResult,
    } = useValues(dataLogic)
    const result = runResult ?? (node.props.result as NotebookNodeSQLV2Result | undefined)
    // A queued cell shows as running, like Jupyter's In [*] for a cell waiting on the kernel.
    const isRunning = isRunningNow || isQueued
    const { runNode, interruptRun } = useActions(dataLogic)
    const { executionCounts } = useValues(notebookJupyterLogic({ shortId }))
    const executionCount = executionCounts[nodeId] ?? null

    // The run endpoint requires editor access on the notebook, so it is offered only to a reader it
    // will answer for. That excludes a public share, a viewer-level reader, and a history preview,
    // all of which render this toolbar in view mode. Without the gate they get a control that
    // returns 403, and a preview would run a version of the code the reader is not editing.
    const canRun = !isShared && canEditNotebook

    const run = useCallback((): void => {
        // A SQL cell's editor holds the code and the connection a keystroke or a just-picked
        // connection before the document does, so prefer it while it is open. A Python cell has no
        // such logic mounted and runs from the document.
        const editorLogic = sqlEditorLogic.findMounted({ tabId: getNotebookSqlEditorTabId(nodeId, 'datav2') })
        const overrides: RunNodeOverrides = editorLogic
            ? {
                  // Pass every string the editor holds, blank included. An editor cleared a render
                  // ahead of the document holds `''`, which has to reach the blank-code check and
                  // be rejected. Dropping it here would fall back to the document and run the
                  // previous query instead. Only `null`, an editor that never took input, defers to
                  // the document.
                  code: editorLogic.values.queryInput ?? undefined,
                  connectionId: editorLogic.values.selectedConnectionId ?? null,
                  sendRawQuery: editorLogic.values.sendRawQueryEnabled,
              }
            : {}
        runNode(overrides)
    }, [nodeId, runNode])

    // A run in flight blocks the shortcuts, because the button turns into Cancel there and a run
    // shortcut must never become a stop.
    const interrupt = useCallback((): void => {
        // Guard against double submission: one interrupt request at a time.
        if ((dataLogic.values.isRunning || dataLogic.values.isQueued) && !dataLogic.values.isInterrupting) {
            interruptRun()
        }
    }, [dataLogic, interruptRun])

    usePublishNotebookComponentRunHandler(
        canRun
            ? {
                  run,
                  // In Jupyter mode a busy notebook queues the run, so only this cell's own run blocks the shortcut.
                  disabledReason: isRunning
                      ? 'This cell is already running'
                      : isJupyterModeActive
                        ? null
                        : (operationBlockReason ?? null),
                  isRunning,
                  isQueued,
                  executionCount,
                  hasError: !!runError || !!result?.stderr,
                  interrupt,
              }
            : null
    )

    if (!canRun) {
        return null
    }

    return (
        <LemonButton
            data-attr="notebook-code-cell-run-button"
            size="xsmall"
            type="primary"
            icon={isRunning ? <IconCancel /> : <IconPlayFilled color="var(--success)" />}
            onClick={() => {
                if (!isRunning) {
                    run()
                } else {
                    interrupt()
                }
            }}
            loading={isInterrupting}
            disabledReason={isJupyterModeActive ? undefined : (operationBlockReason ?? undefined)}
            tooltip={
                isQueued ? 'Remove the cell from the queue' : isRunning ? 'Stop the running cell' : 'Run cell (⌘⏎)'
            }
        >
            {isRunning ? 'Cancel' : 'Run'}
        </LemonButton>
    )
}