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
experimental: wasm/pyodide support (#780)
Myles Scolnick1b1a9b21dc29
diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.jsindex e0dbb126cb..553a8dd65a 100644--- a/frontend/.eslintrc.js+++ b/frontend/.eslintrc.js@@ -97,6 +97,7 @@ module.exports = {"unicorn/no-keyword-prefix": "off","unicorn/no-useless-undefined": "off","unicorn/prefer-add-event-listener": "off",+ "unicorn/require-post-message-target-origin": "off","unicorn/prefer-at": "off","unicorn/prefer-code-point": "off","unicorn/prefer-module": "off",diff --git a/frontend/e2e-tests/cells.spec.ts b/frontend/e2e-tests/cells.spec.tsindex ab06f4c911..3f677a9938 100644--- a/frontend/e2e-tests/cells.spec.ts+++ b/frontend/e2e-tests/cells.spec.ts@@ -32,7 +32,7 @@ test("keeps re-renders from growing", async ({ page }) => {// unexpectedly, it is a sign that something is causing cells to re-render.// It is also ok to decrease the count if we find a way to reduce the number// of renders.- expect(cellRenderCount).toBe("8");+ expect(cellRenderCount).toBe("4");});/**diff --git a/frontend/package.json b/frontend/package.jsonindex 66c8d1d579..f634c58fb1 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -89,9 +89,11 @@"katex": "^0.16.9","lodash-es": "^4.17.21","lucide-react": "^0.321.0",+ "lz-string": "^1.5.0","mermaid": "^10.7.0","partysocket": "0.0.25","plotly.js": "^2.28.0",+ "pyodide": "^0.25.0","react-arborist": "^3.4.0","react-day-picker": "^8.10.0","react-dropzone": "^14.2.3",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 69c60e7f8c..d8fbe7d2a7 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -236,6 +236,9 @@ dependencies:lucide-react:specifier: ^0.321.0version: 0.321.0([email protected])+ lz-string:+ specifier: ^1.5.0+ version: 1.5.0mermaid:specifier: ^10.7.0version: 10.7.0@@ -245,6 +248,9 @@ dependencies:plotly.js:specifier: ^2.28.0version: 2.28.0([email protected])+ pyodide:+ specifier: ^0.25.0+ version: 0.25.0react-arborist:specifier: ^3.4.0@@ -7708,6 +7714,10 @@ packages:resolution: {integrity: sha512-1ugUSr8BHXRnK23KfuYS+gVMC3LB8QGH9W1iGtDPsNWoQbgtXSExkBu2aDR4epiGWZOjZsj6lDl/N/AqqTC3UA==}dev: true+ resolution: {integrity: sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==}+ dev: false+resolution: {integrity: sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==}engines: {node: '>= 0.6.0'}@@ -12169,7 +12179,6 @@ packages:resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}hasBin: true- dev: trueresolution: {integrity: sha512-oreip9rJZkzvA8Qzk9HFs8fZGF/u7H/gtrE8EN6RjKJ9kh2HlC+yQ2QezifqTZfGyiuAV0dRv5a+y/8gBb1m9w==}@@ -13994,6 +14003,16 @@ packages:- utf-8-validatedev: true+ resolution: {integrity: sha512-RagtX3TfV2M0QAfThG2SMvwE31ikqAFDUXc5/4xhppEoVf4VbL7L0kbKOIdSNg7MbVsHELVxftk66WvT926GpA==}+ dependencies:+ base-64: 1.0.0+ ws: 8.16.0+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate+ dev: false+resolution: {integrity: sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==}engines: {node: '>=0.6'}@@ -17378,7 +17397,6 @@ packages:optional: trueutf-8-validate:optional: true- dev: trueresolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}diff --git a/frontend/public/files/wasm-intro.py b/frontend/public/files/wasm-intro.pynew file mode 100644index 0000000000..8f7ca2c608--- /dev/null+++ b/frontend/public/files/wasm-intro.py@@ -0,0 +1,464 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.2.4"+app = marimo.App()+++def __():+ import marimo as mo++ mo.md("# Welcome to marimo running in WASM! 🌊🍃")+ return mo,+++def __(mo):+ slider = mo.ui.slider(1, 22)+ return slider,+++def __(mo, slider):+ mo.md(+ f"""+ marimo is a **reactive** Python notebook.++ This means that unlike traditional notebooks, marimo notebooks **run+ automatically** when you modify them or+ interact with UI elements, like this slider: {slider}.++ {"##" + "🍃" * slider.value}+ """+ )+ return+++def __(mo):+ mo.accordion(+ {+ "Installing packages": mo.md(+ """+ Most packages will be automatically installed,+ These can be found at [packages-in-pyodide](https://pyodide.org/en/stable/usage/packages-in-pyodide.html).++ For those that are not, you can use this `install` function++ ```python+ install("altair")+ ```+ """+ )+ }+ )+ return++[email protected](hide_code=True)+def __():+ import micropip+ import asyncio+++ def install(pkg):+ loop = asyncio.get_event_loop()+ loop.run_until_complete(micropip.install(pkg))+ return asyncio, install, micropip++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """+ ## 1. Reactive execution++ A marimo notebook is made up of small blocks of Python code called+ cells.++ marimo reads your cells and models the dependencies among them: whenever+ a cell that defines a global variable is run, marimo+ **automatically runs** all cells that reference that variable.++ Reactivity keeps your program state and outputs in sync with your code,+ making for a dynamic programming environment that prevents bugs before they+ happen.+ """+ )+ return++[email protected](hide_code=True)+def __(changed, mo):+ (+ mo.md(+ f"""+ **✨ Nice!** The value of `changed` is now {changed}.++ When you updated the value of the variable `changed`, marimo+ **reacted** by running this cell automatically, because this cell+ references the global variable `changed`.++ Reactivity ensures that your notebook state is always+ consistent, which is crucial for doing good science; it's also what+ enables marimo notebooks to double as tools and apps.+ """+ )+ if changed+ else mo.md(+ """+ **🌊 See it in action.** In the next cell, change the value of the+ variable `changed` to `True`, then click the run button.+ """+ )+ )+ return+++def __():+ changed = False+ return changed,++[email protected](hide_code=True)+def __(mo):+ mo.accordion(+ {+ "Tip: execution order": (+ """+ The order of cells on the page has no bearing on+ the order in which cells are executed: marimo knows that a cell+ reading a variable must run after the cell that defines it. This+ frees you to organize your code in the way that makes the most+ sense for you.+ """+ )+ }+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """+ **Global names must be unique.** To enable reactivity, marimo imposes a+ constraint on how names appear in cells: no two cells may define the same+ variable.+ """+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.accordion(+ {+ "Tip: encapsulation": (+ """+ By encapsulating logic in functions, classes, or Python modules,+ you can minimize the number of global variables in your notebook.+ """+ )+ }+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.accordion(+ {+ "Tip: private variables": (+ """+ Variables prefixed with an underscore are "private" to a cell, so+ they can be defined by multiple cells.+ """+ )+ }+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """## 2. UI elements++ Cells can output interactive UI elements. Interacting with a UI+ element **automatically triggers notebook execution**: when+ you interact with a UI element, its value is sent back to Python, and+ every cell that references that element is re-run.++ marimo provides a library of UI elements to choose from under+ `marimo.ui`.+ """+ )+ return+++def __(mo):+ mo.md("**🌊 Some UI elements.** Try interacting with the below elements.")+ return+++def __(mo):+ icon = mo.ui.dropdown(["🍃", "🌊", "✨"], value="🍃")+ return icon,+++def __(icon, mo):+ repetitions = mo.ui.slider(1, 16, label=f"number of {icon.value}: ")+ return repetitions,+++def __(icon, repetitions):+ icon, repetitions+ return+++def __(icon, mo, repetitions):+ mo.md("# " + icon.value * repetitions.value)+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """+ ## 3. marimo is just Python++ marimo cells parse Python (and only Python), and marimo notebooks are+ stored as pure Python files — outputs are _not_ included. There's no+ magical syntax.++ The Python files generated by marimo are:++ - easily versioned with git, yielding minimal diffs+ - legible for both humans and machines+ - formattable using your tool of choice,+ - usable as Python scripts, with UI elements taking their default+ values, and+ - importable by other modules (more on that in the future).+ """+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """+ ## 4. Running notebooks as apps++ marimo notebooks can double as apps. Click the app window icon in the+ bottom-left to see this notebook in "app view."++ Serve a notebook as an app with `marimo run` at the command-line.+ Of course, you can use marimo just to level-up your+ notebooking, without ever making apps.+ """+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """## 5. The `marimo` command-line tool++ **Creating and editing notebooks.** Use++ ```+ marimo edit+ ```++ in a terminal to create a new marimo notebook, or++ ```+ marimo edit notebook.py+ ```++ to create/edit a notebook called `notebook.py`.++ **Running as apps.** Use++ ```+ marimo run notebook.py+ ```++ to start a webserver that serves your notebook as an app in read-only mode,+ with code cells hidden.++ **Convert a Jupyter notebook.** Convert a Jupyter notebook to a marimo+ notebook using `marimo convert`:++ ```+ marimo convert your_notebook.ipynb > your_app.py+ ```++ **Tutorials.** marimo comes packaged with tutorials:++ - `dataflow`: more on marimo's automatic execution+ - `ui`: how to use UI elements+ - `markdown`: how to write markdown, with interpolated values and+ LaTeX+ - `plots`: how plotting works in marimo+ - `fileformat`: how marimo's file format works++ Start a tutorial with `marimo tutorial`; for example,++ ```+ marimo tutorial dataflow+ ```++ In addition to tutorials, we have examples in our+ [our Github repo](https://www.github.com/marimo-team/marimo/tree/main/examples).+ """+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """+ ## 6. The marimo editor++ Here are some tips to help you get started with the marimo editor.+ """+ )+ return+++def __(mo, tips):+ mo.accordion(tips)+ return+++def __(mo):+ mo.md("## Finally, a fun fact")+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """+ The name "marimo" is a reference to a type of algae that, under+ the right conditions, clumps together to form a small sphere+ called a "marimo moss ball". Made of just strands of algae, these+ beloved assemblages are greater than the sum of their parts.+ """+ )+ return++[email protected](hide_code=True)+def __():+ tips = {+ "Saving": (+ """+ **Saving**++ - _Name_ your app using the box at the top of the screen, or+ with `Ctrl/Cmd+s`. You can also create a named app at the+ command line, e.g., `marimo edit app_name.py`.++ - _Save_ by clicking the save icon on the bottom left, or by+ inputting `Ctrl/Cmd+s`. By default marimo is configured+ to autosave.+ """+ ),+ "Running": (+ """+ 1. _Run a cell_ by clicking the play ( ▷ ) button on the bottom+ right of a cell, or by inputting `Ctrl/Cmd+Enter`.++ 2. _Run a stale cell_ by clicking the yellow run button to the+ right of the cell, or by inputting `Ctrl/Cmd+Enter`. A cell is+ stale when its code has been modified but not run.++ 3. _Run all stale cells_ by clicking the play ( ▷ ) button on+ the bottom right of the screen, or input `Ctrl/Cmd+Shift+r`.+ """+ ),+ "Console Output": (+ """+ Console output (e.g., `print()` statements) is shown below a+ cell.+ """+ ),+ "Creating, Moving, and Deleting Cells": (+ """+ 1. _Create_ a new cell above or below a given one by clicking+ the plus button to the left of the cell, which appears on+ mouse hover.++ 2. _Move_ a cell up or down by dragging on the handle to the+ right of the cell, which appears on mouse hover.++ 3. _Delete_ a cell by clicking the trash bin icon. Bring it+ back by clicking the undo button on the bottom right of the+ screen, or with `Ctrl/Cmd+Shift+z`.+ """+ ),+ "Disabling Cells": (+ """+ You can disable a cell via the cell context menu (open it+ by clicking the icon to the right of a cell). marimo will+ never run a disabled cell or any cells that depend on it. This+ can help prevent accidental execution of expensive computations+ when editing a notebook.+ """+ ),+ "Code Folding": (+ """+ You can collapse or fold the code in a cell by clicking the arrow+ icons in the line number column to the left, or by using keyboard+ shortcuts.++ Use the command palette (`Ctrl/Cmd+k`) or a keyboard shortcut to+ quickly fold or unfold all cells.+ """+ ),+ "Code Formatting": (+ """+ If you have [black](https://github.com/psf/black) installed, you can format a cell with+ the keyboard shortcut `Ctrl/Cmd+b`.+ """+ ),+ "Command Palette": (+ """+ Use `Ctrl/Cmd+k` to open the command palette.+ """+ ),+ "Keyboard Shortcuts": (+ """+ Click the keyboard button on the bottom left of the screen (or+ input `Ctrl/Cmd+Shift+h`) to view a list of all keyboard+ shortcuts.+ """+ ),+ "Configuration": (+ """+ Configure the editor by clicking the gears icon near the top-right+ of the screen.+ """+ ),+ }+ return tips,+++if __name__ == "__main__":+ app.run()diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex a0e311d2a8..dad5dcbcbd 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -29,6 +29,7 @@ import { useFilename } from "@/core/saving/filename";import { useImperativeModal } from "@/components/modal/ImperativeModal";import { ShareStaticNotebookModal } from "@/components/static-html/share-modal";import { useRestartKernel } from "./useRestartKernel";+import { createShareableLink } from "@/core/pyodide/share";export function useNotebookActions() {const [filename] = useFilename();@@ -50,6 +51,19 @@ export function useNotebookActions() {openModal(<ShareStaticNotebookModal onClose={closeModal} />);},},+ {+ icon: <Share2Icon size={14} strokeWidth={1.5} />,+ label: "Share notebook via WASM",+ handle: async () => {+ const code = await readCode();+ const url = createShareableLink(code.contents);+ window.navigator.clipboard.writeText(url);+ toast({+ title: "Copied",+ description: "Link copied to clipboard.",+ });+ },+ },{icon: <FolderDownIcon size={14} strokeWidth={1.5} />,label: "Export as HTML",diff --git a/frontend/src/components/icons/large-spinner.tsx b/frontend/src/components/icons/large-spinner.tsxnew file mode 100644index 0000000000..217ce82e1a--- /dev/null+++ b/frontend/src/components/icons/large-spinner.tsx@@ -0,0 +1,16 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { Loader2Icon } from "lucide-react";++export const LargeSpinner = () => {+ return (+ <div className="flex flex-col h-full flex-1 items-center justify-center p-4">+ <Loader2Icon+ className="size-20 animate-spin text-primary"+ strokeWidth={1}+ />+ <div className="mt-2 text-muted-foreground font-semibold text-lg">+ Initializing...+ </div>+ </div>+ );+};diff --git a/frontend/src/components/static-html/static-banner.tsx b/frontend/src/components/static-html/static-banner.tsxindex 69b5ad58b7..72883abde5 100644--- a/frontend/src/components/static-html/static-banner.tsx+++ b/frontend/src/components/static-html/static-banner.tsx@@ -48,7 +48,7 @@ export const StaticBanner: React.FC = () => {};const StaticBannerDialog = () => {- let filename = getFilenameFromDOM() || "app.py";+ let filename = getFilenameFromDOM() || "notebook.py";// Trim the pathconst lastSlash = filename.lastIndexOf("/");if (lastSlash !== -1) {diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsxindex a4de1629d7..2c43b199c8 100644--- a/frontend/src/core/MarimoApp.tsx+++ b/frontend/src/core/MarimoApp.tsx@@ -2,7 +2,7 @@import "../css/index.css";import "iconify-icon";-import { useEffect } from "react";+import { PropsWithChildren, memo, useEffect } from "react";import { ErrorBoundary } from "../components/editor/boundary/ErrorBoundary";import { initializePlugins } from "../plugins/plugins";import { App } from "./App";@@ -16,11 +16,15 @@ import { initialMode } from "./mode";import { AppChrome } from "../components/editor/chrome/wrapper/app-chrome";import { StaticBanner } from "../components/static-html/static-banner";import { CssVariables } from "@/theme/ThemeProvider";+import { useAsyncData } from "@/hooks/useAsyncData";+import { isPyodide } from "./pyodide/utils";+import { PyodideBridge } from "./pyodide/bridge";+import { LargeSpinner } from "@/components/icons/large-spinner";/*** The root component of the Marimo app.*/-export const MarimoApp: React.FC = () => {+export const MarimoApp: React.FC = memo(() => {const [userConfig] = useUserConfig();const [appConfig] = useAppConfig();@@ -47,23 +51,45 @@ export const MarimoApp: React.FC = () => {<ErrorBoundary><TooltipProvider><DayPickerProvider initialProps={{}}>- <ModalProvider>- <CssVariables- variables={{- "--marimo-code-editor-font-size": toRem(- userConfig.display.code_editor_font_size,- ),- }}- >- {body}- </CssVariables>- </ModalProvider>+ <PyodideLoader>+ <ModalProvider>+ <CssVariables+ variables={{+ "--marimo-code-editor-font-size": toRem(+ userConfig.display.code_editor_font_size,+ ),+ }}+ >+ {body}+ </CssVariables>+ </ModalProvider>+ </PyodideLoader></DayPickerProvider></TooltipProvider></ErrorBoundary>);-};+});+MarimoApp.displayName = "MarimoApp";function toRem(px: number) {return `${px / 16}rem`;}++export const PyodideLoader: React.FC<PropsWithChildren> = ({ children }) => {+ if (!isPyodide()) {+ return children;+ }++ // isPyodide() is constant, so this is safe+ // eslint-disable-next-line react-hooks/rules-of-hooks+ const { loading } = useAsyncData(async () => {+ await PyodideBridge.INSTANCE.initialized.promise;+ return true;+ }, []);++ if (loading) {+ return <LargeSpinner />;+ }++ return children;+};diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 72ac9bcbe2..b0d37381a8 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -8,20 +8,28 @@ import {export const UserConfigSchema = z.object({- completion: z.object({- activate_on_typing: z.boolean(),- copilot: z.boolean(),- }),- save: z.object({- autosave: z.enum(["off", "after_delay"]).default("after_delay"),- autosave_delay: z- .number()- .nonnegative()- // Ensure that the delay is at least 1 second- .transform((millis) => Math.max(millis, 1000))- .default(1000),- format_on_save: z.boolean().default(false),- }),+ completion: z+ .object({+ activate_on_typing: z.boolean(),+ copilot: z.boolean(),+ })+ .default({ activate_on_typing: true, copilot: false }),+ save: z+ .object({+ autosave: z.enum(["off", "after_delay"]).default("after_delay"),+ autosave_delay: z+ .number()+ .nonnegative()+ // Ensure that the delay is at least 1 second+ .transform((millis) => Math.max(millis, 1000))+ .default(1000),+ format_on_save: z.boolean().default(false),+ })+ .default({+ autosave: "after_delay",+ autosave_delay: 1000,+ format_on_save: false,+ }),formatting: z.object({line_length: z@@ -31,9 +39,11 @@ export const UserConfigSchema = z.transform((n) => Math.min(n, 1000)),}).default({ line_length: 79 }),- keymap: z.object({- preset: z.enum(["default", "vim"]).default("default"),- }),+ keymap: z+ .object({+ preset: z.enum(["default", "vim"]).default("default"),+ })+ .default({ preset: "default" }),runtime: z.object({auto_instantiate: z.boolean(),diff --git a/frontend/src/core/network/DeferredRequestRegistry.ts b/frontend/src/core/network/DeferredRequestRegistry.tsindex 2fb5e6cfc4..fcf0a7c47e 100644--- a/frontend/src/core/network/DeferredRequestRegistry.ts+++ b/frontend/src/core/network/DeferredRequestRegistry.ts@@ -58,4 +58,14 @@ export class DeferredRequestRegistry<REQ, RES> {entry.resolve(response);this.requests.delete(requestId);}++ reject(requestId: RequestId, error: Error) {+ const entry = this.requests.get(requestId);+ if (entry === undefined) {+ return;+ }++ entry.reject(error);+ this.requests.delete(requestId);+ }}diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex 634e47acc3..271123bce8 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -1,5 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { CellId } from "../cells/ids";+import { PyodideBridge } from "../pyodide/bridge";+import { isPyodide } from "../pyodide/utils";import { isStaticNotebook } from "../static/static-state";import { API } from "./api";import { createStaticRequests } from "./static-requests";@@ -164,4 +166,8 @@ export const {readCode,openFile,sendListFiles,-} = isStaticNotebook() ? createStaticRequests() : createNetworkRequests();+} = isPyodide()+ ? PyodideBridge.INSTANCE+ : isStaticNotebook()+ ? createStaticRequests()+ : createNetworkRequests();diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 38c110cac7..cae8eae287 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -93,7 +93,7 @@ export interface SendStdin {text: string;}-interface ValueUpdate {+export interface ValueUpdate {objectId: string;value: unknown;}@@ -107,6 +107,10 @@ export interface FileInfo {children: FileInfo[];}+export interface FileListRequest {+ path: string | undefined;+}+export interface FileListResponse {files: FileInfo[];root: string;@@ -141,7 +145,5 @@ export interface EditRequests {readCode: () => Promise<{ contents: string }>;openFile: (request: { path: string }) => Promise<null>;// File explorer requests- sendListFiles: (request: {- path: string | undefined;- }) => Promise<FileListResponse>;+ sendListFiles: (request: FileListRequest) => Promise<FileListResponse>;}diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.tsnew file mode 100644index 0000000000..aeb84e7f3b--- /dev/null+++ b/frontend/src/core/pyodide/bridge.ts@@ -0,0 +1,346 @@+/* Copyright 2024 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-explicit-any */+import { Logger } from "@/utils/Logger";+import { CellId } from "../cells/ids";+import {+ CodeCompletionRequest,+ EditRequests,+ FileListRequest,+ FileListResponse,+ FormatRequest,+ FormatResponse,+ InstantiateRequest,+ RunRequests,+ SaveAppConfigRequest,+ SaveCellConfigRequest,+ SaveKernelRequest,+ SaveUserConfigRequest,+ SendFunctionRequest,+ SendStdin,+ ValueUpdate,+} from "../network/types";+import { IReconnectingWebSocket } from "../websocket/types";+import { fileStore } from "./store";+import { isPyodide } from "./utils";+import {+ RawBridge,+ WorkerClientPayload,+ WorkerServerPayload,+} from "./worker/types";+import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";+import { Deferred } from "@/utils/Deferred";+import InlineWorker from "./worker/worker?worker&inline";++export type BridgeFunctionAndPayload = {+ [P in keyof RawBridge]: {+ functionName: P;+ payload: Parameters<RawBridge[P]>[0];+ };+}[keyof RawBridge];++export class PyodideBridge implements RunRequests, EditRequests {+ static INSTANCE = new PyodideBridge();++ private worker!: Worker;+ private messageConsumer: ((message: string) => void) | undefined;+ private fetcher = new DeferredRequestRegistry<+ BridgeFunctionAndPayload,+ unknown+ >("bridge", async (requestId, request) => {+ this.postMessage({+ type: "call-function",+ id: requestId,+ functionName: request.functionName,+ payload: request.payload,+ });+ });++ public initialized = new Deferred<void>();++ constructor() {+ if (isPyodide()) {+ this.worker = new InlineWorker();+ this.worker.onmessage = this.handleWorkerMessage;+ }+ }++ private setCode = async () => {+ const code = await fileStore.readFile();+ this.postMessage({ type: "set-code", code: code || "" });+ };++ private handleWorkerMessage = async (+ event: MessageEvent<WorkerClientPayload>,+ ) => {+ if (event.data.type === "ready") {+ await this.setCode();+ }+ if (event.data.type === "initialized") {+ this.initialized.resolve();+ }+ if (event.data.type === "message") {+ this.messageConsumer?.(event.data.message);+ }+ if (event.data.type === "error") {+ Logger.error(event.data.error);+ this.fetcher.reject(event.data.id, new Error(event.data.error));+ }+ if (event.data.type === "response") {+ this.fetcher.resolve(event.data.id, event.data.response);+ }+ };++ private postMessage = (message: WorkerServerPayload) => {+ this.worker.postMessage(message);+ };++ consumeMessages = (consumer: (message: string) => void) => {+ this.messageConsumer = consumer;+ this.postMessage({ type: "start-messages" });+ };++ sendRename = async (filename: string | null): Promise<null> => {+ if (filename === null) {+ return null;+ }+ await this.fetcher.request({+ functionName: "rename_file",+ payload: filename,+ });+ return null;+ };++ sendSave = async (request: SaveKernelRequest): Promise<null> => {+ await this.fetcher.request({+ functionName: "save",+ payload: request,+ });+ const code = await this.readCode();+ if (code.contents) {+ fileStore.saveFile(code.contents);+ }+ return null;+ };++ sendStdin = async (request: SendStdin): Promise<null> => {+ await this.fetcher.request({+ functionName: "put_input",+ payload: request.text,+ });+ return null;+ };++ sendRun = async (cellIds: CellId[], codes: string[]): Promise<null> => {+ await this.fetcher.request({+ functionName: "load_packages",+ payload: codes.join("\n"),+ });++ await this.putControlRequest({+ execution_requests: cellIds.map((cellId, index) => ({+ cell_id: cellId,+ code: codes[index],+ })),+ });+ return null;+ };+ sendInterrupt = async (): Promise<null> => {+ await this.fetcher.request({+ functionName: "interrupt",+ payload: undefined,+ });+ return null;+ };+ sendShutdown = async (): Promise<null> => {+ window.close();+ return null;+ };+ sendFormat = async (+ request: FormatRequest,+ ): Promise<Record<CellId, string>> => {+ const response = await this.fetcher.request({+ functionName: "format",+ payload: request,+ });+ return (response as FormatResponse).codes;+ };+ sendDeleteCell = async (cellId: CellId): Promise<null> => {+ await this.putControlRequest({+ cell_id: cellId,+ });+ return null;+ };++ sendCodeCompletionRequest = async (+ request: CodeCompletionRequest,+ ): Promise<null> => {+ await this.fetcher.request({+ functionName: "code_complete",+ payload: request,+ });+ return null;+ };++ saveUserConfig = (request: SaveUserConfigRequest): Promise<null> => {+ throw new Error("Method not implemented.");+ };++ saveAppConfig = async (request: SaveAppConfigRequest): Promise<null> => {+ await this.fetcher.request({+ functionName: "save_app_config",+ payload: request,+ });+ return null;+ };++ saveCellConfig = async (request: SaveCellConfigRequest): Promise<null> => {+ await this.putControlRequest({+ configs: request.configs,+ });+ return null;+ };++ sendRestart = async (): Promise<null> => {+ window.location.reload();+ return null;+ };++ readCode = async (): Promise<{ contents: string }> => {+ const response = await this.fetcher.request({+ functionName: "read_code",+ payload: undefined,+ });+ return response as { contents: string };+ };++ openFile = (request: { path: string }): Promise<null> => {+ throw new Error("Method not implemented.");+ };++ sendListFiles = async (+ request: FileListRequest,+ ): Promise<FileListResponse> => {+ const response = await this.fetcher.request({+ functionName: "list_files",+ payload: request,+ });+ return response as FileListResponse;+ };+ sendComponentValues = async (valueUpdates: ValueUpdate[]): Promise<null> => {+ await this.putControlRequest({+ ids_and_values: valueUpdates.map((update) => [+ update.objectId,+ update.value,+ ]),+ });+ return null;+ };++ sendInstantiate = async (request: InstantiateRequest): Promise<null> => {+ return null;+ };++ sendFunctionRequest = async (request: SendFunctionRequest): Promise<null> => {+ await this.putControlRequest({+ function_call: request,+ });+ return null;+ };++ private putControlRequest = async (operation: object) => {+ await this.fetcher.request({+ functionName: "put_control_request",+ payload: operation,+ });+ };+}++export class PyodideWebsocket implements IReconnectingWebSocket {+ CONNECTING = WebSocket.CONNECTING;+ OPEN = WebSocket.OPEN;+ CLOSING = WebSocket.CLOSING;+ CLOSED = WebSocket.CLOSED;+ binaryType = "blob" as BinaryType;+ bufferedAmount = 0;+ extensions = "";+ protocol = "";+ url = "";++ onclose = null;+ onerror = null;+ onmessage = null;+ onopen = null;++ openSubscriptions = new Set<() => void>();+ closeSubscriptions = new Set<() => void>();+ messageSubscriptions = new Set<(event: MessageEvent) => void>();+ errorSubscriptions = new Set<(event: Event) => void>();++ constructor(private bridge: PyodideBridge) {}++ private consumeMessages() {+ this.bridge.consumeMessages((message) => {+ this.messageSubscriptions.forEach((callback) => {+ callback({ data: message } as MessageEvent);+ });+ });+ }++ addEventListener(type: unknown, callback: any, options?: unknown): void {+ switch (type) {+ case "open":+ this.openSubscriptions.add(callback);+ // Call open right away+ callback();+ break;+ case "close":+ this.closeSubscriptions.add(callback);+ break;+ case "message":+ this.messageSubscriptions.add(callback);+ // Don't start consuming messages until we have a message listener+ this.consumeMessages();+ break;+ case "error":+ this.errorSubscriptions.add(callback);+ break;+ }+ }++ removeEventListener(type: unknown, callback: any, options?: unknown): void {+ switch (type) {+ case "open":+ this.openSubscriptions.delete(callback);+ break;+ case "close":+ this.closeSubscriptions.delete(callback);+ break;+ case "message":+ this.messageSubscriptions.delete(callback);+ break;+ case "error":+ this.errorSubscriptions.delete(callback);+ break;+ }+ }++ dispatchEvent(event: Event): boolean {+ throw new Error("Method not implemented.");+ }++ readyState = WebSocket.OPEN;+ retryCount = 0;+ shouldReconnect = false;++ reconnect(code?: number | undefined, reason?: string | undefined): void {+ throw new Error("Method not implemented.");+ }++ send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {+ throw new Error("Method not implemented.");+ }++ close() {+ return;+ }+}diff --git a/frontend/src/core/pyodide/share.ts b/frontend/src/core/pyodide/share.tsnew file mode 100644index 0000000000..880d1306a4--- /dev/null+++ b/frontend/src/core/pyodide/share.ts@@ -0,0 +1,9 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { compressToEncodedURIComponent } from "lz-string";++export function createShareableLink(code: string) {+ const compressed = compressToEncodedURIComponent(code);+ const url = new URL("https://marimo.app");+ url.searchParams.set("code", compressed);+ return url.href;+}diff --git a/frontend/src/core/pyodide/store.ts b/frontend/src/core/pyodide/store.tsnew file mode 100644index 0000000000..b16b4619ca--- /dev/null+++ b/frontend/src/core/pyodide/store.ts@@ -0,0 +1,101 @@+/* Copyright 2024 Marimo. All rights reserved. */+import {+ compressToEncodedURIComponent,+ decompressFromEncodedURIComponent,+} from "lz-string";++export interface FileStore {+ saveFile(contents: string): void;+ readFile(): string | null | Promise<string | null>;+}++const KEY = "marimo:file";+const localStorageFileStore: FileStore = {+ saveFile(contents: string) {+ localStorage.setItem(KEY, contents);+ },+ readFile() {+ return localStorage.getItem(KEY);+ },+};++const URL_PARAM_KEY = "code";+const urlFileStore: FileStore = {+ saveFile(contents: string) {+ const url = new URL(location.href);+ const encoded = compressToEncodedURIComponent(contents);+ url.searchParams.set(URL_PARAM_KEY, encoded);+ history.replaceState(null, "", url.toString());+ },+ readFile() {+ const url = new URL(location.href);+ if (!url.searchParams.has(URL_PARAM_KEY)) {+ return null;+ }+ const code = url.searchParams.get(URL_PARAM_KEY);+ if (!code) {+ return null;+ }+ return decompressFromEncodedURIComponent(code);+ },+};++const remoteDefaultFileStore: FileStore = {+ saveFile(contents: string) {+ // Do nothing+ },+ readFile() {+ const baseURI = document.baseURI;+ return fetch(`${baseURI}files/wasm-intro.py`)+ .then((res) => res.text())+ .catch(() => null);+ },+};++const fallbackFileStore: FileStore = {+ saveFile(contents: string) {+ // Do nothing+ },+ readFile() {+ return [+ "import marimo",+ "app = marimo.App()",+ "",+ "@app.cell",+ "def __():",+ " import marimo as mo",+ " x = 1 + 1",+ " x",+ " return mo,x",+ "",+ 'if __name__ == "__main__":',+ " app.run()",+ ].join("\n");+ },+};++class CompositeFileStore implements FileStore {+ constructor(private stores: FileStore[]) {}++ saveFile(contents: string) {+ this.stores.forEach((store) => store.saveFile(contents));+ }++ readFile() {+ for (const store of this.stores) {+ const contents = store.readFile();+ if (contents) {+ return contents;+ }+ }+ return null;+ }+}++export const fileStore = new CompositeFileStore([+ // Prefer URL param, then local storage, then remote default, then fallback+ urlFileStore,+ localStorageFileStore,+ remoteDefaultFileStore,+ fallbackFileStore,+]);diff --git a/frontend/src/core/pyodide/utils.ts b/frontend/src/core/pyodide/utils.tsnew file mode 100644index 0000000000..3b4dcca63c--- /dev/null+++ b/frontend/src/core/pyodide/utils.ts@@ -0,0 +1,4 @@+/* Copyright 2024 Marimo. All rights reserved. */+export function isPyodide() {+ return document.querySelector("marimo-wasm") !== null;+}diff --git a/frontend/src/core/pyodide/worker/bootstrap.ts b/frontend/src/core/pyodide/worker/bootstrap.tsnew file mode 100644index 0000000000..7b053ab40b--- /dev/null+++ b/frontend/src/core/pyodide/worker/bootstrap.ts@@ -0,0 +1,81 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { PyodideInterface } from "pyodide";+import { APP_FILE_PATH, mountFilesystem } from "./fs";+import { Logger } from "../../../utils/Logger";+import { SerializedBridge } from "./types";++declare let loadPyodide: undefined | (() => Promise<PyodideInterface>);++export async function bootstrap() {+ if (!loadPyodide) {+ throw new Error("loadPyodide is not defined");+ }++ // Load pyodide and micropip+ const pyodide = await loadPyodide();+ await pyodide.loadPackage("micropip");++ // Install marimo+ const baseUrl =+ process.env.NODE_ENV === "production"+ ? `https://marimo.app/registry`+ : "http://localhost:8000/dist";+ await pyodide.runPythonAsync(`+ import micropip++ micropip.add_mock_package("multiprocessing", "*", modules={+ "multiprocessing": None,+ "multiprocessing.connection": None,+ "multiprocessing.context": None,+ "multiprocessing.managers": None,+ "multiprocessing.pool": None,+ "multiprocessing.sharedctypes": None,+ "multiprocessing.shared_memory": None,+ "multiprocessing.spawn": None,+ })++ await micropip.install(+ [+ # Subset of marimo requirements+ "${baseUrl}/marimo-0.2.4-py3-none-any.whl",+ "markdown",+ "jedi",+ "docutils",+ "pymdown-extensions",+ "pygments",+ ],+ deps=False+ );+ `);++ return pyodide;+}++export async function startSession(+ pyodide: PyodideInterface,+ code: string,+): Promise<SerializedBridge> {+ // Set up the filesystem+ await mountFilesystem(pyodide, code);++ // Load packages from the code+ await pyodide.loadPackagesFromImports(code, {+ messageCallback: Logger.log,+ errorCallback: Logger.error,+ });++ const bridge = await pyodide.runPythonAsync(+ `+ print("[py] Starting marimo...")+ import asyncio+ from marimo._pyodide.pyodide_session import create_session, instantiate++ session, bridge = create_session(filename="${APP_FILE_PATH}")+ instantiate(session)+ asyncio.create_task(session.start())++ bridge`,+ );++ return bridge;+}diff --git a/frontend/src/core/pyodide/worker/fs.ts b/frontend/src/core/pyodide/worker/fs.tsnew file mode 100644index 0000000000..531032bfee--- /dev/null+++ b/frontend/src/core/pyodide/worker/fs.ts@@ -0,0 +1,26 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { PyodideInterface } from "pyodide";++export const APP_FILE_PATH = "notebook.py";++export async function mountFilesystem(+ pyodide: PyodideInterface,+ contents: string,+): Promise<string> {+ const mountDir = "/marimo";+ await pyodide.FS.mkdir(mountDir);+ await pyodide.FS.mount(pyodide.FS.filesystems.IDBFS, { root: "." }, mountDir);++ // Change directory to /marimo+ pyodide.runPython(`+ import os+ os.chdir('/marimo')+ `);++ // Check if or write the default app.py+ if (!(await pyodide.FS.analyzePath(APP_FILE_PATH).exists)) {+ await pyodide.FS.writeFile(APP_FILE_PATH, contents, { encoding: "utf8" });+ }++ return contents || "";+}diff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.tsnew file mode 100644index 0000000000..935b5c5342--- /dev/null+++ b/frontend/src/core/pyodide/worker/types.ts@@ -0,0 +1,75 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { RequestId } from "@/core/network/DeferredRequestRegistry";+import type {+ CodeCompletionRequest,+ FileListRequest,+ FileListResponse,+ FormatRequest,+ FormatResponse,+ SaveAppConfigRequest,+ SaveKernelRequest,+} from "../../network/types";++export interface RawBridge {+ put_control_request(operation: object): Promise<string>;+ put_input(input: string): Promise<string>;+ interrupt(): Promise<string>;+ code_complete(request: CodeCompletionRequest): Promise<string>;+ read_code(): Promise<{ contents: string }>;+ format(request: FormatRequest): Promise<FormatResponse>;+ save(request: SaveKernelRequest): Promise<string>;+ save_app_config(request: SaveAppConfigRequest): Promise<string>;+ rename_file(request: string): Promise<string>;+ list_files(request: FileListRequest): Promise<FileListResponse>;+ file_details(request: string): Promise<string>;+ create_file_or_directory(request: string): Promise<string>;+ delete_file_or_directory(request: string): Promise<string>;+ update_file_or_directory(request: string): Promise<string>;+ load_packages(request: string): Promise<string>;+ [Symbol.asyncIterator](): AsyncIterator<string>;+}++export type SerializedBridge = {+ [P in keyof RawBridge]: RawBridge[P] extends (+ payload: string,+ ) => Promise<unknown>+ ? (payload: string) => Promise<string>+ : RawBridge[P];+};++export type WorkerServerPayload =+ | {+ type: "start-messages";+ }+ | {+ type: "set-code";+ code: string;+ }+ | {+ type: "call-function";+ id: RequestId;+ functionName: keyof RawBridge | "load_packages";+ payload: {} | undefined | null;+ };++export type WorkerClientPayload =+ | {+ type: "response";+ id: RequestId;+ response: unknown;+ }+ | {+ type: "ready";+ }+ | {+ type: "initialized";+ }+ | {+ type: "error";+ id: RequestId;+ error: string;+ }+ | {+ type: "message";+ message: string;+ };diff --git a/frontend/src/core/pyodide/worker/worker.ts b/frontend/src/core/pyodide/worker/worker.tsnew file mode 100644index 0000000000..8b1636dc6e--- /dev/null+++ b/frontend/src/core/pyodide/worker/worker.ts@@ -0,0 +1,120 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { bootstrap, startSession } from "./bootstrap";+import type { PyodideInterface } from "pyodide";+import {+ SerializedBridge,+ WorkerClientPayload,+ WorkerServerPayload,+} from "./types";+import { invariant } from "../../../utils/invariant";+import { Deferred } from "../../../utils/Deferred";++declare const self: Window & {+ pyodide: PyodideInterface;+};++// Initialize pyodide+async function loadPyodideAndPackages() {+ // @ts-expect-error ehh TypeScript+ await import("https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js");+ self.pyodide = await bootstrap();+}+const pyodideReadyPromise = loadPyodideAndPackages();++// Initialize the session+const bridgeReady = new Deferred<SerializedBridge>();+let started = false;+function startSessionWithCode(code: string) {+ if (started) {+ return;+ }+ started = true;+ startSession(self.pyodide, code).then((bridge) => {+ bridgeReady.resolve(bridge);+ postMessage({ type: "initialized" });+ });+}+async function getBridge() {+ return bridgeReady.promise;+}++self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {+ // make sure loading is done+ await pyodideReadyPromise;++ // Start the session+ if (event.data.type === "set-code") {+ startSessionWithCode(event.data.code);+ return;+ }++ // Run forever, waiting for messages from the Python bridge+ if (event.data.type === "start-messages") {+ const done = false;++ while (!done) {+ const bridge = await getBridge();+ for await (const message of bridge) {+ postMessage({ type: "message", message });+ }+ }++ return;+ }++ const { id, functionName, payload } = event.data;+ try {+ // Special case for loading packages+ if (functionName === "load_packages") {+ invariant(+ typeof payload === "string",+ "Expected a string payload for load_packages",+ );+ await self.pyodide.loadPackagesFromImports(payload, {+ messageCallback: console.log,+ errorCallback: console.error,+ });++ postMessage({ type: "response", response: null, id });+ return;+ }++ // Perform the function call to the Python bridge+ const bridge = await getBridge();+ // Serialize the payload+ const payloadString =+ payload == null+ ? null+ : typeof payload === "string"+ ? payload+ : JSON.stringify(payload);+ // Make the request+ const response =+ payloadString == null+ ? // @ts-expect-error ehh TypeScript+ await bridge[functionName]()+ : // @ts-expect-error ehh TypeScript+ await bridge[functionName](payloadString);++ // Post the response back to the main thread+ postMessage({+ type: "response",+ response: typeof response === "string" ? JSON.parse(response) : response,+ id,+ });+ } catch (error) {+ console.error("Error in worker", error);+ if (error instanceof Error) {+ postMessage({ type: "error", error: error.message, id });+ } else {+ postMessage({ type: "error", error: String(error), id });+ }+ }+};++function postMessage(message: WorkerClientPayload) {+ self.postMessage(message);+}++postMessage({ type: "ready" });diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.tsindex e5c05b2d07..54d3508908 100644--- a/frontend/src/core/static/download-html.ts+++ b/frontend/src/core/static/download-html.ts@@ -56,7 +56,7 @@ export async function downloadAsHTML(opts: { filename: string }) {const { filename } = opts;const html = await createStaticHTMLNotebook();- const filenameWithoutPath = filename.split("/").pop() ?? "app.py";+ const filenameWithoutPath = filename.split("/").pop() ?? "notebook.py";const filenameWithoutExtension =filenameWithoutPath.split(".").shift() ?? "app";diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex ed85150ab5..c0994bc16c 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -213,7 +213,7 @@ export function useMarimoWebSocket(opts: {// open connection is closed.if (shouldTryReconnecting.current) {shouldTryReconnecting.current = false;- ws.current?.reconnect(code, reason);+ ws.reconnect(code, reason);}};@@ -259,7 +259,7 @@ export function useMarimoWebSocket(opts: {code: WebSocketClosedReason.ALREADY_RUNNING,reason: "another browser tab is already connected to the kernel",});- ws.current?.close(); // close to prevent reconnecting+ ws.close(); // close to prevent reconnectingreturn;case "MARIMO_WRONG_KERNEL_ID":@@ -270,7 +270,7 @@ export function useMarimoWebSocket(opts: {code: WebSocketClosedReason.KERNEL_DISCONNECTED,reason: "kernel not found",});- ws.current?.close(); // close to prevent reconnecting+ ws.close(); // close to prevent reconnectingreturn;case "MARIMO_MALFORMED_QUERY":diff --git a/frontend/src/core/websocket/useWebSocket.tsx b/frontend/src/core/websocket/useWebSocket.tsxindex 0ffb180b54..6f35744404 100644--- a/frontend/src/core/websocket/useWebSocket.tsx+++ b/frontend/src/core/websocket/useWebSocket.tsx@@ -1,8 +1,10 @@/* Copyright 2024 Marimo. All rights reserved. */-import { useEffect, useRef } from "react";+import { useEffect, useState } from "react";import ReconnectingWebSocket from "partysocket/ws";import { IReconnectingWebSocket } from "./types";import { StaticWebsocket } from "./StaticWebsocket";+import { isPyodide } from "../pyodide/utils";+import { PyodideBridge, PyodideWebsocket } from "../pyodide/bridge";interface UseWebSocketOptions {url: string;@@ -21,37 +23,39 @@ interface UseWebSocketOptions {export function useWebSocket(options: UseWebSocketOptions) {const { onOpen, onMessage, onClose, onError, ...rest } = options;- const wsRef = useRef<IReconnectingWebSocket>();+ // eslint-disable-next-line react/hook-use-state+ const [ws] = useState<IReconnectingWebSocket>(() => {+ const socket: IReconnectingWebSocket = isPyodide()+ ? new PyodideWebsocket(PyodideBridge.INSTANCE)+ : options.static+ ? new StaticWebsocket()+ : new ReconnectingWebSocket(rest.url, undefined, {+ // We don't want Infinity retries+ maxRetries: 10,+ debug: false,+ });++ return socket;+ });useEffect(() => {- wsRef.current = options.static- ? new StaticWebsocket()- : new ReconnectingWebSocket(rest.url, undefined, {- // We don't want Infinity retries- maxRetries: 10,- debug: false,- });-- const socket = wsRef.current;- onOpen && socket.addEventListener("open", onOpen);- onClose && socket.addEventListener("close", onClose);- onError && socket.addEventListener("error", onError);- onMessage && socket.addEventListener("message", onMessage);+ onOpen && ws.addEventListener("open", onOpen);+ onClose && ws.addEventListener("close", onClose);+ onError && ws.addEventListener("error", onError);+ onMessage && ws.addEventListener("message", onMessage);return () => {- onOpen && socket.removeEventListener("open", onOpen);- onClose && socket.removeEventListener("close", onClose);- onError && socket.removeEventListener("error", onError);- onMessage && socket.removeEventListener("message", onMessage);+ // Don't disconnect if we're using Pyodide+ if (isPyodide()) {+ return;+ }+ onOpen && ws.removeEventListener("open", onOpen);+ onClose && ws.removeEventListener("close", onClose);+ onError && ws.removeEventListener("error", onError);+ onMessage && ws.removeEventListener("message", onMessage);};// eslint-disable-next-line react-hooks/exhaustive-deps}, []);- useEffect(() => {- const socket = wsRef.current;- return () => socket?.close();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- return wsRef;+ return ws;}diff --git a/frontend/src/css/Cell.css b/frontend/src/css/Cell.cssindex 01d2f5c814..892bcbe0a0 100644--- a/frontend/src/css/Cell.css+++ b/frontend/src/css/Cell.css@@ -165,6 +165,7 @@/* custom shadow until our theme overrides can support colored shadow */--tw-shadow: 0 4px 0px -1px var(--blue-8), 0 2px 4px -2px var(--blue-8) !important;+box-shadow: var(--tw-shadow) !important;@apply shadow-lg;diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 9c9daf0f25..912ca4a135 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -1,5 +1,4 @@/* Copyright 2024 Marimo. All rights reserved. */-import React from "react";import ReactDOM from "react-dom/client";import { ThemeProvider } from "./theme/ThemeProvider";import { ErrorBoundary } from "./components/editor/boundary/ErrorBoundary";@@ -31,13 +30,11 @@ const root = ReactDOM.createRoot(document.getElementById("root")!);try {root.render(- <React.StrictMode>- <Provider store={store}>- <ThemeProvider>- <MarimoApp />- </ThemeProvider>- </Provider>- </React.StrictMode>,+ <Provider store={store}>+ <ThemeProvider>+ <MarimoApp />+ </ThemeProvider>+ </Provider>,);} catch (error) {// Most likely, configuration failed to parse.diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsxindex 44d12e63d9..460851889d 100644--- a/frontend/src/plugins/core/registerReactComponent.tsx+++ b/frontend/src/plugins/core/registerReactComponent.tsx@@ -438,6 +438,10 @@ function shouldCopyStyleSheet(sheet: CSSStyleSheet): boolean {return sheet.href.startsWith(getStaticNotebookAssetUrl());}+ if (sheet.href.startsWith("https://cdn.jsdelivr.net/npm/@marimo-team/")) {+ return true;+ }+return sheet.href.startsWith(window.location.origin);}diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex e74a21d774..0569028f31 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -9,6 +9,7 @@ const HOST = process.env.HOST || "127.0.0.1";const TARGET = `http://${HOST}:${SERVER_PORT}`;const isDev = process.env.NODE_ENV === "development";const isStorybook = process.env.npm_lifecycle_script?.includes("storybook");+const isPyodide = process.env.PYODIDE === "true";const htmlDevPlugin = (): Plugin => {return {@@ -19,6 +20,19 @@ const htmlDevPlugin = (): Plugin => {return html;}+ if (isPyodide) {+ html = html.replace("{{ base_url }}", "");+ html = html.replace("{{ title }}", "marimo");+ html = html.replace("{{ user_config }}", JSON.stringify({}));+ html = html.replace("{{ app_config }}", JSON.stringify({}));+ html = html.replace("{{ server_token }}", "");+ html = html.replace("{{ version }}", "0.2.0");+ html = html.replace("{{ filename }}", "notebook.py");+ html = html.replace("{{ mode }}", "edit");+ html = html.replace(/<\/head>/, `<marimo-wasm></marimo-wasm></head>`);+ return html;+ }+// fetch html from serverconst serverHtmlResponse = await fetch(TARGET);const serverHtml = await serverHtmlResponse.text();diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex 32515a7e12..01b36e1b33 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -148,7 +148,6 @@ class Watcher:# NB: Python doesn't provide a standard out class to inherit from, so# we inherit from TextIOBase.class ThreadSafeStdout(Stdout):- name = "stdout"encoding = sys.stdout.encodingerrors = sys.stdout.errors_fileno: int | None = None@@ -208,7 +207,6 @@ class ThreadSafeStdout(Stdout):class ThreadSafeStderr(Stderr):- name = "stderr"encoding = sys.stderr.encodingerrors = sys.stderr.errors_fileno: int | None = None@@ -271,7 +269,6 @@ class ThreadSafeStderr(Stderr):class ThreadSafeStdin(Stdin):"""Implements a subset of stdin."""- name = "stdin"encoding = sys.stdin.encodingerrors = sys.stdin.errorsdiff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.pyindex 5879dec48e..4ef1dc5ee6 100644--- a/marimo/_messaging/types.py+++ b/marimo/_messaging/types.py@@ -25,16 +25,22 @@ class Stream(abc.ABC):class Stdout(io.TextIOBase):+ name = "stdout"+@abc.abstractmethoddef write(self, __s: str) -> int:passclass Stderr(io.TextIOBase):+ name = "stderr"+@abc.abstractmethoddef write(self, __s: str) -> int:passclass Stdin(io.TextIOBase):+ name = "stdin"+passdiff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pyindex 817a8808dc..e16c4ff669 100644--- a/marimo/_plugins/stateless/mpl/_mpl.py+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -14,15 +14,7 @@ import mimetypesimport signalimport threadingfrom pathlib import Path-from typing import Any, Optional, Tuple--import uvicorn-from starlette.applications import Starlette-from starlette.requests import Request-from starlette.responses import HTMLResponse, Response-from starlette.routing import Mount, Route, WebSocketRoute-from starlette.staticfiles import StaticFiles-from starlette.websockets import WebSocket+from typing import TYPE_CHECKING, Any, Optional, Tuplefrom marimo._output.builder import hfrom marimo._output.hypertext import Html@@ -36,6 +28,9 @@ from marimo._runtime.context import (from marimo._server.utils import find_free_portfrom marimo._utils.signals import get_signals+if TYPE_CHECKING:+ from starlette.applications import Starlette+class FigureManagers:def __init__(self) -> None:@@ -76,6 +71,12 @@ def create_application(from matplotlib.backends.backend_webagg import ( # type: ignore[import-not-found] # noqa: E501FigureManagerWebAgg,)+ from starlette.applications import Starlette+ from starlette.requests import Request+ from starlette.responses import HTMLResponse, Response+ from starlette.routing import Mount, Route, WebSocketRoute+ from starlette.staticfiles import StaticFiles+ from starlette.websockets import WebSocketasync def main_page(request: Request) -> HTMLResponse:figure_id = request.query_params.get("figure")@@ -184,6 +185,8 @@ _app: Optional[Starlette] = Nonedef get_or_create_application() -> Starlette:global _app+ import uvicorn+if _app is None:host = "localhost"port = find_free_port(10_000)diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pynew file mode 100644index 0000000000..9bdc8b311e--- /dev/null+++ b/marimo/_pyodide/pyodide_session.py@@ -0,0 +1,372 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+import dataclasses+import json+from typing import Any, Callable, Optional++from marimo import _loggers+from marimo._ast.cell import CellConfig, CellId_t+from marimo._messaging.ops import KernelReady, serialize+from marimo._messaging.types import KernelMessage+from marimo._pyodide.streams import (+ PyodideStderr,+ PyodideStdin,+ PyodideStdout,+ PyodideStream,+)+from marimo._runtime import requests+from marimo._runtime.context import initialize_context+from marimo._runtime.input_override import input_override+from marimo._runtime.requests import (+ AppMetadata,+ CompletionRequest,+ ControlRequest,+ CreationRequest,+ ExecutionRequest,+ SetUIElementValueRequest,+)+from marimo._runtime.runtime import Kernel+from marimo._server.file_manager import AppFileManager+from marimo._server.files.os_file_system import OSFileSystem+from marimo._server.model import SessionMode+from marimo._server.models.files import (+ FileCreateRequest,+ FileCreateResponse,+ FileDeleteRequest,+ FileDeleteResponse,+ FileDetailsRequest,+ FileDetailsResponse,+ FileListRequest,+ FileListResponse,+ FileUpdateRequest,+ FileUpdateResponse,+)+from marimo._server.models.models import (+ FormatRequest,+ FormatResponse,+ ReadCodeResponse,+ SaveAppConfigurationRequest,+ SaveRequest,+)+from marimo._utils.formatter import BlackFormatter+from marimo._utils.parse_dataclass import parse_raw++LOGGER = _loggers.marimo_logger()+++def instantiate(session: PyodideSession) -> None:+ app = session.app_manager.app+ execution_requests = tuple(+ ExecutionRequest(cell_id=cell_data.cell_id, code=cell_data.code)+ for cell_data in app.cell_manager.cell_data()+ )++ session.put_control_request(+ CreationRequest(+ execution_requests=execution_requests,+ set_ui_element_value_request=SetUIElementValueRequest(list()),+ )+ )+++def create_session(+ filename: str,+) -> tuple[PyodideSession, PyodideBridge]:+ queue = asyncio.Queue[dict[str, Any]]()++ def write_kernel_message(op: KernelMessage) -> None:+ queue.put_nowait({"op": op[0], "data": op[1]})++ app_file_manager = AppFileManager(filename=filename)+ app = app_file_manager.app++ app_metadata = AppMetadata(+ filename=filename,+ )++ session = PyodideSession(+ app_file_manager, SessionMode.EDIT, write_kernel_message, app_metadata+ )++ write_kernel_message(+ (+ KernelReady.name,+ serialize(+ KernelReady(+ codes=tuple(app.cell_manager.codes()),+ names=tuple(app.cell_manager.names()),+ configs=tuple(app.cell_manager.configs()),+ cell_ids=tuple(app.cell_manager.cell_ids()),+ layout=None,+ resumed=False,+ ui_values={},+ last_executed_code={},+ )+ ),+ )+ )++ bridge = PyodideBridge(queue, session)++ return session, bridge+++class AsyncQueueManager:+ """Manages queues for a session."""++ def __init__(self) -> None:+ # Control messages for the kernel (run, set UI element, set config, etc+ # ) are sent through the control queue+ self.control_queue = asyncio.Queue[requests.ControlRequest]()++ # Code completion requests are sent through a separate queue+ self.completion_queue = asyncio.Queue[requests.CompletionRequest]()++ # Input messages for the user's Python code are sent through the+ # input queue+ self.input_queue = asyncio.Queue[str](maxsize=1)++ def close_queues(self) -> None:+ # kernel thread cleans up read/write conn and IOloop handler on+ # exit; we don't join the thread because we don't want to block+ self.control_queue.put_nowait(requests.StopRequest())+++class PyodideSession:+ """A client session that is compatible with Pyodide."""++ def __init__(+ self,+ app: AppFileManager,+ mode: SessionMode,+ on_write: Callable[[KernelMessage], None],+ app_metadata: AppMetadata,+ ) -> None:+ """Initialize kernel and client connection to it."""+ self.app_manager = app+ self.mode = mode+ self.app_metadata = app_metadata+ self._queue_manager = AsyncQueueManager()+ self.session_consumer = on_write++ self.consumers: list[Callable[[KernelMessage], None]] = [+ lambda msg: self.session_consumer(msg),+ ]++ def _on_message(self, msg: KernelMessage) -> None:+ for consumer in self.consumers:+ consumer(msg)++ async def start(self) -> None:+ self.kernel_task = launch_pyodide_kernel(+ control_queue=self._queue_manager.control_queue,+ completion_queue=self._queue_manager.completion_queue,+ input_queue=self._queue_manager.input_queue,+ on_message=self._on_message,+ is_edit_mode=self.mode == SessionMode.EDIT,+ configs=self.app_manager.app.cell_manager.config_map(),+ app_metadata=self.app_metadata,+ )+ await self.kernel_task.start()++ def put_control_request(self, request: requests.ControlRequest) -> None:+ self._queue_manager.control_queue.put_nowait(request)++ def put_completion_request(+ self, request: requests.CompletionRequest+ ) -> None:+ self._queue_manager.completion_queue.put_nowait(request)++ def interrupt(self) -> None:+ assert self.kernel_task is not None+ self.kernel_task.restart()++ def put_input(self, text: str) -> None:+ self._queue_manager.input_queue.put_nowait(text)+++class PyodideBridge:+ def __init__(+ self,+ queue: asyncio.Queue[dict[str, Any]],+ session: PyodideSession,+ ):+ self.queue = queue+ self.session = session+ self.file_system = OSFileSystem()++ async def __aiter__(self) -> Any:+ while True:+ op = await self.queue.get()+ yield json.dumps(op)++ def put_control_request(self, request: str) -> None:+ @dataclasses.dataclass+ class Container:+ body: requests.ControlRequest++ parsed = parse_raw({"body": json.loads(request)}, Container).body+ self.session.put_control_request(parsed)++ def put_input(self, text: str) -> None:+ self.session.put_input(text)++ def interrupt(self) -> None:+ self.session.interrupt()++ def code_complete(self, request: str) -> None:+ parsed = parse_raw(json.loads(request), requests.CompletionRequest)+ self.session.put_completion_request(parsed)++ def read_code(self) -> str:+ contents: str = self.session.app_manager.read_file()+ response = ReadCodeResponse(contents=contents)+ return json.dumps(dataclasses.asdict(response))++ def format(self, request: str) -> str:+ parsed = parse_raw(json.loads(request), FormatRequest)+ formatter = BlackFormatter(line_length=parsed.line_length)++ response = FormatResponse(codes=formatter.format(parsed.codes))+ return json.dumps(dataclasses.asdict(response))++ def save(self, request: str) -> None:+ parsed = parse_raw(json.loads(request), SaveRequest)+ self.session.app_manager.save(parsed)++ def save_app_config(self, request: str) -> None:+ parsed = parse_raw(json.loads(request), SaveAppConfigurationRequest)+ self.session.app_manager.save_app_config(parsed.config)++ def rename_file(self, filename: str) -> None:+ self.session.app_manager.rename(filename)++ def list_files(+ self,+ request: str,+ ) -> str:+ body = parse_raw(json.loads(request), FileListRequest)+ root = body.path or self.file_system.get_root()+ files = self.file_system.list_files(root)+ response = FileListResponse(files=files, root=root)+ return json.dumps(dataclasses.asdict(response))++ def file_details(+ self,+ request: str,+ ) -> str:+ body = parse_raw(json.loads(request), FileDetailsRequest)+ file_info = self.file_system.get_details(body.path)+ response = FileDetailsResponse(file=file_info)+ return json.dumps(dataclasses.asdict(response))++ def create_file_or_directory(+ self,+ request: str,+ ) -> str:+ body = parse_raw(json.loads(request), FileCreateRequest)+ success = self.file_system.create_file_or_directory(+ body.path, body.type, body.name+ )+ response = FileCreateResponse(success=success)+ return json.dumps(dataclasses.asdict(response))++ def delete_file_or_directory(+ self,+ request: str,+ ) -> str:+ body = parse_raw(json.loads(request), FileDeleteRequest)+ success = self.file_system.delete_file_or_directory(body.path)+ response = FileDeleteResponse(success=success)+ return json.dumps(dataclasses.asdict(response))++ def update_file_or_directory(+ self,+ request: str,+ ) -> str:+ body = parse_raw(json.loads(request), FileUpdateRequest)+ success = self.file_system.update_file_or_directory(+ body.path, body.new_path+ )+ response = FileUpdateResponse(success=success)+ return json.dumps(dataclasses.asdict(response))+++def launch_pyodide_kernel(+ control_queue: asyncio.Queue[ControlRequest],+ completion_queue: asyncio.Queue[CompletionRequest],+ input_queue: asyncio.Queue[str],+ on_message: Callable[[KernelMessage], None],+ is_edit_mode: bool,+ configs: dict[CellId_t, CellConfig],+ app_metadata: AppMetadata,+) -> RestartableTask:+ LOGGER.debug("Launching kernel")+ del completion_queue++ # Create communication channels+ stream = PyodideStream(on_message, input_queue)+ stdout = PyodideStdout(stream)+ stderr = PyodideStderr(stream)+ stdin = PyodideStdin(stream) if is_edit_mode else None++ kernel = Kernel(+ cell_configs=configs,+ app_metadata=app_metadata,+ stream=stream,+ stdout=stdout,+ stderr=stderr,+ stdin=stdin,+ input_override=input_override,+ )+ initialize_context(+ kernel=kernel,+ stream=stream,+ virtual_files_supported=False,+ )++ if is_edit_mode:+ from marimo._output.formatters.formatters import register_formatters++ register_formatters()++ async def listen() -> None:+ while True:+ request = await control_queue.get()+ LOGGER.debug("received request %s", request)+ kernel.handle_message(request)++ return RestartableTask(listen)+++class RestartableTask:+ def __init__(self, coro: Callable[[], Any]):+ self.coro = coro+ self.task: Optional[asyncio.Task[Any]] = None+ self.stopped = False++ async def start(self) -> None:+ """Create a task that runs the coro."""+ while True:+ if self.stopped:+ break++ try:+ self.task = asyncio.create_task(self.coro())+ await self.task+ except asyncio.CancelledError:+ pass++ def stop(self) -> None:+ # Stop the task and set the stopped flag+ self.stopped = True+ assert self.task is not None+ self.task.cancel()++ def restart(self) -> None:+ # Cancel the current task, which will cause+ # the while loop to start a new task+ assert self.task is not None+ self.task.cancel()diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.pynew file mode 100644index 0000000000..c7129cc8fa--- /dev/null+++ b/marimo/_pyodide/streams.py@@ -0,0 +1,182 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+import sys+from typing import Any, Callable, Iterable, Optional++from marimo import _loggers+from marimo._ast.cell import CellId_t+from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.ops import CellOp+from marimo._messaging.streams import STD_STREAM_MAX_BYTES+from marimo._messaging.types import (+ KernelMessage,+ Stderr,+ Stdin,+ Stdout,+ Stream,+)++LOGGER = _loggers.marimo_logger()+++class PyodideStream(Stream):+ """A thread-safe wrapper around a pipe."""++ def __init__(+ self,+ pipe: Callable[[KernelMessage], None],+ input_queue: asyncio.Queue[str],+ cell_id: Optional[CellId_t] = None,+ ):+ self.pipe = pipe+ self.cell_id = cell_id+ self.input_queue = input_queue++ def write(self, op: str, data: dict[Any, Any]) -> None:+ self.pipe((op, data))+++class PyodideStdout(Stdout):+ encoding = sys.stdout.encoding+ errors = sys.stdout.errors+ _fileno: int | None = None++ def __init__(self, stream: Stream) -> None:+ self.stream = stream++ def writable(self) -> bool:+ return True++ def readable(self) -> bool:+ return False++ def seekable(self) -> bool:+ return False++ def write(self, data: str) -> int:+ assert self.stream.cell_id is not None+ if not isinstance(data, str):+ raise TypeError(+ "write() argument must be a str, not %s" % type(data).__name__+ )+ if sys.getsizeof(data) > STD_STREAM_MAX_BYTES:+ sys.stderr.write(+ "Warning: marimo truncated a very large console output.\n"+ )+ data = data[: int(STD_STREAM_MAX_BYTES)] + " ... "+ CellOp(+ cell_id=self.stream.cell_id,+ console=CellOutput(+ channel=CellChannel.STDOUT,+ mimetype="text/plain",+ data=data,+ ),+ ).broadcast(self.stream)+ return len(data)++ # Buffer type not available python < 3.12, hence type ignore+ def writelines(self, sequence: Iterable[str]) -> None: # type: ignore[override] # noqa: E501+ for line in sequence:+ self.write(line)+++class PyodideStderr(Stderr):+ encoding = sys.stderr.encoding+ errors = sys.stderr.errors+ _fileno: int | None = None++ def __init__(self, stream: Stream) -> None:+ self.stream = stream++ def writable(self) -> bool:+ return True++ def readable(self) -> bool:+ return False++ def seekable(self) -> bool:+ return False++ def write(self, data: str) -> int:+ assert self.stream.cell_id is not None+ if not isinstance(data, str):+ raise TypeError(+ "write() argument must be a str, not %s" % type(data).__name__+ )+ if sys.getsizeof(data) > STD_STREAM_MAX_BYTES:+ data = (+ "Warning: marimo truncated a very large console output.\n"+ + data[: int(STD_STREAM_MAX_BYTES)]+ + " ... "+ )++ CellOp(+ cell_id=self.stream.cell_id,+ console=CellOutput(+ channel=CellChannel.STDERR,+ mimetype="text/plain",+ data=data,+ ),+ ).broadcast(self.stream)+ return len(data)++ def writelines(self, sequence: Iterable[str]) -> None: # type: ignore[override] # noqa: E501+ for line in sequence:+ self.write(line)+++class PyodideStdin(Stdin):+ encoding = sys.stdin.encoding+ errors = sys.stdin.errors++ def __init__(self, stream: PyodideStream):+ self.stream = stream++ def writable(self) -> bool:+ return False++ def readable(self) -> bool:+ return True++ def _readline_with_prompt(self, prompt: str = "") -> str:+ """Read input from the standard in stream, with an optional prompt."""+ assert self.stream.cell_id is not None+ if not isinstance(prompt, str):+ raise TypeError(+ "prompt must be a str, not %s" % type(prompt).__name__+ )+ if sys.getsizeof(prompt) > STD_STREAM_MAX_BYTES:+ prompt = (+ "Warning: marimo truncated a very large console output.\n"+ + prompt[: int(STD_STREAM_MAX_BYTES)]+ + " ... "+ )++ CellOp(+ cell_id=self.stream.cell_id,+ console=CellOutput(+ channel=CellChannel.STDERR,+ mimetype="text/plain",+ data=prompt,+ ),+ ).broadcast(self.stream)++ loop = asyncio.get_event_loop()+ response = loop.run_until_complete(self.stream.input_queue.get())+ return response++ def readline(self, size: int | None = -1) -> str: # type: ignore[override] # noqa: E501+ # size only included for compatibility with sys.stdin.readline API;+ # we don't support it.+ del size+ return self._readline_with_prompt(prompt="")++ def readlines(self, hint: int | None = -1) -> list[str]: # type: ignore[override] # noqa: E501+ # Just an alias for readline.+ #+ # hint only included for compatibility with sys.stdin.readlines API;+ # we don't support it.+ del hint+ return self._readline_with_prompt(prompt="").split("\n")diff --git a/marimo/_runtime/cell_lifecycle_registry.py b/marimo/_runtime/cell_lifecycle_registry.pyindex 524a8b9c18..0491b99542 100644--- a/marimo/_runtime/cell_lifecycle_registry.py+++ b/marimo/_runtime/cell_lifecycle_registry.py@@ -22,6 +22,7 @@ class CellLifecycleRegistry:from marimo._runtime.context import get_contextctx = get_context()+cell_id = ctx.cell_idif cell_id is None:returndiff --git a/marimo/_runtime/context.py b/marimo/_runtime/context.pyindex 3871e2435c..fac7629a13 100644--- a/marimo/_runtime/context.py+++ b/marimo/_runtime/context.py@@ -54,6 +54,7 @@ class RuntimeContext:function_registry: FunctionRegistrycell_lifecycle_registry: CellLifecycleRegistryvirtual_file_registry: VirtualFileRegistry+ virtual_files_supported: boolstream: Stream_id_provider: Optional[IDProvider] = None@@ -99,8 +100,7 @@ _THREAD_LOCAL_CONTEXT = _ThreadLocalContext()def initialize_context(- kernel: Kernel,- stream: Stream,+ kernel: Kernel, stream: Stream, virtual_files_supported: bool = True) -> None:"""Initializes thread-local/session-specific context.@@ -120,6 +120,7 @@ def initialize_context(function_registry=FunctionRegistry(),cell_lifecycle_registry=CellLifecycleRegistry(),virtual_file_registry=VirtualFileRegistry(),+ virtual_files_supported=virtual_files_supported,stream=stream,)_THREAD_LOCAL_CONTEXT.initialize(runtime_context=runtime_context)diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 05777fdbf0..91cd55de8e 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -7,7 +7,6 @@ import dataclassesimport functoolsimport ioimport itertools-import multiprocessing as mpimport osimport signalimport sys@@ -15,6 +14,7 @@ import threadingimport timeimport tracebackfrom collections.abc import Iterable, Sequence+from multiprocessing import connectionfrom typing import Any, Callable, Iterator, Optionalfrom marimo import _loggers@@ -1079,6 +1079,36 @@ class Kernel:self.run(request.execution_requests)self.reset_ui_initializers()+ def handle_message(self, request: ControlRequest) -> None:+ """Handle a message from the client.+ The message is dispatched to the appropriate method based on its type.+ """+ if isinstance(request, CreationRequest):+ self.instantiate(request)+ CompletedRun().broadcast()+ elif isinstance(request, ExecuteMultipleRequest):+ self.run(request.execution_requests)+ CompletedRun().broadcast()+ elif isinstance(request, SetCellConfigRequest):+ self.set_cell_config(request)+ elif isinstance(request, SetUIElementValueRequest):+ self.set_ui_element_value(request)+ CompletedRun().broadcast()+ elif isinstance(request, FunctionCallRequest):+ status, ret = self.function_call_request(request)+ FunctionCallResult(+ function_call_id=request.function_call_id,+ return_value=ret,+ status=status,+ ).broadcast()+ CompletedRun().broadcast()+ elif isinstance(request, DeleteRequest):+ self.delete(request)+ elif isinstance(request, StopRequest):+ return None+ else:+ raise ValueError(f"Unknown request {request}")+def launch_kernel(control_queue: QueueType[ControlRequest],@@ -1098,7 +1128,7 @@ def launch_kernel(while n_tries < 100:try:pipe = TypedConnection[KernelMessage].of(- mp.connection.Client(socket_addr)+ connection.Client(socket_addr))breakexcept Exception:@@ -1214,34 +1244,12 @@ def launch_kernel(LOGGER.debug("kernel queue.get() failed %s", e)breakLOGGER.debug("received request %s", request)- if isinstance(request, CreationRequest):- kernel.instantiate(request)- CompletedRun().broadcast()- elif isinstance(request, ExecuteMultipleRequest):- kernel.run(request.execution_requests)- CompletedRun().broadcast()- elif isinstance(request, SetCellConfigRequest):- kernel.set_cell_config(request)- elif isinstance(request, SetUIElementValueRequest):- kernel.set_ui_element_value(request)- CompletedRun().broadcast()- elif isinstance(request, FunctionCallRequest):- status, ret = kernel.function_call_request(request)- FunctionCallResult(- function_call_id=request.function_call_id,- return_value=ret,- status=status,- ).broadcast()- CompletedRun().broadcast()- elif isinstance(request, DeleteRequest):- kernel.delete(request)- elif isinstance(request, StopRequest):+ if isinstance(request, StopRequest):break- else:- raise ValueError(f"Unknown request {request}")+ kernel.handle_message(request)- if stdout is not None and isinstance(stdout, ThreadSafeStdout):+ if stdout is not None:stdout._watcher.stop()- if stderr is not None and isinstance(stderr, ThreadSafeStderr):+ if stderr is not None:stderr._watcher.stop()get_context().virtual_file_registry.shutdown()diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.pyindex 6a2568599e..50226dafa0 100644--- a/marimo/_runtime/virtual_file.py+++ b/marimo/_runtime/virtual_file.py@@ -1,16 +1,20 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import base64import dataclasses+import mimetypesimport randomimport stringimport sysimport threadingfrom collections.abc import Iterablefrom multiprocessing import shared_memory-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, Optional, castfrom marimo import _loggers+from marimo._messaging.mimetypes import KnownMimeType+from marimo._output.utils import build_data_urlfrom marimo._runtime.cell_lifecycle_item import CellLifecycleItemif TYPE_CHECKING:@@ -25,7 +29,11 @@ _ALPHABET = string.ascii_letters + string.digitsdef random_filename(ext: str) -> str:# adapted from: https://stackoverflow.com/questions/13484726/safe-enough-8-character-short-unique-random-string # noqa: E501# TODO(akshayka): should callers redraw if they get a collision?- tid = str(threading.get_native_id())+ try:+ tid = str(threading.get_native_id())+ except AttributeError:+ # get_native_id() not implemented in pyodide/WASM+ tid = "0"basename = tid + "-" + "".join(random.choices(_ALPHABET, k=8))return f"{basename}.{ext}"@@ -37,7 +45,11 @@ class VirtualFile:buffer: bytesdef __init__(- self, filename: str, buffer: bytes, url: Optional[str] = None+ self,+ filename: str,+ buffer: bytes,+ url: Optional[str] = None,+ as_data_url: bool = False,) -> None:self.filename = filenameself.buffer = buffer@@ -46,7 +58,16 @@ class VirtualFile:# many bytes to read.# Also, URL is intentionally relative, so it can be resolved with# different base URLs.- self.url = url or f"./@file/{len(buffer)}-{filename}"+ if not as_data_url:+ self.url = url or f"./@file/{len(buffer)}-{filename}"+ else:+ self.url = url or build_data_url(+ mimetype=cast(+ KnownMimeType,+ mimetypes.guess_type(self.filename)[0],+ ),+ data=base64.b64encode(buffer),+ )@staticmethoddef from_external_url(url: str) -> VirtualFile:@@ -97,8 +118,12 @@ class VirtualFileLifecycleItem(CellLifecycleItem):"Failed to add virtual file to registry. ""This is a bug in marimo. Please file an issue.")- self._virtual_file = VirtualFile(filename, self.buffer)- context.virtual_file_registry.add(self._virtual_file)+ self._virtual_file = VirtualFile(+ filename,+ self.buffer,+ as_data_url=not context.virtual_files_supported,+ )+ context.virtual_file_registry.add(self._virtual_file, context)def dispose(self, context: "RuntimeContext", deletion: bool) -> bool:# Remove the file if the refcount is 0, or if the cell is being@@ -164,7 +189,12 @@ class VirtualFileRegistry:return self.registry[filename].refcountreturn 0- def add(self, virtual_file: VirtualFile) -> None:+ def add(+ self, virtual_file: VirtualFile, context: "RuntimeContext"+ ) -> None:+ if not context.virtual_files_supported:+ return+key = virtual_file.filenameif key in self.registry:LOGGER.debug(diff --git a/marimo/_server/api/status.py b/marimo/_server/api/status.pyindex e6bd7df4f2..a53cb1c045 100644--- a/marimo/_server/api/status.py+++ b/marimo/_server/api/status.py@@ -2,6 +2,7 @@from __future__ import annotationsfrom enum import IntEnum+from typing import Optionalclass HTTPStatus(IntEnum):@@ -12,3 +13,13 @@ class HTTPStatus(IntEnum):METHOD_NOT_ALLOWED = 405UNSUPPORTED_MEDIA_TYPE = 415SERVER_ERROR = 500+++class HTTPException(Exception):+ def __init__(+ self,+ status_code: int,+ detail: Optional[str] = None,+ ) -> None:+ self.status_code = status_code+ self.detail = detaildiff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex 603ffcac32..7d2e18b098 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -4,14 +4,12 @@ from __future__ import annotationsimport osfrom typing import Any, Dict, Optional-from starlette.exceptions import HTTPException-from marimo import _loggersfrom marimo._ast import codegenfrom marimo._ast.app import App, InternalAppfrom marimo._ast.cell import CellConfigfrom marimo._runtime.layout.layout import LayoutConfig, save_layout_config-from marimo._server.api.status import HTTPStatus+from marimo._server.api.status import HTTPException, HTTPStatusfrom marimo._server.models.models import (SaveRequest,)@@ -36,6 +34,54 @@ class AppFileManager:"""Reload the app from the file."""self.app = self._load_app(self.path)+ def _is_same_path(self, filename: str) -> bool:+ if self.filename is None:+ return False+ return os.path.abspath(self.filename) == os.path.abspath(filename)++ def _assert_path_does_not_exist(self, filename: str) -> None:+ if os.path.exists(filename):+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="File {0} already exists".format(filename),+ )++ def _assert_path_is_the_same(self, filename: str) -> None:+ if self.filename is not None and not self._is_same_path(filename):+ raise HTTPException(+ status_code=HTTPStatus.BAD_REQUEST,+ detail="Save handler cannot rename files.",+ )++ def _create_file(+ self,+ filename: str,+ contents: str = "",+ header_comments: Optional[str] = None,+ ) -> None:+ try:+ with open(filename, "w", encoding="utf-8") as f:+ if header_comments:+ f.write(header_comments.rstrip() + "\n\n")+ f.write(contents)+ except Exception as err:+ raise HTTPException(+ status_code=HTTPStatus.SERVER_ERROR,+ detail="Failed to save file {0}".format(filename),+ ) from err++ def _rename_file(self, new_filename: str) -> None:+ assert self.filename is not None+ try:+ os.rename(self.filename, new_filename)+ except Exception as err:+ raise HTTPException(+ status_code=HTTPStatus.SERVER_ERROR,+ detail="Failed to rename from {0} to {1}".format(+ self.filename, new_filename+ ),+ ) from err+@staticmethoddef _load_app(path: Optional[str]) -> InternalApp:"""Read the app from the file."""@@ -48,41 +94,21 @@ class AppFileManager:config=CellConfig(),)return empty_app-return InternalApp(app)def rename(self, new_filename: str) -> None:"""Rename the file."""-new_filename = canonicalize_filename(new_filename)- if self.filename == new_filename:+ if self._is_same_path(new_filename):return- if os.path.exists(new_filename):- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="File {0} already exists".format(new_filename),- )++ self._assert_path_does_not_exist(new_filename)+if self.filename is not None:- try:- os.rename(self.filename, new_filename)- except Exception as err:- raise HTTPException(- status_code=HTTPStatus.SERVER_ERROR,- detail="Failed to rename from {0} to {1}".format(- self.filename, new_filename- ),- ) from err+ self._rename_file(new_filename)else:- try:- # create a file named `new_filename`- with open(new_filename, "w") as _:- pass- except Exception as err:- raise HTTPException(- status_code=HTTPStatus.SERVER_ERROR,- detail="Failed to create file {0}".format(new_filename),- ) from err+ self._create_file(new_filename)self.filename = new_filenameself.path = self._get_file_path(new_filename)@@ -102,7 +128,6 @@ class AppFileManager:# TODO(akshayka): Only change the `app = marimo.App` line (at top level# of file), instead of overwriting the whole file.new_config = self.app.update_config(config)-if self.filename is not None:# Try to save the app under the name `self.filename`contents = codegen.generate_filecontents(@@ -111,14 +136,7 @@ class AppFileManager:cell_configs=list(self.app.cell_manager.configs()),config=new_config,)- try:- with open(self.filename, "w", encoding="utf-8") as f:- f.write(contents)- except Exception as e:- raise HTTPException(- status_code=HTTPStatus.SERVER_ERROR,- detail="Failed to save file: {0}".format(str(e)),- ) from e+ self._create_file(self.filename, contents)def save(self, request: SaveRequest) -> None:"""Save the current app."""@@ -138,48 +156,33 @@ class AppFileManager:configs=configs,)- if self.filename is not None and self.filename != filename:+ if self.filename is not None and not self._is_same_path(filename):raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,detail="Save handler cannot rename files.",)- elif self.filename is None and os.path.exists(filename):- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail="File {0} already exists".format(filename),- )- else:- # save layout- if layout is not None:- app_dir = os.path.dirname(filename)- app_name = os.path.basename(filename)- layout_filename = save_layout_config(- app_dir, app_name, LayoutConfig(**layout)- )- self.app.update_config({"layout_file": layout_filename})-- # try to save the app under the name `filename`- contents = codegen.generate_filecontents(- codes,- names,- cell_configs=configs,- config=self.app.config,++ # save layout+ if layout is not None:+ app_dir = os.path.dirname(filename)+ app_name = os.path.basename(filename)+ layout_filename = save_layout_config(+ app_dir, app_name, LayoutConfig(**layout))+ self.app.update_config({"layout_file": layout_filename})+ # try to save the app under the name `filename`+ contents = codegen.generate_filecontents(+ codes,+ names,+ cell_configs=configs,+ config=self.app.config,+ )+ LOGGER.debug("Saving app to %s", filename)+ header_comments = codegen.get_header_comments(filename)+ self._create_file(filename, contents, header_comments)- LOGGER.debug("Saving app to %s", filename)- try:- header_comments = codegen.get_header_comments(filename)- with open(filename, "w", encoding="utf-8") as f:- if header_comments:- f.write(header_comments.rstrip() + "\n\n")- f.write(contents)- except Exception as e:- raise HTTPException(- status_code=HTTPStatus.SERVER_ERROR,- detail="Failed to save file: {0}".format(str(e)),- ) from e- if self.filename is None:- self.rename(filename)+ if self.filename is None:+ self.rename(filename)def read_file(self) -> str:"""Read the contents of the file."""diff --git a/marimo/_server/main.py b/marimo/_server/main.pyindex 387a53bc5b..41d11d9ff3 100644--- a/marimo/_server/main.py+++ b/marimo/_server/main.py@@ -16,6 +16,7 @@ from marimo._server.api.middleware import (ValidateServerTokensMiddleware,)from marimo._server.api.router import ROUTES+from marimo._server.api.status import HTTPException as MarimoHTTPException# Convert exceptions to JSON responses@@ -25,6 +26,10 @@ async def handle_error(request: Request, response: Any) -> Any:return JSONResponse({"detail": response.detail}, status_code=response.status_code)+ if isinstance(response, MarimoHTTPException):+ return JSONResponse(+ {"detail": response.detail}, status_code=response.status_code+ )if isinstance(response, TypeError):return JSONResponse({"detail": str(response)}, status_code=500)if isinstance(response, Exception):diff --git a/marimo/_utils/typed_connection.py b/marimo/_utils/typed_connection.pyindex ed478b04c9..84173c7f85 100644--- a/marimo/_utils/typed_connection.py+++ b/marimo/_utils/typed_connection.py@@ -1,15 +1,20 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from multiprocessing.connection import Connection-from typing import Generic, TypeVar+from typing import TYPE_CHECKING, Generic, TypeVar++if TYPE_CHECKING:+ from multiprocessing.connection import ConnectionT = TypeVar("T")-class TypedConnection(Generic[T], Connection):+class TypedConnection(Generic[T]):"""Wrapper around a connection with strong typing."""+ def __init__(self, delegate: Connection):+ self._delegate = delegate+@classmethoddef of(cls,@@ -19,7 +24,20 @@ class TypedConnection(Generic[T], Connection):return delegate # type: ignore[return-value]def send(self, obj: T) -> None:- super().send(obj)+ self._delegate.send(obj)def recv(self) -> T:- return super().recv() # type: ignore[no-any-return]+ return self._delegate.recv() # type: ignore[no-any-return]++ def poll(self) -> bool:+ return self._delegate.poll()++ def fileno(self) -> int:+ return self._delegate.fileno()++ @property+ def closed(self) -> bool:+ return self._delegate.closed++ def close(self) -> None:+ self._delegate.close()diff --git a/pyodide/DOCS.md b/pyodide/DOCS.mdnew file mode 100644index 0000000000..8f8fcdd16c--- /dev/null+++ b/pyodide/DOCS.md@@ -0,0 +1,8 @@+# marimo + pyodide++```bash+python3 pyodide/build_and_serve.py+# then in another terminal+cd frontend+PYODIDE=true pnpm dev+```diff --git a/pyodide/build_and_serve.py b/pyodide/build_and_serve.pynew file mode 100644index 0000000000..9e77bac743--- /dev/null+++ b/pyodide/build_and_serve.py@@ -0,0 +1,67 @@+import http.server+import os+import socketserver+import subprocess+import threading+from posixpath import join++from watchdog.events import PatternMatchingEventHandler+from watchdog.observers import Observer+++class CORSHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):+ def end_headers(self):+ self.send_header("Access-Control-Allow-Origin", "*")+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")+ self.send_header(+ "Access-Control-Allow-Headers", "X-Requested-With, Content-Type"+ )+ super().end_headers()++ def do_OPTIONS(self):+ self.send_response(200, "ok")+ self.end_headers()+++class WheelBuilderHandler(PatternMatchingEventHandler):+ patterns = ["*.py"] # Watch for changes in Python files++ def on_any_event(self, event):+ print(f"Change detected: {event.src_path}")+ print("Building wheel...")+ subprocess.run(["python3", "-m", "build"])+ print("Wheel built successfully.")+++def serve():+ with socketserver.TCPServer(("", 8000), CORSHTTPRequestHandler) as httpd:+ httpd.allow_reuse_address = True+ print("Serving at http://localhost:8000")+ try:+ httpd.serve_forever()+ except KeyboardInterrupt:+ pass+ httpd.server_close()+ print("Server stopped.")+++cwd = os.getcwd()++if __name__ == "__main__":+ # Start the HTTP server in a separate thread+ threading.Thread(target=serve, daemon=True).start()++ # Set up the watchdog observer to watch the current directory+ observer = Observer()+ path = join(cwd, "marimo")+ observer.schedule(WheelBuilderHandler(), path=path, recursive=True)+ observer.start()++ print("Watching for changes. Press Ctrl+C to stop.")+ print(f"Watching directory: {path}")+ try:+ while True:+ observer.join(1)+ except KeyboardInterrupt:+ observer.stop()+ observer.join()diff --git a/scripts/buildfrontend.sh b/scripts/buildfrontend.shindex 9f6126e6d7..d2b7aea90a 100755--- a/scripts/buildfrontend.sh+++ b/scripts/buildfrontend.sh@@ -7,6 +7,7 @@ if pnpm turbo build; thenecho "Copying new static files..."mkdir -p ../marimo/_static/cp -R dist/* ../marimo/_static/+ rm -rf ../marimo/_static/files/wasm-intro.pyecho "Compilation succeeded.\n"elseecho "Frontend compilation failed.\n"diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex dffa35d3f4..64ba76c15b 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -2,8 +2,10 @@import osimport random+import pytestfrom starlette.testclient import TestClient+from marimo._server.api.status import HTTPExceptionfrom tests._server.conftest import get_session_managerfrom tests._server.mocks import with_session@@ -179,24 +181,27 @@ def test_save_with_invalid_file(client: TestClient) -> None:@with_session(SESSION_ID)def test_save_file_cannot_rename(client: TestClient) -> None:- response = client.post(- "/api/kernel/save",- headers=HEADERS,- json={- "cell_ids": ["1"],- "filename": "random_filename.py",- "codes": ["import marimo as mo"],- "names": ["my_cell"],- "configs": [- {- "hideCode": True,- "disabled": False,- }- ],- },- )- assert response.status_code == 400- assert "cannot rename" in response.text+ with pytest.raises(HTTPException) as response:+ client.post(+ "/api/kernel/save",+ headers=HEADERS,+ json={+ "cell_ids": ["1"],+ "filename": "random_filename.py",+ "codes": ["import marimo as mo"],+ "names": ["my_cell"],+ "configs": [+ {+ "hideCode": True,+ "disabled": False,+ }+ ],+ },+ )+ assert response.value.status_code == 400+ assert (+ response.value.detail and "cannot rename" in response.value.detail+ )@with_session(SESSION_ID)diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.pyindex 39a829a515..ecc7f2a623 100644--- a/tests/_server/test_file_manager.py+++ b/tests/_server/test_file_manager.py@@ -3,10 +3,9 @@ import tempfilefrom typing import Generatorimport pytest-from starlette.exceptions import HTTPExceptionfrom marimo._ast.cell import CellConfig-from marimo._server.api.status import HTTPStatus+from marimo._server.api.status import HTTPException, HTTPStatusfrom marimo._server.file_manager import AppFileManagerfrom marimo._server.models.models import SaveRequest@@ -64,9 +63,9 @@ def test_rename_to_existing_filename(app_file_manager: AppFileManager) -> None:with open(existing_filename, "w") as f:f.write("This is a test file.")try:- app_file_manager.rename(existing_filename)- except HTTPException as e:- assert e.status_code == HTTPStatus.BAD_REQUEST+ with pytest.raises(HTTPException) as e:+ app_file_manager.rename(existing_filename)+ assert e.value == HTTPStatus.BAD_REQUESTfinally:os.remove(existing_filename)@@ -147,8 +146,8 @@ def test_save_existing_filename(app_file_manager: AppFileManager) -> None:def test_save_successful(app_file_manager: AppFileManager) -> None:save_request.filename = app_file_manager.filename or ""- app_file_manager.save(save_request)try:+ app_file_manager.save(save_request)assert os.path.exists(save_request.filename)finally:os.remove(save_request.filename)