: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): run code cells from the block's top row (#83171)
Sinan Kucukkoseler0e5d92be148b
diff --git a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.mdindex 43177f10137e..82e5fd554cbe 100644--- a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md+++ b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md@@ -84,6 +84,11 @@ A `title` equal to the component's own label (e.g. code blocks default `title` t`EditComponent` is optional; if omitted, the component only has a view panel.Call `updateProps(partialProps)` from either component to update persisted markdown props.+`ToolbarComponent` is optional and renders in the block's top row, in view mode as well as edit mode.+The shell mounts it outside both panels, so it stays live while the block is collapsed and while the edit panel is closed.+Use it for a control a reader needs with no editor on screen — a code cell's Run button is one.+It receives `node`, the notebook's `notebookMode`, and `updateProps`.+`exclusiveEditPanel` hides the view panel while the edit panel is open.Use it for expensive or stateful components that should not mount twice.diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scssindex 693d9a23d906..c48009c4781a 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss@@ -1812,12 +1812,17 @@ h3.MarkdownNotebook__text-block--heading {.MarkdownNotebook__component-mode-actions,.MarkdownNotebook__component-actions,+.MarkdownNotebook__component-toolbar-controls,.MarkdownNotebook__component-edit-footer {display: flex;gap: 0.5rem;align-items: center;}+.MarkdownNotebook__component-toolbar-controls {+ flex: 0 0 auto;+}+.MarkdownNotebook__component-title {display: inline-flex;flex: 0 0 auto;diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsxindex 4b35a29d47c4..b4da0d1284d0 100644--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx@@ -574,6 +574,49 @@ describe('NotebookComponentShell', () => {expect(within(collapsedCanvas.container).getByLabelText('Expand')).toBeTruthy()})+ it.each([+ ['edit', { filters: true, results: true }],+ ['view', { filters: false, results: true }],+ // Collapsed: the reason the control is a shell slot rather than a published toolbar extra —+ // a code cell stays runnable with neither its editor nor its results on screen.+ ['edit', { filters: false, results: false }],+ ] as const)('renders the definition toolbar control in %s mode with panels %p', (mode, componentPanels) => {+ const registry = createMarkdownNotebookRegistry([+ {+ tagName: 'Probe',+ label: 'Probe',+ category: 'Test',+ ViewComponent: () => <div>Results</div>,+ EditComponent: () => <div>Filters panel</div>,+ ToolbarComponent: () => <button type="button">Run</button>,+ },+ ])++ const { container } = render(+ <NotebookComponentShell+ node={{ id: 'probe-node', type: 'component', tagName: 'Probe', props: {} }}+ mode={mode}+ componentPanels={componentPanels}+ persistComponentPanelVisibility={false}+ isSelected={false}+ registry={registry}+ toggleComponentPanel={jest.fn()}+ setLocalComponentPanels={jest.fn()}+ rememberComponentPanels={jest.fn()}+ setBlockRef={jest.fn()}+ updateNode={jest.fn()}+ deleteNode={jest.fn()}+ deleteSelectedNotebookBlocks={jest.fn(() => false)}+ insertParagraphAfterNode={jest.fn()}+ moveFocusToAdjacentNode={jest.fn(() => false)}+ />+ )++ expect(+ within(container.querySelector('.MarkdownNotebook__component-toolbar') as HTMLElement).getByText('Run')+ ).toBeTruthy()+ })+it('keeps the toolbar menu when collapsing unmounts the component', () => {function ExtrasProbe(): JSX.Element {const setToolbarExtras = useContext(NotebookComponentToolbarExtrasContext)diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsxindex f6f14f445982..265bd258b5d4 100644--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx@@ -115,6 +115,7 @@ export function NotebookComponentShell({const errors = [...(node.errors ?? []), ...(definition?.validateProps?.(node.props) ?? [])]const ViewComponent = definition?.ViewComponentconst EditComponent = definition?.EditComponent ?? definition?.ViewComponent+ const ToolbarComponent = definition?.ToolbarComponent// Read-only canvases (e.g. customer profiles) keep the filters toggle: it's the only way to// configure nodes there, matching the legacy notebook's canvas behavior.const isViewModeCanvas = mode === 'view' && !!allowViewModeFilters@@ -439,6 +440,13 @@ export function NotebookComponentShell({) : null}</div>) : null}+ {ToolbarComponent ? (+ <div className="MarkdownNotebook__component-toolbar-controls">+ <NotebookComponentToolbarErrorBoundary node={node}>+ <ToolbarComponent node={node} notebookMode={mode} updateProps={updateProps} />+ </NotebookComponentToolbarErrorBoundary>+ </div>+ ) : null}</div>{mode === 'edit' ? (isTitleEditable && isEditingTitle ? (@@ -584,6 +592,31 @@ function isTitleInputTarget(target: EventTarget | null): boolean {return target instanceof HTMLElement && !!target.closest('.MarkdownNotebook__component-toolbar-title--input')}+function NotebookComponentToolbarErrorBoundary({+ children,+ node,+}: {+ children: ReactNode+ node: NotebookComponentBlockNode+}): JSX.Element {+ return (+ <PostHogErrorBoundary+ key={`${node.id}-toolbar`}+ additionalProperties={{+ feature: 'markdown_notebook_component',+ markdown_notebook_node_id: node.id,+ markdown_notebook_tag_name: node.tagName,+ markdown_notebook_panel: 'toolbar',+ }}+ // A crashed control drops out of the toolbar instead of reporting there: an error block+ // in the top row would push the title and the block's actions off it.+ fallback={() => <></>}+ >+ {children}+ </PostHogErrorBoundary>+ )+}+export function NotebookComponentPanelErrorBoundary({children,node,diff --git a/frontend/src/lib/components/MarkdownNotebook/types.ts b/frontend/src/lib/components/MarkdownNotebook/types.tsindex a6073545a6b9..69ef69a68015 100644--- a/frontend/src/lib/components/MarkdownNotebook/types.ts+++ b/frontend/src/lib/components/MarkdownNotebook/types.ts@@ -144,6 +144,12 @@ export type NotebookComponentRenderProps = {deleteNode: () => void}+export type NotebookComponentToolbarProps = {+ node: NotebookComponentBlockNode+ notebookMode: NotebookMode+ updateProps: (props: Partial<NotebookComponentProps>) => void+}+export type NotebookComponentInsertCommand = {label?: stringcategory?: string@@ -168,6 +174,10 @@ export type NotebookComponentDefinition = {getHref?: (node: NotebookComponentBlockNode) => string | null | undefinedViewComponent: (props: NotebookComponentRenderProps) => JSX.ElementEditComponent?: (props: NotebookComponentRenderProps) => JSX.Element+ /** Rendered in the block's toolbar, in view mode as well as edit mode. The shell mounts it+ * outside the panels, so it stays live while the block is collapsed and while the editing+ * panel is closed — for a control a reader needs with no editor on screen, like Run. */+ ToolbarComponent?: (props: NotebookComponentToolbarProps) => JSX.Element | nullexclusiveEditPanel?: booleanhideModeActions?: boolean/** Show the filters toggle in view mode too, when the host opts in via `allowViewModeFilters`diff --git a/frontend/src/lib/components/MarkdownNotebook/utils.test.ts b/frontend/src/lib/components/MarkdownNotebook/utils.test.tsnew file mode 100644index 000000000000..eedd1a43fa5c--- /dev/null+++ b/frontend/src/lib/components/MarkdownNotebook/utils.test.ts@@ -0,0 +1,59 @@+import { getSerializableProps } from './utils'++describe('getSerializableProps', () => {+ it('preserves a query whose nested filter carries undefined fields, stripping the undefined', () => {+ // A completed person-property filter from the DataTable carries an absent+ // label/group_type_index as `undefined`. The `query` prop has to survive that, or the+ // People table never re-queries when a filter is added.+ const result = getSerializableProps({+ query: {+ kind: 'DataTableNode',+ source: {+ kind: 'ActorsQuery',+ properties: [+ { type: 'person', key: 'email', operator: 'exact', value: '[email protected]', label: undefined },+ ],+ },+ },+ })++ expect(result.query).toEqual({+ kind: 'DataTableNode',+ source: {+ kind: 'ActorsQuery',+ properties: [{ type: 'person', key: 'email', operator: 'exact', value: '[email protected]' }],+ },+ })+ })++ it('keeps a fully-serializable filter (e.g. cohort) untouched', () => {+ const query = {+ kind: 'DataTableNode',+ source: {+ kind: 'ActorsQuery',+ properties: [{ type: 'cohort', key: 'id', value: 42, operator: 'in' }],+ },+ }++ expect(getSerializableProps({ query }).query).toEqual(query)+ })++ it.each([+ ['undefined', { a: undefined }, {}],+ ['function', { a: () => undefined }, {}],+ ])('omits the key entirely when the value is not serializable (%s)', (_label, attributes, expected) => {+ expect(getSerializableProps(attributes)).toEqual(expected)+ })++ it('preserves primitive, array and nested object props', () => {+ expect(+ getSerializableProps({ id: 'abc', count: 3, enabled: true, items: ['a', 'b'], nested: { x: 1 } })+ ).toEqual({ id: 'abc', count: 3, enabled: true, items: ['a', 'b'], nested: { x: 1 } })+ })++ it('strips undefined nested in an object while keeping its siblings', () => {+ expect(getSerializableProps({ nested: { keep: 'yes', drop: undefined } })).toEqual({+ nested: { keep: 'yes' },+ })+ })+})diff --git a/frontend/src/lib/components/MarkdownNotebook/utils.ts b/frontend/src/lib/components/MarkdownNotebook/utils.tsindex 6f8d21b205bf..c743c2166b11 100644--- a/frontend/src/lib/components/MarkdownNotebook/utils.ts+++ b/frontend/src/lib/components/MarkdownNotebook/utils.ts@@ -321,6 +321,23 @@ export function toSerializablePropValue(value: unknown): NotebookPropValue | undreturn JSON.parse(serialized) as NotebookPropValue}+// Project a set of node attributes onto the props a component block can carry, dropping the keys+// whose values markdown can't represent.+export function getSerializableProps<T extends object>(attributes: T): NotebookComponentProps {+ return Object.entries(attributes).reduce<NotebookComponentProps>((props, [key, value]) => {+ // Normalize before validating. isNotebookPropValue rejects an object that holds a nested+ // `undefined`, so an unnormalized value loses its whole key: a person-property filter with+ // an absent `label` or `group_type_index` inside `query.source.properties` takes the entire+ // `query` prop with it. Normalizing first drops those keys, so the guard sees a value+ // markdown can actually carry.+ const normalized = toSerializablePropValue(value)+ if (normalized !== undefined && isNotebookPropValue(normalized)) {+ props[key] = normalized+ }+ return props+ }, {})+}+function sortProps(props: NotebookComponentProps): NotebookComponentProps {return Object.keys(props).sort()diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsxindex 070d79a734f4..ccd68fb2eeac 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx@@ -59,6 +59,9 @@ interface QueryWindowProps {/** With onRunQuery: flips the button to Cancel while runQueryLoading, mirroring the native cancel. */onCancelQuery?: () => voidcancelQueryLoading?: boolean+ /** Drop the toolbar's run button, for hosts that offer the run affordance themselves+ * (a notebook code cell runs from the cell's top row). Cmd+Enter still runs. */+ hideRunButton?: booleanonShareTab?: () => void/** Whether the query pane's code editor may grab focus on mount. Defaults to true. */autoFocusQueryPane?: boolean@@ -78,6 +81,7 @@ export function QueryWindow({runQueryTooltip,onCancelQuery,cancelQueryLoading,+ hideRunButton,onShareTab,autoFocusQueryPane,}: QueryWindowProps): JSX.Element {@@ -274,19 +278,21 @@ export function QueryWindow({size="small"/>) : null}- <RunButton- onRunQuery={onRunQuery}- runQueryLoading={runQueryLoading}- runQueryDisabledReason={- runQueryDisabledReason ??- (showBIEditor && !biConfig.source- ? 'Drag a field into the BI editor before running'- : undefined)- }- runQueryTooltip={runQueryTooltip}- onCancelQuery={onCancelQuery}- cancelQueryLoading={cancelQueryLoading}- />+ {hideRunButton ? null : (+ <RunButton+ onRunQuery={onRunQuery}+ runQueryLoading={runQueryLoading}+ runQueryDisabledReason={+ runQueryDisabledReason ??+ (showBIEditor && !biConfig.source+ ? 'Drag a field into the BI editor before running'+ : undefined)+ }+ runQueryTooltip={runQueryTooltip}+ onCancelQuery={onCancelQuery}+ cancelQueryLoading={cancelQueryLoading}+ />+ )}<CollapsedConnectionSelector tabId={tabId} mode={mode} />{!showBIEditor ? <LemonDivider vertical /> : null}{!showBIEditor ? (diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex 1a8d52439ba8..7f1292106a51 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -73,6 +73,8 @@ interface SQLEditorProps {/** With onRunQuery: flips the run button to Cancel while runQueryLoading. */onCancelQuery?: () => voidcancelQueryLoading?: boolean+ /** Drop the toolbar's run button, for hosts that offer the run affordance themselves. */+ hideRunButton?: booleanonShareTab?: () => voidqueryPaneDefaultHeight?: number/** Whether the query pane's code editor may grab focus on mount. Defaults to true. */@@ -93,6 +95,7 @@ export function SQLEditor({runQueryTooltip,onCancelQuery,cancelQueryLoading,+ hideRunButton,onShareTab,queryPaneDefaultHeight,autoFocusQueryPane,@@ -281,6 +284,7 @@ export function SQLEditor({runQueryTooltip={runQueryTooltip}onCancelQuery={onCancelQuery}cancelQueryLoading={cancelQueryLoading}+ hideRunButton={hideRunButton}onShareTab={onShareTab}autoFocusQueryPane={autoFocusQueryPane}/>diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsxindex c52013b66527..b77bfdc5febd 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx@@ -1,10 +1,8 @@import { useActions, useMountedLogic, useValues } from 'kea'import { useEffect, useMemo, useRef } from 'react'-import { IconCornerDownRight, IconPlayFilled } from '@posthog/icons'+import { IconCornerDownRight } from '@posthog/icons'-import { IconCancel } from 'lib/lemon-ui/icons'-import { LemonButton } from 'lib/lemon-ui/LemonButton'import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'import type { NotebookNodeRunTerminalStatus } from 'scenes/notebooks/Notebook/notebookNodeStalenessLogic'@@ -16,7 +14,7 @@ import { NotebookStaleCellBanner } from './components/NotebookStaleCellBanner'import { notebookNodeLogic } from './notebookNodeLogic'import { countTextLines, initialSizedRunId, outputHeightForShape } from './notebookNodeOutputHeight'import type { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'-import { SQL_V2_DEFAULT_PAGE_SIZE, collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'+import { SQL_V2_DEFAULT_PAGE_SIZE, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'import { NotebookDataframeResult } from './pythonExecution'// The revamped Python cell: code runs in the notebook's sandbox kernel via the SQLV2 run@@ -244,73 +242,34 @@ const Settings = ({hasResult: !!attributes.result,getContent: () => notebookLogic.values.content ?? null,})- const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)- const { runQuery, interruptRun } = useActions(dataLogic)+ const { runNode } = useActions(dataLogic)- const run = (): void => {- // Guard here (not just on the button) so Cmd+Enter can't fire a second run mid-flight —- // overlapping runs race the poller and can strand the spinner.- if (isRunning) {- return+ // Read the run state imperatively: Monaco binds Cmd+Enter once at editor mount, so a captured+ // value would be the one from that first render. The guard keeps the keybinding from firing a+ // second run mid-flight — overlapping runs race the poller and can strand the spinner.+ const runOnCmdEnter = (): void => {+ if (!dataLogic.values.isRunning) {+ runNode()}- // The refs map sibling SQLV2 frames; the backend materializes only the ones the code reads.- runQuery(attributes.code ?? '', collectSqlV2Refs(notebookLogic.values.content, nodeId), {- nodeType: 'python',- outputName: attributes.returnVariable,- })}- // Monaco binds Cmd+Enter once at editor mount, so a plain `run` closure would capture the- // initial (empty) code and the guard would drop the run. Route through a ref that always- // points at the latest run so the keybinding sees the current code, output name, and run state.- const runRef = useRef(run)- runRef.current = runreturn (- <div className="flex h-full min-h-0 flex-col">- {/* Mirrors the embedded SQL editor's toolbar (QueryWindow) so code cells look alike. */}- <div- className="flex w-full shrink-0 flex-row items-center gap-2 border-t border-b bg-white py-1 pl-2 pr-2 dark:bg-black"- onClick={(event) => event.stopPropagation()}- >- {/* Run flips to Cancel while the cell runs, mirroring the SQL editor's affordance. */}- <LemonButton- data-attr="notebook-python-v2-run-button"- size="small"- type="primary"- icon={isRunning ? <IconCancel /> : <IconPlayFilled color="var(--success)" />}- onClick={() => {- if (isRunning) {- if (!isInterrupting) {- interruptRun()- }- } else {- run()- }- }}- loading={isInterrupting}- disabledReason={operationBlockReason ?? undefined}- tooltip={isRunning ? 'Stop the running cell' : 'Run Python (⌘⏎)'}- >- {isRunning ? 'Cancel' : 'Run'}- </LemonButton>- </div>- <div- className="min-h-0 flex-1"- // The editor owns pointer drags in here. Without this the resize handle drags the- // node around the markdown notebook instead of resizing the editor.- onMouseDown={(event) => event.stopPropagation()}- onDragStart={(event) => event.stopPropagation()}- >- <CodeEditorResizeable- language="python"- value={typeof attributes.code === 'string' ? attributes.code : ''}- onChange={(value) => updateAttributes({ code: value ?? '' })}- onPressCmdEnter={() => runRef.current()}- minHeight={PYTHON_EDITOR_MIN_HEIGHT}- maxHeight={PYTHON_EDITOR_MAX_HEIGHT}- embedded- />- </div>+ <div+ className="h-full min-h-0"+ // The editor owns pointer drags in here. Without this the resize handle drags the+ // node around the markdown notebook instead of resizing the editor.+ onMouseDown={(event) => event.stopPropagation()}+ onDragStart={(event) => event.stopPropagation()}+ >+ <CodeEditorResizeable+ language="python"+ value={typeof attributes.code === 'string' ? attributes.code : ''}+ onChange={(value) => updateAttributes({ code: value ?? '' })}+ onPressCmdEnter={runOnCmdEnter}+ minHeight={PYTHON_EDITOR_MIN_HEIGHT}+ maxHeight={PYTHON_EDITOR_MAX_HEIGHT}+ embedded+ /></div>)}diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxindex cba53819df6a..1cfaaa561331 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -20,7 +20,7 @@ import { NotebookCodeSQLEditorSettings } from './components/NotebookSQLEditor'import { NotebookStaleCellBanner } from './components/NotebookStaleCellBanner'import { notebookNodeLogic } from './notebookNodeLogic'import { initialSizedRunId, outputHeightForShape } from './notebookNodeOutputHeight'-import { SQL_V2_DEFAULT_PAGE_SIZE, collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'+import { SQL_V2_DEFAULT_PAGE_SIZE, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'import { NotebookDataframeResult } from './pythonExecution'export type NotebookNodeSQLV2Media = { mime_type: string; data: string }@@ -384,7 +384,7 @@ const Settings = ({updateAttributes,}: NotebookNodeAttributeProperties<NotebookNodeSQLV2Attributes>): JSX.Element => {const nodeLogic = useMountedLogic(notebookNodeLogic)- const { nodeId, notebookLogic, sqlV2ReturnVariable } = useValues(nodeLogic)+ const { nodeId, notebookLogic } = useValues(nodeLogic)const notebookShortId = notebookLogic.props.shortIdconst dataLogic = notebookNodeSQLV2Logic({@@ -395,8 +395,8 @@ const Settings = ({hasResult: !!attributes.result,getContent: () => notebookLogic.values.content ?? null,})- const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)- const { runQuery, interruptRun } = useActions(dataLogic)+ const { isRunning } = useValues(dataLogic)+ const { runNode } = useActions(dataLogic)return (<NotebookCodeSQLEditorSettings@@ -404,21 +404,12 @@ const Settings = ({updateAttributes={updateAttributes}tabIdSuffix="datav2"persistConnection- // Refs come from the notebook content, not the tiptap editor: markdown notebooks- // (the only surface with SQLV2 cells) have no tiptap editor at all.- // outputName is what a rerouted (DuckDB) run binds its result to in the kernel, so- // downstream cells can read this cell's frame; a ClickHouse run ignores it.- onRunQuery={(code, connection) =>- runQuery(code, collectSqlV2Refs(notebookLogic.values.content, nodeId), {- ...connection,- outputName: sqlV2ReturnVariable,- })- }+ // The cell runs from the notebook's own top row, so the editor keeps only its Cmd+Enter+ // binding — which hands over what the editor holds, since the document catches up to a+ // keystroke or a just-picked connection a render later.+ hideRunButton+ onRunQuery={(code, connection) => runNode({ code, ...connection })}runQueryLoading={isRunning}- runQueryDisabledReason={operationBlockReason ?? undefined}- runQueryTooltip="Run SQL query"- onCancelQuery={interruptRun}- cancelQueryLoading={isInterrupting}/>)}diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.test.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.test.tsxnew file mode 100644index 000000000000..a0dbcccf2a57--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.test.tsx@@ -0,0 +1,141 @@+jest.mock('scenes/data-warehouse/editor/SQLEditor', () => ({+ SQLEditor: () => null,+ SQLEditorPanel: {+ Output: 'output',+ },+}))++jest.mock('scenes/data-warehouse/editor/sqlEditorLogic', () => ({+ sqlEditorLogic: { findMounted: jest.fn(() => null) },+}))++import { act, fireEvent, render } from '@testing-library/react'+import { BindLogic } from 'kea'+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+import { type NotebookComponentBlockNode } from 'lib/components/MarkdownNotebook/types'+import { type JSONContent } from 'lib/components/RichContentEditor/types'+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel } from '~/types'++import { type NotebookLogicProps, notebookLogic } from '../../Notebook/notebookLogic'+import { NotebookNodeType, type NotebookType } from '../../types'+import { NotebookCodeCellRunButton } from './NotebookCodeCellRunButton'++describe('NotebookCodeCellRunButton', () => {+ const SHORT_ID = 'test-run-button'+ const NODE_ID = 'sql-cell-1'+ const DOCUMENT_SQL = 'select 1'++ const LOGIC_PROPS: NotebookLogicProps = { shortId: SHORT_ID, mode: 'notebook' }++ const NODE: NotebookComponentBlockNode = {+ id: 'block-1',+ type: 'component',+ tagName: 'SQLV2',+ props: { nodeId: NODE_ID },+ }++ const CONTENT: JSONContent = {+ type: 'doc',+ content: [+ {+ type: NotebookNodeType.SQLV2,+ attrs: { nodeId: NODE_ID, code: DOCUMENT_SQL, returnVariable: 'sql_df' },+ },+ ],+ }++ const notebookWith = (userAccessLevel: AccessControlLevel): NotebookType =>+ ({+ id: 'notebook-id',+ short_id: SHORT_ID,+ title: 'Run button',+ content: CONTENT,+ text_content: DOCUMENT_SQL,+ version: 1,+ deleted: false,+ is_template: false,+ user_access_level: userAccessLevel,+ created_at: '2025-01-01T00:00:00Z',+ created_by: null,+ last_modified_at: '2025-01-01T00:00:00Z',+ last_modified_by: null,+ }) as unknown as NotebookType++ let logic: ReturnType<typeof notebookLogic.build>+ let runSpy: jest.SpyInstance++ const mountNotebook = async (userAccessLevel: AccessControlLevel): Promise<void> => {+ jest.spyOn(api.notebooks, 'get').mockResolvedValue(notebookWith(userAccessLevel))+ logic = notebookLogic(LOGIC_PROPS)+ logic.mount()+ logic.actions.loadNotebook()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()+ }++ const renderButton = (): HTMLElement | null => {+ const { container } = render(+ <BindLogic logic={notebookLogic} props={LOGIC_PROPS}>+ <NotebookCodeCellRunButton node={NODE} notebookMode="view" updateProps={jest.fn()} />+ </BindLogic>+ )+ return container.querySelector('[data-attr="notebook-code-cell-run-button"]')+ }++ beforeEach(() => {+ localStorage.clear()+ initKeaTests()+ jest.spyOn(api.notebooks, 'collabStream').mockResolvedValue(undefined as any)+ runSpy = jest.spyOn(api.notebooks, 'sqlV2Run').mockResolvedValue({ run_id: 'r1' })+ jest.spyOn(api.notebooks, 'sqlV2RunResult').mockResolvedValue({ status: 'running', result: null, error: null })+ ;(sqlEditorLogic.findMounted as jest.Mock).mockReturnValue(null)+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ it.each([+ ['an editor', AccessControlLevel.Editor, false, true],+ ['a viewer', AccessControlLevel.Viewer, false, false],+ ['an editor previewing an older version', AccessControlLevel.Editor, true, false],+ ] as const)(+ 'offers the control to %s',+ async (_label, userAccessLevel, isPreviewing, expectsControl): Promise<void> => {+ await mountNotebook(userAccessLevel)+ if (isPreviewing) {+ logic.actions.setPreviewContent(CONTENT)+ }++ expect(renderButton() !== null).toBe(expectsControl)+ }+ )++ it.each([+ ['an empty editor', '', 0],+ ['an editor holding newer code', 'select 2', 1],+ ] as const)(+ 'runs what %s holds rather than the code the document still carries',+ async (_label, queryInput, expectedRuns): Promise<void> => {+ await mountNotebook(AccessControlLevel.Editor)+ ;(sqlEditorLogic.findMounted as jest.Mock).mockReturnValue({+ values: { queryInput, selectedConnectionId: null, sendRawQueryEnabled: false },+ })++ const button = renderButton()+ await act(async () => {+ fireEvent.click(button as HTMLElement)+ })++ expect(runSpy).toHaveBeenCalledTimes(expectedRuns)+ if (expectedRuns > 0) {+ expect(runSpy).toHaveBeenCalledWith(SHORT_ID, expect.objectContaining({ code: queryInput }))+ }+ }+ )+})diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsxnew file mode 100644index 000000000000..8a8446e3b136--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookCodeCellRunButton.tsx@@ -0,0 +1,99 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import { useCallback } from 'react'++import { IconPlayFilled } from '@posthog/icons'++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 { notebookLogic } from '../../Notebook/notebookLogic'+import {+ type NotebookNodeSQLV2LogicProps,+ type RunNodeOverrides,+ notebookNodeSQLV2Logic,+} 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 } = 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 = notebookNodeSQLV2Logic({+ nodeId,+ notebookShortId: mountedNotebookLogic.props.shortId,+ updateAttributes,+ runId: typeof node.props.runId === 'string' ? node.props.runId : null,+ hasResult: !!node.props.result,+ getContent: () => mountedNotebookLogic.values.content ?? null,+ })+ const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)+ const { runNode, interruptRun } = useActions(dataLogic)++ // 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.+ if (isShared || !canEditNotebook) {+ return null+ }++ const run = (): 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)+ }++ 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 if (!isInterrupting) {+ // Guard against double submission: one interrupt request at a time.+ interruptRun()+ }+ }}+ loading={isInterrupting}+ disabledReason={operationBlockReason ?? undefined}+ tooltip={isRunning ? 'Stop the running cell' : 'Run cell (⌘⏎)'}+ >+ {isRunning ? 'Cancel' : 'Run'}+ </LemonButton>+ )+}diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsxindex 2937617a9c1f..e9fd101f78c3 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx@@ -513,6 +513,7 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string } & NotebrunQueryTooltip,onCancelQuery,cancelQueryLoading,+ hideRunButton,persistConnection,}: NotebookNodeAttributeProperties<T> & {tabIdSuffix: string@@ -524,6 +525,8 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string } & Noteb/** With onRunQuery: flips the run button to Cancel while runQueryLoading. */onCancelQuery?: () => voidcancelQueryLoading?: boolean+ /** Drop the editor toolbar's run button, for cells that run from the notebook's own top row. */+ hideRunButton?: boolean/** Store the picked connection on the cell. Only for cells whose run actually honors it. */persistConnection?: boolean}): JSX.Element {@@ -582,6 +585,7 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string } & NotebrunQueryTooltip={runQueryTooltip}onCancelQuery={onCancelQuery}cancelQueryLoading={cancelQueryLoading}+ hideRunButton={hideRunButton}queryPaneDefaultHeight={EMBEDDED_SQL_EDITOR_EDIT_DEFAULT_HEIGHT}/></div>diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsindex c3f1ccd3fcf8..c958432d1c0b 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -94,6 +94,14 @@ export interface RunQueryOptions {sendRawQuery?: boolean}+// What an open editor holds right now, for the callers that can read it — the document only+// catches up to a keystroke or a just-picked connection on a later render.+export interface RunNodeOverrides {+ code?: string+ connectionId?: string | null+ sendRawQuery?: boolean+}+export interface NotebookNodeSQLV2LogicProps {nodeId: stringnotebookShortId: string@@ -181,6 +189,9 @@ export interface notebookNodeSQLV2LogicActions {resetPaging: () => {value: true}+ runNode: (overrides?: RunNodeOverrides) => {+ overrides: RunNodeOverrides+ }runQuery: (code: string,refs?: Record<string, SqlV2RunRef>,@@ -272,6 +283,11 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([refs,opts,}),+ // Run this cell the way its own Run button does, deriving the code, the refs and the run+ // options from the live document rather than from the caller. The single entry point for+ // every run trigger — the toolbar button, Cmd+Enter, a chain dispatch — so a cell runs the+ // same way whether or not its editor is on screen.+ runNode: (overrides: RunNodeOverrides = {}) => ({ overrides }),startPolling: (runId: string) => ({ runId }),pollResult: (runId: string) => ({ runId }),stopPolling: true,@@ -529,23 +545,36 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([actions.nodeRunFinished(props.nodeId, 'failed', null)}},- // A chain-dispatched run (Journey 10): only the matching node acts; it rebuilds its- // code and refs from the live document, exactly like its own Run button would.- dispatchChainRun: ({ nodeId }) => {- if (nodeId !== props.nodeId) {- return- }+ runNode: ({ overrides }) => {const content = props.getContent?.() ?? nullconst self = content ? buildNotebookDependencyGraph(content).nodesById[props.nodeId] : nullif (!content || !self) {+ // A cell the document no longer holds can never report a result, so tell the+ // staleness chain now rather than leave it waiting on this node.actions.nodeRunFinished(props.nodeId, 'failed', null)return}+ // The graph's returnVariable is the disambiguated frame name (sql_df, sql_df_2, …)+ // downstream cells reference, which is what a rerouted run has to bind.const opts: RunQueryOptions =self.nodeType === NotebookNodeType.PythonV2? { nodeType: 'python', outputName: self.returnVariable }- : { connectionId: self.connectionId ?? null, sendRawQuery: !!self.sendRawQuery }- actions.runQuery(self.code ?? '', collectSqlV2Refs(content, props.nodeId), opts)+ : {+ outputName: self.returnVariable,+ connectionId:+ overrides.connectionId !== undefined+ ? overrides.connectionId+ : (self.connectionId ?? null),+ sendRawQuery: overrides.sendRawQuery ?? !!self.sendRawQuery,+ }+ actions.runQuery(overrides.code ?? self.code ?? '', collectSqlV2Refs(content, props.nodeId), opts)+ },+ // A chain-dispatched run (Journey 10): only the matching node acts, and it runs itself+ // exactly as its own Run button would.+ dispatchChainRun: ({ nodeId }) => {+ if (nodeId === props.nodeId) {+ actions.runNode()+ }},startPolling: ({ runId }) => {// Idempotent re-register: also covers a remount resuming a persisted in-flight run.diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsxindex e705c404458d..0557312dfaf5 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx@@ -26,7 +26,6 @@ import {getNodeAttributes,getQueryTitle,getSerializableAttributeInputValue,- getSerializableProps,} from './markdownNotebookRegistry'jest.mock('./MarkdownNotebookEntityPicker', () => ({@@ -395,62 +394,4 @@ describe('markdownNotebookRegistry', () => {expect(getQueryTitle(query)).toEqual(expected)})})-- describe('getSerializableProps', () => {- it('preserves a query whose nested filter carries undefined fields, stripping the undefined', () => {- // Regression: a completed person-property filter from the DataTable arrives with absent- // label/group_type_index as `undefined`. Previously the whole `query` prop was dropped,- // so the People table never re-queried when a filter was added.- const result = getSerializableProps({- query: {- kind: 'DataTableNode',- source: {- kind: 'ActorsQuery',- properties: [- { type: 'person', key: 'email', operator: 'exact', value: '[email protected]', label: undefined },- ],- },- },- })-- expect(result.query).toEqual({- kind: 'DataTableNode',- source: {- kind: 'ActorsQuery',- properties: [{ type: 'person', key: 'email', operator: 'exact', value: '[email protected]' }],- },- })- })-- it('keeps a fully-serializable filter (e.g. cohort) untouched', () => {- const query = {- kind: 'DataTableNode',- source: {- kind: 'ActorsQuery',- properties: [{ type: 'cohort', key: 'id', value: 42, operator: 'in' }],- },- }-- expect(getSerializableProps({ query }).query).toEqual(query)- })-- it.each([- ['undefined', { a: undefined }, {}],- ['function', { a: () => undefined }, {}],- ])('omits the key entirely when the value is not serializable (%s)', (_label, attributes, expected) => {- expect(getSerializableProps(attributes as any)).toEqual(expected)- })-- it('preserves primitive, array and nested object props', () => {- expect(- getSerializableProps({ id: 'abc', count: 3, enabled: true, items: ['a', 'b'], nested: { x: 1 } } as any)- ).toEqual({ id: 'abc', count: 3, enabled: true, items: ['a', 'b'], nested: { x: 1 } })- })-- it('strips undefined nested in an object while keeping its siblings', () => {- expect(getSerializableProps({ nested: { keep: 'yes', drop: undefined } } as any)).toEqual({- nested: { keep: 'yes' },- })- })- })})diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex 44325a8e05ab..5ef201261803 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -66,7 +66,7 @@ import {NotebookComponentRegistry,NotebookPropValue,} from 'lib/components/MarkdownNotebook/types'-import { isNotebookPropValue, toSerializablePropValue } from 'lib/components/MarkdownNotebook/utils'+import { getSerializableProps, isNotebookPropValue } from 'lib/components/MarkdownNotebook/utils'import { FEATURE_FLAGS } from 'lib/constants'import { useUploadFiles } from 'lib/hooks/useUploadFiles'import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'@@ -76,6 +76,7 @@ import { uuid } from 'lib/utils/dom'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { NODE_ICONS } from '../nodeIcons'+import { NotebookCodeCellRunButton } from '../Nodes/components/NotebookCodeCellRunButton'import { NotebookNodeContext } from '../Nodes/NotebookNodeContext'import { notebookNodeLogic } from '../Nodes/notebookNodeLogic'import { getNotebookWidgetViewMenuItem } from '../notebookWidgetMenu'@@ -237,6 +238,7 @@ export const MARKDOWN_NODE_DEFINITIONS: {category: stringlabel?: stringEditComponent?: NotebookComponentDefinition['EditComponent']+ ToolbarComponent?: NotebookComponentDefinition['ToolbarComponent']exclusiveEditPanel?: booleaninsertCommand?: NotebookComponentDefinition['insertCommand']}[] = [@@ -254,6 +256,7 @@ export const MARKDOWN_NODE_DEFINITIONS: {tagName: 'PythonV2',category: 'Code',label: 'Python',+ ToolbarComponent: NotebookCodeCellRunButton,insertCommand: {aliases: ['python', 'py'],defaultProps: () => ({@@ -273,6 +276,7 @@ export const MARKDOWN_NODE_DEFINITIONS: {// The single SQL node once the legacy SQL cells are deprecated (they render but// are not insertable), so it reads as plain "SQL" in the insert menu.label: 'SQL',+ ToolbarComponent: NotebookCodeCellRunButton,insertCommand: {// Sits in the menu's top group, where the built-in SQL command it replaces used to be,// so SQL stays where people already reach for it. Only the menu grouping moves; the@@ -337,6 +341,7 @@ export const NOTEBOOK_MARKDOWN_REGISTRY: NotebookComponentRegistry = createMarkddefaultProps: () => getDefaultPropsForNodeType(nodeType),ViewComponent: RealNotebookNodeView,EditComponent: definition.EditComponent ?? RealNotebookNodeEdit,+ ToolbarComponent: definition.ToolbarComponent,exclusiveEditPanel: definition.exclusiveEditPanel,editableTitle: options?.editableTitle,// Nodes with a Settings panel keep their filters toggle on read-only canvases@@ -1134,20 +1139,6 @@ export function getSerializableAttributeInputValue(return trimmedValue}-export function getSerializableProps(attributes: Partial<NotebookNodeAttributes<any>>): NotebookComponentProps {- return Object.entries(attributes).reduce<NotebookComponentProps>((props, [key, value]) => {- // Normalize before validating, mirroring how the legacy notebook flow synced attributes.- // Otherwise isNotebookPropValue rejects an object with a single nested `undefined` property and—- // it gets ignored. e.g. a person-property filter's absent `label`/`group_type_index` inside- // `query.source.properties` — fails isNotebookPropValue and the whole `query` prop is dropped- const normalized = toSerializablePropValue(value)- if (normalized !== undefined && isNotebookPropValue(normalized)) {- props[key] = normalized- }- return props- }, {})-}-export function splitTagName(tagName: string): string {return tagName.replace(/([a-z])([A-Z])/g, '$1 $2')}diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex 8d9e312ae262..15b58e951155 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -293,6 +293,7 @@ export interface notebookLogicValues {autosavePaused: booleancachedInlineQueryResultsByNodeId: Record<string, AnyResponseType>cachedInsightsByShortId: Record<string, InsightModel>+ canEditNotebook: booleancanvasFiltersOverride: anycontainerSize: 'medium' | 'small'content: JSONContent@@ -660,12 +661,12 @@ export interface notebookLogicMeta {duckSqlNodeIndices: (content: JSONContent) => Map<string, number>hogqlSqlNodeIndices: (content: JSONContent) => Map<string, number>isShowingLeftColumn: (showHistory: boolean) => boolean- isEditable: (- shouldBeEditable: boolean,+ canEditNotebook: (previewContent: JSONContent | null,notebook: NotebookType | null,mode: NotebookLogicMode) => boolean+ isEditable: (shouldBeEditable: boolean, canEditNotebook: boolean) => booleanisShared: (arg: any) => booleancachedInsightsByShortId: (arg: any) => Record<string, InsightModel>cachedInlineQueryResultsByNodeId: (arg: any) => Record<string, AnyResponseType>@@ -1377,23 +1378,27 @@ export const notebookLogic = kea<notebookLogicType>([isShowingLeftColumn: [(s) => [s.showHistory], (showHistory: boolean) => showHistory],+ // Whether this reader may change the notebook at all, independent of the view/edit toggle.+ // A canvas is local to the reader, so it always qualifies. A history preview never does,+ // because it shows a version the reader is not editing. Gate a control that has to work in+ // view mode on this rather than on `isEditable`, which is false whenever the editors are+ // off screen.+ canEditNotebook: [+ (s) => [s.previewContent, s.notebook, s.mode],+ (previewContent: JSONContent | null, notebook: NotebookType | null, mode: NotebookLogicMode) =>+ mode === 'canvas' ||+ (!previewContent &&+ !!notebook?.user_access_level &&+ accessLevelSatisfied(+ AccessControlResourceType.Notebook,+ notebook.user_access_level,+ AccessControlLevel.Editor+ )),+ ],+isEditable: [- (s) => [s.shouldBeEditable, s.previewContent, s.notebook, s.mode],- (- shouldBeEditable: boolean,- previewContent: JSONContent | null,- notebook: NotebookType | null,- mode: NotebookLogicMode- ) =>- shouldBeEditable &&- (mode === 'canvas' ||- (!previewContent &&- !!notebook?.user_access_level &&- accessLevelSatisfied(- AccessControlResourceType.Notebook,- notebook.user_access_level,- AccessControlLevel.Editor- ))),+ (s) => [s.shouldBeEditable, s.canEditNotebook],+ (shouldBeEditable: boolean, canEditNotebook: boolean) => shouldBeEditable && canEditNotebook,],isShared: [() => [(_, props) => props.cachedNotebook], (cachedNotebook): boolean => !!cachedNotebook],