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
feat: pdb (#586)
Myles Scolnickc686986188f8
diff --git a/frontend/src/components/debugger/debugger-code.css b/frontend/src/components/debugger/debugger-code.cssnew file mode 100644index 0000000000..59b8e01a01--- /dev/null+++ b/frontend/src/components/debugger/debugger-code.css@@ -0,0 +1,3 @@+.debugger-input .cm-gutterElement.cm-activeLineGutter {+ background-color: #bdc8d2;+}diff --git a/frontend/src/components/debugger/debugger-code.tsx b/frontend/src/components/debugger/debugger-code.tsxnew file mode 100644index 0000000000..083d173f58--- /dev/null+++ b/frontend/src/components/debugger/debugger-code.tsx@@ -0,0 +1,195 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { langs } from "@uiw/codemirror-extensions-langs";+import ReactCodeMirror, {+ EditorView,+ Prec,+ ReactCodeMirrorRef,+ keymap,+} from "@uiw/react-codemirror";+import React, { memo } from "react";+import { Tooltip } from "../ui/tooltip";+import {+ HelpCircleIcon,+ LayersIcon,+ PlayIcon,+ SkipForwardIcon,+} from "lucide-react";+import { Button } from "../ui/button";+import { cn } from "@/utils/cn";+import "./debugger-code.css";+import { useKeydownOnElement } from "@/hooks/useHotkey";+import { Functions } from "@/utils/functions";++interface Props {+ code: string;+ onSubmit: (code: string) => void;+}++export const Debugger: React.FC<Props> = ({ code, onSubmit }) => {+ return (+ <div className="flex flex-col w-full rounded-b overflow-hidden">+ <DebuggerOutput code={code} />+ <DebuggerInput onSubmit={onSubmit} />+ <DebuggerControls onSubmit={onSubmit} />+ </div>+ );+};++const DebuggerOutput: React.FC<{+ code: string;+}> = memo((props) => {+ const ref = React.useRef<ReactCodeMirrorRef>({});++ return (+ <ReactCodeMirror+ minHeight="200px"+ maxHeight="200px"+ ref={ref}+ theme="dark"+ value={props.code}+ className={`[&>*]:outline-none [&>.cm-editor]:pr-0 overflow-hidden dark`}+ readOnly={true}+ editable={false}+ basicSetup={{+ lineNumbers: false,+ }}+ extensions={[+ langs.shell(),+ EditorView.updateListener.of((update) => {+ if (update.docChanged) {+ ref.current.view?.dispatch({+ selection: {+ anchor: update.state.doc.length,+ head: update.state.doc.length,+ },+ scrollIntoView: true,+ });+ }+ }),+ ]}+ />+ );+});+DebuggerOutput.displayName = "DebuggerOutput";++const DebuggerInput: React.FC<{+ onSubmit: (code: string) => void;+}> = ({ onSubmit }) => {+ const [value, setValue] = React.useState("");+ const ref = React.useRef<HTMLDivElement>(null);++ // Capture some events to prevent default behavior+ useKeydownOnElement(ref.current, {+ ArrowUp: Functions.NOOP,+ ArrowDown: Functions.NOOP,+ });++ return (+ <div ref={ref}>+ <ReactCodeMirror+ minHeight="18px"+ theme="dark"+ className={`debugger-input [&>*]:outline-none cm-focused [&>.cm-editor]:pr-0 overflow-hidden dark border-t-4`}+ value={value}+ autoFocus={true}+ basicSetup={{+ lineNumbers: false,+ }}+ extensions={[+ langs.python(),+ Prec.highest(+ keymap.of([+ {+ key: "Enter",+ preventDefault: true,+ stopPropagation: true,+ run: (view: EditorView) => {+ const v = value.trim().replaceAll("\n", "\\n");+ if (!v) {+ return true;+ }+ onSubmit(v);+ setValue("");+ return true;+ },+ },+ {+ key: "Shift-Enter",+ preventDefault: true,+ stopPropagation: true,+ run: (view: EditorView) => {+ // Insert newline and move cursor to end of line+ view.dispatch({+ changes: {+ from: view.state.selection.main.to,+ insert: "\n",+ },+ });++ return true;+ },+ },+ ])+ ),+ ]}+ onChange={(value) => setValue(value)}+ />+ </div>+ );+};++const DebuggerControls: React.FC<{+ onSubmit: (code: string) => void;+}> = ({ onSubmit }) => {+ const buttonClasses =+ "border m-0 w-9 h-7 bg-[var(--blue-2)] text-[var(--slate-11)] hover:text-[var(--blue-11)] rounded-none border-[var(--blue-2)] hover:bg-[var(--sky-3)] hover:border-[var(--blue-8)]";+ const iconClasses = "w-5 h-5";++ return (+ <div className="flex">+ <Tooltip content="Next line">+ <Button+ variant="text"+ size="icon"+ className={cn(buttonClasses, "rounded-bl-lg")}+ onClick={() => onSubmit("n")}+ >+ <SkipForwardIcon fontSize={36} className={iconClasses} />+ </Button>+ </Tooltip>+ <Tooltip content="Continue execution">+ <Button+ variant="text"+ size="icon"+ onClick={() => onSubmit("c")}+ className={cn(+ buttonClasses,+ "text-[var(--grass-11)] hover:text-[var(--grass-11)] hover:bg-[var(--grass-3)] hover:border-[var(--grass-8)]"+ )}+ >+ <PlayIcon fontSize={36} className={iconClasses} />+ </Button>+ </Tooltip>+ <Tooltip content="Print stack trace">+ <Button+ variant="text"+ size="icon"+ className={buttonClasses}+ onClick={() => onSubmit("bt")}+ >+ <LayersIcon fontSize={36} className={iconClasses} />+ </Button>+ </Tooltip>+ <Tooltip content="Help">+ <Button+ variant="text"+ size="icon"+ className={buttonClasses}+ onClick={() => onSubmit("help")}+ >+ <HelpCircleIcon fontSize={36} className={iconClasses} />+ </Button>+ </Tooltip>+ </div>+ );+};diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex 9397423ca6..7375ee4b5a 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -29,7 +29,6 @@ import { renderShortcut } from "../shortcuts/renderShortcut";import { useCellRenderCount } from "../../hooks/useCellRenderCount";import { Functions } from "../../utils/functions";import { Logger } from "../../utils/Logger";-import { SerializedEditorState } from "../../core/codemirror/types";import { CellDragHandle, SortableCell } from "./SortableCell";import { HTMLCellId } from "../../core/cells/ids";import { Theme } from "../../theme/useTheme";@@ -69,8 +68,12 @@ export interface CellProps| "stopped"| "runStartTimestamp"| "runElapsedTimeMs"+ | "debuggerActive"+ >,+ Pick<+ CellData,+ "id" | "code" | "edited" | "config" | "name" | "serializedEditorState">,- Pick<CellData, "id" | "code" | "edited" | "config" | "name">,Pick<CellActions,| "updateCellCode"@@ -87,7 +90,6 @@ export interface CellProps> {theme: Theme;showPlaceholder: boolean;- serializedEditorState: SerializedEditorState | null;mode: AppMode;appClosed: boolean;showDeleteButton: boolean;@@ -118,6 +120,7 @@ const CellComponent = (stopped,serializedEditorState,mode,+ debuggerActive,appClosed,showDeleteButton,updateCellCode,@@ -449,6 +452,7 @@ const CellComponent = (sendStdin({ text });}}cellId={cellId}+ debuggerActive={debuggerActive}/></SortableCell></CellActionsContextMenu>diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 95eda45c94..ac73711d6d 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -16,7 +16,6 @@ import { AppMode } from "@/core/mode";import useEvent from "react-use-event-hook";import { CellActions, useCellActions } from "@/core/cells/cells";import { CellRuntimeState, CellData, CellConfig } from "@/core/cells/types";-import { SerializedEditorState } from "@/core/codemirror/types";import { UserConfig } from "@/core/config/config-schema";import { Theme } from "@/theme/useTheme";import {@@ -32,7 +31,7 @@ import { HideCodeButton } from "../../code/readonly-python-code";export interface CellEditorPropsextends Pick<CellRuntimeState, "status">,- Pick<CellData, "id" | "code">,+ Pick<CellData, "id" | "code" | "serializedEditorState">,Pick<CellActions,| "updateCellCode"@@ -46,7 +45,6 @@ export interface CellEditorPropsrunCell: () => void;theme: Theme;showPlaceholder: boolean;- serializedEditorState: SerializedEditorState | null;mode: AppMode;editorViewRef: React.MutableRefObject<EditorView | null>;/**diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/ConsoleOutput.tsxindex 3a9cade9a2..9ab8d21e33 100644--- a/frontend/src/components/editor/output/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/ConsoleOutput.tsx@@ -13,11 +13,24 @@ interface Props {cellName: string;consoleOutputs: OutputMessage[];stale: boolean;+ debuggerActive: boolean;onSubmitDebugger: (text: string, index: number) => void;}export const ConsoleOutput = (props: Props): React.ReactNode => {const { consoleOutputs, stale, cellName, cellId, onSubmitDebugger } = props;++ /* The debugger UI needs some work. For now just use the regular+ /* console output. */+ /* if (debuggerActive) {+ return (+ <Debugger+ code={consoleOutputs.map((output) => output.data).join("\n")}+ onSubmit={(text) => onSubmitDebugger(text, consoleOutputs.length - 1)}+ />+ );+ } */+const hasOutputs = consoleOutputs.length > 0;if (!hasOutputs && cellName === DEFAULT_CELL_NAME) {@@ -35,6 +48,10 @@ export const ConsoleOutput = (props: Props): React.ReactNode => {)}>{consoleOutputs.map((output, idx) => {+ if (output.channel === "pdb") {+ return null;+ }+if (output.channel === "stdin") {if (output.response == null) {return (diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 1c9cabe65b..b043add6b4 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -124,6 +124,7 @@ export const CellArray: React.FC<CellArrayProps> = ({sendToBottom={sendToBottom}sendToTop={sendToTop}userConfig={userConfig}+ debuggerActive={cell.debuggerActive}config={cell.config}name={cell.name}/>diff --git a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snapindex c59d3e75d0..bb0be25725 100644--- a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap+++ b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap@@ -1,10 +1,401 @@// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html+exports[`cell reducer > can initialize stdin 1`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": null,+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": null,+ "serializedEditorState": null,+ "status": "idle",+ "stopped": false,+}+`;++exports[`cell reducer > can initialize stdin 2`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": null,+ "serializedEditorState": null,+ "status": "idle",+ "stopped": false,+}+`;++exports[`cell reducer > can initialize stdin 3`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": null,+ "serializedEditorState": null,+ "status": "queued",+ "stopped": false,+}+`;++exports[`cell reducer > can initialize stdin 4`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": 20,+ "serializedEditorState": null,+ "status": "running",+ "stopped": false,+}+`;++exports[`cell reducer > can initialize stdin 5`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [+ {+ "channel": "stdout",+ "data": "hello!",+ "mimetype": "text/plain",+ "timestamp": 1,+ },+ ],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": 20,+ "serializedEditorState": null,+ "status": "running",+ "stopped": false,+}+`;++exports[`cell reducer > can initialize stdin 6`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [+ {+ "channel": "stdout",+ "data": "hello!",+ "mimetype": "text/plain",+ "timestamp": 1,+ },+ ],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": 20,+ "serializedEditorState": null,+ "status": "running",+ "stopped": false,+}+`;++exports[`cell reducer > can initialize stdin 7`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [+ {+ "channel": "stdout",+ "data": "hello!",+ "mimetype": "text/plain",+ "timestamp": 1,+ },+ {+ "channel": "stdin",+ "data": "what is your name?",+ "mimetype": "text/plain",+ "timestamp": 2,+ },+ ],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": 20,+ "serializedEditorState": null,+ "status": "running",+ "stopped": false,+}+`;++exports[`cell reducer > can initialize stdin 8`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [+ {+ "channel": "stdout",+ "data": "hello!",+ "mimetype": "text/plain",+ "timestamp": 1,+ },+ {+ "channel": "stdin",+ "data": "what is your name?",+ "mimetype": "text/plain",+ "response": "Marimo!",+ "timestamp": 2,+ },+ ],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": 20,+ "serializedEditorState": null,+ "status": "running",+ "stopped": false,+}+`;++exports[`cell reducer > can initialize stdin 9`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [+ {+ "channel": "stdout",+ "data": "hello!",+ "mimetype": "text/plain",+ "timestamp": 1,+ },+ {+ "channel": "stdin",+ "data": "what is your name?",+ "mimetype": "text/plain",+ "response": "Marimo!",+ "timestamp": 2,+ },+ {+ "channel": "stdin",+ "data": "how old are you?",+ "mimetype": "text/plain",+ "timestamp": 3,+ },+ ],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": 20,+ "serializedEditorState": null,+ "status": "running",+ "stopped": false,+}+`;++exports[`cell reducer > can receive console when the cell is idle and will clear when starts again 1`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": null,+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": null,+ "serializedEditorState": null,+ "status": "idle",+ "stopped": false,+}+`;++exports[`cell reducer > can receive console when the cell is idle and will clear when starts again 2`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [+ {+ "channel": "stdout",+ "data": "hello!",+ "mimetype": "text/plain",+ "timestamp": 1,+ },+ ],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": null,+ "serializedEditorState": null,+ "status": "idle",+ "stopped": false,+}+`;++exports[`cell reducer > can receive console when the cell is idle and will clear when starts again 3`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [+ {+ "channel": "stdout",+ "data": "hello!",+ "mimetype": "text/plain",+ "timestamp": 1,+ },+ ],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": null,+ "serializedEditorState": null,+ "status": "queued",+ "stopped": false,+}+`;++exports[`cell reducer > can receive console when the cell is idle and will clear when starts again 4`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": null,+ "runStartTimestamp": 20,+ "serializedEditorState": null,+ "status": "running",+ "stopped": false,+}+`;++exports[`cell reducer > can receive console when the cell is idle and will clear when starts again 5`] = `+{+ "code": "",+ "config": {},+ "consoleOutputs": [+ {+ "channel": "stdin",+ "data": "hello again!",+ "mimetype": "text/plain",+ "timestamp": 2,+ },+ ],+ "debuggerActive": false,+ "edited": false,+ "errored": false,+ "id": "0",+ "interrupted": false,+ "lastCodeRun": "",+ "name": "__",+ "outline": null,+ "output": null,+ "runElapsedTimeMs": 2000,+ "runStartTimestamp": null,+ "serializedEditorState": null,+ "status": "idle",+ "stopped": false,+}+`;+exports[`cell reducer > can run a stale cell 1`] = `{"code": "mo.slider()","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "1",@@ -26,6 +417,7 @@ exports[`cell reducer > can run a stale cell 2`] = `"code": "mo.slider()","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "1",@@ -47,6 +439,7 @@ exports[`cell reducer > can run a stopped cell 1`] = `"code": "mo.md('This has an ancestor that was stopped')","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -68,6 +461,7 @@ exports[`cell reducer > can run a stopped cell 2`] = `"code": "mo.md('This has an ancestor that was stopped')","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -89,6 +483,7 @@ exports[`cell reducer > can run a stopped cell 3`] = `"code": "mo.md('This has an ancestor that was stopped')","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -121,6 +516,7 @@ exports[`cell reducer > can run a stopped cell 4`] = `"code": "mo.md('This has an ancestor that was stopped')","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -153,6 +549,7 @@ exports[`cell reducer > can run a stopped cell 5`] = `"code": "mo.md('This has an ancestor that was stopped')","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -174,6 +571,7 @@ exports[`cell reducer > can run cell and receive cell messages 1`] = `"code": "","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -195,6 +593,7 @@ exports[`cell reducer > can run cell and receive cell messages 2`] = `"code": "import marimo as mo","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": true,"errored": false,"id": "0",@@ -216,6 +615,7 @@ exports[`cell reducer > can run cell and receive cell messages 3`] = `"code": "import marimo as mo","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -237,6 +637,7 @@ exports[`cell reducer > can run cell and receive cell messages 4`] = `"code": "import marimo as mo","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -258,6 +659,7 @@ exports[`cell reducer > can run cell and receive cell messages 5`] = `"code": "import marimo as mo","config": {},"consoleOutputs": [],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -280,12 +682,13 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `"config": {},"consoleOutputs": [{- "channel": "console",+ "channel": "stdout","data": "hello!","mimetype": "text/plain","timestamp": 0,},],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -308,12 +711,13 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `"config": {},"consoleOutputs": [{- "channel": "console",+ "channel": "stdout","data": "hello!hello!","mimetype": "text/plain","timestamp": 0,},],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -342,12 +746,13 @@ import numpy","config": {},"consoleOutputs": [{- "channel": "console",+ "channel": "stdout","data": "hello!hello!","mimetype": "text/plain","timestamp": 0,},],+ "debuggerActive": false,"edited": true,"errored": false,"id": "0",@@ -375,12 +780,13 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `"config": {},"consoleOutputs": [{- "channel": "console",+ "channel": "stdout","data": "hello!hello!","mimetype": "text/plain","timestamp": 0,},],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",@@ -409,12 +815,13 @@ import numpy","config": {},"consoleOutputs": [{- "channel": "console",+ "channel": "stdout","data": "hello!hello!","mimetype": "text/plain","timestamp": 0,},],+ "debuggerActive": false,"edited": true,"errored": false,"id": "0",@@ -443,12 +850,13 @@ import numpy","config": {},"consoleOutputs": [{- "channel": "console",+ "channel": "stdout","data": "hello!hello!","mimetype": "text/plain","timestamp": 0,},],+ "debuggerActive": false,"edited": false,"errored": true,"id": "0",@@ -484,12 +892,13 @@ import numpy","config": {},"consoleOutputs": [{- "channel": "console",+ "channel": "stdout","data": "hello!hello!","mimetype": "text/plain","timestamp": 0,},],+ "debuggerActive": false,"edited": false,"errored": false,"id": "0",diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex d42cc81ed1..2f16fad0ef 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -7,6 +7,7 @@ import {notebookCells,} from "../cells";import { CellId } from "@/core/cells/ids";+import { OutputMessage } from "@/core/kernel/messages";const { initialNotebookState, reducer, createActions } = exportedForTesting;@@ -280,7 +281,7 @@ describe("cell reducer", () => {cell_id: firstCellId,output: null,console: {- channel: "console",+ channel: "stdout",mimetype: "text/plain",data: "hello!",timestamp: 0,@@ -308,7 +309,7 @@ describe("cell reducer", () => {timestamp: 0,},console: {- channel: "console",+ channel: "stdout",mimetype: "text/plain",data: "hello!",timestamp: 0,@@ -570,7 +571,7 @@ describe("cell reducer", () => {timestamp: 0,},console: {- channel: "console",+ channel: "stdout",mimetype: "text/plain",data: "hello!",timestamp: 0,@@ -732,4 +733,257 @@ describe("cell reducer", () => {expect(cell.output).toBe(null);expect(cell).toMatchSnapshot(); // snapshot everything as a catch all});++ it("can initialize stdin", () => {+ const STDOUT: OutputMessage = {+ channel: "stdout",+ mimetype: "text/plain",+ data: "hello!",+ timestamp: 1,+ };+ const STD_IN_1: OutputMessage = {+ channel: "stdin",+ mimetype: "text/plain",+ data: "what is your name?",+ timestamp: 2,+ };+ const STD_IN_2: OutputMessage = {+ channel: "stdin",+ mimetype: "text/plain",+ data: "how old are you?",+ timestamp: 3,+ };++ // Initial state+ let cell = cells[0];+ expect(cell.status).toBe("idle");+ expect(cell.consoleOutputs).toEqual([]);+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Prepare for run+ actions.prepareForRun({+ cellId: firstCellId,+ });+ cell = cells[0];+ expect(cell.status).toBe("idle");+ expect(cell.consoleOutputs).toEqual([]);+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Receive queued messages+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "queued",+ timestamp: new Date(10).getTime(),+ },+ });+ cell = cells[0];+ expect(cell.status).toBe("queued");+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Receive running messages+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "running",+ timestamp: new Date(20).getTime(),+ },+ });+ cell = cells[0];+ expect(cell.status).toBe("running");+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Add console+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: null,+ console: STDOUT,+ status: null,+ timestamp: new Date(22).getTime(),+ },+ });+ cell = cells[0];+ expect(cell.status).toBe("running");+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ cell = cells[0];+ expect(cell.consoleOutputs).toEqual([STDOUT]);+ expect(cell.status).toBe("running");+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Ask via stdin+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: null,+ console: STD_IN_1,+ status: null,+ timestamp: new Date(22).getTime(),+ },+ });+ cell = cells[0];+ expect(cell.consoleOutputs).toEqual([STDOUT, STD_IN_1]);+ expect(cell.status).toBe("running");+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Response to stdin+ actions.setStdinResponse({+ response: "Marimo!",+ cellId: firstCellId,+ outputIndex: 1,+ });+ cell = cells[0];+ expect(cell.consoleOutputs).toEqual([+ STDOUT,+ {+ ...STD_IN_1,+ response: "Marimo!",+ },+ ]);+ expect(cell.status).toBe("running");+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Ask via stdin, again+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: null,+ console: STD_IN_2,+ status: null,+ timestamp: new Date(22).getTime(),+ },+ });+ cell = cells[0];+ expect(cell.consoleOutputs).toEqual([+ STDOUT,+ { ...STD_IN_1, response: "Marimo!" },+ STD_IN_2,+ ]);+ expect(cell.status).toBe("running");+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Interrupt, so we respond with ""+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: {+ channel: "marimo-error",+ mimetype: "application/vnd.marimo+error",+ data: [{ type: "interruption" }],+ timestamp: 0,+ },+ console: null,+ status: "idle",+ timestamp: new Date(61).getTime(),+ },+ });+ cell = cells[0];+ expect(cell.status).toBe("idle");+ expect(cell.consoleOutputs).toEqual([+ STDOUT,+ { ...STD_IN_1, response: "Marimo!" },+ { ...STD_IN_2, response: "" },+ ]);+ });++ it("can receive console when the cell is idle and will clear when starts again", () => {+ const OLD_STDOUT: OutputMessage = {+ channel: "stdout",+ mimetype: "text/plain",+ data: "hello!",+ timestamp: 1,+ };+ const STDOUT: OutputMessage = {+ channel: "stdin",+ mimetype: "text/plain",+ data: "hello again!",+ timestamp: 2,+ };++ // Initial state+ let cell = cells[0];+ expect(cell.status).toBe("idle");+ expect(cell.consoleOutputs).toEqual([]);+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Add console+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: null,+ console: [OLD_STDOUT],+ status: null,+ timestamp: new Date(1).getTime(),+ },+ });++ // Prepare for run+ actions.prepareForRun({+ cellId: firstCellId,+ });+ cell = cells[0];+ expect(cell.status).toBe("idle");+ expect(cell.consoleOutputs).toEqual([OLD_STDOUT]); // Old stays there until it starts running+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Receive queued messages+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: null,+ console: null,+ status: "queued",+ timestamp: new Date(10).getTime(),+ },+ });+ cell = cells[0];+ expect(cell.status).toBe("queued");+ expect(cell.consoleOutputs).toEqual([OLD_STDOUT]); // Old stays there until it starts running+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Receive running messages+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: null,+ console: [], // Backend sends an empty array to clearu+ status: "running",+ timestamp: new Date(20).getTime(),+ },+ });+ cell = cells[0];+ expect(cell.status).toBe("running");+ expect(cell.consoleOutputs).toEqual([]);+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Add console+ actions.handleCellMessage({+ cellId: firstCellId,+ message: {+ cell_id: firstCellId,+ output: null,+ console: [STDOUT],+ status: "idle",+ timestamp: new Date(22).getTime(),+ },+ });+ cell = cells[0];+ expect(cell.consoleOutputs).toEqual([STDOUT]);+ expect(cell.status).toBe("idle");+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all+ });});diff --git a/frontend/src/core/cells/__tests__/collapseConsoleOutputs.test.ts b/frontend/src/core/cells/__tests__/collapseConsoleOutputs.test.tsindex d0bd731da7..bd0a4c9839 100644--- a/frontend/src/core/cells/__tests__/collapseConsoleOutputs.test.ts+++ b/frontend/src/core/cells/__tests__/collapseConsoleOutputs.test.ts@@ -21,7 +21,7 @@ describe("collapseConsoleOutputs", () => {},];const result = collapseConsoleOutputs(consoleOutputs);- expect(result[0].data).toMatchInlineSnapshot('"Hello World"');+ expect(result[0].data).toMatchInlineSnapshot(`"Hello World"`);});it("should not collapse outputs on different channels", () => {@@ -34,7 +34,7 @@ describe("collapseConsoleOutputs", () => {},{mimetype: "text/plain",- channel: "console",+ channel: "stdout",data: "World",timestamp: 0,},diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.tsindex 7372c63765..0bd12060f6 100644--- a/frontend/src/core/cells/cell.ts+++ b/frontend/src/core/cells/cell.ts@@ -1,6 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */import { logNever } from "@/utils/assertNever";-import { CellMessage } from "../kernel/messages";+import { CellMessage, OutputMessage } from "../kernel/messages";import { CellRuntimeState } from "./types";import { collapseConsoleOutputs } from "./collapseConsoleOutputs";import { parseOutline } from "../dom/outline";@@ -18,6 +18,7 @@ export function transitionCell(nextCell.interrupted = false;nextCell.errored = false;nextCell.runElapsedTimeMs = null;+ nextCell.debuggerActive = false;// We intentionally don't update lastCodeRun, since the kernel queues// whatever code was last registered with it, which might not match// the cell's current code if the user modified it.@@ -27,6 +28,10 @@ export function transitionCell(if (cell.stopped) {nextCell.output = null;}+ // If it transitioned from queued to running, remove previous console outputs+ if (nextCell.status === "queued") {+ nextCell.consoleOutputs = [];+ }nextCell.stopped = false;nextCell.runStartTimestamp = message.timestamp;break;@@ -36,6 +41,7 @@ export function transitionCell((message.timestamp - cell.runStartTimestamp) * 1000;nextCell.runStartTimestamp = null;}+ nextCell.debuggerActive = false;break;case null:break;@@ -48,6 +54,7 @@ export function transitionCell(default:logNever(message.status);}+nextCell.output = message.output ?? nextCell.output;nextCell.status = message.status ?? nextCell.status;@@ -85,6 +92,28 @@ export function transitionCell(nextCell.consoleOutputs = consoleOutputs;// Derive outline from outputnextCell.outline = parseOutline(nextCell.output);++ // Transition PDB+ const newConsoleOutputs = [message.console].flat().filter(Boolean);+ const pdbOutputs = newConsoleOutputs.filter(+ (output): output is Extract<OutputMessage, { channel: "pdb" }> =>+ output.channel === "pdb"+ );+ const hasPdbOutput = pdbOutputs.length > 0;+ if (hasPdbOutput && pdbOutputs.some((output) => output.data === "start")) {+ nextCell.debuggerActive = true;+ }+ // If interrupted, remove the debugger and resolve all stdin+ if (nextCell.interrupted || nextCell.errored) {+ nextCell.debuggerActive = false;+ nextCell.consoleOutputs = nextCell.consoleOutputs.map((output) => {+ if (output.channel === "stdin") {+ return { ...output, response: output.response ?? "" };+ }+ return output;+ });+ }+return nextCell;}@@ -98,6 +127,7 @@ export function prepareCellForExecution(nextCell.interrupted = false;nextCell.errored = false;nextCell.runElapsedTimeMs = null;+ nextCell.debuggerActive = false;return nextCell;}diff --git a/frontend/src/core/cells/collapseConsoleOutputs.tsx b/frontend/src/core/cells/collapseConsoleOutputs.tsxindex 6a771688f1..584d8f7093 100644--- a/frontend/src/core/cells/collapseConsoleOutputs.tsx+++ b/frontend/src/core/cells/collapseConsoleOutputs.tsx@@ -6,16 +6,17 @@ import { OutputMessage } from "@/core/kernel/messages";export function collapseConsoleOutputs(consoleOutputs: OutputMessage[]): OutputMessage[] {- // Array.at() not supported in older-but-still-recent versions of Safarilet nextOutput = consoleOutputs[consoleOutputs.length - 1];if (nextOutput.mimetype !== "text/plain") {return consoleOutputs;}+ // Skip stdinif (consoleOutputs.length >= 2 &&consoleOutputs[consoleOutputs.length - 2].mimetype === "text/plain" &&- consoleOutputs[consoleOutputs.length - 2].channel === nextOutput.channel+ consoleOutputs[consoleOutputs.length - 2].channel === nextOutput.channel &&+ nextOutput.channel !== "stdin") {consoleOutputs.pop();consoleOutputs[consoleOutputs.length - 1].data += nextOutput.data;diff --git a/frontend/src/core/cells/logs.ts b/frontend/src/core/cells/logs.tsindex 880492ac46..8662c85dcf 100644--- a/frontend/src/core/cells/logs.ts+++ b/frontend/src/core/cells/logs.ts@@ -17,7 +17,6 @@ export function getCellLogsForMessage(cell: CellMessage): CellLog[] {for (const output of outputs) {if (output.mimetype === "text/plain") {switch (output.channel) {- case "console":case "stdout":logs.push({timestamp: output.timestamp,diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.tsindex f6b1df5ab0..f1a6897b15 100644--- a/frontend/src/core/cells/types.ts+++ b/frontend/src/core/cells/types.ts@@ -55,6 +55,7 @@ export function createCellRuntimeState(): CellRuntimeState {stopped: false,runElapsedTimeMs: null,runStartTimestamp: null,+ debuggerActive: false,};}@@ -99,6 +100,8 @@ export interface CellRuntimeState {runStartTimestamp: number | null;/** run elapsed time, in milliseconds */runElapsedTimeMs: number | null;+ /** debugger active */+ debuggerActive: boolean;}export interface CellConfig {diff --git a/frontend/src/core/debugger/state.ts b/frontend/src/core/debugger/state.tsnew file mode 100644index 0000000000..946505a5f2--- /dev/null+++ b/frontend/src/core/debugger/state.ts@@ -0,0 +1,10 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { atom } from "jotai";+import { OutputMessage } from "../kernel/messages";++interface DebuggerState {+ cellId: string;+ outputs: OutputMessage[];+}++export const debuggerAtom = atom<DebuggerState | undefined>(undefined);diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex 0c1bfc0c07..d325246857 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -8,9 +8,9 @@ import { RequestId } from "../network/DeferredRequestRegistry";export type OutputChannel =| "output"- | "console"| "media"| "marimo-error"+ | "pdb"| "stderr"| "stdout";@@ -59,6 +59,12 @@ export type OutputMessage =data: unknown;timestamp: number;}+ | {+ channel: "pdb";+ mimetype: "application/json";+ data: "start" | "stop";+ timestamp: number;+ }| {channel: "stdin";mimetype: "text/plain";diff --git a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snapindex 80e47c940d..a6c4af14de 100644--- a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap+++ b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap@@ -81,7 +81,7 @@ exports[`download-html > should construct html correctly 1`] = `1: "JTdCJTIyaWQlMjIlM0ElMjIxJTIyJTJDJTIyY29uZmlnJTIyJTNBJTdCJTIyaGlkZV9jb2RlJTIyJTNBdHJ1ZSU3RCUyQyUyMm5hbWUlMjIlM0ElMjJjZWxsJTIyJTJDJTIyY29kZSUyMiUzQSUyMmNvZGUlMjIlMkMlMjJlZGl0ZWQlMjIlM0FmYWxzZSUyQyUyMmxhc3RDb2RlUnVuJTIyJTNBbnVsbCUyQyUyMnNlcmlhbGl6ZWRFZGl0b3JTdGF0ZSUyMiUzQW51bGwlN0Q=",},cellRuntime: {- 1: "JTdCJTIyb3V0bGluZSUyMiUzQW51bGwlMkMlMjJvdXRwdXQlMjIlM0FudWxsJTJDJTIyY29uc29sZU91dHB1dHMlMjIlM0ElNUIlNUQlMkMlMjJzdGF0dXMlMjIlM0ElMjJpZGxlJTIyJTJDJTIyaW50ZXJydXB0ZWQlMjIlM0FmYWxzZSUyQyUyMmVycm9yZWQlMjIlM0FmYWxzZSUyQyUyMnN0b3BwZWQlMjIlM0FmYWxzZSUyQyUyMnJ1bkVsYXBzZWRUaW1lTXMlMjIlM0FudWxsJTJDJTIycnVuU3RhcnRUaW1lc3RhbXAlMjIlM0FudWxsJTdE",+ 1: "JTdCJTIyb3V0bGluZSUyMiUzQW51bGwlMkMlMjJvdXRwdXQlMjIlM0FudWxsJTJDJTIyY29uc29sZU91dHB1dHMlMjIlM0ElNUIlNUQlMkMlMjJzdGF0dXMlMjIlM0ElMjJpZGxlJTIyJTJDJTIyaW50ZXJydXB0ZWQlMjIlM0FmYWxzZSUyQyUyMmVycm9yZWQlMjIlM0FmYWxzZSUyQyUyMnN0b3BwZWQlMjIlM0FmYWxzZSUyQyUyMnJ1bkVsYXBzZWRUaW1lTXMlMjIlM0FudWxsJTJDJTIycnVuU3RhcnRUaW1lc3RhbXAlMjIlM0FudWxsJTJDJTIyZGVidWdnZXJBY3RpdmUlMjIlM0FmYWxzZSU3RA==",},};window.__MARIMO_STATIC__.assetUrl =diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex d8df928f69..9dfa4210de 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -36,6 +36,7 @@ const props: CellProps = {appClosed: false,showDeleteButton: true,allowFocus: false,+ debuggerActive: false,createNewCell: Logger.log,deleteCell: Logger.log,focusCell: Logger.log,diff --git a/frontend/src/stories/debugger.stories.tsx b/frontend/src/stories/debugger.stories.tsxnew file mode 100644index 0000000000..9b545560c2--- /dev/null+++ b/frontend/src/stories/debugger.stories.tsx@@ -0,0 +1,33 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { Debugger } from "@/components/debugger/debugger-code";+import type { Meta, StoryFn } from "@storybook/react";+import { useState } from "react";++const meta: Meta<typeof Debugger> = {+ title: "Debugger",+ component: Debugger,+ args: {},+};++export default meta;++const Template: StoryFn<typeof Debugger> = (args) => {+ const [code, setCode] = useState([args.code]);+ return (+ <div className="bg-background">+ <Debugger+ code={code.join("\n")}+ onSubmit={(nextCode) => {+ setCode([...code, nextCode]);+ args.onSubmit(nextCode);+ }}+ />+ </div>+ );+};++export const Default = Template.bind({});+Default.args = {+ code: "print('Hello, world!')",+ onSubmit: (code) => console.log(code),+};diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex d317bd8e0b..4e077a7a80 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -11,9 +11,9 @@ from marimo._ast.cell import (CellFuncType,CellFuncTypeBound,CellId_t,- cell_factory,execute_cell,)+from marimo._ast.compiler import cell_factoryfrom marimo._ast.errors import (CycleError,DeleteNonlocalError,@@ -144,7 +144,9 @@ class App:def decorator(func: CellFuncTypeBound,) -> CellFunction[CellFuncTypeBound]:- cell_function = cell_factory(func)+ cell_function = cell_factory(+ func, cell_id=str(self._cell_id_counter)+ )cell_function.cell.configure(cell_config)self._register_cell(cell_function)return cell_function@@ -156,7 +158,9 @@ class App:else:# If the decorator was used without parentheses, func will be the# decorated function- cell_function = cell_factory(func)+ cell_function = cell_factory(+ func, cell_id=str(self._cell_id_counter)+ )cell_function.cell.configure(cell_config)self._register_cell(cell_function)return cell_functiondiff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 2ce8de6b1f..c3c459ab50 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -5,11 +5,6 @@ import astimport dataclassesimport functoolsimport inspect-import io-import textwrap-import token as token_types-from collections.abc import Iterator-from tokenize import TokenInfo, tokenizefrom types import CodeTypefrom typing import (Any,@@ -17,23 +12,17 @@ from typing import (Literal,Optional,Protocol,- Set,Tuple,TypeVar,- Union,cast,)-from marimo._ast.visitor import Name, ScopedVisitor, _is_local+from marimo._ast.visitor import Namefrom marimo._utils.deep_merge import deep_mergeCellId_t = str-def code_key(code: str) -> int:- return hash(code)--@dataclasses.dataclassclass CellConfig:# If True, the cell and its descendants cannot be executed,@@ -223,161 +212,10 @@ def cell_function(return cell_func-def parse_cell(- code: str, filename: str = "<string>", cell_id: Optional[CellId_t] = None-) -> Cell:- mod = ast.parse(code, mode="exec")- if not mod.body:- # either empty code or just comments- return Cell(- key=hash(""),- code=code,- mod=mod,- defs=set(),- refs=set(),- deleted_refs=set(),- body=None,- last_expr=None,- cell_id=cell_id,- )-- v = ScopedVisitor("cell_" + str(cell_id) if cell_id is not None else None)- v.visit(mod)-- expr: Union[ast.Expression, str]- if isinstance(mod.body[-1], ast.Expr):- expr = ast.Expression(mod.body.pop().value) # type: ignore- else:- expr = "None"- last_expr = compile(expr, filename, mode="eval")- body = compile(mod, filename, mode="exec")-- glbls = {name for name in v.defs if not _is_local(name)}- return Cell(- # keyed by original (user) code, for cache lookups- key=code_key(code),- code=code,- mod=mod,- defs=glbls,- refs=v.refs,- deleted_refs=v.deleted_refs,- body=body,- last_expr=last_expr,- cell_id=cell_id,- )--def is_ws(char: str) -> bool:return char == " " or char == "\n" or char == "\t"-def cell_factory(f: CellFuncTypeBound) -> CellFunction[CellFuncTypeBound]:- """Creates a cell from a function.-- The signature and returns of the function are not used- to generate refs and defs. If the user introduced errors to the- signature, marimo will autofix them on save.- """- function_code = textwrap.dedent(inspect.getsource(f))-- # tokenize to find the start of the function body, including- # comments --- we have to use tokenize because the ast treats the first- # line of code as the starting line of the function body, whereas we- # want the first indented line after the signature- tokens: Iterator[TokenInfo] = tokenize(- io.BytesIO(function_code.encode("utf-8")).readline- )-- def_node: Optional[TokenInfo] = None- for token in tokens:- if token.type == token_types.NAME and token.string == "def":- def_node = token- break- assert def_node is not None-- paren_counter: Optional[int] = None- for token in tokens:- if token.type == token_types.OP and token.string == "(":- paren_counter = 1 if paren_counter is None else paren_counter + 1- elif token.type == token_types.OP and token.string == ")":- assert paren_counter is not None- paren_counter -= 1-- if paren_counter == 0:- break- assert paren_counter == 0-- for token in tokens:- if token.type == token_types.OP and token.string == ":":- break-- after_colon = next(tokens)- start_line: int- start_col: int- if after_colon.type == token_types.NEWLINE:- fn_body_token = next(tokens)- start_line = fn_body_token.start[0] - 1- start_col = 0- elif after_colon.type == token_types.COMMENT:- newline_token = next(tokens)- assert newline_token.type == token_types.NEWLINE- fn_body_token = next(tokens)- start_line = fn_body_token.start[0] - 1- start_col = 0- else:- # function body starts on same line as definition, such as in- # the following examples:- #- # def foo(): pass- #- # def foo(): x = 0; return x- #- # def foo(): x = """- #- # """; return x- fn_body_token = after_colon- start_line = fn_body_token.start[0] - 1- start_col = fn_body_token.start[1]-- # it would be difficult to tell if the last return token were in fact the- # last statement of the function body, so we use the ast, which lets us- # easily find the last statement of the function body;- tree = ast.parse(function_code)- return_node = (- tree.body[0].body[-1] # type: ignore- if isinstance(tree.body[0].body[-1], ast.Return) # type: ignore- else None- )-- end_line, return_offset = (- (return_node.lineno - 1, return_node.col_offset)- if return_node is not None- else (None, None)- )-- cell_code: str- lines = function_code.split("\n")- if start_line == end_line:- # remove leading indentation- cell_code = textwrap.dedent(lines[start_line][start_col:return_offset])- else:- first_line = lines[start_line][start_col:]- cell_code = textwrap.dedent(- "\n".join([first_line] + lines[start_line + 1 : end_line])- ).strip()- if end_line is not None and not lines[end_line].strip().startswith(- "return"- ):- # handle return written on same line as last statement in cell- cell_code += "\n" + lines[end_line][:return_offset]-- arg_names = set(p.arg for p in tree.body[0].args.args) # type: ignore- ret = cell_function(- parse_cell(cell_code), cast(Set[str], arg_names), function_code, f- )- return ret--def execute_cell(cell: Cell, glbls: dict[Any, Any]) -> Any:if cell.body is None:return Nonediff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex cbabc39aad..2d8acdaaaa 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -9,7 +9,8 @@ from typing import Any, List, Optional, Union, castfrom marimo import __version__from marimo._ast.app import App, _AppConfig-from marimo._ast.cell import Cell, CellConfig, parse_cell+from marimo._ast.cell import Cell, CellConfig+from marimo._ast.compiler import compile_cellfrom marimo._ast.visitor import NameINDENT = " "@@ -147,13 +148,17 @@ def generate_filecontents(cell_function_data: list[Union[Cell, tuple[str, CellConfig]]] = []defs: set[Name] = set()+ cell_id = 0for code, cell_config in zip(codes, cell_configs):try:- cell = parse_cell(code).configure(cell_config)+ cell = compile_cell(code, cell_id=str(cell_id)).configure(+ cell_config+ )defs |= cell.defscell_function_data.append(cell)except SyntaxError:cell_function_data.append((code, cell_config))+ cell_id += 1unshadowed_builtins = set(builtins.__dict__.keys()) - defsfndefs: list[str] = []diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pynew file mode 100644index 0000000000..44a5972417--- /dev/null+++ b/marimo/_ast/compiler.py@@ -0,0 +1,215 @@+# Copyright 2024 Marimo. All rights reserved.+import ast+import inspect+import io+import linecache+import os+import sys+import textwrap+import token as token_types+from collections.abc import Iterator+from tokenize import TokenInfo, tokenize+from typing import Optional, Set, Union, cast++from marimo._ast.cell import (+ Cell,+ CellFunction,+ CellFuncTypeBound,+ CellId_t,+ cell_function,+)+from marimo._ast.visitor import ScopedVisitor, _is_local+from marimo._utils.tmpdir import get_tmpdir+++def code_key(code: str) -> int:+ return hash(code)+++def get_filename(basename: str) -> str:+ """Get a temporary Python filename that ends with basename."""+ return os.path.join(get_tmpdir(), basename + ".py")+++def cache(filename: str, code: str) -> None:+ # Generate a cache entry in Python's linecache+ linecache.cache[filename] = (+ len(code),+ None,+ [line + "\n" for line in code.splitlines()],+ filename,+ )+++def compile_cell(+ code: str,+ cell_id: CellId_t,+ basename: Optional[str] = None,+) -> Cell:+ module = ast.parse(code, mode="exec")+ if not module.body:+ # either empty code or just comments+ return Cell(+ key=hash(""),+ code=code,+ mod=module,+ defs=set(),+ refs=set(),+ deleted_refs=set(),+ body=None,+ last_expr=None,+ cell_id=cell_id,+ )++ v = ScopedVisitor("cell_" + str(cell_id) if cell_id is not None else None)+ v.visit(module)++ expr: Union[ast.Expression, str]+ if isinstance(module.body[-1], ast.Expr):+ expr = ast.Expression(module.body.pop().value) # type: ignore+ else:+ expr = "None"++ # store the cell's code in Python's linecache so debuggers can find it+ basename = f"cell_{cell_id}" if basename is None else basename+ body_filename = get_filename(basename)+ last_expr_filename = get_filename(basename + "_output")+ cache(body_filename, code)+ if sys.version_info >= (3, 9):+ # ast.unparse only available >= 3.9+ cache(+ last_expr_filename,+ ast.unparse(expr) if not isinstance(expr, str) else "None",+ )++ body = compile(module, body_filename, mode="exec")+ last_expr = compile(expr, last_expr_filename, mode="eval")++ glbls = {name for name in v.defs if not _is_local(name)}+ return Cell(+ # keyed by original (user) code, for cache lookups+ key=code_key(code),+ code=code,+ mod=module,+ defs=glbls,+ refs=v.refs,+ deleted_refs=v.deleted_refs,+ body=body,+ last_expr=last_expr,+ cell_id=cell_id,+ )+++def cell_factory(+ f: CellFuncTypeBound,+ cell_id: CellId_t,+) -> CellFunction[CellFuncTypeBound]:+ """Creates a cell from a function.++ The signature and returns of the function are not used+ to generate refs and defs. If the user introduced errors to the+ signature, marimo will autofix them on save.+ """+ function_code = textwrap.dedent(inspect.getsource(f))++ # tokenize to find the start of the function body, including+ # comments --- we have to use tokenize because the ast treats the first+ # line of code as the starting line of the function body, whereas we+ # want the first indented line after the signature+ tokens: Iterator[TokenInfo] = tokenize(+ io.BytesIO(function_code.encode("utf-8")).readline+ )++ def_node: Optional[TokenInfo] = None+ for token in tokens:+ if token.type == token_types.NAME and token.string == "def":+ def_node = token+ break+ assert def_node is not None++ paren_counter: Optional[int] = None+ for token in tokens:+ if token.type == token_types.OP and token.string == "(":+ paren_counter = 1 if paren_counter is None else paren_counter + 1+ elif token.type == token_types.OP and token.string == ")":+ assert paren_counter is not None+ paren_counter -= 1++ if paren_counter == 0:+ break+ assert paren_counter == 0++ for token in tokens:+ if token.type == token_types.OP and token.string == ":":+ break++ after_colon = next(tokens)+ start_line: int+ start_col: int+ if after_colon.type == token_types.NEWLINE:+ fn_body_token = next(tokens)+ start_line = fn_body_token.start[0] - 1+ start_col = 0+ elif after_colon.type == token_types.COMMENT:+ newline_token = next(tokens)+ assert newline_token.type == token_types.NEWLINE+ fn_body_token = next(tokens)+ start_line = fn_body_token.start[0] - 1+ start_col = 0+ else:+ # function body starts on same line as definition, such as in+ # the following examples:+ #+ # def foo(): pass+ #+ # def foo(): x = 0; return x+ #+ # def foo(): x = """+ #+ # """; return x+ fn_body_token = after_colon+ start_line = fn_body_token.start[0] - 1+ start_col = fn_body_token.start[1]++ # it would be difficult to tell if the last return token were in fact the+ # last statement of the function body, so we use the ast, which lets us+ # easily find the last statement of the function body;+ tree = ast.parse(function_code)+ return_node = (+ tree.body[0].body[-1] # type: ignore+ if isinstance(tree.body[0].body[-1], ast.Return) # type: ignore+ else None+ )++ end_line, return_offset = (+ (return_node.lineno - 1, return_node.col_offset)+ if return_node is not None+ else (None, None)+ )++ cell_code: str+ lines = function_code.split("\n")+ if start_line == end_line:+ # remove leading indentation+ cell_code = textwrap.dedent(lines[start_line][start_col:return_offset])+ else:+ first_line = lines[start_line][start_col:]+ cell_code = textwrap.dedent(+ "\n".join([first_line] + lines[start_line + 1 : end_line])+ ).strip()+ if end_line is not None and not lines[end_line].strip().startswith(+ "return"+ ):+ # handle return written on same line as last statement in cell+ cell_code += "\n" + lines[end_line][:return_offset]++ arg_names = set(p.arg for p in tree.body[0].args.args) # type: ignore+ # TODO(akshayka): use the name of the function as the basename (if not __)+ # for parse_cell+ ret = cell_function(+ compile_cell(cell_code, cell_id=cell_id),+ cast(Set[str], arg_names),+ function_code,+ f,+ )+ return retdiff --git a/marimo/_runtime/context.py b/marimo/_runtime/context.pyindex 68ef7cf8fb..a84acca123 100644--- a/marimo/_runtime/context.py+++ b/marimo/_runtime/context.py@@ -18,7 +18,7 @@ from marimo._runtime.functions import FunctionRegistryif TYPE_CHECKING:from marimo._ast.cell import CellId_t- from marimo._messaging.streams import Stderr, Stdin, Stdout, Stream+ from marimo._messaging.streams import Streamfrom marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.runtime import Kernelfrom marimo._runtime.virtual_file import VirtualFileRegistry@@ -55,9 +55,6 @@ class RuntimeContext:cell_lifecycle_registry: CellLifecycleRegistryvirtual_file_registry: VirtualFileRegistrystream: Stream- stdout: Optional[Stdout]- stderr: Optional[Stderr]- stdin: Optional[Stdin]_id_provider: Optional[IDProvider] = None@property@@ -104,16 +101,10 @@ _THREAD_LOCAL_CONTEXT = _ThreadLocalContext()def initialize_context(kernel: Kernel,stream: Stream,- stdout: Optional[Stdout],- stderr: Optional[Stderr],- stdin: Optional[Stdin],) -> None:"""Initializes thread-local/session-specific context.Must be called exactly once for each client thread.-- stdout, stderr, and stdin are optional because in `run` mode the- standard streams are not redirected/replaced."""from marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.virtual_file import VirtualFileRegistry@@ -130,9 +121,6 @@ def initialize_context(cell_lifecycle_registry=CellLifecycleRegistry(),virtual_file_registry=VirtualFileRegistry(),stream=stream,- stdout=stdout,- stderr=stderr,- stdin=stdin,)_THREAD_LOCAL_CONTEXT.initialize(runtime_context=runtime_context)diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.pyindex 8464b82e2c..ddb297465a 100644--- a/marimo/_runtime/dataflow.py+++ b/marimo/_runtime/dataflow.py@@ -7,7 +7,8 @@ from dataclasses import dataclass, fieldfrom typing import Tuplefrom marimo import _loggers-from marimo._ast.cell import Cell, CellId_t, code_key+from marimo._ast.cell import Cell, CellId_t+from marimo._ast.compiler import code_keyEdge = Tuple[CellId_t, CellId_t]diff --git a/marimo/_runtime/input_override.py b/marimo/_runtime/input_override.pyindex b1db950e97..58c850c649 100644--- a/marimo/_runtime/input_override.py+++ b/marimo/_runtime/input_override.py@@ -1,10 +1,9 @@# Copyright 2024 Marimo. All rights reserved.import functools--from marimo._runtime.context import get_context+import sys@functools.wraps(input)def input_override(prompt: str = "") -> str:- assert (stdin := get_context().stdin) is not None- return stdin._readline_with_prompt(prompt)+ # sys.stdin is overridden+ return sys.stdin._readline_with_prompt(prompt) # type: ignore[attr-defined, no-any-return] # noqa: E501diff --git a/marimo/_runtime/marimo_pdb.py b/marimo/_runtime/marimo_pdb.pynew file mode 100644index 0000000000..afb974599f--- /dev/null+++ b/marimo/_runtime/marimo_pdb.py@@ -0,0 +1,39 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import inspect+import sys+from pdb import Pdb+from types import FrameType++from marimo import _loggers+from marimo._messaging.streams import Stdin, Stdout++LOGGER = _loggers.marimo_logger()+++class MarimoPdb(Pdb):+ def __init__(self, stdout: Stdout | None, stdin: Stdin | None):+ super().__init__(stdout=stdout, stdin=stdin) # type: ignore[arg-type]+ # it's fine to use input() since marimo overrides it, but disable+ # it anyway -- stdin is fine too ...+ self.use_rawinput = stdin is None++ def set_trace(+ self, frame: FrameType | None = None, header: str | None = None+ ) -> None:+ if header is not None:+ sys.stdout.write(header)+ return super().set_trace(frame)+++def set_trace(+ debugger: MarimoPdb,+ frame: FrameType | None = None,+ header: str | None = None,+) -> None:+ if frame is None:+ # make sure the frame points to user code+ current_frame = inspect.currentframe()+ frame = current_frame.f_back if current_frame is not None else None+ debugger.set_trace(frame, header=header)diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.pyindex ad83babb65..3781651e29 100644--- a/marimo/_runtime/redirect_streams.py+++ b/marimo/_runtime/redirect_streams.py@@ -8,8 +8,7 @@ import threadingfrom typing import Iteratorfrom marimo._ast.cell import CellId_t-from marimo._messaging.streams import Stderr, Stdout-from marimo._runtime.context import get_context+from marimo._messaging.streams import Stderr, Stdin, Stdout, Streamdef forward_os_stream(stream_object: Stdout | Stderr, fd: int) -> None:@@ -42,16 +41,21 @@ def dup2newfd(fd: int) -> tuple[int, int, int]:return fd_dup, read_fd, fd-# Redirect stdout/stderr, if they have been installed+# Redirect output stream and stdout/stderr/stdin (if they have been installed)@contextlib.contextmanager-def redirect_streams(cell_id: CellId_t) -> Iterator[None]:- ctx = get_context()- ctx.stream.cell_id = cell_id- if ctx.stdout is None or ctx.stderr is None:+def redirect_streams(+ cell_id: CellId_t,+ stream: Stream,+ stdout: Stdout | None,+ stderr: Stderr | None,+ stdin: Stdin | None,+) -> Iterator[None]:+ stream.cell_id = cell_id+ if stdout is None or stderr is None:try:yieldfinally:- ctx.stream.cell_id = None+ stream.cell_id = Nonereturn# Redirect file descriptors for writable streams (stdout, stderr).@@ -68,10 +72,10 @@ def redirect_streams(cell_id: CellId_t) -> Iterator[None]:# - using a multiprocessing ThreadPool# - using a concurrent.futures.ThreadPool/ProcessPoolstdout_thread = threading.Thread(- target=forward_os_stream, args=(ctx.stdout, stdout_read_fd)+ target=forward_os_stream, args=(stdout, stdout_read_fd))stderr_thread = threading.Thread(- target=forward_os_stream, args=(ctx.stderr, stderr_read_fd)+ target=forward_os_stream, args=(stderr, stderr_read_fd))# NB: Python doesn't allow monkey patching methods builtins, so@@ -79,9 +83,9 @@ def redirect_streams(cell_id: CellId_t) -> Iterator[None]:py_stdout = sys.stdoutpy_stderr = sys.stderrpy_stdin = sys.stdin- sys.stdout = ctx.stdout # type: ignore- sys.stderr = ctx.stderr # type: ignore- sys.stdin = ctx.stdin # type: ignore+ sys.stdout = stdout # type: ignore+ sys.stderr = stderr # type: ignore+ sys.stdin = stdin # type: ignorestdout_thread.start()stderr_thread.start()@@ -114,4 +118,4 @@ def redirect_streams(cell_id: CellId_t) -> Iterator[None]:sys.stderr = py_stderrsys.stdin = py_stdin- ctx.stream.cell_id = None+ stream.cell_id = Nonediff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 7e500bbffe..ba2d3a2336 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport builtinsimport contextlibimport dataclasses+import functoolsimport ioimport itertoolsimport multiprocessing as mp@@ -18,7 +19,8 @@ from collections.abc import Iterable, Sequencefrom typing import Any, Callable, Iterator, Optionalfrom marimo import _loggers-from marimo._ast.cell import CellConfig, CellId_t, parse_cell+from marimo._ast.cell import CellConfig, CellId_t+from marimo._ast.compiler import compile_cellfrom marimo._config.config import configurefrom marimo._messaging.errors import (Error,@@ -45,7 +47,7 @@ from marimo._output import formattingfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import MarimoConvertValueException-from marimo._runtime import cell_runner, dataflow+from marimo._runtime import cell_runner, dataflow, marimo_pdbfrom marimo._runtime.complete import completefrom marimo._runtime.context import (ContextNotInitializedError,@@ -161,11 +163,33 @@ class Kernel:- input_override: a function that overrides the builtin input() function"""+ def patch_pdb(self, debugger: marimo_pdb.MarimoPdb) -> None:+ import pdb++ # Patch Pdb so manually instantiated debuggers create our debugger+ pdb.Pdb = marimo_pdb.MarimoPdb # type: ignore[misc, assignment]+ pdb.set_trace = functools.partial(+ marimo_pdb.set_trace, debugger=debugger+ )+def __init__(self,cell_configs: dict[CellId_t, CellConfig],+ stream: Stream,+ stdout: Stdout | None,+ stderr: Stderr | None,+ stdin: Stdin | None,input_override: Callable[[Any], str] = input_override,) -> None:+ self.stream = stream+ self.stdout = stdout+ self.stderr = stderr+ self.stdin = stdin+ self._debugger = marimo_pdb.MarimoPdb(+ stdout=self.stdout, stdin=self.stdin+ )+ self.patch_pdb(self._debugger)+self.globals: dict[Any, Any] = {"__name__": "__main__","__builtins__": globals()["__builtins__"],@@ -201,7 +225,11 @@ class Kernel:cell_id, setting_element_value)with get_context().provide_ui_ids(str(cell_id)), redirect_streams(- cell_id+ cell_id,+ stream=self.stream,+ stdout=self.stdout,+ stderr=self.stderr,+ stdin=self.stdin,):try:yield self.execution_context@@ -220,9 +248,7 @@ class Kernel:"""error: Optional[Error] = Nonetry:- cell = parse_cell(- code, cell_runner.cell_filename(cell_id), cell_id- )+ cell = compile_cell(code, cell_id=cell_id)except Exception as e:cell = Noneif isinstance(e, SyntaxError):@@ -1027,13 +1053,17 @@ def launch_kernel(# isn't currently available in run mode.stdin = Stdin(stream) if is_edit_mode else None- kernel = Kernel(cell_configs=configs, input_override=input_override)- initialize_context(- kernel=kernel,+ kernel = Kernel(+ cell_configs=configs,stream=stream,stdout=stdout,stderr=stderr,stdin=stdin,+ input_override=input_override,+ )+ initialize_context(+ kernel=kernel,+ stream=stream,)if is_edit_mode:diff --git a/marimo/_smoke_tests/pdb_test.py b/marimo/_smoke_tests/pdb_test.pynew file mode 100644index 0000000000..c653240c1a--- /dev/null+++ b/marimo/_smoke_tests/pdb_test.py@@ -0,0 +1,22 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.1.77"+app = marimo.App()+++def __():+ import marimo as mo+ return mo,+++def __(mo):+ # import pdb; pdb.set_trace()+ mo.pdb.set_trace()+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_utils/tmpdir.py b/marimo/_utils/tmpdir.pynew file mode 100644index 0000000000..b5e00a783a--- /dev/null+++ b/marimo/_utils/tmpdir.py@@ -0,0 +1,42 @@+# Copyright 2024 Marimo. All rights reserved.+import os+import sys+import tempfile+++def _convert_to_long_pathname(filename: str) -> str:+ return filename+++if sys.platform == "win32":+ # Adapted from IPython.core.compilerop+ #+ # https://github.com/ipython/ipykernel/blob/93a63fb7b8752899ed95118fa35e56f74eedd0c6/ipykernel/compiler.py # noqa: E501+ try:+ import ctypes+ from ctypes.wintypes import DWORD, LPCWSTR, LPWSTR, MAX_PATH++ _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW+ _GetLongPathName.argtypes = [LPCWSTR, LPWSTR, DWORD]+ _GetLongPathName.restype = DWORD++ def _win_convert_to_long_pathname(filename: str) -> str:+ buf = ctypes.create_unicode_buffer(MAX_PATH)+ rv = _GetLongPathName(filename, buf, MAX_PATH)+ if rv != 0 and rv <= MAX_PATH:+ filename = buf.value+ return filename++ # test that it works so if there are any issues we fail just once here+ _win_convert_to_long_pathname(__file__)+ except Exception:+ pass+ else:+ _convert_to_long_pathname = _win_convert_to_long_pathname+++def get_tmpdir() -> str:+ return os.path.join(+ _convert_to_long_pathname(tempfile.gettempdir()),+ "marimo_" + str(os.getpid()),+ )diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex be55124296..45901958d3 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -4,12 +4,15 @@ from __future__ import annotationsimport jsonimport osimport tempfile+from functools import partialfrom inspect import cleandocfrom typing import Optionalfrom marimo import __version__-from marimo._ast import codegen-from marimo._ast.cell import CellConfig, parse_cell+from marimo._ast import codegen, compiler+from marimo._ast.cell import CellConfig++compile_cell = partial(compiler.compile_cell, cell_id="0")DIR_PATH = os.path.dirname(os.path.realpath(__file__))@@ -254,7 +257,7 @@ class TestApp:class TestToFunctionDef:def test_tofunctiondef_one_def(self) -> None:code = "x = 0"- cell = parse_cell(code)+ cell = compile_cell(code)fndef = codegen.to_functiondef(cell, "foo")expected = "\n".join(["@app.cell", "def foo():", " x = 0", " return x,"]@@ -263,7 +266,7 @@ class TestToFunctionDef:def test_tofunctiondef_one_ref(self) -> None:code = "y + 1"- cell = parse_cell(code)+ cell = compile_cell(code)fndef = codegen.to_functiondef(cell, "foo")expected = "\n".join(["@app.cell", "def foo(y):", " y + 1", " return"]@@ -272,12 +275,12 @@ class TestToFunctionDef:def test_tofunctiondef_empty_cells(self) -> None:code = ""- cell = parse_cell(code)+ cell = compile_cell(code)fndef = codegen.to_functiondef(cell, "foo")expected = "\n".join(["@app.cell", "def foo():", " return"])code = "\n #\n"- cell = parse_cell(code)+ cell = compile_cell(code)fndef = codegen.to_functiondef(cell, "foo")expected = cleandoc("""@@ -293,7 +296,7 @@ class TestToFunctionDef:def test_tofunctiondef_builtin_not_a_ref(self) -> None:code = "print(y)"- cell = parse_cell(code)+ cell = compile_cell(code)fndef = codegen.to_functiondef(cell, "foo")expected = "\n".join(["@app.cell", "def foo(y):", " print(y)", " return"]@@ -302,7 +305,7 @@ class TestToFunctionDef:def test_tofunctiondef_refs_and_defs(self) -> None:code = "\n".join(["y = x", "z = x", "z = w + y"])- cell = parse_cell(code)+ cell = compile_cell(code)fndef = codegen.to_functiondef(cell, "foo")expected = "\n".join(["@app.cell", "def foo(w, x):"]@@ -313,7 +316,7 @@ class TestToFunctionDef:def test_with_empty_config(self) -> None:code = "x = 0"- cell = parse_cell(code)+ cell = compile_cell(code)cell = cell.configure(CellConfig())fndef = codegen.to_functiondef(cell, "foo")expected = "\n".join(@@ -323,7 +326,7 @@ class TestToFunctionDef:def test_with_some_config(self) -> None:code = "x = 0"- cell = parse_cell(code)+ cell = compile_cell(code)cell = cell.configure(CellConfig(disabled=True))fndef = codegen.to_functiondef(cell, "foo")expected = "\n".join(@@ -338,7 +341,7 @@ class TestToFunctionDef:def test_with_all_config(self) -> None:code = "x = 0"- cell = parse_cell(code)+ cell = compile_cell(code)cell = cell.configure(CellConfig(disabled=True, hide_code=True))fndef = codegen.to_functiondef(cell, "foo")expected = "\n".join(@@ -353,7 +356,7 @@ class TestToFunctionDef:def test_should_remove_defaults(self) -> None:code = "x = 0"- cell = parse_cell(code)+ cell = compile_cell(code)cell = cell.configure(CellConfig(disabled=False, hide_code=False))fndef = codegen.to_functiondef(cell, "foo")expected = "\n".join(diff --git a/tests/_ast/test_cell.py b/tests/_ast/test_compiler.pysimilarity index 80%rename from tests/_ast/test_cell.pyrename to tests/_ast/test_compiler.pyindex 880cb77c39..4713013c9c 100644--- a/tests/_ast/test_cell.py+++ b/tests/_ast/test_compiler.py@@ -1,14 +1,18 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations-from marimo._ast.cell import cell_factory, parse_cell+from functools import partial++from marimo._ast import compiler++compile_cell = partial(compiler.compile_cell, cell_id="0")class TestParseCell:@staticmethoddef test_parse_simple() -> None:code = "x = 0\nz = y"- cell = parse_cell(code)+ cell = compile_cell(code)assert cell.key == hash(code)assert cell.code == codeassert cell.defs == set(["x", "z"])@@ -17,40 +21,40 @@ class TestParseCell:@staticmethoddef test_local_variables() -> None:code = "_, y = f(x)\ndef _foo():\n _bar = 0\nimport _secret_module"- cell = parse_cell(code)+ cell = compile_cell(code)assert cell.defs == {"y"}assert cell.refs == {"f", "x"}@staticmethoddef test_dunder_dunder_excluded() -> None:code = "__ = 10; __name__ = 20"- cell = parse_cell(code)+ cell = compile_cell(code)assert cell.defs == {"__", "__name__"}assert cell.refs == set()@staticmethoddef test_local_class() -> None:code = "class _A: pass"- cell = parse_cell(code)+ cell = compile_cell(code)assert cell.defs == set()assert cell.refs == set()@staticmethoddef test_alias_underscored_name() -> None:code = "import _m as m"- cell = parse_cell(code)+ cell = compile_cell(code)assert cell.defs == {"m"}assert cell.refs == set()@staticmethoddef test_ref_local_var() -> None:code = "x = _y"- cell = parse_cell(code)+ cell = compile_cell(code)assert cell.defs == {"x"}assert cell.refs == set()code = "def f(x= _y): pass"- cell = parse_cell(code)+ cell = compile_cell(code)assert cell.defs == {"f"}assert cell.refs == set()@@ -64,7 +68,7 @@ class TestCellFactory:x = 10 # noqa: F841y = 20 # noqa: F841- cf = cell_factory(f)+ cf = compiler.cell_factory(f, cell_id="0")assert cf.cell.defs == {"x", "y"}assert not cf.cell.refs@@ -75,6 +79,6 @@ class TestCellFactory:def f() -> None:x = y # noqa: F841 F821- cf = cell_factory(f)+ cf = compiler.cell_factory(f, cell_id="0")assert cf.cell.defs == {"x"}assert cf.cell.refs == {"y"}diff --git a/tests/_runtime/test_dataflow.py b/tests/_runtime/test_dataflow.pyindex 0936641663..9c48bf1340 100644--- a/tests/_runtime/test_dataflow.py+++ b/tests/_runtime/test_dataflow.py@@ -1,9 +1,13 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations-from marimo._ast.cell import parse_cell+from functools import partial++from marimo._ast import compilerfrom marimo._runtime import dataflow+parse_cell = partial(compiler.compile_cell, cell_id="0")+def test_graph_single_node() -> None:code = "x = 0"diff --git a/tests/_runtime/test_marimo_pdb.py b/tests/_runtime/test_marimo_pdb.pynew file mode 100644index 0000000000..5438ee7c50--- /dev/null+++ b/tests/_runtime/test_marimo_pdb.py@@ -0,0 +1,12 @@+from marimo._runtime.marimo_pdb import MarimoPdb+from marimo._runtime.runtime import Kernel+from tests.conftest import ExecReqProvider+++def test_pdb_patched(k: Kernel, exec_req: ExecReqProvider):+ k.run([exec_req.get("import pdb")])++ pdb = k.globals["pdb"]+ assert pdb.Pdb == MarimoPdb+ assert k._debugger.stdout is k.stdout+ assert k._debugger.stdin is k.stdindiff --git a/tests/_runtime/test_validate_graph.py b/tests/_runtime/test_validate_graph.pyindex 6a5881a617..1af412211d 100644--- a/tests/_runtime/test_validate_graph.py+++ b/tests/_runtime/test_validate_graph.py@@ -1,9 +1,10 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations+from functools import partialfrom typing import cast-from marimo._ast.cell import parse_cell+from marimo._ast import compilerfrom marimo._messaging.errors import (CycleError,DeleteNonlocalError,@@ -12,6 +13,8 @@ from marimo._messaging.errors import (from marimo._runtime import dataflowfrom marimo._runtime.validate_graph import check_for_errors+parse_cell = partial(compiler.compile_cell, cell_id="0")+def test_multiple_definition_error() -> None:graph = dataflow.DirectedGraph()diff --git a/tests/conftest.py b/tests/conftest.pyindex fbedc529fb..6820829886 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -61,21 +61,23 @@ class MockStdin(Stdin):@dataclasses.dataclassclass MockedKernel:- k: Kernel = dataclasses.field(- default_factory=lambda: Kernel(cell_configs={})- )stream: _MockStream = dataclasses.field(default_factory=_MockStream)stdout: MockStdout = dataclasses.field(default_factory=MockStdout)stderr: MockStderr = dataclasses.field(default_factory=MockStderr)stdin: MockStdin = dataclasses.field(default_factory=MockStdin)def __post_init__(self) -> None:- initialize_context(- kernel=self.k,- stream=self.stream, # type: ignore+ self.k = Kernel(+ stream=self.stream,stdout=self.stdout,stderr=self.stderr,stdin=self.stdin,+ cell_configs={},+ )++ initialize_context(+ kernel=self.k,+ stream=self.stream, # type: ignore)def __del__(self) -> None: