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
improvement: add more types to the openapi schema (#1621)
Myles Scolnick70940c261f7b
diff --git a/frontend/src/components/dependency-graph/panels.tsx b/frontend/src/components/dependency-graph/panels.tsxindex 7560679c43..0aeb3ff95a 100644--- a/frontend/src/components/dependency-graph/panels.tsx+++ b/frontend/src/components/dependency-graph/panels.tsx@@ -148,7 +148,10 @@ export const GraphSelectionPanel: React.FC<{declaredBy={variable.declaredBy}name={variable.name}/>- <div className="truncate col-span-2" title={variable.value}>+ <div+ className="truncate col-span-2"+ title={variable.value ?? ""}+ >{variable.value}<span className="ml-1 truncate text-foreground/60 font-mono">({variable.dataType})@@ -235,7 +238,10 @@ export const GraphSelectionPanel: React.FC<{<div className="truncate text-foreground/60 font-mono">{variable.dataType}</div>- <div className="truncate col-span-2" title={variable.value}>+ <div+ className="truncate col-span-2"+ title={variable.value ?? ""}+ >{variable.value}</div></React.Fragment>diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex c86344fe58..b01489ec2d 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -14,7 +14,7 @@ import {import { saveCellConfig, sendRun, sendStdin } from "@/core/network/requests";import { autocompletionKeymap } from "@/core/codemirror/cm";import { UserConfig } from "../../core/config/config-schema";-import { CellConfig, CellData, CellRuntimeState } from "../../core/cells/types";+import { CellData, CellRuntimeState } from "../../core/cells/types";import { CellActions } from "../../core/cells/cells";import { derefNotNull } from "../../utils/dereference";import { OutputArea } from "./Output";@@ -302,11 +302,13 @@ const CellComponent = ("cell.moveUp": () => moveCell({ cellId, before: true }),"cell.moveDown": () => moveCell({ cellId, before: false }),"cell.hideCode": () => {- const newConfig: CellConfig = { hide_code: !cellConfig.hide_code };+ const nextHideCode = !cellConfig.hide_code;// Fire-and-forget- void saveCellConfig({ configs: { [cellId]: newConfig } });- updateCellConfig({ cellId, config: newConfig });- if (newConfig.hide_code) {+ void saveCellConfig({+ configs: { [cellId]: { hide_code: nextHideCode } },+ });+ updateCellConfig({ cellId, config: { hide_code: nextHideCode } });+ if (nextHideCode) {// Move focus from the editor to the celleditorView.current?.contentDOM.blur();cellRef.current?.focus();diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsxindex efd76223a1..7a20cb78f6 100644--- a/frontend/src/components/editor/Output.tsx+++ b/frontend/src/components/editor/Output.tsx@@ -19,6 +19,9 @@ import { Button } from "../ui/button";import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";import { Tooltip } from "../ui/tooltip";import { useExpandedOutput } from "@/core/cells/outputs";+import { invariant } from "@/utils/invariant";+import { CsvViewer } from "./file-tree/renderers";+import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";/*** Renders an output based on an OutputMessage.@@ -44,9 +47,11 @@ export const OutputRenderer: React.FC<{// TODO(akshayka): audio; pdf; text/csv; excel?; text/css; text/javascriptswitch (message.mimetype) {case "text/html":+ invariant(typeof message.data === "string", "Expected string data");return <HtmlOutput className={channel} html={message.data} />;case "text/plain":+ invariant(typeof message.data === "string", "Expected string data");return <TextOutput channel={channel} text={message.data} />;case "application/json":@@ -62,17 +67,28 @@ export const OutputRenderer: React.FC<{case "image/bmp":case "image/gif":case "image/jpeg":+ invariant(typeof message.data === "string", "Expected string data");return <ImageOutput className={channel} src={message.data} alt="" />;case "video/mp4":case "video/mpeg":+ invariant(typeof message.data === "string", "Expected string data");return <VideoOutput className={channel} src={message.data} />;case "application/vnd.marimo+error":+ invariant(Array.isArray(message.data), "Expected array data");return <MarimoErrorOutput errors={message.data} />;+ case "text/csv":+ invariant(typeof message.data === "string", "Expected string data");+ return <CsvViewer contents={message.data} />;+ case "text/markdown":+ invariant(typeof message.data === "string", "Expected string data");+ return (+ <LazyAnyLanguageCodeMirror value={message.data} language="markdown" />+ );default:- logNever(message);+ logNever(message.mimetype);return null;}});diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex 9575736c25..4d6f4128f0 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -31,7 +31,7 @@ import {} from "lucide-react";import type { ActionButton } from "./types";import { MultiIcon } from "@/components/icons/multi-icon";-import type { CellConfig, CellData, CellStatus } from "@/core/cells/types";+import type { CellData } from "@/core/cells/types";import type { CellId } from "@/core/cells/ids";import { saveCellConfig } from "@/core/network/requests";import type { EditorView } from "@codemirror/view";@@ -50,6 +50,7 @@ import { MarkdownIcon, PythonIcon } from "../cell/code/icons";import { aiEnabledAtom, autoInstantiateAtom } from "@/core/config/config";import { useDeleteCellCallback } from "../cell/useDeleteCell";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";+import { CellConfig, CellStatus } from "@/core/network/types";export interface CellActionButtonPropsextends Pick<CellData, "name" | "config"> {@@ -98,7 +99,7 @@ export function useCellActionButtons({ cell }: Props) {};const toggleHideCode = async () => {- const newConfig: CellConfig = { hide_code: !config.hide_code };+ const newConfig: Partial<CellConfig> = { hide_code: !config.hide_code };await saveCellConfig({ configs: { [cellId]: newConfig } });updateCellConfig({ cellId, config: newConfig });@@ -166,7 +167,7 @@ export function useCellActionButtons({ cell }: Props) {status === "running" ||status === "queued" ||status === "disabled-transitively" ||- config.disabled === true,+ config.disabled,handle: () => runCell(),},{@@ -226,7 +227,7 @@ export function useCellActionButtons({ cell }: Props) {) : (<EyeOffIcon size={13} strokeWidth={1.5} />),- label: config.hide_code === true ? "Show code" : "Hide code",+ label: config.hide_code ? "Show code" : "Hide code",handle: toggleHideCode,hotkey: "cell.hideCode",},@@ -236,7 +237,7 @@ export function useCellActionButtons({ cell }: Props) {) : (<ZapOffIcon size={13} strokeWidth={1.5} />),- label: config.disabled === true ? "Enable cell" : "Disable cell",+ label: config.disabled ? "Enable cell" : "Disable cell",rightElement: (<Switchdata-testid="cell-disable-switch"diff --git a/frontend/src/components/editor/cell/DeleteButton.tsx b/frontend/src/components/editor/cell/DeleteButton.tsxindex c3a8bf4ef3..18932ddc28 100644--- a/frontend/src/components/editor/cell/DeleteButton.tsx+++ b/frontend/src/components/editor/cell/DeleteButton.tsx@@ -1,9 +1,9 @@/* Copyright 2024 Marimo. All rights reserved. */import { Trash2Icon } from "lucide-react";import { Tooltip } from "../../ui/tooltip";-import { CellStatus } from "../../../core/cells/types";import { Button } from "../../ui/button";import { cn } from "../../../utils/cn";+import { CellStatus } from "@/core/network/types";export const DeleteButton = (props: {status: CellStatus;diff --git a/frontend/src/components/editor/cell/RunButton.tsx b/frontend/src/components/editor/cell/RunButton.tsxindex 96dc8c8a32..b77afc151c 100644--- a/frontend/src/components/editor/cell/RunButton.tsx+++ b/frontend/src/components/editor/cell/RunButton.tsx@@ -4,9 +4,9 @@ import { Button } from "@/components/editor/inputs/Inputs";import { Tooltip } from "../../ui/tooltip";import { renderShortcut } from "../../shortcuts/renderShortcut";import { cn } from "../../../utils/cn";-import { CellConfig, CellStatus } from "../../../core/cells/types";import { sendInterrupt } from "@/core/network/requests";import { useShouldShowInterrupt } from "./useShouldShowInterrupt";+import { CellStatus, CellConfig } from "@/core/network/types";function computeColor(appClosed: boolean,diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 30223ac770..eab96f7484 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -14,11 +14,7 @@ import React, {import { setupCodeMirror } from "@/core/codemirror/cm";import useEvent from "react-use-event-hook";import { type CellActions, useCellActions } from "@/core/cells/cells";-import type {- CellRuntimeState,- CellData,- CellConfig,-} from "@/core/cells/types";+import type { CellRuntimeState, CellData } from "@/core/cells/types";import type { UserConfig } from "@/core/config/config-schema";import type { Theme } from "@/theme/useTheme";import {@@ -138,11 +134,11 @@ const CellEditorInternal = ({[cellId, focusCell],);const toggleHideCode = useEvent(() => {- const newConfig: CellConfig = { hide_code: !hidden };+ const nextHidden = !hidden;// Fire-and-forget save- void saveCellConfig({ configs: { [cellId]: newConfig } });- updateCellConfig({ cellId, config: newConfig });- return newConfig.hide_code || false;+ void saveCellConfig({ configs: { [cellId]: { hide_code: nextHidden } } });+ updateCellConfig({ cellId, config: { hide_code: nextHidden } });+ return nextHidden;});const autoInstantiate = useAtomValue(autoInstantiateAtom);const afterToggleMarkdown = useEvent(() => {@@ -336,7 +332,7 @@ const CellEditorInternal = ({const showCode = async () => {if (hidden) {- await saveCellConfig({ configs: { [cellId]: { hideCode: false } } });+ await saveCellConfig({ configs: { [cellId]: { hide_code: false } } });updateCellConfig({ cellId, config: { hide_code: false } });// Focus on the editor vieweditorViewRef.current?.focus();diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsxindex 3d4de0ca38..f0d719cca8 100644--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx@@ -338,7 +338,7 @@ const DatasetColumnPreview: React.FC<{<div key={key} className="flex items-center gap-1 group"><CopyClipboardIconclassName="h-3 w-3 invisible group-hover:visible"- value={value}+ value={String(value)}/><span className="text-xs min-w-[60px] uppercase">{key}</span><span className="text-xs font-bold text-muted-foreground tracking-wide">diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsxindex c0e56613f2..6d3a66b4dc 100644--- a/frontend/src/components/editor/file-tree/file-viewer.tsx+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx@@ -1,16 +1,12 @@/* Copyright 2024 Marimo. All rights reserved. */-import { generateColumns } from "@/components/data-table/columns";-import { DataTable } from "@/components/data-table/data-table";import { sendFileDetails, sendUpdateFile } from "@/core/network/requests";import { FileInfo } from "@/core/network/types";import { useAsyncData } from "@/hooks/useAsyncData";import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";import { ErrorBanner } from "@/plugins/impl/common/error-banner";-import { parseCsvData } from "@/plugins/impl/vega/loader";import { useTheme } from "@/theme/useTheme";-import { Objects } from "@/utils/objects";import { EditorView, keymap } from "@codemirror/view";-import React, { useEffect, useMemo, useRef, useState } from "react";+import React, { useEffect, useRef, useState } from "react";import { Button } from "../inputs/Inputs";import { CopyIcon, DownloadIcon, SaveIcon } from "lucide-react";import { renderShortcut } from "@/components/shortcuts/renderShortcut";@@ -19,6 +15,7 @@ import { downloadBlob, downloadByURL } from "@/utils/download";import { Base64String, base64ToDataURL } from "@/utils/json/base64";import { hotkeysAtom } from "@/core/config/config";import { useAtomValue } from "jotai";+import { ImageViewer, CsvViewer, AudioViewer, VideoViewer } from "./renderers";interface Props {file: FileInfo;@@ -222,55 +219,6 @@ export const FileViewer: React.FC<Props> = ({ file }) => {);};-const CsvViewer: React.FC<{ contents: string }> = ({ contents }) => {- const data = useMemo(() => parseCsvData(contents), [contents]);- const columns = useMemo(- () =>- generateColumns({- items: data,- rowHeaders: [],- selection: null,- showColumnSummaries: false,- }),- [data],- );-- return (- <DataTable- data={data}- columns={columns}- wrapperClassName="h-full justify-between pb-1 px-1"- pagination={true}- pageSize={10}- className="rounded-none border-b flex overflow-hidden"- rowSelection={Objects.EMPTY}- />- );-};--const ImageViewer: React.FC<{ base64: Base64String; mime: string }> = ({- mime,- base64,-}) => {- return <img src={base64ToDataURL(base64, mime)} alt="Preview" />;-};--const AudioViewer: React.FC<{ base64: Base64String; mime: string }> = ({- mime,- base64,-}) => {- // eslint-disable-next-line jsx-a11y/media-has-caption- return <audio controls={true} src={base64ToDataURL(base64, mime)} />;-};--const VideoViewer: React.FC<{ base64: Base64String; mime: string }> = ({- mime,- base64,-}) => {- // eslint-disable-next-line jsx-a11y/media-has-caption- return <video controls={true} src={base64ToDataURL(base64, mime)} />;-};-const isMedia = (mime: string) => {if (!mime) {return false;diff --git a/frontend/src/components/editor/file-tree/renderers.tsx b/frontend/src/components/editor/file-tree/renderers.tsxnew file mode 100644index 0000000000..c957fb8448--- /dev/null+++ b/frontend/src/components/editor/file-tree/renderers.tsx@@ -0,0 +1,55 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { generateColumns } from "@/components/data-table/columns";+import { DataTable } from "@/components/data-table/data-table";+import { parseCsvData } from "@/plugins/impl/vega/loader";+import { Objects } from "@/utils/objects";+import React, { useMemo } from "react";+import { Base64String, base64ToDataURL } from "@/utils/json/base64";++export const CsvViewer: React.FC<{ contents: string }> = ({ contents }) => {+ const data = useMemo(() => parseCsvData(contents), [contents]);+ const columns = useMemo(+ () =>+ generateColumns({+ items: data,+ rowHeaders: [],+ selection: null,+ showColumnSummaries: false,+ }),+ [data],+ );++ return (+ <DataTable+ data={data}+ columns={columns}+ wrapperClassName="h-full justify-between pb-1 px-1"+ pagination={true}+ pageSize={10}+ className="rounded-none border-b flex overflow-hidden"+ rowSelection={Objects.EMPTY}+ />+ );+};+export const ImageViewer: React.FC<{ base64: Base64String; mime: string }> = ({+ mime,+ base64,+}) => {+ return <img src={base64ToDataURL(base64, mime)} alt="Preview" />;+};++export const AudioViewer: React.FC<{ base64: Base64String; mime: string }> = ({+ mime,+ base64,+}) => {+ // eslint-disable-next-line jsx-a11y/media-has-caption+ return <audio controls={true} src={base64ToDataURL(base64, mime)} />;+};++export const VideoViewer: React.FC<{ base64: Base64String; mime: string }> = ({+ mime,+ base64,+}) => {+ // eslint-disable-next-line jsx-a11y/media-has-caption+ return <video controls={true} src={base64ToDataURL(base64, mime)} />;+};diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/ConsoleOutput.tsxindex 98039b4535..8ff82a2963 100644--- a/frontend/src/components/editor/output/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/ConsoleOutput.tsx@@ -8,13 +8,15 @@ import { NameCellContentEditable } from "../actions/name-cell-input";import { CellId } from "@/core/cells/ids";import { Input } from "@/components/ui/input";import { AnsiUp } from "ansi_up";+import { WithResponse } from "@/core/cells/types";+import { invariant } from "@/utils/invariant";const ansiUp = new AnsiUp();interface Props {cellId: CellId;cellName: string;- consoleOutputs: OutputMessage[];+ consoleOutputs: Array<WithResponse<OutputMessage>>;stale: boolean;debuggerActive: boolean;onSubmitDebugger: (text: string, index: number) => void;@@ -89,6 +91,11 @@ export const ConsoleOutput = (props: Props): React.ReactNode => {const original_idx = consoleOutputs.length - idx - 1;if (output.channel === "stdin") {+ invariant(+ typeof output.data === "string",+ "Expected data to be a string",+ );+if (output.response == null) {return (<div key={idx} className="flex gap-2 items-center">diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsxindex 475f8d112d..2a757f462f 100644--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx@@ -14,6 +14,7 @@ import {} from "@/components/ui/accordion";import { Fragment } from "react";import { CellLinkError } from "../links/cell-link";+import { CellId } from "@/core/cells/ids";const Tip = (props: {className?: string;@@ -65,13 +66,13 @@ export const MarimoErrorOutput = ({<ul className="list-disc">{error.edges_with_vars.map((edge) => (<li className={liStyle} key={`${edge[0]}-${edge[1]}`}>- <CellLinkError cellId={edge[0]} />+ <CellLinkError cellId={edge[0] as CellId} /><span className="text-muted-foreground">{" -> "}{edge[1].length == 1 ? edge[1] : edge[1].join(", ")}{" -> "}</span>- <CellLinkError cellId={edge[2]} />+ <CellLinkError cellId={edge[2] as CellId} /></li>))}</ul>@@ -88,7 +89,7 @@ export const MarimoErrorOutput = ({<ul className="list-disc">{error.cells.map((cid) => (<li className={liStyle} key={cid}>- <CellLinkError cellId={cid} />+ <CellLinkError cellId={cid as CellId} /></li>))}</ul>@@ -106,7 +107,7 @@ export const MarimoErrorOutput = ({<div className="mt-4">{`The variable '${error.name}' can't be deleted because it was defined by another cell ` +`(`}- <CellLinkError cellId={error.cells[0]} />+ <CellLinkError cellId={error.cells[0] as CellId} />{")"}</div><Tip>@@ -132,10 +133,11 @@ export const MarimoErrorOutput = ({) : (<div key={idx}>{error.msg}- <CellLinkError cellId={error.raising_cell} />+ <CellLinkError cellId={error.raising_cell as CellId} /><Tip>- Fix the error in <CellLinkError cellId={error.raising_cell} />, or- handle the exception in with a try/except block.+ Fix the error in{" "}+ <CellLinkError cellId={error.raising_cell as CellId} />, or handle+ the exception in with a try/except block.</Tip></div>);@@ -151,10 +153,10 @@ export const MarimoErrorOutput = ({) : (<div key={idx}>{error.msg}- <CellLinkError cellId={error.blamed_cell} />+ <CellLinkError cellId={error.blamed_cell as CellId} /><Tip>Ensure that - <CellLinkError cellId={error.blamed_cell} />+ <CellLinkError cellId={error.blamed_cell as CellId} /> defines the variable {error.ref}, or turn off strictexecution.</Tip>@@ -167,9 +169,9 @@ export const MarimoErrorOutput = ({return (<div key={idx}>{error.msg}- (<CellLinkError cellId={error.raising_cell} />+ (<CellLinkError cellId={error.raising_cell as CellId} /> blames - <CellLinkError cellId={error.blamed_cell} />)+ <CellLinkError cellId={error.blamed_cell as CellId} />)</div>);case "ancestor-stopped":@@ -179,7 +181,7 @@ export const MarimoErrorOutput = ({return (<div key={idx}>{error.msg}- <CellLinkError cellId={error.raising_cell} />+ <CellLinkError cellId={error.raising_cell as CellId} /></div>);diff --git a/frontend/src/components/editor/output/TextOutput.tsx b/frontend/src/components/editor/output/TextOutput.tsxindex 53fe31b900..e043236842 100644--- a/frontend/src/components/editor/output/TextOutput.tsx+++ b/frontend/src/components/editor/output/TextOutput.tsx@@ -8,7 +8,7 @@ const ansiUp = new AnsiUp();interface Props {text: string;- channel?: OutputChannel | "stdin";+ channel?: OutputChannel;}export const TextOutput = ({ text, channel }: Props): JSX.Element => {diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex ff92a7e333..e0ffb545cd 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import React, { memo, useRef, useState } from "react";-import { CellConfig, CellRuntimeState } from "@/core/cells/types";+import { CellRuntimeState } from "@/core/cells/types";import { CellId, HTMLCellId } from "@/core/cells/ids";import { OutputArea } from "@/components/editor/Output";import { ICellRendererPlugin, ICellRendererProps } from "../types";@@ -30,6 +30,7 @@ import {import { downloadHTMLAsImage } from "@/utils/download";import { downloadAsHTML } from "@/core/static/download-html";import { isPyodide } from "@/core/pyodide/utils";+import { CellConfig } from "@/core/network/types";type VerticalLayout = null;type VerticalLayoutProps = ICellRendererProps<VerticalLayout>;diff --git a/frontend/src/components/variables/variables-table.tsx b/frontend/src/components/variables/variables-table.tsxindex 8d30c29b3b..ae1bc1d289 100644--- a/frontend/src/components/variables/variables-table.tsx+++ b/frontend/src/components/variables/variables-table.tsx@@ -97,7 +97,7 @@ const COLUMNS = [</div><divclassName="text-ellipsis overflow-hidden whitespace-nowrap"- title={value}+ title={value ?? ""}>{value}</div>diff --git a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snapindex b110163ab8..ed1a62668c 100644--- a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap+++ b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap@@ -3,7 +3,10 @@exports[`cell reducer > can initialize stdin 1`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -27,7 +30,10 @@ exports[`cell reducer > can initialize stdin 1`] = `exports[`cell reducer > can initialize stdin 2`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -51,7 +57,10 @@ exports[`cell reducer > can initialize stdin 2`] = `exports[`cell reducer > can initialize stdin 3`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -75,7 +84,10 @@ exports[`cell reducer > can initialize stdin 3`] = `exports[`cell reducer > can initialize stdin 4`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -99,7 +111,10 @@ exports[`cell reducer > can initialize stdin 4`] = `exports[`cell reducer > can initialize stdin 5`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -130,7 +145,10 @@ exports[`cell reducer > can initialize stdin 5`] = `exports[`cell reducer > can initialize stdin 6`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -161,7 +179,10 @@ exports[`cell reducer > can initialize stdin 6`] = `exports[`cell reducer > can initialize stdin 7`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -198,7 +219,10 @@ exports[`cell reducer > can initialize stdin 7`] = `exports[`cell reducer > can initialize stdin 8`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -236,7 +260,10 @@ exports[`cell reducer > can initialize stdin 8`] = `exports[`cell reducer > can initialize stdin 9`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -280,7 +307,10 @@ exports[`cell reducer > can initialize stdin 9`] = `exports[`cell reducer > can receive console when the cell is idle and will clear when starts again 1`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -304,7 +334,10 @@ exports[`cell reducer > can receive console when the cell is idle and will clearexports[`cell reducer > can receive console when the cell is idle and will clear when starts again 2`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -335,7 +368,10 @@ exports[`cell reducer > can receive console when the cell is idle and will clearexports[`cell reducer > can receive console when the cell is idle and will clear when starts again 3`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -366,7 +402,10 @@ exports[`cell reducer > can receive console when the cell is idle and will clearexports[`cell reducer > can receive console when the cell is idle and will clear when starts again 4`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -390,7 +429,10 @@ exports[`cell reducer > can receive console when the cell is idle and will clearexports[`cell reducer > can receive console when the cell is idle and will clear when starts again 5`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdin",@@ -421,7 +463,10 @@ exports[`cell reducer > can receive console when the cell is idle and will clearexports[`cell reducer > can run a stale cell 1`] = `{"code": "mo.slider()",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -445,7 +490,10 @@ exports[`cell reducer > can run a stale cell 1`] = `exports[`cell reducer > can run a stale cell 2`] = `{"code": "mo.slider()",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -469,7 +517,10 @@ exports[`cell reducer > can run a stale cell 2`] = `exports[`cell reducer > can run a stopped cell 1`] = `{"code": "mo.md('This has an ancestor that was stopped')",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -493,7 +544,10 @@ exports[`cell reducer > can run a stopped cell 1`] = `exports[`cell reducer > can run a stopped cell 2`] = `{"code": "mo.md('This has an ancestor that was stopped')",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -517,7 +571,10 @@ exports[`cell reducer > can run a stopped cell 2`] = `exports[`cell reducer > can run a stopped cell 3`] = `{"code": "mo.md('This has an ancestor that was stopped')",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -552,7 +609,10 @@ exports[`cell reducer > can run a stopped cell 3`] = `exports[`cell reducer > can run a stopped cell 4`] = `{"code": "mo.md('This has an ancestor that was stopped')",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -587,7 +647,10 @@ exports[`cell reducer > can run a stopped cell 4`] = `exports[`cell reducer > can run a stopped cell 5`] = `{"code": "mo.md('This has an ancestor that was stopped')",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -611,7 +674,10 @@ exports[`cell reducer > can run a stopped cell 5`] = `exports[`cell reducer > can run cell and receive cell messages 1`] = `{"code": "",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -635,7 +701,10 @@ exports[`cell reducer > can run cell and receive cell messages 1`] = `exports[`cell reducer > can run cell and receive cell messages 2`] = `{"code": "import marimo as mo",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": true,@@ -659,7 +728,10 @@ exports[`cell reducer > can run cell and receive cell messages 2`] = `exports[`cell reducer > can run cell and receive cell messages 3`] = `{"code": "import marimo as mo",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -683,7 +755,10 @@ exports[`cell reducer > can run cell and receive cell messages 3`] = `exports[`cell reducer > can run cell and receive cell messages 4`] = `{"code": "import marimo as mo",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -707,7 +782,10 @@ exports[`cell reducer > can run cell and receive cell messages 4`] = `exports[`cell reducer > can run cell and receive cell messages 5`] = `{"code": "import marimo as mo",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [],"debuggerActive": false,"edited": false,@@ -731,7 +809,10 @@ exports[`cell reducer > can run cell and receive cell messages 5`] = `exports[`cell reducer > can run cell and receive cell messages 6`] = `{"code": "import marimo as mo",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -762,7 +843,10 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `exports[`cell reducer > can run cell and receive cell messages 7`] = `{"code": "import marimo as mo",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -799,7 +883,10 @@ exports[`cell reducer > can run cell and receive cell messages 8`] = `{"code": "import marimo as moimport numpy",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -835,7 +922,10 @@ import numpy",exports[`cell reducer > can run cell and receive cell messages 9`] = `{"code": "import marimo as mo",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -872,7 +962,10 @@ exports[`cell reducer > can run cell and receive cell messages 10`] = `{"code": "import marimo as moimport numpy",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -909,7 +1002,10 @@ exports[`cell reducer > can run cell and receive cell messages 11`] = `{"code": "import marimo as moimport numpy",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",@@ -953,7 +1049,10 @@ exports[`cell reducer > can run cell and receive cell messages 12`] = `{"code": "import marimo as moimport numpy",- "config": {},+ "config": {+ "disabled": false,+ "hide_code": false,+ },"consoleOutputs": [{"channel": "stdout",diff --git a/frontend/src/core/cells/__tests__/cell.test.ts b/frontend/src/core/cells/__tests__/cell.test.tsindex b462670710..be55585fd0 100644--- a/frontend/src/core/cells/__tests__/cell.test.ts+++ b/frontend/src/core/cells/__tests__/cell.test.ts@@ -1,9 +1,9 @@/* Copyright 2024 Marimo. All rights reserved. */import { expect, describe, it } from "vitest";import { outputIsStale } from "../cell";-import { CellStatus } from "../types";import { OutputMessage } from "@/core/kernel/messages";import { Seconds } from "@/utils/time";+import { CellStatus } from "@/core/network/types";const STATUSES: CellStatus[] = ["queued",diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex f0f7104321..56bfc101c4 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -274,7 +274,7 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "queued",stale_inputs: null,@@ -291,7 +291,7 @@ describe("cell reducer", () => {// Receive running messagesactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "running",stale_inputs: null,@@ -308,14 +308,14 @@ describe("cell reducer", () => {// Console messages shouldn't transition statusactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: {channel: "stdout",mimetype: "text/plain",data: "hello!",timestamp: 0,},- status: null,+ status: undefined,stale_inputs: null,timestamp: new Date(22).getTime() as Seconds,});@@ -398,7 +398,7 @@ describe("cell reducer", () => {// Queueactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "queued",stale_inputs: null,@@ -409,7 +409,7 @@ describe("cell reducer", () => {// Runningactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "running",stale_inputs: null,@@ -453,7 +453,7 @@ describe("cell reducer", () => {// Queueactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "queued",stale_inputs: null,@@ -464,7 +464,7 @@ describe("cell reducer", () => {// Runningactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "running",stale_inputs: null,@@ -523,7 +523,7 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({cell_id: secondCell,- output: null,+ output: undefined,console: null,status: "queued",stale_inputs: null,@@ -540,9 +540,9 @@ describe("cell reducer", () => {// Receive stale messageactions.handleCellMessage({cell_id: secondCell,- output: null,+ output: undefined,console: null,- status: null,+ status: undefined,stale_inputs: true,timestamp: new Date(20).getTime() as Seconds,});@@ -612,7 +612,10 @@ describe("cell reducer", () => {const firstCellId = cells[0].id;let cell = cells[0];// Starts empty- expect(cell.config).toEqual({});+ expect(cell.config).toEqual({+ disabled: false,+ hide_code: false,+ });actions.updateCellConfig({cellId: firstCellId,@@ -646,7 +649,7 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "queued",stale_inputs: null,@@ -665,7 +668,7 @@ describe("cell reducer", () => {// Receive idle messageactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "idle",stale_inputs: null,@@ -706,7 +709,7 @@ describe("cell reducer", () => {// Receive queued messageactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "queued",stale_inputs: null,@@ -720,7 +723,7 @@ describe("cell reducer", () => {// Receive running messageactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "running",stale_inputs: null,@@ -771,7 +774,7 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "queued",stale_inputs: null,@@ -784,7 +787,7 @@ describe("cell reducer", () => {// Receive running messagesactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "running",stale_inputs: null,@@ -797,9 +800,9 @@ describe("cell reducer", () => {// Add consoleactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: STDOUT,- status: null,+ status: undefined,stale_inputs: null,timestamp: new Date(22).getTime() as Seconds,});@@ -815,9 +818,9 @@ describe("cell reducer", () => {// Ask via stdinactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: STD_IN_1,- status: null,+ status: undefined,stale_inputs: null,timestamp: new Date(22).getTime() as Seconds,});@@ -846,9 +849,9 @@ describe("cell reducer", () => {// Ask via stdin, againactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: STD_IN_2,- status: null,+ status: undefined,stale_inputs: null,timestamp: new Date(22).getTime() as Seconds,});@@ -907,9 +910,9 @@ describe("cell reducer", () => {// Add consoleactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: [OLD_STDOUT],- status: null,+ status: undefined,stale_inputs: null,timestamp: new Date(1).getTime() as Seconds,});@@ -926,7 +929,7 @@ describe("cell reducer", () => {// Receive queued messagesactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: null,status: "queued",stale_inputs: null,@@ -940,7 +943,7 @@ describe("cell reducer", () => {// Receive running messagesactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: [], // Backend sends an empty array to clearustatus: "running",stale_inputs: null,@@ -954,7 +957,7 @@ describe("cell reducer", () => {// Add consoleactions.handleCellMessage({cell_id: firstCellId,- output: null,+ output: undefined,console: [STDOUT],status: "idle",stale_inputs: null,diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.tsindex b074b7ef24..99e25caacc 100644--- a/frontend/src/core/cells/cell.ts+++ b/frontend/src/core/cells/cell.ts@@ -1,10 +1,11 @@/* Copyright 2024 Marimo. All rights reserved. */import { logNever } from "@/utils/assertNever";-import { CellMessage, OutputMessage } from "../kernel/messages";+import { CellMessage } from "../kernel/messages";import { CellRuntimeState } from "./types";import { collapseConsoleOutputs } from "./collapseConsoleOutputs";import { parseOutline } from "../dom/outline";import { Seconds, Time } from "@/utils/time";+import { invariant } from "@/utils/invariant";export function transitionCell(cell: CellRuntimeState,@@ -37,7 +38,7 @@ export function transitionCell(nextCell.consoleOutputs = [];}nextCell.stopped = false;- nextCell.runStartTimestamp = message.timestamp;+ nextCell.runStartTimestamp = message.timestamp as Seconds;break;case "idle":if (cell.runStartTimestamp) {@@ -54,6 +55,8 @@ export function transitionCell(case "disabled-transitively":// Everything should already be up to date from prepareCellForExecutionbreak;+ case undefined:+ break;default:logNever(message.status);}@@ -67,9 +70,13 @@ export function transitionCell(// Handle errors: marimo includes an error output when a cell is interrupted// or erroredif (- message.output !== null &&+ message.output != null &&message.output.mimetype === "application/vnd.marimo+error") {+ invariant(+ Array.isArray(message.output.data),+ "Expected error output data to be an array",+ );if (message.output.data.some((error) => error.type === "interruption")) {// Interrupted helps distinguish that the cell is stalenextCell.interrupted = true;@@ -107,7 +114,9 @@ export function transitionCell(// existing console outputs.consoleOutputs = Array.isArray(message.console)? message.console- : collapseConsoleOutputs([...consoleOutputs, message.console]);+ : collapseConsoleOutputs(+ [...consoleOutputs, message.console].filter(Boolean),+ );}nextCell.consoleOutputs = consoleOutputs;// Derive outline from output@@ -116,8 +125,7 @@ export function transitionCell(// Transition PDBconst newConsoleOutputs = [message.console].flat().filter(Boolean);const pdbOutputs = newConsoleOutputs.filter(- (output): output is Extract<OutputMessage, { channel: "pdb" }> =>- output.channel === "pdb",+ (output) => output.channel === "pdb",);const hasPdbOutput = pdbOutputs.length > 0;if (hasPdbOutput && pdbOutputs.some((output) => output.data === "start")) {diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex ac2e9c00ad..6ab991f4f7 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -3,7 +3,6 @@ import { atom, useAtom, useAtomValue } from "jotai";import { type ReducerWithoutAction, createRef } from "react";import type { CellMessage } from "../kernel/messages";import {- type CellConfig,type CellRuntimeState,type CellData,createCell,@@ -37,6 +36,8 @@ import {splitEditor,updateEditorCodeFromPython,} from "../codemirror/language/utils";+import { invariant } from "@/utils/invariant";+import { CellConfig } from "../network/types";/*** The state of the notebook.@@ -460,7 +461,7 @@ const {});},handleCellMessage: (state, message: CellMessage) => {- const cellId = message.cell_id;+ const cellId = message.cell_id as CellId;const nextState = updateCellRuntimeState(state, cellId, (cell) => {return transitionCell(cell, message);});@@ -755,6 +756,7 @@ const cellErrorsAtom = atom((get) => {// Filter out ancestor-stopped errors// These are errors that are caused by a cell that was stopped,// but nothing the user can take action on.+ invariant(Array.isArray(cell.output.data), "Expected array data");const nonAncestorErrors = cell.output.data.filter((error) => !error.type.includes("ancestor"),);diff --git a/frontend/src/core/cells/collapseConsoleOutputs.tsx b/frontend/src/core/cells/collapseConsoleOutputs.tsxindex 092e72eff5..a2a3669a29 100644--- a/frontend/src/core/cells/collapseConsoleOutputs.tsx+++ b/frontend/src/core/cells/collapseConsoleOutputs.tsx@@ -63,6 +63,7 @@ function handleCarriageReturns(const carriagePattern = new RegExp("\r[^\n]", "g");// collapse carriage returns in the final output's datalet text = lastOutput.data;+ invariant(typeof text === "string", "expected string");let carriageIdx = text.search(carriagePattern);while (carriageIdx > -1) {// find the newline character preceding the carriage return, if any@@ -73,9 +74,9 @@ function handleCarriageReturns(break;}}- const postCarriageText = text.slice(carriageIdx + 1);+ const postCarriageText: string = text.slice(carriageIdx + 1);const prefix = text.slice(0, newlineIdx + 1);- const intermediateText = text.slice(newlineIdx + 1, carriageIdx);+ const intermediateText: string = text.slice(newlineIdx + 1, carriageIdx);text =intermediateText.length <= postCarriageText.length? prefix + postCarriageText@@ -96,8 +97,9 @@ function truncateHead(consoleOutputs: OutputMessage[], limit: number) {let nLines = 0;let i;for (i = consoleOutputs.length - 1; i >= 0 && nLines < limit; i--) {- const output = consoleOutputs[i];+ const output: OutputMessage = consoleOutputs[i];if (output.mimetype === "text/plain") {+ invariant(typeof output.data === "string", "expected string");nLines += output.data.split("\n").length;} else {nLines++;@@ -117,6 +119,7 @@ function truncateHead(consoleOutputs: OutputMessage[], limit: number) {};const output = consoleOutputs[cutoff];if (output.mimetype == "text/plain") {+ invariant(typeof output.data === "string", "expected string");const output_lines = output.data.split("\n");const nLinesAfterOutput = nLines - output_lines.length;const nLinesToKeep = limit - nLinesAfterOutput;diff --git a/frontend/src/core/cells/focus.ts b/frontend/src/core/cells/focus.tsindex 89c35a233d..494fd4e974 100644--- a/frontend/src/core/cells/focus.ts+++ b/frontend/src/core/cells/focus.ts@@ -3,7 +3,7 @@ import { atom } from "jotai";import type { CellId } from "./ids";import { type NotebookState, notebookAtom } from "./cells";import type { EditorView } from "@codemirror/view";-import type { CellConfig, CellStatus } from "./types";+import { CellConfig, CellStatus } from "../network/types";/*** Holds state for the last focused cell.diff --git a/frontend/src/core/cells/logs.ts b/frontend/src/core/cells/logs.tsindex bbadb18238..79d2033f8f 100644--- a/frontend/src/core/cells/logs.ts+++ b/frontend/src/core/cells/logs.ts@@ -1,4 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */+import { invariant } from "@/utils/invariant";import { CellMessage, OutputMessage } from "../kernel/messages";import { CellId } from "./ids";import { fromUnixTime } from "date-fns";@@ -16,22 +17,18 @@ export function getCellLogsForMessage(cell: CellMessage): CellLog[] {for (const output of outputs) {if (output.mimetype === "text/plain") {+ invariant(typeof output.data === "string", "expected string");+ const isError =+ output.channel === "stderr" || output.channel === "marimo-error";switch (output.channel) {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",+ timestamp: output.timestamp || Date.now(),+ level: isError ? "stderr" : "stdout",message: output.data,- cellId: cell.cell_id,+ cellId: cell.cell_id as CellId,});break;default:diff --git a/frontend/src/core/cells/scrollCellIntoView.ts b/frontend/src/core/cells/scrollCellIntoView.tsindex 756ffa5da7..d01fef54e6 100644--- a/frontend/src/core/cells/scrollCellIntoView.ts+++ b/frontend/src/core/cells/scrollCellIntoView.ts@@ -3,8 +3,8 @@ import type { RefObject } from "react";import { Logger } from "../../utils/Logger";import { type CellId, HTMLCellId } from "./ids";import type { CellHandle } from "@/components/editor/Cell";-import type { CellConfig } from "./types";import { goToVariableDefinition } from "../codemirror/go-to-definition/commands";+import { CellConfig } from "../network/types";export function focusAndScrollCellIntoView({cellId,diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.tsindex 817ca493ec..3133f07383 100644--- a/frontend/src/core/cells/types.ts+++ b/frontend/src/core/cells/types.ts@@ -6,20 +6,7 @@ import { CellId } from "./ids";import { DEFAULT_CELL_NAME } from "./names";import { Milliseconds, Seconds } from "@/utils/time";import { getUserConfig } from "../config/config";--/**- * The status of a cell.- *- * queued: queued by the kernel.- * running: currently executing.- * idle: not running.- * disabled-transitively: disabled because an ancestor was disabled.- */-export type CellStatus =- | "queued"- | "running"- | "idle"- | "disabled-transitively";+import { CellConfig, CellStatus } from "../network/types";/*** Create a new cell with default state.@@ -31,12 +18,15 @@ export function createCell({lastCodeRun = null,lastExecutionTime = null,edited = false,- config = {},+ config,serializedEditorState = null,}: Partial<CellData> & { id: CellId }): CellData {return {id: id,- config: config,+ config: config || {+ hide_code: false,+ disabled: false,+ },name: name,code: code,edited: edited,@@ -93,7 +83,7 @@ export interface CellRuntimeState {/** TOC outline */outline: Outline | null;/** messages encoding the cell's console outputs. */- consoleOutputs: OutputMessage[];+ consoleOutputs: Array<WithResponse<OutputMessage>>;/** current status of the cell */status: CellStatus;/** whether the cell has stale inputs*/@@ -115,13 +105,10 @@ export interface CellRuntimeState {debuggerActive: boolean;}-export interface CellConfig {+export type WithResponse<T> = T & {/**- * If true, the cell and its descendants are unable to run.+ * This is not saved to the server, but we update this field+ * after sending the message to the kernel.*/- disabled?: boolean;- /**- * If true, the cell's code is hidden from the notebook.- */- hide_code?: boolean;-}+ response?: string;+};diff --git a/frontend/src/core/codemirror/completion/Autocompleter.ts b/frontend/src/core/codemirror/completion/Autocompleter.tsindex e063f38440..ca46ac1641 100644--- a/frontend/src/core/codemirror/completion/Autocompleter.ts+++ b/frontend/src/core/codemirror/completion/Autocompleter.ts@@ -11,7 +11,9 @@ import { DeferredRequestRegistry } from "@/core/network/DeferredRequestRegistry"import { CodeCompletionRequest } from "@/core/network/types";import "../../../components/editor/documentation.css";-function constructCompletionInfoNode(innerHtml?: string): HTMLElement | null {+function constructCompletionInfoNode(+ innerHtml?: string | null,+): HTMLElement | null {if (!innerHtml) {return null;}@@ -77,7 +79,7 @@ export const Autocompleter = {limitToType?: "tooltip";excludeTypes?: string[];exactName?: string;- }): (Tooltip & { html?: string }) | undefined {+ }): (Tooltip & { html?: string | null }) | undefined {const firstOption = getFirstOption(message.options, exactName);if (!firstOption) {return undefined;diff --git a/frontend/src/core/datasets/state.ts b/frontend/src/core/datasets/state.tsindex 9ed984eb93..422744df12 100644--- a/frontend/src/core/datasets/state.ts+++ b/frontend/src/core/datasets/state.ts@@ -64,7 +64,9 @@ const {const names = new Set(variableNames);// Filter out tables that come from variables that are not in the listconst tables = state.tables.filter((table) => {- return table.variable_name && names.has(table.variable_name);+ return (+ table.variable_name && names.has(table.variable_name as VariableName)+ );});return { ...state, tables };},diff --git a/frontend/src/core/dom/outline.ts b/frontend/src/core/dom/outline.tsindex 07bc1e4251..b361145dfe 100644--- a/frontend/src/core/dom/outline.ts+++ b/frontend/src/core/dom/outline.ts@@ -3,6 +3,7 @@import { Logger } from "@/utils/Logger";import { OutputMessage } from "../kernel/messages";import { Outline } from "../cells/outline";+import { invariant } from "@/utils/invariant";function getOutline(html: string): Outline {const items: Outline["items"] = [];@@ -50,6 +51,7 @@ export function parseOutline(output: OutputMessage | null): Outline | null {}try {+ invariant(typeof output.data === "string", "expected string");return getOutline(output.data);} catch {Logger.error("Failed to parse outline");diff --git a/frontend/src/core/errors/state.ts b/frontend/src/core/errors/state.tsindex b2da92ef76..5f5cf2341c 100644--- a/frontend/src/core/errors/state.ts+++ b/frontend/src/core/errors/state.ts@@ -2,24 +2,22 @@import { createReducerAndAtoms } from "@/utils/createReducer";import { useAtomValue } from "jotai";--interface Banner {- id: string;- title: string;- description: string;- variant?: "danger";- action?: "restart";-}+import { Banner } from "../kernel/messages";+import { generateUUID } from "@/utils/uuid";+import { Identified } from "@/utils/typed";interface BannerState {- banners: Banner[];+ banners: Array<Identified<Banner>>;}const { valueAtom: bannersAtom, useActions } = createReducerAndAtoms(() => ({ banners: [] }) as BannerState,{addBanner: (state, banner: Banner) => {- return { ...state, banners: [...state.banners, banner] };+ return {+ ...state,+ banners: [...state.banners, { ...banner, id: generateUUID() }],+ };},removeBanner: (state, id: string) => {return {diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.tsindex 4707eb6eee..1dc0ebe8fc 100644--- a/frontend/src/core/islands/main.ts+++ b/frontend/src/core/islands/main.ts@@ -27,6 +27,7 @@ import { defineCustomElement } from "../dom/defineCustomElement";import { MarimoIslandElement } from "./components/web-components";import { RuntimeState } from "../kernel/RuntimeState";import { sendComponentValues } from "../network/requests";+import { RequestId } from "../network/DeferredRequestRegistry";/*** Main entry point for the js bundle for embedded marimo apps.@@ -88,7 +89,10 @@ export async function initialize() {handleRemoveUIElements(msg.data);return;case "function-call-result":- FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);+ FUNCTIONS_REGISTRY.resolve(+ msg.data.function_call_id as RequestId,+ msg.data,+ );return;case "cell-op":handleCellOperation(msg.data, actions.handleCellMessage);@@ -120,6 +124,8 @@ export async function initialize() {case "query-params-clear":queryParamHandlers.clear();return;+ case "reconnected":+ return;default:logNever(msg);}diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.tsindex 676535cfeb..0ec7f307ef 100644--- a/frontend/src/core/kernel/handlers.ts+++ b/frontend/src/core/kernel/handlers.ts@@ -4,19 +4,15 @@ import { Objects } from "@/utils/objects";import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";import { LayoutData, LayoutState, initialLayoutState } from "../layout/layout";import { sendInstantiate } from "../network/requests";-import { CellMessage, OperationMessage } from "./messages";+import { CellMessage, OperationMessageData } from "./messages";import { LayoutType } from "@/components/editor/renderers/types";import { AppConfig } from "../config/config-schema";import { CellData, createCell } from "../cells/types";import { VirtualFileTracker } from "../static/virtual-file-tracker";--export type OperationMessageData<T extends OperationMessage["op"]> = Extract<- OperationMessage,- { op: T }->;+import { CellId, UIElementId } from "../cells/ids";export function handleKernelReady(- data: OperationMessageData<"kernel-ready">["data"],+ data: OperationMessageData<"kernel-ready">,opts: {autoInstantiate: boolean;setCells: (cells: CellData[], layout: LayoutState) => void;@@ -39,10 +35,12 @@ export function handleKernelReady(resumed,ui_values,cell_ids,- last_executed_code = {},+ last_executed_code,last_execution_time = {},app_config,} = data;+ const lastExecutedCode = last_executed_code || {};+ const lastExecutionTime = last_execution_time || {};// Set the layout, initial codes, cellsconst cells = codes.map((code, i) => {@@ -52,7 +50,7 @@ export function handleKernelReady(// or if the code has changed since the last time it was run.let edited = false;if (autoInstantiate || resumed) {- const lastCodeRun = last_executed_code[cellId];+ const lastCodeRun = lastExecutedCode[cellId];if (lastCodeRun) {edited = lastCodeRun !== code;}@@ -61,31 +59,34 @@ export function handleKernelReady(}return createCell({- id: cellId,+ id: cellId as CellId,code,edited: edited,name: names[i],- lastCodeRun: last_executed_code[cellId] ?? null,- lastExecutionTime: last_execution_time[cellId] ?? null,+ lastCodeRun: lastExecutedCode[cellId] ?? null,+ lastExecutionTime: lastExecutionTime[cellId] ?? null,config: configs[i],});});const layoutState = initialLayoutState();if (layout) {- const layoutData = deserializeLayout(layout.type, layout.data, cells);- layoutState.selectedLayout = layout.type;- layoutState.layoutData[layout.type] = layoutData;- setLayoutData({ layoutView: layout.type, data: layoutData });+ const layoutType = layout.type as LayoutType;+ const layoutData = deserializeLayout(layoutType, layout.data, cells);+ layoutState.selectedLayout = layoutType;+ layoutState.layoutData[layoutType] = layoutData;+ setLayoutData({ layoutView: layoutType, data: layoutData });}setCells(cells, layoutState);- setAppConfig(app_config);+ setAppConfig({+ ...app_config,+ } as AppConfig);// If resumed, we don't need to instantiate the UI elements,// and we should read in th existing values from the kernel.if (resumed) {for (const [objectId, value] of Objects.entries(ui_values || {})) {- UI_ELEMENT_REGISTRY.set(objectId, value);+ UI_ELEMENT_REGISTRY.set(objectId as UIElementId, value);}return;}@@ -111,18 +112,18 @@ export function handleKernelReady(}export function handleRemoveUIElements(- data: OperationMessageData<"remove-ui-elements">["data"],+ data: OperationMessageData<"remove-ui-elements">,) {// This removes the element from the registry to (1) clean-up// memory and (2) make sure that the old value doesn't get re-used// if the same cell-id is later reused for another element.- const { cell_id } = data;+ const cell_id = data.cell_id as CellId;UI_ELEMENT_REGISTRY.removeElementsByCell(cell_id);VirtualFileTracker.INSTANCE.removeForCellId(cell_id);}export function handleCellOperation(- data: OperationMessageData<"cell-op">["data"],+ data: OperationMessageData<"cell-op">,handleCellMessage: (message: CellMessage) => void,) {/* Register a state transition for a cell.diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex 11393744ae..df6a38d22c 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -1,400 +1,34 @@/* Copyright 2024 Marimo. All rights reserved. */--import type { LayoutType } from "@/components/editor/renderers/types";-import type { CellConfig, CellStatus } from "../cells/types";-import type { CellId, UIElementId } from "../cells/ids";-import type { VariableName } from "../variables/types";-import type { RequestId } from "../network/DeferredRequestRegistry";-import type { Seconds } from "@/utils/time";-import type { AppConfig } from "../config/config-schema";-import type { ColumnPreviewSummary } from "../datasets/types";-import type { JsonString } from "@/utils/json/base64";--export type DataType =- | "string"- | "boolean"- | "integer"- | "number"- | "date"- | "unknown";--export interface DataTableColumn {- name: string;- type: DataType;-}--export interface DataTable {- name: string;- source: string;- /**- * The variable name if this is a variable in the notebook.- */- variable_name: VariableName | null;- num_rows: number;- num_columns: number;- columns: DataTableColumn[];-}--export type OutputChannel =- | "output"- | "media"- | "marimo-error"- | "pdb"- | "stderr"- | "stdout";--export type MarimoError =- | { type: "syntax"; msg?: string }- | { type: "interruption"; msg?: string }- | {- type: "exception";- exception_type: string;- msg: string;- raising_cell?: CellId;- }- | {- type: "ancestor-prevented";- msg: string;- raising_cell: CellId;- blamed_cell: CellId;- }- | { type: "ancestor-stopped"; msg: string; raising_cell: CellId }- | { type: "cycle"; edges_with_vars: Array<[CellId, string[], CellId]> }- | { type: "multiple-defs"; name: string; cells: CellId[] }- | { type: "delete-nonlocal"; name: string; cells: CellId[] }- | {- type: "strict-exception";- msg: string;- ref: string;- blamed_cell: CellId;- }- | { type: "unknown"; msg?: string };--export type OutputMessage =- | {- channel: OutputChannel;- mimetype: "application/vnd.marimo+error";- data: MarimoError[];- timestamp: number;- }- | {- channel: OutputChannel;- mimetype:- | "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;- timestamp: number;- }- | {- channel: OutputChannel;- mimetype: "application/json";- data: unknown;- timestamp: number;- }- | {- channel: "pdb";- mimetype: "application/json";- data: "start" | "stop";- timestamp: number;- }- | {- channel: "stdin";- mimetype: "text/plain";- data: string;- /**- * This is not saved to the server, but we update this field- * after sending the message to the kernel.- */- response?: string;- timestamp: number;- };--/**- * Control messages sent from the kernel describing the execution state- * and output (including errors) of a cell.- */-export interface CellMessage {- /**- * The ID of the cell this message is about- */- cell_id: CellId;- /**- * The output of the cell, if any- */- output: OutputMessage | null;- /**- * The console output of the cell, if any- */- console: OutputMessage | OutputMessage[] | null;- /**- * Encodes status transitions. Non-null means a transition happened. Null- * means no transition in status.- */- status: CellStatus | null;- /**- * Transition in staleness.- */- stale_inputs: boolean | null;- /**- * Timestamp in seconds since epoch, when the message was sent- */- timestamp: Seconds;-}--export interface CompletionOption {- name: string;- type: string;- completion_info?: string;-}--/**- * Message sent from the kernel in response to a completion request- * from the frontend.- */-export interface CompletionResultMessage {- /**- * The ID of the completion request- */- completion_id: RequestId;- prefix_length: number;- /**- * The options for completion- */- options: CompletionOption[];-}--/**- * Status code, and human readable explanation.- */-export interface HumanReadableStatus {- code: "ok" | "error";- title?: string;- message?: string;-}--/**- * Message for function call results- */-export interface FunctionCallResultMessage {- /**- * The ID of the function call- */- function_call_id: RequestId;- /**- * The result of the function call- */- return_value: unknown;- /**- * Status code and human readable info.- */- status: HumanReadableStatus;-}--export interface PackageInstallationStatus {- /**- * Package name => status- */- [key: string]: "queued" | "installing" | "installed" | "failed";-}--export interface DataColumnPreview {- table_name: string;- column_name: string;- chart_max_rows_errors: boolean;- chart_spec?: JsonString;- chart_code?: string;- error?: string;- summary?: ColumnPreviewSummary;-}--/**- * Message sent from the frontend to the kernel via the websocket.- */-export type OperationMessage =- | {- op: "kernel-ready";- data: {- /**- * The cell names- */- names: string[];- /**- * The cell codes. Will be empty in Read mode.- */- codes: string[];- /**- * The cell IDs- */- cell_ids: CellId[];- /**- * The layout of the notebook- * May be undefined if there is no layout set.- */- layout:- | {- /**- * The type of the layout- */- type: LayoutType;- /**- * The serialized layout- */- data: unknown;- }- | undefined;- /**- * The cell configs.- */- configs: CellConfig[];- /**- * Whether the notebook was resumed from a previous session- */- resumed: boolean;- /**- * UI element values from the previous session.- * If the notebook was not resumed, this will be undefined.- */- ui_values: Record<UIElementId, unknown> | undefined;- /**- * The last executed code- */- last_executed_code: Record<CellId, string | undefined> | undefined;- /**- * The last execution time- */- last_execution_time: Record<CellId, number> | undefined;- /**- * App config- */- app_config: AppConfig;- };- }- | {- op: "completed-run";- }- | {- op: "reload";- }- | {- op: "interrupted";- }- | {- op: "remove-ui-elements";- data: {- /**- * The ID of the cell whose UI elements should be removed- */- cell_id: CellId;- };- }- | {- op: "completion-result";- data: CompletionResultMessage;- }- | {- op: "function-call-result";- data: FunctionCallResultMessage;- }- | {- op: "cell-op";- data: CellMessage;- }- | {- op: "variables";- data: {- variables: Array<{- name: VariableName;- declared_by: CellId[];- used_by: CellId[];- }>;- };- }- | {- op: "variable-values";- data: {- variables: Array<{- name: VariableName;- datatype?: string;- value?: string;- }>;- };- }- | {- op: "datasets";- data: {- tables: DataTable[];- };- }- | {- op: "data-column-preview";- data: DataColumnPreview;- }- | {- op: "query-params-set";- data: {- key: string;- value: string | string[];- };- }- | {- op: "query-params-append";- data: {- key: string;- value: string;- };- }- | {- op: "query-params-delete";- data: {- key: string;- value: string | null;- };- }- | {- op: "query-params-clear";- }- | {- // transient toast / alert- op: "alert";- data: {- title: string;- description: string;- variant?: "danger";- };- }- | {- // permanent alert (requires action)- op: "missing-package-alert";- data: {- kind: "missing";- packages: string[];- isolated: boolean;- };- }- | {- // permanent alert (requires action)- op: "installing-package-alert";- data: {- kind: "installing";- packages: PackageInstallationStatus;- };- }- | {- // permanent notification- op: "banner";- data: {- title: string;- description: string;- variant?: "danger";- action?: "restart";- };- };+import { type components } from "@marimo-team/marimo-api";++export type schemas = components["schemas"];+export type DataType = schemas["DataType"];+export type Banner = OperationMessageData<"banner">;+export type DataTableColumn = schemas["DataTableColumn"];+export type DataTable = schemas["DataTable"];+export type OutputChannel = schemas["CellChannel"];+export type MarimoError = schemas["Error"];+export type OutputMessage = schemas["CellOutput"];+export type CompletionOption = schemas["CompletionResult"]["options"][0];+export type CompletionResultMessage = OperationMessageData<"completion-result">;+export type HumanReadableStatus = schemas["HumanReadableStatus"];+export type FunctionCallResultMessage =+ OperationMessageData<"function-call-result">;+export type PackageInstallationStatus =+ schemas["InstallingPackageAlert"]["packages"];+export type DataColumnPreview = OperationMessageData<"data-column-preview">;++export type OperationMessageType = schemas["MessageOperation"]["name"];+export type OperationMessage = {+ [Type in OperationMessageType]: {+ op: Type;+ data: Omit<Extract<schemas["MessageOperation"], { name: Type }>, "name">;+ };+}[OperationMessageType];++export type CellMessage = OperationMessageData<"cell-op">;++export type OperationMessageData<T extends OperationMessageType> = Omit<+ Extract<schemas["MessageOperation"], { name: T }>,+ "name"+>;diff --git a/frontend/src/core/kernel/queryParamHandlers.ts b/frontend/src/core/kernel/queryParamHandlers.tsindex ec750256c2..25ecc98442 100644--- a/frontend/src/core/kernel/queryParamHandlers.ts+++ b/frontend/src/core/kernel/queryParamHandlers.ts@@ -1,14 +1,15 @@/* Copyright 2024 Marimo. All rights reserved. */-import { OperationMessageData } from "./handlers";++import { OperationMessageData } from "./messages";export const queryParamHandlers = {- append: (data: OperationMessageData<"query-params-append">["data"]) => {+ append: (data: OperationMessageData<"query-params-append">) => {const url = new URL(window.location.href);url.searchParams.append(data.key, data.value);window.history.pushState({}, "", `${url.pathname}${url.search}`);return;},- set: (data: OperationMessageData<"query-params-set">["data"]) => {+ set: (data: OperationMessageData<"query-params-set">) => {const url = new URL(window.location.href);if (Array.isArray(data.value)) {url.searchParams.delete(data.key);@@ -19,7 +20,7 @@ export const queryParamHandlers = {window.history.pushState({}, "", `${url.pathname}${url.search}`);return;},- delete: (data: OperationMessageData<"query-params-delete">["data"]) => {+ delete: (data: OperationMessageData<"query-params-delete">) => {const url = new URL(window.location.href);if (data.value == null) {url.searchParams.delete(data.key);diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 2ecc039fcc..aba6f040f9 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -7,6 +7,15 @@ export type AiCompletionRequest = schemas["AiCompletionRequest"];export type AppMetadata = schemas["AppMetadata"];export type BaseResponse = schemas["BaseResponse"];export type CellConfig = schemas["CellConfig"];+/**+ * The status of a cell.+ *+ * queued: queued by the kernel.+ * running: currently executing.+ * idle: not running.+ * disabled-transitively: disabled because an ancestor was disabled.+ */+export type CellStatus = schemas["CellStatus"];export type CodeCompletionRequest = schemas["CodeCompletionRequest"];export type CreationRequest = schemas["CreationRequest"];export type DeleteRequest = schemas["DeleteRequest"];@@ -49,7 +58,7 @@ export type SaveNotebookRequest = schemas["SaveNotebookRequest"];export type SaveUserConfigurationRequest =schemas["SaveUserConfigurationRequest"];export interface SetCellConfigRequest {- configs: Record<CellId, CellConfig>;+ configs: Record<CellId, Partial<CellConfig>>;}export type SetUIElementValueRequest = schemas["SetUIElementValueRequest"];export type SetUserConfigRequest = schemas["SetUserConfigRequest"];diff --git a/frontend/src/core/saving/useAutoSave.ts b/frontend/src/core/saving/useAutoSave.tsindex 2e73ce96f6..abcc5c55f5 100644--- a/frontend/src/core/saving/useAutoSave.ts+++ b/frontend/src/core/saving/useAutoSave.ts@@ -2,7 +2,7 @@import { useEffect, useRef } from "react";import { ConnectionStatus, WebSocketState } from "../websocket/types";import { UserConfig } from "../config/config-schema";-import { CellConfig } from "../cells/types";+import { CellConfig } from "../network/types";export function useAutoSave(opts: {codes: string[];diff --git a/frontend/src/core/static/types.ts b/frontend/src/core/static/types.tsindex 5cd79af59d..91cc4a5dcc 100644--- a/frontend/src/core/static/types.ts+++ b/frontend/src/core/static/types.ts@@ -2,7 +2,7 @@import { Base64String, DataURLString, JsonString } from "@/utils/json/base64";import { CellId } from "../cells/ids";import { OutputMessage } from "../kernel/messages";-import { CellConfig } from "../cells/types";+import { CellConfig } from "../network/types";export interface StaticNotebookState {cellIds: CellId[];diff --git a/frontend/src/core/static/virtual-file-tracker.ts b/frontend/src/core/static/virtual-file-tracker.tsindex 3e6c3487d0..cd0a39815b 100644--- a/frontend/src/core/static/virtual-file-tracker.ts+++ b/frontend/src/core/static/virtual-file-tracker.ts@@ -27,7 +27,8 @@ export class VirtualFileTracker {}track(message: Pick<CellMessage, "cell_id" | "output">): void {- const { cell_id, output } = message;+ const output = message.output;+ const cell_id = message.cell_id as CellId;if (!output) {return;}diff --git a/frontend/src/core/variables/state.ts b/frontend/src/core/variables/state.tsindex e955815499..5d6039a6c5 100644--- a/frontend/src/core/variables/state.ts+++ b/frontend/src/core/variables/state.ts@@ -38,7 +38,11 @@ const {},setMetadata: (state,- metadata: Array<{ name: VariableName; value?: string; dataType?: string }>,+ metadata: Array<{+ name: VariableName;+ value?: string | null;+ dataType?: string | null;+ }>,) => {const newVariables = { ...state };for (const { name, value, dataType } of metadata) {diff --git a/frontend/src/core/variables/types.ts b/frontend/src/core/variables/types.tsindex a5246a92e3..da3bae3e68 100644--- a/frontend/src/core/variables/types.ts+++ b/frontend/src/core/variables/types.ts@@ -12,11 +12,11 @@ export interface Variable {/*** String representation of the value.*/- value?: string;+ value?: string | null;/*** Type of the value.*/- dataType?: string;+ dataType?: string | null;}export type Variables = Record<VariableName, Variable>;diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex d55f36d016..5d3e7d903c 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -22,7 +22,6 @@ import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";import type { SessionId } from "../kernel/session";import { useBannersActions } from "../errors/state";import { useAlertActions } from "../alerts/state";-import { generateUUID } from "@/utils/uuid";import { createWsUrl } from "./createWsUrl";import { useSetAppConfig } from "../config/config";import {@@ -33,6 +32,9 @@ import {import { queryParamHandlers } from "../kernel/queryParamHandlers";import type { JsonString } from "@/utils/json/base64";import { useDatasetsActions } from "../datasets/state";+import { RequestId } from "../network/DeferredRequestRegistry";+import { VariableName } from "../variables/types";+import { CellId } from "../cells/ids";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -83,10 +85,13 @@ export function useMarimoWebSocket(opts: {return;case "completion-result":- AUTOCOMPLETER.resolve(msg.data.completion_id, msg.data);+ AUTOCOMPLETER.resolve(msg.data.completion_id as RequestId, msg.data);return;case "function-call-result":- FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);+ FUNCTIONS_REGISTRY.resolve(+ msg.data.function_call_id as RequestId,+ msg.data,+ );return;case "cell-op":handleCellOperation(msg.data, handleCellMessage);@@ -95,17 +100,19 @@ export function useMarimoWebSocket(opts: {case "variables":setVariables(msg.data.variables.map((v) => ({- name: v.name,- declaredBy: v.declared_by,- usedBy: v.used_by,+ name: v.name as VariableName,+ declaredBy: v.declared_by as CellId[],+ usedBy: v.used_by as CellId[],})),);- filterDatasetsFromVariables(msg.data.variables.map((v) => v.name));+ filterDatasetsFromVariables(+ msg.data.variables.map((v) => v.name as VariableName),+ );return;case "variable-values":setMetadata(msg.data.variables.map((v) => ({- name: v.name,+ name: v.name as VariableName,dataType: v.datatype,value: v.value,})),@@ -121,10 +128,7 @@ export function useMarimoWebSocket(opts: {});return;case "banner":- addBanner({- ...msg.data,- id: generateUUID(),- });+ addBanner(msg.data);return;case "missing-package-alert":addPackageAlert({@@ -161,6 +165,9 @@ export function useMarimoWebSocket(opts: {addColumnPreview(msg.data);return;+ case "reconnected":+ return;+default:logNever(msg);}diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsxindex 8b57a69a2c..6100f704f5 100644--- a/frontend/src/plugins/core/registerReactComponent.tsx+++ b/frontend/src/plugins/core/registerReactComponent.tsx@@ -168,7 +168,7 @@ function PluginSlotInternal<T>(});if (response.status.code !== "ok") {Logger.error(response.status);- throw new Error(response.status.message);+ throw new Error(response.status.message || "Unknown error");}return prettyParse(output, response.return_value);};diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 21d3ccb5ac..c2eb72ef46 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -50,7 +50,10 @@ const props: CellProps = {updateCellConfig: Logger.log,setStdinResponse: Logger.log,clearSerializedEditorState: Logger.log,- config: {},+ config: {+ hide_code: false,+ disabled: false,+ },userConfig: defaultUserConfig(),};@@ -173,6 +176,7 @@ export const Disabled: Story = {runElapsedTimeMs={20 as Milliseconds}config={{disabled: true,+ hide_code: false,}}output={{channel: "output",@@ -257,6 +261,7 @@ export const DisabledAndStaleStatus: Story = {runElapsedTimeMs={20 as Milliseconds}config={{disabled: true,+ hide_code: false,}}status="disabled-transitively"staleInputs={true}diff --git a/frontend/src/utils/numbers.ts b/frontend/src/utils/numbers.tsindex cd52f9eac9..f5b0913da9 100644--- a/frontend/src/utils/numbers.ts+++ b/frontend/src/utils/numbers.ts@@ -1,7 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */export function prettyNumber(- value: number | string | undefined | null,+ value: number | string | undefined | null | boolean,): string {if (value === undefined || value === null) {return "";@@ -11,6 +11,10 @@ export function prettyNumber(return value;}+ if (typeof value === "boolean") {+ return String(value);+ }+return value.toLocaleString(undefined, {minimumFractionDigits: 0,maximumFractionDigits: 2,diff --git a/frontend/src/utils/typed.ts b/frontend/src/utils/typed.tsindex e9d6a450bc..fe1ac52747 100644--- a/frontend/src/utils/typed.ts+++ b/frontend/src/utils/typed.ts@@ -13,3 +13,5 @@ export type TypedNumber<T> = number & { __type__: T };* It is used to distinguish between different types of strings.*/export type TypedString<T> = string & { __type__: T };++export type Identified<T> = { id: string } & T;diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 19c3a85d81..b777fef7d2 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -1,11 +1,14 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Dict, Type+from typing import Any, Dictimport clickfrom starlette.schemas import SchemaGenerator+import marimo._data.models as data+import marimo._messaging.errors as errors+import marimo._messaging.ops as opsimport marimo._runtime.requests as requestsimport marimo._server.models.completion as completionimport marimo._server.models.export as export@@ -14,21 +17,83 @@ import marimo._server.models.home as homeimport marimo._server.models.models as modelsimport marimo._snippets.snippets as snippetsfrom marimo import __version__-from marimo._ast.cell import CellConfig+from marimo._ast.cell import CellConfig, CellStatusTypefrom marimo._config.config import MarimoConfig+from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.mimetypes import KnownMimeType+from marimo._output.mime import MIME+from marimo._plugins.core.web_component import JSONTypefrom marimo._server.api.router import build_routes-from marimo._utils.dataclass_to_openapi import dataclass_to_openapi_spec+from marimo._utils.dataclass_to_openapi import (+ PythonTypeToOpenAPI,+)def _generate_schema() -> dict[str, Any]:- # dataclass components that we can generate schemas for- COMPONENTS = [+ # dataclass components used in websocket messages+ # these are always snake_case+ MESSAGES = [+ # Base+ MIME,+ CellStatusType,+ KnownMimeType,+ CellChannel,+ data.NonNestedLiteral,+ data.DataType,+ CellConfig,+ MarimoConfig,+ # Errors+ errors.CycleError,+ errors.MultipleDefinitionError,+ errors.DeleteNonlocalError,+ errors.MarimoInterruptionError,+ errors.MarimoAncestorStoppedError,+ errors.MarimoAncestorPreventedError,+ errors.MarimoStrictExecutionError,+ errors.MarimoExceptionRaisedError,+ errors.MarimoSyntaxError,+ errors.UnknownError,+ errors.Error,+ # Outputs+ CellOutput,+ # Data+ data.DataTableColumn,+ data.DataTable,+ data.ColumnSummary,+ # Operations+ ops.CellOp,+ ops.HumanReadableStatus,+ ops.FunctionCallResult,+ ops.RemoveUIElements,+ ops.Interrupted,+ ops.CompletedRun,+ ops.KernelReady,+ ops.CompletionResult,+ ops.Alert,+ ops.MissingPackageAlert,+ ops.InstallingPackageAlert,+ ops.Reconnected,+ ops.Banner,+ ops.Reload,+ ops.VariableDeclaration,+ ops.VariableValue,+ ops.Variables,+ ops.VariableValues,+ ops.Datasets,+ ops.DataColumnPreview,+ ops.QueryParamsSet,+ ops.QueryParamsAppend,+ ops.QueryParamsDelete,+ ops.QueryParamsClear,+ ops.MessageOperation,+ ]++ # dataclass components used in requests/responses+ REQUEST_RESPONSES = [# Sub componentsrequests.AppMetadata,home.MarimoFile,files.FileInfo,- MarimoConfig,- CellConfig,requests.ExecutionRequest,snippets.SnippetSection,snippets.Snippet,@@ -56,7 +121,6 @@ def _generate_schema() -> dict[str, Any]:home.WorkspaceFilesRequest,home.WorkspaceFilesResponse,models.BaseResponse,- models.BaseResponse,models.FormatRequest,models.FormatResponse,models.InstantiateRequest,@@ -85,19 +149,58 @@ def _generate_schema() -> dict[str, Any]:requests.StopRequest,]- dont_camel_case = {MarimoConfig}-- processed_classes: Dict[Type[Any], str] = {}+ processed_classes: Dict[Any, str] = {+ JSONType: "JSONType",+ }+ component_schemas: Dict[str, Any] = {+ # Hand-written schema to avoid circular dependencies+ "JSONType": {+ "oneOf": [+ {"type": "string"},+ {"type": "number"},+ {"type": "object"},+ {"type": "array"},+ {"type": "boolean"},+ {"type": "null"},+ ]+ }+ }+ # We must override the names of some Union Types,+ # otherwise, their __name__ is "Union"+ name_overrides: Dict[Any, str] = {+ JSONType: "JSONType",+ errors.Error: "Error",+ KnownMimeType: "MimeType",+ data.DataType: "DataType",+ data.NonNestedLiteral: "NonNestedLiteral",+ CellStatusType: "CellStatus",+ CellChannel: "CellChannel",+ ops.MessageOperation: "MessageOperation",+ }++ converter = PythonTypeToOpenAPI(+ camel_case=False, name_overrides=name_overrides+ )+ for cls in MESSAGES:+ # Remove self from the list+ # since it may not have been processed yet+ if cls in processed_classes:+ del processed_classes[cls]+ name = name_overrides.get(cls, cls.__name__) # type: ignore[attr-defined]+ component_schemas[name] = converter.convert(cls, processed_classes)+ processed_classes[cls] = name- component_schemas: Dict[str, Any] = {}- for cls in COMPONENTS:+ converter = PythonTypeToOpenAPI(+ camel_case=True, name_overrides=name_overrides+ )+ for cls in REQUEST_RESPONSES:# Remove self from the list# since it may not have been processed yetif cls in processed_classes:del processed_classes[cls]- component_schemas[cls.__name__] = dataclass_to_openapi_spec(- cls, processed_classes, camel_case=cls not in dont_camel_case- )+ name = name_overrides.get(cls, cls.__name__) # type: ignore[attr-defined]+ component_schemas[name] = converter.convert(cls, processed_classes)+ processed_classes[cls] = nameschemas = SchemaGenerator({diff --git a/marimo/_data/models.py b/marimo/_data/models.pyindex bb260c671b..268d844f40 100644--- a/marimo/_data/models.py+++ b/marimo/_data/models.py@@ -67,8 +67,8 @@ class ColumnSummary:mean: Optional[NonNestedLiteral] = Nonemedian: Optional[NonNestedLiteral] = Nonestd: Optional[NonNestedLiteral] = None- true: Optional[NonNestedLiteral] = None- false: Optional[NonNestedLiteral] = None+ true: Optional[int] = None+ false: Optional[int] = Nonep5: Optional[NonNestedLiteral] = Nonep25: Optional[NonNestedLiteral] = None# p50 is the mediandiff --git a/marimo/_messaging/cell_output.py b/marimo/_messaging/cell_output.pyindex d52aa6dc0e..1924124d32 100644--- a/marimo/_messaging/cell_output.py+++ b/marimo/_messaging/cell_output.py@@ -6,7 +6,7 @@ from __future__ import annotationsimport timefrom dataclasses import asdict, dataclass, fieldfrom enum import Enum-from typing import Any, Sequence, Union+from typing import Any, Dict, Sequence, Unionfrom marimo._messaging.errors import Errorfrom marimo._messaging.mimetypes import KnownMimeType@@ -18,6 +18,7 @@ class CellChannel(str, Enum):STDOUT = "stdout"STDERR = "stderr"STDIN = "stdin"+ PDB = "pdb"OUTPUT = "output"MARIMO_ERROR = "marimo-error"MEDIA = "media"@@ -31,7 +32,7 @@ class CellOutput:# descriptive name about the kind of output: e.g., stdout, stderr, ...channel: CellChannelmimetype: KnownMimeType- data: Union[str, Sequence[Error]]+ data: Union[str, Sequence[Error], Dict[str, Any]]timestamp: float = field(default_factory=lambda: time.time())def asdict(self) -> dict[str, Any]:diff --git a/marimo/_messaging/errors.py b/marimo/_messaging/errors.pyindex 5711fc8c4a..5151b775ae 100644--- a/marimo/_messaging/errors.py+++ b/marimo/_messaging/errors.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom dataclasses import dataclass-from typing import Optional, Union+from typing import Literal, Optional, Unionfrom marimo._ast.cell import CellId_tfrom marimo._runtime.dataflow import EdgeWithVar@@ -11,26 +11,26 @@ from marimo._runtime.dataflow import EdgeWithVar@dataclassclass CycleError:edges_with_vars: tuple[EdgeWithVar, ...]- type: str = "cycle"+ type: Literal["cycle"] = "cycle"@dataclassclass MultipleDefinitionError:name: strcells: tuple[CellId_t, ...]- type: str = "multiple-defs"+ type: Literal["multiple-defs"] = "multiple-defs"@dataclassclass DeleteNonlocalError:name: strcells: tuple[CellId_t, ...]- type: str = "delete-nonlocal"+ type: Literal["delete-nonlocal"] = "delete-nonlocal"@dataclassclass MarimoInterruptionError:- type: str = "interruption"+ type: Literal["interruption"] = "interruption"@dataclass@@ -38,14 +38,14 @@ class MarimoAncestorPreventedError:msg: strraising_cell: CellId_tblamed_cell: CellId_t- type: str = "ancestor-prevented"+ type: Literal["ancestor-prevented"] = "ancestor-prevented"@dataclassclass MarimoAncestorStoppedError:msg: strraising_cell: CellId_t- type: str = "ancestor-stopped"+ type: Literal["ancestor-stopped"] = "ancestor-stopped"@dataclass@@ -54,19 +54,19 @@ class MarimoExceptionRaisedError:exception_type: str# None for if raising_cell is the current cellraising_cell: Optional[CellId_t]- type: str = "exception"+ type: Literal["exception"] = "exception"@dataclassclass MarimoSyntaxError:msg: str- type: str = "syntax"+ type: Literal["syntax"] = "syntax"@dataclassclass UnknownError:msg: str- type: str = "unknown"+ type: Literal["unknown"] = "unknown"@dataclass@@ -74,7 +74,7 @@ class MarimoStrictExecutionError:msg: strref: strblamed_cell: CellId_t- type: str = "strict-exception"+ type: Literal["strict-exception"] = "strict-exception"Error = Union[diff --git a/marimo/_messaging/mimetypes.py b/marimo/_messaging/mimetypes.pyindex e9f7d86059..7fbc111906 100644--- a/marimo/_messaging/mimetypes.py+++ b/marimo/_messaging/mimetypes.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+from typing import Literal# It is convenient to write mimetypes as strings,diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 02ee9f4d9c..fd497375a7 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -260,7 +260,7 @@ class CellOp(Op):@dataclass-class HumanReadableStatus(Op):+class HumanReadableStatus:"""Human-readable status."""code: Literal["ok", "error"]diff --git a/marimo/_output/mime.py b/marimo/_output/mime.pyindex 45d312f12d..6cf1a69402 100644--- a/marimo/_output/mime.py+++ b/marimo/_output/mime.py@@ -1,11 +1,13 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from dataclasses import dataclassfrom typing import Protocolfrom marimo._messaging.mimetypes import KnownMimeType+@dataclassclass MIME(Protocol):"""Protocol for instantiating objects using marimo's media viewer.diff --git a/marimo/_plugins/core/web_component.py b/marimo/_plugins/core/web_component.pyindex 3bbf4a29bc..f0c51535b4 100644--- a/marimo/_plugins/core/web_component.py+++ b/marimo/_plugins/core/web_component.py@@ -38,7 +38,6 @@ JSONType: TypeAlias = Union[None,]-S = TypeVar("S", bound=JSONType)diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 868d451071..2eb59f5e7a 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -79,8 +79,8 @@ class PolarsTableManagerFactory(TableManagerFactory):return ColumnSummary(total=total,nulls=col.null_count(),- true=col.sum(),- false=total - col.sum(),+ true=cast(int, col.sum()),+ false=cast(int, total - col.sum()),)if col.is_temporal():return ColumnSummary(diff --git a/marimo/_utils/dataclass_to_openapi.py b/marimo/_utils/dataclass_to_openapi.pyindex 2b584e71c2..15105bba26 100644--- a/marimo/_utils/dataclass_to_openapi.py+++ b/marimo/_utils/dataclass_to_openapi.py@@ -2,10 +2,15 @@from __future__ import annotationsimport dataclasses+import datetime+from collections.abc import Mapping, Sequence+from decimal import Decimalfrom enum import Enumfrom typing import (Any,+ ClassVar,Dict,+ ForwardRef,List,Literal,Optional,@@ -17,149 +22,235 @@ from typing import ()from marimo._server.models.base import to_camel_case+from marimo._utils.typing import NotRequired-def _python_type_to_openapi_type(- py_type: Any, processed_classes: Dict[Type[Any], str]-) -> Dict[str, Any]:- """- Convert a Python type to an OpenAPI schema.- """- origin = get_origin(py_type)- if origin is Union:- args = get_args(py_type)- if type(None) in args:- non_none_args = [arg for arg in args if arg is not type(None)]- if len(non_none_args) == 1:+class PythonTypeToOpenAPI:+ def __init__(self, name_overrides: Dict[Any, str], camel_case: bool):+ self.name_overrides = name_overrides+ self.camel_case = camel_case+ self.optional_name_overrides = {+ Optional[arg]: name for arg, name in name_overrides.items()+ }++ def convert(+ self,+ py_type: Any,+ processed_classes: Dict[Any, str],+ ) -> Dict[str, Any]:+ """+ Convert a Python type to an OpenAPI schema.++ Returns:+ Dict[str, Any]: The OpenAPI schema.+ """+ origin = get_origin(py_type)+ optional_name_overrides = self.optional_name_overrides++ if origin is Union:+ args = get_args(py_type)++ if py_type in processed_classes:+ ref = processed_classes[py_type]+ return {"$ref": f"#/components/schemas/{ref}"}+ if py_type in optional_name_overrides:+ ref = optional_name_overrides[py_type]return {- **_python_type_to_openapi_type(- non_none_args[0], processed_classes- ),+ "$ref": f"#/components/schemas/{ref}","nullable": True,}++ # Optional is a Union[None, ...]+ if type(None) in args:+ non_none_args = [arg for arg in args if arg is not type(None)]+ if len(non_none_args) == 1:+ return {+ **self.convert(+ non_none_args[0],+ processed_classes,+ ),+ "nullable": True,+ }+ else:+ return {+ "oneOf": _unique(+ [+ self.convert(+ arg,+ processed_classes,+ )+ for arg in non_none_args+ ]+ ),+ "nullable": True,+ }else:return {- "oneOf": [- _python_type_to_openapi_type(arg, processed_classes)- for arg in non_none_args- ],- "nullable": True,+ "oneOf": _unique(+ [+ self.convert(+ arg,+ processed_classes,+ )+ for arg in args+ ]+ )}- else:+ elif origin in (list, List) or origin is Sequence:+ (item_type,) = get_args(py_type)return {- "oneOf": [- _python_type_to_openapi_type(arg, processed_classes)- for arg in args- ]+ "type": "array",+ "items": self.convert(item_type, processed_classes),}- elif origin in (list, List):- (item_type,) = get_args(py_type)- return {- "type": "array",- "items": _python_type_to_openapi_type(- item_type, processed_classes- ),- }- elif origin in (dict, Dict):- _key_type, value_type = get_args(py_type)- return {- "type": "object",- "additionalProperties": _python_type_to_openapi_type(- value_type, processed_classes- ),- }- elif origin is Literal:- return {"enum": list(get_args(py_type))}- elif origin is tuple:- args = get_args(py_type)- if len(args) == 2 and isinstance(args[1], type(Ellipsis)):+ elif origin in (dict, Dict) or origin is Mapping:+ _key_type, value_type = get_args(py_type)return {- "type": "array",- "items": _python_type_to_openapi_type(- args[0], processed_classes+ "type": "object",+ "additionalProperties": self.convert(+ value_type, processed_classes),}+ elif origin is Literal:+ if py_type in processed_classes:+ ref = processed_classes[py_type]+ return {"$ref": f"#/components/schemas/{ref}"}+ return {"enum": list(get_args(py_type)), "type": "string"}+ elif origin is NotRequired:+ return self.convert(+ get_args(py_type)[0],+ processed_classes,+ )+ elif origin is tuple:+ args = get_args(py_type)+ if len(args) == 2 and isinstance(args[1], type(Ellipsis)):+ return {+ "type": "array",+ "items": self.convert(args[0], processed_classes),+ }+ else:+ return {+ "type": "array",+ "prefixItems": [+ self.convert(arg, processed_classes) for arg in args+ ],+ }+ elif dataclasses.is_dataclass(py_type):+ return self.convert_dataclass(py_type, processed_classes)+ elif py_type is Any:+ return {}+ elif py_type is object:+ return {"type": "object", "additionalProperties": True}+ elif py_type is str:+ return {"type": "string"}+ elif py_type is int:+ return {"type": "integer"}+ elif py_type is float:+ return {"type": "number"}+ elif py_type is bool:+ return {"type": "boolean"}+ elif py_type is Decimal:+ return {"type": "number"}+ elif py_type is bytes:+ return {"type": "string", "format": "byte"}+ elif py_type is datetime.date:+ return {"type": "string", "format": "date"}+ elif py_type is datetime.time:+ return {"type": "string", "format": "time"}+ elif py_type is datetime.datetime:+ return {"type": "string", "format": "date-time"}+ elif py_type is datetime.timedelta:+ return {"type": "string", "format": "duration"}+ elif py_type is None:+ return {"type": "null"}+ elif isinstance(py_type, type) and issubclass(py_type, Enum):+ if py_type in processed_classes:+ ref = processed_classes[py_type]+ return {"$ref": f"#/components/schemas/{ref}"}+ return {"type": "string", "enum": [e.value for e in py_type]}+ elif isinstance(py_type, ForwardRef):+ return {"$ref": f"#/components/schemas/{py_type.__forward_arg__}"}else:- return {- "type": "array",- "prefixItems": [- _python_type_to_openapi_type(arg, processed_classes)- for arg in args- ],- }- elif dataclasses.is_dataclass(py_type):- return dataclass_to_openapi_spec(py_type, processed_classes)- elif py_type is Any:- return {}- elif py_type is object:- return {"type": "object", "additionalProperties": True}- elif py_type is str:- return {"type": "string"}- elif py_type is int:- return {"type": "integer"}- elif py_type is float:- return {"type": "number"}- elif py_type is bool:- return {"type": "boolean"}- elif isinstance(py_type, type) and issubclass(py_type, Enum):- return {"type": "string", "enum": [e.value for e in py_type]}- else:- raise ValueError(f"Unsupported type: {py_type}")---def dataclass_to_openapi_spec(- cls: Type[Any],- processed_classes: Optional[Dict[Type[Any], str]] = None,- camel_case: bool = False,-) -> Dict[str, Any]:- """Convert a dataclass to an OpenAPI schema.-- Args:- cls (Type[Any]): The dataclass to convert.-- Raises:- ValueError: If cls is not a dataclass.-- Returns:- Dict[str, Any]: The OpenAPI schema.- """- if processed_classes is None:- processed_classes = {}-- if not dataclasses.is_dataclass(cls):- raise ValueError(f"{cls} is not a dataclass")-- if cls in processed_classes:- return {"$ref": f"#/components/schemas/{processed_classes[cls]}"}-- schema_name = cls.__name__- processed_classes[cls] = schema_name-- fields: tuple[dataclasses.Field[Any], ...] = dataclasses.fields(cls)- properties: Dict[str, Dict[str, Any]] = {}- required: List[str] = []-- for field in fields:- field_name = to_camel_case(field.name) if camel_case else field.name- field_type = get_type_hints(cls)[field.name]- properties[field_name] = _python_type_to_openapi_type(- field_type, processed_classes- )- if (- field.default is dataclasses.MISSING- and field.default_factory is dataclasses.MISSING- and not _is_optional(field_type)- ):- required.append(field_name)-- schema: Dict[str, Any] = {- "type": "object",- "properties": properties,- }- if required:- schema["required"] = required-- return schema+ raise ValueError(+ f"Unsupported type: py_type={py_type}, origin={origin}"+ )++ def convert_dataclass(+ self,+ cls: Type[Any],+ processed_classes: Dict[Any, str],+ ) -> Dict[str, Any]:+ """Convert a dataclass to an OpenAPI schema.++ Args:+ cls (Type[Any]): The dataclass to convert.++ Raises:+ ValueError: If cls is not a dataclass.++ Returns:+ Dict[str, Any]: The OpenAPI schema.+ """+ if not dataclasses.is_dataclass(cls):+ raise ValueError(f"{cls} is not a dataclass")++ if cls in processed_classes:+ return {"$ref": f"#/components/schemas/{processed_classes[cls]}"}++ schema_name = self.name_overrides.get(cls, cls.__name__)+ processed_classes[cls] = schema_name++ type_hints = get_type_hints(cls)+ fields: tuple[dataclasses.Field[Any], ...] = dataclasses.fields(cls)+ properties: Dict[str, Dict[str, Any]] = {}+ required: List[str] = []++ for field in fields:+ cased_field_name = (+ to_camel_case(field.name) if self.camel_case else field.name+ )+ field_type = type_hints[field.name]+ properties[cased_field_name] = self.convert(+ field_type, processed_classes+ )+ if not _is_optional(field_type):+ required.append(cased_field_name)++ # Handle ClassVar that might be initialized already+ for field_name, type_hint in type_hints.items():+ cased_field_name = (+ to_camel_case(field_name) if self.camel_case else field_name+ )+ if get_origin(type_hint) is ClassVar:+ # Literal type+ value = getattr(cls, field_name)+ properties[cased_field_name] = {+ "type": "string",+ "enum": [value] if isinstance(value, str) else value,+ }+ required.append(cased_field_name)++ schema: Dict[str, Any] = {+ "type": "object",+ "properties": properties,+ }+ if required:+ schema["required"] = required++ return schema+++def _unique(items: list[Any]) -> list[Any]:+ # Unique dictionaries+ seen: set[str] = set()+ result: list[Any] = []+ for item in items:+ if isinstance(item, dict):+ key = str(item)+ if key in seen:+ continue+ seen.add(key)+ result.append(item)+ return resultdef _is_optional(field: dataclasses.Field[Any]) -> bool:diff --git a/marimo/_utils/typing.py b/marimo/_utils/typing.pynew file mode 100644index 0000000000..3b4497d722--- /dev/null+++ b/marimo/_utils/typing.py@@ -0,0 +1,11 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import sys++if sys.version_info < (3, 11):+ from typing_extensions import NotRequired as _NotRequired+else:+ from typing import NotRequired as _NotRequired++NotRequired = _NotRequireddiff --git a/openapi/api.yaml b/openapi/api.yamlindex d0528dd327..4a7ec20800 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -13,6 +13,26 @@ components:- includeOtherCode- codetype: object+ Alert:+ properties:+ description:+ type: string+ name:+ enum:+ - alert+ type: string+ title:+ type: string+ variant:+ enum:+ - danger+ nullable: true+ type: string+ required:+ - title+ - description+ - name+ type: objectAppMetadata:properties:cliArgs:@@ -45,6 +65,31 @@ components:- queryParams- cliArgstype: object+ Banner:+ properties:+ action:+ enum:+ - restart+ nullable: true+ type: string+ description:+ type: string+ name:+ enum:+ - banner+ type: string+ title:+ type: string+ variant:+ enum:+ - danger+ nullable: true+ type: string+ required:+ - title+ - description+ - name+ type: objectBaseResponse:properties:success:@@ -52,13 +97,86 @@ components:required:- successtype: object+ CellChannel:+ enum:+ - stdout+ - stderr+ - stdin+ - pdb+ - output+ - marimo-error+ - media+ type: stringCellConfig:properties:disabled:type: boolean- hideCode:+ hide_code:type: boolean+ required:+ - disabled+ - hide_codetype: object+ CellOp:+ properties:+ cell_id:+ type: string+ console:+ nullable: true+ oneOf:+ - $ref: '#/components/schemas/CellOutput'+ - items:+ $ref: '#/components/schemas/CellOutput'+ type: array+ name:+ enum:+ - cell-op+ type: string+ output:+ $ref: '#/components/schemas/CellOutput'+ nullable: true+ stale_inputs:+ nullable: true+ type: boolean+ status:+ $ref: '#/components/schemas/CellStatus'+ nullable: true+ timestamp:+ type: number+ required:+ - cell_id+ - timestamp+ - name+ type: object+ CellOutput:+ properties:+ channel:+ $ref: '#/components/schemas/CellChannel'+ data:+ oneOf:+ - type: string+ - items:+ $ref: '#/components/schemas/Error'+ type: array+ - additionalProperties: {}+ type: object+ mimetype:+ $ref: '#/components/schemas/MimeType'+ timestamp:+ type: number+ required:+ - channel+ - mimetype+ - data+ - timestamp+ type: object+ CellStatus:+ enum:+ - idle+ - queued+ - running+ - disabled-transitively+ type: stringCodeCompletionRequest:properties:cellId:@@ -72,6 +190,91 @@ components:- document- cellIdtype: object+ ColumnSummary:+ properties:+ 'false':+ nullable: true+ type: integer+ max:+ $ref: '#/components/schemas/NonNestedLiteral'+ nullable: true+ mean:+ $ref: '#/components/schemas/NonNestedLiteral'+ nullable: true+ median:+ $ref: '#/components/schemas/NonNestedLiteral'+ nullable: true+ min:+ $ref: '#/components/schemas/NonNestedLiteral'+ nullable: true+ nulls:+ nullable: true+ type: integer+ p25:+ $ref: '#/components/schemas/NonNestedLiteral'+ nullable: true+ p5:+ $ref: '#/components/schemas/NonNestedLiteral'+ nullable: true+ p75:+ $ref: '#/components/schemas/NonNestedLiteral'+ nullable: true+ p95:+ $ref: '#/components/schemas/NonNestedLiteral'+ nullable: true+ std:+ $ref: '#/components/schemas/NonNestedLiteral'+ nullable: true+ total:+ nullable: true+ type: integer+ 'true':+ nullable: true+ type: integer+ unique:+ nullable: true+ type: integer+ type: object+ CompletedRun:+ properties:+ name:+ enum:+ - completed-run+ type: string+ required:+ - name+ type: object+ CompletionResult:+ properties:+ completion_id:+ type: string+ name:+ enum:+ - completion-result+ type: string+ options:+ items:+ properties:+ completion_info:+ nullable: true+ type: string+ name:+ type: string+ type:+ type: string+ required:+ - name+ - type+ type: object+ type: array+ prefix_length:+ type: integer+ required:+ - completion_id+ - prefix_length+ - options+ - name+ type: objectCreationRequest:properties:executionRequests:@@ -84,6 +287,130 @@ components:- executionRequests- setUiElementValueRequesttype: object+ CycleError:+ properties:+ edges_with_vars:+ items:+ prefixItems:+ - type: string+ - items:+ type: string+ type: array+ - type: string+ type: array+ type: array+ type:+ enum:+ - cycle+ type: string+ required:+ - edges_with_vars+ - type+ type: object+ DataColumnPreview:+ properties:+ chart_code:+ nullable: true+ type: string+ chart_max_rows_errors:+ type: boolean+ chart_spec:+ nullable: true+ type: string+ column_name:+ type: string+ error:+ nullable: true+ type: string+ name:+ enum:+ - data-column-preview+ type: string+ summary:+ $ref: '#/components/schemas/ColumnSummary'+ nullable: true+ table_name:+ type: string+ required:+ - table_name+ - column_name+ - chart_max_rows_errors+ - name+ type: object+ DataTable:+ properties:+ columns:+ items:+ $ref: '#/components/schemas/DataTableColumn'+ type: array+ name:+ type: string+ num_columns:+ nullable: true+ type: integer+ num_rows:+ nullable: true+ type: integer+ source:+ type: string+ variable_name:+ nullable: true+ type: string+ required:+ - source+ - name+ - columns+ type: object+ DataTableColumn:+ properties:+ name:+ type: string+ type:+ $ref: '#/components/schemas/DataType'+ required:+ - name+ - type+ type: object+ DataType:+ enum:+ - string+ - boolean+ - integer+ - number+ - date+ - unknown+ type: string+ Datasets:+ properties:+ name:+ enum:+ - datasets+ type: string+ tables:+ items:+ $ref: '#/components/schemas/DataTable'+ type: array+ required:+ - tables+ - name+ type: object+ DeleteNonlocalError:+ properties:+ cells:+ items:+ type: string+ type: array+ name:+ type: string+ type:+ enum:+ - delete-nonlocal+ type: string+ required:+ - name+ - cells+ - type+ type: objectDeleteRequest:properties:cellId:@@ -91,6 +418,18 @@ components:required:- cellIdtype: object+ Error:+ oneOf:+ - $ref: '#/components/schemas/CycleError'+ - $ref: '#/components/schemas/MultipleDefinitionError'+ - $ref: '#/components/schemas/DeleteNonlocalError'+ - $ref: '#/components/schemas/MarimoAncestorStoppedError'+ - $ref: '#/components/schemas/MarimoAncestorPreventedError'+ - $ref: '#/components/schemas/MarimoExceptionRaisedError'+ - $ref: '#/components/schemas/MarimoStrictExecutionError'+ - $ref: '#/components/schemas/MarimoInterruptionError'+ - $ref: '#/components/schemas/MarimoSyntaxError'+ - $ref: '#/components/schemas/UnknownError'ExecuteMultipleRequest:properties:cellIds:@@ -241,6 +580,7 @@ components:- name- isDirectory- isMarimoFile+ - childrentype: objectFileListRequest:properties:@@ -344,6 +684,39 @@ components:- functionName- argstype: object+ FunctionCallResult:+ properties:+ function_call_id:+ type: string+ name:+ enum:+ - function-call-result+ type: string+ return_value:+ $ref: '#/components/schemas/JSONType'+ status:+ $ref: '#/components/schemas/HumanReadableStatus'+ required:+ - function_call_id+ - status+ - name+ type: object+ HumanReadableStatus:+ properties:+ code:+ enum:+ - ok+ - error+ type: string+ message:+ nullable: true+ type: string+ title:+ nullable: true+ type: string+ required:+ - code+ type: objectInstallMissingPackagesRequest:properties:manager:@@ -351,6 +724,25 @@ components:required:- managertype: object+ InstallingPackageAlert:+ properties:+ name:+ enum:+ - installing-package-alert+ type: string+ packages:+ additionalProperties:+ enum:+ - queued+ - installing+ - installed+ - failed+ type: string+ type: object+ required:+ - packages+ - name+ type: objectInstantiateRequest:properties:objectIds:@@ -364,6 +756,149 @@ components:- objectIds- valuestype: object+ Interrupted:+ properties:+ name:+ enum:+ - interrupted+ type: string+ required:+ - name+ type: object+ JSONType:+ oneOf:+ - type: string+ - type: number+ - type: object+ - type: array+ - type: boolean+ - type: 'null'+ KernelReady:+ properties:+ app_config:+ properties:+ app_title:+ nullable: true+ type: string+ layout_file:+ nullable: true+ type: string+ width:+ enum:+ - normal+ - compact+ - medium+ - full+ type: string+ required:+ - width+ type: object+ cell_ids:+ items:+ type: string+ type: array+ codes:+ items:+ type: string+ type: array+ configs:+ items:+ $ref: '#/components/schemas/CellConfig'+ type: array+ last_executed_code:+ additionalProperties:+ type: string+ nullable: true+ type: object+ last_execution_time:+ additionalProperties:+ type: number+ nullable: true+ type: object+ layout:+ nullable: true+ properties:+ data:+ additionalProperties: {}+ type: object+ type:+ type: string+ required:+ - type+ - data+ type: object+ name:+ enum:+ - kernel-ready+ type: string+ names:+ items:+ type: string+ type: array+ resumed:+ type: boolean+ ui_values:+ additionalProperties:+ nullable: true+ oneOf:+ - additionalProperties:+ $ref: '#/components/schemas/JSONType'+ type: object+ - items:+ $ref: '#/components/schemas/JSONType'+ type: array+ - type: string+ - type: integer+ - type: number+ - type: boolean+ - $ref: '#/components/schemas/MIME'+ nullable: true+ type: object+ required:+ - cell_ids+ - codes+ - names+ - configs+ - resumed+ - app_config+ - name+ type: object+ MIME:+ properties: {}+ type: object+ MarimoAncestorPreventedError:+ properties:+ blamed_cell:+ type: string+ msg:+ type: string+ raising_cell:+ type: string+ type:+ enum:+ - ancestor-prevented+ type: string+ required:+ - msg+ - raising_cell+ - blamed_cell+ - type+ type: object+ MarimoAncestorStoppedError:+ properties:+ msg:+ type: string+ raising_cell:+ type: string+ type:+ enum:+ - ancestor-stopped+ type: string+ required:+ - msg+ - raising_cell+ - type+ type: objectMarimoConfig:properties:ai:@@ -400,6 +935,7 @@ components:enum:- above- below+ type: stringcode_editor_font_size:type: integerdefault_width:@@ -408,11 +944,13 @@ components:- compact- medium- full+ type: stringtheme:enum:- light- dark- system+ type: stringrequired:- theme- code_editor_font_size@@ -439,6 +977,7 @@ components:enum:- default- vim+ type: stringrequired:- preset- overrides@@ -452,6 +991,7 @@ components:- uv- poetry- pixi+ type: stringrequired:- managertype: object@@ -464,10 +1004,12 @@ components:- 'off'- lazy- autorun+ type: stringon_cell_change:enum:- lazy- autorun+ type: stringrequired:- auto_instantiate- auto_reload@@ -479,6 +1021,7 @@ components:enum:- 'off'- after_delay+ type: stringautosave_delay:type: integerformat_on_save:@@ -494,6 +1037,7 @@ components:oneOf:- enum:- default+ type: string- type: stringfollow_symlink:type: boolean@@ -513,6 +1057,24 @@ components:- ai- experimentaltype: object+ MarimoExceptionRaisedError:+ properties:+ exception_type:+ type: string+ msg:+ type: string+ raising_cell:+ nullable: true+ type: string+ type:+ enum:+ - exception+ type: string+ required:+ - msg+ - exception_type+ - type+ type: objectMarimoFile:properties:initializationId:@@ -532,6 +1094,136 @@ components:- path- lastModifiedtype: object+ MarimoInterruptionError:+ properties:+ type:+ enum:+ - interruption+ type: string+ required:+ - type+ type: object+ MarimoStrictExecutionError:+ properties:+ blamed_cell:+ type: string+ msg:+ type: string+ ref:+ type: string+ type:+ enum:+ - strict-exception+ type: string+ required:+ - msg+ - ref+ - blamed_cell+ - type+ type: object+ MarimoSyntaxError:+ properties:+ msg:+ type: string+ type:+ enum:+ - syntax+ type: string+ required:+ - msg+ - type+ type: object+ MessageOperation:+ oneOf:+ - $ref: '#/components/schemas/CellOp'+ - $ref: '#/components/schemas/FunctionCallResult'+ - $ref: '#/components/schemas/RemoveUIElements'+ - $ref: '#/components/schemas/Reload'+ - $ref: '#/components/schemas/Reconnected'+ - $ref: '#/components/schemas/Interrupted'+ - $ref: '#/components/schemas/CompletedRun'+ - $ref: '#/components/schemas/KernelReady'+ - $ref: '#/components/schemas/CompletionResult'+ - $ref: '#/components/schemas/Alert'+ - $ref: '#/components/schemas/Banner'+ - $ref: '#/components/schemas/MissingPackageAlert'+ - $ref: '#/components/schemas/InstallingPackageAlert'+ - $ref: '#/components/schemas/Variables'+ - $ref: '#/components/schemas/VariableValues'+ - $ref: '#/components/schemas/QueryParamsSet'+ - $ref: '#/components/schemas/QueryParamsAppend'+ - $ref: '#/components/schemas/QueryParamsDelete'+ - $ref: '#/components/schemas/QueryParamsClear'+ - $ref: '#/components/schemas/Datasets'+ - $ref: '#/components/schemas/DataColumnPreview'+ MimeType:+ enum:+ - application/json+ - application/vnd.marimo+error+ - image/png+ - image/svg+xml+ - image/tiff+ - image/avif+ - image/bmp+ - image/gif+ - image/jpeg+ - video/mp4+ - video/mpeg+ - text/html+ - text/plain+ - text/markdown+ - text/csv+ type: string+ MissingPackageAlert:+ properties:+ isolated:+ type: boolean+ name:+ enum:+ - missing-package-alert+ type: string+ packages:+ items:+ type: string+ type: array+ required:+ - packages+ - isolated+ - name+ type: object+ MultipleDefinitionError:+ properties:+ cells:+ items:+ type: string+ type: array+ name:+ type: string+ type:+ enum:+ - multiple-defs+ type: string+ required:+ - name+ - cells+ - type+ type: object+ NonNestedLiteral:+ oneOf:+ - type: integer+ - type: number+ - format: date+ type: string+ - format: time+ type: string+ - format: date-time+ type: string+ - format: duration+ type: string+ - type: string+ - type: boolean+ - format: byte+ type: stringOpenFileRequest:properties:path:@@ -552,6 +1244,64 @@ components:- tableName- columnNametype: object+ QueryParamsAppend:+ properties:+ key:+ type: string+ name:+ enum:+ - query-params-append+ type: string+ value:+ type: string+ required:+ - key+ - value+ - name+ type: object+ QueryParamsClear:+ properties:+ name:+ enum:+ - query-params-clear+ type: string+ required:+ - name+ type: object+ QueryParamsDelete:+ properties:+ key:+ type: string+ name:+ enum:+ - query-params-delete+ type: string+ value:+ nullable: true+ type: string+ required:+ - key+ - name+ type: object+ QueryParamsSet:+ properties:+ key:+ type: string+ name:+ enum:+ - query-params-set+ type: string+ value:+ oneOf:+ - type: string+ - items:+ type: string+ type: array+ required:+ - key+ - value+ - name+ type: objectReadCodeResponse:properties:contents:@@ -568,6 +1318,36 @@ components:required:- filestype: object+ Reconnected:+ properties:+ name:+ enum:+ - reconnected+ type: string+ required:+ - name+ type: object+ Reload:+ properties:+ name:+ enum:+ - reload+ type: string+ required:+ - name+ type: object+ RemoveUIElements:+ properties:+ cell_id:+ type: string+ name:+ enum:+ - remove-ui-elements+ type: string+ required:+ - cell_id+ - name+ type: objectRenameFileRequest:properties:filename:@@ -659,6 +1439,7 @@ components:required:- objectIds- values+ - tokentype: objectSetUserConfigRequest:properties:@@ -722,6 +1503,20 @@ components:properties:success:type: boolean+ required:+ - success+ type: object+ UnknownError:+ properties:+ msg:+ type: string+ type:+ enum:+ - unknown+ type: string+ required:+ - msg+ - typetype: objectUpdateComponentValuesRequest:properties:@@ -736,10 +1531,70 @@ components:- objectIds- valuestype: object+ VariableDeclaration:+ properties:+ declared_by:+ items:+ type: string+ type: array+ name:+ type: string+ used_by:+ items:+ type: string+ type: array+ required:+ - name+ - declared_by+ - used_by+ type: object+ VariableValue:+ properties:+ datatype:+ nullable: true+ type: string+ name:+ type: string+ value:+ nullable: true+ type: string+ required:+ - name+ type: object+ VariableValues:+ properties:+ name:+ enum:+ - variable-values+ type: string+ variables:+ items:+ $ref: '#/components/schemas/VariableValue'+ type: array+ required:+ - variables+ - name+ type: object+ Variables:+ properties:+ name:+ enum:+ - variables+ type: string+ variables:+ items:+ $ref: '#/components/schemas/VariableDeclaration'+ type: array+ required:+ - variables+ - name+ type: objectWorkspaceFilesRequest:properties:includeMarkdown:type: boolean+ required:+ - includeMarkdowntype: objectWorkspaceFilesResponse:properties:@@ -752,7 +1607,7 @@ components:type: objectinfo:title: marimo API- version: 0.6.17+ version: 0.6.19openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 520abb9594..75b6f0fdca 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -3,6 +3,17 @@* Do not make direct changes to the file.*/+/** OneOf type helpers */+type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };+type XOR<T, U> = T | U extends object+ ? (Without<T, U> & U) | (Without<U, T> & T)+ : T | U;+type OneOf<T extends any[]> = T extends [infer Only]+ ? Only+ : T extends [infer A, infer B, ...infer Rest]+ ? OneOf<[XOR<A, B>, ...Rest]>+ : never;+export interface paths {"/@file/{filename_and_length}": {get: {@@ -704,6 +715,14 @@ export interface components {includeOtherCode: string;prompt: string;};+ Alert: {+ description: string;+ /** @enum {string} */+ name: "alert";+ title: string;+ /** @enum {string|null} */+ variant?: "danger" | null;+ };AppMetadata: {cliArgs: {[key: string]:@@ -717,25 +736,156 @@ export interface components {[key: string]: string | string[];};};+ Banner: {+ /** @enum {string|null} */+ action?: "restart" | null;+ description: string;+ /** @enum {string} */+ name: "banner";+ title: string;+ /** @enum {string|null} */+ variant?: "danger" | null;+ };BaseResponse: {success: boolean;};+ /** @enum {string} */+ CellChannel:+ | "stdout"+ | "stderr"+ | "stdin"+ | "pdb"+ | "output"+ | "marimo-error"+ | "media";CellConfig: {- disabled?: boolean;- hideCode?: boolean;- };+ disabled: boolean;+ hide_code: boolean;+ };+ CellOp: {+ cell_id: string;+ console?:+ | components["schemas"]["CellOutput"]+ | components["schemas"]["CellOutput"][]+ | null;+ /** @enum {string} */+ name: "cell-op";+ output?: components["schemas"]["CellOutput"];+ stale_inputs?: boolean | null;+ status?: components["schemas"]["CellStatus"];+ timestamp: number;+ };+ CellOutput: {+ channel: components["schemas"]["CellChannel"];+ data: OneOf<+ [+ string,+ components["schemas"]["Error"][],+ {+ [key: string]: unknown;+ },+ ]+ >;+ mimetype: components["schemas"]["MimeType"];+ timestamp: number;+ };+ /** @enum {string} */+ CellStatus: "idle" | "queued" | "running" | "disabled-transitively";CodeCompletionRequest: {cellId: string;document: string;id: string;};+ ColumnSummary: {+ false?: number | null;+ max?: components["schemas"]["NonNestedLiteral"];+ mean?: components["schemas"]["NonNestedLiteral"];+ median?: components["schemas"]["NonNestedLiteral"];+ min?: components["schemas"]["NonNestedLiteral"];+ nulls?: number | null;+ p25?: components["schemas"]["NonNestedLiteral"];+ p5?: components["schemas"]["NonNestedLiteral"];+ p75?: components["schemas"]["NonNestedLiteral"];+ p95?: components["schemas"]["NonNestedLiteral"];+ std?: components["schemas"]["NonNestedLiteral"];+ total?: number | null;+ true?: number | null;+ unique?: number | null;+ };+ CompletedRun: {+ /** @enum {string} */+ name: "completed-run";+ };+ CompletionResult: {+ completion_id: string;+ /** @enum {string} */+ name: "completion-result";+ options: {+ completion_info?: string | null;+ name: string;+ type: string;+ }[];+ prefix_length: number;+ };CreationRequest: {executionRequests: components["schemas"]["ExecutionRequest"][];setUiElementValueRequest: components["schemas"]["SetUIElementValueRequest"];};+ CycleError: {+ edges_with_vars: [string, string[], string][];+ /** @enum {string} */+ type: "cycle";+ };+ DataColumnPreview: {+ chart_code?: string | null;+ chart_max_rows_errors: boolean;+ chart_spec?: string | null;+ column_name: string;+ error?: string | null;+ /** @enum {string} */+ name: "data-column-preview";+ summary?: components["schemas"]["ColumnSummary"];+ table_name: string;+ };+ DataTable: {+ columns: components["schemas"]["DataTableColumn"][];+ name: string;+ num_columns?: number | null;+ num_rows?: number | null;+ source: string;+ variable_name?: string | null;+ };+ DataTableColumn: {+ name: string;+ type: components["schemas"]["DataType"];+ };+ /** @enum {string} */+ DataType: "string" | "boolean" | "integer" | "number" | "date" | "unknown";+ Datasets: {+ /** @enum {string} */+ name: "datasets";+ tables: components["schemas"]["DataTable"][];+ };+ DeleteNonlocalError: {+ cells: string[];+ name: string;+ /** @enum {string} */+ type: "delete-nonlocal";+ };DeleteRequest: {cellId: string;};+ Error:+ | components["schemas"]["CycleError"]+ | components["schemas"]["MultipleDefinitionError"]+ | components["schemas"]["DeleteNonlocalError"]+ | components["schemas"]["MarimoAncestorStoppedError"]+ | components["schemas"]["MarimoAncestorPreventedError"]+ | components["schemas"]["MarimoExceptionRaisedError"]+ | components["schemas"]["MarimoStrictExecutionError"]+ | components["schemas"]["MarimoInterruptionError"]+ | components["schemas"]["MarimoSyntaxError"]+ | components["schemas"]["UnknownError"];ExecuteMultipleRequest: {cellIds: string[];codes: string[];@@ -784,7 +934,7 @@ export interface components {mimeType?: string | null;};FileInfo: {- children?: components["schemas"]["FileInfo"][];+ children: components["schemas"]["FileInfo"][];id: string;isDirectory: boolean;isMarimoFile: boolean;@@ -836,13 +986,97 @@ export interface components {functionName: string;namespace: string;};+ FunctionCallResult: {+ function_call_id: string;+ /** @enum {string} */+ name: "function-call-result";+ return_value: components["schemas"]["JSONType"];+ status: components["schemas"]["HumanReadableStatus"];+ };+ HumanReadableStatus: {+ /** @enum {string} */+ code: "ok" | "error";+ message?: string | null;+ title?: string | null;+ };InstallMissingPackagesRequest: {manager: string;};+ InstallingPackageAlert: {+ /** @enum {string} */+ name: "installing-package-alert";+ packages: {+ [key: string]: "queued" | "installing" | "installed" | "failed";+ };+ };InstantiateRequest: {objectIds: string[];values: unknown[];};+ Interrupted: {+ /** @enum {string} */+ name: "interrupted";+ };+ JSONType:+ | string+ | number+ | Record<string, never>+ | unknown[]+ | boolean+ | null;+ KernelReady: {+ app_config: {+ app_title?: string | null;+ layout_file?: string | null;+ /** @enum {string} */+ width: "normal" | "compact" | "medium" | "full";+ };+ cell_ids: string[];+ codes: string[];+ configs: components["schemas"]["CellConfig"][];+ last_executed_code?: {+ [key: string]: string;+ } | null;+ last_execution_time?: {+ [key: string]: number;+ } | null;+ layout?: {+ data: {+ [key: string]: unknown;+ };+ type: string;+ } | null;+ /** @enum {string} */+ name: "kernel-ready";+ names: string[];+ resumed: boolean;+ ui_values?: {+ [key: string]:+ | {+ [key: string]: components["schemas"]["JSONType"];+ }+ | components["schemas"]["JSONType"][]+ | string+ | number+ | boolean+ | components["schemas"]["MIME"]+ | null;+ } | null;+ };+ MIME: Record<string, never>;+ MarimoAncestorPreventedError: {+ blamed_cell: string;+ msg: string;+ raising_cell: string;+ /** @enum {string} */+ type: "ancestor-prevented";+ };+ MarimoAncestorStoppedError: {+ msg: string;+ raising_cell: string;+ /** @enum {string} */+ type: "ancestor-stopped";+ };MarimoConfig: {ai: {open_ai: {@@ -856,12 +1090,12 @@ export interface components {copilot: boolean;};display: {- /** @enum {unknown} */+ /** @enum {string} */cell_output: "above" | "below";code_editor_font_size: number;- /** @enum {unknown} */+ /** @enum {string} */default_width: "normal" | "compact" | "medium" | "full";- /** @enum {unknown} */+ /** @enum {string} */theme: "light" | "dark" | "system";};experimental: {@@ -874,22 +1108,22 @@ export interface components {overrides: {[key: string]: string;};- /** @enum {unknown} */+ /** @enum {string} */preset: "default" | "vim";};package_management: {- /** @enum {unknown} */+ /** @enum {string} */manager: "pip" | "rye" | "uv" | "poetry" | "pixi";};runtime: {auto_instantiate: boolean;- /** @enum {unknown} */+ /** @enum {string} */auto_reload: "off" | "lazy" | "autorun";- /** @enum {unknown} */+ /** @enum {string} */on_cell_change: "lazy" | "autorun";};save: {- /** @enum {unknown} */+ /** @enum {string} */autosave: "off" | "after_delay";autosave_delay: number;format_on_save: boolean;@@ -899,6 +1133,13 @@ export interface components {follow_symlink: boolean;};};+ MarimoExceptionRaisedError: {+ exception_type: string;+ msg: string;+ raising_cell?: string | null;+ /** @enum {string} */+ type: "exception";+ };MarimoFile: {initializationId?: string | null;lastModified: number;@@ -906,6 +1147,74 @@ export interface components {path: string;sessionId?: string | null;};+ MarimoInterruptionError: {+ /** @enum {string} */+ type: "interruption";+ };+ MarimoStrictExecutionError: {+ blamed_cell: string;+ msg: string;+ ref: string;+ /** @enum {string} */+ type: "strict-exception";+ };+ MarimoSyntaxError: {+ msg: string;+ /** @enum {string} */+ type: "syntax";+ };+ MessageOperation:+ | components["schemas"]["CellOp"]+ | components["schemas"]["FunctionCallResult"]+ | components["schemas"]["RemoveUIElements"]+ | components["schemas"]["Reload"]+ | components["schemas"]["Reconnected"]+ | components["schemas"]["Interrupted"]+ | components["schemas"]["CompletedRun"]+ | components["schemas"]["KernelReady"]+ | components["schemas"]["CompletionResult"]+ | components["schemas"]["Alert"]+ | components["schemas"]["Banner"]+ | components["schemas"]["MissingPackageAlert"]+ | components["schemas"]["InstallingPackageAlert"]+ | components["schemas"]["Variables"]+ | components["schemas"]["VariableValues"]+ | components["schemas"]["QueryParamsSet"]+ | components["schemas"]["QueryParamsAppend"]+ | components["schemas"]["QueryParamsDelete"]+ | components["schemas"]["QueryParamsClear"]+ | components["schemas"]["Datasets"]+ | components["schemas"]["DataColumnPreview"];+ /** @enum {string} */+ MimeType:+ | "application/json"+ | "application/vnd.marimo+error"+ | "image/png"+ | "image/svg+xml"+ | "image/tiff"+ | "image/avif"+ | "image/bmp"+ | "image/gif"+ | "image/jpeg"+ | "video/mp4"+ | "video/mpeg"+ | "text/html"+ | "text/plain"+ | "text/markdown"+ | "text/csv";+ MissingPackageAlert: {+ isolated: boolean;+ /** @enum {string} */+ name: "missing-package-alert";+ packages: string[];+ };+ MultipleDefinitionError: {+ cells: string[];+ name: string;+ /** @enum {string} */+ type: "multiple-defs";+ };+ NonNestedLiteral: number | string | boolean;OpenFileRequest: {path: string;};@@ -914,12 +1223,47 @@ export interface components {source: string;tableName: string;};+ QueryParamsAppend: {+ key: string;+ /** @enum {string} */+ name: "query-params-append";+ value: string;+ };+ QueryParamsClear: {+ /** @enum {string} */+ name: "query-params-clear";+ };+ QueryParamsDelete: {+ key: string;+ /** @enum {string} */+ name: "query-params-delete";+ value?: string | null;+ };+ QueryParamsSet: {+ key: string;+ /** @enum {string} */+ name: "query-params-set";+ value: string | string[];+ };ReadCodeResponse: {contents: string;};RecentFilesResponse: {files: components["schemas"]["MarimoFile"][];};+ Reconnected: {+ /** @enum {string} */+ name: "reconnected";+ };+ Reload: {+ /** @enum {string} */+ name: "reload";+ };+ RemoveUIElements: {+ cell_id: string;+ /** @enum {string} */+ name: "remove-ui-elements";+ };RenameFileRequest: {filename: string;};@@ -954,7 +1298,7 @@ export interface components {};SetUIElementValueRequest: {objectIds: string[];- token?: string;+ token: string;values: unknown[];};SetUserConfigRequest: {@@ -980,14 +1324,39 @@ export interface components {};StopRequest: Record<string, never>;SuccessResponse: {- success?: boolean;+ success: boolean;+ };+ UnknownError: {+ msg: string;+ /** @enum {string} */+ type: "unknown";};UpdateComponentValuesRequest: {objectIds: string[];values: unknown[];};+ VariableDeclaration: {+ declared_by: string[];+ name: string;+ used_by: string[];+ };+ VariableValue: {+ datatype?: string | null;+ name: string;+ value?: string | null;+ };+ VariableValues: {+ /** @enum {string} */+ name: "variable-values";+ variables: components["schemas"]["VariableValue"][];+ };+ Variables: {+ /** @enum {string} */+ name: "variables";+ variables: components["schemas"]["VariableDeclaration"][];+ };WorkspaceFilesRequest: {- includeMarkdown?: boolean;+ includeMarkdown: boolean;};WorkspaceFilesResponse: {files: components["schemas"]["MarimoFile"][];diff --git a/pyproject.toml b/pyproject.tomlindex be9ecb118a..18f32f6ef7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -94,7 +94,7 @@ dev = ["pytest-asyncio~=0.23.4","types-Markdown~=3.6.0.20240316","types-PyYAML~=6.0.12.20240311",- "mypy~=1.7.0",+ "mypy~=1.10.0","ruff~=0.3.6","typos~=1.17.1",# For docsdiff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.pyindex cf95c684a0..302304c36e 100644--- a/tests/_plugins/ui/_impl/test_anywidget.py+++ b/tests/_plugins/ui/_impl/test_anywidget.py@@ -58,7 +58,7 @@ class CounterWidget(anywidget.AnyWidget):base_widget = CounterWidget()are_same = mo.as_html(base_widget).text == mo.as_html(base_widget).text-are_different = mo.as_html(CounterWidget()) != mo.as_html(CounterWidget())+are_different = mo.as_html(CounterWidget()) is not mo.as_html(CounterWidget())as_marimo_element = mo.ui.anywidget(base_widget)""")diff --git a/tests/_utils/test_dataclass_to_openapi.py b/tests/_utils/test_dataclass_to_openapi.pyindex 34e12b38c8..205baa61e6 100644--- a/tests/_utils/test_dataclass_to_openapi.py+++ b/tests/_utils/test_dataclass_to_openapi.py@@ -1,9 +1,11 @@from __future__ import annotationsimport dataclasses-from typing import Any, List, Literal, Optional+from typing import Any, ClassVar, List, Literal, Optional, Union-from marimo._utils.dataclass_to_openapi import dataclass_to_openapi_spec+from marimo._utils.dataclass_to_openapi import (+ PythonTypeToOpenAPI,+)@dataclasses.dataclass@@ -24,7 +26,9 @@ class Person:def test_dataclass_to_openapi() -> None:- openapi_spec = dataclass_to_openapi_spec(Person)+ openapi_spec = PythonTypeToOpenAPI(+ name_overrides={}, camel_case=False+ ).convert(Person, processed_classes={})assert openapi_spec == {"type": "object","properties": {@@ -36,7 +40,7 @@ def test_dataclass_to_openapi() -> None:"street": {"type": "string"},"city": {"type": "string"},"zip_code": {"type": "integer", "nullable": True},- "kind": {"enum": ["home", "work"]},+ "kind": {"enum": ["home", "work"], "type": "string"},},"required": ["street", "city", "kind"],},@@ -48,14 +52,16 @@ def test_dataclass_to_openapi() -> None:def test_dataclass_to_openapi_with_camelcase() -> None:- openapi_spec = dataclass_to_openapi_spec(Address, camel_case=True)+ openapi_spec = PythonTypeToOpenAPI(+ name_overrides={}, camel_case=True+ ).convert(Address, processed_classes={})assert openapi_spec == {"type": "object","properties": {"street": {"type": "string"},"city": {"type": "string"},"zipCode": {"type": "integer", "nullable": True},- "kind": {"enum": ["home", "work"]},+ "kind": {"enum": ["home", "work"], "type": "string"},},"required": ["street", "city", "kind"],}@@ -69,7 +75,9 @@ class Node:def test_recursive_dataclass_to_openapi() -> None:- openapi_spec = dataclass_to_openapi_spec(Node)+ openapi_spec = PythonTypeToOpenAPI(+ name_overrides={}, camel_case=False+ ).convert(Node, processed_classes={})assert openapi_spec == {"type": "object","properties": {@@ -79,3 +87,58 @@ def test_recursive_dataclass_to_openapi() -> None:},"required": ["value"],}+++Colors = Union[Literal["red"], Literal["green"], Literal["blue"]]+++def test_named_union() -> None:+ openapi_spec = PythonTypeToOpenAPI(+ name_overrides={}, camel_case=False+ ).convert(Colors, processed_classes={})+ assert openapi_spec == {+ "oneOf": [+ {"enum": ["red"], "type": "string"},+ {"enum": ["green"], "type": "string"},+ {"enum": ["blue"], "type": "string"},+ ]+ }+++class Theme:+ primary_color: Colors+ secondary_color: Optional[Colors]+++def test_nested_named_union() -> None:+ openapi_spec = PythonTypeToOpenAPI(+ name_overrides={Colors: "colors"}, camel_case=False+ ).convert(Theme, {Colors: "colors"})+ assert openapi_spec == {+ "type": "object",+ "properties": {+ "primary_color": {"$ref": "#/components/schemas/colors"},+ "secondary_color": {+ "$ref": "#/components/schemas/colors",+ "nullable": True,+ },+ },+ "required": ["primary_color"],+ }+++class Dog:+ name: ClassVar[str] = "dog"+++def test_class_var() -> None:+ openapi_spec = PythonTypeToOpenAPI(+ name_overrides={}, camel_case=False+ ).convert(Dog, {})+ assert openapi_spec == {+ "type": "object",+ "properties": {"name": {"type": "string", "enum": ["dog"]}},+ "required": ["name"],+ }