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.

feat(notebooks): run all cells button (#98160)

Sinan Kucukkoseler1ed126eac810
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index cda18ba8afff..2f80b3b899b5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10810,6 +10810,18 @@ snapshots:
hash: v1.k794b7964.d6c551c581824287879e157abaa61874713bb6389caaa015b1bac305a69c36cb.szC1MJRFAMY6z5Cr9uPHF3D39RLL7VUUFs3FiiemlsA
scenes-app-notebooks-nodes-support-tickets--with-tickets--light:
hash: v1.k794b7964.10a73c98dea8faa9011e00a7f44278e12216eb077e68ffefb4f2799f0ab519ad.yCkGWzRUKGODRvA_V0WHSn9Pdm5FhPyEfJVEcilSpP8
+ scenes-app-notebooks-run-all-banner--last-cell--dark:
+ hash: v1.k794b7964.636c00625c3a849d8b3813e810c2d7aaf62d675049a772ff3d5543c27432ad8b.V2iZz-tdy7XiwDT6-yVJKOW3S3VyaMyoEn5toL5SeUI
+ scenes-app-notebooks-run-all-banner--last-cell--light:
+ hash: v1.k794b7964.ee1b2eeb409eea54cece70d64af1d9e6988782322d9f30ab939fbbc6bde6a0f4.wr8dLlqY1qnabNlrKA7-XWFjnlHDOXAZeHk-X5A9Wuk
+ scenes-app-notebooks-run-all-banner--mid-run--dark:
+ hash: v1.k794b7964.6d79e1f66734705db047688969ad0fc46a690b255a4fbcefcf252cd67b3df915.yQlahVbXql8gxy5LPvhyDgoi5gQES5XVlNCpTHiEXKE
+ scenes-app-notebooks-run-all-banner--mid-run--light:
+ hash: v1.k794b7964.9d674fdf1f7bbb66c7caf1764b1c57c8f4e6081e26981993f7ca49ba458c4185.USIO_PlJeZsQDyIpYt-tTAiSs_XXpUvJUGPQyOQbneg
+ scenes-app-notebooks-run-all-banner--starting--dark:
+ hash: v1.k794b7964.236c0485a9150c930638669fc0e9e894f5957a2ac2745f29b73ed558ffcd1cdc.yeGKlhnvYq8b01QMsu190pnW-nQwU4cGKsf7aH0Ck8k
+ scenes-app-notebooks-run-all-banner--starting--light:
+ hash: v1.k794b7964.6c7bd37efe1d58d68070782d7d1d0ce20be5abfebe1f829feb0376b584ad1158.CVBhfDqMZqLLuxmDgkiTAS9Vn2SANiX9cOWDF1Ui8hk
scenes-app-notebooks-widget-generation-cost--less-than-one-cent--dark:
hash: v1.k794b7964.3d7ab4ed80e86dee207323ed0baf83d86a9c0b53c868f64769ddc708b4ab5881.RKwiZJnBL8K4kWfRM3MV6Aruoqr20twxVmepMy_SU6Y
scenes-app-notebooks-widget-generation-cost--less-than-one-cent--light:
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
index 30ea9eae86e1..35cec79c3df8 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
@@ -7,6 +7,7 @@ import { NotebookNodeType } from '../types'
import {
buildNotebookDependencyGraph,
collectNotebookFrameNodes,
+ collectRunnableCellNodeIds,
extractPythonIdentifiers,
} from './notebookNodeContent'
@@ -245,3 +246,27 @@ describe('buildNotebookDependencyGraph', () => {
expect(graphB.nodesById['b'].exports).toEqual(['df_b'])
})
})
+
+describe('collectRunnableCellNodeIds', () => {
+ // Run all used to key off the SQL summaries, so a notebook of Python cells alone never
+ // got the button — though the backend plan runs exactly these two kinds.
+ it.each([
+ ['python only', [{ tag: 'PythonV2', nodeId: 'p1', code: 'print(1)' }], ['p1']],
+ ['sql only', [{ tag: 'SQLV2', nodeId: 's1', code: 'select 1' }], ['s1']],
+ [
+ 'both, in document order',
+ [
+ { tag: 'SQLV2', nodeId: 's1', code: 'select 1' },
+ { tag: 'PythonV2', nodeId: 'p1', code: 'print(1)' },
+ ],
+ ['s1', 'p1'],
+ ],
+ ['an empty cell is not runnable', [{ tag: 'PythonV2', nodeId: 'p1', code: ' ' }], []],
+ ])('%s', (_name, cells, expected) => {
+ const markdown = cells
+ .map(({ tag, nodeId, code }) => serializeMarkdownNotebookComponent(tag, { nodeId, code }))
+ .join('\n\n')
+
+ expect(collectRunnableCellNodeIds(buildMarkdownNotebookContent(markdown))).toEqual(expected)
+ })
+})
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
index 53625415ea63..702d721ab3a6 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
@@ -369,6 +369,20 @@ export const collectSqlV2Nodes = (content?: JSONContent | null): SqlV2NodeSummar
}
})
+/** Node ids of every cell a whole-notebook run would execute, in document order.
+ *
+ * Wider than `collectSqlV2Nodes`, which only reports cells that export a dataframe: the
+ * backend plan runs every SQL and Python cell that has code, so a notebook of Python cells
+ * alone is perfectly runnable and used to be denied the Run all button. */
+export const collectRunnableCellNodeIds = (content?: JSONContent | null): string[] =>
+ collectNotebookDataframeNodes(content)
+ .filter(
+ ({ node }) =>
+ (node.type === NotebookNodeType.SQLV2 || node.type === NotebookNodeType.PythonV2) &&
+ !!String(node.attrs?.code ?? '').trim()
+ )
+ .map(({ nodeId }) => nodeId)
+
export type NotebookFrameNodeSummary = {
nodeId: string
name: string
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
index 3cdb34f3acd5..182cef02f6ca 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
@@ -629,4 +629,34 @@ describe('notebookNodeSQLV2Logic', () => {
await expectLogic(other).toFinishAllListeners()
expect(runSpy).toHaveBeenCalledTimes(2)
})
+ it('adopts a run the backend started for this cell and polls it', async () => {
+ mount()
+ logic.actions.adoptChainRun('n1', 'chain-run')
+ await expectLogic(logic).toDispatchActions(['startPolling', 'pollResult'])
+
+ // Pinning nodeId keeps the cell's identity: markdown cell ids are content
+ // fingerprints, so a later prop change would otherwise orphan this run.
+ expect(updateAttributes).toHaveBeenCalledWith({
+ nodeId: 'n1',
+ runId: 'chain-run',
+ result: null,
+ runStatus: null,
+ })
+ expect(resultSpy).toHaveBeenCalledWith('nb1', 'chain-run')
+ expect(runSpy).not.toHaveBeenCalled()
+ })
+
+ it('ignores an adopt meant for another cell, and re-adopting its own run', async () => {
+ mount()
+ logic.actions.adoptChainRun('n2', 'other-run')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(updateAttributes).not.toHaveBeenCalled()
+
+ logic.actions.adoptChainRun('n1', 'chain-run')
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.adoptChainRun('n1', 'chain-run')
+ await expectLogic(logic).toFinishAllListeners()
+ // A second adopt of the same run would reset the cell and restart its poller.
+ expect(updateAttributes).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
index 06cabd82609b..49a7ddb4cfbf 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
@@ -192,6 +192,13 @@ export interface notebookNodeSQLV2LogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookNodeSQLV2LogicActions {
+ adoptChainRun: (
+ nodeId: string,
+ runId: string
+ ) => {
+ nodeId: string
+ runId: string
+ } // notebookNodeStalenessLogic
dispatchChainRun: (nodeId: string) => {
nodeId: string
} // notebookNodeStalenessLogic
@@ -334,7 +341,14 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
notebookOperationsLogic({ shortId: props.notebookShortId }),
['startOperation', 'finishOperation', 'finishNodeOperations'],
notebookNodeStalenessLogic({ shortId: props.notebookShortId }),
- ['nodeRunFinished', 'dispatchChainRun', 'runStaleChain', 'registerChainNode', 'unregisterChainNode'],
+ [
+ 'nodeRunFinished',
+ 'dispatchChainRun',
+ 'adoptChainRun',
+ 'runStaleChain',
+ 'registerChainNode',
+ 'unregisterChainNode',
+ ],
notebookSettingsLogic,
['setShowKernelInfo'],
],
@@ -700,6 +714,19 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
actions.runNode()
}
},
+ // A run the backend started for this cell as part of a whole-notebook run. The cell
+ // did not dispatch it, so it pins the run id into the document and picks up the
+ // existing poll path, which writes the result and reports the outcome as usual.
+ // A cell that is not mounted adopts nothing; its runId reaches the document on the
+ // next poll that still sees the run, and afterMount recovers it from there.
+ adoptChainRun: ({ nodeId, runId }) => {
+ if (nodeId !== props.nodeId || cache.activeRunId === runId) {
+ return
+ }
+ cache.activeRunId = runId
+ props.updateAttributes({ nodeId: props.nodeId, runId, result: null, runStatus: null })
+ actions.startPolling(runId)
+ },
startPolling: ({ runId, restoring }) => {
cache.isRestoringResult = restoring
// Idempotent re-register: also covers a remount resuming a persisted in-flight run.
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookRunAllBanner.stories.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookRunAllBanner.stories.tsx
new file mode 100644
index 000000000000..79191ed371b7
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookRunAllBanner.stories.tsx
@@ -0,0 +1,74 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { NotebookRunAllBanner } from './NotebookRunAllBanner'
+import { notebookRunLogic } from './notebookRunLogic'
+
+const SHORT_ID = 'runall01'
+
+const runStatus = (currentIndex: number, cellCount: number): any => ({
+ run_id: 'nbrun-1',
+ status: 'running',
+ trigger: 'ui',
+ variables: [],
+ cell_count: cellCount,
+ current_index: currentIndex,
+ current_node_id: 'n1',
+ failed_node_id: null,
+ error: null,
+ cells: [],
+ created_at: '2026-01-01T00:00:00Z',
+ finished_at: null,
+})
+
+/** Seeds the logic the banner reads, so each story shows one state without a live run.
+ *
+ * Both actions are plain reducer writes. `startRun` would be the truer trigger, but it posts
+ * to the run endpoint, and the failure that follows in a story clears the state again.
+ */
+const withRun = (run: any | null) => {
+ return function Decorator(Story: () => JSX.Element): JSX.Element {
+ const logic = notebookRunLogic({ shortId: SHORT_ID })
+ logic.mount()
+ if (run) {
+ logic.actions.setRun(run)
+ } else {
+ logic.actions.setStarting(true)
+ }
+ return <Story />
+ }
+}
+
+const meta: Meta<typeof NotebookRunAllBanner> = {
+ title: 'Scenes-App/Notebooks/Run all banner',
+ component: NotebookRunAllBanner,
+ args: { shortId: SHORT_ID },
+ // The banner sits above the document, which is narrow when a side panel is open.
+ decorators: [
+ (Story) => (
+ <div className="w-[32rem]">
+ <Story />
+ </div>
+ ),
+ ],
+ parameters: {
+ layout: 'padded',
+ // The banner only exists while a run is in flight, so its spinner never stops. Without
+ // this the snapshot runner waits for every loader to disappear and times out.
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof NotebookRunAllBanner>
+
+export const Starting: Story = {
+ decorators: [withRun(null)],
+}
+
+export const MidRun: Story = {
+ decorators: [withRun(runStatus(2, 8))],
+}
+
+export const LastCell: Story = {
+ decorators: [withRun(runStatus(7, 8))],
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookRunAllBanner.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookRunAllBanner.tsx
new file mode 100644
index 000000000000..abb4ac1e47d2
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookRunAllBanner.tsx
@@ -0,0 +1,36 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+
+import { notebookRunLogic } from './notebookRunLogic'
+
+/**
+ * Progress for a whole-notebook run, above the document. Styled like the downstream-run banner
+ * on a cell, because it is the same kind of nudge rather than an error state.
+ */
+export const NotebookRunAllBanner = ({ shortId }: { shortId: string }): JSX.Element | null => {
+ const { isRunning, isInterrupting, progressLabel } = useValues(notebookRunLogic({ shortId }))
+ const { interruptRun } = useActions(notebookRunLogic({ shortId }))
+
+ if (!isRunning) {
+ return null
+ }
+
+ return (
+ <div className="mx-2 mt-1 flex flex-wrap items-center gap-2 rounded border border-accent bg-accent-highlight-secondary p-2 text-xs">
+ <Spinner textColored />
+ <span>{progressLabel ?? 'Starting the run'}</span>
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ onClick={() => interruptRun()}
+ loading={isInterrupting}
+ disabledReason={isInterrupting ? 'Stopping the run' : undefined}
+ data-attr="notebook-run-all-banner-stop"
+ >
+ Stop
+ </LemonButton>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookRunAllButton.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookRunAllButton.tsx
new file mode 100644
index 000000000000..df581f8425ee
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookRunAllButton.tsx
@@ -0,0 +1,63 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPlay, IconStopFilled } from '@posthog/icons'
+import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'
+
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { isKernelUiEnabled } from '../utils'
+import { isMarkdownNotebookContent } from './markdownNotebookV2'
+import { notebookLogic } from './notebookLogic'
+import { notebookRunLogic } from './notebookRunLogic'
+
+/**
+ * Runs every SQL and Python cell of the open notebook, in document order. While a run is
+ * active the same button stops it, so the toolbar keeps one slot for the whole action.
+ */
+export const NotebookRunAllButton = (
+ props: Pick<LemonButtonProps, 'children' | 'size' | 'type'>
+): JSX.Element | null => {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { content, shortId, isShared, runnableCellNodeIds } = useValues(notebookLogic)
+ const { isRunning, isStarting, isInterrupting, progressLabel } = useValues(notebookRunLogic({ shortId }))
+ const { startRun, interruptRun } = useActions(notebookRunLogic({ shortId }))
+
+ // Only a markdown notebook with something to run gets the button at all. Runnable means
+ // SQL or Python, the same pair the backend plan walks — a notebook of Python cells alone
+ // runs perfectly well, and reading the SQL summaries hid the button from it.
+ if (!isKernelUiEnabled(featureFlags) || !isMarkdownNotebookContent(content) || !runnableCellNodeIds.length) {
+ return null
+ }
+
+ if (isRunning) {
+ return (
+ <LemonButton
+ {...props}
+ onClick={() => interruptRun()}
+ icon={<IconStopFilled />}
+ loading={isInterrupting}
+ disabledReason={isInterrupting ? 'Stopping the run' : undefined}
+ tooltip={progressLabel ?? 'Stop the run'}
+ data-attr="notebook-run-all-stop"
+ >
+ Stop
+ </LemonButton>
+ )
+ }
+
+ return (
+ <LemonButton
+ {...props}
+ onClick={() => startRun()}
+ icon={<IconPlay />}
+ loading={isStarting}
+ disabledReason={
+ isShared ? 'You can only run cells in the notebook itself' : isStarting ? 'Starting the run' : undefined
+ }
+ tooltip="Run every SQL and Python cell in order, stopping at the first one that fails"
+ data-attr="notebook-run-all"
+ >
+ Run all
+ </LemonButton>
+ )
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.ts b/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.ts
index f553a6aa9752..ab2320ebfdc1 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookAnalytics.ts
@@ -3,6 +3,8 @@ import type { MarkdownNotebookAskAIRequest } from 'lib/components/MarkdownNotebo
import { SCRATCHPAD_NOTEBOOK } from '~/models/notebooksModel'
import { AccessControlLevel, UserType } from '~/types'
+import type { NotebookRunStatusResponseApi } from 'products/notebooks/frontend/generated/api.schemas'
+
import { NotebookType } from '../types'
import type { InlineAICompletion } from './MarkdownNotebookInlineAI'
@@ -83,3 +85,43 @@ export function buildNotebookOpenedEvent(
node_count: notebook.content?.content?.length ?? 0,
}
}
+
+export type NotebookRunAllStartedProperties = {
+ short_id: string
+ cell_count: number
+}
+
+export type NotebookRunAllFinishedProperties = {
+ short_id: string
+ cell_count: number
+ python_cell_count: number
+ completed_count: number
+ outcome: string
+ duration_ms: number
+}
+
+/** No code and no cell content in the properties: a run's payload is counts and an outcome. */
+export function buildNotebookRunStartedEvent(
+ shortId: string,
+ cellCount: number
+): ['notebook run all started', NotebookRunAllStartedProperties] {
+ return ['notebook run all started', { short_id: shortId, cell_count: cellCount }]
+}
+
+export function buildNotebookRunFinishedEvent(
+ shortId: string,
+ run: NotebookRunStatusResponseApi,
+ durationMs: number
+): ['notebook run all finished', NotebookRunAllFinishedProperties] {
+ return [
+ 'notebook run all finished',
+ {
+ short_id: shortId,
+ cell_count: run.cell_count,
+ python_cell_count: run.cells.filter((cell) => cell.cell_type === 'python').length,
+ completed_count: run.cells.filter((cell) => cell.status === 'done').length,
+ outcome: run.status,
+ duration_ms: durationMs,
+ },
+ ]
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index 3a4b36452520..488d3e13e877 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -74,6 +74,7 @@ import {
buildNotebookDependencyGraph,
collectNodeIndices,
collectNotebookFrameNodes,
+ collectRunnableCellNodeIds,
collectSqlV2Nodes,
} from '../Nodes/notebookNodeContent'
import type { NotebookDependencyGraph, NotebookFrameNodeSummary, SqlV2NodeSummary } from '../Nodes/notebookNodeContent'
@@ -342,6 +343,7 @@ export interface notebookLogicValues {
notebookPresenceParticipants: NotebookPresenceParticipant[]
personUUIDFromCanvasOverride: string | null
previewContent: JSONContent | null
+ runnableCellNodeIds: string[]
runnableVariables: NotebookVariable[]
shortId: string
shouldBeEditable: boolean
@@ -685,6 +687,7 @@ export interface notebookLogicMeta {
content: JSONContent
) => BuiltLogic<notebookNodeLogicType>[]
sqlV2NodeSummaries: (content: JSONContent) => SqlV2NodeSummary[]
+ runnableCellNodeIds: (content: JSONContent) => string[]
frameNodeSummaries: (content: JSONContent) => NotebookFrameNodeSummary[]
dependencyGraph: (contentAtLastRun: JSONContent | null) => NotebookDependencyGraph
sqlNodeIndices: (content: JSONContent) => Map<string, number>
@@ -1444,6 +1447,7 @@ export const notebookLogic = kea<notebookLogicType>([
],
sqlV2NodeSummaries: [(s) => [s.content], (content: JSONContent) => collectSqlV2Nodes(content)],
+ runnableCellNodeIds: [(s) => [s.content], (content: JSONContent) => collectRunnableCellNodeIds(content)],
frameNodeSummaries: [(s) => [s.content], (content: JSONContent) => collectNotebookFrameNodes(content)],
dependencyGraph: [
// Keyed on the last-run snapshot, not live content, so typing does not rebuild it.
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts
index ce376373bc29..6a04c12c47e2 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts
@@ -89,6 +89,13 @@ export interface notebookNodeStalenessLogicActions {
abortChain: (reason: string | null) => {
reason: string | null
}
+ adoptChainRun: (
+ nodeId: string,
+ runId: string
+ ) => {
+ nodeId: string
+ runId: string
+ }
clearNodeStale: (nodeId: string) => {
nodeId: string
}
@@ -214,6 +221,9 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([
runWidgetDataChain: (content: JSONContent | null, nodeIds: string[]) => ({ content, nodeIds }),
// Consumed by the matching notebookNodeSQLV2Logic, which builds refs and runs itself.
dispatchChainRun: (nodeId: string) => ({ nodeId }),
+ // A run the backend started for this cell, as part of a whole-notebook run. The
+ // matching cell adopts it and polls it as if it had dispatched it itself.
+ adoptChainRun: (nodeId: string, runId: string) => ({ nodeId, runId }),
setChainQueue: (nodeIds: string[]) => ({ nodeIds }),
setChainRoot: (nodeId: string | null) => ({ nodeId }),
setLastRun: (nodeId: string, downstreamNodeIds: string[]) => ({ nodeId, downstreamNodeIds }),
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookRunLogic.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookRunLogic.test.ts
new file mode 100644
index 000000000000..54a8e6f0daff
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/notebookRunLogic.test.ts
@@ -0,0 +1,248 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ notebooksRunsCreate,
+ notebooksRunsInterruptCreate,
+ notebooksRunsRetrieve,
+} from 'products/notebooks/frontend/generated/api'
+
+import { notebookLogic } from './notebookLogic'
+import { notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'
+import { notebookOperationsLogic } from './notebookOperationsLogic'
+import { notebookRunLogic } from './notebookRunLogic'
+
+jest.mock('products/notebooks/frontend/generated/api', () => ({
+ notebooksRunsCreate: jest.fn(),
+ notebooksRunsRetrieve: jest.fn(),
+ notebooksRunsInterruptCreate: jest.fn(),
+}))
+
+const SHORT_ID = 'nbrun01'
+
+const cell = (node_id: string, status: string | null, run_id: string | null): any => ({
+ node_id,
+ cell_type: node_id === 'p1' ? 'python' : 'sql',
+ dataframe_name: node_id,
+ run_id,
+ status,
+ error: null,
+})
+
+const runStatus = (status: string, cells: any[], overrides: Record<string, unknown> = {}): any => ({
+ run_id: 'nbrun-1',
+ status,
+ trigger: 'ui',
+ variables: [],
+ cell_count: cells.length,
+ current_index: 0,
+ current_node_id: cells[0]?.node_id ?? null,
+ failed_node_id: null,
+ error: null,
+ cells,
+ created_at: '2026-01-01T00:00:00Z',
+ finished_at: null,
+ ...overrides,
+})
+
+describe('notebookRunLogic', () => {
+ let logic: ReturnType<typeof notebookRunLogic.build> | undefined
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.mocked(notebooksRunsCreate).mockResolvedValue({
+ run_id: 'nbrun-1',
+ cell_count: 2,
+ starts_sandbox: false,
+ sandbox_hourly_price: null,
+ })
+ jest.mocked(notebooksRunsInterruptCreate).mockResolvedValue({ interrupted: true, status: 'interrupted' })
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ logic = undefined
+ jest.clearAllMocks()
+ })
+
+ it('hands each newly started cell to the cell that owns it', async () => {
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(
+ runStatus('running', [cell('s1', 'done', 'cell-1'), cell('p1', 'running', 'cell-2')])
+ )
+ logic = notebookRunLogic({ shortId: SHORT_ID })
+ logic.mount()
+ const staleness = notebookNodeStalenessLogic({ shortId: SHORT_ID })
+ staleness.mount()
+
+ await expectLogic(logic, () => logic!.actions.startRun())
+ .toDispatchActions(['pollRun', 'setRun'])
+ .toMatchValues({ progressLabel: 'Running cell 1 of 2' })
+ // The started run's id is the only thing linking the poll to the run just created;
+ // polling with undefined would 404 and silently abandon it.
+ expect(notebooksRunsRetrieve).toHaveBeenCalledWith(expect.any(String), SHORT_ID, 'nbrun-1')
+ await expectLogic(staleness).toDispatchActions([
+ staleness.actionCreators.adoptChainRun('s1', 'cell-1'),
+ staleness.actionCreators.adoptChainRun('p1', 'cell-2'),
+ ])
+
+ staleness.unmount()
+ })
+
+ it('holds the notebook busy while a run is active and releases it at the end', async () => {
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(
+ runStatus('running', [cell('s1', 'running', 'cell-1')])
+ )
+ logic = notebookRunLogic({ shortId: SHORT_ID })
+ logic.mount()
+ const operations = notebookOperationsLogic({ shortId: SHORT_ID })
+ operations.mount()
+
+ await expectLogic(logic, () => logic!.actions.startRun()).toDispatchActions(['setRun'])
+ expect(operations.values.isBusy).toBe(true)
+
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(runStatus('done', [cell('s1', 'done', 'cell-1')]))
+ await expectLogic(logic, () => logic!.actions.pollRun()).toDispatchActions(['runFinished', 'stopPolling'])
+ expect(operations.values.isBusy).toBe(false)
+
+ operations.unmount()
+ })
+
+ it('rides out a transient status failure without dropping the run', async () => {
+ // The backend keeps running whether or not one poll lands, so a blip must not leave
+ // the UI stuck on Stop with the notebook held.
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(
+ runStatus('running', [cell('s1', 'running', 'cell-1')])
+ )
+ logic = notebookRunLogic({ shortId: SHORT_ID })
+ logic.mount()
+ const operations = notebookOperationsLogic({ shortId: SHORT_ID })
+ operations.mount()
+ await expectLogic(logic, () => logic!.actions.startRun()).toDispatchActions(['setRun'])
+
+ jest.mocked(notebooksRunsRetrieve).mockRejectedValueOnce(new Error('network blip'))
+ await expectLogic(logic, () => logic!.actions.pollRun()).toFinishAllListeners()
+
+ expect(logic.values.isRunning).toBe(true)
+ expect(operations.values.isBusy).toBe(true)
+
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(runStatus('done', [cell('s1', 'done', 'cell-1')]))
+ await expectLogic(logic, () => logic!.actions.pollRun()).toDispatchActions(['runFinished'])
+ expect(operations.values.isBusy).toBe(false)
+
+ operations.unmount()
+ })
+
+ it('recovers after a long outage instead of stranding the run', async () => {
+ // Giving up released the notebook while the backend run was still live, which let a
+ // per-cell run start underneath it, and left the banner on Stop with no way back.
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(
+ runStatus('running', [cell('s1', 'running', 'cell-1')])
+ )
+ logic = notebookRunLogic({ shortId: SHORT_ID })
+ logic.mount()
+ const operations = notebookOperationsLogic({ shortId: SHORT_ID })
+ operations.mount()
+ await expectLogic(logic, () => logic!.actions.startRun()).toDispatchActions(['setRun'])
+
+ for (let attempt = 0; attempt < 8; attempt++) {
+ jest.mocked(notebooksRunsRetrieve).mockRejectedValueOnce(new Error('offline'))
+ await expectLogic(logic, () => logic!.actions.pollRun()).toFinishAllListeners()
+ }
+
+ // Well past the point the UI says it lost contact, and it is still watching.
+ expect(logic.values.isRunning).toBe(true)
+ expect(operations.values.isBusy).toBe(true)
+
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(runStatus('done', [cell('s1', 'done', 'cell-1')]))
+ await expectLogic(logic, () => logic!.actions.pollRun()).toDispatchActions(['runFinished'])
+ expect(operations.values.isBusy).toBe(false)
+
+ operations.unmount()
+ })
+
+ it('sends a Stop pressed before the run id arrives', async () => {
+ // isStarting already renders Stop, so the click is reachable. It used to return here
+ // without sending anything and without clearing the in-flight flag, leaving both Stop
+ // controls disabled until the run finished on its own.
+ let releaseStart: (value: any) => void = () => {}
+ jest.mocked(notebooksRunsCreate).mockReturnValueOnce(
+ new Promise((resolve) => {
+ releaseStart = resolve
+ }) as any
+ )
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValue(
+ runStatus('interrupted', [cell('s1', 'interrupted', 'cell-1')])
+ )
+ logic = notebookRunLogic({ shortId: SHORT_ID })
+ logic.mount()
+
+ logic.actions.startRun()
+ logic.actions.interruptRun()
+ expect(notebooksRunsInterruptCreate).not.toHaveBeenCalled()
+ expect(logic.values.isInterrupting).toBe(false)
+
+ releaseStart({ run_id: 'nbrun-1', cell_count: 1, starts_sandbox: false, sandbox_hourly_price: null })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(notebooksRunsInterruptCreate).toHaveBeenCalledWith(expect.any(String), SHORT_ID, 'nbrun-1')
+ })
+
+ it('starts the run with the edits autosave is still holding', async () => {
+ // Content saves debounce for 400ms and variables for 500ms, so a click straight after
+ // an edit froze the previously saved code and values, and the results then landed
+ // under newer text the user could see.
+ const pending = {
+ values: {
+ localContent: { type: 'doc' } as any,
+ variables: [{ name: 'days_back', type: 'number', value: 7 }],
+ },
+ actions: {
+ saveNotebookNow: jest.fn(() => {
+ pending.values.localContent = null as any
+ }),
+ },
+ }
+ jest.spyOn(notebookLogic, 'findMounted').mockReturnValue(pending as any)
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValue(runStatus('done', [cell('s1', 'done', 'cell-1')]))
+ logic = notebookRunLogic({ shortId: SHORT_ID })
+ logic.mount()
+
+ await expectLogic(logic, () => logic!.actions.startRun()).toDispatchActions(['setRun'])
+
+ expect(pending.actions.saveNotebookNow).toHaveBeenCalled()
+ expect(jest.mocked(notebooksRunsCreate).mock.calls[0][2]).toEqual({
+ variables: [{ name: 'days_back', type: 'number', value: 7 }],
+ })
+ })
+
+ it('reports a failed run against the cell that stopped it', async () => {
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(
+ runStatus('failed', [cell('s1', 'failed', 'cell-1'), cell('p1', null, null)], {
+ failed_node_id: 's1',
+ })
+ )
+ logic = notebookRunLogic({ shortId: SHORT_ID })
+ logic.mount()
+
+ await expectLogic(logic, () => logic!.actions.startRun()).toDispatchActions(['runFinished'])
+ expect(logic.values.isRunning).toBe(false)
+ })
+
+ it('stops the run through the interrupt endpoint', async () => {
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(
+ runStatus('running', [cell('s1', 'running', 'cell-1')])
+ )
+ logic = notebookRunLogic({ shortId: SHORT_ID })
+ logic.mount()
+ await expectLogic(logic, () => logic!.actions.startRun()).toDispatchActions(['setRun'])
+
+ jest.mocked(notebooksRunsRetrieve).mockResolvedValueOnce(
+ runStatus('interrupted', [cell('s1', 'interrupted', 'cell-1')])
+ )
+ await expectLogic(logic, () => logic!.actions.interruptRun()).toDispatchActions(['runFinished'])
+
+ expect(notebooksRunsInterruptCreate).toHaveBeenCalledWith(expect.any(String), SHORT_ID, 'nbrun-1')
+ expect(logic.values.isRunning).toBe(false)
+ })
+})
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookRunLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookRunLogic.ts
new file mode 100644
index 000000000000..56cebf961f94
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/notebookRunLogic.ts
@@ -0,0 +1,381 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { ApiConfig } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { delay } from 'lib/utils/async'
+
+import {
+ notebooksRunsCreate,
+ notebooksRunsInterruptCreate,
+ notebooksRunsRetrieve,
+} from 'products/notebooks/frontend/generated/api'
+import type {
+ NotebookRunStartRequestApi,
+ NotebookRunStatusResponseApi,
+} from 'products/notebooks/frontend/generated/api.schemas'
+
+import { buildNotebookRunFinishedEvent, buildNotebookRunStartedEvent } from './notebookAnalytics'
+import { notebookLogic } from './notebookLogic'
+import { notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'
+import { NotebookOperation, notebookOperationsLogic } from './notebookOperationsLogic'
+import { notebookSettingsLogic } from './notebookSettingsLogic'
+import { getSavableNotebookVariables } from './notebookVariables'
+import { sandboxStartMessage } from './SandboxStartMessage'
+
+/** How often the scene asks the backend where the run has got to. Matches the workflow's own cadence. */
+const POLL_INTERVAL_MS = 2000
+
+/** Consecutive failed status reads before the UI says so. Polling continues regardless. */
+const MAX_POLL_FAILURES = 5
+
+/** How long to wait for a pending content save before starting a run anyway. */
+const SAVE_FLUSH_TIMEOUT_MS = 3000
+
+export interface NotebookRunLogicProps {
+ shortId: string
+}
+
+/** The operation id the run holds for its whole duration, so per-cell run buttons stay disabled. */
+const runAllOperation = (shortId: string): NotebookOperation => ({
+ id: `${shortId}:run-all`,
+ nodeId: `${shortId}:run-all`,
+ kind: 'run',
+})
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface notebookRunLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ activeOperation: NotebookOperation | null // notebookOperationsLogic
+ isBusy: boolean // notebookOperationsLogic
+ cellCount: number
+ currentCellNumber: number
+ isInterrupting: boolean
+ isRunning: boolean
+ isSandboxComputeFree: boolean
+ isStarting: boolean
+ progressLabel: string | null
+ run: NotebookRunStatusResponseApi | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface notebookRunLogicActions {
+ adoptChainRun: (
+ nodeId: string,
+ runId: string
+ ) => {
+ nodeId: string
+ runId: string
+ } // notebookNodeStalenessLogic
+ finishOperation: (id: string) => {
+ id: string
+ } // notebookOperationsLogic
+ startOperation: (operation: NotebookOperation) => {
+ operation: NotebookOperation
+ } // notebookOperationsLogic
+ setShowKernelInfo: (showKernelInfo: boolean) => {
+ showKernelInfo: boolean
+ } // notebookSettingsLogic
+ interruptRun: () => {
+ value: true
+ }
+ pollRun: () => {
+ value: true
+ }
+ runFinished: (run: NotebookRunStatusResponseApi) => {
+ run: NotebookRunStatusResponseApi
+ }
+ setInterrupting: (isInterrupting: boolean) => {
+ isInterrupting: boolean
+ }
+ setRun: (run: NotebookRunStatusResponseApi | null) => {
+ run: NotebookRunStatusResponseApi | null
+ }
+ setStarting: (isStarting: boolean) => {
+ isStarting: boolean
+ }
+ startRun: () => {
+ value: true
+ }
+ stopPolling: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface notebookRunLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ isRunning: (run: NotebookRunStatusResponseApi | null, isStarting: boolean) => boolean
+ cellCount: (run: NotebookRunStatusResponseApi | null) => number
+ currentCellNumber: (run: NotebookRunStatusResponseApi | null) => number
+ progressLabel: (run: NotebookRunStatusResponseApi | null) => string | null
+ isSandboxComputeFree: (featureFlags: FeatureFlagsSet) => boolean
+ }
+}
+
+export type notebookRunLogicType = MakeLogicType<
+ notebookRunLogicValues,
+ notebookRunLogicActions,
+ NotebookRunLogicProps,
+ notebookRunLogicMeta
+>
+
+/**
+ * Runs every SQL and Python cell of a markdown notebook through the backend's whole-notebook
+ * run, and hands each cell's result back to the cell that owns it.
+ *
+ * The backend drives the cells, so this logic only starts the run, polls it, and tells each
+ * mounted cell which run id is now its own. The cell's existing poll path writes the result
+ * into the document and reports it to the staleness chain, so result rendering, stale marks,
+ * and interrupt all keep working with no new code.
+ */
+export const notebookRunLogic = kea<notebookRunLogicType>([
+ props({} as NotebookRunLogicProps),
+ key((props) => props.shortId),
+ path((key) => ['scenes', 'notebooks', 'Notebook', 'notebookRunLogic', key]),
+ connect((props: NotebookRunLogicProps) => ({
+ values: [
+ featureFlagLogic,
+ ['featureFlags'],
+ notebookOperationsLogic({ shortId: props.shortId }),
+ ['isBusy', 'activeOperation'],
+ ],
+ actions: [
+ notebookOperationsLogic({ shortId: props.shortId }),
+ ['startOperation', 'finishOperation'],
+ notebookNodeStalenessLogic({ shortId: props.shortId }),
+ ['adoptChainRun'],
+ notebookSettingsLogic,
+ ['setShowKernelInfo'],
+ ],
+ })),
+ actions({
+ startRun: true,
+ pollRun: true,
+ interruptRun: true,
+ stopPolling: true,
+ setRun: (run: NotebookRunStatusResponseApi | null) => ({ run }),
+ setStarting: (isStarting: boolean) => ({ isStarting }),
+ setInterrupting: (isInterrupting: boolean) => ({ isInterrupting }),
+ runFinished: (run: NotebookRunStatusResponseApi) => ({ run }),
+ }),
+ reducers({
+ run: [
+ null as NotebookRunStatusResponseApi | null,
+ {
+ setRun: (_, { run }) => run,
+ startRun: () => null,
+ },
+ ],
+ // The stop request is in flight; guards the Stop button against a second click.
+ isInterrupting: [
+ false,
+ {
+ interruptRun: () => true,
+ setInterrupting: (_, { isInterrupting }) => isInterrupting,
+ stopPolling: () => false,
+ startRun: () => false,
+ },
+ ],
+ // The window between the start request and the first status: the button is already
+ // busy, but there is no run to report progress for yet.
+ isStarting: [
+ false,
+ {
+ startRun: () => true,
+ setStarting: (_, { isStarting }) => isStarting,
+ stopPolling: () => false,
+ },
+ ],
+ }),
+ selectors({
+ isRunning: [
+ (s) => [s.run, s.isStarting],
+ (run: NotebookRunStatusResponseApi | null, isStarting: boolean): boolean =>
+ isStarting || run?.status === 'running',
+ ],
+ cellCount: [(s) => [s.run], (run: NotebookRunStatusResponseApi | null): number => run?.cell_count ?? 0],
+ currentCellNumber: [
+ (s) => [s.run],
+ (run: NotebookRunStatusResponseApi | null): number =>
+ run ? Math.min(run.current_index + 1, run.cell_count) : 0,
+ ],
+ progressLabel: [
+ (s) => [s.run],
+ (run: NotebookRunStatusResponseApi | null): string | null =>
+ run && run.status === 'running' && run.cell_count > 0
+ ? `Running cell ${Math.min(run.current_index + 1, run.cell_count)} of ${run.cell_count}`
+ : null,
+ ],
+ isSandboxComputeFree: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.NOTEBOOK_SANDBOX_FREE_COMPUTE],
+ ],
+ }),
+ listeners(({ props, actions, values, cache }) => {
+ const operation = runAllOperation(props.shortId)
+ const teamId = (): string => String(ApiConfig.getCurrentTeamId())
+
+ /** Save whatever autosave is still holding, and return the run body to start with. */
+ const flushPendingEdits = async (): Promise<NotebookRunStartRequestApi> => {
+ const notebook = notebookLogic.findMounted({ shortId: props.shortId })
+ if (!notebook) {
+ return {}
+ }
+ if (notebook.values.localContent) {
+ notebook.actions.saveNotebookNow()
+ // The save clears localContent, which is the signal it landed. Bounded: a save
+ // that cannot complete must not block the run forever, and the worst case is
+ // the behaviour this had before — a run against the last saved content.
+ const deadline = performance.now() + SAVE_FLUSH_TIMEOUT_MS
+ while (notebook.values.localContent && performance.now() < deadline) {
+ await delay(50)
+ }
+ }
+ const variables = getSavableNotebookVariables(notebook.values.variables ?? [])
+ return variables.length ? { variables } : {}
+ }
+
+ return {
+ startRun: async () => {
+ if (values.isBusy && values.activeOperation?.id !== operation.id) {
+ lemonToast.info('Another operation is running in this notebook — wait for it to finish.')
+ actions.setStarting(false)
+ return
+ }
+ actions.startOperation(operation)
+ cache.startedAt = performance.now()
+ cache.interruptRequested = false
+ try {
+ // Autosave debounces content by 400ms and variables by 500ms, so clicking
+ // straight after an edit used to freeze the previously saved code and
+ // values: the results then landed under newer text the user could see.
+ // Flush the content, and hand the variables to the start call, which
+ // stores them in the same transaction that creates the run.
+ const body = await flushPendingEdits()
+ const started = await notebooksRunsCreate(teamId(), props.shortId, body)
+ // The only place this id exists before the first poll, and `startRun`
+ // cleared the previous run, so without it every poll asks for /runs/undefined/.
+ cache.runId = started.run_id
+ if (cache.interruptRequested) {
+ // Stop was pressed while this request was still out. Send it now that
+ // there is something to stop, rather than dropping the click.
+ cache.interruptRequested = false
+ actions.interruptRun()
+ }
+ posthog.capture(...buildNotebookRunStartedEvent(props.shortId, started.cell_count))
+ if (started.starts_sandbox) {
+ // The backend decides this at dispatch, so it is the only accurate source.
+ // Open the panel so the user can watch the sandbox come up.
+ actions.setShowKernelInfo(true)
+ lemonToast.info(
+ sandboxStartMessage(started.sandbox_hourly_price ?? null, values.isSandboxComputeFree)
+ )
+ }
+ cache.seenCellRunIds = new Set<string>()
+ cache.pollFailures = 0
+ actions.setStarting(false)
+ actions.pollRun()
+ cache.disposables.add(() => {
+ const timer = window.setInterval(() => actions.pollRun(), POLL_INTERVAL_MS)
+ return () => clearInterval(timer)
+ }, 'pollRun')
+ } catch (error: any) {
+ actions.stopPolling()
+ lemonToast.error(error?.detail || error?.message || 'Could not start the run')
+ }
+ },
+ pollRun: async () => {
+ if (cache.pollInFlight) {
+ return
+ }
+ cache.pollInFlight = true
+ try {
+ const run = await notebooksRunsRetrieve(teamId(), props.shortId, values.run?.run_id ?? cache.runId)
+ cache.runId = run.run_id
+ actions.setRun(run)
+ // Hand every newly started cell to the cell that owns it, so its own poll
+ // path writes the result into the document.
+ const seen: Set<string> = (cache.seenCellRunIds ??= new Set<string>())
+ for (const cell of run.cells) {
+ if (cell.run_id && !seen.has(cell.run_id)) {
+ seen.add(cell.run_id)
+ actions.adoptChainRun(cell.node_id, cell.run_id)
+ }
+ }
+ cache.pollFailures = 0
+ if (run.status !== 'running') {
+ actions.runFinished(run)
+ }
+ } catch (error: any) {
+ if ((error as { status?: number } | null)?.status === 404) {
+ // The run is gone, so there is nothing left to recover.
+ actions.stopPolling()
+ lemonToast.error('That run no longer exists.')
+ return
+ }
+ // Anything else is the status endpoint being unreachable, and the run keeps
+ // going on the backend regardless. Giving up here released the notebook
+ // while the run was still live — letting a per-cell run start underneath it
+ // — and left the banner stuck on Stop with no way back. So keep the timer
+ // and the operation, say so once, and let a later poll pick the run up.
+ cache.pollFailures = (cache.pollFailures ?? 0) + 1
+ if (cache.pollFailures === MAX_POLL_FAILURES) {
+ lemonToast.error(error?.detail || error?.message || 'Lost contact with the run — still trying')
+ }
+ } finally {
+ cache.pollInFlight = false
+ }
+ },
+ runFinished: ({ run }) => {
+ actions.stopPolling()
+ posthog.capture(
+ ...buildNotebookRunFinishedEvent(
+ props.shortId,
+ run,
+ Math.round(performance.now() - (cache.startedAt ?? 0))
+ )
+ )
+ if (run.status === 'done') {
+ lemonToast.success('Notebook run finished.')
+ return
+ }
+ if (run.status === 'interrupted') {
+ lemonToast.info('Notebook run stopped.')
+ return
+ }
+ const failed = run.cells.find((cell) => cell.node_id === run.failed_node_id)
+ const position = run.cells.findIndex((cell) => cell.node_id === run.failed_node_id) + 1
+ const name = failed?.dataframe_name || (position > 0 ? `cell ${position}` : 'a cell')
+ lemonToast.error(`The run stopped at ${name}. Fix it and run again.`)
+ },
+ interruptRun: async () => {
+ const runId = values.run?.run_id ?? cache.runId
+ if (!runId) {
+ // The start request has not answered yet, so there is no run to stop.
+ // Remember the click: `startRun` sends it the moment the id lands. Without
+ // this the click vanished and left both Stop controls disabled for the
+ // rest of the run, because nothing reset the in-flight flag.
+ cache.interruptRequested = true
+ actions.setInterrupting(false)
+ return
+ }
+ try {
+ await notebooksRunsInterruptCreate(teamId(), props.shortId, runId)
+ // The next poll observes the terminal state and reports it once.
+ actions.pollRun()
+ } catch (error: any) {
+ actions.setInterrupting(false)
+ lemonToast.error(error?.detail || error?.message || 'Could not stop the run')
+ }
+ },
+ stopPolling: () => {
+ cache.disposables.dispose('pollRun')
+ actions.finishOperation(operation.id)
+ },
+ }
+ }),
+])
diff --git a/frontend/src/scenes/notebooks/NotebookScene.tsx b/frontend/src/scenes/notebooks/NotebookScene.tsx
index 8c59ff3f8cf3..3854d63bc19a 100644
--- a/frontend/src/scenes/notebooks/NotebookScene.tsx
+++ b/frontend/src/scenes/notebooks/NotebookScene.tsx
@@ -27,6 +27,8 @@ import {
NotebookPresence,
NotebookSyncInfo,
} from './Notebook/NotebookMeta'
+import { NotebookRunAllBanner } from './Notebook/NotebookRunAllBanner'
+import { NotebookRunAllButton } from './Notebook/NotebookRunAllButton'
import { NotebookShareModal } from './Notebook/NotebookShareModal'
import { NotebookMenu } from './NotebookMenu'
import { notebookPanelLogic } from './NotebookPanel/notebookPanelLogic'
@@ -135,6 +137,7 @@ export function NotebookScene(): JSX.Element {
<UserActivityIndicator at={notebook?.last_modified_at} by={notebook?.last_modified_by} />
<BindLogic logic={notebookLogic} props={{ shortId: notebookId, target: NotebookTarget.Scene }}>
<NotebookVariablesButton type="tertiary" size="small" />
+ <NotebookRunAllButton type="tertiary" size="small" />
</BindLogic>
</div>
@@ -177,6 +180,10 @@ export function NotebookScene(): JSX.Element {
</div>
</div>
+ <BindLogic logic={notebookLogic} props={{ shortId: notebookId, target: NotebookTarget.Scene }}>
+ <NotebookRunAllBanner shortId={notebookId} />
+ </BindLogic>
+
<Notebook
key={notebookId}
shortId={notebookId}