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
Tweaks for islands off Vite (#1214)
Dylan Madisettica63e9e5ac27
diff --git a/frontend/src/core/dom/marimo-tag.ts b/frontend/src/core/dom/marimo-tag.tsindex df95660476..cd44e3565d 100644--- a/frontend/src/core/dom/marimo-tag.ts+++ b/frontend/src/core/dom/marimo-tag.ts@@ -1,6 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { assertExists } from "@/utils/assertExists";import { invariant } from "@/utils/invariant";+import { isIslands } from "@/core/islands/utils";interface MarimoSettings {getMarimoVersion: () => string;@@ -31,9 +32,13 @@ const domBasedMarimoSettings: MarimoSettings = {},};-// We don't control the DOM so we need to use a different method to get the values+// We have limited access to the DOM, so defaults are provided.const islandsBasedMarimoSettings: MarimoSettings = {getMarimoVersion: () => {+ if (import.meta.env.VITE_MARIMO_VERSION === undefined) {+ // Version set by export, but can be overridden by ENV.+ return getMarimoDOMValue("marimo-version", "version");+ }assertExists(import.meta.env.VITE_MARIMO_VERSION);return import.meta.env.VITE_MARIMO_VERSION;},@@ -51,15 +56,33 @@ const islandsBasedMarimoSettings: MarimoSettings = {},};+function getMarimoSettingLookup<T extends keyof MarimoSettings>(+ settingName: T,+): () => ReturnType<MarimoSettings[T]> {+ return () => {+ // DOM isn't accessible at time of lookup, so defer to callback+ const result = isIslands()+ ? islandsBasedMarimoSettings[settingName]()+ : domBasedMarimoSettings[settingName]();+ return result as ReturnType<MarimoSettings[T]>;+ };+}++const MarimoSettingsWrapper: MarimoSettings = {+ getMarimoVersion: getMarimoSettingLookup("getMarimoVersion"),+ getMarimoServerToken: getMarimoSettingLookup("getMarimoServerToken"),+ getMarimoAppConfig: getMarimoSettingLookup("getMarimoAppConfig"),+ getMarimoUserConfig: getMarimoSettingLookup("getMarimoUserConfig"),+ getMarimoCode: getMarimoSettingLookup("getMarimoCode"),+};+const {getMarimoVersion,getMarimoServerToken,getMarimoAppConfig,getMarimoUserConfig,getMarimoCode,-} = import.meta.env.VITE_MARIMO_ISLANDS- ? islandsBasedMarimoSettings- : domBasedMarimoSettings;+} = MarimoSettingsWrapper;export {getMarimoVersion,diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.tsindex c525700dda..f9520f052c 100644--- a/frontend/src/core/islands/bridge.ts+++ b/frontend/src/core/islands/bridge.ts@@ -9,13 +9,14 @@ import {} from "../network/types";import { Deferred } from "@/utils/Deferred";import { getMarimoVersion } from "../dom/marimo-tag";-import { getWorkerRPC } from "./rpc";+import { getWorkerRPC } from "@/core/pyodide/rpc";import { OperationMessage } from "../kernel/messages";import { JsonString } from "@/utils/json/base64";-import InlineWorker from "./worker/worker.ts?worker&inline";import { CellId } from "@/core/cells/ids";import { throwNotImplemented } from "@/utils/functions";-import { isIslands } from "@/core/islands/utils";+import type { WorkerSchema } from "./worker/worker";++import { createMarimoFile, parseMarimoIslandApps } from "./parse";export class IslandsPyodideBridge implements RunRequests, EditRequests {/**@@ -29,7 +30,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {return IslandsPyodideBridge._instance;}- private rpc: ReturnType<typeof getWorkerRPC>;+ private rpc: ReturnType<typeof getWorkerRPC<WorkerSchema>>;private messageConsumer:| ((message: JsonString<OperationMessage>) => void)| undefined;@@ -37,17 +38,39 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {public initialized = new Deferred<void>();private constructor() {- // Create a worker, must be inline to work with CORS restrictions- const worker = new InlineWorker({- // Pass the version to the worker- /* @vite-ignore */- name: isIslands() ? getMarimoVersion() : "dev",+ // TODO: abstract out into a worker constructor+ const js = `import ${JSON.stringify(new URL("worker/worker.ts", import.meta.url))}`;+ const blob = new Blob([js], { type: "application/javascript" });+ const objURL = URL.createObjectURL(blob);+ const worker = new Worker(+ // eslint-disable-next-line unicorn/relative-url-style+ objURL,+ {+ type: "module",+ // Pass the version to the worker+ /* @vite-ignore */+ name: getMarimoVersion(),+ },+ );++ worker.addEventListener("error", (e) => {+ // Fallback to cleaning up created object URL+ URL.revokeObjectURL(objURL);});// Create the RPC- this.rpc = getWorkerRPC(worker);+ this.rpc = getWorkerRPC<WorkerSchema>(worker);// Listeners+ this.rpc.addMessageListener("ready", () => {+ const apps = parseMarimoIslandApps();+ for (const app of apps) {+ this.startSession({+ code: createMarimoFile(app),+ appId: app.id,+ });+ }+ });this.rpc.addMessageListener("initialized", () => {this.initialized.resolve();});diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.tsindex 398e9eae82..112d66a3c4 100644--- a/frontend/src/core/islands/main.ts+++ b/frontend/src/core/islands/main.ts@@ -3,7 +3,6 @@ import "./islands.css";import "iconify-icon";import { initializePlugins } from "@/plugins/plugins";-import { createMarimoFile, parseMarimoIslandApps } from "./parse";import { IslandsPyodideBridge } from "./bridge";import { store } from "../state/jotai";import {@@ -49,17 +48,6 @@ export async function initialize() {// This will display all the static HTML content.initializePlugins();- // Find all "applications" which consist of snippets of code that are inside <marimo-island> tags.- const apps = parseMarimoIslandApps();-- // Initialize each app- for (const app of apps) {- await IslandsPyodideBridge.INSTANCE.startSession({- code: createMarimoFile(app),- appId: app.id,- });- }-const actions = createNotebookActions((action) => {store.set(notebookAtom, (state) => notebookReducer(state, action));});diff --git a/frontend/src/core/islands/rpc.ts b/frontend/src/core/islands/rpc.tsdeleted file mode 100644index 4c110f1e06..0000000000--- a/frontend/src/core/islands/rpc.ts+++ /dev/null@@ -1,29 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */-import { createWorkerTransport, createRPC, type RPCSchema } from "rpc-anywhere";--import type { WorkerSchema } from "./worker/worker";-import { Logger } from "../../utils/Logger";-import { TRANSPORT_ID } from "../pyodide/worker/constants";--export type ParentSchema = RPCSchema<{- messages: {- consumerReady: {};- };-}>;--export function getWorkerRPC(worker: Worker) {- return createRPC<ParentSchema, WorkerSchema>({- transport: createWorkerTransport(worker, {- transportId: TRANSPORT_ID,- }),- maxRequestTime: 20_000, // 20 seconds- _debugHooks: {- onSend: (message) => {- Logger.debug("[rpc] Parent -> Worker", message);- },- onReceive: (message) => {- Logger.debug("[rpc] Worker -> Parent", message);- },- },- });-}diff --git a/frontend/src/core/islands/utils.ts b/frontend/src/core/islands/utils.tsindex 810ce2849f..2127815712 100644--- a/frontend/src/core/islands/utils.ts+++ b/frontend/src/core/islands/utils.ts@@ -1,4 +1,12 @@/* Copyright 2024 Marimo. All rights reserved. */+export function isIslands() {- return import.meta.env.VITE_MARIMO_ISLANDS === true;+ // importing "@/core/mode" has the expectation of a valid mode,+ // which is not the case during testing.+ const tag = document.querySelector("marimo-mode");+ const initialMode =+ tag === null || !(tag instanceof HTMLElement) ? null : tag.dataset.mode;+ return (+ import.meta.env.VITE_MARIMO_ISLANDS === true || initialMode === "island"+ );}diff --git a/frontend/src/core/mode.ts b/frontend/src/core/mode.tsindex 4487b087ea..5e86e93439 100644--- a/frontend/src/core/mode.ts+++ b/frontend/src/core/mode.ts@@ -11,8 +11,9 @@ import { assertNever } from "@/utils/assertNever";* - `edit`: A user is editing the notebook. Can switch to present mode.* - `present`: A user is presenting the notebook, it looks like read mode but with some editing features. Cannot switch to present mode.* - `home`: A user is in the home page.+ * - `island`: A user is interacting with marimo from an external application.*/-export type AppMode = "read" | "edit" | "present" | "home";+export type AppMode = "read" | "edit" | "present" | "home" | "island";export function getInitialAppMode(): AppMode {const tag = document.querySelector("marimo-mode");@@ -28,6 +29,8 @@ export function getInitialAppMode(): AppMode {return "edit";case "home":return "home";+ case "island":+ return "island";case "present":throw new Error("internal-error: present mode is not supported");case undefined:diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.tsindex 315f581564..692fedd1c2 100644--- a/frontend/src/core/pyodide/bridge.ts+++ b/frontend/src/core/pyodide/bridge.ts@@ -40,11 +40,12 @@ import { API } from "../network/api";import { RuntimeState } from "@/core/kernel/RuntimeState";import { parseUserConfig } from "../config/config-schema";import { throwNotImplemented } from "@/utils/functions";+import type { WorkerSchema } from "./worker/worker";export class PyodideBridge implements RunRequests, EditRequests {static INSTANCE = new PyodideBridge();- private rpc!: ReturnType<typeof getWorkerRPC>;+ private rpc!: ReturnType<typeof getWorkerRPC<WorkerSchema>>;private interruptBuffer?: Uint8Array;private messageConsumer: ((message: string) => void) | undefined;@@ -65,7 +66,7 @@ export class PyodideBridge implements RunRequests, EditRequests {);// Create the RPC- this.rpc = getWorkerRPC(worker);+ this.rpc = getWorkerRPC<WorkerSchema>(worker);// Listenersthis.rpc.addMessageListener("ready", () => {diff --git a/frontend/src/core/pyodide/rpc.ts b/frontend/src/core/pyodide/rpc.tsindex 15c9bfdda2..e1ffbc4cc5 100644--- a/frontend/src/core/pyodide/rpc.ts+++ b/frontend/src/core/pyodide/rpc.ts@@ -1,7 +1,11 @@/* Copyright 2024 Marimo. All rights reserved. */-import { createWorkerTransport, createRPC, type RPCSchema } from "rpc-anywhere";+import {+ createWorkerTransport,+ createRPC,+ type RPCSchema,+ type RPCOptions,+} from "rpc-anywhere";-import type { WorkerSchema } from "./worker/worker";import { TRANSPORT_ID } from "./worker/constants";import { Logger } from "@/utils/Logger";@@ -11,7 +15,7 @@ export type ParentSchema = RPCSchema<{};}>;-export function getWorkerRPC(worker: Worker) {+export function getWorkerRPC<WorkerSchema extends RPCSchema>(worker: Worker) {return createRPC<ParentSchema, WorkerSchema>({transport: createWorkerTransport(worker, {transportId: TRANSPORT_ID,@@ -25,5 +29,5 @@ export function getWorkerRPC(worker: Worker) {Logger.debug("[rpc] Worker -> Parent", message);},},- });+ } as RPCOptions<ParentSchema, WorkerSchema>);}diff --git a/frontend/src/core/pyodide/worker/getMarimoWheel.ts b/frontend/src/core/pyodide/worker/getMarimoWheel.tsindex 3756b2660a..b9f01c09ed 100644--- a/frontend/src/core/pyodide/worker/getMarimoWheel.ts+++ b/frontend/src/core/pyodide/worker/getMarimoWheel.ts@@ -4,7 +4,7 @@ export function getMarimoWheel(version: string) {return "marimo >= 0.3.0";}if (version === "local") {- return "http://localhost:8000/dist/marimo-0.4.2-py3-none-any.whl";+ return "http://localhost:8000/dist/marimo-0.4.4-py3-none-any.whl";}if (version === "latest") {return "marimo";diff --git a/marimo/_islands/island_generator.py b/marimo/_islands/island_generator.pyindex a8c2f97d9a..51be8c15d8 100644--- a/marimo/_islands/island_generator.py+++ b/marimo/_islands/island_generator.py@@ -1,14 +1,17 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import jsonfrom textwrap import dedent-from typing import TYPE_CHECKING, List, Optional, cast+from typing import TYPE_CHECKING, List, Optional, Union, castfrom marimo import __version__, _loggersfrom marimo._ast.app import App, InternalAppfrom marimo._ast.cell import Cell, CellConfigfrom marimo._ast.compiler import compile_cell+from marimo._messaging.cell_output import CellOutputfrom marimo._output.utils import uri_encode_component+from marimo._plugins.stateless.json_output import json_outputif TYPE_CHECKING:from marimo._server.sessions import Session@@ -23,13 +26,33 @@ class MarimoIslandStub:self._code = codeself._internal_app: Optional[InternalApp] = Noneself._session: Optional[Session] = None+ self._output: Optional[CellOutput] = None++ @property+ def output(self) -> Optional[CellOutput]:+ # Leave output accessible for direct use for non-interactive cases e.g.+ # pdf.+ if self._output is None:+ assert (+ self._session is not None+ ), "You must call build() before rendering"+ assert (+ self._internal_app is not None+ ), "You must call build() accessing output"+ outputs = self._session.session_view.get_cell_outputs(+ [self._cell_id]+ )+ self._output = outputs.get(self._cell_id, None)+ return self._output@propertydef code(self) -> str:return self._codedef render(- self, include_code: bool = True, include_output: bool = True+ self,+ include_code: bool = True,+ include_output: bool = True,) -> str:"""Render the HTML island code for the cell.@@ -43,18 +66,10 @@ class MarimoIslandStub:- str: The HTML code."""- assert (- self._internal_app is not None- ), "You must call build() before rendering"- assert (- self._session is not None- ), "You must call build() before rendering"-if include_code is False and include_output is False:raise ValueError("You must include either code or output")- outputs = self._session.session_view.get_cell_outputs([self._cell_id])- output = outputs.get(self._cell_id, None)+ output = handle_mimetypes(self.output) if self.output else None# Cell may not have output# (e.g. imports, but still needs to be included)@@ -66,7 +81,7 @@ class MarimoIslandStub:data-cell-id="{self._cell_id}"><marimo-cell-output>- {output.data if output and include_output else ""}+ {output if output and include_output else ""}</marimo-cell-output><marimo-cell-code hidden>{uri_encode_component(self.code) if include_code else ""}@@ -127,16 +142,20 @@ class MarimoIslandGenerator:def add_code(self,code: str,+ raw: bool = False,) -> MarimoIslandStub:"""Add a code cell to the app.*Args:*- code (str): The code to add to the app.+ - raw (bool): Handled the code unprocessed or formatted."""+ if not raw:+ code = dedent(code)cell_id = self._app.cell_manager.create_cell_id()- cell_impl = compile_cell(dedent(code), cell_id)+ cell_impl = compile_cell(code, cell_id)cell_impl.configure(CellConfig(disabled=False, hide_code=False))cell = Cell(_name="__", _cell=cell_impl)@@ -184,7 +203,7 @@ class MarimoIslandGenerator:self,*,version_override: str = __version__,- _development_url: bool = False,+ _development_url: Union[str | bool] = False,) -> str:"""Render the header for the app.@@ -220,10 +239,16 @@ class MarimoIslandGenerator:integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"crossorigin="anonymous"/>++ <marimo-version data-version="{version_override}" hidden="">+ </marimo-version>+ <marimo-mode data-mode="island" hidden=""></marimo-mode>""".strip()if _development_url:base_url = "http://localhost:5174"+ if isinstance(_development_url, str):+ base_url = _development_urlreturn dedent(f"""<script@@ -249,3 +274,17 @@ class MarimoIslandGenerator:def remove_empty_lines(text: str) -> str:return "\n".join([line for line in text.split("\n") if line.strip() != ""])+++def handle_mimetypes(output: CellOutput) -> str:+ data = output.data+ if not isinstance(data, str):+ return f"{data}"+ mimetype = output.mimetype+ # Since raw data, without wrapping in an image tag, this is just a huge+ # blob.+ if mimetype.startswith("image/"):+ data = f"<img src='{data}'/>"+ elif mimetype == "application/json":+ data = f"{json_output(json.loads(data))}"+ return datadiff --git a/tests/_islands/snapshots/header.txt b/tests/_islands/snapshots/header.txtindex a53b19bfa1..3afce503e6 100644--- a/tests/_islands/snapshots/header.txt+++ b/tests/_islands/snapshots/header.txt@@ -16,4 +16,8 @@href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"crossorigin="anonymous"-/>\ No newline at end of file+/>++<marimo-version data-version="0.0.0" hidden="">+</marimo-version>+<marimo-mode data-mode="island" hidden=""></marimo-mode>\ No newline at end of filediff --git a/tests/_islands/snapshots/islan d-no-code.txt b/tests/_islands/snapshots/island-no-code.txtsimilarity index 100%rename from tests/_islands/snapshots/islan d-no-code.txtrename to tests/_islands/snapshots/island-no-code.txtdiff --git a/tests/_islands/test_island_generator.py b/tests/_islands/test_island_generator.pyindex 8770aff443..00bc87208c 100644--- a/tests/_islands/test_island_generator.py+++ b/tests/_islands/test_island_generator.py@@ -3,7 +3,11 @@ from __future__ import annotationsimport pytestfrom marimo import __version__-from marimo._islands.island_generator import MarimoIslandGenerator+from marimo._islands.island_generator import (+ MarimoIslandGenerator,+ handle_mimetypes,+)+from marimo._messaging.cell_output import CellChannel, CellOutputfrom tests.mocks import snapshottersnapshot = snapshotter(__file__)@@ -54,7 +58,7 @@ async def test_render():# Check if render works after build() is calledsnapshot("island.txt", block2.render())- snapshot("islan d-no-code.txt", block2.render(include_code=False))+ snapshot("island-no-code.txt", block2.render(include_code=False))snapshot("island-no-output.txt", block2.render(include_output=False))@@ -68,3 +72,21 @@ async def test_render_head():snapshot("header.txt", generator.render_head().replace(__version__, "0.0.0"))+++async def test_handle_image_mimetype():+ small_image = CellOutput(+ data="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",+ mimetype="image/gif",+ channel=CellChannel.OUTPUT,+ )+ assert handle_mimetypes(small_image).startswith("<img")+++async def test_handle_json_mimetype():+ small_image = CellOutput(+ data="[1, 2, 3]",+ mimetype="application/json",+ channel=CellChannel.OUTPUT,+ )+ assert handle_mimetypes(small_image).startswith("<marimo-json")