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: highlight lines when cell has a traceback (#4779)
Myles Scolnickfb9bb7a30fa0
diff --git a/frontend/src/__mocks__/tracebacks.ts b/frontend/src/__mocks__/tracebacks.tsnew file mode 100644index 0000000000..0f4cb6acfd--- /dev/null+++ b/frontend/src/__mocks__/tracebacks.ts@@ -0,0 +1,32 @@+/* Copyright 2024 Marimo. All rights reserved. */++// 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>`;++export const Tracebacks = {+ raw: rawTraceback,+ assertion: assertionTraceback,+};diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsxindex 66029fd80e..d7abd84f8a 100644--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx@@ -2,8 +2,6 @@import { cn } from "../../../utils/cn";-import type { CellId } from "@/core/cells/ids";-import {Accordion,AccordionContent,@@ -33,6 +31,10 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { copyToClipboard } from "@/utils/copy";+import {+ elementContainsMarimoCellFile,+ getTracebackInfo,+} from "@/utils/traceback";interface Props {traceback: string;@@ -148,75 +150,14 @@ function lastLine(text: string): string {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- // inherent 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>- );- }- }- }+ const info = getTracebackInfo(domNode);+ if (info) {+ return (+ <span className="nb">+ <CellLinkTraceback cellId={info.cellId} lineNumber={info.lineNumber} />+ </span>+ );}};diff --git a/frontend/src/components/editor/output/__tests__/traceback.test.tsx b/frontend/src/components/editor/output/__tests__/traceback.test.tsxindex bc8b4ebf11..8f5ef704b7 100644--- a/frontend/src/components/editor/output/__tests__/traceback.test.tsx+++ b/frontend/src/components/editor/output/__tests__/traceback.test.tsx@@ -5,39 +5,13 @@ import {replaceTracebackFilenames,} from "../MarimoTracebackOutput";import { renderHTML } from "@/plugins/core/RenderHTML";-+import { Tracebacks } from "@/__mocks__/tracebacks";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 traceback = <MarimoTracebackOutput traceback={Tracebacks.raw} />;const { unmount, getAllByRole } = render(traceback);// Has traceback links@@ -53,14 +27,14 @@ describe("traceback component", () => {});test("renames File to Cell for relevant lines", () => {- const traceback = <MarimoTracebackOutput traceback={rawTraceback} />;+ const traceback = <MarimoTracebackOutput traceback={Tracebacks.raw} />;const { unmount, container } = render(traceback);expect(container).not.toBeNull();- expect(rawTraceback).not.toMatch(/Cell/);+ expect(Tracebacks.raw).not.toMatch(/Cell/);expect(container.textContent).toMatch(/Cell/);- expect(rawTraceback.match(/File/g)).toHaveLength(3);+ expect(Tracebacks.raw.match(/File/g)).toHaveLength(3);expect(container?.textContent?.match(/File/g)).toHaveLength(1);unmount();});@@ -69,16 +43,16 @@ describe("traceback component", () => {describe("traceback replacement", () => {test("replaces File with Cell", () => {const traceback = renderHTML({- html: assertionTraceback,+ html: Tracebacks.assertion,additionalReplacements: [replaceTracebackPrefix],});const { unmount, container } = render(traceback);expect(container).not.toBeNull();- expect(assertionTraceback).not.toMatch(/Cell/);+ expect(Tracebacks.assertion).not.toMatch(/Cell/);expect(container.textContent).toMatch(/Cell/);- expect(assertionTraceback.match(/File/g)).toHaveLength(3);+ expect(Tracebacks.assertion.match(/File/g)).toHaveLength(3);// Only replaces the relevant File to Cellexpect(container?.textContent?.match(/File/g)).toHaveLength(2);unmount();@@ -86,7 +60,7 @@ describe("traceback replacement", () => {test("renames filenames", () => {const traceback = renderHTML({- html: assertionTraceback,+ html: Tracebacks.assertion,additionalReplacements: [replaceTracebackFilenames],});const { unmount, getAllByRole, container } = render(traceback);@@ -100,7 +74,7 @@ describe("traceback replacement", () => {"marimo://untitled#cell=",);- expect(assertionTraceback.match(/__marimo__cell_Hbol_/g)).toHaveLength(2);+ expect(Tracebacks.assertion.match(/__marimo__cell_Hbol_/g)).toHaveLength(2);// Still contains the string of the filename in the traceexpect(container?.textContent?.match(/__marimo__cell_Hbol_/g)).toHaveLength(1,diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.tsindex 880b31c6e5..dafc827eca 100644--- a/frontend/src/core/cells/cell.ts+++ b/frontend/src/core/cells/cell.ts@@ -1,12 +1,13 @@/* Copyright 2024 Marimo. All rights reserved. */import { logNever } from "@/utils/assertNever";-import type { CellMessage } from "../kernel/messages";+import type { CellMessage, OutputMessage } from "../kernel/messages";import type { CellRuntimeState } from "./types";import { collapseConsoleOutputs } from "./collapseConsoleOutputs";import { parseOutline } from "../dom/outline";import { type Seconds, Time } from "@/utils/time";import { invariant } from "@/utils/invariant";import type { RuntimeState } from "../network/types";+import { extractAllTracebackInfo, type TracebackInfo } from "@/utils/traceback";export function transitionCell(cell: CellRuntimeState,@@ -218,3 +219,22 @@ export function outputIsStale(return staleInputs;}++/**+ * Convert a list of outputs to a traceback.+ */+export function outputToTraceback(+ outputs: OutputMessage[],+): TracebackInfo[] | undefined {+ const firstTraceback = outputs.find(+ (output) => output.mimetype === "application/vnd.marimo+traceback",+ );+ if (!firstTraceback) {+ return undefined;+ }+ const traceback = firstTraceback.data;+ if (typeof traceback !== "string") {+ return undefined;+ }+ return extractAllTracebackInfo(traceback);+}diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 6f3c12af2f..db665e66cd 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { atom, useAtom, useAtomValue } from "jotai";+import { type Atom, atom, useAtom, useAtomValue } from "jotai";import { type ReducerWithoutAction, createRef } from "react";import type { CellMessage } from "../kernel/messages";import {@@ -49,6 +49,7 @@ import {} from "@/utils/id-tree";import { isEqual, zip } from "lodash-es";import { isErrorMime } from "../mime";+import { extractAllTracebackInfo, type TracebackInfo } from "@/utils/traceback";export const SCRATCH_CELL_ID = "__scratch__" as CellId;export const SETUP_CELL_ID = "setup" as CellId;@@ -1495,6 +1496,46 @@ export function flattenTopLevelNotebookCells();}+export function createTracebackInfoAtom(+ cellId: CellId,+): Atom<TracebackInfo[] | undefined> {+ // We create an intermediate atom that just computes the string+ // so it prevents downstream recomputations.+ const tracebackStringAtom = atom<string | undefined>((get) => {+ const notebook = get(notebookAtom);+ const data = notebook.cellRuntime[cellId];+ if (!data) {+ return undefined;+ }+ // Must be errored and idle+ if (data.status !== "idle") {+ return undefined;+ }+ const outputs = data.consoleOutputs;+ // console.warn(notebook);+ if (!outputs || outputs.length === 0) {+ return undefined;+ }++ const firstTraceback = outputs.find(+ (output) => output.mimetype === "application/vnd.marimo+traceback",+ );+ if (!firstTraceback) {+ return undefined;+ }+ const traceback = firstTraceback.data;+ return traceback as string;+ });++ return atom((get) => {+ const traceback = get(tracebackStringAtom);+ if (!traceback) {+ return undefined;+ }+ return extractAllTracebackInfo(traceback);+ });+}+/*** Use this hook to dispatch cell actions. This hook will not cause a re-render* when cells change.diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex c3efd1c896..ca64b1088c 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -14,7 +14,10 @@ import {cellIdState,type CodemirrorCellActions,} from "./state";-import { SCRATCH_CELL_ID } from "@/core/cells/cells";+import { createTracebackInfoAtom, SCRATCH_CELL_ID } from "@/core/cells/cells";+import { errorLineHighlighter } from "./traceback-decorations";+import { createObservable } from "@/core/state/observable";+import { store } from "@/core/state/jotai";/*** Extensions for cell actions@@ -346,5 +349,8 @@ export function cellBundle(cellIdState.of(cellId),cellKeymaps(cellId, hotkeys),cellCodeEditing(hotkeys),+ errorLineHighlighter(+ createObservable(createTracebackInfoAtom(cellId), store),+ ),];}diff --git a/frontend/src/core/codemirror/cells/traceback-decorations.ts b/frontend/src/core/codemirror/cells/traceback-decorations.tsnew file mode 100644index 0000000000..6be6f3b64c--- /dev/null+++ b/frontend/src/core/codemirror/cells/traceback-decorations.ts@@ -0,0 +1,101 @@+/* Copyright 2024 Marimo. All rights reserved. */+import {+ Decoration,+ type DecorationSet,+ EditorView,+ type PluginValue,+ ViewPlugin,+ type ViewUpdate,+} from "@codemirror/view";+import type { Extension, EditorState } from "@codemirror/state";+import { RangeSetBuilder } from "@codemirror/state";+import type { Observable } from "@/core/state/observable";+import type { TracebackInfo } from "@/utils/traceback";+import { cellIdState } from "./state";++type TracebackInfos = TracebackInfo[] | undefined;++/**+ * Create the decoration for error lines.+ */+function createErrorDecorations(state: EditorState, errors: TracebackInfos) {+ if (!errors?.length) {+ return Decoration.none;+ }++ const builder = new RangeSetBuilder<Decoration>();+ const cellId = state.facet(cellIdState);++ // Filter and sort errors by line number to ensure they're added in order+ const relevantErrors = errors+ .filter((error) => error.cellId === cellId)+ .sort((a, b) => a.lineNumber - b.lineNumber);++ for (const error of relevantErrors) {+ const line = state.doc.line(error.lineNumber);+ const deco = Decoration.line({+ class: "cm-error-line",+ });+ builder.add(line.from, line.from, deco);+ }++ return builder.finish();+}++/**+ * A view plugin that highlights error lines in the editor.+ */+class ErrorHighlighter implements PluginValue {+ private unsubscribe: () => void;+ decorations: DecorationSet;++ constructor(view: EditorView, errorsObservable: Observable<TracebackInfos>) {+ this.decorations = createErrorDecorations(+ view.state,+ errorsObservable.get(),+ );++ this.unsubscribe = errorsObservable.sub((errors) => {+ this.decorations = createErrorDecorations(view.state, errors);+ });+ }++ update(update: ViewUpdate) {+ this.decorations = this.decorations.map(update.changes);+ }++ destroy() {+ this.unsubscribe();+ }+}++/**+ * Create a view plugin that highlights error lines in the editor.+ */+function createErrorHighlighter(errorsObservable: Observable<TracebackInfos>) {+ return ViewPlugin.define(+ (view) => new ErrorHighlighter(view, errorsObservable),+ {+ decorations: (f) => f.decorations,+ },+ );+}++/**+ * Create an extension that highlights error lines in the editor.+ */+export function errorLineHighlighter(+ errorsObservable: Observable<TracebackInfos>,+): Extension {+ return [+ createErrorHighlighter(errorsObservable),+ EditorView.theme({+ ".cm-error-line": {+ backgroundColor: "color-mix(in srgb, var(--red-4) 40%, transparent)",+ },+ "&.cm-focused .cm-error-line.cm-activeLine": {+ backgroundColor: "color-mix(in srgb, var(--red-6) 40%, transparent)",+ },+ }),+ ];+}diff --git a/frontend/src/core/codemirror/utils.ts b/frontend/src/core/codemirror/utils.tsindex fb769bc651..fc0c9036e0 100644--- a/frontend/src/core/codemirror/utils.ts+++ b/frontend/src/core/codemirror/utils.ts@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */-import type { EditorState } from "@codemirror/state";-import type { EditorView } from "@codemirror/view";+import type { EditorState, Transaction } from "@codemirror/state";+import type { EditorView, ViewUpdate } from "@codemirror/view";import { getCM } from "@replit/codemirror-vim";export function isAtStartOfEditor(ev: { state: EditorState }) {@@ -60,3 +60,40 @@ export function selectAllText(ev: EditorView | undefined) {},});}++/**+ * Checks if a transaction contains changes that add or remove line breaks.+ *+ * @param tr The CodeMirror transaction to check+ * @returns True if the transaction adds or removes line breaks, false otherwise+ */+export function hasNewLines(tr: Transaction | ViewUpdate): boolean {+ // If there are no changes in the transaction, return false+ if (!tr.docChanged) {+ return false;+ }++ let hasNewLines = false;+ // Iterate through all changes in the transaction+ tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => {+ // Check if the inserted text contains line breaks+ if (inserted.toString().includes("\n")) {+ hasNewLines = true;+ }++ // Count the number of line breaks in the deleted range+ const deletedText = tr.startState.doc.sliceString(fromA, toA);+ if (deletedText.includes("\n")) {+ hasNewLines = true;+ }++ // Another approach: check if the change spans multiple lines+ const fromLine = tr.startState.doc.lineAt(fromA).number;+ const toLine = tr.startState.doc.lineAt(toA).number;+ if (fromLine !== toLine) {+ hasNewLines = true;+ }+ });++ return hasNewLines;+}diff --git a/frontend/src/core/state/jotai.ts b/frontend/src/core/state/jotai.tsindex 5a3df068be..8df34284c6 100644--- a/frontend/src/core/state/jotai.ts+++ b/frontend/src/core/state/jotai.ts@@ -7,6 +7,7 @@ import { useEffect } from "react";* Global store allows getting and setting global state outside of React components.*/export const store = createStore();+export type JotaiStore = typeof store;/*** Wait for an atom to satisfy a predicate.diff --git a/frontend/src/core/state/observable.ts b/frontend/src/core/state/observable.tsnew file mode 100644index 0000000000..fe10a86d1d--- /dev/null+++ b/frontend/src/core/state/observable.ts@@ -0,0 +1,23 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { Atom } from "jotai";+import type { JotaiStore } from "./jotai";++export interface Observable<T> {+ get(): T;+ sub(callback: (value: T) => void): () => void;+}++/**+ * Create an observable from a Jotai atom.+ *+ * This is just a simpler read-only API that hides the Jotai store.+ */+export function createObservable<T>(+ value: Atom<T>,+ store: JotaiStore,+): Observable<T> {+ return {+ get: () => store.get(value),+ sub: (callback) => store.sub(value, () => callback(store.get(value))),+ };+}diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.cssindex b43ef78aad..4975c49961 100644--- a/frontend/src/css/app/Cell.css+++ b/frontend/src/css/app/Cell.css@@ -345,12 +345,12 @@background: #e2f2ff;}- .cm-activeLine {+ .cm-activeLine:not(.cm-error-line) {background: hsl(210deg 100% 50% / 3%);}}- .cm-activeLine {+ .cm-activeLine:not(.cm-error-line) {background: transparent;/* Soften the corners of the active-line highlight. */diff --git a/frontend/src/utils/__tests__/traceback.test.ts b/frontend/src/utils/__tests__/traceback.test.tsnew file mode 100644index 0000000000..9c32a37457--- /dev/null+++ b/frontend/src/utils/__tests__/traceback.test.ts@@ -0,0 +1,34 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, expect, test } from "vitest";+import { extractAllTracebackInfo } from "../traceback";+import { Tracebacks } from "@/__mocks__/tracebacks";++describe("traceback", () => {+ test("extracts cell-link", () => {+ const errors = extractAllTracebackInfo(Tracebacks.raw);+ expect(errors).toMatchInlineSnapshot(`+ [+ {+ "cellId": "Hbol",+ "lineNumber": 4,+ },+ {+ "cellId": "Hbol",+ "lineNumber": 2,+ },+ ]+ `);+ });++ test("extracts cell-link from assertion", () => {+ const info = extractAllTracebackInfo(Tracebacks.assertion);+ expect(info).toMatchInlineSnapshot(`+ [+ {+ "cellId": "Hbol",+ "lineNumber": 1,+ },+ ]+ `);+ });+});diff --git a/frontend/src/utils/traceback.ts b/frontend/src/utils/traceback.tsnew file mode 100644index 0000000000..457d010f05--- /dev/null+++ b/frontend/src/utils/traceback.ts@@ -0,0 +1,106 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { CellId } from "@/core/cells/ids";+import { type DOMNode, Element, Text } from "html-react-parser";+import parse from "html-react-parser";++/**+ * Check if a DOM node matches a selector.+ */+export 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))+ );+};++/**+ * Check if a DOM node contains a marimo cell file.+ */+export const elementContainsMarimoCellFile = (domNode: Element) => {+ return (+ domNode &&+ matchesSelector(domNode, "span.nb") &&+ domNode.firstChild instanceof Text &&+ domNode.firstChild.nodeValue?.includes("__marimo__")+ );+};++export interface TracebackInfo {+ cellId: CellId;+ lineNumber: number;+}++/**+ * Extract the cell id and line number from a traceback DOM node.+ */+export function getTracebackInfo(domNode: DOMNode): TracebackInfo | null {+ // 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+ // inherent 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 { cellId: cellId as CellId, lineNumber };+ }+ }+ }+ }+ return null;+}++export function extractAllTracebackInfo(traceback: string): TracebackInfo[] {+ const infos: TracebackInfo[] = [];++ // Parse the traceback to recurse over the DOM.+ // We don't do anything with the result.+ parse(traceback, {+ replace: (domNode) => {+ const info = getTracebackInfo(domNode);+ if (info) {+ infos.push({+ cellId: info.cellId,+ lineNumber: info.lineNumber,+ });+ return `${info.cellId}:${info.lineNumber}`;+ }+ },+ });+ return infos;+}