Skip to content

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.

feat: better traceback, help with google or AI (#1833)

Myles Scolnick91d7b78758eb
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 60fcb85bf0..e02bb28cfb 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -369,11 +369,12 @@ const CellComponent = (
"cell.aiCompletion": () => {
let closed = false;
setAiCompletionCell((v) => {
- if (v === cellId) {
+ // Toggle close
+ if (v?.cellId === cellId) {
closed = true;
return null;
}
- return cellId;
+ return { cellId };
});
if (closed) {
derefNotNull(editorView).focus();
@@ -431,6 +432,10 @@ const CellComponent = (
}
};
+ const handleRefactorWithAI = (opts: { prompt: string }) => {
+ setAiCompletionCell({ cellId, initialPrompt: opts.prompt });
+ };
+
return (
<CellActionsContextMenu
cellId={cellId}
@@ -539,6 +544,7 @@ const CellComponent = (
consoleOutputs={consoleOutputs}
stale={consoleOutputStale}
cellName={name}
+ onRefactorWithAI={handleRefactorWithAI}
onSubmitDebugger={(text, index) => {
setStdinResponse({ cellId, response: text, outputIndex: index });
sendStdin({ text });
diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsx
index c190a15cb0..b4aa3dc2ab 100644
--- a/frontend/src/components/editor/Output.tsx
+++ b/frontend/src/components/editor/Output.tsx
@@ -22,14 +22,16 @@ import { useExpandedOutput } from "@/core/cells/outputs";
import { invariant } from "@/utils/invariant";
import { CsvViewer } from "./file-tree/renderers";
import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";
+import { MarimoTracebackOutput } from "./output/MarimoTracebackOutput";
/**
* Renders an output based on an OutputMessage.
*/
export const OutputRenderer: React.FC<{
message: OutputMessage;
+ onRefactorWithAI?: (opts: { prompt: string }) => void;
}> = memo((props) => {
- const { message } = props;
+ const { message, onRefactorWithAI } = props;
// Memoize parsing the json data
const parsedJsonData = useMemo(() => {
@@ -95,6 +97,18 @@ export const OutputRenderer: React.FC<{
invariant(Array.isArray(data), "Expected array data");
return <MarimoErrorOutput errors={data} />;
+ case "application/vnd.marimo+traceback":
+ invariant(
+ typeof data === "string",
+ `Expected string data for mime=${mimetype}. Got ${typeof data}`,
+ );
+ return (
+ <MarimoTracebackOutput
+ onRefactorWithAI={onRefactorWithAI}
+ traceback={data}
+ />
+ );
+
case "text/csv":
invariant(
typeof data === "string",
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsx
index f984e118a2..b12703e57f 100644
--- a/frontend/src/components/editor/actions/useCellActionButton.tsx
+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx
@@ -179,7 +179,7 @@ export function useCellActionButtons({ cell }: Props) {
hidden: !aiEnabled,
handle: () => {
setAiCompletionCell((current) =>
- current === cellId ? null : cellId,
+ current?.cellId === cellId ? null : { cellId },
);
},
hotkey: "cell.aiCompletion",
diff --git a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
index 6b4f5f807d..27e7a62756 100644
--- a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
+++ b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
@@ -28,6 +28,7 @@ const Modified = CodeMirrorMerge.Modified;
interface Props {
currentCode: string;
currentLanguageAdapter: LanguageAdapterType | undefined;
+ initialPrompt: string | undefined;
onChange: (code: string) => void;
declineChange: () => void;
acceptChange: (rightHandCode: string) => void;
@@ -42,6 +43,7 @@ const baseExtensions = [customPythonLanguageSupport(), EditorView.lineWrapping];
export const AiCompletionEditor: React.FC<Props> = ({
onChange,
+ initialPrompt,
currentLanguageAdapter,
currentCode,
declineChange,
@@ -59,11 +61,13 @@ export const AiCompletionEditor: React.FC<Props> = ({
stop,
isLoading,
setCompletion,
+ setInput,
handleInputChange,
handleSubmit,
} = useCompletion({
api: asURL("api/ai/completion").toString(),
headers: API.headers(),
+ initialInput: initialPrompt,
streamMode: "text",
body: {
includeOtherCode: includeOtherCells ? getCodes(currentCode) : "",
@@ -80,6 +84,7 @@ export const AiCompletionEditor: React.FC<Props> = ({
const inputRef = React.useRef<HTMLInputElement>(null);
+ // Focus the input
useEffect(() => {
if (enabled && inputRef.current) {
inputRef.current.focus();
@@ -87,6 +92,13 @@ export const AiCompletionEditor: React.FC<Props> = ({
}
}, [enabled]);
+ // Reset the input when the prompt changes
+ useEffect(() => {
+ if (enabled) {
+ setInput(initialPrompt || "");
+ }
+ }, [enabled, initialPrompt, setInput]);
+
const { theme } = useTheme();
return (
@@ -98,87 +110,95 @@ export const AiCompletionEditor: React.FC<Props> = ({
!enabled && "h-0 invisible",
)}
>
- <SparklesIcon
- className="text-[var(--blue-10)] flex-shrink-0"
- size={16}
- />
- <input
- className="h-8 outline-none px-2 focus-visible:shadow-none flex-1 rounded-none border-none focus:border-none"
- value={input}
- ref={inputRef}
- onChange={handleInputChange}
- placeholder="Type for completion"
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- handleSubmit(e as unknown as React.FormEvent<HTMLFormElement>);
- }
- if (e.key === "Escape") {
- e.preventDefault();
- declineChange();
- setCompletion("");
- }
- }}
- />
- {isLoading && (
- <Button
- data-testid="stop-completion-button"
- variant="text"
- size="xs"
- className="mb-0"
- onClick={stop}
- >
- <Loader2Icon className="animate-spin mr-1" size={14} />
- Stop
- </Button>
- )}
- {!isLoading && completion && (
- <Button
- data-testid="accept-completion-button"
- variant="text"
- size="xs"
- className="mb-0"
- disabled={isLoading}
- onClick={() => {
- acceptChange(completion);
- setCompletion("");
- }}
- >
- <span className="text-[var(--grass-11)] opacity-100">Accept</span>
- </Button>
- )}
- <div className="h-full w-px bg-border mx-2" />
- <Tooltip content="Include code from other cells">
- <div className="flex flex-row items-start gap-1 overflow-hidden">
- <Checkbox
- data-testid="include-other-cells-checkbox"
- id="include-other-cells"
- checked={includeOtherCells}
- onCheckedChange={(checked) =>
- setIncludeOtherCells(Boolean(checked))
- }
+ {enabled && (
+ <>
+ <SparklesIcon
+ className="text-[var(--blue-10)] flex-shrink-0"
+ size={16}
+ />
+ <input
+ className="h-8 outline-none px-2 focus-visible:shadow-none flex-1 rounded-none border-none focus:border-none"
+ value={input}
+ ref={inputRef}
+ onChange={handleInputChange}
+ placeholder="Type for completion"
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleSubmit(
+ e as unknown as React.FormEvent<HTMLFormElement>,
+ );
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ declineChange();
+ setCompletion("");
+ }
+ }}
/>
- <Label
- htmlFor="include-other-cells"
- className="text-muted-foreground text-xs whitespace-nowrap ellipsis"
+ {isLoading && (
+ <Button
+ data-testid="stop-completion-button"
+ variant="text"
+ size="xs"
+ className="mb-0"
+ onClick={stop}
+ >
+ <Loader2Icon className="animate-spin mr-1" size={14} />
+ Stop
+ </Button>
+ )}
+ {!isLoading && completion && (
+ <Button
+ data-testid="accept-completion-button"
+ variant="text"
+ size="xs"
+ className="mb-0"
+ disabled={isLoading}
+ onClick={() => {
+ acceptChange(completion);
+ setCompletion("");
+ }}
+ >
+ <span className="text-[var(--grass-11)] opacity-100">
+ Accept
+ </span>
+ </Button>
+ )}
+ <div className="h-full w-px bg-border mx-2" />
+ <Tooltip content="Include code from other cells">
+ <div className="flex flex-row items-start gap-1 overflow-hidden">
+ <Checkbox
+ data-testid="include-other-cells-checkbox"
+ id="include-other-cells"
+ checked={includeOtherCells}
+ onCheckedChange={(checked) =>
+ setIncludeOtherCells(Boolean(checked))
+ }
+ />
+ <Label
+ htmlFor="include-other-cells"
+ className="text-muted-foreground text-xs whitespace-nowrap ellipsis"
+ >
+ Include all code
+ </Label>
+ </div>
+ </Tooltip>
+ <Button
+ data-testid="decline-completion-button"
+ variant="text"
+ size="icon"
+ disabled={isLoading}
+ onClick={() => {
+ stop();
+ declineChange();
+ setCompletion("");
+ }}
>
- Include all code
- </Label>
- </div>
- </Tooltip>
- <Button
- data-testid="decline-completion-button"
- variant="text"
- size="icon"
- disabled={isLoading}
- onClick={() => {
- stop();
- declineChange();
- setCompletion("");
- }}
- >
- <XIcon className="text-[var(--red-10)]" size={16} />
- </Button>
+ <XIcon className="text-[var(--red-10)]" size={16} />
+ </Button>
+ </>
+ )}
</div>
{completion && enabled && (
<CodeMirrorMerge className="cm" theme={theme}>
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 20b9a9b9d9..02974e1f08 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -167,11 +167,12 @@ const CellEditorInternal = ({
aiCellCompletion: () => {
let closed = false;
setAiCompletionCell((v) => {
- if (v === cellId) {
+ // Toggle close
+ if (v?.cellId === cellId) {
closed = true;
return null;
}
- return cellId;
+ return { cellId };
});
return closed;
},
@@ -331,7 +332,8 @@ const CellEditorInternal = ({
return (
<AiCompletionEditor
- enabled={aiCompletionCell === cellId}
+ enabled={aiCompletionCell?.cellId === cellId}
+ initialPrompt={aiCompletionCell?.initialPrompt}
currentCode={editorViewRef.current?.state.doc.toString() ?? code}
currentLanguageAdapter={languageAdapter}
declineChange={() => {
diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/ConsoleOutput.tsx
index aa008ef916..629e710eb0 100644
--- a/frontend/src/components/editor/output/ConsoleOutput.tsx
+++ b/frontend/src/components/editor/output/ConsoleOutput.tsx
@@ -20,6 +20,7 @@ interface Props {
consoleOutputs: Array<WithResponse<OutputMessage>>;
stale: boolean;
debuggerActive: boolean;
+ onRefactorWithAI?: (opts: { prompt: string }) => void;
onSubmitDebugger: (text: string, index: number) => void;
}
@@ -31,6 +32,7 @@ export const ConsoleOutput = (props: Props): React.ReactNode => {
cellName,
cellId,
onSubmitDebugger,
+ onRefactorWithAI,
className,
} = props;
@@ -135,7 +137,10 @@ export const ConsoleOutput = (props: Props): React.ReactNode => {
return (
<React.Fragment key={idx}>
- <OutputRenderer message={output} />
+ <OutputRenderer
+ onRefactorWithAI={onRefactorWithAI}
+ message={output}
+ />
</React.Fragment>
);
})}
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
index 53841db7ff..3c40b00d92 100644
--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
@@ -22,16 +22,9 @@ const Tip = (props: {
}): JSX.Element => {
return (
<Accordion type="single" collapsible={true} className={props.className}>
- <AccordionItem
- value="item-1"
- className="text-muted-foreground border-muted-foreground-20"
- >
- <AccordionTrigger className="py-2 text-[0.84375rem]">
- Tip:
- </AccordionTrigger>
- <AccordionContent className="text-[0.84375rem]">
- {props.children}
- </AccordionContent>
+ <AccordionItem value="item-1" className="text-muted-foreground">
+ <AccordionTrigger className="py-2">Tip:</AccordionTrigger>
+ <AccordionContent>{props.children}</AccordionContent>
</AccordionItem>
</Accordion>
);
@@ -128,7 +121,9 @@ export const MarimoErrorOutput = ({
return error.raising_cell == null ? (
<Fragment key={idx}>
<p>{error.msg}</p>
- <Tip>See the console area for a traceback.</Tip>
+ <div className="text-sm text-muted-foreground mt-2">
+ See the console area for a traceback.
+ </div>
</Fragment>
) : (
<div key={idx}>
@@ -197,7 +192,7 @@ export const MarimoErrorOutput = ({
});
const title = (
- <AlertTitle className="font-code font-bold mb-4">
+ <AlertTitle className="font-code font-bold mb-4 tracking-wide">
{titleContents}
</AlertTitle>
);
diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
new file mode 100644
index 0000000000..312843d8be
--- /dev/null
+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
@@ -0,0 +1,96 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { cn } from "../../../utils/cn";
+
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+} from "@/components/ui/accordion";
+import { Button, buttonVariants } from "@/components/ui/button";
+import { renderHTML } from "@/plugins/core/RenderHTML";
+
+import "./traceback-output.css";
+import { BugIcon, ChevronDown, ExternalLinkIcon } from "lucide-react";
+import { useState } from "react";
+import { useAtomValue } from "jotai";
+import { aiEnabledAtom } from "@/core/config/config";
+
+interface Props {
+ traceback: string;
+ onRefactorWithAI?: (opts: { prompt: string }) => void;
+}
+
+const KEY = "item";
+
+/**
+ * List of errors due to violations of Marimo semantics.
+ */
+export const MarimoTracebackOutput = ({
+ onRefactorWithAI,
+ traceback,
+}: Props): JSX.Element => {
+ const htmlTraceback = renderHTML({ html: traceback });
+ const [expanded, setExpanded] = useState(true);
+
+ const lastTracebackLine = lastLine(traceback);
+ const aiEnabled = useAtomValue(aiEnabledAtom);
+
+ const handleRefactorWithAI = () => {
+ onRefactorWithAI?.({
+ prompt: `My code gives the following error: ${lastTracebackLine}`,
+ });
+ };
+
+ return (
+ <div className="flex flex-col gap-2">
+ <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 flex-shrink-0",
+ expanded ? "rotate-180" : "rotate-0",
+ )}
+ />
+ <div className="pb-5">
+ <div className="traceback-header text-destructive line-clamp-1 text-sm inline">
+ {htmlTraceback}
+ </div>
+ </div>
+ </div>
+ <AccordionContent className="px-4 text-muted-foreground px-4 pt-2 text-xs">
+ {htmlTraceback}
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ <div className="flex gap-2">
+ {onRefactorWithAI && aiEnabled && (
+ <Button size="xs" variant="outline" onClick={handleRefactorWithAI}>
+ <BugIcon className="h-3 w-3 mr-2" />
+ Fix with AI
+ </Button>
+ )}
+ <a
+ className={buttonVariants({ size: "xs", variant: "text" })}
+ target="_blank"
+ href={`https://www.google.com/search?q=${encodeURIComponent(lastTracebackLine)}`}
+ rel="noreferrer"
+ >
+ Search on Google
+ <ExternalLinkIcon className="h-3 w-3 ml-1" />
+ </a>
+ </div>
+ </div>
+ );
+};
+
+function lastLine(text: string): string {
+ const el = document.createElement("div");
+ el.innerHTML = text;
+ const lines = el.textContent?.split("\n").filter(Boolean);
+ return lines?.at(-1) || "";
+}
diff --git a/frontend/src/components/editor/output/traceback-output.css b/frontend/src/components/editor/output/traceback-output.css
new file mode 100644
index 0000000000..2e63142899
--- /dev/null
+++ b/frontend/src/components/editor/output/traceback-output.css
@@ -0,0 +1,14 @@
+.traceback-header {
+ display: inline-grid;
+ height: 1lh; /* height of one line */
+ overflow: hidden;
+ place-content: end;
+}
+
+/* fallback if lh is not supported */
+@supports not (height:1lh) {
+ .traceback-header {
+ line-height: 1.5em;
+ height: 1.5em;
+ }
+}
diff --git a/frontend/src/components/ui/accordion.tsx b/frontend/src/components/ui/accordion.tsx
index 1c01729461..8851d0df62 100644
--- a/frontend/src/components/ui/accordion.tsx
+++ b/frontend/src/components/ui/accordion.tsx
@@ -56,4 +56,12 @@ const AccordionContent = React.forwardRef<
));
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
-export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
+const AccordionPrimitiveTrigger = AccordionPrimitive.Trigger;
+
+export {
+ Accordion,
+ AccordionItem,
+ AccordionTrigger,
+ AccordionContent,
+ AccordionPrimitiveTrigger,
+};
diff --git a/frontend/src/core/ai/state.ts b/frontend/src/core/ai/state.ts
index 485d34726b..535e7d77bf 100644
--- a/frontend/src/core/ai/state.ts
+++ b/frontend/src/core/ai/state.ts
@@ -2,5 +2,8 @@
import { atom } from "jotai";
import { CellId } from "../cells/ids";
-export const aiCompletionCellAtom = atom<CellId | null>(null);
+export const aiCompletionCellAtom = atom<{
+ cellId: CellId;
+ initialPrompt?: string;
+} | null>(null);
export const includeOtherCellsAtom = atom<boolean>(false);
diff --git a/marimo/_messaging/mimetypes.py b/marimo/_messaging/mimetypes.py
index 7fbc111906..2fd6d14696 100644
--- a/marimo/_messaging/mimetypes.py
+++ b/marimo/_messaging/mimetypes.py
@@ -9,6 +9,7 @@ from typing import Literal
KnownMimeType = Literal[
"application/json",
"application/vnd.marimo+error",
+ "application/vnd.marimo+traceback",
"image/png",
"image/svg+xml",
"image/tiff",
diff --git a/marimo/_messaging/tracebacks.py b/marimo/_messaging/tracebacks.py
index 76c670ec05..ae8f1224e4 100644
--- a/marimo/_messaging/tracebacks.py
+++ b/marimo/_messaging/tracebacks.py
@@ -24,7 +24,8 @@ def _highlight_traceback(traceback: str) -> str:
def write_traceback(traceback: str) -> None:
if isinstance(sys.stderr, Stderr):
sys.stderr._write_with_mimetype(
- _highlight_traceback(traceback), mimetype="text/html"
+ _highlight_traceback(traceback),
+ mimetype="application/vnd.marimo+traceback",
)
else:
sys.stderr.write(traceback)
diff --git a/marimo/_output/mime.py b/marimo/_output/mime.py
index 6cf1a69402..cd9308103e 100644
--- a/marimo/_output/mime.py
+++ b/marimo/_output/mime.py
@@ -26,6 +26,7 @@ class MIME(Protocol):
The supported mimetypes are:
application/json
application/vnd.marimo+error
+ application/vnd.marimo+traceback
image/png
image/svg+xml
image/tiff
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 318c8c3ba6..d7356f719e 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -462,9 +462,12 @@ components:
items:
type: string
type: array
+ timestamp:
+ type: number
required:
- cellIds
- codes
+ - timestamp
type: object
ExecuteScratchpadRequest:
properties:
@@ -482,9 +485,12 @@ components:
type: string
code:
type: string
+ timestamp:
+ type: number
required:
- cellId
- code
+ - timestamp
type: object
ExportAsHTMLRequest:
properties:
@@ -1224,6 +1230,7 @@ components:
enum:
- application/json
- application/vnd.marimo+error
+ - application/vnd.marimo+traceback
- image/png
- image/svg+xml
- image/tiff
@@ -1751,7 +1758,7 @@ components:
type: object
info:
title: marimo API
- version: 0.7.5
+ version: 0.7.8
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 5112691a4c..51968ee016 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -936,6 +936,7 @@ export interface components {
ExecuteMultipleRequest: {
cellIds: string[];
codes: string[];
+ timestamp: number;
};
ExecuteScratchpadRequest: {
code: string;
@@ -944,6 +945,7 @@ export interface components {
ExecutionRequest: {
cellId: string;
code: string;
+ timestamp: number;
};
ExportAsHTMLRequest: {
assetUrl?: string | null;
@@ -1253,6 +1255,7 @@ export interface components {
MimeType:
| "application/json"
| "application/vnd.marimo+error"
+ | "application/vnd.marimo+traceback"
| "image/png"
| "image/svg+xml"
| "image/tiff"