Skip to content

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.

feat: HTML and WASM export of Reveal slides (#10703)

Péter Gyarmati24d3abcd672a
diff --git a/docs/guides/apps.md b/docs/guides/apps.md
index bd004e6648..3652c5e935 100644
--- a/docs/guides/apps.md
+++ b/docs/guides/apps.md
@@ -91,6 +91,26 @@ If you prefer a slideshow-like experience, you can use the slides layout. Enable
- Add speaker notes at the bottom of each slide and launch speaker view by pressing `S`.
- Powered by [reveal.js](https://revealjs.com/), so you can use most of its features like keyboard shortcuts, navigation, etc.
+#### Export slides
+
+Export a notebook that uses the slides layout as static HTML or WebAssembly HTML:
+
+```bash
+marimo export html presentation.py -o presentation.html
+marimo export html-wasm presentation.py -o presentation --mode run
+```
+
+WebAssembly exports (html-wasm) require an HTTP server. Serve the output directory
+locally with `python -m http.server --directory presentation`.
+
+Both formats preserve slide types, fragments, speaker notes, and deck settings.
+Static HTML includes the outputs generated during export and supports speaker
+view. WebAssembly HTML runs Python in the browser, so notebook controls remain
+interactive. Speaker view is not available in WebAssembly HTML exports.
+
+Speaker notes are embedded in the HTML file and readable by anyone who
+receives it.
+
#### Styling slides
The slides layout is rendered with [reveal.js](https://revealjs.com/), so you
diff --git a/docs/guides/exporting/static_html.md b/docs/guides/exporting/static_html.md
index 707c115e54..2b403896ee 100644
--- a/docs/guides/exporting/static_html.md
+++ b/docs/guides/exporting/static_html.md
@@ -54,6 +54,8 @@ be non-zero. However, the export result may still be generated, with the error
included in the output. Errors can be ignored by appending `|| true` to the
command, e.g. `marimo export html notebook.py || true`.
+**Slides.** If your notebook is configured with the slides layout, a HTML reveal.js slide deck is created. It preserves slide structure, speaker notes and deck settings. Speaker notes are embedded in the HTML file and readable by anyone who receives it.
+
## Pre-render HTML exports
Static marimo exports execute Javascript to render the notebook source code as HTML at browser runtime. If you would like to directly serve the HTML representation of your notebook, you can run the following post-processing script and serve the resulting file instead.
diff --git a/docs/guides/exporting/webassembly_html.md b/docs/guides/exporting/webassembly_html.md
index 27ed688321..1b6791a9a6 100644
--- a/docs/guides/exporting/webassembly_html.md
+++ b/docs/guides/exporting/webassembly_html.md
@@ -13,6 +13,15 @@ marimo export html-wasm notebook.py -o output_dir --mode run
marimo export html-wasm notebook.py -o output_dir --mode edit
```
+With `--mode run`, a notebook that uses the slides layout opens as a reveal.js
+deck. The export preserves slide types, fragments, speaker notes, and deck
+settings. Python runs in the browser, so notebook controls remain interactive.
+
+`--mode edit` opens the notebook editor instead of the slides layout. Speaker
+view is not available in WebAssembly HTML exports.
+
+Speaker notes are embedded in the HTML file and readable by anyone who receives it.
+
The exported HTML file will run your notebook using WebAssembly, making it completely self-contained and executable in the browser. This means users can interact with your notebook without needing Python or marimo installed.
Options:
diff --git a/frontend/e2e-tests/slides.spec.ts b/frontend/e2e-tests/slides.spec.ts
index 8eb70fa4b2..ed7cbc9d1f 100644
--- a/frontend/e2e-tests/slides.spec.ts
+++ b/frontend/e2e-tests/slides.spec.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import path from "node:path";
import { fileURLToPath } from "node:url";
import { expect, test } from "@playwright/test";
import { getAppUrl } from "../playwright.config";
@@ -7,6 +8,9 @@ import { openCommandPalette, takeScreenshot } from "./helper";
import { waitForMarimoApp } from "./test-utils";
const __filename = fileURLToPath(import.meta.url);
+const staticRoot = fileURLToPath(
+ new URL("../../marimo/_static/", import.meta.url),
+);
const appUrl = getAppUrl("slides.py");
test.beforeEach(async ({ page }, info) => {
@@ -79,3 +83,49 @@ test("slides fullscreen", async ({ page }) => {
// Slides container should still be visible after exiting fullscreen
await expect(slidesContainer).toBeVisible();
});
+
+test("slides static HTML export", async ({ page }, testInfo) => {
+ await openCommandPalette({ page, command: "Download as HTML" });
+
+ const [download] = await Promise.all([
+ page.waitForEvent("download"),
+ page.getByRole("button", { name: "Export HTML" }).click(),
+ ]);
+ const outputPath = testInfo.outputPath("slides.html");
+ await download.saveAs(outputPath);
+
+ const exportPage = await page.context().newPage();
+ await exportPage.route("http://slides.test/slides.html", async (route) => {
+ await route.fulfill({ path: outputPath });
+ });
+ await exportPage.route(
+ "https://cdn.jsdelivr.net/npm/@marimo-team/frontend@*/dist/**",
+ async (route) => {
+ const pathname = new URL(route.request().url()).pathname;
+ const assetPath = pathname.slice(pathname.indexOf("/dist/") + 6);
+ await route.fulfill({ path: path.join(staticRoot, assetPath) });
+ },
+ );
+ await exportPage.goto("http://slides.test/slides.html#/1/0", {
+ waitUntil: "domcontentloaded",
+ });
+
+ const slidesContainer = exportPage.locator(".reveal.mo-slides-theme");
+ await expect(slidesContainer).toBeVisible();
+ const slides = slidesContainer.locator(".slides > section");
+ await expect(slides).toHaveCount(2);
+ await expect(slides.nth(1)).toHaveClass(/present/);
+ await expect(exportPage.getByTestId("static-notebook-banner")).toHaveCount(0);
+ await expect(exportPage.getByTestId("watermark")).toHaveCount(0);
+
+ await slidesContainer.click();
+ await exportPage.keyboard.press("ArrowLeft");
+ await expect(slides.nth(0)).toHaveClass(/present/);
+ await expect
+ .poll(() =>
+ exportPage
+ .locator("#App")
+ .evaluate((app) => app.scrollHeight <= app.clientHeight),
+ )
+ .toBe(true);
+});
diff --git a/frontend/src/__tests__/mount.test.ts b/frontend/src/__tests__/mount.test.ts
index 764ebf9f76..8262c94c21 100644
--- a/frontend/src/__tests__/mount.test.ts
+++ b/frontend/src/__tests__/mount.test.ts
@@ -1,8 +1,12 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { getSerializedLayout } from "@/core/layout/layout";
+import { initialLayoutState, layoutStateAtom } from "@/core/layout/state";
+import { kioskModeAtom } from "@/core/mode";
import { connectionAtom } from "@/core/network/connection";
import { store } from "@/core/state/jotai";
+import { isStaticNotebook } from "@/core/static/static-state";
import { WebSocketState } from "@/core/websocket/types";
import { mount, visibleForTesting } from "../mount";
@@ -15,6 +19,8 @@ vi.mock("react-dom/client", () => ({
// Mock static state
vi.mock("@/core/static/static-state", () => ({
+ getStaticModelNotifications: vi.fn(() => undefined),
+ getStaticVirtualFiles: vi.fn(() => ({})),
isStaticNotebook: vi.fn(() => false),
}));
@@ -46,6 +52,10 @@ describe("mount", () => {
beforeEach(() => {
visibleForTesting.reset();
+ window.history.replaceState({}, "", "/");
+ vi.mocked(isStaticNotebook).mockReturnValue(false);
+ store.set(layoutStateAtom, initialLayoutState());
+ store.set(kioskModeAtom, false);
// Reset connection atom to initial state
store.set(connectionAtom, { state: WebSocketState.NOT_STARTED });
});
@@ -66,6 +76,12 @@ describe("mount", () => {
serverToken: "",
};
+ const mountRead = (options: Record<string, unknown> = {}) =>
+ mount(
+ { ...baseOptions, mode: "read", runtimeConfig: [], ...options },
+ mockElement,
+ );
+
describe("connection state initialization", () => {
it("should set connection to CONNECTING when runtimeConfig has lazy=false", () => {
mount(
@@ -106,8 +122,7 @@ describe("mount", () => {
expect(connection.state).toBe(WebSocketState.NOT_STARTED);
});
- it("should keep connection as NOT_STARTED for static notebooks even with lazy=false", async () => {
- const { isStaticNotebook } = await import("@/core/static/static-state");
+ it("should keep connection as NOT_STARTED for static notebooks even with lazy=false", () => {
vi.mocked(isStaticNotebook).mockReturnValue(true);
// Reset mount state to allow another mount
@@ -125,4 +140,41 @@ describe("mount", () => {
expect(connection.state).toBe(WebSocketState.NOT_STARTED);
});
});
+
+ it("hydrates the layout embedded in the mount config", () => {
+ const layout = {
+ type: "slides",
+ data: {
+ deck: { transition: "fade", verticalAlign: "center" },
+ },
+ };
+ const error = mountRead({ layout });
+
+ expect(error).toBeUndefined();
+ const layoutState = store.get(layoutStateAtom);
+ expect(layoutState.selectedLayout).toBe("slides");
+ expect(getSerializedLayout()).toEqual({
+ type: "slides",
+ data: {
+ cells: [],
+ deck: { transition: "fade", verticalAlign: "center" },
+ },
+ });
+ });
+
+ it("uses vertical layout for malformed mount data", () => {
+ const error = mountRead({ layout: { data: {} } });
+
+ expect(error).toBeUndefined();
+ expect(store.get(layoutStateAtom)).toEqual(initialLayoutState());
+ });
+
+ it("starts kiosk clients in kiosk mode", () => {
+ window.history.replaceState({}, "", "/?kiosk=true");
+
+ const error = mountRead();
+
+ expect(error).toBeUndefined();
+ expect(store.get(kioskModeAtom)).toBe(true);
+ });
});
diff --git a/frontend/src/components/editor/__tests__/viewer-banner.test.tsx b/frontend/src/components/editor/__tests__/viewer-banner.test.tsx
index 5aaa6d976d..0dcbfba667 100644
--- a/frontend/src/components/editor/__tests__/viewer-banner.test.tsx
+++ b/frontend/src/components/editor/__tests__/viewer-banner.test.tsx
@@ -3,7 +3,7 @@ import { render, screen } from "@testing-library/react";
import { createStore, Provider } from "jotai";
import { describe, expect, it, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
-import { layoutStateAtom } from "@/core/layout/layout";
+import { layoutStateAtom } from "@/core/layout/state";
import { kioskModeAtom, viewStateAtom } from "@/core/mode";
import { API } from "@/core/network/api";
import { ViewerBanner } from "../viewer-banner";
diff --git a/frontend/src/components/editor/actions/export-dialog/__tests__/export-notebook.test.ts b/frontend/src/components/editor/actions/export-dialog/__tests__/export-notebook.test.ts
index 5054d91fd2..36fb38ea81 100644
--- a/frontend/src/components/editor/actions/export-dialog/__tests__/export-notebook.test.ts
+++ b/frontend/src/components/editor/actions/export-dialog/__tests__/export-notebook.test.ts
@@ -43,12 +43,17 @@ describe("exportNotebook", () => {
let captureOutputs: Mock<() => Promise<void>>;
let capturePNG: Mock<() => Promise<void>>;
let downloadFile: Mock<(file: ExportedFile) => void>;
+ let getLayout: Mock;
beforeEach(() => {
requests = makeRequests();
captureOutputs = vi.fn().mockResolvedValue(undefined);
capturePNG = vi.fn().mockResolvedValue(undefined);
downloadFile = vi.fn();
+ getLayout = vi.fn().mockResolvedValue({
+ type: "slides",
+ data: { deck: { transition: "fade" } },
+ });
});
const run = (
@@ -61,6 +66,7 @@ describe("exportNotebook", () => {
requests,
sourceFilename: "notebook.py",
htmlFiles: ["data.csv"],
+ getLayout,
captureOutputs,
capturePNG,
downloadFile,
@@ -73,8 +79,10 @@ describe("exportNotebook", () => {
download: false,
files: ["data.csv"],
includeCode: false,
+ layout: { type: "slides", data: { deck: { transition: "fade" } } },
});
expect(downloadFile).toHaveBeenCalledWith(FILE);
+ expect(getLayout).toHaveBeenCalledOnce();
});
it("passes the selected Markdown flavor through the session API", async () => {
@@ -84,6 +92,7 @@ describe("exportNotebook", () => {
download: false,
flavor: "qmd",
});
+ expect(getLayout).not.toHaveBeenCalled();
expect(downloadFile).toHaveBeenCalledWith(FILE);
});
diff --git a/frontend/src/components/editor/actions/export-dialog/export-notebook.ts b/frontend/src/components/editor/actions/export-dialog/export-notebook.ts
index 08c2a701db..aa0a7e85fd 100644
--- a/frontend/src/components/editor/actions/export-dialog/export-notebook.ts
+++ b/frontend/src/components/editor/actions/export-dialog/export-notebook.ts
@@ -1,6 +1,10 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import type { EditRequests, ExportedFile } from "@/core/network/types";
+import type {
+ EditRequests,
+ ExportAsHTMLRequest,
+ ExportedFile,
+} from "@/core/network/types";
import { assertNever } from "@/utils/assertNever";
import { runServerSidePDFDownload } from "../pdf-export";
import type { ExportFormat, ExportOptions } from "./state";
@@ -21,6 +25,7 @@ export async function exportNotebook({
requests,
sourceFilename,
htmlFiles,
+ getLayout,
captureOutputs,
capturePNG,
downloadFile,
@@ -30,6 +35,7 @@ export async function exportNotebook({
requests: ExportRequests;
sourceFilename: string;
htmlFiles: string[];
+ getLayout: () => Promise<ExportAsHTMLRequest["layout"]>;
captureOutputs: () => Promise<void>;
capturePNG: () => Promise<void>;
downloadFile: (file: ExportedFile) => void;
@@ -40,6 +46,7 @@ export async function exportNotebook({
download: false,
files: htmlFiles,
includeCode: options.html.includeCode,
+ layout: await getLayout(),
});
downloadFile(file);
return;
diff --git a/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts b/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts
index 23194645f2..99bc11b611 100644
--- a/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts
+++ b/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts
@@ -7,6 +7,7 @@ import {
updateCellOutputsWithScreenshots,
useEnrichCellOutputs,
} from "@/core/export/hooks";
+import { getExportLayout } from "@/core/export/layout";
import { runDuringPresentMode, useInstallAllowed } from "@/core/mode";
import { useRequestClient } from "@/core/network/requests";
import type { ExportAvailabilityResponse } from "@/core/network/types";
@@ -349,6 +350,7 @@ function useExportDialogAction({
requests,
sourceFilename,
htmlFiles: VirtualFileTracker.INSTANCE.filenames(),
+ getLayout: getExportLayout,
captureOutputs: () => captureOutputs(progress),
capturePNG,
downloadFile: downloadExportedFile,
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index 37488560b9..a4227a8f0c 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -66,7 +66,7 @@ import { disabledCellIds } from "@/core/cells/utils";
import { capabilitiesAtom } from "@/core/config/capabilities";
import { aiEnabledAtom, useResolvedMarimoConfig } from "@/core/config/config";
import { Constants } from "@/core/constants";
-import { useLayoutActions, useLayoutState } from "@/core/layout/layout";
+import { useLayoutActions, useLayoutState } from "@/core/layout/state";
import { useTogglePresenting } from "@/core/layout/useTogglePresenting";
import { kioskModeAtom, viewStateAtom } from "@/core/mode";
import { useRequestClient } from "@/core/network/requests";
diff --git a/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx b/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx
index 6976b2aa48..286e072b10 100644
--- a/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx
+++ b/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx
@@ -18,7 +18,7 @@ import {
invalidateDataSourceDiscovery,
} from "@/core/datasets/data-source-discovery";
import { DiscoverDataSources } from "@/core/datasets/request-registry";
-import { layoutStateAtom } from "@/core/layout/layout";
+import { layoutStateAtom } from "@/core/layout/state";
import { kioskModeAtom, viewStateAtom } from "@/core/mode";
import { connectionAtom } from "@/core/network/connection";
import { requestClientAtom } from "@/core/network/requests";
diff --git a/frontend/src/components/editor/renderers/__tests__/cells-renderer.test.tsx b/frontend/src/components/editor/renderers/__tests__/cells-renderer.test.tsx
index 0edc812348..ba35907913 100644
--- a/frontend/src/components/editor/renderers/__tests__/cells-renderer.test.tsx
+++ b/frontend/src/components/editor/renderers/__tests__/cells-renderer.test.tsx
@@ -4,7 +4,7 @@ import { createStore, Provider } from "jotai";
import { describe, expect, it } from "vitest";
import { MockRequestClient } from "@/__mocks__/requests";
import { parseAppConfig } from "@/core/config/config-schema";
-import { initialLayoutState, layoutStateAtom } from "@/core/layout/layout";
+import { initialLayoutState, layoutStateAtom } from "@/core/layout/state";
import { type AppMode, kioskModeAtom } from "@/core/mode";
import { requestClientAtom } from "@/core/network/requests";
import { CellsRenderer } from "../cells-renderer";
diff --git a/frontend/src/components/editor/renderers/cells-renderer.tsx b/frontend/src/components/editor/renderers/cells-renderer.tsx
index afa03cf071..74aa080995 100644
--- a/frontend/src/components/editor/renderers/cells-renderer.tsx
+++ b/frontend/src/components/editor/renderers/cells-renderer.tsx
@@ -5,19 +5,15 @@ import type React from "react";
import { memo, type PropsWithChildren } from "react";
import { flattenTopLevelNotebookCells, useNotebook } from "@/core/cells/cells";
import type { AppConfig } from "@/core/config/config-schema";
-import { KnownQueryParams } from "@/core/constants";
+import { resolveLayoutData } from "@/core/layout/layout";
import {
- type LayoutData,
+ resolveLayoutType,
useLayoutActions,
useLayoutState,
-} from "@/core/layout/layout";
+} from "@/core/layout/state";
import { type AppMode, kioskModeAtom } from "@/core/mode";
import { cellRendererPlugins } from "./plugins";
-import {
- type ICellRendererPlugin,
- type LayoutType,
- OVERRIDABLE_LAYOUT_TYPES,
-} from "./types";
+import type { ICellRendererPlugin } from "./types";
interface Props {
appConfig: AppConfig;
@@ -26,7 +22,7 @@ interface Props {
export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
({ appConfig, mode, children }) => {
- const { selectedLayout, layoutData } = useLayoutState();
+ const { selectedLayout } = useLayoutState();
const kioskMode = useAtomValue(kioskModeAtom);
// Render children (the editable notebook) in edit mode, and in present
@@ -43,14 +39,11 @@ export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
// We allow overriding the layout type by url params when in 'read' mode,
// for example, forcing the 'slides' view.
// https://marimo.app/?slug=14ovyr8&mode=run&view-as=slides
- let finalLayout = selectedLayout;
- const params = new URLSearchParams(window.location.search);
- if (mode === "read" && params.has(KnownQueryParams.viewAs)) {
- const viewAsOverride = params.get(KnownQueryParams.viewAs);
- if (OVERRIDABLE_LAYOUT_TYPES.includes(viewAsOverride as LayoutType)) {
- finalLayout = viewAsOverride as LayoutType;
- }
- }
+ const finalLayout = resolveLayoutType({
+ selectedLayout,
+ isReading: mode === "read",
+ searchParams: new URLSearchParams(window.location.search),
+ });
const plugin = cellRendererPlugins.find((p) => p.type === finalLayout);
@@ -60,13 +53,7 @@ export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
}
return (
- <PluginCellRenderer
- appConfig={appConfig}
- mode={mode}
- plugin={plugin}
- layoutData={layoutData}
- finalLayout={finalLayout}
- />
+ <PluginCellRenderer appConfig={appConfig} mode={mode} plugin={plugin} />
);
},
);
@@ -77,15 +64,15 @@ interface PluginCellRendererProps extends PropsWithChildren<Props> {
mode: AppMode;
// oxlint-disable-next-line typescript/no-explicit-any
plugin: ICellRendererPlugin<any, any>;
- layoutData: Partial<Record<LayoutType, LayoutData>>;
- finalLayout: LayoutType;
}
export const PluginCellRenderer = (props: PluginCellRendererProps) => {
- const { appConfig, mode, plugin, layoutData, finalLayout } = props;
+ const { appConfig, mode, plugin } = props;
+ const layoutState = useLayoutState();
const notebook = useNotebook();
const { setCurrentLayoutData } = useLayoutActions();
const cells = flattenTopLevelNotebookCells(notebook);
+ const layout = resolveLayoutData({ state: layoutState, plugin, cells });
const Renderer = plugin.Component;
const body = (
@@ -93,7 +80,7 @@ export const PluginCellRenderer = (props: PluginCellRendererProps) => {
appConfig={appConfig}
mode={mode}
cells={cells}
- layout={layoutData[finalLayout] || plugin.getInitialLayout(cells)}
+ layout={layout}
setLayout={setCurrentLayoutData}
/>
);
diff --git a/frontend/src/components/editor/renderers/grid-layout/__tests__/plugin.test.ts b/frontend/src/components/editor/renderers/grid-layout/__tests__/plugin.test.ts
new file mode 100644
index 0000000000..388302e085
--- /dev/null
+++ b/frontend/src/components/editor/renderers/grid-layout/__tests__/plugin.test.ts
@@ -0,0 +1,42 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import { MockNotebook } from "@/__mocks__/notebook";
+import { cellId } from "@/__tests__/branded";
+import { deserializeLayout } from "../../plugins";
+
+describe("GridLayoutPlugin validation", () => {
+ it("preserves valid cell positions while normalizing optional fields", () => {
+ const a = cellId("a");
+ const b = cellId("b");
+ const { cellData } = MockNotebook.notebookState({
+ cellData: { [a]: {}, [b]: {} },
+ });
+ const layout = deserializeLayout({
+ type: "grid",
+ data: {
+ columns: 12,
+ rowHeight: 20,
+ maxWidth: null,
+ cells: [
+ {
+ position: [0, 0, 6, 4],
+ side: "right",
+ },
+ {
+ position: [1, 4, 6, 4],
+ side: "future-side",
+ },
+ ],
+ },
+ cells: [cellData[a], cellData[b]],
+ });
+
+ expect(layout.maxWidth).toBeUndefined();
+ expect(layout.cellSide).toEqual(new Map([["a", "right"]]));
+ expect(layout.cells).toEqual([
+ { i: "a", x: 0, y: 0, w: 6, h: 4 },
+ { i: "b", x: 1, y: 4, w: 6, h: 4 },
+ ]);
+ });
+});
diff --git a/frontend/src/components/editor/renderers/grid-layout/plugin.tsx b/frontend/src/components/editor/renderers/grid-layout/plugin.tsx
index 66ac0e7f66..373a669cf6 100644
--- a/frontend/src/components/editor/renderers/grid-layout/plugin.tsx
+++ b/frontend/src/components/editor/renderers/grid-layout/plugin.tsx
@@ -24,19 +24,29 @@ export const GridLayoutPlugin: ICellRendererPlugin<
type: "grid",
name: "Grid",
- validator: z.object({
+ validator: z.looseObject({
columns: z.number().min(1),
rowHeight: z.number().min(1),
- maxWidth: z.number().optional(),
- bordered: z.boolean().optional(),
+ maxWidth: z
+ .number()
+ .nullish()
+ .transform((value) => value ?? undefined)
+ .catch(undefined),
+ bordered: z.boolean().optional().catch(undefined),
cells: z.array(
- z.object({
- position: z
- .tuple([z.number(), z.number(), z.number(), z.number()])
- .nullable(),
- scrollable: z.boolean().optional(),
- alignment: z.enum(["top", "bottom", "left", "right"]).optional(),
- }),
+ z
+ .looseObject({
+ position: z
+ .tuple([z.number(), z.number(), z.number(), z.number()])
+ .nullable()
+ .catch(null),
+ scrollable: z.boolean().optional().catch(undefined),
+ side: z
+ .enum(["top", "bottom", "left", "right"])
+ .optional()
+ .catch(undefined),
+ })
+ .catch({ position: null }),
),
}),
diff --git a/frontend/src/components/editor/renderers/layout-select.tsx b/frontend/src/components/editor/renderers/layout-select.tsx
index 064a37f9b2..37490c5acd 100644
--- a/frontend/src/components/editor/renderers/layout-select.tsx
+++ b/frontend/src/components/editor/renderers/layout-select.tsx
@@ -17,7 +17,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { getFeatureFlag } from "@/core/config/feature-flag";
-import { useLayoutActions, useLayoutState } from "@/core/layout/layout";
+import { useLayoutActions, useLayoutState } from "@/core/layout/state";
import { isWasm } from "@/core/wasm/utils";
import { logNever } from "@/utils/assertNever";
import { Strings } from "@/utils/strings";
diff --git a/frontend/src/components/editor/renderers/plugins.ts b/frontend/src/components/editor/renderers/plugins.ts
index 8532a29e1a..a811ccf385 100644
--- a/frontend/src/components/editor/renderers/plugins.ts
+++ b/frontend/src/components/editor/renderers/plugins.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { CellData } from "@/core/cells/types";
+import { Logger } from "@/utils/Logger";
import { GridLayoutPlugin } from "./grid-layout/plugin";
import { SlidesLayoutPlugin } from "./slides-layout/plugin";
import type { ICellRendererPlugin, LayoutType } from "./types";
@@ -27,5 +28,10 @@ export function deserializeLayout({
if (plugin === undefined) {
throw new Error(`Unknown layout type: ${type}`);
}
- return plugin.deserializeLayout(data, cells);
+ const parsed = plugin.validator.safeParse(data);
+ if (!parsed.success) {
+ Logger.warn(`Invalid ${type} layout`, parsed.error);
+ return plugin.getInitialLayout(cells);
+ }
+ return plugin.deserializeLayout(parsed.data, cells);
}
diff --git a/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts b/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts
index 0ce0f79955..849be4557c 100644
--- a/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts
+++ b/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts
@@ -1,10 +1,12 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import { SlidesLayoutPlugin } from "../plugin";
import type { CellData } from "@/core/cells/types";
import type { CellId } from "@/core/cells/ids";
import { cellId } from "@/__tests__/branded";
+import { deserializeLayout } from "../../plugins";
+import { Logger } from "@/utils/Logger";
function makeCell(id: string, code = "print('hi')"): CellData {
return {
@@ -35,12 +37,36 @@ describe("SlidesLayoutPlugin validator", () => {
).toBe(true);
});
- it("rejects unknown slide types", () => {
- expect(
- SlidesLayoutPlugin.validator.safeParse({
- cells: [{ type: "bogus" }],
- }).success,
- ).toBe(false);
+ it("drops unsupported fields while preserving the rest of the layout", () => {
+ const layout = deserializeLayout({
+ type: "slides",
+ data: {
+ cells: [
+ {
+ type: "bogus",
+ speakerNotes: "Keep these notes",
+ futureCellOption: true,
+ },
+ { type: "fragment" },
+ ],
+ deck: {
+ transition: "future-transition",
+ verticalAlign: "center",
+ futureDeckOption: true,
+ },
+ },
+ cells: [makeCell("a"), makeCell("b")],
+ });
+
+ expect(layout.cells.get("a" as CellId)).toEqual({
+ speakerNotes: "Keep these notes",
+ futureCellOption: true,
+ });
+ expect(layout.cells.get("b" as CellId)).toEqual({ type: "fragment" });
+ expect(layout.deck).toEqual({
+ verticalAlign: "center",
+ futureDeckOption: true,
+ });
});
it("accepts each valid deck vertical alignment", () => {
@@ -52,12 +78,21 @@ describe("SlidesLayoutPlugin validator", () => {
}
});
- it("rejects an unknown deck vertical alignment", () => {
- expect(
- SlidesLayoutPlugin.validator.safeParse({
- deck: { verticalAlign: "middle" },
- }).success,
- ).toBe(false);
+ it("falls back to the initial layout when serialized data is invalid", () => {
+ const warning = vi
+ .spyOn(Logger, "warn")
+ .mockImplementation(() => undefined);
+ try {
+ expect(
+ deserializeLayout({
+ type: "slides",
+ data: null,
+ cells: [makeCell("a")],
+ }),
+ ).toEqual({ cells: new Map(), deck: {} });
+ } finally {
+ warning.mockRestore();
+ }
});
});
@@ -169,8 +204,7 @@ describe("SlidesLayoutPlugin serializeLayout", () => {
* shape to `serializedSnapshot` so a diff will surface the change in review.
*
* Every snapshot is required to:
- * 1. pass the zod validator (today it is defined but not applied on load;
- * this guards against regressions once it is),
+ * 1. pass the zod validator used during load,
* 2. deserialize without throwing,
* 3. survive a deserialize → serialize → deserialize round trip without
* throwing or losing any user-set field carried in the expectations.
diff --git a/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx b/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx
index 8be22154d6..979b525ed3 100644
--- a/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx
+++ b/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx
@@ -8,6 +8,7 @@ import type { ICellRendererProps } from "../types";
import type { SlidesLayout } from "./types";
import { computeSlideCellsInfo } from "./compute-slide-cells";
import { SlidesMinimap } from "@/components/slides/minimap";
+import { isSpeakerViewReceiver } from "@/components/slides/speaker-view";
import useEvent from "react-use-event-hook";
type Props = ICellRendererProps<SlidesLayout>;
@@ -38,6 +39,19 @@ export const SlidesLayoutRenderer: React.FC<Props> = ({
: startCellIndex;
const resolvedIndex =
activeSlideIndex === -1 ? startCellIndex : activeSlideIndex;
+ const isSpeakerReceiver = isSpeakerViewReceiver(
+ kioskMode,
+ window.location.search,
+ );
+ // Let reveal.js resolve an initial URL coordinate before React resumes
+ // controlling the deck through the active cell.
+ const isInitialDeepLink =
+ isReading && activeCellId == null && window.location.hash.startsWith("#/");
+ // Speaker-view receivers take their position from reveal.js messages and
+ // the URL hash. Controlling their index here can push the presenter back to
+ // the first slide while the receiver initializes.
+ const controlledIndex =
+ isSpeakerReceiver || isInitialDeepLink ? undefined : resolvedIndex;
const handleSlideChange = useEvent((index: number) => {
const cell = slideCells[index];
@@ -52,8 +66,8 @@ export const SlidesLayoutRenderer: React.FC<Props> = ({
layout={layout}
setLayout={setLayout}
noOutputIds={noOutputIds}
- activeIndex={resolvedIndex}
- onSlideChange={handleSlideChange}
+ activeIndex={controlledIndex}
+ onSlideChange={isSpeakerReceiver ? undefined : handleSlideChange}
configWidth={280}
mode={isReading ? "read" : mode}
isEditable={!isReading}
diff --git a/frontend/src/components/editor/renderers/slides-layout/types.ts b/frontend/src/components/editor/renderers/slides-layout/types.ts
index f4841380d7..b2e29faeb6 100644
--- a/frontend/src/components/editor/renderers/slides-layout/types.ts
+++ b/frontend/src/components/editor/renderers/slides-layout/types.ts
@@ -6,11 +6,13 @@ import type { CellId } from "@/core/cells/ids";
const SlideTypeSchema = z.enum(["slide", "sub-slide", "fragment", "skip"]);
export type SlideType = z.infer<typeof SlideTypeSchema>;
-const SlideConfigSchema = z.looseObject({
- type: SlideTypeSchema.optional(),
- speakerNotes: z.string().optional(),
- showCode: z.boolean().optional(),
-});
+const SlideConfigSchema = z
+ .looseObject({
+ type: SlideTypeSchema.optional().catch(undefined),
+ speakerNotes: z.string().optional().catch(undefined),
+ showCode: z.boolean().optional().catch(undefined),
+ })
+ .catch({});
export type SlideConfig = z.infer<typeof SlideConfigSchema>;
const DeckTransitionSchema = z.enum([
@@ -26,10 +28,12 @@ export type DeckTransition = z.infer<typeof DeckTransitionSchema>;
const DeckVerticalAlignSchema = z.enum(["top", "center", "bottom"]);
export type DeckVerticalAlign = z.infer<typeof DeckVerticalAlignSchema>;
-const DeckConfigSchema = z.looseObject({
- transition: DeckTransitionSchema.optional(),
- verticalAlign: DeckVerticalAlignSchema.optional(),
-});
+const DeckConfigSchema = z
+ .looseObject({
+ transition: DeckTransitionSchema.optional().catch(undefined),
+ verticalAlign: DeckVerticalAlignSchema.optional().catch(undefined),
+ })
+ .catch({});
export type DeckConfig = z.infer<typeof DeckConfigSchema>;
/**
@@ -41,8 +45,8 @@ export type DeckConfig = z.infer<typeof DeckConfigSchema>;
* keys are preserved (via `looseObject`) for the same reason.
*/
export const SlidesLayoutSchema = z.looseObject({
- cells: z.array(SlideConfigSchema).optional(),
- deck: DeckConfigSchema.optional(),
+ cells: z.array(SlideConfigSchema).optional().catch(undefined),
+ deck: DeckConfigSchema.optional().catch(undefined),
});
export type SerializedSlidesLayout = z.infer<typeof SlidesLayoutSchema>;
diff --git a/frontend/src/components/editor/renderers/types.ts b/frontend/src/components/editor/renderers/types.ts
index c715df22f0..ebb0e3ea40 100644
--- a/frontend/src/components/editor/renderers/types.ts
+++ b/frontend/src/components/editor/renderers/types.ts
@@ -37,11 +37,11 @@ export interface ICellRendererProps<L> {
setLayout: (layout: L) => void;
}
-export type LayoutType = "vertical" | "grid" | "slides";
-/**
- * List of supported layout types, in the order to be displayed.
- */
-export const LAYOUT_TYPES: LayoutType[] = ["vertical", "grid", "slides"];
+export const LAYOUT_TYPES = ["vertical", "grid", "slides"] as const;
+export type LayoutType = (typeof LAYOUT_TYPES)[number];
+export function isLayoutType(value: string): value is LayoutType {
+ return (LAYOUT_TYPES as readonly string[]).includes(value);
+}
/**
* Overridable layout types.
* These types can override the current layout via a URL parameter.
diff --git a/frontend/src/components/editor/viewer-banner.tsx b/frontend/src/components/editor/viewer-banner.tsx
index ad5ebc0b73..09efcfb290 100644
--- a/frontend/src/components/editor/viewer-banner.tsx
+++ b/frontend/src/components/editor/viewer-banner.tsx
@@ -3,7 +3,7 @@
import { useAtomValue } from "jotai/react";
import { ArrowRightSquareIcon, EyeIcon } from "lucide-react";
import { KnownQueryParams } from "@/core/constants";
-import { useLayoutState } from "@/core/layout/layout";
+import { useLayoutState } from "@/core/layout/state";
import { kioskModeAtom, viewStateAtom } from "@/core/mode";
import { API } from "@/core/network/api";
import { Banner } from "@/plugins/impl/common/error-banner";
diff --git a/frontend/src/components/pages/run-page.tsx b/frontend/src/components/pages/run-page.tsx
index 1e72d2ece0..2b0c412d07 100644
--- a/frontend/src/components/pages/run-page.tsx
+++ b/frontend/src/components/pages/run-page.tsx
@@ -1,12 +1,13 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { Panel, PanelGroup } from "react-resizable-panels";
+import { useAtomValue } from "jotai";
import { MarimoIcon } from "@/components/icons/marimo-icons";
import type { AppConfig } from "@/core/config/config-schema";
import { Constants } from "@/core/constants";
+import { resolveLayoutType, useLayoutState } from "@/core/layout/state";
import { RunApp } from "@/core/run-app";
-import { isStaticNotebook } from "@/core/static/static-state";
-import { isWasm } from "@/core/wasm/utils";
+import { runtimeAdapterAtom } from "@/core/runtime/adapter";
import { ContextAwarePanel } from "../editor/chrome/panels/context-aware-panel/context-aware-panel";
import { PanelsWrapper } from "../editor/chrome/wrapper/panels";
import { StaticBanner } from "../static-html/static-banner";
@@ -15,16 +16,24 @@ interface Props {
appConfig: AppConfig;
}
-const showWatermark = isWasm() || isStaticNotebook();
-
const RunPage = (props: Props) => {
+ const runtimeKind = useAtomValue(runtimeAdapterAtom).kind;
+ const isExportedNotebook = runtimeKind === "static" || runtimeKind === "wasm";
+ const { selectedLayout } = useLayoutState();
+ const finalLayout = resolveLayoutType({
+ selectedLayout,
+ isReading: true,
+ searchParams: new URLSearchParams(window.location.search),
+ });
+ const isExportedSlides = isExportedNotebook && finalLayout === "slides";
+
return (
<PanelsWrapper>
<PanelGroup direction="horizontal" autoSaveId="marimo:chrome:v1:run1">
<Panel>
- <StaticBanner />
- <RunApp appConfig={props.appConfig} />
- {showWatermark && <Watermark />}
+ {!isExportedSlides && <StaticBanner />}
+ <RunApp appConfig={props.appConfig} hideHeader={isExportedSlides} />
+ {isExportedNotebook && !isExportedSlides && <Watermark />}
</Panel>
<ContextAwarePanel />
</PanelGroup>
diff --git a/frontend/src/components/slides/__tests__/reveal-component.test.ts b/frontend/src/components/slides/__tests__/reveal-component.test.ts
index 2118da01ea..93b761ebf7 100644
--- a/frontend/src/components/slides/__tests__/reveal-component.test.ts
+++ b/frontend/src/components/slides/__tests__/reveal-component.test.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { act, renderHook } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { cellId } from "@/__tests__/branded";
import type { CellId } from "@/core/cells/ids";
import type { RuntimeCell } from "@/core/cells/types";
@@ -10,6 +10,7 @@ import {
deckSlideType,
parkedRendersSource,
shouldShowCode,
+ syncCodeToggleKeyBinding,
useParkedPreview,
} from "../reveal-component";
@@ -24,14 +25,38 @@ const cells = (
// to this test helper (see `@/__tests__/branded` for the same rationale).
const cell = (id: CellId): RuntimeCell => ({ id }) as RuntimeCell;
+describe("syncCodeToggleKeyBinding", () => {
+ it("tracks whether code is available after Reveal is ready", () => {
+ const deck = {
+ addKeyBinding: vi.fn(),
+ removeKeyBinding: vi.fn(),
+ };
+ const onToggle = vi.fn();
+
+ syncCodeToggleKeyBinding({ deck, enabled: false, onToggle });
+ expect(deck.removeKeyBinding).toHaveBeenLastCalledWith(67);
+ expect(deck.addKeyBinding).not.toHaveBeenCalled();
+
+ syncCodeToggleKeyBinding({ deck, enabled: true, onToggle });
+ expect(deck.addKeyBinding).toHaveBeenCalledWith(
+ {
+ keyCode: 67,
+ key: "C",
+ description: "Toggle code editor",
+ },
+ onToggle,
+ );
+ });
+});
+
describe("shouldShowCode", () => {
- it("is off when the code toggle is unavailable, regardless of config/override", () => {
+ it("is off when code is unavailable, regardless of config/override", () => {
expect(
shouldShowCode({
cells: cells([A, { showCode: true }]),
cellId: A,
showCodeOverrides: new Set([A]),
- codeToggleEnabled: false,
+ codeAvailable: false,
}),
).toBe(false);
});
@@ -42,7 +67,7 @@ describe("shouldShowCode", () => {
cells: cells([A, { showCode: true }]),
cellId: undefined,
showCodeOverrides: new Set(),
- codeToggleEnabled: true,
+ codeAvailable: true,
}),
).toBe(false);
});
@@ -53,7 +78,7 @@ describe("shouldShowCode", () => {
cells: cells([A, { showCode: true }]),
cellId: A,
showCodeOverrides: new Set(),
- codeToggleEnabled: true,
+ codeAvailable: true,
}),
).toBe(true);
// Missing config entry defaults to off.
@@ -62,7 +87,7 @@ describe("shouldShowCode", () => {
cells: cells(),
cellId: A,
showCodeOverrides: new Set(),
- codeToggleEnabled: true,
+ codeAvailable: true,
}),
).toBe(false);
});
@@ -74,7 +99,7 @@ describe("shouldShowCode", () => {
cells: cells(),
cellId: A,
showCodeOverrides: new Set([A]),
- codeToggleEnabled: true,
+ codeAvailable: true,
}),
).toBe(true);
// Configured + override present -> still shown; the override never hides.
@@ -83,7 +108,7 @@ describe("shouldShowCode", () => {
cells: cells([A, { showCode: true }]),
cellId: A,
showCodeOverrides: new Set([A]),
- codeToggleEnabled: true,
+ codeAvailable: true,
}),
).toBe(true);
});
diff --git a/frontend/src/components/slides/__tests__/speaker-view.test.ts b/frontend/src/components/slides/__tests__/speaker-view.test.ts
new file mode 100644
index 0000000000..e5fb3b8f40
--- /dev/null
+++ b/frontend/src/components/slides/__tests__/speaker-view.test.ts
@@ -0,0 +1,27 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import {
+ createSpeakerViewUrl,
+ isSpeakerViewReceiver,
+ supportsSpeakerView,
+} from "../speaker-view";
+
+describe("speaker view policy", () => {
+ it("builds a receiver base URL independently of the active Reveal hash", () => {
+ expect(
+ createSpeakerViewUrl("https://example.test/deck?theme=dark#/2/1"),
+ ).toBe("https://example.test/deck?theme=dark&kiosk=true&show-chrome=false");
+ });
+
+ it("recognizes kiosk receiver frames", () => {
+ expect(isSpeakerViewReceiver(true, "?kiosk=true&receiver")).toBe(true);
+ expect(isSpeakerViewReceiver(false, "?receiver")).toBe(false);
+ });
+
+ it("keeps speaker view on shared and static runtimes", () => {
+ expect(supportsSpeakerView("remote")).toBe(true);
+ expect(supportsSpeakerView("static")).toBe(true);
+ expect(supportsSpeakerView("wasm")).toBe(false);
+ });
+});
diff --git a/frontend/src/components/slides/reveal-component.tsx b/frontend/src/components/slides/reveal-component.tsx
index fadb46ddcf..7672fc88af 100644
--- a/frontend/src/components/slides/reveal-component.tsx
+++ b/frontend/src/components/slides/reveal-component.tsx
@@ -56,12 +56,45 @@ import { SlideNotesEditor } from "./slide-notes-editor";
import { buildSubslideNotes, NOTES_DIVIDER } from "./slide-notes";
import { cn } from "@/utils/cn";
import { isIslands } from "@/core/islands/utils";
+import { initialRunCompletedAtom } from "@/core/kernel/state";
import { useNotebookCodeAvailable } from "@/core/meta/code-visibility";
import { type AppMode, kioskModeAtom } from "@/core/mode";
+import { runtimeAdapterAtom } from "@/core/runtime/adapter";
import { useAtomValue } from "jotai";
import RevealNotes from "reveal.js/plugin/notes";
+import {
+ createSpeakerViewUrl,
+ isSpeakerViewReceiver,
+ supportsSpeakerView,
+} from "./speaker-view";
const ASPECT_RATIO = 16 / 9;
+const CODE_TOGGLE_KEY_CODE = 67;
+
+// Reveal retains custom key bindings after initialization. Replace the `C`
+// binding when code availability or receiver mode changes so it cannot keep a
+// stale handler.
+export function syncCodeToggleKeyBinding({
+ deck,
+ enabled,
+ onToggle,
+}: {
+ deck: Pick<RevealApi, "addKeyBinding" | "removeKeyBinding">;
+ enabled: boolean;
+ onToggle: () => void;
+}): void {
+ deck.removeKeyBinding(CODE_TOGGLE_KEY_CODE);
+ if (enabled) {
+ deck.addKeyBinding(
+ {
+ keyCode: CODE_TOGGLE_KEY_CODE,
+ key: "C",
+ description: "Toggle code editor",
+ },
+ onToggle,
+ );
+ }
+}
/**
* reveal.js caches the last visited vertical index on each stack and can
@@ -161,10 +194,10 @@ export function shouldShowCode(options: {
cells: ReadonlyMap<CellId, SlideConfig>;
cellId: CellId | undefined;
showCodeOverrides: ReadonlySet<CellId>;
- codeToggleEnabled: boolean;
+ codeAvailable: boolean;
}): boolean {
- const { cells, cellId, showCodeOverrides, codeToggleEnabled } = options;
- if (cellId == null || !codeToggleEnabled) {
+ const { cells, cellId, showCodeOverrides, codeAvailable } = options;
+ if (cellId == null || !codeAvailable) {
return false;
}
const configured = cells.get(cellId)?.showCode ?? false;
@@ -450,12 +483,15 @@ const RevealSlidesComponent = ({
const { width, height } = useSlideDimensions(containerRef);
const isFullscreen = useFullScreenElement() != null;
- // Skip the Notes plugin inside reveal's own speaker-view iframes so pressing
- // `S` there doesn't try to spawn another popup.
+ // A receiver frame cannot spawn another speaker view. WebAssembly exports
+ // also omit the plugin because each receiver would start another runtime.
const kioskMode = useAtomValue(kioskModeAtom);
+ const runtimeKind = useAtomValue(runtimeAdapterAtom).kind;
+ const initialRunCompleted = useAtomValue(initialRunCompletedAtom);
+ const canResolveInitialHash = runtimeKind !== "wasm" || initialRunCompleted;
const deckPlugins = useMemo(
- () => (kioskMode ? [] : [RevealNotes]),
- [kioskMode],
+ () => (kioskMode || !supportsSpeakerView(runtimeKind) ? [] : [RevealNotes]),
+ [kioskMode, runtimeKind],
);
// Store the state of the code toggle for each cell
@@ -464,7 +500,12 @@ const RevealSlidesComponent = ({
ReadonlySet<CellId>
>(() => new Set());
const codeAvailable = useNotebookCodeAvailable(slideCells);
- const codeToggleEnabled = !isIslands() && codeAvailable;
+ const codeRenderingEnabled = !isIslands() && codeAvailable;
+ const isSpeakerReceiver = isSpeakerViewReceiver(
+ kioskMode,
+ window.location.search,
+ );
+ const codeToggleEnabled = !isSpeakerReceiver && codeRenderingEnabled;
const activeCell = activeIndex != null ? slideCells[activeIndex] : undefined;
// Fall back to the first cell while the deck settles on an initial slide.
@@ -489,7 +530,7 @@ const RevealSlidesComponent = ({
cells: layout.cells,
cellId,
showCodeOverrides,
- codeToggleEnabled,
+ codeAvailable: codeRenderingEnabled,
});
// `C` and the toolbar button target the active slide's cell (the revealed
@@ -501,7 +542,7 @@ const RevealSlidesComponent = ({
// A slide persisted with `showCode: true` always renders code
const codeAlwaysShown =
- codeToggleEnabled &&
+ codeRenderingEnabled &&
cellIdToShowCode != null &&
(layout.cells.get(cellIdToShowCode)?.showCode ?? false);
@@ -540,10 +581,7 @@ const RevealSlidesComponent = ({
// app chrome hidden, which `<SlidesLayoutRenderer>` interprets the same as
// read mode (no minimap, sidebar, or notes editor).
const kioskUrl = useMemo(() => {
- const url = new URL(window.location.href);
- url.searchParams.set("kiosk", "true");
- url.searchParams.set("show-chrome", "false");
- return url.toString();
+ return createSpeakerViewUrl(window.location.href);
}, []);
const revealConfig: RevealConfig = useMemo(
@@ -566,6 +604,14 @@ const RevealSlidesComponent = ({
);
const navigateDeckToActiveCell = useEvent((deck: RevealApi) => {
+ if (activeIndex == null && window.location.hash.startsWith("#/")) {
+ if (!canResolveInitialHash) {
+ return;
+ }
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ clearPreviousVerticalIndices(deck);
+ return;
+ }
const target = resolveDeckNavigationTarget({
activeIndex,
cells: slideCells,
@@ -586,7 +632,13 @@ const RevealSlidesComponent = ({
return;
}
navigateDeckToActiveCell(deck);
- }, [activeIndex, cellToTarget, slideCells, navigateDeckToActiveCell]);
+ }, [
+ activeIndex,
+ canResolveInitialHash,
+ cellToTarget,
+ slideCells,
+ navigateDeckToActiveCell,
+ ]);
// Toggling code (re)mounts a CodeMirror editor on the active slide. Defer
// the state update so the button/keypress paints first and the heavier mount
@@ -612,18 +664,52 @@ const RevealSlidesComponent = ({
);
});
+ useEffect(() => {
+ const deck = deckRef.current;
+ if (deck) {
+ syncCodeToggleKeyBinding({
+ deck,
+ enabled: codeToggleEnabled,
+ onToggle: toggleShowCode,
+ });
+ }
+ return () => {
+ deckRef.current?.removeKeyBinding(CODE_TOGGLE_KEY_CODE);
+ };
+ }, [codeToggleEnabled, toggleShowCode]);
+
+ // Ignore programmatic preview navigation so the minimap selection remains
+ // pinned to the previewed cell.
+ const reportDeckCell = useEvent((deck: RevealApi) => {
+ if (parkedPreviewCell != null) {
+ return;
+ }
+ const flatIndex = resolveActiveCellIndex(
+ targetToCellIndex,
+ deck.getIndices(),
+ );
+ if (flatIndex != null) {
+ onSlideChange?.(flatIndex);
+ }
+ });
+
+ const reportCurrentCell = useEvent(() => {
+ const deck = deckRef.current;
+ if (deck) {
+ reportDeckCell(deck);
+ }
+ });
+
const handleDeckReady = useEvent((deck: RevealApi) => {
navigateDeckToActiveCell(deck);
- if (codeToggleEnabled) {
- deck.addKeyBinding(
- {
- keyCode: 67,
- key: "C",
- description: "Toggle code editor",
- },
- toggleShowCode,
- );
+ if (canResolveInitialHash) {
+ reportDeckCell(deck);
}
+ syncCodeToggleKeyBinding({
+ deck,
+ enabled: codeToggleEnabled,
+ onToggle: toggleShowCode,
+ });
// Reveal listens for `keydown` on `document` and bails when
// `document.activeElement` is an input/contenteditable (e.g. the speaker
@@ -636,27 +722,6 @@ const RevealSlidesComponent = ({
}
});
- // Forward the deck's current cell to the parent, except while a parked
- // preview is parked: every reveal.js event during that window is an echo
- // of the programmatic park (possibly with transient indices), so ignoring
- // them keeps `activeCellId` pinned on the minimap cell.
- const reportCurrentCell = useEvent(() => {
- if (parkedPreviewCell != null) {
- return;
- }
- const deck = deckRef.current;
- if (!deck) {
- return;
- }
- const flatIndex = resolveActiveCellIndex(
- targetToCellIndex,
- deck.getIndices(),
- );
- if (flatIndex != null) {
- onSlideChange?.(flatIndex);
- }
- });
-
// While parked on a preview, step through minimap order instead of
// letting reveal.js advance from the parked slide the user can't see.
const handleParkedNavKey = useEvent((event: KeyboardEvent) => {
diff --git a/frontend/src/components/slides/speaker-view.ts b/frontend/src/components/slides/speaker-view.ts
new file mode 100644
index 0000000000..53597a236b
--- /dev/null
+++ b/frontend/src/components/slides/speaker-view.ts
@@ -0,0 +1,22 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { RuntimeKind } from "@/core/runtime/adapter";
+
+export function createSpeakerViewUrl(href: string): string {
+ const url = new URL(href);
+ url.hash = "";
+ url.searchParams.set("kiosk", "true");
+ url.searchParams.set("show-chrome", "false");
+ return url.toString();
+}
+
+export function isSpeakerViewReceiver(
+ kioskMode: boolean,
+ search: string,
+): boolean {
+ return kioskMode && new URLSearchParams(search).has("receiver");
+}
+
+export function supportsSpeakerView(runtimeKind: RuntimeKind): boolean {
+ return runtimeKind !== "wasm";
+}
diff --git a/frontend/src/components/static-html/share-modal.tsx b/frontend/src/components/static-html/share-modal.tsx
index 290a85e611..244b4c00ee 100644
--- a/frontend/src/components/static-html/share-modal.tsx
+++ b/frontend/src/components/static-html/share-modal.tsx
@@ -12,6 +12,7 @@ import {
} from "@/components/ui/dialog";
import { toast } from "@/components/ui/use-toast";
import { Constants } from "@/core/constants";
+import { getExportLayout } from "@/core/export/layout";
import { useRequestClient } from "@/core/network/requests";
import { VirtualFileTracker } from "@/core/static/virtual-file-tracker";
import { copyToClipboard } from "@/utils/copy";
@@ -44,6 +45,7 @@ export const ShareStaticNotebookModal: React.FC<{
download: false,
includeCode: true,
files: VirtualFileTracker.INSTANCE.filenames(),
+ layout: await getExportLayout(),
});
const prevToast = toast({
diff --git a/frontend/src/core/cells/__tests__/document-changes.test.ts b/frontend/src/core/cells/__tests__/document-changes.test.ts
index 1a992804c5..bb12a37e02 100644
--- a/frontend/src/core/cells/__tests__/document-changes.test.ts
+++ b/frontend/src/core/cells/__tests__/document-changes.test.ts
@@ -33,14 +33,20 @@ import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
import { requestClientAtom } from "@/core/network/requests";
import type { EditRequests, RunRequests } from "@/core/network/types";
import { store } from "@/core/state/jotai";
+import { Deferred } from "@/utils/Deferred";
import { MultiColumn } from "@/utils/id-tree";
import { exportedForTesting, type NotebookState } from "../cells";
import {
type CellAction,
+ abortDocumentResync,
+ beginDocumentResync,
coalesceChanges,
+ completeDocumentResync,
type DocumentChange,
+ flushDocumentChanges,
exportedForTesting as middlewareExports,
toDocumentChanges,
+ withDocumentSave,
} from "../document-changes";
import { CellId } from "../ids";
@@ -698,15 +704,16 @@ describe("coalesceChanges", () => {
});
});
-/**
- * End-to-end of the debounced flush path: dispatch through the real middleware
- * reducer, let the debounce fire, and inspect the batch that reaches
- * sendDocumentTransaction. Coalescing only matters once edits actually share a
- * debounce window, which drainChanges-based tests can't observe.
- */
-describe("flush path coalescing", () => {
+describe("document transaction middleware", () => {
let sent: DocumentChange[][];
+ const updateCode = (cellId: CellId, code: string) => {
+ state = dispatch(state, {
+ type: "updateCellCode",
+ payload: { cellId, code, formattingChange: false },
+ });
+ };
+
beforeEach(() => {
vi.useFakeTimers();
sent = [];
@@ -732,54 +739,364 @@ describe("flush path coalescing", () => {
vi.useRealTimers();
});
- it("coalesces edit + delete of the same cell within one debounce window", () => {
+ it("coalesces edit + delete of the same cell within one debounce window", async () => {
setup("x = 1");
const [x] = state.cellIds.inOrderIds;
// Discard the create-cell from setup; it would flush as its own batch.
middlewareExports.cancelPendingChanges();
- // Same window: edit the cell, then delete it, with no timer advance.
- state = dispatch(state, {
- type: "updateCellCode",
- payload: { cellId: x, code: "x = 2", formattingChange: false },
- });
+ updateCode(x, "x = 2");
state = dispatch(state, {
type: "deleteCell",
payload: { cellId: x },
});
- // Debounced: nothing on the wire yet.
expect(sent).toEqual([]);
- vi.advanceTimersByTime(400);
+ await vi.advanceTimersByTimeAsync(400);
- // One transaction, and it is just the delete — the conflicting set-code
- // has been dropped, so the server never sees edit+delete of one cell.
expect(sent).toHaveLength(1);
expect(sent[0]).toEqual([{ type: "delete-cell", cellId: x }]);
});
- it("sends edit and delete as separate clean transactions across windows", () => {
+ it("sends edit and delete as separate clean transactions across windows", async () => {
setup("x = 1");
const [x] = state.cellIds.inOrderIds;
middlewareExports.cancelPendingChanges();
- state = dispatch(state, {
- type: "updateCellCode",
- payload: { cellId: x, code: "x = 2", formattingChange: false },
- });
- vi.advanceTimersByTime(400);
+ updateCode(x, "x = 2");
+ await vi.advanceTimersByTimeAsync(400);
state = dispatch(state, {
type: "deleteCell",
payload: { cellId: x },
});
- vi.advanceTimersByTime(400);
+ await vi.advanceTimersByTimeAsync(400);
- // Two separate, individually-valid transactions: neither conflicts, which
- // is why the bug only ever surfaced when both landed in the same window.
expect(sent).toHaveLength(2);
expect(sent[0]).toEqual([{ type: "set-code", cellId: x, code: "x = 2" }]);
expect(sent[1]).toEqual([{ type: "delete-cell", cellId: x }]);
});
+
+ it("flushes pending changes before a dependent operation", async () => {
+ setup("x = 1");
+ const [x] = state.cellIds.inOrderIds;
+ middlewareExports.cancelPendingChanges();
+ updateCode(x, "x = 2");
+
+ await flushDocumentChanges();
+
+ expect(sent).toEqual([[{ type: "set-code", cellId: x, code: "x = 2" }]]);
+ });
+
+ it("keeps a failed transaction sticky before a dependent operation", async () => {
+ const failingClient: Pick<
+ EditRequests & RunRequests,
+ "sendDocumentTransaction"
+ > = {
+ sendDocumentTransaction: async ({ changes }) => {
+ sent.push(changes);
+ throw new Error("connection lost");
+ },
+ };
+ store.set(
+ requestClientAtom,
+ failingClient as unknown as EditRequests & RunRequests,
+ );
+
+ setup("x = 1");
+ const [x] = state.cellIds.inOrderIds;
+ middlewareExports.cancelPendingChanges();
+ updateCode(x, "x = 2");
+ await vi.advanceTimersByTimeAsync(400);
+
+ updateCode(x, "x = 3");
+ await expect(flushDocumentChanges()).rejects.toThrow("connection lost");
+
+ expect(sent).toEqual([[{ type: "set-code", cellId: x, code: "x = 2" }]]);
+ });
+
+ it("resumes after a full document save establishes a fresh baseline", async () => {
+ let attempt = 0;
+ const recoveringClient: Pick<
+ EditRequests & RunRequests,
+ "sendDocumentTransaction"
+ > = {
+ sendDocumentTransaction: async ({ changes }) => {
+ sent.push(changes);
+ attempt += 1;
+ if (attempt === 1) {
+ throw new Error("connection lost");
+ }
+ return null;
+ },
+ };
+ store.set(
+ requestClientAtom,
+ recoveringClient as unknown as EditRequests & RunRequests,
+ );
+
+ setup("x = 1");
+ const [x] = state.cellIds.inOrderIds;
+ middlewareExports.cancelPendingChanges();
+ updateCode(x, "x = 2");
+ await vi.advanceTimersByTimeAsync(400);
+
+ updateCode(x, "x = 3");
+ await withDocumentSave(async () => {
+ updateCode(x, "x = 4");
+ });
+
+ await vi.advanceTimersByTimeAsync(400);
+ expect(sent).toEqual([
+ [{ type: "set-code", cellId: x, code: "x = 2" }],
+ [{ type: "set-code", cellId: x, code: "x = 4" }],
+ ]);
+ });
+
+ it("restores unsent edits when a full document save fails", async () => {
+ const firstStarted = new Deferred<void>();
+ const firstRelease = new Deferred<void>();
+ const failingClient: Pick<
+ EditRequests & RunRequests,
+ "sendDocumentTransaction"
+ > = {
+ sendDocumentTransaction: async ({ changes }) => {
+ sent.push(changes);
+ if (sent.length === 1) {
+ firstStarted.resolve();
+ await firstRelease.promise;
+ throw new Error("connection lost");
+ }
+ return null;
+ },
+ };
+ store.set(
+ requestClientAtom,
+ failingClient as unknown as EditRequests & RunRequests,
+ );
+
+ setup("x = 1");
+ const [x] = state.cellIds.inOrderIds;
+ middlewareExports.cancelPendingChanges();
+ updateCode(x, "x = 2");
+ vi.advanceTimersByTime(400);
+ await firstStarted.promise;
+
+ updateCode(x, "x = 3");
+ await vi.advanceTimersByTimeAsync(400);
+ firstRelease.resolve();
+ await expect(flushDocumentChanges()).rejects.toThrow("connection lost");
+
+ updateCode(x, "x = 4");
+ const firstResync = beginDocumentResync();
+ abortDocumentResync(firstResync);
+ const secondResync = beginDocumentResync();
+ expect(secondResync?.includedTransactions).toEqual([
+ [{ type: "set-code", cellId: x, code: "x = 3" }],
+ ]);
+ expect(secondResync?.includedChanges).toEqual([
+ { type: "set-code", cellId: x, code: "x = 4" },
+ ]);
+ await completeDocumentResync(secondResync);
+
+ updateCode(x, "x = 5");
+ await vi.advanceTimersByTimeAsync(400);
+ expect(sent.at(-1)).toEqual([
+ { type: "set-code", cellId: x, code: "x = 5" },
+ ]);
+ });
+
+ it("keeps edits debounced while an earlier transaction is in flight", async () => {
+ const firstRelease = new Deferred<void>();
+ const firstStarted = new Deferred<void>();
+ const delayedClient: Pick<
+ EditRequests & RunRequests,
+ "sendDocumentTransaction"
+ > = {
+ sendDocumentTransaction: async ({ changes }) => {
+ sent.push(changes);
+ if (sent.length === 1) {
+ firstStarted.resolve();
+ await firstRelease.promise;
+ }
+ return null;
+ },
+ };
+ store.set(
+ requestClientAtom,
+ delayedClient as unknown as EditRequests & RunRequests,
+ );
+
+ setup("x = 1");
+ const [x] = state.cellIds.inOrderIds;
+ middlewareExports.cancelPendingChanges();
+ updateCode(x, "x = 2");
+ vi.advanceTimersByTime(400);
+ await firstStarted.promise;
+
+ updateCode(x, "x = 3");
+ firstRelease.resolve();
+ await vi.advanceTimersByTimeAsync(399);
+ expect(sent).toHaveLength(1);
+
+ await vi.advanceTimersByTimeAsync(1);
+ expect(sent).toEqual([
+ [{ type: "set-code", cellId: x, code: "x = 2" }],
+ [{ type: "set-code", cellId: x, code: "x = 3" }],
+ ]);
+ });
+
+ it("waits for every transaction queued while flushing", async () => {
+ const releases = Array.from({ length: 3 }, () => new Deferred<void>());
+ const starts = Array.from({ length: 3 }, () => new Deferred<void>());
+ const orderedClient: Pick<
+ EditRequests & RunRequests,
+ "sendDocumentTransaction"
+ > = {
+ sendDocumentTransaction: async ({ changes }) => {
+ const index = sent.length;
+ sent.push(changes);
+ starts[index].resolve();
+ await releases[index].promise;
+ return null;
+ },
+ };
+ store.set(
+ requestClientAtom,
+ orderedClient as unknown as EditRequests & RunRequests,
+ );
+
+ setup("x = 1");
+ const [x] = state.cellIds.inOrderIds;
+ middlewareExports.cancelPendingChanges();
+ updateCode(x, "x = 2");
+ vi.advanceTimersByTime(400);
+ await starts[0].promise;
+
+ const flushed = flushDocumentChanges();
+
+ updateCode(x, "x = 3");
+ await vi.advanceTimersByTimeAsync(400);
+ expect(sent).toHaveLength(1);
+
+ releases[0].resolve();
+ await starts[1].promise;
+
+ updateCode(x, "x = 4");
+ await vi.advanceTimersByTimeAsync(400);
+ expect(sent).toHaveLength(2);
+
+ let flushResolved = false;
+ void flushed.then(() => {
+ flushResolved = true;
+ });
+ releases[1].resolve();
+ await starts[2].promise;
+ expect(flushResolved).toBe(false);
+
+ releases[2].resolve();
+ await flushed;
+ expect(sent).toEqual([
+ [{ type: "set-code", cellId: x, code: "x = 2" }],
+ [{ type: "set-code", cellId: x, code: "x = 3" }],
+ [{ type: "set-code", cellId: x, code: "x = 4" }],
+ ]);
+ });
+
+ it("orders a full save between earlier and later transactions", async () => {
+ const firstStarted = new Deferred<void>();
+ const firstRelease = new Deferred<void>();
+ const saveStarted = new Deferred<void>();
+ const saveRelease = new Deferred<void>();
+ const events: string[] = [];
+ const delayedClient: Pick<
+ EditRequests & RunRequests,
+ "sendDocumentTransaction"
+ > = {
+ sendDocumentTransaction: async ({ changes }) => {
+ const change = changes[0];
+ events.push("code" in change ? change.code : change.type);
+ if (events.length === 1) {
+ firstStarted.resolve();
+ await firstRelease.promise;
+ }
+ return null;
+ },
+ };
+ store.set(
+ requestClientAtom,
+ delayedClient as unknown as EditRequests & RunRequests,
+ );
+
+ setup("x = 1");
+ const [x] = state.cellIds.inOrderIds;
+ middlewareExports.cancelPendingChanges();
+ updateCode(x, "x = 2");
+ vi.advanceTimersByTime(400);
+ await firstStarted.promise;
+
+ const saving = withDocumentSave(async () => {
+ events.push("save");
+ saveStarted.resolve();
+ await saveRelease.promise;
+ });
+ expect(events).toEqual(["x = 2"]);
+
+ firstRelease.resolve();
+ await saveStarted.promise;
+ updateCode(x, "x = 3");
+ await vi.advanceTimersByTimeAsync(400);
+ expect(events).toEqual(["x = 2", "save"]);
+
+ saveRelease.resolve();
+ await saving;
+ await flushDocumentChanges();
+ expect(events).toEqual(["x = 2", "save", "x = 3"]);
+ });
+
+ it("ignores a failure from a transaction reset while in flight", async () => {
+ const firstStarted = new Deferred<void>();
+ const firstRelease = new Deferred<void>();
+ const firstFinished = new Deferred<void>();
+ const delayedClient: Pick<
+ EditRequests & RunRequests,
+ "sendDocumentTransaction"
+ > = {
+ sendDocumentTransaction: async ({ changes }) => {
+ sent.push(changes);
+ if (sent.length === 1) {
+ firstStarted.resolve();
+ try {
+ await firstRelease.promise;
+ } finally {
+ firstFinished.resolve();
+ }
+ }
+ return null;
+ },
+ };
+ store.set(
+ requestClientAtom,
+ delayedClient as unknown as EditRequests & RunRequests,
+ );
+
+ setup("x = 1");
+ const [x] = state.cellIds.inOrderIds;
+ middlewareExports.cancelPendingChanges();
+ updateCode(x, "x = 2");
+ vi.advanceTimersByTime(400);
+ await firstStarted.promise;
+
+ middlewareExports.cancelPendingChanges();
+ firstRelease.reject(new Error("stale connection failure"));
+ await firstFinished.promise;
+ await Promise.resolve();
+
+ updateCode(x, "x = 3");
+ await flushDocumentChanges();
+ expect(sent.at(-1)).toEqual([
+ { type: "set-code", cellId: x, code: "x = 3" },
+ ]);
+ });
});
diff --git a/frontend/src/core/cells/document-changes.ts b/frontend/src/core/cells/document-changes.ts
index 8c39127d88..35386471d6 100644
--- a/frontend/src/core/cells/document-changes.ts
+++ b/frontend/src/core/cells/document-changes.ts
@@ -17,6 +17,7 @@
import { debounce } from "lodash-es";
import { assertNever } from "@/utils/assertNever";
import type { DispatchedActionOf } from "@/utils/createReducer";
+import { Deferred } from "@/utils/Deferred";
import { Logger } from "@/utils/Logger";
import type { NotificationMessageData } from "../kernel/messages";
import { kioskModeAtom } from "../mode";
@@ -632,16 +633,184 @@ export function coalesceChanges(changes: DocumentChange[]): DocumentChange[] {
// ---------------------------------------------------------------------------
let pendingChanges: DocumentChange[] = [];
+let stagedTransactions: DocumentChange[][] = [];
+let transactionQueue: Promise<void> = Promise.resolve();
+let transactionGeneration = 0;
+let activeDocumentSave: Deferred<void> | null = null;
+
+type TransactionSyncState =
+ | { status: "synchronized" }
+ | { status: "failed"; error: unknown };
+
+interface DocumentResync {
+ failure: Extract<TransactionSyncState, { status: "failed" }>;
+ includedChanges: DocumentChange[];
+ includedTransactions: DocumentChange[][];
+}
-const flushChanges = debounce(() => {
+let transactionSyncState: TransactionSyncState = { status: "synchronized" };
+
+function stagePendingTransaction(): void {
+ if (transactionSyncState.status === "failed") {
+ return;
+ }
const changes = coalesceChanges(pendingChanges);
pendingChanges = [];
- if (changes.length === 0) {
+ if (changes.length > 0) {
+ stagedTransactions.push(changes);
+ }
+}
+
+async function sendStagedTransactions(generation: number): Promise<void> {
+ if (generation !== transactionGeneration) {
return;
}
- void getRequestClient().sendDocumentTransaction({ changes });
+ if (transactionSyncState.status === "failed") {
+ throw transactionSyncState.error;
+ }
+
+ while (stagedTransactions.length > 0) {
+ const changes = stagedTransactions[0];
+
+ try {
+ await getRequestClient().sendDocumentTransaction({ changes });
+ } catch (error) {
+ if (generation !== transactionGeneration) {
+ return;
+ }
+ // A transport failure is ambiguous: the server may have applied the
+ // transaction before the response was lost. Keep the failure sticky so
+ // an export cannot claim synchronization without a fresh document.
+ transactionSyncState = { status: "failed", error };
+ stagedTransactions = stagedTransactions.slice(1);
+ throw error;
+ }
+ if (generation !== transactionGeneration) {
+ return;
+ }
+ stagedTransactions.shift();
+ }
+}
+
+function queuePendingTransactions(): Promise<void> {
+ const generation = transactionGeneration;
+ const saveBarrier = activeDocumentSave?.promise ?? Promise.resolve();
+ const queued = Promise.all([
+ transactionQueue.catch(() => undefined),
+ saveBarrier,
+ ]).then(() => sendStagedTransactions(generation));
+ transactionQueue = queued;
+ return queued;
+}
+
+const flushChanges = debounce(() => {
+ stagePendingTransaction();
+ void queuePendingTransactions().catch(() => undefined);
}, 400);
+export async function flushDocumentChanges(): Promise<void> {
+ if (transactionSyncState.status === "failed") {
+ throw transactionSyncState.error;
+ }
+ flushChanges.cancel();
+ stagePendingTransaction();
+ let awaitedQueue = queuePendingTransactions();
+ while (true) {
+ await awaitedQueue;
+ flushChanges.cancel();
+ stagePendingTransaction();
+ if (
+ pendingChanges.length === 0 &&
+ stagedTransactions.length === 0 &&
+ transactionQueue === awaitedQueue
+ ) {
+ return;
+ }
+ awaitedQueue =
+ transactionQueue === awaitedQueue
+ ? queuePendingTransactions()
+ : transactionQueue;
+ }
+}
+
+export function beginDocumentResync(): DocumentResync | null {
+ if (transactionSyncState.status !== "failed") {
+ return null;
+ }
+ flushChanges.cancel();
+ const includedChanges = pendingChanges;
+ const includedTransactions = stagedTransactions;
+ pendingChanges = [];
+ stagedTransactions = [];
+ return {
+ failure: transactionSyncState,
+ includedChanges,
+ includedTransactions,
+ };
+}
+
+export function abortDocumentResync(resync: DocumentResync | null): void {
+ if (resync === null || transactionSyncState !== resync.failure) {
+ return;
+ }
+ pendingChanges = [...resync.includedChanges, ...pendingChanges];
+ stagedTransactions = [...resync.includedTransactions, ...stagedTransactions];
+}
+
+export async function completeDocumentResync(
+ resync: DocumentResync | null,
+): Promise<void> {
+ if (resync === null) {
+ return;
+ }
+ await transactionQueue.catch(() => undefined);
+ if (transactionSyncState !== resync.failure) {
+ return;
+ }
+ transactionSyncState = { status: "synchronized" };
+ transactionQueue = Promise.resolve();
+ if (pendingChanges.length > 0) {
+ flushChanges();
+ }
+}
+
+function releaseDocumentSave(barrier: Deferred<void>): void {
+ if (activeDocumentSave === barrier) {
+ activeDocumentSave = null;
+ }
+ barrier.resolve();
+}
+
+/**
+ * Runs a full save after earlier document transactions and holds later
+ * transactions until the save settles. A failed transaction makes the save
+ * the authoritative document resync boundary.
+ */
+export async function withDocumentSave<T>(save: () => Promise<T>): Promise<T> {
+ let resync: DocumentResync | null = null;
+ try {
+ await flushDocumentChanges();
+ } catch (error) {
+ resync = beginDocumentResync();
+ if (resync === null) {
+ throw error;
+ }
+ }
+
+ const barrier = new Deferred<void>();
+ activeDocumentSave = barrier;
+ try {
+ const result = await save();
+ releaseDocumentSave(barrier);
+ await completeDocumentResync(resync);
+ return result;
+ } catch (error) {
+ abortDocumentResync(resync);
+ releaseDocumentSave(barrier);
+ throw error;
+ }
+}
+
function isScratchChange(change: DocumentChange): boolean {
if ("cellId" in change && change.cellId === SCRATCH_CELL_ID) {
return true;
@@ -658,7 +827,9 @@ function enqueue(change: DocumentChange) {
return;
}
pendingChanges.push(change);
- flushChanges();
+ if (transactionSyncState.status === "synchronized") {
+ flushChanges();
+ }
}
/**
@@ -746,7 +917,13 @@ export function applyTransactionChanges(
export const exportedForTesting = {
cancelPendingChanges: () => {
flushChanges.cancel();
+ activeDocumentSave?.resolve();
+ activeDocumentSave = null;
+ transactionGeneration += 1;
pendingChanges = [];
+ stagedTransactions = [];
+ transactionSyncState = { status: "synchronized" };
+ transactionQueue = Promise.resolve();
},
drainChanges: (): DocumentChange[] => {
flushChanges.cancel();
diff --git a/frontend/src/core/export/hooks.ts b/frontend/src/core/export/hooks.ts
index dc0905c1a4..652ea79f1c 100644
--- a/frontend/src/core/export/hooks.ts
+++ b/frontend/src/core/export/hooks.ts
@@ -11,6 +11,7 @@ import { Objects } from "@/utils/objects";
import { ProgressState } from "@/utils/progress";
import { cellsRuntimeAtom } from "../cells/cells";
import type { CellId } from "../cells/ids";
+import { getExportLayout } from "./layout";
import { connectionAtom } from "../network/connection";
import { useRequestClient } from "../network/requests";
import type { UpdateCellOutputsRequest } from "../network/types";
@@ -56,6 +57,7 @@ export function useAutoExport() {
download: false,
includeCode: true,
files: VirtualFileTracker.INSTANCE.filenames(),
+ layout: await getExportLayout(),
});
},
// Run every 5 seconds, or when the document becomes visible
diff --git a/frontend/src/core/export/layout.ts b/frontend/src/core/export/layout.ts
new file mode 100644
index 0000000000..f55b202dde
--- /dev/null
+++ b/frontend/src/core/export/layout.ts
@@ -0,0 +1,9 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { flushDocumentChanges } from "@/core/cells/document-changes";
+import { getSerializedLayout } from "@/core/layout/layout";
+
+export async function getExportLayout() {
+ await flushDocumentChanges();
+ return getSerializedLayout();
+}
diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.ts
index 04bc225df5..d616b73aa8 100644
--- a/frontend/src/core/kernel/handlers.ts
+++ b/frontend/src/core/kernel/handlers.ts
@@ -1,5 +1,4 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { deserializeLayout } from "@/components/editor/renderers/plugins";
import type { LayoutType } from "@/components/editor/renderers/types";
import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
@@ -7,11 +6,8 @@ import type { UIElementId } from "../cells/ids";
import { type CellData, createCell } from "../cells/types";
import { type AppConfig, AppConfigSchema } from "../config/config-schema";
import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";
-import {
- initialLayoutState,
- type LayoutData,
- type LayoutState,
-} from "../layout/layout";
+import { deserializeLayoutState } from "../layout/layout";
+import type { LayoutData, LayoutState } from "../layout/state";
import { getRequestClient } from "../network/requests";
import { VirtualFileTracker } from "../static/virtual-file-tracker";
import type {
@@ -69,19 +65,14 @@ export function buildLayoutState(
data: LayoutData;
}) => void,
): LayoutState {
- const layoutState = initialLayoutState();
const { layout } = data;
+ const layoutState = deserializeLayoutState(layout, cells);
- if (layout) {
- const layoutType = layout.type as LayoutType;
- const layoutData = deserializeLayout({
- type: layoutType,
- data: layout.data,
- cells,
+ if (layout && layout.type === layoutState.selectedLayout) {
+ setLayoutData({
+ layoutView: layoutState.selectedLayout,
+ data: layoutState.layoutData[layoutState.selectedLayout],
});
- layoutState.selectedLayout = layoutType;
- layoutState.layoutData[layoutType] = layoutData;
- setLayoutData({ layoutView: layoutType, data: layoutData });
}
return layoutState;
diff --git a/frontend/src/core/kernel/state.ts b/frontend/src/core/kernel/state.ts
index e3109db6d0..27901ee841 100644
--- a/frontend/src/core/kernel/state.ts
+++ b/frontend/src/core/kernel/state.ts
@@ -12,6 +12,8 @@ export const kernelStateAtom = atom<KernelState>({
error: null,
});
+export const initialRunCompletedAtom = atom(false);
+
export function waitForKernelToBeInstantiated(): Promise<KernelState> {
return waitFor(kernelStateAtom, (value) => value.isInstantiated);
}
diff --git a/frontend/src/core/layout/__tests__/layout.test.ts b/frontend/src/core/layout/__tests__/layout.test.ts
new file mode 100644
index 0000000000..e5237dd26d
--- /dev/null
+++ b/frontend/src/core/layout/__tests__/layout.test.ts
@@ -0,0 +1,95 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { beforeEach, describe, expect, it } from "vitest";
+import { MockNotebook } from "@/__mocks__/notebook";
+import { cellId } from "@/__tests__/branded";
+import { notebookAtom } from "@/core/cells/cells";
+import { store } from "@/core/state/jotai";
+import { getSerializedLayout } from "../layout";
+import {
+ initialLayoutState,
+ layoutStateAtom,
+ resolveLayoutType,
+ selectLayout,
+} from "../state";
+
+describe("layout state", () => {
+ it("falls back to vertical for an unknown layout type", () => {
+ expect(initialLayoutState({ type: "unknown", data: {} })).toEqual({
+ selectedLayout: "vertical",
+ layoutData: {},
+ });
+ });
+
+ it("preserves pending data until a different layout is selected", () => {
+ const state = initialLayoutState({
+ type: "slides",
+ data: { deck: { transition: "fade" } },
+ });
+
+ expect(selectLayout(state, "slides")).toBe(state);
+ expect(selectLayout(state, "grid")).toEqual({
+ selectedLayout: "grid",
+ layoutData: {},
+ });
+ });
+
+ it.each([
+ { isReading: true, expected: "slides" },
+ { isReading: false, expected: "vertical" },
+ ] as const)(
+ "returns $expected when read mode is $isReading",
+ ({ isReading, expected }) => {
+ expect(
+ resolveLayoutType({
+ selectedLayout: "vertical",
+ isReading,
+ searchParams: new URLSearchParams("view-as=slides"),
+ }),
+ ).toBe(expected);
+ },
+ );
+});
+
+describe("getSerializedLayout", () => {
+ beforeEach(() => {
+ store.set(layoutStateAtom, initialLayoutState());
+ store.set(
+ notebookAtom,
+ MockNotebook.notebookState({
+ cellData: {
+ [cellId("cell-1")]: { code: "first = 1" },
+ [cellId("cell-2")]: { code: "second = 2" },
+ },
+ }),
+ );
+ });
+
+ it("preserves a pending embedded layout when edit mode saves", () => {
+ const layout = {
+ type: "slides",
+ data: {
+ cells: [
+ { type: "slide", speakerNotes: "Introduce the result" },
+ { type: "fragment" },
+ ],
+ deck: { transition: "fade", verticalAlign: "center" },
+ },
+ };
+ store.set(layoutStateAtom, initialLayoutState(layout));
+
+ expect(getSerializedLayout()).toEqual(layout);
+ });
+
+ it("uses the initial layout when materialized data is null", () => {
+ store.set(layoutStateAtom, {
+ selectedLayout: "slides",
+ layoutData: { slides: null },
+ });
+
+ expect(getSerializedLayout()).toEqual({
+ type: "slides",
+ data: { cells: [{}, {}], deck: {} },
+ });
+ });
+});
diff --git a/frontend/src/core/layout/layout.ts b/frontend/src/core/layout/layout.ts
index d885bb7766..3a6e33ea54 100644
--- a/frontend/src/core/layout/layout.ts
+++ b/frontend/src/core/layout/layout.ts
@@ -1,89 +1,86 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { useAtomValue } from "jotai";
-import type { GridLayout } from "@/components/editor/renderers/grid-layout/types";
-import { cellRendererPlugins } from "@/components/editor/renderers/plugins";
-import type { LayoutType } from "@/components/editor/renderers/types";
-import { createReducerAndAtoms } from "@/utils/createReducer";
+import {
+ cellRendererPlugins,
+ deserializeLayout,
+} from "@/components/editor/renderers/plugins";
+import type { ICellRendererPlugin } from "@/components/editor/renderers/types";
import { Logger } from "@/utils/Logger";
import { getNotebook } from "../cells/cells";
+import type { CellData } from "../cells/types";
import { notebookCells } from "../cells/utils";
import { store } from "../state/jotai";
+import {
+ initialLayoutState,
+ layoutStateAtom,
+ type LayoutState,
+ type SerializedLayout,
+} from "./state";
-export type LayoutData = GridLayout | undefined;
+export function deserializeLayoutState(
+ layout: SerializedLayout | null | undefined,
+ cells: CellData[],
+): LayoutState {
+ if (layout == null) {
+ return initialLayoutState();
+ }
-export interface LayoutState {
- selectedLayout: LayoutType;
- layoutData: Partial<Record<LayoutType, LayoutData>>;
-}
+ const plugin = cellRendererPlugins.find(
+ (candidate) => candidate.type === layout.type,
+ );
+ if (plugin === undefined) {
+ Logger.warn(`Unknown layout type: ${layout.type}`);
+ return initialLayoutState();
+ }
-export function initialLayoutState(): LayoutState {
return {
- selectedLayout: "vertical",
- layoutData: {},
+ selectedLayout: plugin.type,
+ layoutData: {
+ [plugin.type]: deserializeLayout({
+ type: plugin.type,
+ data: layout.data,
+ cells,
+ }),
+ },
};
}
-const { valueAtom: layoutStateAtom, useActions } = createReducerAndAtoms(
- initialLayoutState,
- {
- setLayoutView: (state, payload: LayoutType) => {
- return {
- ...state,
- selectedLayout: payload,
- };
- },
- setLayoutData: (
- state,
- payload: { layoutView: LayoutType; data: LayoutData },
- ) => {
- return {
- ...state,
- selectedLayout: payload.layoutView,
- layoutData: {
- ...state.layoutData,
- [payload.layoutView]: payload.data,
- },
- };
- },
- setCurrentLayoutData: (state, payload: LayoutData) => {
- return {
- ...state,
- layoutData: {
- ...state.layoutData,
- [state.selectedLayout]: payload,
- },
- };
- },
- },
-);
-
-export { layoutStateAtom };
-
-export const useLayoutState = () => {
- return useAtomValue(layoutStateAtom);
-};
-
-export const useLayoutActions = () => {
- return useActions();
-};
+export function resolveLayoutData<S, L>({
+ state,
+ plugin,
+ cells,
+}: {
+ state: LayoutState;
+ plugin: ICellRendererPlugin<S, L>;
+ cells: CellData[];
+}): L {
+ const materialized = state.layoutData[plugin.type];
+ if (materialized != null) {
+ return materialized as L;
+ }
+ if (state.pendingLayout?.type === plugin.type) {
+ return deserializeLayout({
+ type: plugin.type,
+ data: state.pendingLayout.data,
+ cells,
+ }) as L;
+ }
+ return plugin.getInitialLayout(cells);
+}
/**
* Get the serialized layout data, to be used when saving.
*/
export function getSerializedLayout() {
const notebook = getNotebook();
- const { layoutData, selectedLayout } = store.get(layoutStateAtom);
+ const layoutState = store.get(layoutStateAtom);
+ const { selectedLayout } = layoutState;
// Vertical layout has no data, as it is the default.
if (selectedLayout === "vertical") {
return null;
}
- if (layoutData === undefined) {
- return null;
- }
-
const plugin = cellRendererPlugins.find(
(plugin) => plugin.type === selectedLayout,
);
@@ -92,10 +89,7 @@ export function getSerializedLayout() {
return null;
}
const cells = notebookCells(notebook);
- // Fall back to the plugin's initial layout when the user has not yet
- // interacted with this layout — otherwise serializers that expect a
- // structured layout object crash on `undefined`.
- const data = layoutData[selectedLayout] ?? plugin.getInitialLayout(cells);
+ const data = resolveLayoutData({ state: layoutState, plugin, cells });
return {
type: selectedLayout,
data: plugin.serializeLayout(data, cells),
diff --git a/frontend/src/core/layout/state.ts b/frontend/src/core/layout/state.ts
new file mode 100644
index 0000000000..3b9172e714
--- /dev/null
+++ b/frontend/src/core/layout/state.ts
@@ -0,0 +1,121 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useAtomValue } from "jotai";
+import type { GridLayout } from "@/components/editor/renderers/grid-layout/types";
+import type { SlidesLayout } from "@/components/editor/renderers/slides-layout/types";
+import {
+ type LayoutType,
+ isLayoutType,
+ OVERRIDABLE_LAYOUT_TYPES,
+} from "@/components/editor/renderers/types";
+import { KnownQueryParams } from "@/core/constants";
+import { createReducerAndAtoms } from "@/utils/createReducer";
+import { isRecord } from "@/utils/records";
+
+export type LayoutData = GridLayout | SlidesLayout | null | undefined;
+
+export interface SerializedLayout {
+ type: string;
+ data: unknown;
+}
+
+export function isSerializedLayout(value: unknown): value is SerializedLayout {
+ return isRecord(value) && typeof value.type === "string" && "data" in value;
+}
+
+interface LayoutStateBase {
+ selectedLayout: LayoutType;
+ layoutData: Partial<Record<LayoutType, LayoutData>>;
+}
+
+export type LayoutState =
+ | (LayoutStateBase & { pendingLayout: SerializedLayout })
+ | (LayoutStateBase & { pendingLayout?: never });
+
+export function initialLayoutState(
+ serializedLayout?: SerializedLayout,
+): LayoutState {
+ if (serializedLayout && isLayoutType(serializedLayout.type)) {
+ return {
+ selectedLayout: serializedLayout.type,
+ layoutData: {},
+ pendingLayout: serializedLayout,
+ };
+ }
+ return {
+ selectedLayout: "vertical",
+ layoutData: {},
+ };
+}
+
+export function selectLayout(
+ state: LayoutState,
+ selectedLayout: LayoutType,
+): LayoutState {
+ if (selectedLayout === state.selectedLayout) {
+ return state;
+ }
+ const { pendingLayout: _pendingLayout, ...materializedState } = state;
+ return { ...materializedState, selectedLayout };
+}
+
+const { valueAtom: layoutStateAtom, useActions } = createReducerAndAtoms(
+ initialLayoutState,
+ {
+ setLayoutView: selectLayout,
+ setLayoutData: (
+ { pendingLayout: _pendingLayout, ...state },
+ payload: { layoutView: LayoutType; data: LayoutData },
+ ) => {
+ return {
+ ...state,
+ selectedLayout: payload.layoutView,
+ layoutData: {
+ ...state.layoutData,
+ [payload.layoutView]: payload.data,
+ },
+ };
+ },
+ setCurrentLayoutData: (
+ { pendingLayout: _pendingLayout, ...state },
+ payload: LayoutData,
+ ) => {
+ return {
+ ...state,
+ layoutData: {
+ ...state.layoutData,
+ [state.selectedLayout]: payload,
+ },
+ };
+ },
+ },
+);
+
+export { layoutStateAtom };
+
+export const useLayoutState = () => {
+ return useAtomValue(layoutStateAtom);
+};
+
+export const useLayoutActions = () => {
+ return useActions();
+};
+
+export function resolveLayoutType({
+ selectedLayout,
+ isReading,
+ searchParams,
+}: {
+ selectedLayout: LayoutType;
+ isReading: boolean;
+ searchParams: URLSearchParams;
+}): LayoutType {
+ if (!isReading) {
+ return selectedLayout;
+ }
+ const requested = searchParams.get(KnownQueryParams.viewAs);
+ return (
+ OVERRIDABLE_LAYOUT_TYPES.find((layout) => layout === requested) ??
+ selectedLayout
+ );
+}
diff --git a/frontend/src/core/meta/__tests__/code-visibility.test.tsx b/frontend/src/core/meta/__tests__/code-visibility.test.tsx
index f4632fbf7e..4ebdc55def 100644
--- a/frontend/src/core/meta/__tests__/code-visibility.test.tsx
+++ b/frontend/src/core/meta/__tests__/code-visibility.test.tsx
@@ -6,23 +6,32 @@ import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { showCodeInRunModeAtom } from "@/core/meta/state";
import { type AppMode, kioskModeAtom, viewStateAtom } from "@/core/mode";
+import {
+ remoteAdapter,
+ runtimeAdapterAtom,
+ staticAdapter,
+ type RuntimeAdapter,
+} from "@/core/runtime/adapter";
import { useNotebookCodeAvailable } from "../code-visibility";
interface StoreOpts {
mode?: AppMode;
kiosk?: boolean;
showInRunMode?: boolean;
+ runtime?: RuntimeAdapter;
}
function makeStore({
mode = "read",
kiosk = false,
showInRunMode = true,
+ runtime = remoteAdapter,
}: StoreOpts = {}) {
const store = createStore();
store.set(viewStateAtom, { mode, cellAnchor: null });
store.set(kioskModeAtom, kiosk);
store.set(showCodeInRunModeAtom, showInRunMode);
+ store.set(runtimeAdapterAtom, runtime);
return store;
}
@@ -128,6 +137,25 @@ describe("useNotebookCodeAvailable", () => {
expect(result.current).toBe(true);
});
+ it("checks embedded code in a static kiosk", () => {
+ const store = makeStore({
+ mode: "read",
+ kiosk: true,
+ runtime: staticAdapter,
+ });
+
+ const withoutCode = renderHook(
+ () => useNotebookCodeAvailable(cellsWithoutCode),
+ { wrapper: wrap(store) },
+ );
+ const withCode = renderHook(() => useNotebookCodeAvailable(cellsWithCode), {
+ wrapper: wrap(store),
+ });
+
+ expect(withoutCode.result.current).toBe(false);
+ expect(withCode.result.current).toBe(true);
+ });
+
it("returns false for non-edit/non-read modes (home, gallery)", () => {
for (const mode of ["home", "gallery"] as const) {
const store = makeStore({ mode });
diff --git a/frontend/src/core/meta/code-visibility.ts b/frontend/src/core/meta/code-visibility.ts
index a5aaef8589..d825d6789a 100644
--- a/frontend/src/core/meta/code-visibility.ts
+++ b/frontend/src/core/meta/code-visibility.ts
@@ -4,6 +4,7 @@ import { useAtomValue } from "jotai";
import { KnownQueryParams } from "@/core/constants";
import { showCodeInRunModeAtom } from "@/core/meta/state";
import { kioskModeAtom, viewStateAtom } from "@/core/mode";
+import { runtimeAdapterAtom } from "@/core/runtime/adapter";
import { logNever } from "@/utils/assertNever";
/**
@@ -19,8 +20,9 @@ export function useNotebookCodeAvailable(
const kioskMode = useAtomValue(kioskModeAtom);
const { mode } = useAtomValue(viewStateAtom);
const showInRunMode = useAtomValue(showCodeInRunModeAtom);
+ const runtimeKind = useAtomValue(runtimeAdapterAtom).kind;
- if (kioskMode) {
+ if (kioskMode && runtimeKind === "remote") {
return true;
}
diff --git a/frontend/src/core/run-app.tsx b/frontend/src/core/run-app.tsx
index f2a9f8a429..8786ab48dc 100644
--- a/frontend/src/core/run-app.tsx
+++ b/frontend/src/core/run-app.tsx
@@ -25,6 +25,7 @@ import { useMarimoKernelConnection } from "./websocket/useMarimoKernelConnection
interface AppProps {
appConfig: AppConfig;
+ hideHeader?: boolean;
}
/**
@@ -37,7 +38,7 @@ const canPaintRunAppAtom = atom(
(get) => get(hasCellsAtom) || !isAppConnecting(get(connectionAtom).state),
);
-export const RunApp: React.FC<AppProps> = ({ appConfig }) => {
+export const RunApp: React.FC<AppProps> = ({ appConfig, hideHeader }) => {
const { setCells } = useCellActions();
const { sendComponentValues } = useRequestClient();
@@ -77,7 +78,10 @@ export const RunApp: React.FC<AppProps> = ({ appConfig }) => {
width={appConfig.width}
onReconnect={reconnect}
>
- <AppHeader connection={connection} className="sm:pt-8">
+ <AppHeader
+ connection={connection}
+ className={hideHeader ? "hidden" : "sm:pt-8"}
+ >
{galleryHref && (
<div className="flex items-center px-6 pt-4 sm:-mt-8">
<a
diff --git a/frontend/src/core/saving/__tests__/save-component.test.ts b/frontend/src/core/saving/__tests__/save-component.test.ts
index 29819fa97b..e07037ba6d 100644
--- a/frontend/src/core/saving/__tests__/save-component.test.ts
+++ b/frontend/src/core/saving/__tests__/save-component.test.ts
@@ -1,7 +1,8 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { isNamedPersistentFile } from "../save-component";
+import { Deferred } from "@/utils/Deferred";
+import { enqueueNotebookSave, isNamedPersistentFile } from "../save-component";
describe("isNamedPersistentFile", () => {
it.each([
@@ -18,3 +19,32 @@ describe("isNamedPersistentFile", () => {
expect(isNamedPersistentFile(filename)).toBe(expected);
});
});
+
+describe("enqueueNotebookSave", () => {
+ it("serializes snapshots across callers and continues after a failure", async () => {
+ const firstStarted = new Deferred<void>();
+ const releaseFirst = new Deferred<void>();
+ const snapshots: string[] = [];
+ let current = "first";
+
+ const first = enqueueNotebookSave(async () => {
+ snapshots.push(current);
+ firstStarted.resolve();
+ await releaseFirst.promise;
+ throw new Error("save failed");
+ });
+ await firstStarted.promise;
+
+ current = "queued";
+ const second = enqueueNotebookSave(async () => {
+ snapshots.push(current);
+ });
+ current = "latest";
+
+ expect(snapshots).toEqual(["first"]);
+ releaseFirst.resolve();
+ await expect(first).rejects.toThrow("save failed");
+ await second;
+ expect(snapshots).toEqual(["first", "latest"]);
+ });
+});
diff --git a/frontend/src/core/saving/save-component.tsx b/frontend/src/core/saving/save-component.tsx
index f2f151f6a1..bd16417afd 100644
--- a/frontend/src/core/saving/save-component.tsx
+++ b/frontend/src/core/saving/save-component.tsx
@@ -21,11 +21,13 @@ import { Label } from "../../components/ui/label";
import { useEvent } from "../../hooks/useEvent";
import { Logger } from "../../utils/Logger";
import { getCellConfigs, getNotebook, useNotebook } from "../cells/cells";
+import { withDocumentSave } from "../cells/document-changes";
import { notebookCells } from "../cells/utils";
import { formatAll } from "../codemirror/format";
import { autoSaveConfigAtom } from "../config/config";
import { useAutoExport } from "../export/hooks";
-import { getSerializedLayout, layoutStateAtom } from "../layout/layout";
+import { getSerializedLayout } from "../layout/layout";
+import { layoutStateAtom } from "../layout/state";
import { kioskModeAtom } from "../mode";
import { connectionAtom } from "../network/connection";
import { useRequestClient } from "../network/requests";
@@ -39,6 +41,17 @@ interface SaveNotebookProps {
kioskMode: boolean;
}
+let notebookSaveQueue: Promise<void> = Promise.resolve();
+
+export function enqueueNotebookSave<T>(save: () => Promise<T>): Promise<T> {
+ const result = notebookSaveQueue.then(save);
+ notebookSaveQueue = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ return result;
+}
+
export const SaveComponent = ({ kioskMode }: SaveNotebookProps) => {
const filename = useFilename();
const needsSave = useAtomValue(needsSaveAtom);
@@ -96,8 +109,8 @@ export function useSaveNotebook() {
const store = useStore();
// Save the notebook with the given filename
- const saveNotebook = useEvent(
- async (filename: string, userInitiated: boolean) => {
+ const saveNotebook = useEvent((filename: string, userInitiated: boolean) =>
+ enqueueNotebookSave(async () => {
const connection = store.get(connectionAtom);
const autoSaveConfig = store.get(autoSaveConfigAtom);
const kioskMode = store.get(kioskModeAtom);
@@ -119,37 +132,34 @@ export function useSaveNotebook() {
await formatAll();
}
- // Grab the latest notebook state, after formatting
- const notebook = getNotebook();
- const cells = notebookCells(notebook);
- const cellIds = cells.map((cell) => cell.id);
- const codes = cells.map((cell) => cell.code);
- const cellNames = cells.map((cell) => cell.name);
- const configs = getCellConfigs(notebook);
- const layout = store.get(layoutStateAtom);
-
- // Don't save if there are no cells
- if (codes.length === 0) {
+ if (notebookCells(getNotebook()).length === 0) {
return;
}
- await sendSave({
- cellIds: cellIds,
- codes,
- names: cellNames,
- filename,
- configs,
- layout: getSerializedLayout(),
- persist: true,
- });
+ const savedNotebook = await withDocumentSave(async () => {
+ // Grab the latest notebook state after formatting and after every
+ // earlier document transaction has reached the server.
+ const notebook = getNotebook();
+ const cells = notebookCells(notebook);
+ const cellIds = cells.map((cell) => cell.id);
+ const codes = cells.map((cell) => cell.code);
+ const cellNames = cells.map((cell) => cell.name);
+ const configs = getCellConfigs(notebook);
+ const layout = store.get(layoutStateAtom);
- setLastSavedNotebook({
- names: cellNames,
- codes,
- configs,
- layout,
+ await sendSave({
+ cellIds: cellIds,
+ codes,
+ names: cellNames,
+ filename,
+ configs,
+ layout: getSerializedLayout(),
+ persist: true,
+ });
+ return { names: cellNames, codes, configs, layout };
});
- },
+ setLastSavedNotebook(savedNotebook);
+ }),
);
// Save the notebook with the current filename, only if the filename exists
diff --git a/frontend/src/core/saving/state.ts b/frontend/src/core/saving/state.ts
index 05ada2a550..36ce63ed55 100644
--- a/frontend/src/core/saving/state.ts
+++ b/frontend/src/core/saving/state.ts
@@ -4,7 +4,7 @@ import { dequal as isEqual } from "dequal";
import { atom } from "jotai";
import { arrayShallowEquals } from "@/utils/arrays";
import { type NotebookState, notebookAtom } from "../cells/cells";
-import { type LayoutState, layoutStateAtom } from "../layout/layout";
+import { type LayoutState, layoutStateAtom } from "../layout/state";
import type { CellConfig } from "../network/types";
export interface LastSavedNotebook {
diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.ts
index 7429802601..c53e909159 100644
--- a/frontend/src/core/static/download-html.ts
+++ b/frontend/src/core/static/download-html.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { downloadExportedFile } from "@/utils/download";
+import { getExportLayout } from "../export/layout";
import { getRequestClient } from "../network/requests";
import { VirtualFileTracker } from "./virtual-file-tracker";
@@ -14,6 +15,7 @@ export async function downloadAsHTML(opts: { includeCode: boolean }) {
download: true,
includeCode: includeCode,
files: VirtualFileTracker.INSTANCE.filenames(),
+ layout: await getExportLayout(),
});
downloadExportedFile(exportedFile);
diff --git a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx
index c0b21802b3..368fa97c50 100644
--- a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx
@@ -27,6 +27,7 @@ vi.mock("@/core/runtime/config", async () => {
});
import { useRuntimeManager } from "@/core/runtime/config";
+import { initialRunCompletedAtom } from "../../kernel/state";
import { connectionAtom } from "../../network/connection";
import type { SessionId } from "../../kernel/session";
import { WebSocketClosedReason, WebSocketState } from "../types";
@@ -68,6 +69,23 @@ function makeRuntimeManager(
};
}
+function renderConnectionHook(store: ReturnType<typeof createStore>) {
+ const wrapper: React.FC<React.PropsWithChildren> = ({ children }) => (
+ <JotaiProvider store={store}>
+ <ErrorBoundary fallback={null}>{children}</ErrorBoundary>
+ </JotaiProvider>
+ );
+ return renderHook(
+ () =>
+ useMarimoKernelConnection({
+ sessionId: "test-session" as SessionId,
+ autoInstantiate: false,
+ setCells: () => {},
+ }),
+ { wrapper },
+ );
+}
+
describe("useMarimoKernelConnection.reconnect()", () => {
let transport: MockTransport;
let isHealthy: Mock<() => Promise<boolean>>;
@@ -91,20 +109,7 @@ describe("useMarimoKernelConnection.reconnect()", () => {
});
function renderUseHook() {
- const wrapper: React.FC<React.PropsWithChildren> = ({ children }) => (
- <JotaiProvider store={store}>
- <ErrorBoundary fallback={null}>{children}</ErrorBoundary>
- </JotaiProvider>
- );
- return renderHook(
- () =>
- useMarimoKernelConnection({
- sessionId: "test-session" as SessionId,
- autoInstantiate: false,
- setCells: () => {},
- }),
- { wrapper },
- );
+ return renderConnectionHook(store);
}
it("is a no-op when the transport is already OPEN", async () => {
@@ -155,3 +160,31 @@ describe("useMarimoKernelConnection.reconnect()", () => {
});
});
});
+
+describe("useMarimoKernelConnection messages", () => {
+ it("records completion of the initial run", () => {
+ const store = createStore();
+ vi.mocked(useConnectionTransport).mockClear();
+ vi.mocked(useConnectionTransport).mockReturnValue(
+ makeTransport(WebSocket.OPEN),
+ );
+ vi.mocked(useRuntimeManager).mockReturnValue(
+ makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,
+ );
+ renderConnectionHook(store);
+
+ const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)?.[0];
+ expect(store.get(initialRunCompletedAtom)).toBe(false);
+ act(() => {
+ options?.onMessage(
+ new MessageEvent("message", {
+ data: JSON.stringify({
+ op: "completed-run",
+ data: { op: "completed-run", run_id: null },
+ }),
+ }),
+ );
+ });
+ expect(store.get(initialRunCompletedAtom)).toBe(true);
+ });
+});
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index ceef54a64a..36b638f7ec 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -60,8 +60,8 @@ import {
} from "../kernel/handlers";
import { queryParamHandlers } from "../kernel/queryParamHandlers";
import type { SessionId } from "../kernel/session";
-import { kernelStateAtom } from "../kernel/state";
-import { type LayoutState, useLayoutActions } from "../layout/layout";
+import { initialRunCompletedAtom, kernelStateAtom } from "../kernel/state";
+import { type LayoutState, useLayoutActions } from "../layout/state";
import { kioskModeAtom } from "../mode";
import { connectionAtom } from "../network/connection";
import type { RequestId } from "../network/DeferredRequestRegistry";
@@ -212,6 +212,7 @@ export function useMarimoKernelConnection(opts: {
};
const { addCellNotification } = useRunsActions();
const setKernelState = useSetAtom(kernelStateAtom);
+ const setInitialRunCompleted = useSetAtom(initialRunCompletedAtom);
const setAppConfig = useSetAppConfig();
const { setVariables, setMetadata } = useVariablesActions();
const { addColumnPreview } = useDatasetsActions();
@@ -240,6 +241,9 @@ export function useMarimoKernelConnection(opts: {
reloadSafe();
return;
case "kernel-ready": {
+ setInitialRunCompleted(
+ Boolean(msg.data.resumed || msg.data.auto_instantiated),
+ );
const existingCells = getExistingCells();
handleKernelReady(msg.data, {
@@ -268,6 +272,7 @@ export function useMarimoKernelConnection(opts: {
}
case "completed-run":
+ setInitialRunCompleted(true);
return;
case "interrupted":
return;
diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsx
index ee4286f799..e9446cd964 100644
--- a/frontend/src/mount.tsx
+++ b/frontend/src/mount.tsx
@@ -27,7 +27,17 @@ import {
parseUserConfig,
} from "./core/config/config-schema";
import { MarimoApp, preloadPage } from "./core/MarimoApp";
-import { type AppMode, initialModeAtom, viewStateAtom } from "./core/mode";
+import {
+ initialLayoutState,
+ isSerializedLayout,
+ layoutStateAtom,
+} from "./core/layout/state";
+import {
+ type AppMode,
+ initialModeAtom,
+ kioskModeAtom,
+ viewStateAtom,
+} from "./core/mode";
import { cleanupAuthQueryParams } from "./core/network/auth";
import { connectionAtom } from "./core/network/connection";
import { requestClientAtom } from "./core/network/requests";
@@ -202,6 +212,13 @@ const mountOptionsSchema = z.object({
* marimo app config
*/
appConfig: passthroughObject,
+ /**
+ * Serialized notebook layout
+ */
+ layout: z
+ .unknown()
+ .optional()
+ .transform((val) => (isSerializedLayout(val) ? val : undefined)),
/**
* show code in run mode
*/
@@ -310,15 +327,15 @@ function initStore(options: unknown) {
store.set(marimoVersionAtom, parsedOptions.data.version);
store.set(showCodeInRunModeAtom, parsedOptions.data.view.showAppCode);
- // Check for view-as parameter to start in present mode
- const shouldStartInPresentMode = (() => {
- const url = new URL(window.location.href);
- return url.searchParams.get(KnownQueryParams.viewAs) === "present";
- })();
+ const url = new URL(window.location.href);
+ const shouldStartInPresentMode =
+ url.searchParams.get(KnownQueryParams.viewAs) === "present";
+ const isKioskMode = url.searchParams.get(KnownQueryParams.kiosk) === "true";
const initialViewMode =
mode === "edit" && shouldStartInPresentMode ? "present" : mode;
store.set(viewStateAtom, { mode: initialViewMode, cellAnchor: null });
+ store.set(kioskModeAtom, isKioskMode);
store.set(serverTokenAtom, parsedOptions.data.serverToken);
// Config
@@ -354,6 +371,7 @@ function initStore(options: unknown) {
parsedOptions.data.session,
parsedOptions.data.notebook,
);
+ store.set(layoutStateAtom, initialLayoutState(parsedOptions.data.layout));
if (notebook) {
store.set(notebookAtom, notebook);
}
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 5dacdfdb6e..ac5a4f49ec 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -1,7 +1,6 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-import base64
import inspect
import os
import sys
@@ -14,7 +13,6 @@ from collections.abc import (
Sequence,
)
from dataclasses import dataclass
-from pathlib import Path
from textwrap import dedent
from typing import (
TYPE_CHECKING,
@@ -1008,19 +1006,6 @@ class InternalApp:
def update_config(self, updates: dict[str, Any]) -> _AppConfig:
return self.config.update(updates)
- def inline_layout_file(self) -> InternalApp:
- if self.config.layout_file:
- layout_path = Path(self.config.layout_file)
- if self._app._filename:
- # Resolve relative to the current working directory
- layout_path = Path(self._app._filename).parent / layout_path
- layout_file = layout_path.read_bytes()
- data_uri = base64.b64encode(layout_file).decode()
- self.update_config(
- {"layout_file": f"data:application/json;base64,{data_uri}"}
- )
- return self
-
def with_data(
self,
*,
@@ -1040,6 +1025,23 @@ class InternalApp:
callers from save flows pass the frontend's snapshot, which
renames/reorders/reconfigures cells but doesn't recompile.
"""
+ self.apply_data(
+ cell_ids=cell_ids,
+ codes=codes,
+ names=names,
+ configs=configs,
+ )
+ return self
+
+ def apply_data(
+ self,
+ *,
+ cell_ids: Iterable[CellId_t],
+ codes: Iterable[str],
+ names: Iterable[str],
+ configs: Iterable[CellConfig],
+ ) -> Transaction:
+ """Rewrite the cell list and return the applied transaction."""
cm = self._app._cell_manager
prev_compiled = dict(cm._compiled_cells)
rebuilt = CellManager(prefix=cm.prefix)
@@ -1054,8 +1056,10 @@ class InternalApp:
cell=prev_compiled.get(cell_id),
)
- cm.apply_diff_from(rebuilt, source="cell-manager")
- return self
+ transaction, _changed_cell_ids = cm.apply_diff_from(
+ rebuilt, source="cell-manager"
+ )
+ return transaction
async def run_cell_async(
self, cell: Cell, kwargs: dict[str, Any]
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 325e341aef..eab1b62d07 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -757,7 +757,6 @@ def preview(file_path: Path, port: int, host: str, headless: bool) -> None:
from starlette.routing import Route
from starlette.staticfiles import StaticFiles
- from marimo._ast.app_config import _AppConfig
from marimo._config.config import DEFAULT_CONFIG
from marimo._server.tokens import SkewProtectionToken
from marimo._templates import static_notebook_template
@@ -834,13 +833,14 @@ def preview(file_path: Path, port: int, host: str, headless: bool) -> None:
user_config=DEFAULT_CONFIG,
config_overrides={},
server_token=SkewProtectionToken("preview"),
- app_config=_AppConfig(),
+ app_config=file_manager.app.config,
filepath=str(file_path),
code=code,
session_snapshot=session_snapshot,
code_hash=hash_code(code),
notebook_snapshot=notebook_snapshot,
files={},
+ layout=file_manager.read_layout_config(),
model_notifications=session_view.get_model_notifications(),
asset_url=asset_url,
)
diff --git a/marimo/_export/exporter.py b/marimo/_export/exporter.py
index b2c191b877..6a9a9e55d5 100644
--- a/marimo/_export/exporter.py
+++ b/marimo/_export/exporter.py
@@ -6,7 +6,7 @@ import base64
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
-from typing import TYPE_CHECKING, Any, cast
+from typing import TYPE_CHECKING, Any, Literal, cast
from marimo import _loggers
from marimo._ast.names import DEFAULT_CELL_NAME
@@ -271,6 +271,7 @@ class Exporter:
session_snapshot=session_snapshot,
notebook_snapshot=notebook_snapshot,
files=virtual_files,
+ layout=request.layout,
model_notifications=model_notifications,
asset_url=request.options.asset_url,
)
@@ -537,6 +538,7 @@ class Exporter:
code=request.code,
asset_url=request.options.asset_url,
show_code=request.options.show_code,
+ layout=request.layout,
session_snapshot=request.session_snapshot,
notebook_snapshot=request.notebook_snapshot,
)
@@ -871,6 +873,9 @@ async def render_pdf(request: PDFExportRequest) -> bytes | None:
return exporter.export_as_pdf(request)
+AutoExportFormat = Literal["html", "md", "ipynb"]
+
+
class AutoExporter:
def __init__(self) -> None:
# Cache directories we've already created to avoid redundant checks
@@ -879,31 +884,59 @@ class AutoExporter:
self._executor = ThreadPoolExecutor(
max_workers=4, thread_name_prefix="export"
)
+ self._latest_revisions: dict[Path, int] = {}
+ self._file_locks: dict[Path, asyncio.Lock] = {}
- async def _save_file(
- self, filename: str | None, content: str, extension: str
- ) -> None:
+ @staticmethod
+ def _export_path(
+ filename: str | None, extension: AutoExportFormat
+ ) -> Path:
notebook_path = get_filename(filename)
download_name = get_download_filename(filename, extension)
- export_dir = notebook_output_dir(notebook_path)
+ return notebook_output_dir(notebook_path) / download_name
- await self._ensure_export_dir_async(export_dir)
- filepath = export_dir / download_name
+ def reserve_revision(
+ self, filename: str | None, extension: AutoExportFormat
+ ) -> int:
+ filepath = self._export_path(filename, extension)
+ revision = self._latest_revisions.get(filepath, 0) + 1
+ self._latest_revisions[filepath] = revision
+ return revision
- # Run blocking file I/O in thread pool
- loop = asyncio.get_running_loop()
- await loop.run_in_executor(
- self._executor, self._write_file_sync, filepath, content
- )
+ async def _save_file(
+ self,
+ filename: str | None,
+ content: str,
+ extension: AutoExportFormat,
+ revision: int,
+ ) -> bool:
+ filepath = self._export_path(filename, extension)
+ lock = self._file_locks.setdefault(filepath, asyncio.Lock())
+ async with lock:
+ if revision != self._latest_revisions.get(filepath):
+ return False
+
+ await self._ensure_export_dir_async(filepath.parent)
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(
+ self._executor, self._write_file_sync, filepath, content
+ )
+ return revision == self._latest_revisions.get(filepath)
- async def save_html(self, filename: str | None, html: str) -> None:
- await self._save_file(filename, html, "html")
+ async def save_html(
+ self, filename: str | None, html: str, *, revision: int
+ ) -> bool:
+ return await self._save_file(filename, html, "html", revision)
- async def save_md(self, filename: str | None, markdown: str) -> None:
- await self._save_file(filename, markdown, "md")
+ async def save_md(
+ self, filename: str | None, markdown: str, *, revision: int
+ ) -> bool:
+ return await self._save_file(filename, markdown, "md", revision)
- async def save_ipynb(self, filename: str | None, ipynb: str) -> None:
- await self._save_file(filename, ipynb, "ipynb")
+ async def save_ipynb(
+ self, filename: str | None, ipynb: str, *, revision: int
+ ) -> bool:
+ return await self._save_file(filename, ipynb, "ipynb", revision)
def _write_file_sync(self, filepath: Path, content: str) -> None:
"""Synchronous file write (runs in thread pool)"""
@@ -925,6 +958,8 @@ class AutoExporter:
def cleanup(self) -> None:
"""Cleanup resources"""
self._executor.shutdown(wait=False)
+ self._latest_revisions.clear()
+ self._file_locks.clear()
def get_html_contents() -> str:
diff --git a/marimo/_export/file.py b/marimo/_export/file.py
index 8cfe9e8293..d2c03a43c9 100644
--- a/marimo/_export/file.py
+++ b/marimo/_export/file.py
@@ -55,6 +55,11 @@ from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage
from marimo._output.hypertext import patch_html_for_non_interactive_output
from marimo._runtime.commands import AppMetadata
+from marimo._runtime.layout.layout import (
+ LayoutConfig,
+ layout_config_to_data_uri,
+ read_layout_config,
+)
from marimo._runtime.patches import extract_docstring_from_header
from marimo._schemas.export_options import (
IPYNBExportOptions,
@@ -79,6 +84,25 @@ if TYPE_CHECKING:
from marimo._types.ids import CellId_t
+def _resolve_and_inline_layout(app: InternalApp) -> LayoutConfig | None:
+ layout_file = app.config.layout_file
+ if layout_file is None:
+ return None
+
+ directory = Path(app.filename).parent if app.filename else Path.cwd()
+ layout = read_layout_config(directory, layout_file)
+ app.update_config(
+ {
+ "layout_file": (
+ layout_config_to_data_uri(layout)
+ if layout is not None
+ else None
+ )
+ }
+ )
+ return layout
+
+
def _as_ir(path: MarimoPath) -> NotebookSerialization:
if path.is_python():
py_contents = path.read_text(encoding="utf-8")
@@ -192,8 +216,7 @@ async def export_wasm(
did_error=True,
)
app = InternalApp(_app)
- # Inline the layout file, if it exists
- app.inline_layout_file()
+ layout = _resolve_and_inline_layout(app)
config = get_default_config_manager(
current_path=request.path.absolute_name
)
@@ -210,6 +233,7 @@ async def export_wasm(
display_config=resolved["display"],
code=code,
options=request.options,
+ layout=layout,
sharing_config=resolved.get("sharing"),
)
)
@@ -322,9 +346,7 @@ async def export_html(
request: HTMLFileExportRequest,
) -> ExportResult:
file_manager = load_notebook(request.path.absolute_name)
-
- # Inline the layout file, if it exists
- file_manager.app.inline_layout_file()
+ layout = _resolve_and_inline_layout(file_manager.app)
if request.execution is None:
from marimo._session.state.session_view import SessionView
@@ -358,6 +380,7 @@ async def export_html(
),
display_config=display_config,
options=request.options,
+ layout=layout,
sharing_config=(
resolved.get("sharing")
if request.execution is not None
@@ -447,7 +470,7 @@ async def _export_wasm_with_execution(
raise ValueError("Execution options are required.")
file_manager = load_notebook(request.path.absolute_name)
- file_manager.app.inline_layout_file()
+ layout = _resolve_and_inline_layout(file_manager.app)
config = get_default_config_manager(current_path=file_manager.path)
resolved = config.get_config()
@@ -508,6 +531,7 @@ async def _export_wasm_with_execution(
display_config=display_config,
code=code,
options=request.options,
+ layout=layout,
session_snapshot=snapshot.session,
notebook_snapshot=snapshot.notebook,
sharing_config=resolved.get("sharing"),
diff --git a/marimo/_export/requests.py b/marimo/_export/requests.py
index 986e2c88a8..f71a040e59 100644
--- a/marimo/_export/requests.py
+++ b/marimo/_export/requests.py
@@ -13,6 +13,7 @@ from marimo._ast.app_config import _AppConfig
from marimo._config.config import DisplayConfig, SharingConfig
from marimo._export._status import PDFExportStatusCallback
from marimo._runtime.commands import SerializedCLIArgs
+from marimo._runtime.layout.layout import LayoutConfig
from marimo._schemas.export_options import (
HTMLExportOptions,
IPYNBExportOptions,
@@ -77,6 +78,7 @@ class HTMLExportRequest:
snapshot: NotebookExportSnapshot
display_config: DisplayConfig
options: HTMLExportOptions
+ layout: LayoutConfig | None = None
sharing_config: SharingConfig | None = None
@@ -94,6 +96,7 @@ class WASMExportRequest:
display_config: DisplayConfig
code: str
options: WASMExportOptions
+ layout: LayoutConfig | None = None
session_snapshot: NotebookSessionV1 | None = None
notebook_snapshot: NotebookV1 | None = None
sharing_config: SharingConfig | None = None
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index dec66984b9..982016e379 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -44,6 +44,7 @@ from marimo._schemas.export import (
ExportAsMarkdownRequest,
ExportAsScriptRequest,
ExportedFile,
+ to_html_export_layout,
to_html_export_options,
to_markdown_export_options,
)
@@ -417,6 +418,12 @@ class PyodideBridge:
),
display_config=self.session._initial_user_config["display"],
options=to_html_export_options(parsed),
+ layout=(
+ to_html_export_layout(
+ parsed,
+ fallback=self.session.app_manager.read_layout_config,
+ )
+ ),
)
)
return self._dump(
diff --git a/marimo/_runtime/layout/layout.py b/marimo/_runtime/layout/layout.py
index 75714dba07..d73ec36c0f 100644
--- a/marimo/_runtime/layout/layout.py
+++ b/marimo/_runtime/layout/layout.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import base64
import json
import os
from dataclasses import dataclass
@@ -23,6 +24,40 @@ class LayoutConfig:
data: dict[str, Any]
+def layout_config_to_data_uri(config: LayoutConfig) -> str:
+ contents = json.dumps({"type": config.type, "data": config.data})
+ encoded = base64.b64encode(contents.encode("utf-8")).decode("ascii")
+ return f"data:application/json;base64,{encoded}"
+
+
+def parse_layout_config(value: object, *, source: str) -> LayoutConfig | None:
+ if not isinstance(value, dict):
+ LOGGER.warning("Layout config %s must be an object", source)
+ return None
+
+ layout_type = value.get("type")
+ layout_data = value.get("data")
+ if not isinstance(layout_type, str) or not isinstance(layout_data, dict):
+ LOGGER.warning(
+ "Layout config %s must contain string `type` and object `data` fields",
+ source,
+ )
+ return None
+
+ return LayoutConfig(type=layout_type, data=layout_data)
+
+
+def _parse_layout_config(
+ contents: str | bytes, *, source: str
+) -> LayoutConfig | None:
+ try:
+ value = json.loads(contents)
+ except (json.JSONDecodeError, UnicodeDecodeError, TypeError) as error:
+ LOGGER.warning("Failed to parse layout config %s: %s", source, error)
+ return None
+ return parse_layout_config(value, source=source)
+
+
def save_layout_config(
directory: str | Path, app_name: str, config: LayoutConfig
) -> str:
@@ -63,14 +98,11 @@ def read_layout_config(
# Handle data URI
if filename.startswith("data:"):
try:
- # Decode base64
_mime, data = from_data_uri(filename)
- # Parse as JSON
- data_json = json.loads(data)
- return LayoutConfig(type=data_json["type"], data=data_json["data"])
except Exception as e:
LOGGER.warning("Failed to decode data URI: %s", e)
return None
+ return _parse_layout_config(data, source="data URI")
filepath = os.path.join(directory, filename)
if not os.path.exists(filepath):
@@ -79,6 +111,10 @@ def read_layout_config(
if not filepath.endswith(".json"):
LOGGER.warning("Layout file %s is not a JSON file", filepath)
return None
- with open(filepath, encoding="utf-8") as f:
- data = json.load(f)
- return LayoutConfig(type=data["type"], data=data["data"]) # type: ignore[call-overload]
+ try:
+ with open(filepath, encoding="utf-8") as f:
+ contents = f.read()
+ except (OSError, UnicodeError) as error:
+ LOGGER.warning("Failed to read layout config %s: %s", filepath, error)
+ return None
+ return _parse_layout_config(contents, source=filepath)
diff --git a/marimo/_schemas/export.py b/marimo/_schemas/export.py
index faa36e0774..1917a5793f 100644
--- a/marimo/_schemas/export.py
+++ b/marimo/_schemas/export.py
@@ -1,12 +1,13 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
import msgspec
from marimo._convert.markdown.flavor.base import MarkdownFlavorName
from marimo._messaging.mimetypes import MimeBundleTuple
+from marimo._runtime.layout.layout import LayoutConfig
from marimo._schemas.export_options import (
ExportPDFPreset,
ExportSetupRequirementName,
@@ -19,12 +20,23 @@ from marimo._schemas.export_options import (
)
from marimo._types.ids import CellId_t
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
class ExportAsHTMLRequest(msgspec.Struct, rename="camel"):
+ """Request a static HTML export.
+
+ `layout` carries the current client layout. An omitted field reads the
+ saved layout file, `null` selects the vertical layout, and an object uses
+ that serialized layout for this export.
+ """
+
download: bool
files: list[str]
include_code: bool
asset_url: str | None = None
+ layout: LayoutConfig | None | msgspec.UnsetType = msgspec.UNSET
def to_html_export_options(
@@ -37,6 +49,16 @@ def to_html_export_options(
)
+def to_html_export_layout(
+ request: ExportAsHTMLRequest,
+ *,
+ fallback: Callable[[], LayoutConfig | None],
+) -> LayoutConfig | None:
+ if request.layout is msgspec.UNSET:
+ return fallback()
+ return request.layout
+
+
class ExportAsScriptRequest(msgspec.Struct, rename="camel"):
download: bool
diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.py
index 2f7917bb8a..60a187c06a 100644
--- a/marimo/_server/api/endpoints/export.py
+++ b/marimo/_server/api/endpoints/export.py
@@ -53,6 +53,7 @@ from marimo._schemas.export import (
ExportFormatAvailability,
InstallExportRequirementsRequest,
UpdateCellOutputsRequest,
+ to_html_export_layout,
to_html_export_options,
to_ipynb_export_options,
to_markdown_export_options,
@@ -239,6 +240,10 @@ async def export_as_html(
resolved_config = session.config_manager.get_config()
app = session.app_file_manager.app
+ layout = to_html_export_layout(
+ body,
+ fallback=session.app_file_manager.read_layout_config,
+ )
html, filename = Exporter().export_as_html(
HTMLExportRequest(
filename=session.app_file_manager.filename,
@@ -252,6 +257,7 @@ async def export_as_html(
),
display_config=resolved_config["display"],
options=to_html_export_options(body),
+ layout=layout,
sharing_config=resolved_config.get("sharing"),
)
)
@@ -295,9 +301,11 @@ async def auto_export_as_html(
body = await parse_request(request, cls=ExportAsHTMLRequest)
session = app_state.require_current_session()
- # Reload the file manager to get the latest state
- session.app_file_manager.reload()
session_view = session.session_view
+ layout = to_html_export_layout(
+ body,
+ fallback=session.app_file_manager.read_layout_config,
+ )
if not session.app_file_manager.is_notebook_named:
raise HTTPException(
@@ -306,7 +314,7 @@ async def auto_export_as_html(
)
# If we have already exported to HTML, don't do it again
- if not session_view.needs_export("html"):
+ if not session_view.needs_auto_export_html(layout):
LOGGER.debug("Already auto-exported to HTML")
return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)
@@ -315,11 +323,15 @@ async def auto_export_as_html(
LOGGER.info("No outputs to export")
return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)
+ filename = session.app_file_manager.filename
+ generation = session_view.auto_export_generation
+ revision = auto_exporter.reserve_revision(filename, "html")
+
async def _background_export() -> None:
app = session.app_file_manager.app
html, _filename = Exporter().export_as_html(
HTMLExportRequest(
- filename=session.app_file_manager.filename,
+ filename=filename,
app_code=app.to_py(),
app_config=app.config,
snapshot=serialize_notebook_snapshot(
@@ -330,15 +342,20 @@ async def auto_export_as_html(
),
display_config=session.config_manager.get_config()["display"],
options=to_html_export_options(body),
+ layout=layout,
)
)
# Save the HTML file to disk, at `.marimo/<filename>.html`
- await auto_exporter.save_html(
- filename=session.app_file_manager.filename,
+ if session.app_file_manager.filename != filename:
+ return
+ committed = await auto_exporter.save_html(
+ filename=filename,
html=html,
+ revision=revision,
)
- session_view.mark_auto_export_html()
+ if committed:
+ session_view.mark_auto_export_html(layout, generation=generation)
return JSONResponse(
content=asdict(SuccessResponse()),
@@ -563,6 +580,10 @@ async def auto_export_as_markdown(
LOGGER.debug("Already auto-exported to Markdown")
return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)
+ filename = session.app_file_manager.filename
+ generation = session_view.auto_export_generation
+ revision = auto_exporter.reserve_revision(filename, "md")
+
async def _background_export() -> None:
# Reload the file manager to get the latest state
session.app_file_manager.reload()
@@ -575,11 +596,15 @@ async def auto_export_as_markdown(
)
# Save the Markdown file to disk, at `.marimo/<filename>.md`
- await auto_exporter.save_md(
- filename=session.app_file_manager.filename,
+ if session.app_file_manager.filename != filename:
+ return
+ committed = await auto_exporter.save_md(
+ filename=filename,
markdown=result.text,
+ revision=revision,
)
- session_view.mark_auto_export_md()
+ if committed:
+ session_view.mark_auto_export_md(generation=generation)
return JSONResponse(
content=asdict(SuccessResponse()),
@@ -652,6 +677,10 @@ async def auto_export_as_ipynb(
session_view.mark_auto_export_ipynb()
return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)
+ filename = session.app_file_manager.filename
+ generation = session_view.auto_export_generation
+ revision = auto_exporter.reserve_revision(filename, "ipynb")
+
async def _background_export() -> None:
# Reload the file manager to get the latest state
session.app_file_manager.reload()
@@ -665,11 +694,15 @@ async def auto_export_as_ipynb(
)
# Save the IPYNB file to disk, at `.marimo/<filename>.ipynb`
- await auto_exporter.save_ipynb(
- filename=session.app_file_manager.filename,
+ if session.app_file_manager.filename != filename:
+ return
+ committed = await auto_exporter.save_ipynb(
+ filename=filename,
ipynb=ipynb,
+ revision=revision,
)
- session_view.mark_auto_export_ipynb()
+ if committed:
+ session_view.mark_auto_export_ipynb(generation=generation)
return JSONResponse(
content=asdict(SuccessResponse()),
diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.py
index 9143531937..f3b32c2d76 100644
--- a/marimo/_server/api/endpoints/files.py
+++ b/marimo/_server/api/endpoints/files.py
@@ -9,6 +9,9 @@ from starlette.exceptions import HTTPException
from starlette.responses import PlainTextResponse
from marimo import _loggers
+from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
+)
from marimo._runtime.commands import RenameNotebookCommand
from marimo._server.api.deps import AppState
from marimo._server.api.utils import (
@@ -184,7 +187,14 @@ async def save(
)
session = app_state.require_current_session()
- contents = session.app_file_manager.save(body)
+ session_id = app_state.require_current_session_id()
+ contents = session.app_file_manager.save(
+ body,
+ on_document_transaction=lambda transaction: session.notify(
+ NotebookDocumentTransactionNotification(transaction=transaction),
+ from_consumer_id=ConsumerId(session_id),
+ ),
+ )
return PlainTextResponse(content=contents)
diff --git a/marimo/_server/templates/api.py b/marimo/_server/templates/api.py
index f39b462b7c..f1d062cea6 100644
--- a/marimo/_server/templates/api.py
+++ b/marimo/_server/templates/api.py
@@ -14,6 +14,7 @@ from typing import Any, Literal, cast
from marimo._ast.app_config import _AppConfig
from marimo._config.config import MarimoConfig, PartialMarimoConfig
from marimo._convert.converters import MarimoConvert
+from marimo._runtime.layout.layout import parse_layout_config
from marimo._schemas.notebook import NotebookV1
from marimo._schemas.session import NotebookSessionV1
from marimo._server.tokens import SkewProtectionToken
@@ -162,6 +163,7 @@ def render_static_notebook(
session_snapshot: NotebookSessionV1,
notebook_snapshot: NotebookV1 | None = None,
files: dict[str, str] | None = None,
+ layout: dict[str, Any] | None = None,
config: dict[str, Any] | None = None,
app_config: dict[str, Any] | None = None,
asset_url: str | None = None,
@@ -178,6 +180,7 @@ def render_static_notebook(
session_snapshot: Pre-computed outputs for all cells (required).
notebook_snapshot: Notebook structure/metadata.
files: Files to embed (key=path, value=base64 content).
+ layout: Serialized notebook layout with `type` and `data` fields.
config: User configuration overrides.
app_config: Notebook-specific configuration.
asset_url: CDN URL for assets (default: jsDelivr).
@@ -207,6 +210,11 @@ def render_static_notebook(
user_config = _parse_config(config)
config_overrides_obj = _parse_partial_config(config or {})
app_config_obj = _AppConfig.from_untrusted_dict(app_config)
+ layout_config = (
+ parse_layout_config(layout, source="render_static_notebook")
+ if layout is not None
+ else None
+ )
# Get HTML template
html = _get_html_template()
@@ -223,6 +231,7 @@ def render_static_notebook(
session_snapshot=session_snapshot,
notebook_snapshot=notebook_snapshot,
files=files or {},
+ layout=layout_config,
asset_url=asset_url,
)
diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.py
index d53b577507..0620756a93 100644
--- a/marimo/_session/notebook/file_manager.py
+++ b/marimo/_session/notebook/file_manager.py
@@ -37,7 +37,7 @@ from marimo._utils.scripts import with_python_version_requirement
LOGGER = _loggers.marimo_logger()
if TYPE_CHECKING:
- from collections.abc import Sequence
+ from collections.abc import Callable, Sequence
from marimo._messaging.notebook.document import NotebookCell
from marimo._server.models.models import (
@@ -415,11 +415,18 @@ class AppFileManager:
)
return ""
- def save(self, request: SaveNotebookRequest) -> str:
+ def save(
+ self,
+ request: SaveNotebookRequest,
+ *,
+ on_document_transaction: Callable[[Transaction], None] | None = None,
+ ) -> str:
"""Save the notebook.
Args:
request: Save request with cell data and options
+ on_document_transaction: Called with the applied in-memory
+ document transaction before the file is persisted.
Returns:
Serialized notebook content
@@ -439,14 +446,6 @@ class AppFileManager:
filename_path = Path(canonicalize_filename(filename))
with self._save_lock:
- # Update app with new cell data
- self.app.with_data(
- cell_ids=cell_ids,
- codes=codes,
- names=names,
- configs=configs,
- )
-
if self.is_notebook_named and not self._is_same_path(
filename_path
):
@@ -455,6 +454,15 @@ class AppFileManager:
detail="Save handler cannot rename files.",
)
+ transaction = self.app.apply_data(
+ cell_ids=cell_ids,
+ codes=codes,
+ names=names,
+ configs=configs,
+ )
+ if on_document_transaction is not None and transaction.changes:
+ on_document_transaction(transaction)
+
# Save layout if provided
if layout is not None:
app_dir = filename_path.parent
diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.py
index 0d3d84da47..bd42302931 100644
--- a/marimo/_session/state/session_view.py
+++ b/marimo/_session/state/session_view.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import copy
import time
from dataclasses import dataclass
from typing import Any, Literal, cast
@@ -45,6 +46,7 @@ from marimo._runtime.commands import (
SyncGraphCommand,
UpdateUIElementCommand,
)
+from marimo._runtime.layout.layout import LayoutConfig
from marimo._sql.connection_utils import (
update_schema_list_in_connection,
update_table_in_connection,
@@ -128,8 +130,10 @@ class AutoExportState:
md: bool = False
ipynb: bool = False
session: bool = False
+ generation: int = 0
def mark_all_stale(self) -> None:
+ self.generation += 1
self.html = False
self.md = False
self.ipynb = False
@@ -138,8 +142,13 @@ class AutoExportState:
def is_stale(self, export_type: ExportType) -> bool:
return not getattr(self, export_type)
- def mark_exported(self, export_type: ExportType) -> None:
+ def mark_exported(
+ self, export_type: ExportType, *, generation: int | None = None
+ ) -> bool:
+ if generation is not None and generation != self.generation:
+ return False
setattr(self, export_type, True)
+ return True
class SessionView:
@@ -202,6 +211,7 @@ class SessionView:
# Auto-saving
self.auto_export_state = AutoExportState()
+ self._auto_export_html_layout: LayoutConfig | None = None
def _add_ui_value(self, name: str, value: Any) -> None:
self.ui_values[name] = value
@@ -210,7 +220,6 @@ class SessionView:
self.last_executed_code[req.cell_id] = req.code
def add_raw_notification(self, raw_notification: KernelMessage) -> None:
- self._touch()
# Type ignore because NotificationMessage is a Union, not a class
self.add_notification(deserialize_kernel_message(raw_notification)) # type: ignore[arg-type]
@@ -279,7 +288,6 @@ class SessionView:
def add_notification(self, notification: NotificationMessage) -> None:
"""Add a notification to the session view."""
self._touch()
- self.auto_export_state.mark_all_stale()
if isinstance(notification, CellNotification):
previous = self.cell_notifications.get(notification.cell_id)
@@ -622,14 +630,33 @@ class SessionView:
for notif in self.cell_notifications.values()
)
- def mark_auto_export_html(self) -> None:
- self.auto_export_state.mark_exported("html")
+ def mark_auto_export_html(
+ self,
+ layout: LayoutConfig | None = None,
+ *,
+ generation: int | None = None,
+ ) -> bool:
+ if not self.auto_export_state.mark_exported(
+ "html", generation=generation
+ ):
+ return False
+ self._auto_export_html_layout = copy.deepcopy(layout)
+ return True
- def mark_auto_export_md(self) -> None:
- self.auto_export_state.mark_exported("md")
+ def needs_auto_export_html(self, layout: LayoutConfig | None) -> bool:
+ return self.needs_export("html") or (
+ layout != self._auto_export_html_layout
+ )
- def mark_auto_export_ipynb(self) -> None:
- self.auto_export_state.mark_exported("ipynb")
+ def mark_auto_export_md(self, *, generation: int | None = None) -> bool:
+ return self.auto_export_state.mark_exported(
+ "md", generation=generation
+ )
+
+ def mark_auto_export_ipynb(self, *, generation: int | None = None) -> bool:
+ return self.auto_export_state.mark_exported(
+ "ipynb", generation=generation
+ )
def mark_auto_export_session(self) -> None:
self.auto_export_state.mark_exported("session")
@@ -637,6 +664,10 @@ class SessionView:
def needs_export(self, export_type: ExportType) -> bool:
return self.auto_export_state.is_stale(export_type)
+ @property
+ def auto_export_generation(self) -> int:
+ return self.auto_export_state.generation
+
def _touch(self) -> None:
self.auto_export_state.mark_all_stale()
diff --git a/marimo/_templates.py b/marimo/_templates.py
index 1fbdce6d73..39cbc2b558 100644
--- a/marimo/_templates.py
+++ b/marimo/_templates.py
@@ -25,6 +25,7 @@ from marimo._utils.versions import is_editable
from marimo._version import __version__
if TYPE_CHECKING:
+ from marimo._runtime.layout.layout import LayoutConfig
from marimo._server.api.endpoints.assets import LspWorkspace
@@ -104,6 +105,7 @@ def _get_mount_config(
session_snapshot: NotebookSessionV1 | None = None,
notebook_snapshot: NotebookV1 | None = None,
runtime_config: list[dict[str, Any]] | None = None,
+ layout: LayoutConfig | None = None,
) -> str:
"""
Return a JSON string with custom indentation and sorting.
@@ -121,6 +123,11 @@ def _get_mount_config(
"app_config": _del_none_or_empty(app_config.asdict())
if app_config
else {},
+ "layout": (
+ {"type": layout.type, "data": layout.data}
+ if layout is not None
+ else None
+ ),
"view": {
"showAppCode": show_app_code,
},
@@ -139,10 +146,11 @@ def _get_mount_config(
"config": {user_config},
"configOverrides": {config_overrides},
"appConfig": {app_config},
+ "layout": {layout},
"view": {view},
"notebook": {notebook},
"session": {session},
- "runtimeConfig": {runtime_config},
+ "runtimeConfig": {runtime_config}
}}
""".format(**{k: json_script(v) for k, v in options.items()}).strip()
@@ -397,6 +405,7 @@ def static_notebook_template(
files: dict[str, str],
model_notifications: list[ModelLifecycleNotification] | None = None,
asset_url: str | None = None,
+ layout: LayoutConfig | None = None,
) -> str:
if asset_url is None:
version = str(__version__).replace(".dev", "-dev")
@@ -423,6 +432,7 @@ def static_notebook_template(
session_snapshot=session_snapshot,
notebook_snapshot=notebook_snapshot,
runtime_config=None,
+ layout=layout,
),
)
@@ -508,6 +518,7 @@ def wasm_notebook_template(
mode: Literal["edit", "run"],
code: str,
show_code: bool,
+ layout: LayoutConfig | None = None,
asset_url: str | None = None,
session_snapshot: NotebookSessionV1 | None = None,
notebook_snapshot: NotebookV1 | None = None,
@@ -546,6 +557,7 @@ def wasm_notebook_template(
runtime_config=None,
session_snapshot=session_snapshot,
notebook_snapshot=notebook_snapshot,
+ layout=layout,
),
)
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index a587bacbaa..fc8ffb1d8c 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -1594,6 +1594,18 @@ components:
- label
title: DetectedDataSourceOrigin
type: object
+ DiagnosticsConfig:
+ description: "Configuration options for diagnostics.\n\n **Keys.**\n\n \
+ \ - `enabled`: if `True`, diagnostics will be shown in the editor\n -\
+ \ `sql_linter`: if `True`, SQL cells will have linting enabled"
+ properties:
+ enabled:
+ type: boolean
+ sql_linter:
+ type: boolean
+ required: []
+ title: DiagnosticsConfig
+ type: object
DialectHidesWhen:
description: Hide this suggestion when a live SQL engine dialect contains a
substring.
@@ -1610,18 +1622,6 @@ components:
- substrings
title: DialectHidesWhen
type: object
- DiagnosticsConfig:
- description: "Configuration options for diagnostics.\n\n **Keys.**\n\n \
- \ - `enabled`: if `True`, diagnostics will be shown in the editor\n -\
- \ `sql_linter`: if `True`, SQL cells will have linting enabled"
- properties:
- enabled:
- type: boolean
- sql_linter:
- type: boolean
- required: []
- title: DiagnosticsConfig
- type: object
DiscoverDataSourcesCommand:
description: "Discover datasource connections from the live kernel environment\
\ and configuration.\n\n Attributes:\n request_id: Unique identifier\
@@ -1917,6 +1917,10 @@ components:
title: ExecuteStaleCellsCommand
type: object
ExportAsHTMLRequest:
+ description: "Request a static HTML export.\n\n `layout` carries the current\
+ \ client layout. An omitted field reads the\n saved layout file, `null`\
+ \ selects the vertical layout, and an object uses\n that serialized layout\
+ \ for this export."
properties:
assetUrl:
anyOf:
@@ -1931,6 +1935,10 @@ components:
type: array
includeCode:
type: boolean
+ layout:
+ anyOf:
+ - $ref: '#/components/schemas/LayoutConfig'
+ - type: 'null'
required:
- download
- files
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 490d05bf0a..17e9f757d0 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -4633,15 +4633,6 @@ export interface components {
/** @enum {unknown} */
type: "configuration" | "environment";
};
- /**
- * DialectHidesWhen
- * @description Hide this suggestion when a live SQL engine dialect contains a substring.
- */
- DialectHidesWhen: {
- /** @enum {unknown} */
- kind: "dialect";
- substrings: string[];
- };
/**
* DiagnosticsConfig
* @description Configuration options for diagnostics.
@@ -4655,6 +4646,15 @@ export interface components {
enabled?: boolean;
sql_linter?: boolean;
};
+ /**
+ * DialectHidesWhen
+ * @description Hide this suggestion when a live SQL engine dialect contains a substring.
+ */
+ DialectHidesWhen: {
+ /** @enum {unknown} */
+ kind: "dialect";
+ substrings: string[];
+ };
/**
* DiscoverDataSourcesCommand
* @description Discover datasource connections from the live kernel environment and configuration.
@@ -4851,13 +4851,21 @@ export interface components {
/** @enum {unknown} */
type: "execute-stale-cells";
};
- /** ExportAsHTMLRequest */
+ /**
+ * ExportAsHTMLRequest
+ * @description Request a static HTML export.
+ *
+ * `layout` carries the current client layout. An omitted field reads the
+ * saved layout file, `null` selects the vertical layout, and an object uses
+ * that serialized layout for this export.
+ */
ExportAsHTMLRequest: {
/** @default null */
assetUrl?: string | null;
download: boolean;
files: string[];
includeCode: boolean;
+ layout?: components["schemas"]["LayoutConfig"] | null;
};
/** ExportAsIPYNBRequest */
ExportAsIPYNBRequest: {
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 9dd70db979..356e67aace 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -28,7 +28,10 @@ from marimo._utils import async_path
from marimo._utils.paths import marimo_package_path
from marimo._utils.platform import is_windows
from marimo._utils.scripts import read_pyproject_from_script
-from tests._server.templates.utils import normalize_index_html
+from tests._server.templates.utils import (
+ normalize_index_html,
+ parse_mount_config,
+)
from tests.mocks import (
_sanitize_version,
delete_lines_with_files,
@@ -153,11 +156,14 @@ async def _wait_for_file(file: str, timeout: float = 10.0) -> None:
def _write_minimal_wasm_notebook(
- file: Path, cell: str, metadata: str = ""
+ file: Path,
+ cell: str,
+ metadata: str = "",
+ app_args: str = "",
) -> None:
file.write_text(
f"{metadata}import marimo\n\n"
- "app = marimo.App()\n\n"
+ f"app = marimo.App({app_args})\n\n"
"@app.cell\n"
"def __():\n"
f"{cell}\n\n"
@@ -221,11 +227,20 @@ class TestExportHTML:
assert '<marimo-code hidden=""></marimo-code>' in html
@staticmethod
- def test_cli_export_html_wasm(temp_marimo_file: str) -> None:
- out_dir = Path(temp_marimo_file).parent / "out"
+ def test_cli_export_html_wasm(tmp_path: Path) -> None:
+ notebook = tmp_path / "notebook.py"
+ _write_minimal_wasm_notebook(
+ notebook,
+ ' "hello"\n return\n',
+ app_args='layout_file="layouts/notebook.slides.json"',
+ )
+ layout_file = tmp_path / "layouts" / "notebook.slides.json"
+ layout_file.parent.mkdir()
+ layout_file.write_text('{"type": "slides", "data": {}}')
+ out_dir = tmp_path / "out"
p = _run_export(
"html-wasm",
- temp_marimo_file,
+ str(notebook),
"--mode",
"edit",
"--output",
@@ -239,6 +254,9 @@ class TestExportHTML:
assert "<marimo-wasm" in html
assert '"showAppCode": false' in html
assert Path(out_dir / ".nojekyll").exists()
+ mount_config = parse_mount_config((out_dir / "index.html").read_text())
+ assert mount_config["mode"] == "edit"
+ assert mount_config["layout"] == {"type": "slides", "data": {}}
@staticmethod
def test_cli_export_html_wasm_packages_local_modules(
diff --git a/tests/_export/test_auto_exporter.py b/tests/_export/test_auto_exporter.py
new file mode 100644
index 0000000000..77033034e1
--- /dev/null
+++ b/tests/_export/test_auto_exporter.py
@@ -0,0 +1,43 @@
+import asyncio
+import threading
+from pathlib import Path
+
+from marimo._export.exporter import AutoExporter
+
+
+async def test_newer_auto_export_supersedes_an_older_write(
+ tmp_path: Path, monkeypatch
+) -> None:
+ monkeypatch.setattr(
+ "marimo._export.exporter.notebook_output_dir",
+ lambda _path: tmp_path,
+ )
+ exporter = AutoExporter()
+ try:
+ older_write_started = threading.Event()
+ release_older_write = threading.Event()
+
+ def write_file(filepath: Path, content: str) -> None:
+ if content == "older":
+ older_write_started.set()
+ assert release_older_write.wait(timeout=2)
+ filepath.write_text(content)
+
+ monkeypatch.setattr(exporter, "_write_file_sync", write_file)
+ older = exporter.reserve_revision("notebook.py", "html")
+ older_task = asyncio.create_task(
+ exporter.save_html("notebook.py", "older", revision=older)
+ )
+ assert await asyncio.to_thread(older_write_started.wait, 2)
+
+ newer = exporter.reserve_revision("notebook.py", "html")
+ newer_task = asyncio.create_task(
+ exporter.save_html("notebook.py", "newer", revision=newer)
+ )
+ release_older_write.set()
+
+ assert not await older_task
+ assert await newer_task
+ assert (tmp_path / "notebook.html").read_text() == "newer"
+ finally:
+ exporter.cleanup()
diff --git a/tests/_export/test_exporter.py b/tests/_export/test_exporter.py
index 16fd7f94b8..5f8be44286 100644
--- a/tests/_export/test_exporter.py
+++ b/tests/_export/test_exporter.py
@@ -67,6 +67,7 @@ from marimo._session.state.serialize import get_session_cache_file
from marimo._session.state.session_view import SessionView
from marimo._types.ids import WidgetModelId
from marimo._utils.marimo_path import MarimoPath
+from tests._server.templates.utils import parse_mount_config
from tests.mocks import delete_lines_with_files, snapshotter
if TYPE_CHECKING:
@@ -143,6 +144,26 @@ def _wasm_export_request(
)
+def _write_layout_notebook(
+ tmp_path: Path,
+ *,
+ contents: str | None,
+ layout_file: str = "layouts/layout.json",
+) -> Path:
+ notebook = tmp_path / "test.py"
+ source = (
+ (FIXTURES_DIR / "with_layout.py")
+ .read_text()
+ .replace("layouts/layout.json", layout_file)
+ )
+ notebook.write_text(source)
+ if contents is not None:
+ path = tmp_path / layout_file
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(contents)
+ return notebook
+
+
def _pdf_export_request(
*,
app: InternalApp,
@@ -421,25 +442,78 @@ async def test_export_wasm(mode: str, expected_mode_in_content: str) -> None:
assert expected_mode_in_content in content
-async def test_export_html_with_layout(tmp_path: Path) -> None:
- """Test HTML export with layout file."""
- test_file = tmp_path / "test.py"
- test_file.write_text((FIXTURES_DIR / "with_layout.py").read_text())
-
- # Create the layout file
- layout_file = tmp_path / "layouts" / "layout.json"
- layout_file.parent.mkdir(parents=True, exist_ok=True)
- layout_file.write_text('{"type": "slides", "data": {}}')
+ "export_kind",
+ ["static", "wasm", "wasm-executed"],
+)
+ ("layout_file", "contents", "expected"),
+ [
+ (
+ "layouts/layout.json",
+ '{"type": "slides", "data": {}}',
+ {"type": "slides", "data": {}},
+ ),
+ ("layouts/layout.json", "{", None),
+ ("layouts/missing.json", None, None),
+ (
+ "data:application/json;base64,"
+ + base64.b64encode(
+ b'{"type":"slides","data":{"deck":{"transition":"fade"}}}'
+ ).decode("ascii"),
+ None,
+ {
+ "type": "slides",
+ "data": {"deck": {"transition": "fade"}},
+ },
+ ),
+ (
+ "layouts/layout.txt",
+ '{"type": "slides", "data": {}}',
+ None,
+ ),
+ ],
+ ids=["valid", "malformed", "missing", "data-uri", "non-json"],
+)
+async def test_file_export_resolves_layout_once(
+ tmp_path: Path,
+ export_kind: str,
+ layout_file: str,
+ contents: str | None,
+ expected: dict[str, Any] | None,
+) -> None:
+ test_file = _write_layout_notebook(
+ tmp_path,
+ layout_file=layout_file,
+ contents=contents,
+ )
- result = await export_wasm(
- WASMFileExportRequest(
- path=MarimoPath(test_file),
- options=WASMExportOptions(mode="edit", show_code=True),
+ if export_kind == "static":
+ result = await export_html(
+ HTMLFileExportRequest(
+ path=MarimoPath(test_file),
+ options=HTMLExportOptions(files=(), include_code=True),
+ )
)
- )
+ else:
+ result = await export_wasm(
+ WASMFileExportRequest(
+ path=MarimoPath(test_file),
+ options=WASMExportOptions(mode="run", show_code=True),
+ execution=(
+ NotebookExecutionOptions(cli_args={}, argv=[])
+ if export_kind == "wasm-executed"
+ else None
+ ),
+ )
+ )
+
assert result.did_error is False
- assert "layout.json" not in result.text
- assert "data:application/json" in result.text
+ assert parse_mount_config(result.text)["layout"] == expected
+ if not layout_file.startswith("data:"):
+ assert layout_file not in result.text
+ if expected is not None:
+ assert "data:application/json;base64," in result.text
# HTML export
diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.py
index f11a50b427..3acf9409b4 100644
--- a/tests/_pyodide/test_pyodide_session.py
+++ b/tests/_pyodide/test_pyodide_session.py
@@ -54,6 +54,7 @@ from marimo._runtime.context.types import teardown_context
from marimo._session.model import SessionMode
from marimo._session.notebook import AppFileManager
from marimo._types.ids import CellId_t, UIElementId
+from tests._server.templates.utils import parse_mount_config
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Generator
@@ -1074,6 +1075,10 @@ def test_pyodide_bridge_export_html(
"download": False,
"files": [],
"includeCode": True,
+ "layout": {
+ "type": "slides",
+ "data": {"deck": {"transition": "fade"}},
+ },
}
)
@@ -1082,8 +1087,10 @@ def test_pyodide_bridge_export_html(
assert exported_file["filename"] == "test.html"
assert exported_file["mediaType"] == "text/html; charset=utf-8"
- # HTML should contain marimo-related content
- assert len(exported_file["contents"]) > 0
+ assert parse_mount_config(exported_file["contents"])["layout"] == {
+ "type": "slides",
+ "data": {"deck": {"transition": "fade"}},
+ }
@pytest.mark.parametrize(
diff --git a/tests/_runtime/layout/test_layout.py b/tests/_runtime/layout/test_layout.py
index e55ad41a89..17c7d3f538 100644
--- a/tests/_runtime/layout/test_layout.py
+++ b/tests/_runtime/layout/test_layout.py
@@ -79,11 +79,19 @@ def test_read_layout_config_invalid_data_uri():
assert config is None
-def test_read_layout_config_invalid_json(temp_dir: str):
- # Create an invalid JSON file
- path = Path(temp_dir) / "layouts" / "invalid.grid.json"
+ "contents",
+ ["invalid json", b"\xff\xfe", "[]", '{"type": 1, "data": []}'],
+ ids=["json", "encoding", "root", "fields"],
+)
+def test_read_layout_config_invalid_contents(
+ temp_dir: str, contents: str | bytes
+) -> None:
+ path = Path(temp_dir) / "layouts" / "invalid.slides.json"
path.parent.mkdir(exist_ok=True)
- path.write_text("invalid json")
+ if isinstance(contents, bytes):
+ path.write_bytes(contents)
+ else:
+ path.write_text(contents)
- with pytest.raises(json.JSONDecodeError):
- read_layout_config(temp_dir, "layouts/invalid.grid.json")
+ assert read_layout_config(temp_dir, "layouts/invalid.slides.json") is None
diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.py
index 4c3bc83a0c..af1b67af2b 100644
--- a/tests/_server/api/endpoints/test_export.py
+++ b/tests/_server/api/endpoints/test_export.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import asyncio
import json
import os
import re
@@ -22,6 +23,7 @@ from marimo._export.requests import PDFExportRequest
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.notification import CellNotification
from marimo._output.utils import uri_encode_component
+from marimo._runtime.layout.layout import LayoutConfig
from marimo._schemas.export import (
ExportAvailabilityResponse,
ExportFormatAvailability,
@@ -42,9 +44,12 @@ from tests._server.mocks import (
with_read_session,
with_session,
)
+from tests._server.templates.utils import parse_mount_config
from tests.mocks import EDGE_CASE_FILENAMES, snapshotter
if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable
+
from httpx import Response
from starlette.testclient import TestClient
@@ -442,15 +447,31 @@ def test_export_html(client: TestClient) -> None:
session = get_session_manager(client).get_session(SESSION_ID)
assert session
session.app_file_manager.filename = "test.py"
- response = client.post(
- "/api/export/html",
- headers={**HEADERS, "Origin": "localhost"},
- json={
- "download": False,
- "files": [],
- "includeCode": True,
- },
- )
+ with patch.object(
+ session.app_file_manager,
+ "read_layout_config",
+ return_value=LayoutConfig(type="slides", data={"deck": {}}),
+ ):
+ response = client.post(
+ "/api/export/html",
+ headers={**HEADERS, "Origin": "localhost"},
+ json={
+ "download": False,
+ "files": [],
+ "includeCode": True,
+ },
+ )
+ current_layout_response = client.post(
+ "/api/export/html",
+ headers=HEADERS,
+ json={
+ "download": False,
+ "files": [],
+ "includeCode": True,
+ "layout": None,
+ },
+ )
+
body = response.text
assert '<marimo-code hidden=""></marimo-code>' not in body
assert CODE in body
@@ -461,6 +482,12 @@ def test_export_html(client: TestClient) -> None:
assert response.headers["content-type"] == "text/html; charset=utf-8"
exposed_headers = response.headers["access-control-expose-headers"].lower()
assert "content-disposition" in exposed_headers
+ assert parse_mount_config(response.text)["layout"] == {
+ "type": "slides",
+ "data": {"deck": {}},
+ }
+ assert current_layout_response.status_code == 200
+ assert parse_mount_config(current_layout_response.text)["layout"] is None
@with_session(SESSION_ID)
@@ -955,7 +982,7 @@ def test_auto_export_html(client: TestClient, temp_marimo_file: str) -> None:
session = get_session_manager(client).get_session(SESSION_ID)
assert session
assert temp_marimo_file is not None
- session.app_file_manager.filename = temp_marimo_file
+ session.app_file_manager = AppFileManager(temp_marimo_file)
session.session_view.add_notification(
CellNotification(
cell_id=CellId_t("new_cell"),
@@ -966,35 +993,91 @@ def test_auto_export_html(client: TestClient, temp_marimo_file: str) -> None:
),
)
)
-
+ cell_id = session.document.cell_ids[0]
response = client.post(
- "/api/export/auto_export/html",
+ "/api/document/transaction",
headers=HEADERS,
json={
- "download": False,
- "files": [],
- "includeCode": True,
+ "changes": [
+ {
+ "type": "set-code",
+ "cellId": cell_id,
+ "code": 'live_value = "export-current-session"',
+ }
+ ]
},
)
assert response.status_code == 200
+
+ def auto_export(**overrides: object) -> Response:
+ return client.post(
+ "/api/export/auto_export/html",
+ headers=HEADERS,
+ json={
+ "download": False,
+ "files": [],
+ "includeCode": True,
+ **overrides,
+ },
+ )
+
+ response = auto_export()
+ assert response.status_code == 200
assert response.json() == {"success": True}
+ exported_html = (
+ Path(temp_marimo_file).parent / "__marimo__" / "notebook.html"
+ ).read_text(encoding="utf-8")
+ assert "export-current-session" in exported_html
- response = client.post(
- "/api/export/auto_export/html",
- headers=HEADERS,
- json={
- "download": False,
- "files": [],
- "includeCode": True,
- },
+ assert auto_export().status_code == 304
+
+ slides = {"type": "slides", "data": {}}
+ assert auto_export(layout=slides).status_code == 200
+ assert auto_export(layout=slides).status_code == 304
+
+
+@with_session(SESSION_ID)
+def test_auto_export_html_skips_a_renamed_notebook(
+ client: TestClient, temp_marimo_file: str
+) -> None:
+ session = get_session_manager(client).get_session(SESSION_ID)
+ assert session
+ session.app_file_manager = AppFileManager(temp_marimo_file)
+ session.session_view.add_notification(
+ CellNotification(
+ cell_id=CellId_t("new_cell"),
+ output=CellOutput.stdout("hello"),
+ )
)
- # Not modified response
- assert response.status_code == 304
- # Assert __marimo__ directory is created
- assert os.path.exists(
- os.path.join(os.path.dirname(temp_marimo_file), "__marimo__")
+ tasks: list[Callable[[], Awaitable[None]]] = []
+
+ class DeferredBackgroundTask:
+ def __init__(self, task: Callable[[], Awaitable[None]]) -> None:
+ tasks.append(task)
+
+ async def __call__(self) -> None:
+ return
+
+ with patch(
+ "marimo._server.api.endpoints.export.BackgroundTask",
+ DeferredBackgroundTask,
+ ):
+ response = client.post(
+ "/api/export/auto_export/html",
+ headers=HEADERS,
+ json={"download": False, "files": [], "includeCode": True},
+ )
+ assert response.status_code == 200
+ assert len(tasks) == 1
+
+ old_export = Path(temp_marimo_file).parent / "__marimo__" / "notebook.html"
+ session.app_file_manager.filename = str(
+ Path(temp_marimo_file).with_name("renamed.py")
)
+ asyncio.run(tasks[0]())
+
+ assert not old_export.exists()
@with_session(SESSION_ID)
diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.py
index cb5eae2b67..4469b90ca9 100644
--- a/tests/_server/api/endpoints/test_kiosk.py
+++ b/tests/_server/api/endpoints/test_kiosk.py
@@ -25,8 +25,8 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:
with client.websocket_connect(
"/ws?session_id=123", headers=_HEADERS
) as websocket:
- data = websocket.receive_json()
- assert_kernel_ready_response(data)
+ editor_ready = websocket.receive_json()
+ assert_kernel_ready_response(editor_ready)
# Connect in kiosk mode
with client.websocket_connect(
@@ -66,6 +66,36 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:
data = other_websocket.receive_json()
assert data["op"] == "notebook-document-transaction"
+ # A full save replaces the canonical document. Viewers receive
+ # the applied diff even when it includes edits that bypassed the
+ # incremental document endpoint during recovery.
+ filename = client.app.state.session_manager.workspace.get_unique_file_key()
+ assert filename
+ replacement_code = editor_ready["data"]["codes"][0] + "\n# saved"
+ response = client.post(
+ "/api/kernel/save",
+ headers=HEADERS,
+ json={
+ "cellIds": editor_ready["data"]["cell_ids"],
+ "filename": filename,
+ "codes": [
+ replacement_code,
+ *editor_ready["data"]["codes"][1:],
+ ],
+ "names": editor_ready["data"]["names"],
+ "configs": editor_ready["data"]["configs"],
+ },
+ )
+ assert response.status_code == 200, response.text
+ data = receive_until(
+ "notebook-document-transaction", other_websocket
+ )
+ assert any(
+ change["type"] == "set-code"
+ and change["code"] == replacement_code
+ for change in data["data"]["transaction"]["changes"]
+ )
+
# Send run single cell
response = client.post(
"/api/kernel/run",
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
index a3aafbfe7c..4ce31a2994 100644
--- a/tests/_server/templates/snapshots/export1.txt
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -103,10 +103,11 @@
"config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "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": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "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"},
+ "layout": null,
"view": {"showAppCode": true},
"notebook": {"cells": [{"code": "print('Hello, Cell 1')", "code_hash": "6eea77c855e5bfd73f3d851f474ed789", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "code_hash": "0dce0226aecd5db222f6a3aa3223214b", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
- "runtimeConfig": null,
+ "runtimeConfig": null
}),
writable: false,
configurable: false,
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
index a4c3041430..250a51c0a3 100644
--- a/tests/_server/templates/snapshots/export2.txt
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -103,10 +103,11 @@
"config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "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": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "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"},
+ "layout": null,
"view": {"showAppCode": true},
"notebook": {"cells": [{"code": "print('Hello, Cell 1')", "code_hash": "6eea77c855e5bfd73f3d851f474ed789", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "code_hash": "0dce0226aecd5db222f6a3aa3223214b", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
- "runtimeConfig": null,
+ "runtimeConfig": null
}),
writable: false,
configurable: false,
diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txt
index 91f2a5f537..85c60fc738 100644
--- a/tests/_server/templates/snapshots/export3.txt
+++ b/tests/_server/templates/snapshots/export3.txt
@@ -103,10 +103,11 @@
"config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "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": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "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"},
+ "layout": null,
"view": {"showAppCode": true},
"notebook": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"session": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
- "runtimeConfig": null,
+ "runtimeConfig": null
}),
writable: false,
configurable: false,
diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txt
index d0e36a64b9..57ea4bd320 100644
--- a/tests/_server/templates/snapshots/export4.txt
+++ b/tests/_server/templates/snapshots/export4.txt
@@ -103,10 +103,11 @@
"config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "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": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "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"},
+ "layout": null,
"view": {"showAppCode": true},
"notebook": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"session": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
- "runtimeConfig": null,
+ "runtimeConfig": null
}),
writable: false,
configurable: false,
diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txt
index af55fed968..8639bed716 100644
--- a/tests/_server/templates/snapshots/export5.txt
+++ b/tests/_server/templates/snapshots/export5.txt
@@ -115,10 +115,11 @@
"config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "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": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "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"},
+ "layout": null,
"view": {"showAppCode": true},
"notebook": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"session": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
- "runtimeConfig": null,
+ "runtimeConfig": null
}),
writable: false,
configurable: false,
diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txt
index d95c2a7573..80113423e1 100644
--- a/tests/_server/templates/snapshots/export6.txt
+++ b/tests/_server/templates/snapshots/export6.txt
@@ -104,10 +104,11 @@
"config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "custom_css": ["custom1.css", "custom2.css"], "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "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": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "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"},
+ "layout": null,
"view": {"showAppCode": true},
"notebook": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"session": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
- "runtimeConfig": null,
+ "runtimeConfig": null
}),
writable: false,
configurable: false,
diff --git a/tests/_server/templates/test_templates_api.py b/tests/_server/templates/test_templates_api.py
index 47d1401fa4..4351776e5d 100644
--- a/tests/_server/templates/test_templates_api.py
+++ b/tests/_server/templates/test_templates_api.py
@@ -14,6 +14,7 @@ from marimo._server.templates.api import (
render_notebook,
render_static_notebook,
)
+from tests._server.templates.utils import parse_mount_config
class TestRenderNotebook(unittest.TestCase):
@@ -116,9 +117,38 @@ if __name__ == "__main__":
def test_render_static_notebook(self) -> None:
html = render_static_notebook(
- code=self.code, session_snapshot=self.session_snapshot
+ code=self.code,
+ session_snapshot=self.session_snapshot,
+ layout={"type": "slides", "data": {"deck": {}}},
)
assert "<html" in html
+ assert parse_mount_config(html)["layout"] == {
+ "type": "slides",
+ "data": {"deck": {}},
+ }
+
+ def test_render_static_notebook_validates_layout(self) -> None:
+ html = render_static_notebook(
+ code=self.code,
+ session_snapshot=self.session_snapshot,
+ layout={"type": "slides", "data": {}, "future": True},
+ )
+ assert parse_mount_config(html)["layout"] == {
+ "type": "slides",
+ "data": {},
+ }
+
+ for layout in (
+ {"data": {}},
+ {"type": 1, "data": {}},
+ {"type": "slides", "data": []},
+ ):
+ html = render_static_notebook(
+ code=self.code,
+ session_snapshot=self.session_snapshot,
+ layout=layout,
+ )
+ assert parse_mount_config(html)["layout"] is None
def test_render_static_notebook_with_filename(self) -> None:
html = render_static_notebook(
diff --git a/tests/_server/templates/utils.py b/tests/_server/templates/utils.py
index 4592d78774..c1c72df978 100644
--- a/tests/_server/templates/utils.py
+++ b/tests/_server/templates/utils.py
@@ -1,7 +1,20 @@
from __future__ import annotations
+import json
import os
import re
+from typing import Any, cast
+
+
+def parse_mount_config(html: str) -> dict[str, Any]:
+ property_start = html.index(
+ 'Object.defineProperty(window, "__MARIMO_MOUNT_CONFIG__"'
+ )
+ start = html.index("value: Object.freeze({", property_start) + len(
+ "value: Object.freeze("
+ )
+ config, _end = json.JSONDecoder().raw_decode(html[start:])
+ return cast(dict[str, Any], config)
def remove_hash_from_href(url: str) -> str:
diff --git a/tests/_server/test_templates_filename.py b/tests/_server/test_templates_filename.py
index 10bf51f8ab..23f400b873 100644
--- a/tests/_server/test_templates_filename.py
+++ b/tests/_server/test_templates_filename.py
@@ -76,10 +76,6 @@ class TestTemplateFilenameHandling:
config_overrides=config_overrides,
app_config=app_config,
)
- # Remove the last ','
- last_comma_index = result.rfind(",")
- result = result[:last_comma_index] + result[last_comma_index + 1 :]
-
# Should be valid JSON
config_data = json.loads(result)
@@ -291,10 +287,6 @@ class TestMountConfigInjectionPrevention:
app_config=app_config,
)
- # Remove trailing comma for JSON parsing
- last_comma_index = result.rfind(",")
- result = result[:last_comma_index] + result[last_comma_index + 1 :]
-
# Must not contain unescaped script tags (< and > should be escaped)
assert "</script><script>" not in result
assert "<script>" not in result.lower()
@@ -332,10 +324,6 @@ class TestMountConfigInjectionPrevention:
app_config=app_config,
)
- # Remove trailing comma
- last_comma_index = result.rfind(",")
- result = result[:last_comma_index] + result[last_comma_index + 1 :]
-
# Must not contain unescaped script tags (< and > should be escaped)
assert "</script><script>" not in result
diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.py
index 87a51be85c..1a39667a5b 100644
--- a/tests/_session/state/test_session_view.py
+++ b/tests/_session/state/test_session_view.py
@@ -50,6 +50,7 @@ from marimo._runtime.commands import (
ModelUpdateMessage,
UpdateUIElementCommand,
)
+from marimo._runtime.layout.layout import LayoutConfig
from marimo._session.state.session_view import ModelReplayState, SessionView
from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE
from marimo._types.ids import CellId_t, RequestId, VariableName, WidgetModelId
@@ -1605,6 +1606,48 @@ def test_mark_auto_export(session_view: SessionView):
assert session_view.needs_export("session")
+def test_auto_export_html_tracks_layout(session_view: SessionView):
+ slides = LayoutConfig(type="slides", data={"deck": {}})
+ changed_slides = LayoutConfig(
+ type="slides", data={"deck": {"transition": "fade"}}
+ )
+
+ assert session_view.needs_auto_export_html(slides)
+ session_view.mark_auto_export_html(slides)
+ assert not session_view.needs_auto_export_html(slides)
+ assert session_view.needs_auto_export_html(changed_slides)
+
+
+def test_auto_export_does_not_mark_an_older_generation_current(
+ session_view: SessionView,
+) -> None:
+ generation = session_view.auto_export_generation
+ session_view._touch()
+
+ assert not session_view.mark_auto_export_html(generation=generation)
+ assert not session_view.mark_auto_export_md(generation=generation)
+ assert not session_view.mark_auto_export_ipynb(generation=generation)
+ assert session_view.needs_export("html")
+ assert session_view.needs_export("md")
+ assert session_view.needs_export("ipynb")
+
+
+def test_notification_advances_auto_export_generation_once() -> None:
+ notification = CellNotification(
+ cell_id=cell_id,
+ output=initial_output,
+ status=initial_status,
+ )
+
+ direct = SessionView()
+ direct.add_notification(notification)
+ assert direct.auto_export_generation == 1
+
+ serialized = SessionView()
+ serialized.add_raw_notification(serialize_kernel_message(notification))
+ assert serialized.auto_export_generation == 1
+
+
def test_dataset_filter_by_engine_and_variable(
session_view: SessionView,
) -> None: