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 linenumber links in tracebacks (#1904)
Dylan Madisetti86501eaa7e8e
diff --git a/frontend/src/components/editor/links/cell-link.tsx b/frontend/src/components/editor/links/cell-link.tsxindex 78036f2595..ac914072a3 100644--- a/frontend/src/components/editor/links/cell-link.tsx+++ b/frontend/src/components/editor/links/cell-link.tsx@@ -1,9 +1,12 @@/* Copyright 2024 Marimo. All rights reserved. */+import { SCRATCH_CELL_ID } from "@/core/cells/cells";import { type CellId, HTMLCellId } from "@/core/cells/ids";import { Logger } from "../../../utils/Logger";import { cn } from "@/utils/cn";import { displayCellName } from "@/core/cells/names";import { useCellActions, useCellIds, useCellNames } from "@/core/cells/cells";+import { useFilename } from "@/core/saving/filename";+import { goToCellLine } from "@/core/codemirror/go-to-definition/utils";interface Props {cellId: CellId;@@ -11,15 +14,18 @@ interface Props {shouldScroll?: boolean;skipScroll?: boolean;onClick?: () => void;+ formatCellName?: (name: string) => string;variant?: "destructive" | "focus";}/* Component that adds a link to a cell, with styling. */export const CellLink = (props: Props): JSX.Element => {- const { className, cellId, variant, onClick, skipScroll } = props;+ const { className, cellId, variant, onClick, formatCellName, skipScroll } =+ props;const cellName = useCellNames()[cellId] ?? "";const cellIndex = useCellIds().inOrderIds.indexOf(cellId);const { showCellIfHidden } = useCellActions();+ const formatName = formatCellName ?? ((name: string) => name);return (<div@@ -27,7 +33,14 @@ export const CellLink = (props: Props): JSX.Element => {"inline-block cursor-pointer text-[var(--blue-10)] hover:underline",className,)}+ role="link"+ tabIndex={-1}onClick={(e) => {+ // Scratch causes a crash since scratch is not registered like a+ // normal cell.+ if (cellId == SCRATCH_CELL_ID) {+ return false;+ }showCellIfHidden({ cellId });e.stopPropagation();e.preventDefault();@@ -39,7 +52,7 @@ export const CellLink = (props: Props): JSX.Element => {});}}>- {displayCellName(cellName, cellIndex)}+ {formatName(displayCellName(cellName, cellIndex))}</div>);};@@ -51,6 +64,28 @@ export const CellLinkError = (return <CellLink {...props} variant={"destructive"} />;};+/* Component that adds a link to a cell, for use in tracebacks. */+export const CellLinkTraceback = ({+ cellId,+ lineNumber,+}: { cellId: CellId; lineNumber: number }): JSX.Element => {+ const [filename] = useFilename();+ return (+ <CellLink+ cellId={cellId}+ onClick={() => goToCellLine(cellId, lineNumber)}+ skipScroll={true}+ variant={"destructive"}+ className="traceback-cell-link"+ formatCellName={(name: string) =>+ cellId == SCRATCH_CELL_ID+ ? "scratch"+ : `marimo://${filename || "untitled"}#cell=${name}`+ }+ />+ );+};+export function scrollAndHighlightCell(cellId: CellId,variant?: "destructive" | "focus",diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsxindex b4f074362e..db112d44c4 100644--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx@@ -2,6 +2,8 @@import { cn } from "../../../utils/cn";+import { type CellId } from "@/core/cells/ids";+import {Accordion,AccordionContent,@@ -14,6 +16,9 @@ import { BugIcon, ChevronDown, ExternalLinkIcon } from "lucide-react";import { useState } from "react";import { useAtomValue } from "jotai";import { aiEnabledAtom } from "@/core/config/config";+import { Element, Text, DOMNode } from "html-react-parser";++import { CellLinkTraceback } from "../links/cell-link";interface Props {traceback: string;@@ -29,7 +34,10 @@ export const MarimoTracebackOutput = ({onRefactorWithAI,traceback,}: Props): JSX.Element => {- const htmlTraceback = renderHTML({ html: traceback });+ const htmlTraceback = renderHTML({+ html: traceback,+ additionalReplacements: [replaceTracebackFilenames, replaceTracebackPrefix],+ });const [expanded, setExpanded] = useState(true);const lastTracebackLine = lastLine(traceback);@@ -94,3 +102,86 @@ function lastLine(text: string): string {const lines = el.textContent?.split("\n").filter(Boolean);return lines?.at(-1) || "";}++const matchesSelector = (domNode: Element, selector: string) => {+ const [tagName, ...classes] = selector.split(".");+ // Note domhandler.Element does not have a classList property, just an+ // (optional) string attribute.+ const classList = (domNode.attribs.class || "").split(" ");+ return (+ domNode.tagName === tagName &&+ classes.every((cls) => classList.includes(cls))+ );+};+const elementContainsMarimoCellFile = (domNode: Element) => {+ return (+ domNode &&+ matchesSelector(domNode, "span.nb") &&+ domNode.firstChild instanceof Text &&+ domNode.firstChild.nodeValue?.includes("__marimo__")+ );+};++export const replaceTracebackFilenames = (domNode: DOMNode) => {+ // The traceback can be manipulated either in output render or in the pygments+ // parser. pygments extracts tokens and maps them to tags, but has no+ // inherient knowledge of the traceback structure, so the methodology would+ // have to be similar. Moreover, the client side "cell-id" is particular to+ // frontend, so frontend handling would have to occur anyway.+ //+ // A little verbose working with intermediate representation, but best reference+ // for documentation is found in library source (@domhandler/src/node.ts)+ //+ // Expected to transform:+ //+ // File <span class="nb">"/tmp/marimo_<number>/__marimo__cell_<cell-id>.py</span>+ // , line <span class="n">1</span>...+ //+ // into+ //+ // File marimo://notebook#cell=<CellID>, line 1, in <module>+ if (+ domNode instanceof Element &&+ domNode.firstChild instanceof Text &&+ elementContainsMarimoCellFile(domNode)+ ) {+ const nextSibling = domNode.next;+ if (nextSibling && nextSibling instanceof Text) {+ const lineSibling = nextSibling.next;+ if (+ lineSibling &&+ lineSibling instanceof Element &&+ lineSibling.firstChild instanceof Text &&+ matchesSelector(lineSibling, "span.m")+ ) {+ const cellId = /__marimo__cell_(\w+)_/.exec(+ domNode.firstChild.nodeValue,+ )?.[1];+ const lineNumber = Number.parseInt(+ lineSibling.firstChild.nodeValue || "0",+ );+ if (cellId && lineNumber) {+ return (+ <span className="nb">+ <CellLinkTraceback+ cellId={cellId as CellId}+ lineNumber={lineNumber}+ />+ </span>+ );+ }+ }+ }+ }+};++export const replaceTracebackPrefix = (domNode: DOMNode) => {+ if (+ domNode instanceof Text &&+ domNode.nodeValue?.includes("File") &&+ domNode.next instanceof Element &&+ elementContainsMarimoCellFile(domNode.next)+ ) {+ return <>{domNode.nodeValue.replace("File", "Cell")}</>;+ }+};diff --git a/frontend/src/components/editor/output/Outputs.css b/frontend/src/components/editor/output/Outputs.cssindex 7a7d21259d..0f19c625c4 100644--- a/frontend/src/components/editor/output/Outputs.css+++ b/frontend/src/components/editor/output/Outputs.css@@ -72,3 +72,7 @@margin-top: 0.2rem;margin-bottom: 0.2rem;}++.traceback-cell-link {+ color: inherit;+}diff --git a/frontend/src/components/editor/output/__tests__/traceback.test.tsx b/frontend/src/components/editor/output/__tests__/traceback.test.tsxnew file mode 100644index 0000000000..3f17edaa67--- /dev/null+++ b/frontend/src/components/editor/output/__tests__/traceback.test.tsx@@ -0,0 +1,110 @@+/* Copyright 2024 Marimo. All rights reserved. */+import {+ MarimoTracebackOutput,+ replaceTracebackPrefix,+ replaceTracebackFilenames,+} from "../MarimoTracebackOutput";+import { renderHTML } from "@/plugins/core/RenderHTML";++import { render } from "@testing-library/react";+import { describe, expect, test } from "vitest";++// from:+// def foo():+// return 1/ 0+// foo()+const rawTraceback = `<div class="highlight"><pre><span></span><span class="gt">Traceback (most recent call last):</span>+ File <span class="nb">"/lib/python3.12/site-packages/marimo/_runtime/executor.py"</span>, line <span class="m">193</span>, in <span class="n">execute_cell</span>+<span class="w"> </span><span class="k">return</span> <span class="nb">eval</span><span class="p">(</span><span class="n">cell</span><span class="o">.</span><span class="n">last_expr</span><span class="p">,</span> <span class="n">glbls</span><span class="p">)</span>+<span class="w"> </span><span class="pm">^^^^^^^^^^^^^^^^^^^^^^^^^^^</span>+ File <span class="nb">"/tmp/marimo_42/__marimo__cell_Hbol_.py"</span>, line <span class="m">4</span>, in <span class="n"><module></span>+<span class="w"> </span><span class="n">foo</span><span class="p">()</span>+ File <span class="nb">"/tmp/marimo_42/__marimo__cell_Hbol_.py"</span>, line <span class="m">2</span>, in <span class="n">foo</span>+<span class="w"> </span><span class="k">return</span> <span class="mi">1</span><span class="o">/</span> <span class="mi">0</span>+<span class="w"> </span><span class="pm">~^~~</span>+<span class="gr">ZeroDivisionError</span>: <span class="n">division by zero</span>+</pre></div>`;++// from:+// assert not "File /tmp/marimo_42/__marimo__cell_Hbol_.py"+const assertionTraceback = `<div class="highlight"><pre><span></span><span class="gt">Traceback (most recent call last):</span>+ File <span class="nb">"/lib/python3.12/site-packages/marimo/_runtime/executor.py"</span>, line <span class="m">192</span>, in <span class="n">execute_cell</span>+<span class="w"> </span><span class="n">exec</span><span class="p">(</span><span class="n">cell</span><span class="o">.</span><span class="n">body</span><span class="p">,</span> <span class="n">glbls</span><span class="p">)</span>+ File <span class="nb">"/tmp/marimo_42/__marimo__cell_Hbol_.py"</span>, line <span class="m">1</span>, in <span class="n"><module></span>+<span class="w"> </span><span class="k">assert</span> <span class="ow">not</span> <span class="s2">"File /tmp/marimo_42/__marimo__cell_Hbol_.py"</span>+<span class="gr">AssertionError</span>+</pre></div>`;++describe("traceback component", () => {+ test("extracts cell-link", () => {+ const traceback = <MarimoTracebackOutput traceback={rawTraceback} />;+ const { unmount, getAllByRole } = render(traceback);++ // Has traceback links and google search link+ expect(getAllByRole("link")).toHaveLength(3);+ // Check that the traceback links are parsed+ expect(getAllByRole("link")[0].textContent).toContain(+ "marimo://untitled#cell=",+ );+ expect(getAllByRole("link")[1].textContent).toContain(+ "marimo://untitled#cell=",+ );+ unmount();+ });++ test("renames File to Cell for relevant lines", () => {+ const traceback = <MarimoTracebackOutput traceback={rawTraceback} />;+ const { unmount, container } = render(traceback);++ expect(container).not.toBeNull();++ expect(rawTraceback).not.toMatch(/Cell/);+ expect(container.textContent).toMatch(/Cell/);+ expect(rawTraceback.match(/File/g)).toHaveLength(3);+ expect(container?.textContent?.match(/File/g)).toHaveLength(1);+ unmount();+ });+});++describe("traceback replacement", () => {+ test("replaces File with Cell", () => {+ const traceback = renderHTML({+ html: assertionTraceback,+ additionalReplacements: [replaceTracebackPrefix],+ });+ const { unmount, container } = render(traceback);++ expect(container).not.toBeNull();++ expect(assertionTraceback).not.toMatch(/Cell/);+ expect(container.textContent).toMatch(/Cell/);+ expect(assertionTraceback.match(/File/g)).toHaveLength(3);+ // Only replaces the relevant File to Cell+ expect(container?.textContent?.match(/File/g)).toHaveLength(2);+ unmount();+ });++ test("renames filenames", () => {+ const traceback = renderHTML({+ html: assertionTraceback,+ additionalReplacements: [replaceTracebackFilenames],+ });+ const { unmount, getAllByRole, container } = render(traceback);++ expect(container).not.toBeNull();++ // Has just traceback links+ expect(getAllByRole("link")).toHaveLength(1);+ // Check that the traceback links are parsed+ expect(getAllByRole("link")[0].textContent).toContain(+ "marimo://untitled#cell=",+ );++ expect(assertionTraceback.match(/__marimo__cell_Hbol_/g)).toHaveLength(2);+ // Still contains the string of the filename in the trace+ expect(container?.textContent?.match(/__marimo__cell_Hbol_/g)).toHaveLength(+ 1,+ );+ unmount();+ });+});diff --git a/frontend/src/core/codemirror/go-to-definition/commands.ts b/frontend/src/core/codemirror/go-to-definition/commands.tsindex a556c7bb96..a09e9a6367 100644--- a/frontend/src/core/codemirror/go-to-definition/commands.ts+++ b/frontend/src/core/codemirror/go-to-definition/commands.ts@@ -2,6 +2,25 @@import { EditorView } from "@codemirror/view";import { syntaxTree } from "@codemirror/language";+function goToPosition(view: EditorView, from: number): void {+ view.focus();+ // Wait for the next frame, otherwise codemirror will+ // add a cursor from a pointer click.+ requestAnimationFrame(() => {+ view.dispatch({+ selection: {+ anchor: from,+ head: from,+ },+ // Unfortunately, EditorView.scrollIntoView does+ // not support smooth scrolling.+ effects: EditorView.scrollIntoView(from, {+ y: "center",+ }),+ });+ });+}+/*** This function will select the first occurrence of the given variable name,* for a given editor view.@@ -42,23 +61,19 @@ export function goToVariableDefinition(});if (found) {- view.focus();- // Wait for the next frame, otherwise codemirror will- // add a cursor from a pointer click.- requestAnimationFrame(() => {- view.dispatch({- selection: {- anchor: from,- head: from,- },- // Unfortunately, EditorView.scrollIntoView does- // not support smooth scrolling.- effects: EditorView.scrollIntoView(from, {- y: "center",- }),- });- });+ goToPosition(view, from);return true;}return false;}++/**+ * This function jumps to a given position in the editor.+ * @param view The editor view which contains the variable name.+ * @param lineNumber The line number to jump to.+ */+export function goToLine(view: EditorView, lineNumber: number): boolean {+ const line = view.state.doc.line(lineNumber);+ goToPosition(view, line.from);+ return true;+}diff --git a/frontend/src/core/codemirror/go-to-definition/utils.ts b/frontend/src/core/codemirror/go-to-definition/utils.tsindex fa095763e6..ac9aa1f341 100644--- a/frontend/src/core/codemirror/go-to-definition/utils.ts+++ b/frontend/src/core/codemirror/go-to-definition/utils.ts@@ -7,7 +7,7 @@ import { store } from "../../state/jotai";import { notebookAtom } from "../../cells/cells";import { variablesAtom } from "../../variables/state";import type { CellId } from "@/core/cells/ids";-import { goToVariableDefinition } from "./commands";+import { goToVariableDefinition, goToLine } from "./commands";import { closeCompletion } from "@codemirror/autocomplete";/**@@ -77,6 +77,19 @@ export function goToDefinition(return goToVariableDefinition(editorWithVariable, variableName);}+/**+ * Go to the given line number in the cell with the given ID.+ * @param cellId The ID of the cell to go to.+ * @param line The line number to go to.+ */+export function goToCellLine(cellId: CellId, lineNumber: number): boolean {+ const view = getEditorForCell(cellId);+ if (!view) {+ return false;+ }+ return goToLine(view, lineNumber);+}+/*** @param editor The editor view at which the command was invoked.* @param variableName The name of the variable to go to.@@ -95,9 +108,18 @@ function getEditorForVariable(const cellId = getCellIdOfDefinition(variables, variableName);if (cellId) {- const notebookState = store.get(notebookAtom);- return notebookState.cellHandles[cellId].current?.editorView ?? null;+ return getEditorForCell(cellId);}return null;}++/**+ * Go to the given line number in the editor view.+ * @param view The editor view to go to.+ * @param line The line number to go to.+ */+function getEditorForCell(cellId: CellId): EditorView | null {+ const notebookState = store.get(notebookAtom);+ return notebookState.cellHandles[cellId].current?.editorView ?? null;+}diff --git a/frontend/src/core/dom/htmlUtils.ts b/frontend/src/core/dom/htmlUtils.tsindex 9772772551..728cc24611 100644--- a/frontend/src/core/dom/htmlUtils.ts+++ b/frontend/src/core/dom/htmlUtils.ts@@ -59,6 +59,9 @@ export function getFilenameFromDOM() {}const filenameTag = document.querySelector("marimo-filename");+ if (import.meta.env.MODE === "test" && !filenameTag) {+ return null;+ }assertExists(filenameTag, "marimo-filename tag not found");const name = filenameTag.innerHTML;return name.length === 0 ? null : name;diff --git a/frontend/src/plugins/core/RenderHTML.tsx b/frontend/src/plugins/core/RenderHTML.tsxindex d938deef42..2e7a245c8f 100644--- a/frontend/src/plugins/core/RenderHTML.tsx+++ b/frontend/src/plugins/core/RenderHTML.tsx@@ -1,45 +1,58 @@/* Copyright 2024 Marimo. All rights reserved. */-import parse, { Element } from "html-react-parser";+import parse, { Element, DOMNode } from "html-react-parser";import React from "react";+type ReplacementFn = Array<(domNode: DOMNode) => JSX.Element | undefined>;+interface Options {html: string;+ additionalReplacements?: ReplacementFn;}-/**- * We instead render HTML to React elements using html-react-parser as this keeps- * React elements in place so React's reconciliation algorithm will update nodes instead of unmounting and remounting.- */-export const renderHTML = ({ html }: Options) => {- return parse(html, {- replace: (domNode) => {- // Don't render invalid tags- if (- domNode instanceof Element &&- !/^[A-Za-z][\w-]*$/.test(domNode.name)- ) {- return React.createElement(React.Fragment);+const replaceValidTags = (domNode: DOMNode) => {+ // Don't render invalid tags+ if (domNode instanceof Element && !/^[A-Za-z][\w-]*$/.test(domNode.name)) {+ return React.createElement(React.Fragment);+ }+};++const replaceValidIframes = (domNode: DOMNode) => {+ // For iframe, we just want to use dangerouslySetInnerHTML so:+ // 1) we can remount the iframe when the src changes+ // 2) keep event attributes (onload, etc.) since this library removes them+ if (+ domNode instanceof Element &&+ domNode.attribs &&+ domNode.name === "iframe"+ ) {+ const element = document.createElement("iframe");+ Object.entries(domNode.attribs).forEach(([key, value]) => {+ // If it is wrapped in quotes, remove them+ // html-react-parser will return quoted keys if they are+ // valueless attributes (e.g. "allowfullscreen")+ if (key.startsWith('"') && key.endsWith('"')) {+ key = key.slice(1, -1);}+ element.setAttribute(key, value);+ });+ return <div dangerouslySetInnerHTML={{ __html: element.outerHTML }} />;+ }+};++export const renderHTML = ({ html, additionalReplacements = [] }: Options) => {+ const renderFunctions: ReplacementFn = [+ replaceValidTags,+ replaceValidIframes,+ ...additionalReplacements,+ ];- // For iframe, we just want to use dangerouslySetInnerHTML so:- // 1) we can remount the iframe when the src changes- // 2) keep event attributes (onload, etc.) since this library removes them- if (- domNode instanceof Element &&- domNode.attribs &&- domNode.name === "iframe"- ) {- const element = document.createElement("iframe");- Object.entries(domNode.attribs).forEach(([key, value]) => {- // If it is wrapped in quotes, remove them- // html-react-parser will return quoted keys if they are- // valueless attributes (e.g. "allowfullscreen")- if (key.startsWith('"') && key.endsWith('"')) {- key = key.slice(1, -1);- }- element.setAttribute(key, value);- });- return <div dangerouslySetInnerHTML={{ __html: element.outerHTML }} />;+ return parse(html, {+ replace: (domNode: DOMNode) => {+ for (const renderFunction of renderFunctions) {+ const replacement = renderFunction(domNode);+ if (replacement) {+ return replacement;+ }}return domNode;},