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
Fix dropped error hints and improve error output UI (#9673)
Akshay Agrawal44638a544b65
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsxindex 1d9c1f32e6..3b4e32b045 100644--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx@@ -1,12 +1,16 @@/* Copyright 2026 Marimo. All rights reserved. */+import { useAtomValue } from "jotai";import {+ ChevronDown,+ ChevronRight,+ InfoIcon,NotebookPenIcon,PackageIcon,SquareArrowOutUpRightIcon,TerminalIcon,} from "lucide-react";-import { Fragment, type JSX } from "react";+import { Fragment, type JSX, useState } from "react";import {Accordion,AccordionContent,@@ -16,7 +20,9 @@ import {import { Button } from "@/components/ui/button";import { Kbd } from "@/components/ui/kbd";import { ExternalLink } from "@/components/ui/links";+import { Tooltip } from "@/components/ui/tooltip";import type { CellId } from "@/core/cells/ids";+import { resolvedMarimoConfigAtom } from "@/core/config/config";import { renderHTML } from "@/plugins/core/RenderHTML";import { splitMangledLocals } from "@/utils/local-variables";import type { MarimoError } from "../../../core/kernel/messages";@@ -29,6 +35,39 @@ import { MangledSegments } from "../errors/mangled-local-chip";import { CellLinkError } from "../links/cell-link";import { processTextForUrls } from "./console/text-rendering";+const CollapsibleTraceback = ({+ traceback,+}: {+ traceback: string;+}): JSX.Element => {+ const [isOpen, setIsOpen] = useState(true);+ return (+ <div className="mt-2">+ <button+ type="button"+ onClick={() => setIsOpen(!isOpen)}+ aria-expanded={isOpen}+ aria-label={isOpen ? "Collapse traceback" : "Expand traceback"}+ className="flex items-center gap-1 text-muted-foreground/70 hover:text-muted-foreground transition-colors"+ >+ {isOpen ? (+ <ChevronDown className="h-3 w-3" />+ ) : (+ <ChevronRight className="h-3 w-3" />+ )}+ <span className="text-[0.6875rem] uppercase tracking-wider">+ Traceback+ </span>+ </button>+ {isOpen && (+ <div className="font-code text-sm mt-1 p-3 bg-muted rounded border overflow-auto max-h-[50vh] cursor-text select-text">+ {renderHTML({ html: traceback })}+ </div>+ )}+ </div>+ );+};+const Tip = (props: {title?: string;className?: string;@@ -37,10 +76,13 @@ const Tip = (props: {return (<Accordion type="single" collapsible={true} className={props.className}><AccordionItem value="item-1" className="text-muted-foreground">- <AccordionTrigger className="pt-2 pb-2 font-normal">+ <AccordionTrigger className="pt-2 pb-0 font-normal">{props.title ?? "Tip"}</AccordionTrigger>- <AccordionContent className="mr-24 text-[0.84375rem]">+ <AccordionContent+ className="mr-24 text-[0.84375rem]"+ wrapperClassName="pt-0 pb-2"+ >{props.children}</AccordionContent></AccordionItem>@@ -63,10 +105,21 @@ export const MarimoErrorOutput = ({className,}: Props): JSX.Element => {const chromeActions = useChromeActions();-- let titleContents = "This cell wasn't run because it has errors";+ // The console area (where tracebacks are shown) sits below the cell editor.+ // When cell outputs are also displayed below the editor, the traceback is+ // already adjacent, so the "See the console area" hint is redundant. It is+ // only helpful when outputs are displayed above the editor.+ const showConsoleHint =+ useAtomValue(resolvedMarimoConfigAtom).display.cell_output === "above";++ let titleContents: string | null =+ "This cell wasn't run because it has errors";let alertVariant: "destructive" | "default" = "destructive";let titleColor = "text-error";+ // A small muted overline shown above the title for static errors, where+ // the cell genuinely never executes. These errors have no separate title:+ // the body text already describes them, so the overline carries the status.+ let statusOverline: string | null = null;const liStyle = "my-0.5 ml-8 text-muted-foreground/40";// Check for certain error types to adjust title and appearance@@ -77,7 +130,6 @@ export const MarimoErrorOutput = ({} else if (errors.some((e) => e.type === "ancestor-prevented")) {titleContents = "Ancestor prevented from running";alertVariant = "default";- titleColor = "text-muted-foreground";titleColor = "text-secondary-foreground";} else if (errors.some((e) => e.type === "ancestor-stopped")) {titleContents = "Ancestor stopped";@@ -85,6 +137,19 @@ export const MarimoErrorOutput = ({titleColor = "text-secondary-foreground";} else if (errors.some((e) => e.type === "sql-error")) {titleContents = "SQL error";+ } else if (+ errors.some(+ (e) =>+ e.type === "multiple-defs" ||+ e.type === "cycle" ||+ e.type === "setup-refs" ||+ e.type === "import-star",+ )+ ) {+ // Static errors: the body text describes the problem, so there is no+ // separate title — only the status overline.+ titleContents = null;+ statusOverline = "Cell not run";} else {// Check for exception typeconst exceptionError = errors.find((e) => e.type === "exception");@@ -475,9 +540,11 @@ export const MarimoErrorOutput = ({</ExternalLink>).</p>- <div className="text-muted-foreground mt-2">- See the console area for a traceback.- </div>+ {showConsoleHint && (+ <div className="text-muted-foreground mt-2">+ See the console area for a traceback.+ </div>+ )}</div></li>);@@ -492,13 +559,13 @@ export const MarimoErrorOutput = ({{processTextForUrls(error.msg, `exception-${idx}`)}</p>{"traceback" in error && error.traceback ? (- <div className="font-code text-sm mt-2 p-3 bg-muted rounded border overflow-auto max-h-[50vh] cursor-text select-text">- {renderHTML({ html: error.traceback })}- </div>+ <CollapsibleTraceback traceback={error.traceback} />) : (- <div className="text-muted-foreground mt-2">- See the console area for a traceback.- </div>+ showConsoleHint && (+ <div className="text-muted-foreground mt-2">+ See the console area for a traceback.+ </div>+ ))}</div>) : (@@ -506,9 +573,7 @@ export const MarimoErrorOutput = ({{processTextForUrls(error.msg, `exception-${idx}`)}<CellLinkError cellId={error.raising_cell} />{"traceback" in error && error.traceback && (- <div className="font-code text-sm mt-2 p-3 bg-muted rounded border overflow-auto max-h-[50vh] cursor-text select-text">- {renderHTML({ html: error.traceback })}- </div>+ <CollapsibleTraceback traceback={error.traceback} />)}</div>)}@@ -633,23 +698,36 @@ export const MarimoErrorOutput = ({};const title = (- <AlertTitle className={`font-code font-medium tracking-wide ${titleColor}`}>- {titleContents}- </AlertTitle>+ <div className="space-y-0.5">+ {statusOverline && (+ <div className="flex items-center gap-1 font-code text-[0.6875rem] uppercase tracking-wider text-muted-foreground/70">+ {statusOverline}+ <Tooltip+ content="marimo didn't run this cell because it detected an error."+ delayDuration={200}+ >+ <InfoIcon className="size-3 cursor-help" />+ </Tooltip>+ </div>+ )}+ {titleContents && (+ <AlertTitle className={`font-code font-medium ${titleColor}`}>+ {titleContents}+ </AlertTitle>+ )}+ </div>);return (<Alertvariant={alertVariant}className={cn(- "border-none font-code text-sm text-[0.84375rem] px-0 text-muted-foreground normal [&:has(svg)]:pl-0 space-y-4",+ "border-none font-code text-sm text-[0.84375rem] p-0 text-muted-foreground normal [&:has(svg)]:pl-0 space-y-2",className,)}>{title}- <div>- <div className="flex flex-col gap-8">{renderMessages()}</div>- </div>+ <div className="flex flex-col gap-4">{renderMessages()}</div></Alert>);};diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsxindex 1f447c73ba..fb264ea56d 100644--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx@@ -5,17 +5,13 @@ import { useAtomValue } from "jotai";import {BugPlayIcon,ChevronDown,+ ChevronRight,CopyIcon,ExternalLinkIcon,MessageCircleIcon,SearchIcon,} from "lucide-react";import { type JSX, useState } from "react";-import {- Accordion,- AccordionContent,- AccordionItem,-} from "@/components/ui/accordion";import { Button } from "@/components/ui/button";import {DropdownMenu,@@ -45,7 +41,6 @@ import {extractAllTracebackInfo,getTracebackInfo,} from "@/utils/traceback";-import { cn } from "../../../utils/cn";import { AIFixButton } from "../errors/auto-fix";import { MangledSegments } from "../errors/mangled-local-chip";import { CellLinkTraceback } from "../links/cell-link";@@ -57,8 +52,6 @@ interface Props {onRefactorWithAI?: OnRefactorWithAI;}-const KEY = "item";-/*** List of errors due to violations of Marimo semantics.*/@@ -75,7 +68,6 @@ export const MarimoTracebackOutput = ({replaceMangledLocal,],});- const [expanded, setExpanded] = useState(true);const lastTracebackLine = lastLine(traceback);const aiEnabled = useAtomValue(aiEnabledAtom);@@ -95,6 +87,8 @@ export const MarimoTracebackOutput = ({const showSearch = !isStaticNotebook();+ const [isOpen, setIsOpen] = useState(true);+const handleRefactorWithAI = (triggerImmediately: boolean) => {onRefactorWithAI?.({prompt: `My code gives the following error:\n\n${lastTracebackLine}`,@@ -102,35 +96,29 @@ export const MarimoTracebackOutput = ({});};- const [error, errorMessage] = lastTracebackLine.split(":", 2);- const errorMessageSegments = errorMessage- ? splitMangledLocals(errorMessage)- : [];-return (<div className="flex flex-col gap-2 min-w-full w-fit">- <Accordion type="single" collapsible={true} value={expanded ? KEY : ""}>- <AccordionItem value={KEY} className="border-none">- <div- className="flex gap-2 h-10 px-2 hover:bg-muted rounded-sm select-none items-center cursor-pointer transition-all"- onClick={() => setExpanded((prev) => !prev)}- >- <ChevronDown- className={cn(- "h-4 w-4 text-muted-foreground transition-transform duration-200 shrink-0",- expanded ? "rotate-180" : "rotate-0",- )}- />- <div className="text-sm inline font-mono">- <span className="text-destructive">{error || "Error"}:</span>{" "}- <MangledSegments segments={errorMessageSegments} />- </div>- </div>- <AccordionContent className="text-muted-foreground px-4 pt-2 text-xs overflow-auto">- {htmlTraceback}- </AccordionContent>- </AccordionItem>- </Accordion>+ <button+ type="button"+ onClick={() => setIsOpen(!isOpen)}+ aria-expanded={isOpen}+ aria-label={isOpen ? "Collapse traceback" : "Expand traceback"}+ className="self-start flex items-center gap-1 pt-2 text-muted-foreground/70 hover:text-muted-foreground transition-colors"+ >+ {isOpen ? (+ <ChevronDown className="h-3 w-3" />+ ) : (+ <ChevronRight className="h-3 w-3" />+ )}+ <span className="text-[0.6875rem] uppercase tracking-wider">+ Traceback+ </span>+ </button>+ {isOpen && (+ <div className="text-muted-foreground pr-4 text-xs overflow-auto">+ {htmlTraceback}+ </div>+ )}<div className="flex gap-2">{showAIFix && (<AIFixButtondiff --git a/frontend/src/core/codemirror/cells/traceback-decorations.ts b/frontend/src/core/codemirror/cells/traceback-decorations.tsindex f390158320..9599af6237 100644--- a/frontend/src/core/codemirror/cells/traceback-decorations.ts+++ b/frontend/src/core/codemirror/cells/traceback-decorations.ts@@ -147,7 +147,7 @@ export function errorLineHighlighter(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)",+ backgroundColor: "color-mix(in srgb, var(--red-5) 40%, transparent)",},}),];diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.cssindex cce5e903fa..4fc253380d 100644--- a/frontend/src/css/app/Cell.css+++ b/frontend/src/css/app/Cell.css@@ -214,7 +214,6 @@&.error-outline,&.error-outline:focus-within {box-shadow: 8px 8px 0 0 color-mix(in srgb, var(--error), transparent 80%);- background-color: var(--red-2);}/* Needs Run */diff --git a/marimo/_messaging/tracebacks.py b/marimo/_messaging/tracebacks.pyindex cb15340775..557d71451f 100644--- a/marimo/_messaging/tracebacks.py+++ b/marimo/_messaging/tracebacks.py@@ -2,6 +2,7 @@from __future__ import annotationsimport sys+import traceback as tbfrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.context import is_code_mode_request@@ -105,5 +106,36 @@ def _trim_traceback(traceback: str) -> str:return traceback+def format_exception_message(exc: BaseException) -> str:+ """Return an exception's message, including Python's helpful hints.++ `str(exc)` yields only the bare message (`exc.args[0]`). Python's+ "Did you mean: ..." suggestions for `NameError`, `AttributeError`,+ `ImportError`, etc. are computed by the `traceback` module from the+ exception's frame, so they are dropped by `str()`. Format via+ `TracebackException` to keep them, while stripping the leading+ "ExceptionType: " prefix (marimo displays the exception type separately).++ Falls back to `str(exc)` when the formatted output isn't a single+ "ExceptionType: message" line (e.g. `SyntaxError`, whose formatting+ spans multiple lines, or an exception with no message).+ """+ base = str(exc)+ try:+ formatted = "".join(+ tb.TracebackException.from_exception(exc).format_exception_only()+ ).strip()+ except Exception:+ return base+ # `format_exception_only` emits a single "{ExceptionType}: {message}"+ # line, with any "Did you mean: ..." hint appended to the message.+ # Partition on the first ": " to drop the type prefix; an exception+ # type name never contains ": ", so a colon in the message is kept.+ type_str, sep, rest = formatted.partition(": ")+ if sep and "\n" not in type_str:+ return rest+ return base++def is_code_highlighting(value: str) -> bool:return 'class="codehilite"' in valuediff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex 52e08ccb5a..8b82bf0ede 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -36,6 +36,7 @@ from marimo._messaging.notification_utils import (from marimo._messaging.tracebacks import (_highlight_traceback,_trim_traceback,+ format_exception_message,write_traceback,)from marimo._messaging.variables import create_variable_value@@ -409,7 +410,10 @@ def _broadcast_outputs(# don't clear console because this cell was running and# its console outputs are not staleexception_type = type(run_result.exception).__name__- msg = str(run_result.exception)+ if isinstance(run_result.exception, BaseException):+ msg = format_exception_message(run_result.exception)+ else:+ msg = str(run_result.exception)if not msg:msg = f"This cell raised an exception: {exception_type}"diff --git a/tests/_messaging/test_tracebacks.py b/tests/_messaging/test_tracebacks.pyindex ddd4fe4350..1346eba195 100644--- a/tests/_messaging/test_tracebacks.py+++ b/tests/_messaging/test_tracebacks.py@@ -1,12 +1,16 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import sysfrom unittest.mock import MagicMock, patch+import pytest+from marimo._messaging.context import HTTP_REQUEST_CTX, is_code_mode_requestfrom marimo._messaging.tracebacks import (_highlight_traceback,_trim_traceback,+ format_exception_message,is_code_highlighting,write_traceback,)@@ -167,6 +171,40 @@ class TestTracebacks:assert kwargs["mimetype"] == "application/vnd.marimo+traceback"+class TestFormatExceptionMessage:+ def test_name_error_includes_suggestion(self) -> None:+ """Python's "Did you mean: ..." suggestion is kept (str() drops it)."""+ aaa = 1+ with pytest.raises(NameError) as excinfo:+ print(aa) # type: ignore[name-defined] # noqa: F821+ msg = format_exception_message(excinfo.value)+ # The base message is stable across all supported Python versions.+ assert msg.startswith("name 'aa' is not defined")+ # Python 3.13 was the first release where `TracebackException` exposes+ # the "Did you mean: ..." hint via `format_exception_only`; on 3.10-+ # 3.12 the interpreter prints the hint in C but doesn't surface it+ # there, so the helper degrades to the base message on those versions.+ if sys.version_info >= (3, 13):+ assert "Did you mean: 'aaa'?" in msg++ def test_plain_message_unchanged(self) -> None:+ """Without a suggestion, the bare message is returned without the+ leading "ExceptionType: " prefix."""+ with pytest.raises(ValueError) as excinfo:+ raise ValueError("some message")+ assert format_exception_message(excinfo.value) == "some message"++ def test_empty_message(self) -> None:+ with pytest.raises(RuntimeError) as excinfo:+ raise RuntimeError+ assert format_exception_message(excinfo.value) == ""++ def test_message_containing_colon(self) -> None:+ with pytest.raises(ValueError) as excinfo:+ raise ValueError("expected: a value")+ assert format_exception_message(excinfo.value) == "expected: a value"++class TestIsCodeModeRequest:def test_no_request_context(self) -> None:assert is_code_mode_request() is Falsediff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex d6cbbc711e..0e9793a2dd 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -3635,6 +3635,35 @@ class TestErrorHandling:assert errors[0].traceback is not Noneassert "ValueError" in errors[0].traceback+ async def test_name_error_includes_suggestion(+ self, mocked_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ """A NameError's "Did you mean: ..." suggestion should not be+ dropped from the error message (regression test)."""+ k = mocked_kernel.k+ await k.run(+ [+ exec_req.get("aaa = 1"),+ exec_req.get("print(aa)"),+ ]+ )+ cell_notifications = mocked_kernel.stream.cell_notifications+ error_cell_notification = _filter_to_error_ops(cell_notifications)+ assert len(error_cell_notification) == 1+ errors = _parse_error_output(error_cell_notification[0])++ assert len(errors) == 1+ assert isinstance(errors[0], MarimoExceptionRaisedError)+ assert errors[0].exception_type == "NameError"+ # The base message is stable across all supported Python versions.+ assert errors[0].msg.startswith("name 'aa' is not defined")+ # Python 3.13 was the first release where `TracebackException`+ # exposes the "Did you mean: ..." hint via `format_exception_only`,+ # which is what the runtime uses to build the message. On 3.10-3.12+ # the helper degrades to the base message; see test_tracebacks.py.+ if sys.version_info >= (3, 13):+ assert "Did you mean: 'aaa'?" in errors[0].msg+async def test_error_handling_in_run_mode_stop(self, run_mode_kernel: MockedKernel, exec_req: ExecReqProvider) -> None: