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: cleanup config passing to HTML from server (#5120)
Myles Scolnickb42afa298584
diff --git a/docs/apps/embedding_numbers.py b/docs/apps/embedding_numbers.pyindex cb5e402a88..85e7b41494 100644--- a/docs/apps/embedding_numbers.py+++ b/docs/apps/embedding_numbers.py@@ -1,30 +1,30 @@import marimo-__generated_with = "0.7.19"+__generated_with = "0.13.14"app = marimo.App()@app.cell-def __(mo):+def _(mo):mo.md("""- # Embedding MNIST+ # Embedding MNIST- This app shows how to use the function `pymde.preserve_neighbors`- to produce embeddings that highlight the local structure of your- data, using MNIST as a case study. In these embeddings similar- digits are near each other, and dissimilar digits are not near each other.+ This app shows how to use the function `pymde.preserve_neighbors`+ to produce embeddings that highlight the local structure of your+ data, using MNIST as a case study. In these embeddings similar+ digits are near each other, and dissimilar digits are not near each other.- ## Data- The data we'll embed are 70,000 28x28 grayscale images of handwritten- digits:- """+ ## Data+ The data we'll embed are 70,000 28x28 grayscale images of handwritten+ digits:+ """)return@app.cell-def __(button, show_random_images):+def _(button, show_random_images):buttonshow_random_images(5)@@ -32,14 +32,14 @@ def __(button, show_random_images):@app.cell-def __(mo):+def _(mo):button = mo.ui.button(label="Click this button")mo.md(f"{button} _to view another random sample of images._").center()- return button,+ return (button,)@app.cell-def __(mo):+def _(mo):params = (mo.md("""@@ -61,11 +61,11 @@ def __(mo):)params- return params,+ return (params,)@app.cell-def __(params):+def _(params):if params.value is not None:embedding_dimension, constraint_type = (params.value["embedding_dimension"],@@ -77,7 +77,7 @@ def __(params):@app.cell-def __(constraint_type, pymde):+def _(constraint_type, pymde):if constraint_type is not None:_constraints = {"Centered": pymde.Centered(),@@ -85,18 +85,11 @@ def __(constraint_type, pymde):}constraint = _constraints[constraint_type]- return constraint,+ return (constraint,)@app.cell-def __(- compute_embedding,- constraint,- embedding_dimension,- mnist,- plt,- pymde,-):+def _(compute_embedding, constraint, embedding_dimension, mnist, plt, pymde):def show_embedding():_, embedding = compute_embedding(embedding_dimension, constraint)pymde.plot(embedding, color_by=mnist.attributes["digits"])@@ -105,11 +98,11 @@ def __(show_embedding() if embedding_dimension is not None else None- return show_embedding,+ return@app.cell-def __(mnist, pymde, torch):+def _(mnist, pymde, torch):embedding_cache = {}@@ -129,17 +122,17 @@ def __(mnist, pymde, torch):value = (mde, X)embedding_cache[key] = valuereturn value- return compute_embedding, embedding_cache+ return (compute_embedding,)@app.cell-def __(pymde):+def _(pymde):mnist = pymde.datasets.MNIST()- return mnist,+ return (mnist,)@app.cell-def __(mnist, plt, torch):+def _(mnist, plt, torch):def show_random_images(n_images):indices = torch.randperm(mnist.data.shape[0])[:n_images]images = mnist.data[indices].reshape((-1, 28, 28))@@ -151,11 +144,11 @@ def __(mnist, plt, torch):ax.set_xticks([])plt.tight_layout()return fig- return show_random_images,+ return (show_random_images,)@app.cell-def __():+def _():import matplotlib.pyplot as pltimport pymdeimport torchdiff --git a/docs/apps/intro.py b/docs/apps/intro.pyindex 0bb9ae6b5f..ab63bd1c00 100644--- a/docs/apps/intro.py+++ b/docs/apps/intro.py@@ -1,40 +1,40 @@import marimo-__generated_with = "0.0.6"+__generated_with = "0.13.14"app = marimo.App()@app.cell-def __(mo):- mo.md("# Welcome to marimo! 🌊🍃")+def _(mo):+ mo.md("""# Welcome to marimo! 🌊🍃""")return@app.cell-def __(mo):+def _(mo):slider = mo.ui.slider(1, 22)- return slider,+ return (slider,)@app.cell-def __(mo, slider):+def _(mo, slider):mo.md(f"""- marimo is a Python library for creating reactive and interactive- notebooks and apps.+ marimo is a Python library for creating reactive and interactive+ notebooks and apps.- Unlike traditional notebooks, marimo notebooks **run- automatically** when you modify them or- interact with UI elements, like this slider: {slider}.+ Unlike traditional notebooks, marimo notebooks **run+ automatically** when you modify them or+ interact with UI elements, like this slider: {slider}.- {"##" + "🍃" * slider.value}- """+ {"##" + "🍃" * slider.value}+ """)return@app.cell-def __(mo):+def _(mo):mo.accordion({"A notebook or an app?": (@@ -54,9 +54,9 @@ def __(mo):@app.cell-def __():+def _():import marimo as mo- return mo,+ return (mo,)if __name__ == "__main__":diff --git a/frontend/.storybook/preview-head.html b/frontend/.storybook/preview-head.htmlindex 2ed620bd3b..52d2f84dc7 100644--- a/frontend/.storybook/preview-head.html+++ b/frontend/.storybook/preview-head.html@@ -1,9 +1 @@<marimo-filename hidden>app.py</marimo-filename>-<marimo-mode data-mode="edit" hidden></marimo-mode>-<marimo-version data-mode="0.1.0" hidden></marimo-version>-<marimo-user-config- data-config='{"completion":{"activate_on_typing":false, "copilot": true},"save":{"autosave":"off","autosave_delay":0},"keymap":{"preset":"default"},"experimental":{}}'- hidden-></marimo-user-config>-<marimo-app-config data-config="{}" hidden></marimo-app-config>-<marimo-server-token data-token="123" hidden></marimo-server-token>diff --git a/frontend/index.html b/frontend/index.htmlindex e77f1710e5..42fd362058 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -53,15 +53,13 @@}</script><marimo-filename hidden>{{ filename }}</marimo-filename>- <marimo-mode data-mode='{{ mode }}' hidden></marimo-mode>- <marimo-version data-version='{{ version }}' hidden></marimo-version>- <marimo-user-config data-config='{{ user_config }}' data-overrides='{{ config_overrides }}' hidden></marimo-user-config>- <marimo-app-config data-config='{{ app_config }}' hidden></marimo-app-config>- <marimo-server-token data-token='{{ server_token }}' hidden></marimo-server-token><title>{{ title }}</title></head><body><div id="root"></div>+ <script>+ window.__MARIMO_MOUNT_CONFIG__ = '{{ mount_config }}';+ </script><script type="module" src="/src/main.tsx"></script></body></html>diff --git a/frontend/islands/__demo__/index.html b/frontend/islands/__demo__/index.htmlindex 8f5c93d3a2..6de26999bc 100644--- a/frontend/islands/__demo__/index.html+++ b/frontend/islands/__demo__/index.html@@ -8,27 +8,26 @@<meta name="description" content="a marimo app" /><title>🏝️</title>- <script type="module" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/main.js"></script>- <link- href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/style.css"- rel="stylesheet"- crossorigin="anonymous"- />- <link rel="preconnect" href="https://fonts.googleapis.com" />- <link- rel="preconnect"- href="https://fonts.gstatic.com"- crossorigin- />- <link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap" rel="stylesheet" />- <link- rel="stylesheet"- href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"- integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"- crossorigin="anonymous"- />- <marimo-filename hidden></marimo-filename>-<marimo-mode data-mode='read' hidden></marimo-mode>+ <script type="module" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/main.js"></script>+<link+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/style.css"+ rel="stylesheet"+ crossorigin="anonymous"+/>+<link rel="preconnect" href="https://fonts.googleapis.com" />+<link+ rel="preconnect"+ href="https://fonts.gstatic.com"+ crossorigin+/>+<link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap" rel="stylesheet" />+<link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"+ integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"+ crossorigin="anonymous"+/>+<marimo-filename hidden></marimo-filename><!-- If running a local server of the production build --><!-- <script type="module" src="http://127.0.0.1:8001/main.js"></script>@@ -69,7 +68,7 @@data-reactive="true"><marimo-cell-output>- <marimo-ui-element object-id='vblA-0' random-id='eb5f2816-d9cf-4b03-bae6-6c67925d4253'><marimo-slider data-initial-value='0' data-label='null' data-start='0' data-stop='100' data-step='2' data-steps='[]' data-debounce='false' data-orientation='"horizontal"' data-show-value='false' data-full-width='false'></marimo-slider></marimo-ui-element>+ <marimo-ui-element object-id='vblA-0' random-id='f766db97-6524-c217-3975-99e795060023'><marimo-slider data-initial-value='0' data-label='null' data-start='0' data-stop='100' data-step='2' data-steps='[]' data-debounce='false' data-disabled='false' data-orientation='"horizontal"' data-show-value='false' data-include-input='false' data-full-width='false'></marimo-slider></marimo-ui-element></marimo-cell-output><marimo-cell-code hidden>%0Aslider%20%3D%20mo.ui.slider(0%2C%20100%2C%202)%0Aslider%0A</marimo-cell-code></marimo-island>@@ -91,7 +90,7 @@<marimo-cell-output><span class="markdown prose dark:prose-invert"><span class="paragraph">We can also show the island code!</span></span></marimo-cell-output>- <marimo-ui-element object-id='135dcce7-6c7f-49fe-853d-fbcb784342fa' random-id='135dcce7-6c7f-49fe-853d-fbcb784342fa'><marimo-code-editor data-initial-value='"mo.md(\"We can also show the island code!\")"' data-label='null' data-language='"python"' data-placeholder='""' data-disabled='false'></marimo-code-editor></marimo-ui-element>+ <marimo-ui-element object-id='3f8d1379-362f-ff6e-5534-e045a7f80ff7' random-id='3f8d1379-362f-ff6e-5534-e045a7f80ff7'><marimo-code-editor data-initial-value='"mo.md(\"We can also show the island code!\")"' data-label='null' data-language='"python"' data-placeholder='""' data-disabled='false' data-show-copy-button='true' data-debounce='false'></marimo-code-editor></marimo-ui-element></marimo-island><marimo-islanddata-app-id="main"@@ -99,9 +98,9 @@data-reactive="false"><marimo-cell-output>- <marimo-mime-renderer data-mime='"application/vnd.marimo+error"' data-data='[{"msg": "This cell raised an exception: ModuleNotFoundError('No module named 'matplotlib'')", "exception_type": "ModuleNotFoundError", "raising_cell": null, "type": "exception"}]'></marimo-mime-renderer>+ <marimo-mime-renderer data-mime='"application/vnd.marimo+error"' data-data='[{"msg": "No module named 'matplotlib'", "exception_type": "ModuleNotFoundError", "raising_cell": null, "type": "exception"}]'></marimo-mime-renderer></marimo-cell-output>- <marimo-ui-element object-id='332c9909-e441-462a-9faa-6a60625e808b' random-id='332c9909-e441-462a-9faa-6a60625e808b'><marimo-code-editor data-initial-value='"# Also run expensive outputs without performing them in the browser\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.linspace(0, 2*np.pi, 100)\ny = np.sin(x)\nplt.plot(x, y)\nplt.gca()"' data-label='null' data-language='"python"' data-placeholder='""' data-disabled='false'></marimo-code-editor></marimo-ui-element>+ <marimo-ui-element object-id='04d339f9-b859-6b60-030d-0bf689282c88' random-id='04d339f9-b859-6b60-030d-0bf689282c88'><marimo-code-editor data-initial-value='"# Also run expensive outputs without performing them in the browser\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.linspace(0, 2*np.pi, 100)\ny = np.sin(x)\nplt.plot(x, y)\nplt.gca()"' data-label='null' data-language='"python"' data-placeholder='""' data-disabled='false' data-show-copy-button='true' data-debounce='false'></marimo-code-editor></marimo-ui-element></marimo-island><marimo-islanddata-app-id="main"@@ -109,7 +108,7 @@data-reactive="true"><marimo-cell-output>- <marimo-mime-renderer data-mime='"application/vnd.marimo+error"' data-data='[{"msg": "This cell raised an exception: ModuleNotFoundError('No module named 'idk_package'')", "exception_type": "ModuleNotFoundError", "raising_cell": null, "type": "exception"}]'></marimo-mime-renderer>+ <marimo-mime-renderer data-mime='"application/vnd.marimo+error"' data-data='[{"msg": "No module named 'idk_package'", "exception_type": "ModuleNotFoundError", "raising_cell": null, "type": "exception"}]'></marimo-mime-renderer></marimo-cell-output><marimo-cell-code hidden>%0Aimport%20idk_package%0A%22Should%20raise%20an%20error%22%0A</marimo-cell-code></marimo-island>@@ -125,7 +124,7 @@ apps. This function compiles Markdown into HTML that marimocan display.</span><span class="paragraph">For example, here's the code that rendered the above title andparagraph:</span>-<div class="codehilite"><pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span>+<div class="language-python3 codehilite"><pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span><span class="w"> </span><span class="sd">'''</span><span class="sd"> # Hello, Markdown!</span><span class="sd"> Use marimo's "`md`" function to embed rich text into your marimo</span>@@ -146,10 +145,10 @@ paragraph:</span><span class="markdown prose dark:prose-invert"><h2 id="latex">LaTeX</h2><span class="paragraph">You can embed LaTeX in Markdown.</span><span class="paragraph">For example,</span>-<div class="codehilite"><pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span><span class="sa">r</span><span class="s1">'$f : \mathbf</span><span class="si">{R}</span><span class="s1"> o \mathbf</span><span class="si">{R}</span><span class="s1">$'</span><span class="p">)</span>+<div class="language-python3 codehilite"><pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span><span class="sa">r</span><span class="s1">'$f : \mathbf</span><span class="si">{R}</span><span class="s1"> o \mathbf</span><span class="si">{R}</span><span class="s1">$'</span><span class="p">)</span></code></pre></div><span class="paragraph">renders <marimo-tex class="arithmatex">||(f : \mathbf{R} o \mathbf{R}||)</marimo-tex>, while</span>-<div class="codehilite"><pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span>+<div class="language-python3 codehilite"><pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span><span class="w"> </span><span class="sa">r</span><span class="sd">'''</span><span class="sd"> \[</span><span class="sd"> f: \mathbf{R} o \mathbf{R}</span>diff --git a/frontend/islands/vite.config.mts b/frontend/islands/vite.config.mtsindex 32eb35a008..b939fa1264 100644--- a/frontend/islands/vite.config.mts+++ b/frontend/islands/vite.config.mts@@ -1,6 +1,8 @@/* Copyright 2024 Marimo. All rights reserved. */import { type Plugin, defineConfig } from "vite";import fs from "node:fs";+import wasm from "vite-plugin-wasm";+import topLevelAwait from "vite-plugin-top-level-await";import path from "node:path";import react from "@vitejs/plugin-react";import tsconfigPaths from "vite-tsconfig-paths";@@ -65,6 +67,8 @@ export default defineConfig({},}),tsconfigPaths(),+ wasm(),+ topLevelAwait(),],build: {emptyOutDir: true,diff --git a/frontend/src/__tests__/main.test.tsx b/frontend/src/__tests__/main.test.tsxnew file mode 100644index 0000000000..752fb87610--- /dev/null+++ b/frontend/src/__tests__/main.test.tsx@@ -0,0 +1,173 @@+/* Copyright 2024 Marimo. All rights reserved. */+// @vitest-environment jsdom+import { mount, visibleForTesting } from "../mount";+import { store } from "../core/state/jotai";+import { type AppMode, viewStateAtom } from "../core/mode";+import { codeAtom, filenameAtom } from "../core/saving/file-state";+import { showCodeInRunModeAtom, marimoVersionAtom } from "../core/meta/state";+import {+ appConfigAtom,+ userConfigAtom,+ configOverridesAtom,+} from "../core/config/config";+import { describe, beforeEach, it, expect, vi } from "vitest";+import {+ type AppConfig,+ parseAppConfig,+ parseUserConfig,+} from "@/core/config/config-schema";++vi.mock("../utils/vitals", () => ({+ reportVitals: vi.fn(),+}));++vi.mock("react-dom/client", () => ({+ createRoot: vi.fn().mockImplementation((el) => {+ return {+ render: vi.fn(),+ };+ }),+}));++describe("main", () => {+ beforeEach(() => {+ visibleForTesting.reset();++ // Reset store before each test+ store.set(viewStateAtom, { mode: "not-set" as AppMode, cellAnchor: null });+ store.set(codeAtom, undefined);+ store.set(filenameAtom, null);+ store.set(showCodeInRunModeAtom, false);+ store.set(marimoVersionAtom, "unknown");+ store.set(appConfigAtom, parseAppConfig({}));+ store.set(userConfigAtom, parseUserConfig({}));+ store.set(configOverridesAtom, {});+ });++ it.each(["edit", "read", "home", "run"])(+ "should mount with mode %s",+ (mode) => {+ const el = document.createElement("div");+ mount({ mode: "edit" }, el);++ expect(store.get(viewStateAtom).mode).toBe("edit");+ expect(store.get(filenameAtom)).toBeDefined();+ expect(store.get(marimoVersionAtom)).toBe("unknown");+ expect(store.get(showCodeInRunModeAtom)).toBe(true);+ },+ );++ it("should not mount with invalid mode", () => {+ const el = document.createElement("div");+ const error = mount({ mode: "invalid" }, el);+ expect(error).toBeDefined();+ expect(error?.message).toBe("Invalid marimo mount options");+ });++ it("should mount with null values", () => {+ const el = document.createElement("div");+ const error = mount(+ { mode: "edit", filename: null, code: null, version: null },+ el,+ );+ expect(error).toBeUndefined();++ mount({ mode: "edit", filename: null, code: null, version: null }, el);+ expect(store.get(filenameAtom)).toBeNull();+ expect(store.get(codeAtom)).toBe("");+ expect(store.get(marimoVersionAtom)).toBe("unknown");+ expect(store.get(viewStateAtom).mode).toBe("edit");+ });++ it("should mount with undefined values", () => {+ const el = document.createElement("div");+ const error = mount(+ {+ mode: "edit",+ filename: undefined,+ code: undefined,+ version: undefined,+ },+ el,+ );+ expect(error).toBeUndefined();++ expect(store.get(filenameAtom)).toBeNull();+ expect(store.get(codeAtom)).toBe("");+ expect(store.get(marimoVersionAtom)).toBe("unknown");+ expect(store.get(viewStateAtom).mode).toBe("edit");+ });++ it("should mount with empty config", () => {+ const el = document.createElement("div");+ const error = mount(+ { mode: "edit", config: {}, configOverrides: {}, appConfig: {} },+ el,+ );+ expect(error).toBeUndefined();+ expect(store.get(userConfigAtom)).toEqual(parseUserConfig({}));+ expect(store.get(configOverridesAtom)).toEqual({});+ expect(store.get(appConfigAtom)).toEqual(parseAppConfig({}));+ expect(store.get(viewStateAtom).mode).toBe("edit");+ expect(store.get(showCodeInRunModeAtom)).toBe(true);+ });++ it("should mount with all options", () => {+ const el = document.createElement("div");+ const options = {+ filename: "test.py",+ code: "print('hello')",+ version: "1.0.0",+ mode: "edit" as const,+ config: {+ display: {+ cell_output: "above",+ code_editor_font_size: 99,+ dataframes: "rich",+ default_table_page_size: 10,+ default_width: "medium",+ theme: "light",+ },+ },+ configOverrides: { display: { code_editor_font_size: 100 } },+ appConfig: { app_title: "My App" } as AppConfig,+ view: { showAppCode: true },+ };++ mount(options, el);++ expect(store.get(filenameAtom)).toBe("test.py");+ expect(store.get(codeAtom)).toBe("print('hello')");+ expect(store.get(marimoVersionAtom)).toBe("1.0.0");+ expect(store.get(viewStateAtom).mode).toBe("edit");+ expect(store.get(showCodeInRunModeAtom)).toBe(true);+ expect(store.get(userConfigAtom).display).toEqual(+ expect.objectContaining({+ code_editor_font_size: 99,+ }),+ );+ expect(store.get(configOverridesAtom)).toEqual(+ expect.objectContaining({+ display: { code_editor_font_size: 100 },+ }),+ );+ expect(store.get(appConfigAtom)).toEqual(+ expect.objectContaining({ app_title: "My App" }),+ );+ });++ it("should throw on invalid options", () => {+ const el = document.createElement("div");+ const error = mount({ invalid: true } as unknown, el);+ expect(error).toBeDefined();+ expect(error?.message).toBe("Invalid marimo mount options");+ });++ it("should not mount twice", () => {+ const el = document.createElement("div");+ mount({ mode: "edit" }, el);+ const error = mount({ mode: "edit" }, el);+ expect(error).toBeDefined();+ expect(error?.message).toBe("marimo app has already been mounted.");+ });+});diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 0aee2e4941..3d8a5f3c2f 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -49,11 +49,11 @@ import { KNOWN_AI_MODELS, AWS_REGIONS } from "./constants";import { Textarea } from "../ui/textarea";import { get } from "lodash-es";import { Tooltip } from "../ui/tooltip";-import { getMarimoVersion } from "@/core/dom/marimo-tag";import { Badge } from "../ui/badge";import { capabilitiesAtom } from "@/core/config/capabilities";import { Banner } from "@/plugins/impl/common/error-banner";import { OptionalFeatures } from "./optional-features";+import { marimoVersionAtom } from "@/core/meta/state";const formItemClasses = "flex flex-row items-center space-x-1 space-y-0";const categories = [@@ -115,6 +115,7 @@ export const UserConfigForm: React.FC = () => {activeUserConfigCategoryAtom,);const capabilities = useAtomValue(capabilitiesAtom);+ const marimoVersion = useAtomValue(marimoVersionAtom);// Create formconst form = useForm<UserConfig>({@@ -1510,7 +1511,7 @@ export const UserConfigForm: React.FC = () => {))}<div className="p-2 text-xs text-muted-foreground self-start">- <span>Version: {getMarimoVersion()}</span>+ <span>Version: {marimoVersion}</span></div><div className="flex-1" />diff --git a/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx b/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsxindex 5265d0434a..e1dda9d74a 100644--- a/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx+++ b/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx@@ -1,14 +1,16 @@/* Copyright 2024 Marimo. All rights reserved. */import type { OutlineItem } from "@/core/cells/outline";import { headingToIdentifier } from "@/core/dom/outline";-import { initialMode } from "@/core/mode";+import { getInitialAppMode } from "@/core/mode";import { Logger } from "@/utils/Logger";import { useEffect, useRef, useState } from "react";function getRootScrollableElement() {// HACK: this is a bit leaky// this gets the root element that contains the scrollable content- return initialMode === "edit" ? document.getElementById("App") : undefined;+ return getInitialAppMode() === "edit"+ ? document.getElementById("App")+ : undefined;}/**diff --git a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsxindex d95152126c..48612932d4 100644--- a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx+++ b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx@@ -16,7 +16,7 @@ import {import { MinimalShortcut } from "../../shortcuts/renderShortcut";import { useNotebookActions } from "../actions/useNotebookActions";import type { ActionButton } from "../actions/types";-import { getMarimoVersion } from "@/core/dom/marimo-tag";+import { getMarimoVersion } from "@/core/meta/globals";import { Tooltip } from "@/components/ui/tooltip";export const NotebookMenuDropdown: React.FC = () => {diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex 998ec91c06..5ccfcda245 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -39,7 +39,7 @@ import { KnownQueryParams } from "@/core/constants";import { useResolvedMarimoConfig } from "@/core/config/config";import { MarkdownLanguageAdapter } from "@/core/codemirror/language/languages/markdown";import { isErrorMime } from "@/core/mime";-import { getMarimoShowCode } from "@/core/dom/marimo-tag";+import { showCodeInRunModeAtom } from "@/core/meta/state";type VerticalLayout = null;type VerticalLayoutProps = ICellRendererProps<VerticalLayout>;@@ -52,12 +52,12 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({const { invisible } = useDelayVisibility(cells.length, mode);const kioskMode = useAtomValue(kioskModeAtom);const [userConfig] = useResolvedMarimoConfig();+ const showCodeInRunModePreference = useAtomValue(showCodeInRunModeAtom);const urlParams = new URLSearchParams(window.location.search);const [showCode, setShowCode] = useState(() => {- // Check marimo-code tag setting first- const showCodePreference = getMarimoShowCode();- if (!showCodePreference) {+ // Check if the setting was set in the mount options+ if (!showCodeInRunModePreference) {return false;}// If 'auto' or not found, use URL paramdiff --git a/frontend/src/components/static-html/static-banner.tsx b/frontend/src/components/static-html/static-banner.tsxindex 05c8898567..de7167f1a7 100644--- a/frontend/src/components/static-html/static-banner.tsx+++ b/frontend/src/components/static-html/static-banner.tsx@@ -6,9 +6,7 @@ import { isStaticNotebook } from "@/core/static/static-state";import type React from "react";import { Button } from "../ui/button";import { toast } from "../ui/use-toast";-import { getMarimoCode } from "@/core/dom/marimo-tag";import { downloadBlob } from "@/utils/download";-import { getFilenameFromDOM } from "@/core/dom/htmlUtils";import {DialogHeader,Dialog,@@ -21,13 +19,17 @@ import { CopyIcon, DownloadIcon } from "lucide-react";import { createShareableLink } from "@/core/wasm/share";import { copyToClipboard } from "@/utils/copy";import { Constants } from "@/core/constants";+import { useFilename } from "@/core/saving/filename";+import { useAtomValue } from "jotai";+import { codeAtom } from "@/core/saving/file-state";export const StaticBanner: React.FC = () => {+ const code = useAtomValue(codeAtom);+if (!isStaticNotebook()) {return null;}- const code = getMarimoCode();if (!code) {return null;}@@ -51,7 +53,7 @@ export const StaticBanner: React.FC = () => {};const StaticBannerDialog = ({ code }: { code: string }) => {- let filename = getFilenameFromDOM() || "notebook.py";+ let filename = useFilename() || "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 c64435b64f..841a8532db 100644--- a/frontend/src/core/MarimoApp.tsx+++ b/frontend/src/core/MarimoApp.tsx@@ -10,12 +10,12 @@ import { TooltipProvider } from "../components/ui/tooltip";import { Toaster } from "../components/ui/toaster";import { ModalProvider } from "../components/modal/ImperativeModal";import { useAppConfig, useResolvedMarimoConfig } from "@/core/config/config";-import { initialMode } from "./mode";import { CssVariables } from "@/theme/ThemeProvider";import { TailwindIndicator } from "@/components/debug/indicator";import { Provider as SlotzProvider } from "@marimo-team/react-slotz";import { slotsController } from "./slots/slots";import { reactLazyWithPreload } from "@/utils/lazy";+import { getInitialAppMode } from "@/core/mode";// Force tailwind classnames// tailwind only creates css for classnames that exist the FE files@@ -33,7 +33,7 @@ const LazyEditPage = reactLazyWithPreload(() => import("@/components/pages/edit-page"),);-function preload(mode: string) {+export function preloadPage(mode: string) {if (mode === "home") {LazyHomePage.preload();} else if (mode === "read") {@@ -42,7 +42,6 @@ function preload(mode: string) {LazyEditPage.preload();}}-preload(initialMode);/*** The root component of the Marimo app.@@ -53,6 +52,7 @@ export const MarimoApp: React.FC = memo(() => {const editorFontSize = toRem(userConfig.display.code_editor_font_size);const renderBody = () => {+ const initialMode = getInitialAppMode();if (initialMode === "home") {return <LazyHomePage.Component />;}diff --git a/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts b/frontend/src/core/codemirror/markdown/__tests__/commands.test.tsindex a9877e1050..46ccd839fd 100644--- a/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts+++ b/frontend/src/core/codemirror/markdown/__tests__/commands.test.ts@@ -21,7 +21,7 @@ import {insertUL,} from "../commands";import { sendCreateFileOrFolder } from "@/core/network/requests";-import { filenameAtom } from "@/core/saving/filenameAtom";+import { filenameAtom } from "@/core/saving/file-state";import { store } from "@/core/state/jotai";function createEditor(content: string) {diff --git a/frontend/src/core/codemirror/markdown/commands.ts b/frontend/src/core/codemirror/markdown/commands.tsindex 35fe0808af..b6e282bba1 100644--- a/frontend/src/core/codemirror/markdown/commands.ts+++ b/frontend/src/core/codemirror/markdown/commands.ts@@ -1,7 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { toast } from "@/components/ui/use-toast";import { sendCreateFileOrFolder } from "@/core/network/requests";-import { filenameAtom } from "@/core/saving/filenameAtom";+import { filenameAtom } from "@/core/saving/file-state";import { store } from "@/core/state/jotai";import { Paths, type FilePath } from "@/utils/paths";import {diff --git a/frontend/src/core/codemirror/rtc/extension.ts b/frontend/src/core/codemirror/rtc/extension.tsindex 6d0802223a..3c3ceb7ffb 100644--- a/frontend/src/core/codemirror/rtc/extension.ts+++ b/frontend/src/core/codemirror/rtc/extension.ts@@ -28,7 +28,6 @@ import { createSelectionLayer } from "./loro/awareness";import { createCursorLayer } from "./loro/awareness";import { remoteAwarenessStateField } from "./loro/awareness";import type { UserState } from "./loro/awareness";-import { initialMode } from "@/core/mode";import { isRtcEnabled, usernameAtom } from "@/core/rtc/state";import { getColor } from "./loro/colors";import {@@ -38,6 +37,7 @@ import {} from "../language/metadata";import { invariant } from "@/utils/invariant";import { isEqual } from "lodash-es";+import { getInitialAppMode } from "@/core/mode";const logger = Logger.get("rtc");const awarenessLogger = logger.get("awareness").disabled();@@ -90,6 +90,11 @@ const getWs = once(() => {// This is to ensure the LoroDoc is created on the serverawait waitForConnectionOpen();+ // Don't open the websocket if not in edit mode+ if (getInitialAppMode() !== "edit") {+ return;+ }+// Now open the websocketws.reconnect();});@@ -138,7 +143,7 @@ const getWs = once(() => {});// Kickoff the WS connection for edit mode-if (isRtcEnabled() && initialMode === "edit") {+if (isRtcEnabled()) {getWs();}diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 316ab29970..d05ff34b81 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -1,11 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { z } from "zod";import { Logger } from "@/utils/Logger";-import {- getMarimoAppConfig,- getMarimoConfigOverrides,- getMarimoUserConfig,-} from "../dom/marimo-tag";import type { MarimoConfig } from "../network/types";import { invariant } from "@/utils/invariant";@@ -213,9 +208,9 @@ export const AppConfigSchema = z.default({ width: "medium", auto_download: [] });export type AppConfig = z.infer<typeof AppConfigSchema>;-export function parseAppConfig() {+export function parseAppConfig(config: unknown) {try {- return AppConfigSchema.parse(getMarimoAppConfig());+ return AppConfigSchema.parse(config);} catch (error) {Logger.error(`Marimo got an unexpected value in the configuration file: ${error}`,@@ -224,9 +219,9 @@ export function parseAppConfig() {}}-export function parseUserConfig(): UserConfig {+export function parseUserConfig(config: unknown): UserConfig {try {- const parsed = UserConfigSchema.parse(getMarimoUserConfig());+ const parsed = UserConfigSchema.parse(config);for (const [key, value] of Object.entries(parsed.experimental)) {if (value === true) {Logger.log(`🧪 Experimental feature "${key}" is enabled.`);@@ -241,9 +236,9 @@ export function parseUserConfig(): UserConfig {}}-export function parseConfigOverrides(): {} {+export function parseConfigOverrides(config: unknown): {} {try {- const overrides = getMarimoConfigOverrides() as {};+ const overrides = config as {};invariant(typeof overrides === "object","internal-error: marimo-config-overrides is not an object",diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.tsindex a4047f681f..fbe32fa1af 100644--- a/frontend/src/core/config/config.ts+++ b/frontend/src/core/config/config.ts@@ -4,7 +4,6 @@ import {type AppConfig,type UserConfig,parseAppConfig,- parseConfigOverrides,parseUserConfig,} from "./config-schema";import { store } from "../state/jotai";@@ -14,9 +13,9 @@ import { merge } from "lodash-es";/*** Atom for storing the user config.*/-export const userConfigAtom = atom<UserConfig>(parseUserConfig());+export const userConfigAtom = atom<UserConfig>(parseUserConfig({}));-export const configOverridesAtom = atom<{}>(parseConfigOverrides());+export const configOverridesAtom = atom<{}>({});export const resolvedMarimoConfigAtom = atom<UserConfig>((get) => {const overrides = get(configOverridesAtom);@@ -83,7 +82,7 @@ export function isAiEnabled(config: UserConfig) {/*** Atom for storing the app config.*/-export const appConfigAtom = atom<AppConfig>(parseAppConfig());+export const appConfigAtom = atom<AppConfig>(parseAppConfig({}));/*** Returns the app config.diff --git a/frontend/src/core/dom/htmlUtils.ts b/frontend/src/core/dom/htmlUtils.tsindex 728cc24611..b25f935a7e 100644--- a/frontend/src/core/dom/htmlUtils.ts+++ b/frontend/src/core/dom/htmlUtils.ts@@ -58,6 +58,8 @@ export function getFilenameFromDOM() {}}+ // TODO: Remove this once downstream usage of `getFilenameFromDOM` is removed+ // such that is it not called before mounting the app.const filenameTag = document.querySelector("marimo-filename");if (import.meta.env.MODE === "test" && !filenameTag) {return null;diff --git a/frontend/src/core/dom/marimo-tag.ts b/frontend/src/core/dom/marimo-tag.tsdeleted file mode 100644index 613ee993ca..0000000000--- a/frontend/src/core/dom/marimo-tag.ts+++ /dev/null@@ -1,106 +0,0 @@-/* 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;- getMarimoServerToken: () => string;- getMarimoAppConfig: () => unknown;- getMarimoUserConfig: () => unknown;- getMarimoConfigOverrides: () => unknown;- getMarimoCode: () => string;- getMarimoShowCode: () => boolean;-}--const domBasedMarimoSettings: MarimoSettings = {- getMarimoVersion: () => {- return getMarimoDOMValue("marimo-version", "version");- },- getMarimoServerToken: () => {- return getMarimoDOMValue("marimo-server-token", "token");- },- getMarimoAppConfig: () => {- return JSON.parse(getMarimoDOMValue("marimo-app-config", "config"));- },- getMarimoUserConfig: () => {- return JSON.parse(getMarimoDOMValue("marimo-user-config", "config"));- },- getMarimoConfigOverrides: () => {- try {- return JSON.parse(getMarimoDOMValue("marimo-user-config", "overrides"));- } catch {- return {};- }- },- getMarimoCode: () => {- const tag = document.querySelector("marimo-code");- invariant(tag, "internal-error: marimo-code not tag not found");- const inner = tag.innerHTML;- return decodeURIComponent(inner).trim();- },- getMarimoShowCode: () => {- try {- const tag = document.querySelector<HTMLElement>("marimo-code");- invariant(tag, "internal-error: marimo-code not tag not found");- const showCode = tag.dataset.showCode;- if (showCode === "false") {- return false;- }- return true;- } catch {- return true;- }- },-};--const islandsBasedMarimoSettings: MarimoSettings = {- getMarimoVersion: () => {- assertExists(import.meta.env.VITE_MARIMO_VERSION);- return import.meta.env.VITE_MARIMO_VERSION;- },- getMarimoServerToken: () => {- return "";- },- getMarimoConfigOverrides: () => {- return {};- },- getMarimoAppConfig: () => {- return {};- },- getMarimoUserConfig: () => {- return {};- },- getMarimoCode: () => {- return "";- },- getMarimoShowCode: () => {- return true;- },-};--export const {- getMarimoVersion,- getMarimoServerToken,- getMarimoAppConfig,- getMarimoUserConfig,- getMarimoConfigOverrides,- getMarimoCode,- getMarimoShowCode,-} = isIslands() ? islandsBasedMarimoSettings : domBasedMarimoSettings;--function getMarimoDOMValue(tagName: string, key: string) {- const tag = document.querySelector(tagName);- invariant(- tag !== null && tag instanceof HTMLElement,- `internal-error: ${tagName} tag not found`,- );-- const value = tag.dataset[key];- invariant(- value !== undefined,- `internal-error: ${tagName} tag does not have ${key}`,- );-- return value;-}diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.tsindex cffa211d88..f0ac99b3ef 100644--- a/frontend/src/core/islands/bridge.ts+++ b/frontend/src/core/islands/bridge.ts@@ -2,7 +2,7 @@/* eslint-disable @typescript-eslint/no-explicit-any */import type { EditRequests, RunRequests } from "../network/types";import { Deferred } from "@/utils/Deferred";-import { getMarimoVersion } from "../dom/marimo-tag";+import { getMarimoVersion } from "../meta/globals";import { getWorkerRPC } from "@/core/wasm/rpc";import type { OperationMessage } from "../kernel/messages";import type { JsonString } from "@/utils/json/base64";diff --git a/frontend/src/core/meta/globals.ts b/frontend/src/core/meta/globals.tsnew file mode 100644index 0000000000..0bd7ca0852--- /dev/null+++ b/frontend/src/core/meta/globals.ts@@ -0,0 +1,25 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { marimoVersionAtom, serverTokenAtom } from "@/core/meta/state";+import { store } from "@/core/state/jotai";++/**+ * This should be avoided and instead use the store.+ */+export const getMarimoVersion = () => store.get(marimoVersionAtom);+/**+ * This should be avoided and instead use the store.+ */+export const getMarimoServerToken = () => store.get(serverTokenAtom);++/**+ * N.B This still exists for backwards compatibility.+ * Some code paths still look for the marimo-code html tag.+ */+export const getMarimoCode = (): string | undefined => {+ const tag = document.querySelector("marimo-code");+ if (!tag) {+ return undefined;+ }+ const inner = tag.innerHTML;+ return decodeURIComponent(inner).trim();+};diff --git a/frontend/src/core/meta/state.ts b/frontend/src/core/meta/state.tsnew file mode 100644index 0000000000..632f9b081f--- /dev/null+++ b/frontend/src/core/meta/state.ts@@ -0,0 +1,10 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { atom } from "jotai";++const BUILD_VERSION: string = import.meta.env.VITE_MARIMO_VERSION || "unknown";++export const marimoVersionAtom = atom<string>(BUILD_VERSION);++export const showCodeInRunModeAtom = atom<boolean>(true);++export const serverTokenAtom = atom<string | null>(null);diff --git a/frontend/src/core/mode.ts b/frontend/src/core/mode.tsindex cbf27bf37c..9d9878b65a 100644--- a/frontend/src/core/mode.ts+++ b/frontend/src/core/mode.ts@@ -3,8 +3,8 @@import { atom } from "jotai";import type { CellId } from "./cells/ids";import { store } from "./state/jotai";-import { assertNever } from "@/utils/assertNever";-import { Logger } from "@/utils/Logger";+import { assertExists } from "@/utils/assertExists";+import { isIslands } from "@/core/islands/utils";/*** This is the internal mode.@@ -15,28 +15,10 @@ import { Logger } from "@/utils/Logger";*/export type AppMode = "read" | "edit" | "present" | "home";-export function getInitialAppMode(): AppMode {- const tag = document.querySelector("marimo-mode");- if (tag === null || !(tag instanceof HTMLElement)) {- Logger.warn("internal-error: marimo-mode tag not found");- return "read";- }-- const mode = tag.dataset.mode as AppMode | undefined;- switch (mode) {- case "read":- return "read";- case "edit":- return "edit";- case "home":- return "home";- case "present":- throw new Error("internal-error: present mode is not supported");- case undefined:- throw new Error("internal-error: mode attribute not found");- default:- assertNever(mode);- }+export function getInitialAppMode(): Exclude<AppMode, "present"> {+ const initialMode = store.get(initialModeAtom);+ assertExists(initialMode, "internal-error: initial mode not found");+ return initialMode as Exclude<AppMode, "present">;}export function toggleAppMode(mode: AppMode): AppMode {@@ -63,8 +45,6 @@ interface ViewState {cellAnchor: CellId | null;}-export const initialMode = getInitialAppMode();-export async function runDuringPresentMode(fn: () => void | Promise<void>,): Promise<void> {@@ -86,8 +66,10 @@ export async function runDuringPresentMode(}export const viewStateAtom = atom<ViewState>({- mode: initialMode,+ mode: isIslands() ? "read" : ("not-set" as AppMode),cellAnchor: null,});+export const initialModeAtom = atom<AppMode | undefined>(undefined);+export const kioskModeAtom = atom<boolean>(false);diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.tsindex 601b86e68c..2ce5f9615a 100644--- a/frontend/src/core/network/api.ts+++ b/frontend/src/core/network/api.ts@@ -1,12 +1,16 @@/* Copyright 2024 Marimo. All rights reserved. */import { once } from "@/utils/once";import { Logger } from "../../utils/Logger";-import { getMarimoServerToken } from "../dom/marimo-tag";import { getSessionId } from "../kernel/session";import { createMarimoClient } from "@marimo-team/marimo-api";+import { store } from "@/core/state/jotai";+import { serverTokenAtom } from "@/core/meta/state";+import { assertExists } from "@/utils/assertExists";const getServerTokenOnce = once(() => {- return getMarimoServerToken();+ const token = store.get(serverTokenAtom);+ assertExists(token, "internal-error: server token not found");+ return token;});function getBaseUriWithoutQueryParams(): string {diff --git a/frontend/src/core/saving/filenameAtom.ts b/frontend/src/core/saving/file-state.tssimilarity index 76%rename from frontend/src/core/saving/filenameAtom.tsrename to frontend/src/core/saving/file-state.tsindex 0c26710138..7c232280d9 100644--- a/frontend/src/core/saving/filenameAtom.ts+++ b/frontend/src/core/saving/file-state.ts@@ -3,9 +3,13 @@import { atom } from "jotai";import { getFilenameFromDOM } from "../dom/htmlUtils";-// The atom is separated from the filename logic to avoid circular dependencies./*** Atom for storing the current notebook filename.* This is used to scope local storage to the current notebook.*/export const filenameAtom = atom<string | null>(getFilenameFromDOM());++/**+ * Set for static notebooks.+ */+export const codeAtom = atom<string | undefined>(undefined);diff --git a/frontend/src/core/saving/filename.ts b/frontend/src/core/saving/filename.tsindex f616d2fea8..fbbbef7dad 100644--- a/frontend/src/core/saving/filename.ts+++ b/frontend/src/core/saving/filename.ts@@ -10,7 +10,7 @@ import { WebSocketState } from "../websocket/types";import { useImperativeModal } from "@/components/modal/ImperativeModal";import { connectionAtom } from "../network/connection";import { getAppConfig } from "../config/config";-import { filenameAtom } from "./filenameAtom";+import { filenameAtom } from "./file-state";export function useFilename() {return useAtomValue(filenameAtom);diff --git a/frontend/src/core/saving/save-component.tsx b/frontend/src/core/saving/save-component.tsxindex 063d74d34b..f8ec02edab 100644--- a/frontend/src/core/saving/save-component.tsx+++ b/frontend/src/core/saving/save-component.tsx@@ -22,7 +22,7 @@ import { getSerializedLayout, layoutStateAtom } from "../layout/layout";import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";import { formatAll } from "../codemirror/format";import { useFilename, useUpdateFilename } from "./filename";-import { filenameAtom } from "./filenameAtom";+import { filenameAtom } from "./file-state";import { connectionAtom } from "../network/connection";import { autoSaveConfigAtom } from "../config/config";import { lastSavedNotebookAtom, needsSaveAtom } from "./state";diff --git a/frontend/src/core/wasm/PyodideLoader.tsx b/frontend/src/core/wasm/PyodideLoader.tsxindex 610058324c..8a7bddf977 100644--- a/frontend/src/core/wasm/PyodideLoader.tsx+++ b/frontend/src/core/wasm/PyodideLoader.tsx@@ -7,10 +7,11 @@ import { PyodideBridge } from "./bridge";import { LargeSpinner } from "@/components/icons/large-spinner";import { useAtomValue } from "jotai";import { hasAnyOutputAtom, wasmInitializationAtom } from "./state";-import { initialMode } from "../mode";+import { getInitialAppMode } from "../mode";import { hasQueryParam } from "@/utils/urls";import { KnownQueryParams } from "../constants";-import { getMarimoShowCode } from "../dom/marimo-tag";+import { showCodeInRunModeAtom } from "@/core/meta/state";+import { store } from "@/core/state/jotai";/*** HOC to load Pyodide before rendering children, if necessary.@@ -41,7 +42,7 @@ const PyodideLoaderInner: React.FC<PropsWithChildren> = ({ children }) => {// - we are not showing the code// - and there is no output// then show the spinner- if (!hasOutput && initialMode === "read" && isCodeHidden()) {+ if (!hasOutput && getInitialAppMode() === "read" && isCodeHidden()) {return <WasmSpinner />;}@@ -56,9 +57,10 @@ const PyodideLoaderInner: React.FC<PropsWithChildren> = ({ children }) => {function isCodeHidden() {// Code is hidden if ANY are true:// - the query param is set to false- // - the marimo-code html-tag has data-show-code="false"+ // - the view.showAppCode is falsereturn (- hasQueryParam(KnownQueryParams.showCode, "false") || !getMarimoShowCode()+ hasQueryParam(KnownQueryParams.showCode, "false") ||+ !store.get(showCodeInRunModeAtom));}diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.tsindex d5764743b9..1065b7fefe 100644--- a/frontend/src/core/wasm/bridge.ts+++ b/frontend/src/core/wasm/bridge.ts@@ -22,10 +22,9 @@ import { isWasm } from "./utils";import { Deferred } from "@/utils/Deferred";import { createShareableLink } from "./share";import { PyodideRouter } from "./router";-import { getMarimoVersion } from "../dom/marimo-tag";+import { getMarimoVersion } from "../meta/globals";import { getWorkerRPC } from "./rpc";import { API } from "../network/api";-import { parseUserConfig } from "../config/config-schema";import { throwNotImplemented } from "@/utils/functions";import type { WorkerSchema } from "./worker/worker";import type { SaveWorkerSchema } from "./worker/save-worker";@@ -33,9 +32,10 @@ import { toast } from "@/components/ui/use-toast";import { generateUUID } from "@/utils/uuid";import { store } from "../state/jotai";import { notebookIsRunningAtom } from "../cells/cells";-import { getInitialAppMode, initialMode } from "../mode";+import { getInitialAppMode } from "../mode";import { wasmInitializationAtom } from "./state";import { reloadSafe } from "@/utils/reload-safe";+import { userConfigAtom } from "@/core/config/config";type SaveWorker = ReturnType<typeof getWorkerRPC<SaveWorkerSchema>@@ -58,7 +58,7 @@ export class PyodideBridge implements RunRequests, EditRequests {public initialized = new Deferred<void>();private getSaveWorker(): SaveWorker {- if (initialMode === "read") {+ if (getInitialAppMode() === "read") {Logger.debug("Skipping SaveWorker in read-mode");return {readFile: throwNotImplemented,@@ -140,7 +140,7 @@ export class PyodideBridge implements RunRequests, EditRequests {const code = await notebookFileStore.readFile();const fallbackCode = await fallbackFileStore.readFile();const filename = PyodideRouter.getFilename();- const userConfig = parseUserConfig();+ const userConfig = store.get(userConfigAtom);const queryParameters: Record<string, string | string[]> = {};const searchParams = new URLSearchParams(window.location.search);diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 86c08728cc..d281e9eb40 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -1,55 +1,20 @@/* Copyright 2024 Marimo. All rights reserved. */-import ReactDOM from "react-dom/client";-import { ThemeProvider } from "./theme/ThemeProvider";-import { ErrorBoundary } from "./components/editor/boundary/ErrorBoundary";-import { MarimoApp } from "./core/MarimoApp";-import { reportVitals } from "./utils/vitals";-import { Provider } from "jotai";-import { store } from "./core/state/jotai";-import { maybeRegisterVSCodeBindings } from "./core/vscode/vscode-bindings";-import { patchFetch, patchVegaLoader } from "./core/static/files";-import { isStaticNotebook } from "./core/static/static-state";-import { vegaLoader } from "./plugins/impl/vega/loader";-import { initializePlugins } from "./plugins/plugins";-import { cleanupAuthQueryParams } from "./core/network/auth";-maybeRegisterVSCodeBindings();-initializePlugins();-cleanupAuthQueryParams();+import { mount } from "@/mount";-/**- * Main entry point for the Marimo app.- *- * Sets up the Marimo app with a theme provider.- */--// If we're in static mode, we need to patch fetch to use the virtual file-if (isStaticNotebook()) {- patchFetch();- patchVegaLoader(vegaLoader);+declare global {+ interface Window {+ __MARIMO_MOUNT_CONFIG__: unknown;+ }}-// eslint-disable-next-line @typescript-eslint/no-non-null-assertion, ssr-friendly/no-dom-globals-in-module-scope-const root = ReactDOM.createRoot(document.getElementById("root")!);--try {- root.render(- <Provider store={store}>- <ThemeProvider>- <MarimoApp />- </ThemeProvider>- </Provider>,- );-} catch (error) {- // Most likely, configuration failed to parse.- const Throw = () => {- throw error;- };- root.render(- <ErrorBoundary>- <Throw />- </ErrorBoundary>,- );-} finally {- reportVitals();+// eslint-disable-next-line ssr-friendly/no-dom-globals-in-module-scope+const el = document.getElementById("root");+if (el) {+ if (!window.__MARIMO_MOUNT_CONFIG__) {+ throw new Error("[marimo] mount config not found");+ }+ mount(window.__MARIMO_MOUNT_CONFIG__, el);+} else {+ throw new Error("[marimo] root element not found");}diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsxnew file mode 100644index 0000000000..261fe3730b--- /dev/null+++ b/frontend/src/mount.tsx@@ -0,0 +1,211 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { createRoot } from "react-dom/client";+import { ThemeProvider } from "./theme/ThemeProvider";+import { ErrorBoundary } from "./components/editor/boundary/ErrorBoundary";+import { MarimoApp, preloadPage } from "./core/MarimoApp";+import { reportVitals } from "./utils/vitals";+import { Provider } from "jotai";+import { store } from "./core/state/jotai";+import { maybeRegisterVSCodeBindings } from "./core/vscode/vscode-bindings";+import { patchFetch, patchVegaLoader } from "./core/static/files";+import { isStaticNotebook } from "./core/static/static-state";+import { vegaLoader } from "./plugins/impl/vega/loader";+import { initializePlugins } from "./plugins/plugins";+import { cleanupAuthQueryParams } from "./core/network/auth";+import {+ parseAppConfig,+ parseConfigOverrides,+ parseUserConfig,+} from "./core/config/config-schema";+import { type AppMode, initialModeAtom, viewStateAtom } from "./core/mode";+import { codeAtom, filenameAtom } from "./core/saving/file-state";+import { Logger } from "@/utils/Logger";+import { z } from "zod";+import { getFilenameFromDOM } from "@/core/dom/htmlUtils";+import {+ showCodeInRunModeAtom,+ marimoVersionAtom,+ serverTokenAtom,+} from "@/core/meta/state";+import { appConfigAtom, userConfigAtom } from "@/core/config/config";+import { configOverridesAtom } from "@/core/config/config";+import { getMarimoCode } from "@/core/meta/globals";++let hasMounted = false;++/**+ * Main entry point for the mairmo app.+ *+ * Sets up the mairmo app with a theme provider.+ */+export function mount(options: unknown, el: Element): Error | undefined {+ if (hasMounted) {+ Logger.warn("marimo app has already been mounted.");+ return new Error("marimo app has already been mounted.");+ }++ hasMounted = true;++ const root = createRoot(el);++ try {+ // Init side-effects+ maybeRegisterVSCodeBindings();+ initializePlugins();+ cleanupAuthQueryParams();++ // Patches+ if (isStaticNotebook()) {+ // If we're in static mode, we need to patch fetch to use the virtual file+ patchFetch();+ patchVegaLoader(vegaLoader);+ }++ // Init store+ initStore(options);++ root.render(+ <Provider store={store}>+ <ThemeProvider>+ <MarimoApp />+ </ThemeProvider>+ </Provider>,+ );+ } catch (error) {+ // Most likely, configuration failed to parse.+ const Throw = () => {+ throw error;+ };+ root.render(+ <ErrorBoundary>+ <Throw />+ </ErrorBoundary>,+ );+ return error as Error;+ } finally {+ reportVitals();+ }+}++const passthroughObject = z+ .object({})+ .passthrough() // Allow any extra fields+ .nullish()+ .default({}) // Default to empty object+ .transform((val) => {+ if (val) {+ return val;+ }+ if (typeof val === "string") {+ Logger.warn(+ "[marimo] received JSON string instead of object. Parsing...",+ );+ return JSON.parse(val);+ }+ Logger.warn("[marimo] missing config data");+ return {};+ });++// This should be extremely backwards compatible and require no options+const mountOptionsSchema = z.object({+ /**+ * filename of the notebook to open+ */+ filename: z+ .string()+ .nullish()+ .transform((val) => {+ if (val) {+ return val;+ }+ Logger.warn("No filename provided, using fallback");+ return getFilenameFromDOM();+ }),+ /**+ * notebook code+ */+ code: z+ .string()+ .nullish()+ .transform((val) => val ?? getMarimoCode() ?? ""),+ /**+ * marimo version+ */+ version: z+ .string()+ .nullish()+ .transform((val) => val ?? "unknown"),+ /**+ * 'edit' or 'read'/'run' or 'home'+ */+ mode: z.enum(["edit", "read", "home", "run"]).transform((val): AppMode => {+ if (val === "run") {+ return "read";+ }+ return val;+ }),+ /**+ * marimo config+ */+ config: passthroughObject,+ /**+ * marimo config overrides+ */+ configOverrides: passthroughObject,+ /**+ * marimo app config+ */+ appConfig: passthroughObject,+ /**+ * show code in run mode+ */+ view: z+ .object({+ showAppCode: z.boolean().default(true),+ })+ .nullish()+ .transform((val) => val ?? { showAppCode: true }),++ /**+ * server token+ */+ serverToken: z+ .string()+ .nullish()+ .transform((val) => val ?? ""),+});++function initStore(options: unknown) {+ const parsedOptions = mountOptionsSchema.safeParse(options);+ if (!parsedOptions.success) {+ Logger.error("Invalid marimo mount options", parsedOptions.error);+ throw new Error("Invalid marimo mount options");+ }+ const mode = parsedOptions.data.mode as AppMode;+ preloadPage(mode);++ // Files+ store.set(filenameAtom, parsedOptions.data.filename);+ store.set(codeAtom, parsedOptions.data.code);+ store.set(initialModeAtom, mode);++ // Meta+ store.set(marimoVersionAtom, parsedOptions.data.version);+ store.set(showCodeInRunModeAtom, parsedOptions.data.view.showAppCode);+ store.set(viewStateAtom, { mode, cellAnchor: null });+ store.set(serverTokenAtom, parsedOptions.data.serverToken);++ // Config+ store.set(+ configOverridesAtom,+ parseConfigOverrides(parsedOptions.data.configOverrides),+ );+ store.set(userConfigAtom, parseUserConfig(parsedOptions.data.config));+ store.set(appConfigAtom, parseAppConfig(parsedOptions.data.appConfig));+}++export const visibleForTesting = {+ reset: () => {+ hasMounted = false;+ },+};diff --git a/frontend/src/utils/__tests__/local-storage.test.ts b/frontend/src/utils/__tests__/local-storage.test.tsindex 907b8f69ed..3626aa50d1 100644--- a/frontend/src/utils/__tests__/local-storage.test.ts+++ b/frontend/src/utils/__tests__/local-storage.test.ts@@ -4,7 +4,7 @@ import { describe, it, expect, afterEach } from "vitest";import { NotebookScopedLocalStorage } from "../localStorage";import { z } from "zod";import { store } from "@/core/state/jotai";-import { filenameAtom } from "@/core/saving/filenameAtom";+import { filenameAtom } from "@/core/saving/file-state";describe("NotebookScopedLocalStorage", () => {const schema = z.object({diff --git a/frontend/src/utils/localStorage.ts b/frontend/src/utils/localStorage.tsindex aaf1000cc6..48ad585df1 100644--- a/frontend/src/utils/localStorage.ts+++ b/frontend/src/utils/localStorage.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { filenameAtom } from "@/core/saving/filenameAtom";+import { filenameAtom } from "@/core/saving/file-state";import { store } from "@/core/state/jotai";import type { ZodType, ZodTypeDef } from "zod";import { Logger } from "./Logger";diff --git a/frontend/src/utils/vitals.ts b/frontend/src/utils/vitals.tsindex 22a0fe0db9..0b5eff8877 100644--- a/frontend/src/utils/vitals.ts+++ b/frontend/src/utils/vitals.ts@@ -2,6 +2,10 @@import { Logger } from "./Logger";export async function reportVitals() {+ if (typeof document === "undefined") {+ return;+ }+const { onLCP, onINP, onCLS } = await import("web-vitals");Logger.log("Reporting vitals");const logMetric = (metric: {diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 008cfcef6a..584ea1820f 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -38,25 +38,24 @@ const htmlDevPlugin = (): Plugin => {html = html.replace("{{ base_url }}", "");html = html.replace("{{ title }}", "marimo");html = html.replace(- "{{ user_config }}",+ "'{{ mount_config }}'",JSON.stringify({- // Add/remove user config here while developing- // runtime: {- // auto_instantiate: false,- // },+ filename: "notebook.py",+ mode: modeFromUrl,+ // If VITE_MARIMO_VERSION is defined, pull the local version of marimo+ // Otherwise, pull the latest version of marimo from PyPI+ version: process.env.VITE_MARIMO_VERSION ? "local" : "latest",+ config: {+ // Add/remove user config here while developing+ // runtime: {+ // auto_instantiate: false,+ // },+ },+ configOverrides: {},+ appConfig: {},+ serverToken: "",}),);- html = html.replace("{{ app_config }}", JSON.stringify({}));- html = html.replace("{{ server_token }}", "");- 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 }}", modeFromUrl);html = html.replace(/<\/head>/, "<marimo-wasm></marimo-wasm></head>");return html;}@@ -138,15 +137,7 @@ If the server is already running, make sure it is using port ${SERVER_PORT} with}// copies these elements from server to dev- const copyElements = [- "title",- "marimo-filename",- "marimo-version",- "marimo-mode",- "marimo-user-config",- "marimo-app-config",- "marimo-server-token",- ];+ const copyElements = ["title", "marimo-filename"];// remove from devcopyElements.forEach((id) => {@@ -157,6 +148,13 @@ If the server is already running, make sure it is using port ${SERVER_PORT} with}element.remove();});+ // Remove script that contains __MARIMO_MOUNT_CONFIG__+ const scriptsDev = devDoc.querySelectorAll("script");+ scriptsDev.forEach((script) => {+ if (script.innerHTML.includes("__MARIMO_MOUNT_CONFIG__")) {+ script.remove();+ }+ });// copy from servercopyElements.forEach((id) => {@@ -174,6 +172,12 @@ If the server is already running, make sure it is using port ${SERVER_PORT} withdevDoc.head.append(style);});+ // Copy scripts+ const scripts = serverDoc.querySelectorAll("script");+ scripts.forEach((script) => {+ devDoc.head.append(script);+ });+return `<!DOCTYPE html>\n${devDoc.documentElement.outerHTML}`;},};diff --git a/marimo/_islands/_island_generator.py b/marimo/_islands/_island_generator.pyindex 3b012bdb95..075ad956cd 100644--- a/marimo/_islands/_island_generator.py+++ b/marimo/_islands/_island_generator.py@@ -420,7 +420,6 @@ class MarimoIslandGenerator:marimo_tags = """<marimo-filename hidden></marimo-filename>- <marimo-mode data-mode='read' hidden></marimo-mode>""".strip()return dedent(diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex e92c997666..9f253a0b81 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -20,6 +20,53 @@ from marimo._server.tokens import SkewProtectionTokenfrom marimo._types.ids import CellId_tfrom marimo._utils.versions import is_editable+MOUNT_CONFIG_TEMPLATE = "'{{ mount_config }}'"+++def _get_mount_config(+ *,+ filename: Optional[str],+ mode: Literal["edit", "home", "read"],+ server_token: SkewProtectionToken,+ user_config: MarimoConfig,+ config_overrides: PartialMarimoConfig,+ app_config: Optional[_AppConfig],+ version: Optional[str] = None,+ show_app_code: bool = True,+) -> str:+ """+ Return a JSON string with custom indentation and sorting.+ """++ options: dict[str, Any] = {+ "filename": filename,+ "mode": mode,+ "version": version or get_version(),+ "server_token": str(server_token),+ "user_config": user_config,+ "config_overrides": config_overrides,+ "app_config": _del_none_or_empty(app_config.asdict())+ if app_config+ else None,+ "view": {+ "showAppCode": show_app_code,+ },+ }++ return """{{+ "filename": {filename},+ "mode": {mode},+ "version": {version},+ "serverToken": {server_token},+ "config": {user_config},+ "configOverrides": {config_overrides},+ "appConfig": {app_config},+ "view": {view},+ }}+""".format(+ **{k: json.dumps(v, sort_keys=True) for k, v in options.items()}+ ).strip()+def home_page_template(html: str,@@ -29,15 +76,20 @@ def home_page_template(server_token: SkewProtectionToken,) -> str:html = html.replace("{{ base_url }}", base_url)- html = html.replace("{{ user_config }}", json.dumps(user_config))- html = html.replace("{{ config_overrides }}", json.dumps(config_overrides))- html = html.replace("{{ server_token }}", str(server_token))- html = html.replace("{{ version }}", get_version())-html = html.replace("{{ title }}", "marimo")- html = html.replace("{{ app_config }}", json.dumps({}))html = html.replace("{{ filename }}", "")- html = html.replace("{{ mode }}", "home")++ html = html.replace(+ MOUNT_CONFIG_TEMPLATE,+ _get_mount_config(+ filename=None,+ mode="home",+ server_token=server_token,+ user_config=user_config,+ config_overrides=config_overrides,+ app_config=None,+ ),+ )# Add custom CSS from display confightml = _inject_custom_css_for_config(html, user_config)@@ -56,10 +108,19 @@ def notebook_page_template(mode: SessionMode,) -> str:html = html.replace("{{ base_url }}", base_url)- html = html.replace("{{ user_config }}", json.dumps(user_config))- html = html.replace("{{ config_overrides }}", json.dumps(config_overrides))- html = html.replace("{{ server_token }}", str(server_token))- html = html.replace("{{ version }}", get_version())++ html = html.replace("{{ filename }}", filename or "")+ html = html.replace(+ MOUNT_CONFIG_TEMPLATE,+ _get_mount_config(+ filename=filename,+ mode="read" if mode == SessionMode.RUN else "edit",+ server_token=server_token,+ user_config=user_config,+ config_overrides=config_overrides,+ app_config=app_config,+ ),+ )html = html.replace("{{ title }}",@@ -69,14 +130,7 @@ def notebook_page_template(else app_config.app_title),)- html = html.replace(- "{{ app_config }}", json.dumps(_del_none_or_empty(app_config.asdict()))- )- html = html.replace("{{ filename }}", filename or "")- html = html.replace(- "{{ mode }}",- "read" if mode == SessionMode.RUN else "edit",- )+# If has custom css, inline the css and add to the headif app_config.css_file:css_contents = read_css_file(app_config.css_file, filename=filename)@@ -123,16 +177,24 @@ def static_notebook_template(asset_url = f"https://cdn.jsdelivr.net/npm/@marimo-team/frontend@{__version__}/dist"html = html.replace("{{ base_url }}", "")+ filename = os.path.basename(filepath or "")+ html = html.replace("{{ filename }}", filename or "")+# We don't need all this user config when we export the notebook,# but we do need some:# - display.theme# - display.cell_outputhtml = html.replace(- "{{ user_config }}", json.dumps(user_config, sort_keys=True)+ MOUNT_CONFIG_TEMPLATE,+ _get_mount_config(+ filename=filename,+ mode="read",+ server_token=server_token,+ user_config=user_config,+ config_overrides=config_overrides,+ app_config=app_config,+ ),)- html = html.replace("{{ config_overrides }}", json.dumps(config_overrides))- html = html.replace("{{ server_token }}", str(server_token))- html = html.replace("{{ version }}", get_version())html = html.replace("{{ title }}",@@ -142,12 +204,6 @@ def static_notebook_template(else app_config.app_title),)- html = html.replace(- "{{ app_config }}",- json.dumps(_del_none_or_empty(app_config.asdict()), sort_keys=True),- )- html = html.replace("{{ filename }}", os.path.basename(filepath or ""))- html = html.replace("{{ mode }}", "read")serialized_cell_outputs = {cell_id: _serialize_to_base64(json.dumps(output.asdict()))@@ -274,16 +330,23 @@ def wasm_notebook_template(if app_config.app_title is Noneelse app_config.app_title,)- body = body.replace("{{ user_config }}", json.dumps(user_config))++ body = body.replace("{{ filename }}", "notebook.py")body = body.replace(- "{{ app_config }}", json.dumps(_del_none_or_empty(app_config.asdict()))+ MOUNT_CONFIG_TEMPLATE,+ _get_mount_config(+ # WASM runtime currently expect this to be notebook.py instead of the actual filename+ filename="notebook.py",+ mode="edit" if mode == "edit" else "read",+ server_token=SkewProtectionToken("unused"),+ user_config=user_config,+ config_overrides=config_overrides,+ app_config=app_config,+ version=version,+ show_app_code=show_code,+ ),)- body = body.replace("{{ config_overrides }}", json.dumps(config_overrides))- body = body.replace("{{ server_token }}", "123")- body = body.replace("{{ version }}", version)- # WASM runtime currently expect this to be notebook.py instead of the actual filename- body = body.replace("{{ filename }}", "notebook.py")- body = body.replace("{{ mode }}", "edit" if mode == "edit" else "read")+body = body.replace("</head>", '<marimo-wasm hidden=""></marimo-wasm></head>')@@ -333,7 +396,7 @@ def wasm_notebook_template(body = body.replace("</head>",- f'<marimo-code hidden="" data-show-code="{json.dumps(show_code)}">{uri_encode_component(code)}</marimo-code></head>',+ f'<marimo-code hidden="">{uri_encode_component(code)}</marimo-code></head>',)return bodydiff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.pyindex 391a60d069..fa4e09afa1 100644--- a/tests/_cli/test_cli.py+++ b/tests/_cli/test_cli.py@@ -213,13 +213,13 @@ def test_cli_edit_none() -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='home'", contents)+ _check_contents(p, b'"mode": "home"', contents)_check_contents(p,- f"marimo-version data-version='{get_version()}'".encode(),+ f'"version": "{get_version()}"'.encode(),contents,)- _check_contents(p, b"marimo-server-token", contents)+ _check_contents(p, b'"serverToken": ', contents)def test_cli_edit_token() -> None:@@ -239,13 +239,13 @@ def test_cli_edit_token() -> None:])contents = _try_fetch(port, "localhost", "secret")- _check_contents(p, b"marimo-mode data-mode='home'", contents)+ _check_contents(p, b'"mode": "home"', contents)_check_contents(p,- f"marimo-version data-version='{get_version()}'".encode(),+ f'"version": "{get_version()}"'.encode(),contents,)- _check_contents(p, b"marimo-server-token", contents)+ _check_contents(p, b'"serverToken": ', contents)def test_cli_edit_directory() -> None:@@ -264,13 +264,13 @@ def test_cli_edit_directory() -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='home'", contents)+ _check_contents(p, b'"mode": "home"', contents)_check_contents(p,- f"marimo-version data-version='{get_version()}'".encode(),+ f'"version": "{get_version()}"'.encode(),contents,)- _check_contents(p, b"marimo-server-token", contents)+ _check_contents(p, b'"serverToken": ', contents)def test_cli_edit_new_file() -> None:@@ -290,11 +290,9 @@ def test_cli_edit_new_file() -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )- _check_contents(p, b"marimo-server-token", contents)+ _check_contents(p, b'"mode": "edit"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)+ _check_contents(p, b'"serverToken": ', contents)def test_cli_edit_with_additional_args(temp_marimo_file: str) -> None:@@ -315,10 +313,8 @@ def test_cli_edit_with_additional_args(temp_marimo_file: str) -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )+ _check_contents(p, b'"mode": "edit"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)@pytest.mark.skipif(@@ -336,7 +332,7 @@ def test_cli_edit_update_check() -> None:env=env,)contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='home'", contents)+ _check_contents(p, b'"mode": "home"', contents)state_contents = _read_toml(os.path.join(tempdir, CONFIG_ROOT_DIR, "state.toml")@@ -365,7 +361,7 @@ def test_cli_edit_skip_update_check() -> None:env={**os.environ, "MARIMO_PYTEST_HOME_DIR": tempdir},)contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='home'", contents)+ _check_contents(p, b'"mode": "home"', contents)state_contents = _read_toml(os.path.join(tempdir, CONFIG_ROOT_DIR, "state.toml")@@ -382,11 +378,9 @@ def test_cli_new() -> None:["marimo", "new", "-p", str(port), "--headless", "--no-token"])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )- _check_contents(p, b"marimo-server-token", contents)+ _check_contents(p, b'"mode": "edit"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)+ _check_contents(p, b'"serverToken": ', contents)def test_cli_run(temp_marimo_file: str) -> None:@@ -395,10 +389,8 @@ def test_cli_run(temp_marimo_file: str) -> None:["marimo", "run", temp_marimo_file, "-p", str(port), "--headless"])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='read'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )+ _check_contents(p, b'"mode": "read"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)def test_cli_run_with_show_code(temp_marimo_file: str) -> None:@@ -415,10 +407,8 @@ def test_cli_run_with_show_code(temp_marimo_file: str) -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='read'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )+ _check_contents(p, b'"mode": "read"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)def test_cli_run_with_additional_args(temp_marimo_file: str) -> None:@@ -437,10 +427,8 @@ def test_cli_run_with_additional_args(temp_marimo_file: str) -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='read'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )+ _check_contents(p, b'"mode": "read"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)def test_cli_tutorial() -> None:@@ -457,10 +445,8 @@ def test_cli_tutorial() -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )+ _check_contents(p, b'"mode": "edit"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)_check_contents(p, b"intro.py", contents)@@ -478,10 +464,8 @@ def test_cli_md_tutorial() -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )+ _check_contents(p, b'"mode": "edit"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)_check_contents(p, b"markdown-format.md", contents)@@ -491,10 +475,8 @@ def test_cli_md_run(temp_md_marimo_file: str) -> None:["marimo", "run", temp_md_marimo_file, "-p", str(port), "--headless"])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='read'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )+ _check_contents(p, b'"mode": "read"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)def test_cli_md_edit(temp_md_marimo_file: str) -> None:@@ -512,10 +494,8 @@ def test_cli_md_edit(temp_md_marimo_file: str) -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)- _check_contents(- p, f"marimo-version data-version='{get_version()}'".encode(), contents- )+ _check_contents(p, b'"mode": "edit"', contents)+ _check_contents(p, f'"version": "{get_version()}"'.encode(), contents)def test_cli_custom_host() -> None:@@ -535,7 +515,7 @@ def test_cli_custom_host() -> None:])contents = _try_fetch(port, host)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)+ _check_contents(p, b'"mode": "edit"', contents)@pytest.mark.skipif(not HAS_UV, reason="uv is required for sandbox tests")@@ -554,7 +534,7 @@ def test_cli_sandbox_edit(temp_marimo_file: str) -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)+ _check_contents(p, b"edit", contents)@pytest.mark.skipif(not HAS_UV, reason="uv is required for sandbox tests")@@ -573,7 +553,7 @@ def test_cli_sandbox_edit_no_prompt(temp_marimo_file: str) -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)+ _check_contents(p, b"edit", contents)@pytest.mark.skipif(not HAS_UV, reason="uv is required for sandbox tests")@@ -594,7 +574,7 @@ def test_cli_sandbox_edit_new_file() -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)+ _check_contents(p, b"edit", contents)@pytest.mark.skipif(is_windows(), reason="Windows will prompt for Docker")@@ -612,7 +592,7 @@ def test_cli_edit_by_url() -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='edit'", contents)+ _check_contents(p, b'"mode": "edit"', contents)@pytest.mark.skipif(not HAS_UV, reason="uv is required for sandbox tests")@@ -630,7 +610,7 @@ def test_cli_sandbox_run(temp_marimo_file: str) -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='read'", contents)+ _check_contents(p, b"read", contents)@pytest.mark.skipif(not HAS_UV, reason="uv is required for sandbox tests")@@ -648,7 +628,7 @@ def test_cli_sandbox_run_no_prompt(temp_marimo_file: str) -> None:])contents = _try_fetch(port)- _check_contents(p, b"marimo-mode data-mode='read'", contents)+ _check_contents(p, b'"mode": "read"', contents)@pytest.mark.skipif(not HAS_UV, reason="uv is required for sandbox tests")@@ -680,7 +660,7 @@ def test_cli_sandbox_run_with_python_version(f"Server failed to start. stdout:\n{stdout}\nstderr:\n{stderr}")- _check_contents(p, b"marimo-mode data-mode='read'", contents)+ _check_contents(p, b"read", contents)p.terminate()p.wait(timeout=5)diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex 6186701ff5..58a5819c91 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -80,12 +80,10 @@ class TestExportHTML:)assert p.returncode == 0, p.stderr.decode()html = Path(out_dir / "index.html").read_text()- assert "<marimo-mode data-mode='edit'" in html- assert (- '<marimo-code hidden="" data-show-code="false"></marimo-code>'- not in html- )+ assert '"mode": "edit"' in html+ assert '<marimo-code hidden=""></marimo-code>' not in htmlassert "<marimo-wasm" in html+ assert '"showAppCode": false' in htmlassert Path(out_dir / ".nojekyll").exists()@staticmethod@@ -199,11 +197,9 @@ class TestExportHTML:)assert p.returncode == 0, p.stderr.decode()html = Path(out_dir / "index.html").read_text()- assert "<marimo-mode data-mode='read'" in html- assert (- '<marimo-code hidden="" data-show-code="false"></marimo-code>'- not in html- )+ assert '"mode": "read"' in html+ assert '<marimo-code hidden=""></marimo-code>' not in html+ assert '"showAppCode": false' in htmlassert "<marimo-wasm" in html@pytest.mark.skipif(diff --git a/tests/_islands/snapshots/header.txt b/tests/_islands/snapshots/header.txtindex 1e2d9243c7..2b012b6c71 100644--- a/tests/_islands/snapshots/header.txt+++ b/tests/_islands/snapshots/header.txt@@ -1,21 +1,20 @@<script type="module" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/main.js"></script>- <link- href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/style.css"- rel="stylesheet"- crossorigin="anonymous"- />- <link rel="preconnect" href="https://fonts.googleapis.com" />- <link- rel="preconnect"- href="https://fonts.gstatic.com"- crossorigin- />- <link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap" rel="stylesheet" />- <link- rel="stylesheet"- href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"- integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"- crossorigin="anonymous"- />- <marimo-filename hidden></marimo-filename>-<marimo-mode data-mode='read' hidden></marimo-mode>\ No newline at end of file+<link+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/style.css"+ rel="stylesheet"+ crossorigin="anonymous"+/>+<link rel="preconnect" href="https://fonts.googleapis.com" />+<link+ rel="preconnect"+ href="https://fonts.gstatic.com"+ crossorigin+/>+<link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap" rel="stylesheet" />+<link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"+ integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"+ crossorigin="anonymous"+/>+<marimo-filename hidden></marimo-filename>\ No newline at end of filediff --git a/tests/_islands/snapshots/html.txt b/tests/_islands/snapshots/html.txtindex 39b470253f..33fd1e8801 100644--- a/tests/_islands/snapshots/html.txt+++ b/tests/_islands/snapshots/html.txt@@ -4,26 +4,25 @@<meta charset="UTF-8" /><title> main </title><script type="module" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/main.js"></script>- <link- href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/style.css"- rel="stylesheet"- crossorigin="anonymous"- />- <link rel="preconnect" href="https://fonts.googleapis.com" />- <link- rel="preconnect"- href="https://fonts.gstatic.com"- crossorigin- />- <link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap" rel="stylesheet" />- <link- rel="stylesheet"- href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"- integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"- crossorigin="anonymous"- />- <marimo-filename hidden></marimo-filename>-<marimo-mode data-mode='read' hidden></marimo-mode>+<link+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/style.css"+ rel="stylesheet"+ crossorigin="anonymous"+/>+<link rel="preconnect" href="https://fonts.googleapis.com" />+<link+ rel="preconnect"+ href="https://fonts.gstatic.com"+ crossorigin+/>+<link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap" rel="stylesheet" />+<link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"+ integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"+ crossorigin="anonymous"+/>+<marimo-filename hidden></marimo-filename></head><body><div style="margin: auto; max-width: 740px;">diff --git a/tests/_server/api/endpoints/test_assets.py b/tests/_server/api/endpoints/test_assets.pyindex e9a93fdfc8..9d1277bd2e 100644--- a/tests/_server/api/endpoints/test_assets.py+++ b/tests/_server/api/endpoints/test_assets.py@@ -34,7 +34,7 @@ def test_index(client: TestClient) -> None:assert f"<marimo-filename hidden>{filename}</marimo-filename>" in contentassert filename is not Noneassert filename in content- assert "<marimo-mode data-mode='edit'" in content+ assert '"mode": "edit"' in contentassert f"<title>{title}</title>" in content# Check for /public file service worker@@ -53,7 +53,7 @@ def test_index_when_empty(client: TestClient) -> None:assert response.status_code == 200, response.textcontent = response.textassert "<marimo-filename hidden></marimo-filename>" in content- assert "<marimo-mode data-mode='home'" in content+ assert '"mode": "home"' in contentassert "<title>marimo</title>" in content@@ -69,7 +69,7 @@ def test_index_when_new_file(client: TestClient) -> None:assert response.status_code == 200, response.textcontent = response.textassert "<marimo-filename hidden></marimo-filename>" in content- assert "<marimo-mode data-mode='edit'" in content+ assert '"mode": "edit"' in contentassert "<title>marimo</title>" in content@@ -82,7 +82,7 @@ def test_index_with_directory(client: TestClient) -> None:assert response.status_code == 200, response.textcontent = response.textassert "<marimo-filename" in content- assert "<marimo-mode data-mode='home'" in content+ assert '"mode": "home"' in contentassert "<title>marimo</title>" in contentdiff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.pyindex 5a152d7b34..55947f1cf8 100644--- a/tests/_server/export/test_exporter.py+++ b/tests/_server/export/test_exporter.py@@ -334,7 +334,7 @@ async def test_export_wasm_edit():assert filename == "notebook.wasm.html"assert "alert(" in content- assert "mode='edit'" in content+ assert '"mode": "edit"' in contentasync def test_export_wasm_run():@@ -358,7 +358,7 @@ async def test_export_wasm_run():assert filename == "notebook.wasm.html"assert "alert(" in content- assert "mode='read'" in content+ assert '"mode": "read"' in contentasync def test_export_html_with_layout(tmp_path: Path):diff --git a/tests/_server/templates/data/index.html b/tests/_server/templates/data/index.htmlindex 3047ac8a1d..a333f30e40 100644--- a/tests/_server/templates/data/index.html+++ b/tests/_server/templates/data/index.html@@ -53,14 +53,12 @@}</script><marimo-filename hidden>{{ filename }}</marimo-filename>- <marimo-mode data-mode='{{ mode }}' hidden></marimo-mode>- <marimo-version data-version='{{ version }}' hidden></marimo-version>- <marimo-user-config data-config='{{ user_config }}' data-overrides='{{ config_overrides }}' hidden></marimo-user-config>- <marimo-app-config data-config='{{ app_config }}' hidden></marimo-app-config>- <marimo-server-token data-token='{{ server_token }}' hidden></marimo-server-token>+ <script>+ window.__MARIMO_MOUNT_CONFIG__ = '{{ mount_config }}';+ </script><title>{{ title }}</title><script type="module" crossorigin src="./assets/index-h93-9ptT.js"></script>- <link rel="stylesheet" crossorigin href="./assets/index-Bkoicf0g.css">+ <link rel="stylesheet" crossorigin href="./assets/index-Bkoicf0g.css" /></head><body><div id="root"></div>diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txtindex ad851abdb1..5fc06173c9 100644--- a/tests/_server/templates/snapshots/export1.txt+++ b/tests/_server/templates/snapshots/export1.txt@@ -53,14 +53,21 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <marimo-mode data-mode='read' hidden></marimo-mode>- <marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>- <marimo-app-config data-config='{"sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>- <marimo-server-token data-token='token' hidden></marimo-server-token>+ <script>+ window.__MARIMO_MOUNT_CONFIG__ = {+ "filename": "notebook.py",+ "mode": "read",+ "version": "0.0.0",+ "serverToken": "token",+ "config": {"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},+ "configOverrides": {"formatting": {"line_length": 100}},+ "appConfig": {"sql_output": "auto", "width": "compact"},+ "view": {"showAppCode": true},+ };+ </script><title>notebook</title><script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>- <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"" /><script data-marimo="true">window.__MARIMO_STATIC__ = {};diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txtindex 1f65793fa1..05eda50f61 100644--- a/tests/_server/templates/snapshots/export2.txt+++ b/tests/_server/templates/snapshots/export2.txt@@ -53,14 +53,21 @@}</script><marimo-filename hidden></marimo-filename>- <marimo-mode data-mode='read' hidden></marimo-mode>- <marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>- <marimo-app-config data-config='{"sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>- <marimo-server-token data-token='token' hidden></marimo-server-token>+ <script>+ window.__MARIMO_MOUNT_CONFIG__ = {+ "filename": "",+ "mode": "read",+ "version": "0.0.0",+ "serverToken": "token",+ "config": {"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},+ "configOverrides": {"formatting": {"line_length": 100}},+ "appConfig": {"sql_output": "auto", "width": "compact"},+ "view": {"showAppCode": true},+ };+ </script><title>marimo</title><script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>- <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"" /><script data-marimo="true">window.__MARIMO_STATIC__ = {};diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txtindex 9f2b44d4f8..e45ea3245c 100644--- a/tests/_server/templates/snapshots/export3.txt+++ b/tests/_server/templates/snapshots/export3.txt@@ -53,14 +53,21 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <marimo-mode data-mode='read' hidden></marimo-mode>- <marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>- <marimo-app-config data-config='{"sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>- <marimo-server-token data-token='token' hidden></marimo-server-token>+ <script>+ window.__MARIMO_MOUNT_CONFIG__ = {+ "filename": "notebook.py",+ "mode": "read",+ "version": "0.0.0",+ "serverToken": "token",+ "config": {"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},+ "configOverrides": {"formatting": {"line_length": 100}},+ "appConfig": {"sql_output": "auto", "width": "compact"},+ "view": {"showAppCode": true},+ };+ </script><title>notebook</title><script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>- <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"" /><script data-marimo="true">window.__MARIMO_STATIC__ = {};diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txtindex 389e9adb0d..5c8812b001 100644--- a/tests/_server/templates/snapshots/export4.txt+++ b/tests/_server/templates/snapshots/export4.txt@@ -53,14 +53,21 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <marimo-mode data-mode='read' hidden></marimo-mode>- <marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>- <marimo-app-config data-config='{"css_file": "custom.css", "sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>- <marimo-server-token data-token='token' hidden></marimo-server-token>+ <script>+ window.__MARIMO_MOUNT_CONFIG__ = {+ "filename": "notebook.py",+ "mode": "read",+ "version": "0.0.0",+ "serverToken": "token",+ "config": {"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},+ "configOverrides": {"formatting": {"line_length": 100}},+ "appConfig": {"css_file": "custom.css", "sql_output": "auto", "width": "compact"},+ "view": {"showAppCode": true},+ };+ </script><title>notebook</title><script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>- <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"" /><script data-marimo="true">window.__MARIMO_STATIC__ = {};diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txtindex e3ec48b7d1..df83cc97fb 100644--- a/tests/_server/templates/snapshots/export5.txt+++ b/tests/_server/templates/snapshots/export5.txt@@ -53,14 +53,21 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <marimo-mode data-mode='read' hidden></marimo-mode>- <marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>- <marimo-app-config data-config='{"app_title": "My App", "html_head_file": "head.html", "sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>- <marimo-server-token data-token='token' hidden></marimo-server-token>+ <script>+ window.__MARIMO_MOUNT_CONFIG__ = {+ "filename": "notebook.py",+ "mode": "read",+ "version": "0.0.0",+ "serverToken": "token",+ "config": {"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},+ "configOverrides": {"formatting": {"line_length": 100}},+ "appConfig": {"app_title": "My App", "html_head_file": "head.html", "sql_output": "auto", "width": "compact"},+ "view": {"showAppCode": true},+ };+ </script><title>My App</title><script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>- <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"" /><script data-marimo="true">window.__MARIMO_STATIC__ = {};diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txtindex 896f3e48ca..3d5fdf19d4 100644--- a/tests/_server/templates/snapshots/export6.txt+++ b/tests/_server/templates/snapshots/export6.txt@@ -53,14 +53,21 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <marimo-mode data-mode='read' hidden></marimo-mode>- <marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "custom_css": ["custom1.css", "custom2.css"], "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>- <marimo-app-config data-config='{"sql_output": "auto", "width": "compact"}' hidden></marimo-app-config>- <marimo-server-token data-token='token' hidden></marimo-server-token>+ <script>+ window.__MARIMO_MOUNT_CONFIG__ = {+ "filename": "notebook.py",+ "mode": "read",+ "version": "0.0.0",+ "serverToken": "token",+ "config": {"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "custom_css": ["custom1.css", "custom2.css"], "dataframes": "rich", "default_table_page_size": 10, "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "pixi"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},+ "configOverrides": {"formatting": {"line_length": 100}},+ "appConfig": {"sql_output": "auto", "width": "compact"},+ "view": {"showAppCode": true},+ };+ </script><title>notebook</title><script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>- <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"" /><script data-marimo="true">window.__MARIMO_STATIC__ = {};diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex d75983650c..88b1d5488c 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -26,6 +26,11 @@ snapshot = snapshotter(__file__)default_config = merge_default_config({})+def _assert_no_leftover_replacements(result: str) -> None:+ has_replacement = "{{" in result and "}}" in result+ assert not has_replacement, f"Found {{}} in {result}"++class TestNotebookPageTemplate(unittest.TestCase):def setUp(self) -> None:tmp_path = Path(tempfile.mkdtemp())@@ -61,6 +66,7 @@ class TestNotebookPageTemplate(unittest.TestCase):assert str(self.server_token) in resultassert self.filename.name in resultassert "read" in result+ _assert_no_leftover_replacements(result)def test_notebook_page_template_no_filename(self) -> None:result = templates.notebook_page_template(@@ -78,6 +84,7 @@ class TestNotebookPageTemplate(unittest.TestCase):assert str(self.server_token) in resultassert "<title>marimo</title>" in resultassert "read" in result+ _assert_no_leftover_replacements(result)def test_notebook_page_template_edit_mode(self) -> None:result = templates.notebook_page_template(@@ -95,6 +102,7 @@ class TestNotebookPageTemplate(unittest.TestCase):assert str(self.server_token) in resultassert self.filename.name in resultassert "edit" in result+ _assert_no_leftover_replacements(result)def test_notebook_page_template_custom_css(self) -> None:# Create css file@@ -115,6 +123,7 @@ class TestNotebookPageTemplate(unittest.TestCase):)assert css in result+ _assert_no_leftover_replacements(result)def test_notebook_page_template_custom_head(self) -> None:# Create html head file@@ -145,6 +154,7 @@ class TestNotebookPageTemplate(unittest.TestCase):)assert head in result+ _assert_no_leftover_replacements(result)def test_notebook_page_template_with_custom_css_config(self) -> None:# Create CSS files@@ -174,6 +184,7 @@ class TestNotebookPageTemplate(unittest.TestCase):assert css1 in resultassert css2 in resultassert "<style title='marimo-custom'>" in result+ _assert_no_leftover_replacements(result)def test_notebook_page_template_with_absolute_custom_css(self) -> None:# Create CSS file with absolute path@@ -198,6 +209,7 @@ class TestNotebookPageTemplate(unittest.TestCase):assert css in resultassert "<style title='marimo-custom'>" in result+ _assert_no_leftover_replacements(result)def test_notebook_page_template_with_config_overrides_custom_css(self,@@ -224,6 +236,7 @@ class TestNotebookPageTemplate(unittest.TestCase):assert css1 in resultassert "<style title='marimo-custom'>" in result+ _assert_no_leftover_replacements(result)def test_notebook_page_template_with_nonexistent_custom_css(self) -> None:# Update config with nonexistent CSS path@@ -243,6 +256,7 @@ class TestNotebookPageTemplate(unittest.TestCase):assert "nonexistent.css" in resultassert "<style title='marimo-custom'>" not in result+ _assert_no_leftover_replacements(result)class TestHomePageTemplate(unittest.TestCase):@@ -273,11 +287,12 @@ class TestHomePageTemplate(unittest.TestCase):assert self.base_url not in resultassert str(self.server_token) in result- assert json.dumps(self.user_config) in result+ assert json.dumps(self.user_config, sort_keys=True) in resultassert "marimo" in resultassert json.dumps({}) in resultassert "" in resultassert "home" in result+ _assert_no_leftover_replacements(result)class TestStaticNotebookTemplate(unittest.TestCase):@@ -351,6 +366,7 @@ class TestStaticNotebookTemplate(unittest.TestCase):)snapshot("export1.txt", normalize_index_html(result))+ _assert_no_leftover_replacements(result)def test_static_notebook_template_no_filename(self) -> None:result = templates.static_notebook_template(@@ -372,6 +388,7 @@ class TestStaticNotebookTemplate(unittest.TestCase):)snapshot("export2.txt", normalize_index_html(result))+ _assert_no_leftover_replacements(result)def test_static_notebook_template_no_code(self) -> None:result = templates.static_notebook_template(@@ -393,6 +410,7 @@ class TestStaticNotebookTemplate(unittest.TestCase):)snapshot("export3.txt", normalize_index_html(result))+ _assert_no_leftover_replacements(result)def test_static_notebook_template_with_css(self) -> None:# Create css file@@ -420,6 +438,7 @@ class TestStaticNotebookTemplate(unittest.TestCase):)snapshot("export4.txt", normalize_index_html(result))+ _assert_no_leftover_replacements(result)def test_static_notebook_template_with_head(self) -> None:# Create html head file@@ -457,6 +476,7 @@ class TestStaticNotebookTemplate(unittest.TestCase):)snapshot("export5.txt", normalize_index_html(result))+ _assert_no_leftover_replacements(result)def test_static_notebook_template_with_custom_css_config(self) -> None:# Create CSS files@@ -494,6 +514,7 @@ class TestStaticNotebookTemplate(unittest.TestCase):assert css2 in resultassert "<style title='marimo-custom'>" in resultsnapshot("export6.txt", normalize_index_html(result))+ _assert_no_leftover_replacements(result)def test_static_notebook_template_with_absolute_custom_css(self) -> None:# Create CSS file with absolute path@@ -525,6 +546,7 @@ class TestStaticNotebookTemplate(unittest.TestCase):assert css in resultassert "<style title='marimo-custom'>" in result+ _assert_no_leftover_replacements(result)def test_static_notebook_template_with_nonexistent_custom_css(self,@@ -553,6 +575,7 @@ class TestStaticNotebookTemplate(unittest.TestCase):assert "nonexistent.css" in resultassert "<style title='marimo-custom'>" not in result+ _assert_no_leftover_replacements(result)class TestWasmNotebookTemplate(unittest.TestCase):@@ -589,10 +612,12 @@ class TestWasmNotebookTemplate(unittest.TestCase):assert self.filename.name in resultassert self.mode in result- assert json.dumps(self.user_config) in result+ assert json.dumps(self.user_config, sort_keys=True) in resultassert '<marimo-wasm hidden="">' in result- assert '<marimo-code hidden="" data-show-code="false">' in result+ assert '<marimo-code hidden="">' in result+ assert '"showAppCode": false' in resultassert "<title>notebook</title>" in result+ _assert_no_leftover_replacements(result)def test_wasm_notebook_template_custom_css_and_assets(self) -> None:# Create css file@@ -617,7 +642,9 @@ class TestWasmNotebookTemplate(unittest.TestCase):assert css in resultassert '<marimo-wasm hidden="">' in resultassert "https://my.cdn.com/assets/" in result- assert '<marimo-code hidden="" data-show-code="true">' in result+ assert '<marimo-code hidden="">' in result+ assert '"showAppCode": true' in result+ _assert_no_leftover_replacements(result)def test_wasm_notebook_template_custom_head(self) -> None:# Create html head file@@ -652,7 +679,9 @@ class TestWasmNotebookTemplate(unittest.TestCase):assert head in resultassert '<marimo-wasm hidden="">' in result- assert '<marimo-code hidden="" data-show-code="false">' in result+ assert '<marimo-code hidden="">' in result+ assert '"showAppCode": false' in resultassert "#save-button" in resultassert "#filename-input" in resultassert "<title>My App</title>" in result+ _assert_no_leftover_replacements(result)