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: add 'Insert breakpoint' in traceback (#4795)
Myles Scolnick6c69e3a08513
diff --git a/frontend/src/components/debugger/debugger-code.tsx b/frontend/src/components/debugger/debugger-code.tsxindex 319eb25458..164d32d5db 100644--- a/frontend/src/components/debugger/debugger-code.tsx+++ b/frontend/src/components/debugger/debugger-code.tsx@@ -13,6 +13,7 @@ import {LayersIcon,PlayIcon,SkipForwardIcon,+ TrashIcon,} from "lucide-react";import { Button } from "../ui/button";import { cn } from "@/utils/cn";@@ -140,11 +141,15 @@ const DebuggerInput: React.FC<{);};-const DebuggerControls: React.FC<{+export 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)]";+ onClear?: () => void;+}> = ({ onSubmit, onClear }) => {+ const buttonClasses = cn(+ "m-0 w-9 h-8 bg-[var(--slate-2)] text-[var(--slate-11)] hover:text-[var(--blue-11)] rounded-none hover:bg-[var(--sky-3)] hover:border-[var(--blue-8)]",+ "first:rounded-l-lg first:border-l border-t border-b hover:border",+ "last:rounded-r-lg last:border-r",+ );const iconClasses = "w-5 h-5";return (@@ -154,7 +159,7 @@ const DebuggerControls: React.FC<{variant="text"size="icon"data-testid="debugger-next-button"- className={cn(buttonClasses, "rounded-bl-lg")}+ className={buttonClasses}onClick={() => onSubmit("n")}><SkipForwardIcon fontSize={36} className={iconClasses} />@@ -196,6 +201,22 @@ const DebuggerControls: React.FC<{<HelpCircleIcon fontSize={36} className={iconClasses} /></Button></Tooltip>+ {onClear && (+ <Tooltip content="Clear">+ <Button+ variant="text"+ size="icon"+ data-testid="debugger-clear-button"+ className={cn(+ buttonClasses,+ "text-[var(--red-11)] hover:text-[var(--red-11)] hover:bg-[var(--red-2)] hover:border-[var(--red-8)]",+ )}+ onClick={onClear}+ >+ <TrashIcon fontSize={36} className={iconClasses} />+ </Button>+ </Tooltip>+ )}</div>);};diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex 01cfd4ba4b..eefe7be23a 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -325,6 +325,7 @@ export type CellComponentActions = Pick<| "updateCellConfig"| "clearSerializedEditorState"| "setStdinResponse"+ | "clearCellConsoleOutput"| "sendToBottom"| "sendToTop">;@@ -901,6 +902,9 @@ const EditableCellComponent = ({// Empty name if serialization triggeredcellName={serialization ? "_" : name}onRefactorWithAI={handleRefactorWithAI}+ onClear={() => {+ actions.clearCellConsoleOutput({ cellId });+ }}onSubmitDebugger={(text, index) => {actions.setStdinResponse({cellId,@@ -1345,6 +1349,9 @@ const SetupCellComponent = ({// Don't show namecellName={"_"}onRefactorWithAI={handleRefactorWithAI}+ onClear={() => {+ actions.clearCellConsoleOutput({ cellId });+ }}onSubmitDebugger={(text, index) => {actions.setStdinResponse({cellId,diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsxindex 7f4749152a..af9371881b 100644--- a/frontend/src/components/editor/Output.tsx+++ b/frontend/src/components/editor/Output.tsx@@ -135,6 +135,7 @@ export const OutputRenderer: React.FC<{<MarimoTracebackOutputonRefactorWithAI={onRefactorWithAI}traceback={data}+ cellId={cellId}/>);diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex a596311a5d..4394c91648 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -112,6 +112,14 @@ const CellEditorInternal = ({return true;});+ const handleRunCell = useEvent(() => {+ if (loading) {+ return false;+ }+ runCell();+ return true;+ });+const toggleHideCode = useEvent(() => {// Use cellConfig.hide_code instead of hidden, since it may be temporarily shownconst nextHidden = !cellConfig.hide_code;@@ -136,7 +144,7 @@ const CellEditorInternal = ({cellActions: {...cellActions,afterToggleMarkdown,- onRun: runCell,+ onRun: handleRunCell,deleteCell: handleDelete,saveNotebook: saveOrNameNotebook,createManyBelow: (cells) => {@@ -218,7 +226,7 @@ const CellEditorInternal = ({splitCell,toggleHideCode,handleDelete,- runCell,+ handleRunCell,setAiCompletionCell,afterToggleMarkdown,setLanguageAdapter,diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/ConsoleOutput.tsxindex 0077d3f04b..a96752dc9f 100644--- a/frontend/src/components/editor/output/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/ConsoleOutput.tsx@@ -11,6 +11,8 @@ import { AnsiUp } from "ansi_up";import type { WithResponse } from "@/core/cells/types";import { invariant } from "@/utils/invariant";import { ErrorBoundary } from "../boundary/ErrorBoundary";+import { DebuggerControls } from "@/components/debugger/debugger-code";+import { ChevronRightIcon } from "lucide-react";const ansiUp = new AnsiUp();@@ -22,6 +24,7 @@ interface Props {stale: boolean;debuggerActive: boolean;onRefactorWithAI?: (opts: { prompt: string }) => void;+ onClear?: () => void;onSubmitDebugger: (text: string, index: number) => void;}@@ -41,6 +44,7 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {cellName,cellId,onSubmitDebugger,+ onClear,onRefactorWithAI,className,} = props;@@ -85,6 +89,10 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {}const reversedOutputs = [...consoleOutputs].reverse();+ const isPdb = reversedOutputs.some(+ (output) =>+ typeof output.data === "string" && output.data.includes("(Pdb)"),+ );return (<div@@ -92,7 +100,7 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {data-testid="console-output-area"ref={ref}className={cn(- "console-output-area overflow-hidden rounded-b-lg flex flex-col-reverse w-full",+ "console-output-area overflow-hidden rounded-b-lg flex flex-col-reverse w-full gap-1",stale && "marimo-output-stale",hasOutputs ? "p-5" : "p-3",className,@@ -116,7 +124,9 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {<StdInputkey={idx}output={output.data}+ isPdb={isPdb}onSubmit={(text) => onSubmitDebugger(text, originalIdx)}+ onClear={onClear}/>);}@@ -151,18 +161,21 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {const StdInput = (props: {onSubmit: (text: string) => void;+ onClear?: () => void;output: string;response?: string;+ isPdb: boolean;}) => {return (- <div className="flex gap-2 items-center">+ <div className="flex gap-2 items-center pt-2">{renderText(props.output)}<Inputdata-testid="console-input"type="text"autoComplete="off"autoFocus={true}- className="m-0"+ icon={<ChevronRightIcon className="w-5 h-5" />}+ className="m-0 h-8 focus-visible:shadow-xsSolid"placeholder="stdin"onKeyDown={(e) => {if (e.key === "Enter" && !e.shiftKey) {@@ -170,6 +183,7 @@ const StdInput = (props: {}}}/>+ <DebuggerControls onSubmit={props.onSubmit} onClear={props.onClear} /></div>);};@@ -186,7 +200,11 @@ const StdInputWithResponse = (props: {);};-const renderText = (text: string) => {+const renderText = (text: string | null) => {+ if (!text) {+ return null;+ }+return (<span dangerouslySetInnerHTML={{ __html: ansiUp.ansi_to_html(text) }} />);diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsxindex d7abd84f8a..1cdfe4d8f5 100644--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx@@ -17,6 +17,7 @@ import {SearchIcon,MessageCircleIcon,CopyIcon,+ BugPlayIcon,} from "lucide-react";import { useState } from "react";import { useAtomValue } from "jotai";@@ -33,10 +34,17 @@ import {import { copyToClipboard } from "@/utils/copy";import {elementContainsMarimoCellFile,+ extractAllTracebackInfo,getTracebackInfo,} from "@/utils/traceback";+import type { CellId } from "@/core/cells/ids";+import { Tooltip } from "@/components/ui/tooltip";+import { Kbd } from "@/components/ui/kbd";+import { insertDebuggerAtLine } from "@/core/codemirror/editing/debugging";+import { getCellEditorView } from "@/core/cells/cells";interface Props {+ cellId: CellId | undefined;traceback: string;onRefactorWithAI?: (opts: { prompt: string }) => void;}@@ -49,6 +57,7 @@ const KEY = "item";export const MarimoTracebackOutput = ({onRefactorWithAI,traceback,+ cellId,}: Props): JSX.Element => {const htmlTraceback = renderHTML({html: traceback,@@ -59,6 +68,9 @@ export const MarimoTracebackOutput = ({const lastTracebackLine = lastLine(traceback);const aiEnabled = useAtomValue(aiEnabledAtom);+ // Get last traceback info+ const lastTracebackInfo = extractAllTracebackInfo(traceback)?.at(-1);+const handleRefactorWithAI = () => {onRefactorWithAI?.({prompt: `My code gives the following error:\n\n${lastTracebackLine}`,@@ -86,7 +98,7 @@ export const MarimoTracebackOutput = ({{errorMessage}</div></div>- <AccordionContent className="px-4 text-muted-foreground px-4 pt-2 text-xs overflow-auto">+ <AccordionContent className="text-muted-foreground px-4 pt-2 text-xs overflow-auto">{htmlTraceback}</AccordionContent></AccordionItem>@@ -98,6 +110,21 @@ export const MarimoTracebackOutput = ({Fix with AI</Button>)}+ {lastTracebackInfo && (+ <Button+ size="xs"+ variant="outline"+ onClick={() => {+ const view = getCellEditorView(lastTracebackInfo.cellId);+ if (view) {+ insertDebuggerAtLine(view, lastTracebackInfo.lineNumber);+ }+ }}+ >+ <BugPlayIcon className="h-3 w-3 mr-2" />+ Insert breakpoint+ </Button>+ )}<DropdownMenu><DropdownMenuTrigger asChild={true}><Button size="xs" variant="text">@@ -153,9 +180,31 @@ function lastLine(text: string): string {export const replaceTracebackFilenames = (domNode: DOMNode) => {const info = getTracebackInfo(domNode);if (info) {+ const tooltipContent = <InsertBreakpointContent />;return (<span className="nb">- <CellLinkTraceback cellId={info.cellId} lineNumber={info.lineNumber} />+ <span className="inline-flex items-center">+ <CellLinkTraceback+ cellId={info.cellId}+ lineNumber={info.lineNumber}+ />+ <Tooltip content={tooltipContent}>+ <button+ type="button"+ className="ml-1 p-1 rounded-sm hover:bg-muted transition-all inline"+ >+ <BugPlayIcon+ onClick={() => {+ const view = getCellEditorView(info.cellId);+ if (view) {+ insertDebuggerAtLine(view, info.lineNumber);+ }+ }}+ className="h-3 w-3"+ />+ </button>+ </Tooltip>+ </span></span>);}@@ -171,3 +220,11 @@ export const replaceTracebackPrefix = (domNode: DOMNode) => {return <>{domNode.nodeValue.replace("File", "Cell")}</>;}};++const InsertBreakpointContent = () => {+ return (+ <>+ Insert a <Kbd className="inline">breakpoint()</Kbd> at this line+ </>+ );+};diff --git a/frontend/src/components/editor/output/__tests__/traceback.test.tsx b/frontend/src/components/editor/output/__tests__/traceback.test.tsxindex 8f5ef704b7..58c7f6892f 100644--- a/frontend/src/components/editor/output/__tests__/traceback.test.tsx+++ b/frontend/src/components/editor/output/__tests__/traceback.test.tsx@@ -8,10 +8,18 @@ import { renderHTML } from "@/plugins/core/RenderHTML";import { Tracebacks } from "@/__mocks__/tracebacks";import { render } from "@testing-library/react";import { describe, expect, test } from "vitest";+import type { CellId } from "@/core/cells/ids";+import { TooltipProvider } from "@/components/ui/tooltip";++const cellId = "1" as CellId;describe("traceback component", () => {test("extracts cell-link", () => {- const traceback = <MarimoTracebackOutput traceback={Tracebacks.raw} />;+ const traceback = (+ <TooltipProvider>+ <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cellId} />+ </TooltipProvider>+ );const { unmount, getAllByRole } = render(traceback);// Has traceback links@@ -27,7 +35,11 @@ describe("traceback component", () => {});test("renames File to Cell for relevant lines", () => {- const traceback = <MarimoTracebackOutput traceback={Tracebacks.raw} />;+ const traceback = (+ <TooltipProvider>+ <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cellId} />+ </TooltipProvider>+ );const { unmount, container } = render(traceback);expect(container).not.toBeNull();@@ -46,7 +58,9 @@ describe("traceback replacement", () => {html: Tracebacks.assertion,additionalReplacements: [replaceTracebackPrefix],});- const { unmount, container } = render(traceback);+ const { unmount, container } = render(+ <TooltipProvider>{traceback}</TooltipProvider>,+ );expect(container).not.toBeNull();@@ -63,7 +77,9 @@ describe("traceback replacement", () => {html: Tracebacks.assertion,additionalReplacements: [replaceTracebackFilenames],});- const { unmount, getAllByRole, container } = render(traceback);+ const { unmount, getAllByRole, container } = render(+ <TooltipProvider>{traceback}</TooltipProvider>,+ );expect(container).not.toBeNull();diff --git a/frontend/src/components/ui/input.tsx b/frontend/src/components/ui/input.tsxindex d2671a097e..3774e02f3f 100644--- a/frontend/src/components/ui/input.tsx+++ b/frontend/src/components/ui/input.tsx@@ -28,7 +28,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(return (<div className={cn("relative", props.rootClassName)}>{icon && (- <div className="absolute inset-y-0 left-0 flex items-center pl-[6px] pointer-events-none text-muted-foreground h-6">+ <div className="absolute inset-y-0 left-0 flex items-center pl-[6px] pointer-events-none text-muted-foreground">{icon}</div>)}diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex d3d0fac615..6615648bf4 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -1948,6 +1948,57 @@ describe("cell reducer", () => {expect(cell.consoleOutputs).toEqual([]);});+ it("can clear console output of a single cell", () => {+ // Set up initial state with output+ actions.handleCellMessage({+ cell_id: firstCellId,+ output: {+ channel: "output",+ mimetype: "text/plain",+ data: "test output",+ timestamp: 0,+ },+ console: {+ channel: "stdout",+ mimetype: "text/plain",+ data: "console output",+ timestamp: 0,+ },+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(33).getTime() as Seconds,+ });++ // Add a stdin console output that should be preserved+ actions.handleCellMessage({+ cell_id: firstCellId,+ console: {+ channel: "stdin",+ mimetype: "text/plain",+ data: "stdin prompt",+ timestamp: 0,+ },+ status: "idle",+ stale_inputs: null,+ timestamp: new Date(34).getTime() as Seconds,+ });++ // Verify initial state has output and console outputs+ let cell = cells[0];+ expect(cell.output).not.toBeNull();+ expect(cell.consoleOutputs.length).toBe(2);++ // Clear console output+ actions.clearCellConsoleOutput({ cellId: firstCellId });++ // Verify only console output is cleared, but stdin is preserved+ cell = cells[0];+ expect(cell.output).not.toBeNull(); // Output should remain+ expect(cell.consoleOutputs.length).toBe(1);+ expect(cell.consoleOutputs[0].channel).toBe("stdin");+ expect(cell.consoleOutputs[0].data).toBe("stdin prompt");+ });+it("can clear output of all cells", () => {// Create multiple cells with outputactions.createNewCell({ cellId: firstCellId, before: false });diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.tsindex dafc827eca..af3da3241a 100644--- a/frontend/src/core/cells/cell.ts+++ b/frontend/src/core/cells/cell.ts@@ -221,9 +221,12 @@ export function outputIsStale(}/**- * Convert a list of outputs to a traceback.+ * Extract traceback information from a list of outputs.+ * This function searches for the first output with a mimetype of+ * "application/vnd.marimo+traceback" and parses its data to retrieve+ * all traceback details.*/-export function outputToTraceback(+export function outputToTracebackInfo(outputs: OutputMessage[],): TracebackInfo[] | undefined {const firstTraceback = outputs.find(diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex e714a6d1cb..0ae34d66bc 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -1198,6 +1198,16 @@ const {consoleOutputs: [],}));},+ clearCellConsoleOutput: (state, action: { cellId: CellId }) => {+ const { cellId } = action;+ return updateCellRuntimeState(state, cellId, (cell) => ({+ ...cell,+ // Remove everything except unresponsed stdin+ consoleOutputs: cell.consoleOutputs.filter(+ (output) => output.channel === "stdin" && output.response == null,+ ),+ }));+ },clearAllCellOutputs: (state) => {const newCellRuntime = { ...state.cellRuntime };for (const cellId of state.cellIds.inOrderIds) {diff --git a/frontend/src/core/codemirror/editing/__tests__/debugging.test.ts b/frontend/src/core/codemirror/editing/__tests__/debugging.test.tsnew file mode 100644index 0000000000..9e1f673374--- /dev/null+++ b/frontend/src/core/codemirror/editing/__tests__/debugging.test.ts@@ -0,0 +1,192 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { python } from "@codemirror/lang-python";+import { insertDebuggerAtLine } from "../debugging";++describe("insertDebuggerAtLine", () => {+ let container: HTMLElement;+ let view: EditorView;++ beforeEach(() => {+ // Create a container for the editor+ container = document.createElement("div");+ document.body.append(container);+ });++ afterEach(() => {+ // Clean up after each test+ view.destroy();+ container.remove();+ });++ it("should insert a debugger statement at the beginning of a line", () => {+ // Create an editor with some python code+ const initialDoc = 'def test():\n print("hello")\n return True';++ view = new EditorView({+ state: EditorState.create({+ doc: initialDoc,+ extensions: [python()],+ }),+ parent: container,+ });++ // Insert a debugger statement at line 2+ const result = insertDebuggerAtLine(view, 2);++ // Check the result+ expect(result).toBe(true);++ // Check the updated document content+ const expectedDoc =+ 'def test():\n breakpoint()\n print("hello")\n return True';+ expect(view.state.doc.toString()).toBe(expectedDoc);++ // Check that the cursor is at the end of the breakpoint line+ const cursorPos = view.state.selection.main.head;+ const breakpointLine = view.state.doc.line(2);+ expect(cursorPos).toBe(breakpointLine.to);+ });++ it("should match the indentation of the target line", () => {+ // Create an editor with code that has different indentation levels+ const initialDoc =+ 'def test():\n if True:\n print("nested")\n return True';++ view = new EditorView({+ state: EditorState.create({+ doc: initialDoc,+ extensions: [python()],+ }),+ parent: container,+ });++ // Insert a debugger statement at the deeply indented line+ const result = insertDebuggerAtLine(view, 3);++ // Check the result+ expect(result).toBe(true);++ // Check that the debugger statement has the same indentation+ const expectedDoc =+ 'def test():\n if True:\n breakpoint()\n print("nested")\n return True';+ expect(view.state.doc.toString()).toBe(expectedDoc);++ // Check that the cursor is at the end of the breakpoint line+ const cursorPos = view.state.selection.main.head;+ const breakpointLine = view.state.doc.line(3);+ expect(cursorPos).toBe(breakpointLine.to);+ });++ it("should handle the first line correctly", () => {+ const initialDoc = "x = 1\ny = 2";++ view = new EditorView({+ state: EditorState.create({+ doc: initialDoc,+ extensions: [python()],+ }),+ parent: container,+ });++ // Insert a debugger statement at line 1+ const result = insertDebuggerAtLine(view, 1);++ // Check the result+ expect(result).toBe(true);++ // Check the updated document content+ const expectedDoc = "breakpoint()\nx = 1\ny = 2";+ expect(view.state.doc.toString()).toBe(expectedDoc);+ });++ it("should return false for invalid line numbers", () => {+ const initialDoc = "x = 1\ny = 2";++ view = new EditorView({+ state: EditorState.create({+ doc: initialDoc,+ extensions: [python()],+ }),+ parent: container,+ });++ // Try to insert a debugger statement at an invalid line+ const result = insertDebuggerAtLine(view, 999);++ // Check the result+ expect(result).toBe(false);++ // Check that the document was not modified+ expect(view.state.doc.toString()).toBe(initialDoc);+ });++ it("should handle empty lines correctly", () => {+ const initialDoc = "x = 1\n\ny = 2";++ view = new EditorView({+ state: EditorState.create({+ doc: initialDoc,+ extensions: [python()],+ }),+ parent: container,+ });++ // Insert a debugger statement at the empty line+ const result = insertDebuggerAtLine(view, 2);++ // Check the result+ expect(result).toBe(true);++ // Check the updated document content+ const expectedDoc = "x = 1\nbreakpoint()\n\ny = 2";+ expect(view.state.doc.toString()).toBe(expectedDoc);+ });++ it("should handle tab indentation correctly", () => {+ const initialDoc =+ 'def test():\n\tif True:\n\t\tprint("tabbed")\n\treturn True';++ view = new EditorView({+ state: EditorState.create({+ doc: initialDoc,+ extensions: [python()],+ }),+ parent: container,+ });++ // Insert a debugger statement at the tabbed line+ const result = insertDebuggerAtLine(view, 3);++ // Check the result+ expect(result).toBe(true);++ // Check that the debugger statement has the same tab indentation+ const expectedDoc =+ 'def test():\n\tif True:\n\t\tbreakpoint()\n\t\tprint("tabbed")\n\treturn True';+ expect(view.state.doc.toString()).toBe(expectedDoc);+ });++ it("should skip insertion if line already contains breakpoint()", () => {+ const initialDoc = "x = 1\nbreakpoint()\ny = 2";++ view = new EditorView({+ state: EditorState.create({+ doc: initialDoc,+ extensions: [python()],+ }),+ parent: container,+ });++ // Try to insert a debugger statement at line 2 which already has breakpoint()+ const result = insertDebuggerAtLine(view, 2);++ // Check the result+ expect(result).toBe(true);++ // Check that the document was not modified+ expect(view.state.doc.toString()).toBe(initialDoc);+ });+});diff --git a/frontend/src/core/codemirror/editing/debugging.ts b/frontend/src/core/codemirror/editing/debugging.tsnew file mode 100644index 0000000000..ce7e139710--- /dev/null+++ b/frontend/src/core/codemirror/editing/debugging.ts@@ -0,0 +1,57 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { Logger } from "@/utils/Logger";+import { EditorView } from "@codemirror/view";++export function insertDebuggerAtLine(view: EditorView, line: number): boolean {+ // Get the document+ const { state } = view;+ const doc = state.doc;++ // Check if the line number is valid+ if (line <= 0 || line > doc.lines) {+ Logger.warn(+ `Invalid line number: ${line}. Document has ${doc.lines} lines.`,+ );+ return false;+ }++ // Get the target line+ const targetLine = doc.line(line);++ // Skip if line already contains breakpoint()+ if (targetLine.text.includes("breakpoint()")) {+ return true;+ }++ // Extract the indentation from the target line+ const lineContent = targetLine.text;+ const indentMatch = lineContent.match(/^(\s*)/);+ const indentation = indentMatch ? indentMatch[1] : "";++ // Create the breakpoint statement with the same indentation+ const breakpointStatement = `${indentation}breakpoint()\n`;++ // Get the position where we need to insert the breakpoint statement+ const insertPos = targetLine.from;++ // Create and dispatch the transaction+ view.dispatch({+ changes: {+ from: insertPos,+ to: insertPos,+ insert: breakpointStatement,+ },+ // Scroll to the breakpoint+ selection: {+ anchor: insertPos + breakpointStatement.length - 1,+ head: insertPos + breakpointStatement.length - 1,+ },+ scrollIntoView: true,+ effects: [EditorView.scrollIntoView(insertPos, { y: "center" })],+ });++ // Focus the editor after the transaction+ view.focus();++ return true;+}diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 3dc7d7f840..47c8cbabe1 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -45,6 +45,7 @@ const props: CellProps = {deleteCell: Logger.log,actions: {updateCellCode: Logger.log,+ clearCellConsoleOutput: Logger.log,collapseCell: Logger.log,expandCell: Logger.log,createNewCell: Logger.log,