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
chore: improve wasm development, e2e test (#1323)
Myles Scolnick9452fbb5ce7c
diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.ymlindex a421bae915..80129ce4ce 100644--- a/.github/workflows/playwright.yml+++ b/.github/workflows/playwright.yml@@ -68,6 +68,7 @@ jobs:run: |python -m pip install --upgrade pippip install .+ echo "MARIMO_VERSION=$(marimo --version)" >> $GITHUB_ENV- name: 🎭 Get installed Playwright versionid: playwright-version@@ -93,6 +94,8 @@ jobs:- name: 🎭 Run Playwright testsworking-directory: ./frontendrun: npx playwright test+ env:+ VITE_MARIMO_VERSION: ${{ env.MARIMO_VERSION }}- name: ☁️ Google Authuses: google-github-actions/auth@v1diff --git a/frontend/e2e-tests/helper.ts b/frontend/e2e-tests/helper.tsindex 95ae50216d..eaca0a1f98 100644--- a/frontend/e2e-tests/helper.ts+++ b/frontend/e2e-tests/helper.ts@@ -122,9 +122,11 @@ export async function exportAsHTMLAndTakeScreenshot(page: Page) {await takeScreenshot(exportPage, path);// Toggle code- await exportPage.getByTestId("show-code").click();- // wait 100ms for the code to be shown- await exportPage.waitForTimeout(100);+ if (await exportPage.isVisible("[data-testid=show-code]")) {+ await exportPage.getByTestId("show-code").click();+ // wait 100ms for the code to be shown+ await exportPage.waitForTimeout(100);+ }// Take screenshot of codeawait takeScreenshot(exportPage, `code-${path}`);diff --git a/frontend/e2e-tests/kitchen-sink-wasm.spec.ts b/frontend/e2e-tests/kitchen-sink-wasm.spec.tsnew file mode 100644index 0000000000..7666209c02--- /dev/null+++ b/frontend/e2e-tests/kitchen-sink-wasm.spec.ts@@ -0,0 +1,34 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { test } from "@playwright/test";+import {+ exportAsHTMLAndTakeScreenshot,+ exportAsPNG,+ takeScreenshot,+} from "./helper";+import { fileURLToPath } from "node:url";++const __filename = fileURLToPath(import.meta.url);++test("can screenshot and download as html edit", async ({ page }) => {+ await page.goto("http://localhost:3000");++ // See text Initializing+ await page.waitForSelector("text=Initializing");+ // See text Welcome+ await page.waitForSelector("text=Welcome");++ await takeScreenshot(page, __filename);+ await exportAsHTMLAndTakeScreenshot(page);+});++test("can screenshot and download as html in run", async ({ page }) => {+ await page.goto("http://localhost:3000?mode=read");++ // See text Initializing+ await page.waitForSelector("text=Initializing");+ // See text Welcome+ await page.waitForSelector("text=Welcome");++ await takeScreenshot(page, __filename);+ await exportAsHTMLAndTakeScreenshot(page);+});diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.tsindex 508501008e..cba5eb4472 100644--- a/frontend/playwright.config.ts+++ b/frontend/playwright.config.ts@@ -85,6 +85,12 @@ export function startServer(app: ApplicationNames): void {exec(marimoCmd);}+const WASM_SERVER = {+ command: `PYODIDE=true vite --port 3000`,+ url: "http://localhost:3000",+ reuseExistingServer: !!process.env.CI,+};+// See https://playwright.dev/docs/test-configuration.const config: PlaywrightTestConfig = {testDir: "./e2e-tests",@@ -172,6 +178,7 @@ const config: PlaywrightTestConfig = {url: getUrl(EDIT_PORT),reuseExistingServer: false,},+ WASM_SERVER,],};diff --git a/frontend/src/core/pyodide/worker/getMarimoWheel.ts b/frontend/src/core/pyodide/worker/getMarimoWheel.tsindex b9f01c09ed..214d3321c4 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.4-py3-none-any.whl";+ return `http://localhost:8000/dist/marimo-${import.meta.env.VITE_MARIMO_VERSION}-py3-none-any.whl`;}if (version === "latest") {return "marimo";diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 1e49ef82b0..7a767b1530 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -21,14 +21,23 @@ const htmlDevPlugin = (): Plugin => {}if (isPyodide) {+ const modeFromUrl = ctx.originalUrl?.includes("mode=read")+ ? "read"+ : "edit";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 }}", "local");+ if (process.env.VITE_MARIMO_VERSION) {+ // If VITE_MARIMO_VERSION is defined, pull the local version of marimo+ html = html.replace("{{ version }}", "local");+ } else {+ // Otherwise, pull the latest version of marimo from PyPI+ html = html.replace("{{ version }}", "latest");+ }html = html.replace("{{ filename }}", "notebook.py");- html = html.replace("{{ mode }}", "edit");+ html = html.replace("{{ mode }}", modeFromUrl);html = html.replace(/<\/head>/, `<marimo-wasm></marimo-wasm></head>`);return html;}@@ -105,6 +114,11 @@ export default defineConfig({"Cross-Origin-Embedder-Policy": "require-corp",},},+ define: {+ "import.meta.env.VITE_MARIMO_VERSION": process.env.VITE_MARIMO_VERSION+ ? JSON.stringify(process.env.VITE_MARIMO_VERSION)+ : JSON.stringify("latest"),+ },build: {minify: isDev ? false : "terser",sourcemap: isDev,diff --git a/marimo/_config/manager.py b/marimo/_config/manager.pyindex 1b8dae3432..1392f72c3b 100644--- a/marimo/_config/manager.py+++ b/marimo/_config/manager.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.-import os+from __future__ import annotations-import tomlkit+import osfrom marimo import _loggersfrom marimo._config.config import (@@ -21,12 +21,15 @@ class UserConfigManager:self.config = load_config()def save_config(self, config: MarimoConfig) -> MarimoConfig:+ import tomlkit+config_path = self._get_config_path()LOGGER.debug("Saving user configuration to %s", config_path)# Remove the secret placeholders from the incoming configconfig = remove_secret_placeholders(config)# Merge the current config with the new configmerged = merge_config(self.config, config)+with open(config_path, "w", encoding="utf-8") as f:tomlkit.dump(merged, f)diff --git a/marimo/_config/utils.py b/marimo/_config/utils.pyindex 5b38a2184e..f9e6269356 100644--- a/marimo/_config/utils.py+++ b/marimo/_config/utils.py@@ -1,9 +1,9 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import osfrom typing import Optional, cast-import tomlkit-from marimo import _loggersfrom marimo._config.config import (DEFAULT_CONFIG,@@ -98,6 +98,8 @@ def load_config() -> MarimoConfig:if path is not None:LOGGER.debug("Using config at %s", path)try:+ import tomlkit+with open(path, "rb") as f:user_config = tomlkit.parse(f.read())except Exception as e:diff --git a/marimo/_islands/island_generator.py b/marimo/_islands/island_generator.pyindex d0eed0814c..5466723b8b 100644--- a/marimo/_islands/island_generator.py+++ b/marimo/_islands/island_generator.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport jsonfrom textwrap import dedent-from typing import TYPE_CHECKING, List, Optional, Union, cast+from typing import List, Optional, Union, castfrom marimo import __version__, _loggersfrom marimo._ast.app import App, InternalApp@@ -14,9 +14,7 @@ from marimo._output.formatting import as_htmlfrom marimo._output.utils import uri_encode_componentfrom marimo._plugins.stateless.json_output import json_outputfrom marimo._plugins.ui import code_editor--if TYPE_CHECKING:- from marimo._server.sessions import Session+from marimo._server.session.session_view import SessionViewLOGGER = _loggers.marimo_logger()@@ -40,7 +38,7 @@ class MarimoIslandStub:self._is_reactive = is_reactiveself._internal_app: Optional[InternalApp] = None- self._session: Optional[Session] = None+ self._session_view: Optional[SessionView] = Noneself._output: Optional[CellOutput] = None@property@@ -49,14 +47,12 @@ class MarimoIslandStub:# pdf.if self._output is None:assert (- self._session is not None+ self._session_view 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]- )+ outputs = self._session_view.get_cell_outputs([self._cell_id])self._output = outputs.get(self._cell_id, None)return self._output@@ -245,7 +241,7 @@ class MarimoIslandGenerator:for stub in self._stubs:stub._internal_app = self._app- stub._session = session+ stub._session_view = sessionreturn cast(App, self._app)diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex 08ed3f312b..9143613167 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -14,7 +14,7 @@ from marimo._server.file_router import AppFileRouterfrom marimo._server.model import ConnectionState, SessionConsumer, SessionModefrom marimo._server.models.export import ExportAsHTMLRequestfrom marimo._server.models.models import InstantiateRequest-from marimo._server.sessions import Session+from marimo._server.session.session_view import SessionViewdef export_as_script(@@ -51,11 +51,11 @@ async def run_app_then_export_as_html(file_manager = file_router.get_file_manager(file_key)config = UserConfigManager()- session = await run_app_until_completion(file_manager, cli_args)+ session_view = await run_app_until_completion(file_manager, cli_args)# Export the session as HTMLhtml, filename = Exporter().export_as_html(- file_manager=session.app_file_manager,- session_view=session.session_view,+ file_manager=file_manager,+ session_view=session_view,display_config=config.get_config()["display"],request=ExportAsHTMLRequest(include_code=include_code,@@ -69,7 +69,9 @@ async def run_app_then_export_as_html(async def run_app_until_completion(file_manager: AppFileManager,cli_args: SerializedCLIArgs,-) -> Session:+) -> SessionView:+ from marimo._server.sessions import Session+instantiated_event = asyncio.Event()# Create a no-op session consumer@@ -130,4 +132,4 @@ async def run_app_until_completion(# Stop distributor, terminate kernel process, etc -- all information is# captured by the session view.session.close()- return session+ return session.session_viewdiff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex adf5352d2b..8a67f9c635 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -7,10 +7,6 @@ from textwrap import dedentfrom typing import castfrom marimo import __version__-from marimo._cli.convert.markdown import (- formatted_code_block,- is_sanitized_markdown,-)from marimo._config.config import (DEFAULT_CONFIG,DisplayConfig,@@ -32,15 +28,6 @@ from marimo._server.session.session_view import SessionViewfrom marimo._server.templates.templates import static_notebook_templatefrom marimo._utils.paths import import_files-# Click not bound to be installed (e.g. pyodide).-try:- from click import UsageError-except ImportError:-- class UsageError(Exception): # type: ignore[no-redef]- pass--# Root directory for static assetsroot = os.path.realpath(str(import_files("marimo").joinpath("_static")))@@ -116,6 +103,8 @@ class Exporter:if not cell:continueif cell._is_coroutine():+ from click import UsageError+raise UsageError("Cannot export a notebook with async code to a flat script")@@ -134,6 +123,11 @@ class Exporter:return code, download_filenamedef export_as_md(self, file_manager: AppFileManager) -> tuple[str, str]:+ from marimo._cli.convert.markdown import (+ formatted_code_block,+ is_sanitized_markdown,+ )+# TODO: Provide filter or kernel in header such that markdown documents# are executable.document = [diff --git a/pyodide/DOCS.md b/pyodide/DOCS.mdindex 8f8fcdd16c..69fa11cb7f 100644--- a/pyodide/DOCS.md+++ b/pyodide/DOCS.md@@ -1,8 +1,22 @@# marimo + pyodide+## Running the frontend against the latest deploy on PyPi+```bash-python3 pyodide/build_and_serve.py-# then in another terminalcd frontendPYODIDE=true pnpm dev```++## Running the frontend against a local backend++This requires `watchdog` to be installed (`pip install watchdog`).++```bash+# build once+python3 -m build+# server and watch for changes+python3 pyodide/build_and_serve.py+# in another terminal+cd frontend+PYODIDE=true VITE_MARIMO_VERSION=$(marimo --version) pnpm dev+```