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.

Add support for notebook logs and additional panel type in editor (#344)

Myles Scolnicka7fa761a1d57
diff --git a/frontend/src/components/editor/chrome/panels/logs-panel.tsx b/frontend/src/components/editor/chrome/panels/logs-panel.tsx
new file mode 100644
index 0000000000..98c2ed8f52
--- /dev/null
+++ b/frontend/src/components/editor/chrome/panels/logs-panel.tsx
@@ -0,0 +1,90 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { useCellActions, useCellLogs } from "@/core/cells/cells";
+import { CellLog, formatLogTimestamp } from "@/core/cells/logs";
+import { cn } from "@/utils/cn";
+import React from "react";
+import { FileTextIcon } from "lucide-react";
+
+interface Props {
+ className?: string;
+ logs: CellLog[];
+}
+
+export const LogsPanel: React.FC = () => {
+ const logs = useCellLogs();
+ const { clearLogs } = useCellActions();
+
+ if (logs.length === 0) {
+ return (
+ <div className="mx-6 my-6 flex flex-row gap-2 items-center rounded-lg">
+ <FileTextIcon className="text-muted-foreground" />
+ <span className="mt-[0.25rem] text-muted-foreground">No logs</span>
+ </div>
+ );
+ }
+
+ return (
+ <>
+ <div className="flex flex-row justify-end px-2 py-1">
+ <button
+ className="text-xs font-semibold text-accent-foreground"
+ onClick={clearLogs}
+ >
+ Clear
+ </button>
+ </div>
+ <div className="overflow-auto flex-1">
+ <LogViewer logs={logs} className="min-w-[300px]" />
+ </div>
+ </>
+ );
+};
+
+export const LogViewer: React.FC<Props> = ({ logs, className }) => {
+ const hover =
+ "opacity-70 group-hover:bg-[var(--gray-3)] group-hover:opacity-100";
+ return (
+ <div className={cn("flex flex-col", className)}>
+ <pre className="grid text-xs font-mono gap-1 whitespace-break-spaces font-semibold align-left">
+ <div
+ className="grid grid-cols-[30px,1fr]"
+ style={{ whiteSpace: "pre-wrap" }}
+ >
+ {logs.map((log, index) => (
+ <div key={index} className="contents group">
+ <span className={cn(hover, "text-right col-span-1 py-1 pr-1")}>
+ {index + 1}
+ </span>
+ <span className={cn(hover, "px-2 flex gap-x-1.5 py-1 flex-wrap")}>
+ {formatLog(log)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </pre>
+ </div>
+ );
+};
+
+function formatLog(log: CellLog) {
+ const timestamp = formatLogTimestamp(log.timestamp);
+
+ const color = levelColor[log.level];
+ const level = log.level.toUpperCase();
+
+ return (
+ <>
+ <span className="flex-shrink-0 text-[var(--gray-10)]">[{timestamp}]</span>
+ <span className={cn("flex-shrink-0", color)}>{level}</span>
+ <span className="flex-shrink-0 text-[var(--gray-10)]">
+ ({log.cellId})
+ </span>
+ {log.message}
+ </>
+ );
+}
+
+const levelColor: Record<CellLog["level"], string> = {
+ stdout: "text-[var(--grass-9)]",
+ stderr: "text-[var(--red-9)]",
+};
diff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.ts
index 89ad911f00..f39dd589e8 100644
--- a/frontend/src/components/editor/chrome/types.ts
+++ b/frontend/src/components/editor/chrome/types.ts
@@ -1,2 +1,7 @@
/* Copyright 2023 Marimo. All rights reserved. */
-export type PanelType = "errors" | "variables" | "outline" | "dependencies";
+export type PanelType =
+ | "errors"
+ | "variables"
+ | "outline"
+ | "dependencies"
+ | "logs";
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index 7f493abbef..0fa91b2d6d 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -17,6 +17,7 @@ import { ErrorsPanel } from "../panels/error-panel";
import { OutlinePanel } from "../panels/outline-panel";
import { DependencyGraphPanel } from "@/components/editor/chrome/panels/dependency-graph-panel";
import { VariablePanel } from "../panels/variable-panel";
+import { LogsPanel } from "../panels/logs-panel";
export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
const { isOpen, selectedPanel, panelLocation } = useChromeState();
@@ -88,6 +89,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
{selectedPanel === "variables" && <VariablePanel />}
{selectedPanel === "dependencies" && <DependencyGraphPanel />}
{selectedPanel === "outline" && <OutlinePanel />}
+ {selectedPanel === "logs" && <LogsPanel />}
</div>
);
diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsx
index 4d16285013..1e25649fc4 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx
@@ -7,6 +7,7 @@ import {
XCircleIcon,
ScrollTextIcon,
NetworkIcon,
+ FileTextIcon,
} from "lucide-react";
import { cn } from "@/utils/cn";
import { useChromeActions, useChromeState } from "../state";
@@ -54,6 +55,13 @@ export const Footer: React.FC = () => {
>
<NetworkIcon className={cn("h-4 w-4")} />
</FooterItem>
+ <FooterItem
+ tooltip="Notebook logs"
+ selected={selectedPanel === "logs"}
+ onClick={() => openApplication("logs")}
+ >
+ <FileTextIcon className={cn("h-4 w-4")} />
+ </FooterItem>
<div className="mx-auto" />
<FooterItem
tooltip="Move panel to the left"
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 4fc956ad3f..4c50b204f3 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -28,6 +28,7 @@ import { Objects } from "@/utils/objects";
import { EditorView } from "@codemirror/view";
import { splitAtom, selectAtom } from "jotai/utils";
import { isStaticNotebook, parseStaticState } from "../static/static-state";
+import { CellLog, getCellLogsForMessage } from "./logs";
/**
* The state of the notebook.
@@ -62,6 +63,10 @@ export interface NotebookState {
* and clear this field.
*/
scrollKey: CellId | null;
+ /**
+ * Logs of all cell messages
+ */
+ cellLogs: CellLog[];
}
/**
@@ -77,6 +82,7 @@ function initialNotebookState(): NotebookState {
cellHandles: {},
history: [],
scrollKey: null,
+ cellLogs: [],
};
}
@@ -87,6 +93,7 @@ function initialNotebookState(): NotebookState {
cellHandles: {},
history: [],
scrollKey: null,
+ cellLogs: [],
};
}
@@ -348,9 +355,13 @@ const { reducer, createActions } = createReducer(initialNotebookState, {
action: { cellId: CellId; message: CellMessage }
) => {
const { cellId, message } = action;
- return updateCellRuntimeState(state, cellId, (cell) => {
+ const nextState = updateCellRuntimeState(state, cellId, (cell) => {
return transitionCell(cell, message);
});
+ return {
+ ...nextState,
+ cellLogs: [...nextState.cellLogs, ...getCellLogsForMessage(message)],
+ };
},
setCells: (state, cells: CellData[]) => {
return {
@@ -464,6 +475,12 @@ const { reducer, createActions } = createReducer(initialNotebookState, {
unfoldAllBulk(targets);
return state;
},
+ clearLogs: (state) => {
+ return {
+ ...state,
+ cellLogs: [],
+ };
+ },
});
// Helper function to update a cell in the array
@@ -562,6 +579,11 @@ export const useCellIds = () => useAtomValue(cellIdsAtom);
*/
export const useCellErrors = () => useAtomValue(cellErrorsAtom);
+/**
+ * React-hook for the cell logs.
+ */
+export const useCellLogs = () => useAtomValue(notebookAtom).cellLogs;
+
/// IMPERATIVE GETTERS
/**
diff --git a/frontend/src/core/cells/logs.ts b/frontend/src/core/cells/logs.ts
new file mode 100644
index 0000000000..880492ac46
--- /dev/null
+++ b/frontend/src/core/cells/logs.ts
@@ -0,0 +1,82 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { CellMessage, OutputMessage } from "../kernel/messages";
+import { CellId } from "./ids";
+import { fromUnixTime } from "date-fns";
+
+export interface CellLog {
+ timestamp: number;
+ level: "stdout" | "stderr";
+ message: string;
+ cellId: CellId;
+}
+
+export function getCellLogsForMessage(cell: CellMessage): CellLog[] {
+ const logs: CellLog[] = [];
+ const outputs: OutputMessage[] = [cell.console].filter(Boolean).flat();
+
+ for (const output of outputs) {
+ if (output.mimetype === "text/plain") {
+ switch (output.channel) {
+ case "console":
+ case "stdout":
+ logs.push({
+ timestamp: output.timestamp,
+ level: "stdout",
+ message: output.data,
+ cellId: cell.cell_id,
+ });
+ break;
+ case "stderr":
+ case "marimo-error":
+ logs.push({
+ timestamp: output.timestamp,
+ level: "stderr",
+ message: output.data,
+ cellId: cell.cell_id,
+ });
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ // Log each to the console
+ logs.forEach(CellLogLogger.log);
+
+ return logs;
+}
+
+const CellLogLogger = {
+ log: (payload: CellLog) => {
+ const color =
+ payload.level === "stdout"
+ ? "gray"
+ : payload.level === "stderr"
+ ? "red"
+ : "orange";
+ const status = payload.level.toUpperCase();
+ console.log(
+ `%c[${status}]`,
+ `color:${color}; padding:2px 0; border-radius:2px; font-weight:bold`,
+ `[${formatLogTimestamp(payload.timestamp)}]`,
+ `(${payload.cellId}) ${payload.message}`
+ );
+ },
+};
+
+// e.g. 9:45:10 AM
+export function formatLogTimestamp(timestamp: number): string {
+ try {
+ // parse from UTC
+ const date = fromUnixTime(timestamp);
+ return date.toLocaleTimeString("en-US", {
+ hour12: true,
+ hour: "numeric",
+ minute: "numeric",
+ second: "numeric",
+ });
+ } catch {
+ return "";
+ }
+}
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index ccecba3de1..61e300b899 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -39,16 +39,15 @@ export type OutputMessage =
| {
channel: OutputChannel;
mimetype:
- | "text/plain"
- | "text/html"
- | "text/plain"
- | "image/png"
- | "image/svg+xml"
- | "image/tiff"
| "image/avif"
| "image/bmp"
| "image/gif"
| "image/jpeg"
+ | "image/png"
+ | "image/svg+xml"
+ | "image/tiff"
+ | "text/html"
+ | "text/plain"
| "video/mp4"
| "video/mpeg";
data: string;
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index a49afebb71..0c6fa727eb 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -3,6 +3,7 @@ import type { Meta, StoryObj } from "@storybook/react";
import { Cell, CellProps } from "../components/editor/Cell";
import { TooltipProvider } from "../components/ui/tooltip";
import { CellId } from "../core/cells/ids";
+import { Logger } from "@/utils/Logger";
const meta: Meta<typeof Cell> = {
title: "Cell",
@@ -25,9 +26,9 @@ const props: CellProps = {
interrupted: false,
errored: false,
stopped: false,
- updateCellCode: console.log,
- prepareForRun: console.log,
- registerRunStart: console.log,
+ updateCellCode: Logger.log,
+ prepareForRun: Logger.log,
+ registerRunStart: Logger.log,
runStartTimestamp: 0,
runElapsedTimeMs: 10,
serializedEditorState: null,
@@ -35,11 +36,11 @@ const props: CellProps = {
appClosed: false,
showDeleteButton: true,
allowFocus: false,
- createNewCell: console.log,
- deleteCell: console.log,
- focusCell: console.log,
- moveCell: console.log,
- moveToNextCell: console.log,
+ createNewCell: Logger.log,
+ deleteCell: Logger.log,
+ focusCell: Logger.log,
+ moveCell: Logger.log,
+ moveToNextCell: Logger.log,
config: {},
userConfig: {
completion: {
diff --git a/frontend/src/stories/log-viewer.stories.tsx b/frontend/src/stories/log-viewer.stories.tsx
new file mode 100644
index 0000000000..47f3fdafd0
--- /dev/null
+++ b/frontend/src/stories/log-viewer.stories.tsx
@@ -0,0 +1,74 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import type { Meta, StoryObj } from "@storybook/react";
+import { Dialog } from "../components/ui/dialog";
+import { TooltipProvider } from "../components/ui/tooltip";
+import { LogViewer } from "@/components/editor/chrome/panels/logs-panel";
+import { CellId } from "@/core/cells/ids";
+
+const meta: Meta<typeof LogViewer> = {
+ title: "LogViewer",
+ component: LogViewer,
+ args: {},
+};
+
+export default meta;
+type Story = StoryObj<typeof LogViewer>;
+
+export const Primary: Story = {
+ render: () => (
+ <Dialog>
+ <TooltipProvider>
+ <LogViewer
+ logs={[
+ {
+ timestamp: Date.now(),
+ level: "stdout",
+ cellId: "cell1" as CellId,
+ message: "Hello world!",
+ },
+ {
+ timestamp: Date.now(),
+ level: "stdout",
+ cellId: "cell1" as CellId,
+ message: "Running cell...",
+ },
+ {
+ timestamp: Date.now(),
+ level: "stdout",
+ cellId: "cell1" as CellId,
+ message: "Done!",
+ },
+ {
+ timestamp: Date.now(),
+ level: "stderr",
+ cellId: "cell2" as CellId,
+ message: "Output is too large!",
+ },
+ {
+ timestamp: Date.now(),
+ level: "stderr",
+ cellId: "cell2" as CellId,
+ message: "String length is too short.".repeat(100),
+ },
+ ...Array.from({ length: 100 }).map((_, index) => ({
+ timestamp: Date.now(),
+ level: "stdout" as const,
+ cellId: "cell1" as CellId,
+ message: "Running cell...",
+ })),
+ ]}
+ />
+ </TooltipProvider>
+ </Dialog>
+ ),
+};
+
+export const Empty: Story = {
+ render: () => (
+ <Dialog>
+ <TooltipProvider>
+ <LogViewer logs={[]} />
+ </TooltipProvider>
+ </Dialog>
+ ),
+};
diff --git a/frontend/src/utils/strings.ts b/frontend/src/utils/strings.ts
index 35b5d9ab63..f12bdbc8fe 100644
--- a/frontend/src/utils/strings.ts
+++ b/frontend/src/utils/strings.ts
@@ -1,5 +1,6 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { startCase } from "lodash-es";
+import { Logger } from "./Logger";
export const Strings = {
/**
@@ -11,7 +12,7 @@ export const Strings = {
}
if (typeof str !== "string") {
- console.error(str);
+ Logger.error(str);
throw new TypeError(`Expected string, got ${typeof str}`);
}
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 08a1482f12..9a63d0e3f5 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -6,12 +6,17 @@ import { JSDOM } from "jsdom";
const SERVER_PORT = process.env.SERVER_PORT || 2718;
const isDev = process.env.NODE_ENV === "development";
+const isStorybook = process.env.npm_lifecycle_script?.includes("storybook");
const htmlDevPlugin = (): Plugin => {
return {
apply: "serve",
name: "html-transform",
transformIndexHtml: async (html) => {
+ if (isStorybook) {
+ return html;
+ }
+
// fetch html from server
const serverHtml = await fetch(`http://localhost:${SERVER_PORT}/`).then(
(res) => res.text()