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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
experimental: scratch pad (#1800)
Myles Scolnicke9af0fc9f604
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex 7db38149ae..b429501249 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -43,7 +43,7 @@ import { ShareStaticNotebookModal } from "@/components/static-html/share-modal";import { useRestartKernel } from "./useRestartKernel";import { createShareableLink } from "@/core/wasm/share";import { useChromeActions, useChromeState } from "../chrome/state";-import { PANEL_ICONS, PANEL_TYPES } from "../chrome/types";+import { PANELS } from "../chrome/types";import { startCase } from "lodash-es";import { keyboardShortcutsAtom } from "../controls/keyboard-shortcuts";import { MarkdownIcon } from "@/components/editor/cell/code/icons";@@ -174,8 +174,10 @@ export function useNotebookActions() {icon: <PanelLeftIcon size={14} strokeWidth={1.5} />,label: "Helper panel",handle: NOOP_HANDLER,- dropdown: PANEL_TYPES.map((type) => {- const Icon = PANEL_ICONS[type];+ dropdown: PANELS.flatMap(({ type, Icon, hidden }) => {+ if (hidden) {+ return [];+ }return {label: startCase(type),rightElement: (diff --git a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx b/frontend/src/components/editor/cell/code/ai-completion-editor.tsxindex 2edf41d904..6b4f5f807d 100644--- a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx+++ b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx@@ -20,7 +20,7 @@ import { Checkbox } from "@/components/ui/checkbox";import { getCodes } from "@/core/codemirror/copilot/getCodes";import { useTheme } from "@/theme/useTheme";import { asURL } from "@/utils/url";-import { LanguageAdapterType } from "@/core/codemirror/language/types";+import type { LanguageAdapterType } from "@/core/codemirror/language/types";const Original = CodeMirrorMerge.Original;const Modified = CodeMirrorMerge.Modified;@@ -98,7 +98,10 @@ export const AiCompletionEditor: React.FC<Props> = ({!enabled && "h-0 invisible",)}>- <SparklesIcon className="text-[var(--blue-10)]" size={16} />+ <SparklesIcon+ className="text-[var(--blue-10)] flex-shrink-0"+ size={16}+ /><inputclassName="h-8 outline-none px-2 focus-visible:shadow-none flex-1 rounded-none border-none focus:border-none"value={input}@@ -146,7 +149,7 @@ export const AiCompletionEditor: React.FC<Props> = ({)}<div className="h-full w-px bg-border mx-2" /><Tooltip content="Include code from other cells">- <div className="flex flex-row items-start gap-1">+ <div className="flex flex-row items-start gap-1 overflow-hidden"><Checkboxdata-testid="include-other-cells-checkbox"id="include-other-cells"@@ -157,7 +160,7 @@ export const AiCompletionEditor: React.FC<Props> = ({/><LabelhtmlFor="include-other-cells"- className="text-muted-foreground text-xs"+ className="text-muted-foreground text-xs whitespace-nowrap ellipsis">Include all code</Label>diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 5d07944479..a5b01f9b06 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -28,10 +28,10 @@ import { cn } from "@/utils/cn";import { saveCellConfig } from "@/core/network/requests";import { HideCodeButton } from "../../code/readonly-python-code";import { AiCompletionEditor } from "./ai-completion-editor";-import { useAtom, useAtomValue, useSetAtom } from "jotai";+import { useAtom, useAtomValue } from "jotai";import { aiCompletionCellAtom } from "@/core/ai/state";import { mergeRefs } from "@/utils/mergeRefs";-import { lastFocusedCellIdAtom } from "@/core/cells/focus";+import { useSetLastFocusedCellId } from "@/core/cells/focus";import type { LanguageAdapterType } from "@/core/codemirror/language/types";import { autoInstantiateAtom } from "@/core/config/config";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";@@ -87,7 +87,7 @@ const CellEditorInternal = ({}: CellEditorProps) => {const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom);const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();- const setLastFocusedCellId = useSetAtom(lastFocusedCellIdAtom);+ const setLastFocusedCellId = useSetLastFocusedCellId();// DOM node where the editorView will be mountedconst editorViewParentRef = useRef<HTMLDivElement>(null);diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsxindex 160fd9341d..687488b829 100644--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx@@ -18,7 +18,7 @@ import {import { DATA_TYPE_ICON } from "@/components/datasets/icons";import { Button } from "@/components/ui/button";import { cellIdsAtom, useCellActions } from "@/core/cells/cells";-import { lastFocusedCellIdAtom } from "@/core/cells/focus";+import { useLastFocusedCellId } from "@/core/cells/focus";import { atom, useAtomValue } from "jotai";import { Tooltip } from "@/components/ui/tooltip";import { PanelEmptyState } from "./empty-state";@@ -35,7 +35,7 @@ import {maybeAddMarimoImport,} from "@/core/cells/add-missing-import";import { autoInstantiateAtom } from "@/core/config/config";-import {+import type {DataColumnPreview,DataTable,DataTableColumn,@@ -73,7 +73,7 @@ export const DataSourcesPanel: React.FC = () => {const [searchValue, setSearchValue] = React.useState<string>("");const autoInstantiate = useAtomValue(autoInstantiateAtom);- const lastFocusedCellId = useAtomValue(lastFocusedCellIdAtom);+ const lastFocusedCellId = useLastFocusedCellId();const { expandedColumns, expandedTables, columnsPreviews } = useDatasets();const { toggleTable, toggleColumn, closeAllColumns } = useDatasetsActions();const { createNewCell } = useCellActions();diff --git a/frontend/src/components/editor/chrome/panels/scratchpad-panel.tsx b/frontend/src/components/editor/chrome/panels/scratchpad-panel.tsxnew file mode 100644index 0000000000..30351ae536--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/scratchpad-panel.tsx@@ -0,0 +1,7 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { ScratchPad } from "@/components/scratchpad/scratchpad";+import type React from "react";++export const ScratchpadPanel: React.FC = () => {+ return <ScratchPad />;+};diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx b/frontend/src/components/editor/chrome/panels/snippets-panel.tsxindex 620fe66132..201f36ae64 100644--- a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx@@ -22,8 +22,7 @@ import { EditorView } from "@codemirror/view";import { Suspense } from "react";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";-import { useAtomValue } from "jotai";-import { lastFocusedCellIdAtom } from "@/core/cells/focus";+import { useLastFocusedCellId } from "@/core/cells/focus";import { useCellActions } from "@/core/cells/cells";import { cn } from "@/utils/cn";import { ContributeSnippetButton } from "../components/contribute-snippet-button";@@ -99,7 +98,7 @@ export const SnippetsPanel: React.FC = () => {const SnippetViewer: React.FC<{ snippet: Snippet }> = ({ snippet }) => {const { theme } = useTheme();const { createNewCell } = useCellActions();- const lastFocusedCellId = useAtomValue(lastFocusedCellIdAtom);+ const lastFocusedCellId = useLastFocusedCellId();const handleInsertSnippet = () => {// Add below last focused cell in reverse orderdiff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.tsindex 654241b600..9b1cf5c0de 100644--- a/frontend/src/components/editor/chrome/types.ts+++ b/frontend/src/components/editor/chrome/types.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { Objects } from "@/utils/objects";+import { getFeatureFlag } from "@/core/config/feature-flag";import {XCircleIcon,FolderTreeIcon,@@ -11,6 +11,7 @@ import {type LucideIcon,SquareDashedBottomCodeIcon,DatabaseIcon,+ NotebookPenIcon,} from "lucide-react";export type PanelType =@@ -22,18 +23,77 @@ export type PanelType =| "documentation"| "snippets"| "datasources"+ | "scratchpad"| "logs";-export const PANEL_ICONS: Record<PanelType, LucideIcon> = {- errors: XCircleIcon,- files: FolderTreeIcon,- variables: FunctionSquareIcon,- datasources: DatabaseIcon,- dependencies: NetworkIcon,- outline: ScrollTextIcon,- documentation: TextSearchIcon,- logs: FileTextIcon,- snippets: SquareDashedBottomCodeIcon,-};+export interface PanelDescriptor {+ type: PanelType;+ Icon: LucideIcon;+ hidden?: boolean;+ tooltip: string;+ position: "sidebar" | "footer";+}-export const PANEL_TYPES: PanelType[] = Objects.keys(PANEL_ICONS);+export const PANELS: PanelDescriptor[] = [+ {+ type: "files",+ Icon: FolderTreeIcon,+ tooltip: "View files",+ position: "sidebar",+ },+ {+ type: "variables",+ Icon: FunctionSquareIcon,+ tooltip: "Explore variables",+ position: "sidebar",+ },+ {+ type: "datasources",+ Icon: DatabaseIcon,+ tooltip: "Explore data sources",+ position: "sidebar",+ },+ {+ type: "dependencies",+ Icon: NetworkIcon,+ tooltip: "Explore dependencies",+ position: "sidebar",+ },+ {+ type: "outline",+ Icon: ScrollTextIcon,+ tooltip: "View outline",+ position: "sidebar",+ },+ {+ type: "documentation",+ Icon: TextSearchIcon,+ tooltip: "View live docs",+ position: "sidebar",+ },+ {+ type: "logs",+ Icon: FileTextIcon,+ tooltip: "Notebook logs",+ position: "sidebar",+ },+ {+ type: "snippets",+ Icon: SquareDashedBottomCodeIcon,+ tooltip: "Snippets",+ position: "sidebar",+ },+ {+ type: "scratchpad",+ Icon: NotebookPenIcon,+ hidden: !getFeatureFlag("scratchpad"),+ tooltip: "Scratchpad",+ position: "sidebar",+ },+ {+ type: "errors",+ Icon: XCircleIcon,+ tooltip: "View errors",+ position: "footer",+ },+];diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsxindex 98773eaa7d..01c515d43a 100644--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx@@ -24,6 +24,7 @@ import { FileExplorerPanel } from "../panels/file-explorer-panel";import { SnippetsPanel } from "../panels/snippets-panel";import { ErrorBoundary } from "../../boundary/ErrorBoundary";import { DataSourcesPanel } from "../panels/datasources-panel";+import { ScratchpadPanel } from "../panels/scratchpad-panel";export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {const { isOpen, selectedPanel } = useChromeState();@@ -105,6 +106,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {{selectedPanel === "datasources" && <DataSourcesPanel />}{selectedPanel === "documentation" && <DocumentationPanel />}{selectedPanel === "snippets" && <SnippetsPanel />}+ {selectedPanel === "scratchpad" && <ScratchpadPanel />}{selectedPanel === "logs" && <LogsPanel />}</div></Suspense>diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsxindex 6c2dee1cb3..fed266dc23 100644--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx@@ -1,17 +1,19 @@/* Copyright 2024 Marimo. All rights reserved. */-import React, { PropsWithChildren } from "react";+import type React from "react";+import type { PropsWithChildren } from "react";import { cn } from "@/utils/cn";import { useChromeActions, useChromeState } from "../state";import { Tooltip } from "@/components/ui/tooltip";import { useAtomValue } from "jotai";import { cellErrorCount } from "@/core/cells/cells";-import { PANEL_ICONS, PanelType } from "../types";+import { type PanelDescriptor, PANELS } from "../types";import { MachineStats } from "./machine-stats";import { useUserConfig } from "@/core/config/config";import { ZapIcon, ZapOffIcon } from "lucide-react";import { saveUserConfig } from "@/core/network/requests";-import { UserConfig } from "@/core/config/config-schema";+import type { UserConfig } from "@/core/config/config-schema";import { ShowInKioskMode } from "../../kiosk-mode";+import { invariant } from "@/utils/invariant";export const Footer: React.FC = () => {const { selectedPanel } = useChromeState();@@ -19,19 +21,21 @@ export const Footer: React.FC = () => {const [config, setConfig] = useUserConfig();const errorCount = useAtomValue(cellErrorCount);- const renderIcon = (type: PanelType, className?: string) => {- const Icon = PANEL_ICONS[type];+ const renderIcon = ({ Icon }: PanelDescriptor, className?: string) => {return <Icon className={cn("h-5 w-5", className)} />;};+ const errorPanel = PANELS.find((p) => p.type === "errors");+ invariant(errorPanel, "Error panel not found");+return (<footer className="h-10 py-2 bg-background flex items-center text-muted-foreground text-md pl-1 pr-4 border-t border-border select-none no-print text-sm shadow-[0_0_4px_1px_rgba(0,0,0,0.1)] z-50"><FooterItem- tooltip="View errors"- selected={selectedPanel === "errors"}- onClick={() => openApplication("errors")}+ tooltip={errorPanel.tooltip}+ selected={selectedPanel === errorPanel.type}+ onClick={() => openApplication(errorPanel.type)}>- {renderIcon("errors", errorCount > 0 ? "text-destructive" : "")}+ {renderIcon(errorPanel, errorCount > 0 ? "text-destructive" : "")}<span className="ml-1 font-mono mt-[0.125rem]">{errorCount}</span></FooterItem>diff --git a/frontend/src/components/editor/chrome/wrapper/sidebar.tsx b/frontend/src/components/editor/chrome/wrapper/sidebar.tsxindex f57fedce1b..748229163e 100644--- a/frontend/src/components/editor/chrome/wrapper/sidebar.tsx+++ b/frontend/src/components/editor/chrome/wrapper/sidebar.tsx@@ -6,75 +6,32 @@ import { cn } from "@/utils/cn";import { useChromeActions, useChromeState } from "../state";import { Tooltip } from "@/components/ui/tooltip";import { FeedbackButton } from "../components/feedback-button";-import { PANEL_ICONS, type PanelType } from "../types";+import { type PanelDescriptor, PANELS } from "../types";export const Sidebar: React.FC = () => {const { selectedPanel } = useChromeState();const { openApplication } = useChromeActions();- const renderIcon = (type: PanelType, className?: string) => {- const Icon = PANEL_ICONS[type];+ const renderIcon = ({ Icon }: PanelDescriptor, className?: string) => {return <Icon className={cn("h-5 w-5", className)} />;};+ const sidebarItems = PANELS.filter(+ (p) => !p.hidden && p.position === "sidebar",+ );+return (<div className="h-full py-4 px-1 flex flex-col items-start text-muted-foreground text-md select-none no-print text-sm z-50 dark:bg-background">- <SidebarItem- tooltip="View files"- selected={selectedPanel === "files"}- onClick={() => openApplication("files")}- >- {renderIcon("files")}- </SidebarItem>- <SidebarItem- tooltip="Explore variables"- selected={selectedPanel === "variables"}- onClick={() => openApplication("variables")}- >- {renderIcon("variables")}- </SidebarItem>- <SidebarItem- tooltip="Explore data sources"- selected={selectedPanel === "datasources"}- onClick={() => openApplication("datasources")}- >- {renderIcon("datasources")}- </SidebarItem>- <SidebarItem- tooltip="Explore dependencies"- selected={selectedPanel === "dependencies"}- onClick={() => openApplication("dependencies")}- >- {renderIcon("dependencies")}- </SidebarItem>- <SidebarItem- tooltip="View outline"- selected={selectedPanel === "outline"}- onClick={() => openApplication("outline")}- >- {renderIcon("outline")}- </SidebarItem>- <SidebarItem- tooltip="View live docs"- selected={selectedPanel === "documentation"}- onClick={() => openApplication("documentation")}- >- {renderIcon("documentation")}- </SidebarItem>- <SidebarItem- tooltip="Notebook logs"- selected={selectedPanel === "logs"}- onClick={() => openApplication("logs")}- >- {renderIcon("logs")}- </SidebarItem>- <SidebarItem- tooltip="Snippets"- selected={selectedPanel === "snippets"}- onClick={() => openApplication("snippets")}- >- {renderIcon("snippets")}- </SidebarItem>+ {sidebarItems.map((p) => (+ <SidebarItem+ key={p.type}+ tooltip={p.tooltip}+ selected={selectedPanel === p.type}+ onClick={() => openApplication(p.type)}+ >+ {renderIcon(p)}+ </SidebarItem>+ ))}<FeedbackButton><SidebarItem tooltip="Send feedback!" selected={false}>diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsxindex e0c4c13946..248b54f9d9 100644--- a/frontend/src/components/editor/file-tree/file-explorer.tsx+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx@@ -172,7 +172,6 @@ const Toolbar = ({ onRefresh }: { onRefresh: () => void }) => {className={buttonVariants({variant: "text",size: "xs",- className: "mb-0",})}><UploadIcon size={16} />@@ -185,7 +184,6 @@ const Toolbar = ({ onRefresh }: { onRefresh: () => void }) => {onClick={onRefresh}variant="text"size="xs"- className="mb-0"><RefreshCcwIcon size={16} /></Button>diff --git a/frontend/src/components/editor/header/filename-input.tsx b/frontend/src/components/editor/header/filename-input.tsxindex a0626e76a3..2420696f95 100644--- a/frontend/src/components/editor/header/filename-input.tsx+++ b/frontend/src/components/editor/header/filename-input.tsx@@ -17,10 +17,10 @@ import { FilePenIcon } from "lucide-react";import { FILE_TYPE_ICONS, guessFileType } from "../file-tree/types";import { Popover, PopoverContent } from "../../ui/popover";import { PopoverAnchor } from "@radix-ui/react-popover";-import { FileInfo } from "@/core/network/types";+import type { FileInfo } from "@/core/network/types";+import { getFeatureFlag } from "@/core/config/feature-flag";import "./filename-input.css";-import { getFeatureFlag } from "@/core/config/feature-flag";interface FilenameInputProps {resetOnBlur?: boolean;diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/ConsoleOutput.tsxindex 8ff82a2963..aa008ef916 100644--- a/frontend/src/components/editor/output/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/ConsoleOutput.tsx@@ -1,14 +1,14 @@/* Copyright 2024 Marimo. All rights reserved. */import React, { useLayoutEffect } from "react";-import { OutputMessage } from "@/core/kernel/messages";+import type { OutputMessage } from "@/core/kernel/messages";import { OutputRenderer } from "../Output";import { cn } from "@/utils/cn";import { DEFAULT_CELL_NAME } from "@/core/cells/names";import { NameCellContentEditable } from "../actions/name-cell-input";-import { CellId } from "@/core/cells/ids";+import type { CellId } from "@/core/cells/ids";import { Input } from "@/components/ui/input";import { AnsiUp } from "ansi_up";-import { WithResponse } from "@/core/cells/types";+import type { WithResponse } from "@/core/cells/types";import { invariant } from "@/utils/invariant";const ansiUp = new AnsiUp();@@ -16,6 +16,7 @@ const ansiUp = new AnsiUp();interface Props {cellId: CellId;cellName: string;+ className?: string;consoleOutputs: Array<WithResponse<OutputMessage>>;stale: boolean;debuggerActive: boolean;@@ -24,7 +25,14 @@ interface Props {export const ConsoleOutput = (props: Props): React.ReactNode => {const ref = React.useRef<HTMLDivElement>(null);- const { consoleOutputs, stale, cellName, cellId, onSubmitDebugger } = props;+ const {+ consoleOutputs,+ stale,+ cellName,+ cellId,+ onSubmitDebugger,+ className,+ } = props;/* The debugger UI needs some work. For now just use the regular/* console output. */@@ -82,6 +90,7 @@ export const ConsoleOutput = (props: Props): React.ReactNode => {"console-output-area overflow-hidden rounded-b-lg flex flex-col-reverse w-full",stale && "marimo-output-stale",hasOutputs ? "p-5" : "p-3",+ className,)}>{reversedOutputs.map((output, idx) => {diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsxnew file mode 100644index 0000000000..f744a8b2ed--- /dev/null+++ b/frontend/src/components/scratchpad/scratchpad.tsx@@ -0,0 +1,128 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type React from "react";+import { useUserConfig } from "@/core/config/config";+import { useRef } from "react";+import { useTheme } from "@/theme/useTheme";+import { CellEditor } from "../editor/cell/code/cell-editor";+import { HTMLCellId } from "@/core/cells/ids";+import { Functions } from "@/utils/functions";+import type { EditorView } from "@codemirror/view";+import useEvent from "react-use-event-hook";+import { sendRunScratchpad } from "@/core/network/requests";+import { OutputArea } from "../editor/Output";+import { ConsoleOutput } from "../editor/output/ConsoleOutput";+import {+ SCRATCH_CELL_ID,+ useCellActions,+ useNotebook,+} from "@/core/cells/cells";+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 { HideInKioskMode } from "../editor/kiosk-mode";+import { useLastFocusedCellId } from "@/core/cells/focus";++export const ScratchPad: React.FC = () => {+ const notebookState = useNotebook();+ const [userConfig] = useUserConfig();+ const { theme } = useTheme();+ const ref = useRef<EditorView>(null);+ const lastFocusedCellId = useLastFocusedCellId();+ const { createNewCell, updateCellCode } = useCellActions();++ const cellId = SCRATCH_CELL_ID;+ const cellRuntime = notebookState.cellRuntime[cellId];+ const output = cellRuntime?.output;+ const consoleOutputs = cellRuntime?.consoleOutputs;+ const cellData = notebookState.cellData[cellId];+ const code = cellData?.code ?? "";++ const handleRun = useEvent(() => {+ sendRunScratchpad({ code });+ });++ const handleInsertCode = useEvent(() => {+ createNewCell({+ code,+ before: false,+ cellId: lastFocusedCellId ?? "__end__",+ });+ });++ 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>+ <Tooltip content={renderShortcut("cell.run")}>+ <Button+ data-testid="scratchpad-run-button"+ onClick={handleRun}+ variant="text"+ // className="bg-[var(--grass-3)] hover:bg-[var(--grass-4)] rounded-none"+ size="xs"+ >+ <PlayIcon color="var(--grass-11)" size={16} />+ </Button>+ </Tooltip>+ </div>+ <div>+ <HideInKioskMode>+ <Tooltip content="Insert code">+ <Button size="xs" variant="text" onClick={handleInsertCode}>+ <BetweenHorizontalStartIcon size={16} />+ </Button>+ </Tooltip>+ </HideInKioskMode>+ </div>+ </div>+ <div className="overflow-auto flex-shrink-0 max-h-[40%]">+ <CellEditor+ theme={theme}+ showPlaceholder={false}+ allowFocus={false}+ id={cellId}+ code={code}+ status="idle"+ serializedEditorState={null}+ runCell={handleRun}+ updateCellCode={updateCellCode}+ createNewCell={Functions.NOOP}+ deleteCell={Functions.NOOP}+ focusCell={Functions.NOOP}+ moveCell={Functions.NOOP}+ moveToNextCell={Functions.NOOP}+ updateCellConfig={Functions.NOOP}+ clearSerializedEditorState={Functions.NOOP}+ userConfig={userConfig}+ editorViewRef={ref}+ hidden={false}+ />+ </div>+ <div className="flex-1 overflow-auto flex-shrink-0">+ <OutputArea+ allowExpand={false}+ output={output}+ className="output-area"+ cellId={cellId}+ stale={false}+ />+ </div>+ <div className="overflow-auto flex-shrink-0 max-h-[25%]">+ <ConsoleOutput+ consoleOutputs={consoleOutputs}+ className="overflow-auto"+ stale={false}+ cellName={DEFAULT_CELL_NAME}+ onSubmitDebugger={Functions.NOOP}+ cellId={cellId}+ debuggerActive={false}+ />+ </div>+ </div>+ );+};diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.tsindex 99e25caacc..9b507618ed 100644--- a/frontend/src/core/cells/cell.ts+++ b/frontend/src/core/cells/cell.ts@@ -1,10 +1,10 @@/* Copyright 2024 Marimo. All rights reserved. */import { logNever } from "@/utils/assertNever";-import { CellMessage } from "../kernel/messages";-import { CellRuntimeState } from "./types";+import type { CellMessage } from "../kernel/messages";+import type { CellRuntimeState } from "./types";import { collapseConsoleOutputs } from "./collapseConsoleOutputs";import { parseOutline } from "../dom/outline";-import { Seconds, Time } from "@/utils/time";+import { type Seconds, Time } from "@/utils/time";import { invariant } from "@/utils/invariant";export function transitionCell(diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 8759a4b6b9..0ee687184d 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -46,6 +46,8 @@ import { getUserConfig } from "@/core/config/config";import { syncCellIds } from "../network/requests";import { kioskModeAtom } from "../mode";+export const SCRATCH_CELL_ID = "__scratch__" as CellId;+/*** The state of the notebook.*/@@ -92,6 +94,24 @@ export interface LastSavedNotebook {layout: LayoutState;}+function withScratchCell(notebookState: NotebookState): NotebookState {+ return {+ ...notebookState,+ cellData: {+ [SCRATCH_CELL_ID]: createCell({ id: SCRATCH_CELL_ID }),+ ...notebookState.cellData,+ },+ cellRuntime: {+ [SCRATCH_CELL_ID]: createCellRuntimeState(),+ ...notebookState.cellRuntime,+ },+ cellHandles: {+ [SCRATCH_CELL_ID]: createRef(),+ ...notebookState.cellHandles,+ },+ };+}+/*** Initial state of the notebook.*/@@ -143,7 +163,7 @@ function initialNotebookState(): NotebookState {};}- return {+ return withScratchCell({cellIds: [],cellData: {},cellRuntime: {},@@ -151,7 +171,7 @@ function initialNotebookState(): NotebookState {history: [],scrollKey: null,cellLogs: [],- };+ });}/**@@ -419,9 +439,7 @@ const {},) => {const { cellId, code, formattingChange } = action;- const cellIndex = state.cellIds.indexOf(cellId);-- if (cellIndex === -1) {+ if (!state.cellData[cellId]) {return state;}@@ -568,7 +586,7 @@ const {cells.map((cell) => [cell.id, createCellRuntimeState()]),);- return {+ return withScratchCell({...state,cellIds: cells.map((cell) => cell.id),cellData: cellData,@@ -576,7 +594,7 @@ const {cellHandles: Object.fromEntries(cells.map((cell) => [cell.id, createRef()]),),- };+ });},/*** Move focus to next celldiff --git a/frontend/src/core/cells/focus.ts b/frontend/src/core/cells/focus.tsindex 494fd4e974..82078a96b3 100644--- a/frontend/src/core/cells/focus.ts+++ b/frontend/src/core/cells/focus.ts@@ -1,14 +1,27 @@/* Copyright 2024 Marimo. All rights reserved. */-import { atom } from "jotai";+import { atom, useAtomValue, useSetAtom } from "jotai";import type { CellId } from "./ids";-import { type NotebookState, notebookAtom } from "./cells";+import { type NotebookState, SCRATCH_CELL_ID, notebookAtom } from "./cells";import type { EditorView } from "@codemirror/view";-import { CellConfig, CellStatus } from "../network/types";+import type { CellConfig, CellStatus } from "../network/types";/*** Holds state for the last focused cell.*/-export const lastFocusedCellIdAtom = atom<CellId | null>(null);+const lastFocusedCellIdAtom = atom<CellId | null>(null);++export function useLastFocusedCellId() {+ return useAtomValue(lastFocusedCellIdAtom);+}+export function useSetLastFocusedCellId() {+ const setter = useSetAtom(lastFocusedCellIdAtom);+ return (cellId: CellId | null) => {+ if (SCRATCH_CELL_ID === cellId) {+ return;+ }+ setter(cellId);+ };+}export const lastFocusedCellAtom = atom<{name: string;@@ -23,6 +36,10 @@ export const lastFocusedCellAtom = atom<{return null;}+ if (cellId === SCRATCH_CELL_ID) {+ return null;+ }+return cellFocusDetails(cellId, get(notebookAtom));});@@ -36,7 +53,7 @@ function cellFocusDetails(cellId: CellId, notebookState: NotebookState) {const { cellData, cellHandles, cellRuntime } = notebookState;const data = cellData[cellId];const runtime = cellRuntime[cellId];- const handle = cellHandles[cellId].current;+ const handle = cellHandles[cellId]?.current;if (!data || !handle) {return null;}diff --git a/frontend/src/core/codemirror/completion/completer.ts b/frontend/src/core/codemirror/completion/completer.tsindex a5537e4354..a61701d9e7 100644--- a/frontend/src/core/codemirror/completion/completer.ts+++ b/frontend/src/core/codemirror/completion/completer.ts@@ -1,9 +1,12 @@/* Copyright 2024 Marimo. All rights reserved. */-import { CompletionContext, CompletionResult } from "@codemirror/autocomplete";+import type {+ CompletionContext,+ CompletionResult,+} from "@codemirror/autocomplete";import { AUTOCOMPLETER, Autocompleter } from "./Autocompleter";import { Logger } from "../../../utils/Logger";-import { CellId, HTMLCellId } from "@/core/cells/ids";+import { type CellId, HTMLCellId } from "@/core/cells/ids";import { store } from "@/core/state/jotai";import { documentationAtom } from "@/core/documentation/state";diff --git a/frontend/src/core/config/feature-flag.ts b/frontend/src/core/config/feature-flag.tsxsimilarity index 78%rename from frontend/src/core/config/feature-flag.tsrename to frontend/src/core/config/feature-flag.tsxindex eab29159bf..6f9cff0fe9 100644--- a/frontend/src/core/config/feature-flag.ts+++ b/frontend/src/core/config/feature-flag.tsx@@ -9,12 +9,14 @@ import { getUserConfig } from "./config";export interface ExperimentalFeatures {markdown: boolean;wasm_layouts: boolean;+ scratchpad: boolean;// Add new feature flags here}const defaultValues: ExperimentalFeatures = {markdown: true,wasm_layouts: false,+ scratchpad: false,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(@@ -35,5 +37,16 @@ function setFeatureFlag(saveUserConfig({ config: userConfig });}+export const FeatureFlagged: React.FC<{+ feature: keyof ExperimentalFeatures;+ children: React.ReactNode;+}> = ({ feature, children }) => {+ const value = getFeatureFlag(feature);+ if (value) {+ return children;+ }+ return null;+};+// Allow setting feature flags from the consolerepl(setFeatureFlag, "setFeatureFlag");diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.tsindex 67b781668c..8085dc68ac 100644--- a/frontend/src/core/islands/bridge.ts+++ b/frontend/src/core/islands/bridge.ts@@ -125,6 +125,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {getUsageStats = throwNotImplemented;sendRename = throwNotImplemented;sendSave = throwNotImplemented;+ sendRunScratchpad = throwNotImplemented;sendStdin = throwNotImplemented;sendInterrupt = throwNotImplemented;sendShutdown = throwNotImplemented;diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.tsindex 2ae20fa308..3367d4a81a 100644--- a/frontend/src/core/network/requests-network.ts+++ b/frontend/src/core/network/requests-network.ts@@ -64,6 +64,13 @@ export function createNetworkRequests(): EditRequests & RunRequests {}).then(handleResponseReturnNull);},+ sendRunScratchpad: (request) => {+ return marimoClient+ .POST("/api/kernel/scratchpad/run", {+ body: request,+ })+ .then(handleResponseReturnNull);+ },sendInstantiate: (request) => {return marimoClient.POST("/api/kernel/instantiate", {diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.tsindex 937b0a709f..beef5e2dd1 100644--- a/frontend/src/core/network/requests-static.ts+++ b/frontend/src/core/network/requests-static.ts@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { toast } from "@/components/ui/use-toast";-import { EditRequests, RunRequests } from "./types";+import type { EditRequests, RunRequests } from "./types";import { Logger } from "@/utils/Logger";export function createStaticRequests(): EditRequests & RunRequests {@@ -34,6 +34,7 @@ export function createStaticRequests(): EditRequests & RunRequests {sendRestart: throwNotInEditMode,syncCellIds: throwNotInEditMode,sendRun: throwNotInEditMode,+ sendRunScratchpad: throwNotInEditMode,sendRename: throwNotInEditMode,sendSave: throwNotInEditMode,sendInterrupt: throwNotInEditMode,diff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.tsindex d35eb3f98e..b56b697247 100644--- a/frontend/src/core/network/requests-toasting.ts+++ b/frontend/src/core/network/requests-toasting.ts@@ -1,7 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. *//* eslint-disable @typescript-eslint/no-explicit-any */import { toast } from "@/components/ui/use-toast";-import { EditRequests, RequestKey, RunRequests } from "./types";+import type { EditRequests, RequestKey, RunRequests } from "./types";import { Logger } from "@/utils/Logger";import { prettyError } from "@/utils/errors";@@ -15,6 +15,7 @@ export function createErrorToastingRequests(sendRestart: "Failed to restart",syncCellIds: "Failed to sync cell IDs",sendRun: "Failed to run",+ sendRunScratchpad: "Failed to run scratchpad",sendRename: "Failed to rename",sendSave: "Failed to save",sendInterrupt: "Failed to interrupt",diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex 1e71a35862..58c7dd8503 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -36,6 +36,7 @@ export const {sendInterrupt,sendShutdown,sendRun,+ sendRunScratchpad,sendInstantiate,sendDeleteCell,sendCodeCompletionRequest,diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 28a3f0ccd6..54e76c41b1 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */-import { paths, type components } from "@marimo-team/marimo-api";-import { CellId } from "../cells/ids";+import type { paths, components } from "@marimo-team/marimo-api";+import type { CellId } from "../cells/ids";export type schemas = components["schemas"];export type AiCompletionRequest = schemas["AiCompletionRequest"];@@ -52,6 +52,7 @@ export type ReadCodeResponse = schemas["ReadCodeResponse"];export type RecentFilesResponse = schemas["RecentFilesResponse"];export type RenameFileRequest = schemas["RenameFileRequest"];export type RunRequest = schemas["RunRequest"];+export type RunScratchpadRequest = schemas["RunScratchpadRequest"];export type SaveAppConfigurationRequest =schemas["SaveAppConfigurationRequest"];export type SaveNotebookRequest = schemas["SaveNotebookRequest"];@@ -94,6 +95,7 @@ export interface EditRequests {sendSave: (request: SaveNotebookRequest) => Promise<null>;sendStdin: (request: StdinRequest) => Promise<null>;sendRun: (request: RunRequest) => Promise<null>;+ sendRunScratchpad: (request: RunScratchpadRequest) => Promise<null>;sendInterrupt: () => Promise<null>;sendShutdown: () => Promise<null>;sendFormat: (request: FormatRequest) => Promise<FormatResponse>;diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.tsindex 13b293eae3..0f71d4ac0b 100644--- a/frontend/src/core/wasm/bridge.ts+++ b/frontend/src/core/wasm/bridge.ts@@ -201,6 +201,12 @@ export class PyodideBridge implements RunRequests, EditRequests {await this.putControlRequest(request);return null;};+ sendRunScratchpad: EditRequests["sendRunScratchpad"] = async (request) => {+ await this.rpc.proxy.request.loadPackages(request.code);++ await this.putControlRequest(request);+ return null;+ };sendInterrupt: EditRequests["sendInterrupt"] = async () => {if (this.interruptBuffer !== undefined) {// 2 sends a SIGINTdiff --git a/frontend/src/css/app/codemirror.css b/frontend/src/css/app/codemirror.cssindex 546c09e188..1b14b58d9d 100644--- a/frontend/src/css/app/codemirror.css+++ b/frontend/src/css/app/codemirror.css@@ -29,7 +29,7 @@/* -- Tooltips: code completion and type hints -- */-#App .cm-tooltip {+#root .cm-tooltip {border: none;box-shadow: var(--light-shadow);border-radius: 4px;@@ -41,9 +41,9 @@First selector is when there is a tooltip by hoverSecond selector is when there is tooltip by cursorThird selector is during code completion */-#App .cm-tooltip.cm-tooltip-hover,-#App .cm-tooltip.mo-cm-tooltip,-#App .cm-tooltip.cm-completionInfo {+#root .cm-tooltip.cm-tooltip-hover,+#root .cm-tooltip.mo-cm-tooltip,+#root .cm-tooltip.cm-completionInfo {max-height: 45vh; /* 45% of viewport height */max-width: 40vw; /* 40% of viewport width */overflow: auto;@@ -54,33 +54,33 @@}/* Hover tooltips get highest priority in display. */-#App .cm-tooltip.cm-tooltip-hover {+#root .cm-tooltip.cm-tooltip-hover {z-index: 1000;}/* -- Completion Info -- *//* Compeletion Symbol */-#App .cm-tooltip-autocomplete {+#root .cm-tooltip-autocomplete {/* CodeMirror's default is too wide. */max-width: 200px;}-#App .cm-tooltip.cm-tooltip-autocomplete > ul {+#root .cm-tooltip.cm-tooltip-autocomplete > ul {min-width: unset;}-#App .cm-tooltip-autocomplete ul li[aria-selected] {+#root .cm-tooltip-autocomplete ul li[aria-selected] {background: #1177ccb0;max-width: 200px;}-.dark #App .cm-tooltip-autocomplete ul li[aria-selected] {+.dark #root .cm-tooltip-autocomplete ul li[aria-selected] {background: #1177cc80;max-width: 200px;}-#App .cm-tooltip.cm-completionInfo {+#root .cm-tooltip.cm-completionInfo {/* Codemirror generates an inline style for these properties,* so we have to override them with !important. */top: 0 !important;@@ -89,7 +89,7 @@max-width: 36rem !important;}-#App .cm-completionInfo.cm-completionInfo-right-narrow {+#root .cm-completionInfo.cm-completionInfo-right-narrow {/* CodeMirror's default makes the completionInfo overlap with the* compeletion symbol */left: 100%;@@ -98,13 +98,13 @@/* Completion Info may show up to the left or right of another menu item.First is the parent (completion list)Second is the child (completion info) */-#App .cm-tooltip:has(.cm-completionInfo-left),-#App .cm-tooltip.cm-completionInfo-right {+#root .cm-tooltip:has(.cm-completionInfo-left),+#root .cm-tooltip.cm-completionInfo-right {border-top-left-radius: 0;}-#App .cm-tooltip:has(.cm-completionInfo-right),-#App .cm-tooltip.cm-completionInfo-left {+#root .cm-tooltip:has(.cm-completionInfo-right),+#root .cm-tooltip.cm-completionInfo-left {border-top-right-radius: 0;}diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex d10fab1289..f732cd6be6 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -133,6 +133,7 @@ def _generate_schema() -> dict[str, Any]:models.ReadCodeResponse,models.RenameFileRequest,models.RunRequest,+ models.RunScratchpadRequest,models.SaveAppConfigurationRequest,models.SaveNotebookRequest,models.SaveUserConfigurationRequest,@@ -144,6 +145,7 @@ def _generate_schema() -> dict[str, Any]:requests.CreationRequest,requests.DeleteCellRequest,requests.ExecuteMultipleRequest,+ requests.ExecuteScratchpadRequest,requests.ExecuteStaleRequest,requests.ExecutionRequest,requests.FunctionCallRequest,diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 687d0e0a23..b32c8177ed 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -49,6 +49,11 @@ class ExecuteMultipleRequest:), "Mismatched cell_ids and codes"+@dataclass+class ExecuteScratchpadRequest:+ code: str++@dataclassclass SetUIElementValueRequest:object_ids: List[UIElementId]@@ -149,6 +154,7 @@ class PreviewDatasetColumnRequest:ControlRequest = Union[ExecuteMultipleRequest,+ ExecuteScratchpadRequest,ExecuteStaleRequest,CreationRequest,DeleteCellRequest,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex ad78175681..699f664ea8 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -89,6 +89,7 @@ from marimo._runtime.requests import (CreationRequest,DeleteCellRequest,ExecuteMultipleRequest,+ ExecuteScratchpadRequest,ExecuteStaleRequest,ExecutionRequest,FunctionCallRequest,@@ -110,6 +111,7 @@ from marimo._runtime.runner.hooks_on_finish import OnFinishHookTypefrom marimo._runtime.runner.hooks_post_execution import PostExecutionHookTypefrom marimo._runtime.runner.hooks_pre_execution import PreExecutionHookTypefrom marimo._runtime.runner.hooks_preparation import PreparationHookType+from marimo._runtime.scratch import SCRATCH_CELL_IDfrom marimo._runtime.state import Statefrom marimo._runtime.utils.set_ui_element_request_manager import (SetUIElementRequestManager,@@ -754,6 +756,8 @@ class Kernel:syntax_errors[er.cell_id] = errorfor dr in deletion_requests:+ if dr.cell_id not in cells_before_mutation:+ continuecells_that_were_children_of_mutated_cells |= self._delete_cell(dr.cell_id)@@ -1035,8 +1039,44 @@ class Kernel:"""await self._run_cells(- self.mutate_graph(execution_requests, deletion_requests=[])+ self.mutate_graph(+ execution_requests,+ deletion_requests=[+ # Always delete the scratchpad cell+ DeleteCellRequest(cell_id=SCRATCH_CELL_ID)+ ],+ )+ )++ async def run_scratchpad(self, request: ExecuteScratchpadRequest) -> None:+ LOGGER.warning("Running scratchpad cell")+ roots = {SCRATCH_CELL_ID}+ # Mutated graph by adding scratchpad cell+ self.mutate_graph(+ execution_requests=[+ ExecutionRequest(SCRATCH_CELL_ID, request.code)+ ],+ deletion_requests=[],)+ runner = cell_runner.Runner(+ roots=roots,+ graph=self.graph,+ glbls=self.globals,+ excluded_cells=set(self.errors.keys()),+ 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],+ 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]+ ),+ )++ await runner.run_all()async def run_stale_cells(self) -> None:cells_to_run: set[CellId_t] = set()@@ -1481,6 +1521,8 @@ class Kernel:elif isinstance(request, ExecuteMultipleRequest):await self.run(request.execution_requests)CompletedRun().broadcast()+ elif isinstance(request, ExecuteScratchpadRequest):+ await self.run_scratchpad(request)elif isinstance(request, ExecuteStaleRequest):await self.run_stale_cells()elif isinstance(request, SetCellConfigRequest):diff --git a/marimo/_runtime/scratch.py b/marimo/_runtime/scratch.pynew file mode 100644index 0000000000..13cf16b97c--- /dev/null+++ b/marimo/_runtime/scratch.py@@ -0,0 +1,6 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo._ast.cell import CellId_t++SCRATCH_CELL_ID: CellId_t = "__scratch__"diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.pyindex 2eebd3b62b..8d1adaba17 100644--- a/marimo/_server/api/endpoints/execution.py+++ b/marimo/_server/api/endpoints/execution.py@@ -17,6 +17,7 @@ from marimo._server.models.models import (BaseResponse,InstantiateRequest,RunRequest,+ RunScratchpadRequest,SuccessResponse,UpdateComponentValuesRequest,)@@ -164,6 +165,35 @@ async def run_cell(return SuccessResponse()[email protected]("/scratchpad/run")+@requires("edit")+async def run_scratchpad(+ *,+ request: Request,+) -> BaseResponse:+ """+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/RunScratchpadRequest"+ responses:+ 200:+ description: Run the scratchpad+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/SuccessResponse"+ """ # noqa: E501+ app_state = AppState(request)+ body = await parse_request(request, cls=RunScratchpadRequest)+ app_state.require_current_session().put_control_request(+ body.as_execution_request()+ )++ return SuccessResponse()++@router.post("/restart_session")@requires("edit")async def restart_session(diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.pyindex d8b11aee36..5509a36eff 100644--- a/marimo/_server/models/models.py+++ b/marimo/_server/models/models.py@@ -6,7 +6,10 @@ from typing import Any, Dict, List, Optionalfrom marimo._ast.cell import CellConfig, CellId_tfrom marimo._config.config import MarimoConfig-from marimo._runtime.requests import ExecuteMultipleRequest+from marimo._runtime.requests import (+ ExecuteMultipleRequest,+ ExecuteScratchpadRequest,+)UIElementId = str@@ -86,6 +89,14 @@ class RunRequest:), "Mismatched cell_ids and codes"+@dataclass+class RunScratchpadRequest:+ code: str++ def as_execution_request(self) -> ExecuteScratchpadRequest:+ return ExecuteScratchpadRequest(code=self.code)++@dataclassclass SaveNotebookRequest:# id of each celldiff --git a/openapi/api.yaml b/openapi/api.yamlindex 74df98b1c2..c3c3d24ded 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -454,6 +454,13 @@ components:- cellIds- codestype: object+ ExecuteScratchpadRequest:+ properties:+ code:+ type: string+ required:+ - code+ type: objectExecuteStaleRequest:properties: {}type: object@@ -1414,6 +1421,13 @@ components:- cellIds- codestype: object+ RunScratchpadRequest:+ properties:+ code:+ type: string+ required:+ - code+ type: objectRunningNotebooksResponse:properties:files:@@ -1719,7 +1733,7 @@ components:type: objectinfo:title: marimo API- version: 0.7.2+ version: 0.7.5openapi: 3.1.0paths:/@file/{filename_and_length}:@@ -2159,6 +2173,20 @@ paths:$ref: '#/components/schemas/SuccessResponse'description: Update the user config on disk and in the kernel. Only allowedin edit mode.+ /api/kernel/scratchpad/run:+ post:+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RunScratchpadRequest'+ responses:+ 200:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SuccessResponse'+ description: Run the scratchpad/api/kernel/set_cell_config:post:requestBody:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex fca178d88b..3c828540ef 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -557,6 +557,23 @@ export interface paths {};};};+ "/api/kernel/scratchpad/run": {+ post: {+ requestBody?: {+ content: {+ "application/json": components["schemas"]["RunScratchpadRequest"];+ };+ };+ responses: {+ /** @description Run the scratchpad */+ 200: {+ content: {+ "application/json": components["schemas"]["SuccessResponse"];+ };+ };+ };+ };+ };"/api/kernel/set_cell_config": {post: {requestBody?: {@@ -916,6 +933,9 @@ export interface components {cellIds: string[];codes: string[];};+ ExecuteScratchpadRequest: {+ code: string;+ };ExecuteStaleRequest: Record<string, never>;ExecutionRequest: {cellId: string;@@ -1311,6 +1331,9 @@ export interface components {cellIds: string[];codes: string[];};+ RunScratchpadRequest: {+ code: string;+ };RunningNotebooksResponse: {files: components["schemas"]["MarimoFile"][];};diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.pyindex b6d7c356b6..079221f75d 100644--- a/tests/_server/api/endpoints/test_execution.py+++ b/tests/_server/api/endpoints/test_execution.py@@ -104,6 +104,18 @@ class TestExecutionRoutes_EditMode:assert response.headers["content-type"] == "application/json"assert "success" in response.json()+ @staticmethod+ @with_session(SESSION_ID)+ def test_run_scratchpad(client: TestClient) -> None:+ response = client.post(+ "/api/kernel/scratchpad/run",+ headers=HEADERS,+ json={"code": "print('Hello, scratchpad')"},+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert "success" in response.json()+class TestExecutionRoutes_RunMode:@staticmethod@@ -177,3 +189,13 @@ class TestExecutionRoutes_RunMode:},)assert response.status_code == 401, response.text++ @staticmethod+ @with_read_session(SESSION_ID)+ def test_run_scratchpad(client: TestClient) -> None:+ response = client.post(+ "/api/kernel/scratchpad/run",+ headers=HEADERS,+ json={"code": "print('Hello, scratchpad')"},+ )+ assert response.status_code == 401, response.text