Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: scratchpad (#1821)

Myles Scolnick7de7a27569cd
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index a5b01f9b06..20b9a9b9d9 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -47,11 +47,11 @@ export interface CellEditorProps
| "deleteCell"
| "focusCell"
| "moveCell"
- | "moveToNextCell"
| "updateCellConfig"
| "clearSerializedEditorState"
> {
runCell: () => void;
+ moveToNextCell: CellActions["moveToNextCell"] | undefined;
theme: Theme;
showPlaceholder: boolean;
editorViewRef: React.MutableRefObject<EditorView | null>;
@@ -128,6 +128,7 @@ const CellEditorInternal = ({
() => focusCell({ cellId, before: true }),
[cellId, focusCell],
);
+
const toggleHideCode = useEvent(() => {
const nextHidden = !hidden;
// Fire-and-forget save
diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsx
index f744a8b2ed..3539ff344c 100644
--- a/frontend/src/components/scratchpad/scratchpad.tsx
+++ b/frontend/src/components/scratchpad/scratchpad.tsx
@@ -20,9 +20,10 @@ import { DEFAULT_CELL_NAME } from "@/core/cells/names";
import { Button } from "../ui/button";
import { Tooltip } from "../ui/tooltip";
import { renderShortcut } from "../shortcuts/renderShortcut";
-import { BetweenHorizontalStartIcon, PlayIcon } from "lucide-react";
+import { BetweenHorizontalStartIcon, EraserIcon, PlayIcon } from "lucide-react";
import { HideInKioskMode } from "../editor/kiosk-mode";
import { useLastFocusedCellId } from "@/core/cells/focus";
+import { Spinner } from "../icons/spinner";
export const ScratchPad: React.FC = () => {
const notebookState = useNotebook();
@@ -35,6 +36,7 @@ export const ScratchPad: React.FC = () => {
const cellId = SCRATCH_CELL_ID;
const cellRuntime = notebookState.cellRuntime[cellId];
const output = cellRuntime?.output;
+ const status = cellRuntime?.status;
const consoleOutputs = cellRuntime?.consoleOutputs;
const cellData = notebookState.cellData[cellId];
const code = cellData?.code ?? "";
@@ -44,6 +46,9 @@ export const ScratchPad: React.FC = () => {
});
const handleInsertCode = useEvent(() => {
+ if (!code.trim()) {
+ return;
+ }
createNewCell({
code,
before: false,
@@ -51,13 +56,32 @@ export const ScratchPad: React.FC = () => {
});
});
+ const handleClearCode = useEvent(() => {
+ updateCellCode({
+ cellId,
+ code: "",
+ formattingChange: false,
+ });
+ sendRunScratchpad({ code: "" });
+ const ev = ref.current;
+ if (ev) {
+ ev.dispatch({
+ changes: {
+ from: 0,
+ to: ev.state.doc.length,
+ insert: "",
+ },
+ });
+ }
+ });
+
return (
<div
className="flex flex-col h-full overflow-hidden divide-y"
id={HTMLCellId.create(cellId)}
>
<div className="flex gap-2 justify-between items-center flex-shrink-0">
- <div>
+ <div className="flex items-center">
<Tooltip content={renderShortcut("cell.run")}>
<Button
data-testid="scratchpad-run-button"
@@ -69,8 +93,16 @@ export const ScratchPad: React.FC = () => {
<PlayIcon color="var(--grass-11)" size={16} />
</Button>
</Tooltip>
+ {(status === "running" || status === "queued") && (
+ <Spinner className="inline" size="small" />
+ )}
</div>
<div>
+ <Tooltip content="Clear code and outputs">
+ <Button size="xs" variant="text" onClick={handleClearCode}>
+ <EraserIcon size={16} />
+ </Button>
+ </Tooltip>
<HideInKioskMode>
<Tooltip content="Insert code">
<Button size="xs" variant="text" onClick={handleInsertCode}>
@@ -83,8 +115,8 @@ export const ScratchPad: React.FC = () => {
<div className="overflow-auto flex-shrink-0 max-h-[40%]">
<CellEditor
theme={theme}
- showPlaceholder={false}
allowFocus={false}
+ showPlaceholder={false}
id={cellId}
code={code}
status="idle"
@@ -95,7 +127,7 @@ export const ScratchPad: React.FC = () => {
deleteCell={Functions.NOOP}
focusCell={Functions.NOOP}
moveCell={Functions.NOOP}
- moveToNextCell={Functions.NOOP}
+ moveToNextCell={undefined}
updateCellConfig={Functions.NOOP}
clearSerializedEditorState={Functions.NOOP}
userConfig={userConfig}
@@ -112,7 +144,7 @@ export const ScratchPad: React.FC = () => {
stale={false}
/>
</div>
- <div className="overflow-auto flex-shrink-0 max-h-[25%]">
+ <div className="overflow-auto flex-shrink-0 max-h-[35%]">
<ConsoleOutput
consoleOutputs={consoleOutputs}
className="overflow-auto"
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index a79b0ded6d..60276de9f5 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { HotkeyProvider } from "@/core/hotkeys/hotkeys";
+import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";
import { EditorView, type KeyBinding, keymap } from "@codemirror/view";
import { type CellId, HTMLCellId } from "@/core/cells/ids";
import { type Extension, Prec } from "@codemirror/state";
@@ -12,10 +12,8 @@ import { isAtEndOfEditor, isAtStartOfEditor } from "../utils";
import { goToDefinitionAtCursorPosition } from "../go-to-definition/utils";
export interface MovementCallbacks
- extends Pick<
- CellActions,
- "splitCell" | "sendToTop" | "sendToBottom" | "moveToNextCell"
- > {
+ extends Pick<CellActions, "splitCell" | "sendToTop" | "sendToBottom"> {
+ moveToNextCell: CellActions["moveToNextCell"] | undefined;
onRun: () => void;
deleteCell: () => void;
createAbove: () => void;
@@ -69,6 +67,9 @@ export function cellMovementBundle(
stopPropagation: true,
run: (ev) => {
onRun();
+ if (!moveToNextCell) {
+ return true;
+ }
ev.contentDOM.blur();
moveToNextCell({ cellId, before: false });
return true;
@@ -80,6 +81,9 @@ export function cellMovementBundle(
stopPropagation: true,
run: (ev) => {
onRun();
+ if (!moveToNextCell) {
+ return true;
+ }
ev.contentDOM.blur();
moveToNextCell({ cellId, before: true });
return true;
@@ -257,6 +261,9 @@ export function cellMovementBundle(
stopPropagation: true,
run: (ev) => {
splitCell({ cellId });
+ if (!moveToNextCell) {
+ return true;
+ }
requestAnimationFrame(() => {
ev.contentDOM.blur();
moveToNextCell({ cellId, before: false }); // focus new cell
diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsx
index 6f9cff0fe9..4c569d3680 100644
--- a/frontend/src/core/config/feature-flag.tsx
+++ b/frontend/src/core/config/feature-flag.tsx
@@ -16,7 +16,7 @@ export interface ExperimentalFeatures {
const defaultValues: ExperimentalFeatures = {
markdown: true,
wasm_layouts: false,
- scratchpad: false,
+ scratchpad: true,
};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index e4d53d63b5..5ae57e76ad 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -14,6 +14,7 @@ import sys
import threading
import time
import traceback
+from copy import copy
from multiprocessing import connection
from typing import (
TYPE_CHECKING,
@@ -939,6 +940,38 @@ class Kernel:
break
LOGGER.debug("Finished run.")
+ def _broadcast_missing_packages(self, runner: cell_runner.Runner) -> None:
+ if (
+ any(
+ isinstance(e, ModuleNotFoundError)
+ for e in runner.exceptions.values()
+ )
+ and self.package_manager is not None
+ ):
+ missing_packages = [
+ self.package_manager.module_to_package(mod)
+ for mod in self.module_registry.missing_modules()
+ ]
+
+ if missing_packages:
+ if self.package_manager.should_auto_install():
+ self._execute_install_missing_packages_callback(
+ self.package_manager.name
+ )
+ else:
+ MissingPackageAlert(
+ packages=list(sorted(missing_packages)),
+ isolated=is_python_isolated(),
+ ).broadcast()
+
+ def _propagate_kernel_errors(
+ self,
+ runner: cell_runner.Runner,
+ ) -> None:
+ for cell_id, error in runner.exceptions.items():
+ if isinstance(error, MarimoStrictExecutionError):
+ self.errors[cell_id] = (error,)
+
async def _run_cells_internal(self, roots: set[CellId_t]) -> set[CellId_t]:
"""Run cells, send outputs to frontends
@@ -956,37 +989,6 @@ class Kernel:
for cid in runner.cells_to_run:
self._invalidate_cell_state(cid)
- def broadcast_missing_packages(runner: cell_runner.Runner) -> None:
- if (
- any(
- isinstance(e, ModuleNotFoundError)
- for e in runner.exceptions.values()
- )
- and self.package_manager is not None
- ):
- missing_packages = [
- self.package_manager.module_to_package(mod)
- for mod in self.module_registry.missing_modules()
- ]
-
- if missing_packages:
- if self.package_manager.should_auto_install():
- self._execute_install_missing_packages_callback(
- self.package_manager.name
- )
- else:
- MissingPackageAlert(
- packages=list(sorted(missing_packages)),
- isolated=is_python_isolated(),
- ).broadcast()
-
- def propagate_kernel_errors(
- runner: cell_runner.Runner,
- ) -> None:
- for cell_id, error in runner.exceptions.items():
- if isinstance(error, MarimoStrictExecutionError):
- self.errors[cell_id] = (error,)
-
def note_time_of_interruption(
cell_impl: CellImpl,
runner: cell_runner.Runner,
@@ -1012,7 +1014,10 @@ class Kernel:
+ [note_time_of_interruption],
on_finish_hooks=(
self._on_finish_hooks
- + [broadcast_missing_packages, propagate_kernel_errors]
+ + [
+ self._broadcast_missing_packages,
+ self._propagate_kernel_errors,
+ ]
),
)
@@ -1088,40 +1093,38 @@ class Kernel:
filtered_requests.append(request)
await self._run_cells(
- self.mutate_graph(
- filtered_requests,
- deletion_requests=[
- # Always delete the scratchpad cell
- DeleteCellRequest(cell_id=SCRATCH_CELL_ID)
- ],
- )
+ self.mutate_graph(filtered_requests, deletion_requests=[])
)
- async def run_scratchpad(self, request: ExecuteScratchpadRequest) -> None:
- LOGGER.warning("Running scratchpad cell")
+ async def run_scratchpad(self, code: str) -> None:
roots = {SCRATCH_CELL_ID}
- # Mutated graph by adding scratchpad cell
- self.mutate_graph(
- execution_requests=[
- ExecutionRequest(SCRATCH_CELL_ID, request.code)
- ],
- deletion_requests=[],
- )
+
+ # If cannot compile, don't run
+ try:
+ cell = compile_cell(code, SCRATCH_CELL_ID)
+ cell.defs.clear() # remove definitions
+ cell.refs.clear() # remove definitions
+ except SyntaxError:
+ return
+
+ # Create graph of just the scratchpad cell
+ graph = dataflow.DirectedGraph()
+ graph.register_cell(SCRATCH_CELL_ID, cell)
+
runner = cell_runner.Runner(
roots=roots,
- graph=self.graph,
- glbls=self.globals,
- excluded_cells=set(self.errors.keys()),
+ graph=graph,
+ glbls=copy(self.globals),
+ excluded_cells=set(),
debugger=self.debugger,
execution_mode=self.reactive_execution_mode,
execution_type=self.execution_type,
execution_context=self._install_execution_context,
- preparation_hooks=self._preparation_hooks, # + [invalidate_state],
+ preparation_hooks=self._preparation_hooks,
pre_execution_hooks=self._pre_execution_hooks,
post_execution_hooks=self._post_execution_hooks,
on_finish_hooks=(
- self._on_finish_hooks
- # + [broadcast_missing_packages, propagate_kernel_errors]
+ self._on_finish_hooks + [self._broadcast_missing_packages]
),
)
@@ -1583,7 +1586,7 @@ class Kernel:
await self.run(request.execution_requests)
CompletedRun().broadcast()
elif isinstance(request, ExecuteScratchpadRequest):
- await self.run_scratchpad(request)
+ await self.run_scratchpad(request.code)
elif isinstance(request, ExecuteStaleRequest):
await self.run_stale_cells()
elif isinstance(request, SetCellConfigRequest):
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 453bf25adc..b743479c41 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -30,6 +30,7 @@ from marimo._runtime.requests import (
SetUIElementValueRequest,
)
from marimo._runtime.runtime import Kernel
+from marimo._runtime.scratch import SCRATCH_CELL_ID
from marimo._utils.parse_dataclass import parse_raw
from tests.conftest import ExecReqProvider, MockedKernel
@@ -868,6 +869,82 @@ class TestExecution:
assert "exc" not in k.graph.cells[er_1.cell_id].defs
assert "e" in k.globals
+ @staticmethod
+ async def test_run_scratch(mocked_kernel: MockedKernel) -> None:
+ k = mocked_kernel.k
+ await k.run_scratchpad("x = 1; x")
+ # Has no errors
+ assert not k.errors
+ messages = mocked_kernel.stream.messages
+ (m1, m2, m3, m4) = messages
+ assert all(m[0] == "cell-op" for m in messages)
+ assert all(m[1]["cell_id"] == SCRATCH_CELL_ID for m in messages)
+ assert m1[1]["status"] == "queued"
+ assert m2[1]["status"] == "running"
+ assert m3[1]["status"] == "idle"
+ assert m4[1]["status"] is None
+ assert (
+ m4[1]["output"]["data"] == "<pre style='font-size: 12px'>1</pre>"
+ )
+ # Does not pollute globals
+ assert "x" not in k.globals
+
+ @staticmethod
+ async def test_run_scratch_with_other_globals(
+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = mocked_kernel.k
+ await k.run(
+ [
+ exec_req.get(
+ """
+ z = 10
+ """
+ ),
+ ]
+ )
+
+ await k.run_scratchpad("y = z * 2; y")
+ # Has no errors
+ assert not k.errors
+ messages = mocked_kernel.stream.messages
+ last_message = messages[-1]
+ assert (
+ last_message[1]["output"]["data"]
+ == "<pre style='font-size: 12px'>20</pre>"
+ )
+ assert "z" in k.globals
+ # Does not pollute globals
+ assert "y" not in k.globals
+
+ @staticmethod
+ async def test_run_scratch_can_temporarily_overwrite_globals(
+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = mocked_kernel.k
+ await k.run(
+ [
+ exec_req.get(
+ """
+ z = 10
+ """
+ ),
+ ]
+ )
+
+ await k.run_scratchpad("z = 20; z")
+ # Has no errors
+ assert not k.errors
+ messages = mocked_kernel.stream.messages
+ last_message = messages[-1]
+ assert (
+ last_message[1]["output"]["data"]
+ == "<pre style='font-size: 12px'>20</pre>"
+ )
+ assert "z" in k.globals
+ # Does not pollute globals, reverts back to 10
+ assert k.globals["z"] == 10
+
class TestStrictExecution:
@staticmethod