A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: hydrate islands from JSON payloads (#9987)
Péter Gyarmatic3e14e30082c
diff --git a/docs/guides/exporting/webassembly_html.md b/docs/guides/exporting/webassembly_html.mdindex dc5cd4ce94..0a6b7368d8 100644--- a/docs/guides/exporting/webassembly_html.md+++ b/docs/guides/exporting/webassembly_html.md@@ -176,6 +176,20 @@ Use `MarimoIslandGenerator` to generate HTML for islandsAny relevant `.html` that gets generated can be run through the [`development.md`](https://github.com/marimo-team/marimo/blob/main/frontend/islands/development.md) file instructions.+### Island payloads++`MarimoIslandGenerator.render_html(include_payload=True)` and `render_body(include_payload=True)` include a JSON payload. The payload stores each cell's code, rendered output HTML, output MIME type, and display settings.++The islands runtime uses this payload to hydrate the page. The DOM still provides the visible island slots, and the payload provides the runtime cell code and output metadata.++An emitted payload looks like this. HTML-sensitive characters inside JSON strings are escaped before marimo writes the script tag.++```html+<script type="application/vnd.marimo.islands+json">{"schemaVersion":1,"appId":"main","cells":[{"cellId":"cell-1","code":"mo.md('Hello, islands!')","outputHtml":"\u003cspan\u003eHello, islands!\u003c/span\u003e","outputMimetype":"text/markdown","reactive":true,"displayCode":false,"displayOutput":true}]}</script>+```++If you post-process island HTML, preserve the script tag with type `application/vnd.marimo.islands+json` and keep its contents unchanged.+### Islands in action!!! warning "Advanced topic!"diff --git a/frontend/src/core/islands/__tests__/bridge.test.ts b/frontend/src/core/islands/__tests__/bridge.test.tsindex 5575d210b5..cac5fa2e9c 100644--- a/frontend/src/core/islands/__tests__/bridge.test.ts+++ b/frontend/src/core/islands/__tests__/bridge.test.ts@@ -12,6 +12,7 @@ import {type Base64String = components["schemas"]["Base64String"];interface TestIslandApp {id: string;+ payloadBacked?: boolean;cells: { code: string; idx: number; output: string }[];}interface TestExportContext {@@ -142,6 +143,30 @@ describe("IslandsPyodideBridge", () => {});});+ it("should ignore trusted export notebook code for a payload-backed app", async () => {+ const payloadApp = {+ id: "app-1",+ payloadBacked: true,+ cells: [{ code: "x = 1", idx: 0, output: "<div>1</div>" }],+ };+ mockParseMarimoIslandApps.mockReturnValue([payloadApp]);+ mockGetMarimoExportContext.mockReturnValue({+ trusted: true,+ notebookCode: "full notebook should be ignored",+ });+ mockCreateMarimoFile.mockReturnValue("generated payload app");++ await (+ bridge as unknown as { startSessionsForAllApps(): Promise<void> }+ ).startSessionsForAllApps();++ expect(mockCreateMarimoFile).toHaveBeenCalledWith(payloadApp);+ expect(mockStartSessionRequest).toHaveBeenCalledWith({+ appId: "app-1",+ code: "generated payload app",+ });+ });+it("should keep synthesized per-app files for multiple reactive apps even when export context exists", async () => {mockParseMarimoIslandApps.mockReturnValue([{diff --git a/frontend/src/core/islands/__tests__/parse.test.ts b/frontend/src/core/islands/__tests__/parse.test.tsindex 5c575b8162..593170e28f 100644--- a/frontend/src/core/islands/__tests__/parse.test.ts+++ b/frontend/src/core/islands/__tests__/parse.test.ts@@ -1,9 +1,12 @@/* Copyright 2026 Marimo. All rights reserved. */-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { readFileSync } from "node:fs";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {ISLAND_DATA_ATTRIBUTES,ISLAND_TAG_NAMES,+ ISLANDS_JSON_SCRIPT_TYPE,} from "@/core/islands/constants";+import { Logger } from "@/utils/Logger";import {createMarimoFile,extractIslandCodeFromEmbed,@@ -15,6 +18,43 @@ import {} from "../parse";import { createMockIslandElement, createMockIslands } from "./test-utils.tsx";+function createPayloadCell(+ overrides: Partial<{+ cellId: string;+ code: string;+ outputHtml: string;+ outputMimetype: string;+ reactive: boolean;+ displayCode: boolean;+ displayOutput: boolean;+ }> = {},+) {+ return {+ cellId: "cell-1",+ code: 'print("payload")',+ outputHtml: "<div>payload</div>",+ outputMimetype: "text/html",+ reactive: true,+ displayCode: false,+ displayOutput: true,+ ...overrides,+ };+}++function appendPayload(+ root: HTMLElement,+ payload: {+ schemaVersion: number;+ appId: string;+ cells: ReturnType<typeof createPayloadCell>[];+ },+) {+ const script = document.createElement("script");+ script.type = ISLANDS_JSON_SCRIPT_TYPE;+ script.textContent = JSON.stringify(payload);+ root.appendChild(script);+}+describe("createMarimoFile", () => {it("should return a string", () => {const app = {@@ -90,6 +130,27 @@ describe("createMarimoFile", () => {`);});+ it("should create disabled marimo cells", () => {+ const app = {+ cells: [{ code: "x = 0", disabled: true }, { code: "x = 1" }],+ };++ const result = createMarimoFile(app);++ expect(result).toMatchInlineSnapshot(`+ "import marimo+ app = marimo.App()+ @app.cell(disabled=True)+ def __():+ pass+ return+ @app.cell+ def __():+ x = 1+ return"+ `);+ });+it("should properly indent multi-line code", () => {const app = {cells: [{ code: "if True:\n print('hello')\n print('world')" }],@@ -459,6 +520,7 @@ describe("parseMarimoIslandApps", () => {afterEach(() => {document.body.removeChild(container);+ vi.restoreAllMocks();});it("should parse islands from document", () => {@@ -528,4 +590,526 @@ describe("parseMarimoIslandApps", () => {]`);});++ it("should use supported JSON payload data for matched islands", () => {+ const island = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: 'print("dom")',+ innerHTML: "<div>dom</div>",+ });+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.appendChild(island);+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [createPayloadCell()],+ });++ const result = parseMarimoIslandApps(container);++ expect(result).toEqual([+ {+ id: "app1",+ payloadBacked: true,+ cells: [+ {+ cellId: "cell-1",+ code: 'print("payload")',+ idx: 0,+ output: "<div>payload</div>",+ },+ ],+ },+ ]);+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("0");+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_ID)).toBeNull();+ expect(extractIslandCodeFromEmbed(island)).toBe('print("payload")');+ expect(island.querySelector(ISLAND_TAG_NAMES.CELL_OUTPUT)?.innerHTML).toBe(+ "<div>payload</div>",+ );+ });++ it("should parse Python-generated island payload snapshots", () => {+ const html = readFileSync(+ new URL(+ "../../../../../tests/_islands/snapshots/html-payload.txt",+ import.meta.url,+ ).pathname.replace(/^\/@fs/, ""),+ "utf8",+ );+ container.innerHTML = html;++ const result = parseMarimoIslandApps(container);+ const islands = container.querySelectorAll<HTMLElement>(+ ISLAND_TAG_NAMES.ISLAND,+ );++ expect(result).toEqual([+ {+ id: "main",+ payloadBacked: true,+ cells: [+ {+ cellId: "Hbol",+ code: "import marimo as mo",+ idx: 0,+ output: "",+ },+ {+ cellId: "MJUe",+ code: "mo.md('Hello, HTML!')",+ idx: 1,+ output: "",+ },+ ],+ },+ ]);+ expect(islands[0].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBeNull();+ expect(islands[1].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("0");+ expect(islands[2].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("1");+ });++ it("should fall back to DOM islands for unsupported payload versions", () => {+ const island = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: 'print("dom")',+ innerHTML: "<div>dom</div>",+ });+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.appendChild(island);+ appendPayload(container, {+ schemaVersion: 2,+ appId: "app1",+ cells: [createPayloadCell()],+ });++ const result = parseMarimoIslandApps(container);++ expect(result).toEqual([+ {+ id: "app1",+ cells: [+ {+ code: 'print("dom")',+ idx: 0,+ output: "<div>dom</div>",+ },+ ],+ },+ ]);+ });++ it("should ignore payload scripts rendered inside island output", () => {+ const nestedPayload = {+ schemaVersion: 1,+ appId: "app1",+ cells: [+ createPayloadCell({+ code: "payload_code_should_not_run = True",+ outputHtml: "<div>payload</div>",+ }),+ ],+ };+ const island = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: 'print("dom")',+ innerHTML: `<div>dom</div><script type="${ISLANDS_JSON_SCRIPT_TYPE}">${JSON.stringify(nestedPayload)}</script>`,+ });+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.appendChild(island);++ const result = parseMarimoIslandApps(container);++ expect(result).toEqual([+ {+ id: "app1",+ cells: [+ {+ code: 'print("dom")',+ idx: 0,+ output: island.querySelector(ISLAND_TAG_NAMES.CELL_OUTPUT)+ ?.innerHTML,+ },+ ],+ },+ ]);+ });++ it("should use payload order for runtime cell indices", () => {+ const second = createMockIslandElement({+ appId: "app1",+ cellId: "cell-2",+ code: "second_dom = True",+ innerHTML: "<div>second dom</div>",+ });+ const first = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: "first_dom = True",+ innerHTML: "<div>first dom</div>",+ });+ for (const island of [second, first]) {+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.appendChild(island);+ }+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [+ createPayloadCell({+ cellId: "cell-1",+ code: "first_payload = True",+ outputHtml: "<div>first payload</div>",+ }),+ createPayloadCell({+ cellId: "cell-2",+ code: "second_payload = True",+ outputHtml: "<div>second payload</div>",+ }),+ ],+ });++ const result = parseMarimoIslandApps(container);++ expect(result[0].cells.map((cell) => cell.code)).toEqual([+ "first_payload = True",+ "second_payload = True",+ ]);+ expect(first.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("0");+ expect(second.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("1");+ });++ it("should include payload-only runtime cells", () => {+ const island = createMockIslandElement({+ appId: "app1",+ cellId: "cell-2",+ code: "value",+ innerHTML: "<div>value</div>",+ });+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.appendChild(island);+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [+ createPayloadCell({+ cellId: "cell-1",+ code: "import marimo as mo",+ outputHtml: "",+ }),+ createPayloadCell({+ cellId: "cell-2",+ code: "mo.md('visible')",+ outputHtml: "<div>visible</div>",+ }),+ ],+ });++ const result = parseMarimoIslandApps(container);++ expect(result[0].cells.map((cell) => cell.code)).toEqual([+ "import marimo as mo",+ "mo.md('visible')",+ ]);+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("1");+ });++ it("should bind payload-backed islands by runtime index after static cells", () => {+ const island = createMockIslandElement({+ appId: "app1",+ cellId: "cell-2",+ code: "visible_dom = True",+ innerHTML: "<div>visible dom</div>",+ });+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.appendChild(island);+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [+ createPayloadCell({+ cellId: "cell-1",+ code: "",+ outputHtml: "<div>static</div>",+ reactive: false,+ }),+ createPayloadCell({+ cellId: "cell-2",+ code: "visible_payload = True",+ outputHtml: "<div>visible payload</div>",+ }),+ ],+ });++ const result = parseMarimoIslandApps(container);++ expect(result[0].cells).toEqual([+ {+ cellId: "cell-1",+ code: "",+ disabled: true,+ idx: 0,+ output: "<div>static</div>",+ },+ {+ cellId: "cell-2",+ code: "visible_payload = True",+ idx: 1,+ output: "<div>visible payload</div>",+ },+ ]);+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("1");+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_ID)).toBeNull();+ });++ it("should fall back to DOM when no payload cell matches an island", () => {+ const island = createMockIslandElement({+ appId: "app1",+ cellId: "dom-only",+ code: "dom_only = True",+ innerHTML: "<div>dom only</div>",+ });+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ island.removeAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX);+ container.appendChild(island);+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [+ createPayloadCell({+ cellId: "payload-only",+ code: "payload_only = True",+ outputHtml: "<div>payload only</div>",+ }),+ ],+ });++ const result = parseMarimoIslandApps(container);++ expect(result).toEqual([+ {+ id: "app1",+ cells: [+ {+ code: "dom_only = True",+ idx: 0,+ output: "<div>dom only</div>",+ },+ ],+ },+ ]);+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("0");+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_ID)).toBe(+ "dom-only",+ );+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE)).toBe("true");+ });++ it("should ignore payloads without matching islands", () => {+ const warn = vi.spyOn(Logger, "warn").mockImplementation(() => undefined);+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [createPayloadCell()],+ });++ const result = parseMarimoIslandApps(container);++ expect(result).toEqual([]);+ expect(warn).toHaveBeenCalledWith("No embedded marimo apps found.");+ });++ it("should still parse DOM-only apps when another app has payload", () => {+ const payloadIsland = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: "payload_dom = True",+ innerHTML: "<div>payload dom</div>",+ });+ const domIsland = createMockIslandElement({+ appId: "app2",+ code: "dom_app = True",+ innerHTML: "<div>dom app</div>",+ });+ for (const island of [payloadIsland, domIsland]) {+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.appendChild(island);+ }+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [createPayloadCell()],+ });++ const result = parseMarimoIslandApps(container);++ expect(result.map((app) => app.id)).toEqual(["app1", "app2"]);+ expect(result[0].cells[0].code).toBe('print("payload")');+ expect(result[1].cells[0].code).toBe("dom_app = True");+ });++ it("should materialize non-reactive payload islands without runtime cells", () => {+ const island = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: "static_dom = True",+ innerHTML: "<div>static dom</div>",+ });+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "false");+ island.removeAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX);+ container.appendChild(island);+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [+ createPayloadCell({+ code: "",+ outputHtml: "<div>static payload</div>",+ reactive: false,+ }),+ ],+ });++ const result = parseMarimoIslandApps(container);++ expect(result).toEqual([]);+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBeNull();+ expect(island.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_ID)).toBeNull();+ expect(island.querySelector(ISLAND_TAG_NAMES.CELL_OUTPUT)?.innerHTML).toBe(+ "<div>static payload</div>",+ );+ });++ it("should keep non-reactive display code out of runtime cells", () => {+ const staticIsland = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: "x = 0",+ innerHTML: "<div>static</div>",+ });+ const reactiveIsland = createMockIslandElement({+ appId: "app1",+ cellId: "cell-2",+ code: "y = 1",+ innerHTML: "<div>reactive</div>",+ });+ staticIsland.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "false");+ reactiveIsland.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.append(staticIsland, reactiveIsland);+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [+ createPayloadCell({+ cellId: "cell-1",+ code: "x = 0",+ outputHtml: "<div>static payload</div>",+ reactive: false,+ displayCode: true,+ }),+ createPayloadCell({+ cellId: "cell-2",+ code: "y = 1",+ outputHtml: "<div>reactive payload</div>",+ }),+ ],+ });++ const result = parseMarimoIslandApps(container);+ const file = createMarimoFile(result[0]);++ expect(result[0].cells).toEqual([+ {+ cellId: "cell-1",+ code: "",+ disabled: true,+ idx: 0,+ output: "<div>static payload</div>",+ },+ {+ cellId: "cell-2",+ code: "y = 1",+ idx: 1,+ output: "<div>reactive payload</div>",+ },+ ]);+ expect(file).not.toContain("x = 0");+ expect(file).toContain("@app.cell(disabled=True)\ndef __():\n pass");+ expect(reactiveIsland.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe(+ "1",+ );+ });++ it("should update editor initial values from payload code", () => {+ const island = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: 'print("dom")',+ innerHTML: "<div>dom</div>",+ });+ island.insertAdjacentHTML(+ "beforeend",+ '<div data-marimo-element><marimo-code-editor data-initial-value="\\"print(\\\\\\"dom\\\\\\")\\""></marimo-code-editor></div>',+ );+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.appendChild(island);+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [createPayloadCell()],+ });++ parseMarimoIslandApps(container);++ expect(+ island+ .querySelector(ISLAND_TAG_NAMES.CODE_EDITOR)+ ?.getAttribute("data-initial-value"),+ ).toBe(JSON.stringify('print("payload")'));+ });++ it("should match duplicate cell ids by occurrence", () => {+ const first = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: "dom_first = True",+ innerHTML: "<div>dom first</div>",+ });+ const second = createMockIslandElement({+ appId: "app1",+ cellId: "cell-1",+ code: "dom_second = True",+ innerHTML: "<div>dom second</div>",+ });+ for (const island of [first, second]) {+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");+ container.appendChild(island);+ }+ appendPayload(container, {+ schemaVersion: 1,+ appId: "app1",+ cells: [+ createPayloadCell({+ code: "payload_first = True",+ outputHtml: "<div>payload first</div>",+ }),+ createPayloadCell({+ code: "payload_second = True",+ outputHtml: "<div>payload second</div>",+ }),+ ],+ });++ const result = parseMarimoIslandApps(container);++ expect(result[0].cells.map((cell) => cell.code)).toEqual([+ "payload_first = True",+ "payload_second = True",+ ]);+ expect(first.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("0");+ expect(second.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("1");+ });});diff --git a/frontend/src/core/islands/__tests__/test-utils.tsx b/frontend/src/core/islands/__tests__/test-utils.tsxindex 86d82bfd38..6178c23b69 100644--- a/frontend/src/core/islands/__tests__/test-utils.tsx+++ b/frontend/src/core/islands/__tests__/test-utils.tsx@@ -23,12 +23,14 @@ import type { WorkerFactory } from "@/core/islands/worker-factory";export function createMockIslandElement(options: {appId?: string;cellIdx?: string;+ cellId?: string;code?: string;innerHTML?: string;}): HTMLElement {const {appId = "test-app",cellIdx = "0",+ cellId,code = "import marimo as mo",innerHTML = "",} = options;@@ -36,6 +38,9 @@ export function createMockIslandElement(options: {const element = document.createElement(ISLAND_TAG_NAMES.ISLAND);element.setAttribute(ISLAND_DATA_ATTRIBUTES.APP_ID, appId);element.setAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX, cellIdx);+ if (cellId) {+ element.setAttribute(ISLAND_DATA_ATTRIBUTES.CELL_ID, cellId);+ }if (code) {const codeElement = document.createElement(ISLAND_TAG_NAMES.CELL_CODE);@@ -146,6 +151,7 @@ export async function waitForNoError<T>(export interface IslandSpec {appId?: string;+ cellId?: string;reactive?: boolean;code?: string;output?: string;@@ -160,6 +166,9 @@ export function buildIslandHTML(islands: IslandSpec[]): string {return islands.map((spec) => {const appId = spec.appId ?? "test-app";+ const cellId = spec.cellId+ ? ` ${ISLAND_DATA_ATTRIBUTES.CELL_ID}="${spec.cellId}"`+ : "";const reactive = spec.reactive ?? true;const output = spec.output ?? "<div>output</div>";const code = spec.code ?? 'print("hello")';@@ -169,7 +178,7 @@ export function buildIslandHTML(islands: IslandSpec[]): string {: "";const outputTag = `<${ISLAND_TAG_NAMES.CELL_OUTPUT}>${output}</${ISLAND_TAG_NAMES.CELL_OUTPUT}>`;- return `<${ISLAND_TAG_NAMES.ISLAND} ${ISLAND_DATA_ATTRIBUTES.APP_ID}="${appId}" ${ISLAND_DATA_ATTRIBUTES.REACTIVE}="${reactive}">${outputTag}${codeTag}</${ISLAND_TAG_NAMES.ISLAND}>`;+ return `<${ISLAND_TAG_NAMES.ISLAND} ${ISLAND_DATA_ATTRIBUTES.APP_ID}="${appId}"${cellId} ${ISLAND_DATA_ATTRIBUTES.REACTIVE}="${reactive}">${outputTag}${codeTag}</${ISLAND_TAG_NAMES.ISLAND}>`;}).join("\n");}diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.tsindex 0696d08c4e..215d4b950e 100644--- a/frontend/src/core/islands/bridge.ts+++ b/frontend/src/core/islands/bridge.ts@@ -124,8 +124,13 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {`Starting sessions for ${apps.length} app(s):`,apps.map((a) => `${a.id} (${a.cells.length} cells)`),);+ // Payload-backed apps already carry the exact runtime cells and order. The+ // full-notebook export context may describe a different source and would+ // override the payload contract for single-app pages.const exportContext =- apps.length === 1 ? getMarimoExportContext() : undefined;+ apps.length === 1 && !apps[0]?.payloadBacked+ ? getMarimoExportContext()+ : undefined;const notebookCode = exportContext?.notebookCode;for (const app of apps) {const file = notebookCode || createMarimoFile(app);diff --git a/frontend/src/core/islands/constants.ts b/frontend/src/core/islands/constants.tsindex d163406f54..a54ca97d1d 100644--- a/frontend/src/core/islands/constants.ts+++ b/frontend/src/core/islands/constants.ts@@ -10,6 +10,8 @@ export const ISLAND_TAG_NAMES = {CODE_EDITOR: "marimo-code-editor",} as const;+export const ISLANDS_JSON_SCRIPT_TYPE = "application/vnd.marimo.islands+json";+/*** Data attributes for islands*/diff --git a/frontend/src/core/islands/parse.ts b/frontend/src/core/islands/parse.tsindex 2518e372d0..8e8e4d3c66 100644--- a/frontend/src/core/islands/parse.ts+++ b/frontend/src/core/islands/parse.ts@@ -3,6 +3,7 @@import {ISLAND_DATA_ATTRIBUTES,ISLAND_TAG_NAMES,+ ISLANDS_JSON_SCRIPT_TYPE,} from "@/core/islands/constants";import { Logger } from "@/utils/Logger";@@ -23,6 +24,10 @@ export interface MarimoIslandApp {* ID since we allow multiple apps on the same page.*/id: string;+ /**+ * Whether cells came from a supported JSON payload instead of DOM parsing.+ */+ payloadBacked?: boolean;/*** Cells in the app.*/@@ -42,6 +47,30 @@ interface MarimoIslandCell {* Index of the cell.*/idx: number;+ /**+ * Stable cell identifier, when provided by the island payload.+ */+ cellId?: string;+ /**+ * Whether the generated marimo cell should be present but not executed.+ */+ disabled?: boolean;+}++interface MarimoIslandPayload {+ schemaVersion: 1;+ appId: string;+ cells: MarimoIslandPayloadCell[];+}++interface MarimoIslandPayloadCell {+ cellId: string;+ code: string;+ outputHtml: string;+ outputMimetype: string;+ reactive: boolean;+ displayCode: boolean;+ displayOutput: boolean;}/**@@ -51,14 +80,20 @@ interface MarimoIslandCell {export function parseMarimoIslandApps(root: Document | Element = document,): MarimoIslandApp[] {- const embeds = root.querySelectorAll<HTMLElement>(ISLAND_TAG_NAMES.ISLAND);+ const embeds = [+ ...root.querySelectorAll<HTMLElement>(ISLAND_TAG_NAMES.ISLAND),+ ];+ const payloads = parseMarimoIslandPayloads(root);if (embeds.length === 0) {Logger.warn("No embedded marimo apps found.");return [];}- // eslint-disable-next-line prefer-spread- return parseIslandElementsIntoApps(Array.from(embeds));+ if (payloads.length > 0) {+ return parsePayloadBackedApps(embeds, payloads);+ }++ return parseIslandElementsIntoApps(embeds);}/**@@ -90,11 +125,12 @@ export function parseIslandElementsIntoApps(continue;}- if (!apps.has(appId)) {- apps.set(appId, { id: appId, cells: [] });+ let app = apps.get(appId);+ if (!app) {+ app = { id: appId, cells: [] };+ apps.set(appId, app);}- const app = apps.get(appId)!;const idx = app.cells.length;app.cells.push({output: cellData.output,@@ -109,6 +145,159 @@ export function parseIslandElementsIntoApps(return [...apps.values()];}+function parsePayloadBackedApps(+ embeds: HTMLElement[],+ payloads: MarimoIslandPayload[],+): MarimoIslandApp[] {+ const apps = new Map<string, MarimoIslandApp>();+ const matchedPayloadCells = new Map<MarimoIslandPayloadCell, HTMLElement>();+ const consumedEmbeds = new Set<HTMLElement>();+ const acceptedPayloads: MarimoIslandPayload[] = [];++ for (const payload of payloads) {+ let hasMatchedIsland = false;+ for (const cell of payload.cells) {+ const embed = findMatchingIsland({+ embeds,+ appId: payload.appId,+ cell,+ consumedEmbeds,+ });+ if (!embed) {+ continue;+ }+ consumedEmbeds.add(embed);+ matchedPayloadCells.set(cell, embed);+ materializeIslandPayload(embed, cell);+ hasMatchedIsland = true;+ }+ // Only payloads matched to island anchors can start runtime apps.+ if (hasMatchedIsland) {+ acceptedPayloads.push(payload);+ }+ }++ const payloadAppIds = new Set(+ acceptedPayloads.map((payload) => payload.appId),+ );+ const reactivePayloadAppIds = new Set(+ acceptedPayloads+ .filter((payload) => payload.cells.some((cell) => cell.reactive))+ .map((payload) => payload.appId),+ );++ for (const payload of acceptedPayloads) {+ for (const cell of payload.cells) {+ const embed = matchedPayloadCells.get(cell);+ // Static-only payload apps render from HTML and do not need a Pyodide+ // session.+ if (!reactivePayloadAppIds.has(payload.appId)) {+ continue;+ }++ let app = apps.get(payload.appId);+ if (!app) {+ app = { id: payload.appId, payloadBacked: true, cells: [] };+ apps.set(payload.appId, app);+ }++ const idx = app.cells.length;+ const appCell: MarimoIslandCell = {+ cellId: cell.cellId,+ output: cell.outputHtml,+ code: cell.reactive ? cell.code : "",+ idx: idx,+ };+ // Keep static cells in the generated file so later reactive cells keep+ // stable runtime indices without executing static code.+ if (!cell.reactive) {+ appCell.disabled = true;+ }+ app.cells.push(appCell);+ if (cell.reactive) {+ embed?.setAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX, idx.toString());+ }+ }+ }++ // A supported payload is the runtime source for its app. Extra same-app DOM+ // islands are disconnected from runtime binding.+ for (const embed of embeds) {+ const appId = embed.getAttribute(ISLAND_DATA_ATTRIBUTES.APP_ID);+ if (appId && payloadAppIds.has(appId) && !consumedEmbeds.has(embed)) {+ embed.removeAttribute(ISLAND_DATA_ATTRIBUTES.CELL_ID);+ embed.removeAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX);+ embed.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "false");+ }+ }++ const domOnlyEmbeds = embeds.filter((embed) => {+ const appId = embed.getAttribute(ISLAND_DATA_ATTRIBUTES.APP_ID);+ return !appId || !payloadAppIds.has(appId);+ });++ return [...apps.values(), ...parseIslandElementsIntoApps(domOnlyEmbeds)];+}++function findMatchingIsland({+ embeds,+ appId,+ cell,+ consumedEmbeds,+}: {+ embeds: HTMLElement[];+ appId: string;+ cell: MarimoIslandPayloadCell;+ consumedEmbeds: Set<HTMLElement>;+}): HTMLElement | undefined {+ return embeds.find((embed) => {+ if (consumedEmbeds.has(embed)) {+ return false;+ }+ return (+ embed.getAttribute(ISLAND_DATA_ATTRIBUTES.APP_ID) === appId &&+ embed.getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_ID) === cell.cellId+ );+ });+}++function materializeIslandPayload(+ embed: HTMLElement,+ cell: MarimoIslandPayloadCell,+): void {+ embed.setAttribute(+ ISLAND_DATA_ATTRIBUTES.REACTIVE,+ JSON.stringify(cell.reactive),+ );+ // The runtime file is synthesized from payload order, so DOM anchors bind+ // by index.+ embed.removeAttribute(ISLAND_DATA_ATTRIBUTES.CELL_ID);+ if (!cell.reactive) {+ embed.removeAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX);+ }++ const output = ensureIslandChild(embed, ISLAND_TAG_NAMES.CELL_OUTPUT);+ output.innerHTML = cell.displayOutput ? cell.outputHtml : "";++ const code = ensureIslandChild(embed, ISLAND_TAG_NAMES.CELL_CODE);+ code.hidden = true;+ code.textContent = encodeURIComponent(cell.code);++ const editor = embed.querySelector<HTMLElement>(ISLAND_TAG_NAMES.CODE_EDITOR);+ if (editor) {+ editor.setAttribute("data-initial-value", JSON.stringify(cell.code));+ }+}++function ensureIslandChild(embed: HTMLElement, tagName: string): HTMLElement {+ let child = embed.querySelector<HTMLElement>(tagName);+ if (!child) {+ child = embed.ownerDocument.createElement(tagName);+ embed.appendChild(child);+ }+ return child;+}+/*** Parses a single island element into cell data* @param embed - The island HTML element@@ -132,26 +321,35 @@ export function parseIslandElement(};}-export function createMarimoFile(app: { cells: { code: string }[] }): string {+export function createMarimoFile(app: {+ cells: { code: string; disabled?: boolean }[];+}): string {const lines = ["import marimo","app = marimo.App()",app.cells.map((cell) => {- // Add 4 spaces to each line- const code = cell.code- .split("\n")- .map((line) => ` ${line}`)- .join("\n");+ // Disabled payload cells are placeholders. Emit pass so static code+ // does not define names in the runtime graph.+ const sourceCode = cell.disabled ? "" : cell.code;+ const code = sourceCode+ ? sourceCode+ .split("\n")+ .map((line) => ` ${line}`)+ .join("\n")+ : " pass";// TODO: Handle async cells better// This is probably not the best way to check if the code is async// Ideally this is pushed into the Python codeconst isAsync = code.includes("await ");const prefix = isAsync ? "async def" : "def";+ const decorator = cell.disabled+ ? "@app.cell(disabled=True)"+ : "@app.cell";// Wrap in a function- return `@app.cell\n${prefix} __():\n${code}\n return`;+ return `${decorator}\n${prefix} __():\n${code}\n return`;}).join("\n"),];@@ -204,3 +402,85 @@ export function extractIslandCodeFromEmbed(embed: HTMLElement): string {return "";}++function parseMarimoIslandPayloads(+ root: Document | Element,+): MarimoIslandPayload[] {+ const scripts = root.querySelectorAll<HTMLScriptElement>(+ `script[type="${ISLANDS_JSON_SCRIPT_TYPE}"]`,+ );+ const payloads: MarimoIslandPayload[] = [];++ for (const script of scripts) {+ if (isNestedIslandPayloadScript(script)) {+ continue;+ }+ const payload = parseMarimoIslandPayload(script.textContent);+ if (payload) {+ payloads.push(payload);+ }+ }++ return payloads;+}++function isNestedIslandPayloadScript(script: HTMLScriptElement): boolean {+ return Boolean(+ script.closest(ISLAND_TAG_NAMES.ISLAND) ||+ script.closest(ISLAND_TAG_NAMES.CELL_OUTPUT),+ );+}++function parseMarimoIslandPayload(+ text: string | undefined | null,+): MarimoIslandPayload | null {+ if (!text) {+ return null;+ }++ try {+ const payload = JSON.parse(text);+ if (isMarimoIslandPayload(payload)) {+ return payload;+ }+ } catch {+ return null;+ }++ return null;+}++function isMarimoIslandPayload(+ payload: unknown,+): payload is MarimoIslandPayload {+ if (!isRecord(payload)) {+ return false;+ }+ return (+ payload.schemaVersion === 1 &&+ typeof payload.appId === "string" &&+ Array.isArray(payload.cells) &&+ payload.cells.every(isMarimoIslandPayloadCell)+ );+}++function isMarimoIslandPayloadCell(+ cell: unknown,+): cell is MarimoIslandPayloadCell {+ if (!isRecord(cell)) {+ return false;+ }+ return (+ typeof cell.cellId === "string" &&+ typeof cell.code === "string" &&+ typeof cell.outputHtml === "string" &&+ typeof cell.outputMimetype === "string" &&+ typeof cell.reactive === "boolean" &&+ typeof cell.displayCode === "boolean" &&+ typeof cell.displayOutput === "boolean"+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null;+}diff --git a/marimo/_islands/_island_generator.py b/marimo/_islands/_island_generator.pyindex 37cfffb9a5..0a88ef2287 100644--- a/marimo/_islands/_island_generator.py+++ b/marimo/_islands/_island_generator.py@@ -16,7 +16,14 @@ from marimo._ast.compiler import compile_cellfrom marimo._ast.load import load_notebook_irfrom marimo._messaging.cell_output import CellOutputfrom marimo._output.utils import uri_encode_component+from marimo._schemas.islands import (+ ISLANDS_JSON_SCHEMA_VERSION,+ ISLANDS_JSON_SCRIPT_TYPE,+ MarimoIslandCellPayload,+ MarimoIslandPayload,+)from marimo._schemas.serialization import NotebookSerialization+from marimo._server.templates.templates import json_scriptfrom marimo._session.notebook import AppFileManager, load_notebookfrom marimo._types.ids import CellId_tfrom marimo._utils.marimo_path import MarimoPath@@ -41,7 +48,6 @@ class MarimoIslandStub:is_reactive: Whether it is reactive.cell_id: Cell identifier.app_id: App identifier.- app_id: App identifier.code: Code."""@@ -101,50 +107,49 @@ class MarimoIslandStub:- str: The HTML code."""- from marimo._output.formatting import as_html, mime_to_html+ from marimo._output.formatting import as_htmlfrom marimo._plugins.ui import code_editor- is_reactive = (- is_reactive if is_reactive is not None else self._is_reactive- )- display_code = (- display_code if display_code is not None else self._display_code- )- display_output = (- display_output- if display_output is not None- else self._display_output+ (+ resolved_display_code,+ resolved_display_output,+ resolved_is_reactive,+ ) = self._resolve_render_options(+ display_code=display_code,+ display_output=display_output,+ is_reactive=is_reactive,)- if not (display_code or display_output or is_reactive):+ if not (+ resolved_display_code+ or resolved_display_output+ or resolved_is_reactive+ ):raise ValueError("You must include either code or output")- output = (- mime_to_html(self.output.mimetype, self.output.data)- if self.output is not None- else None- )+ output_html = self._output_html()# Specifying display_code=False will hide the code block, but still# make it present for reactivity, unless reactivity is disabled.- if display_code:+ if resolved_display_code:# TODO: Allow for non-disabled code editors.code_block = as_html(code_editor(self.code.strip(), disabled=False)).textelse:+ encoded_code = (+ uri_encode_component(self.code) if resolved_is_reactive else ""+ )code_block = (- "<marimo-cell-code hidden>"- f"{uri_encode_component(self.code) if is_reactive else ''}"- "</marimo-cell-code>"+ f"<marimo-cell-code hidden>{encoded_code}</marimo-cell-code>")if as_raw:# If as_raw is True, output as raw values as possible.# Used primarily for cases with no js (like pdfs)released = (- output.text.encode().decode("unicode_escape")- if output and display_output+ output_html.encode().decode("unicode_escape")+ if output_html and resolved_display_outputelse "")return dedent(@@ -162,10 +167,10 @@ class MarimoIslandStub:<marimo-islanddata-app-id="{self._app_id}"data-cell-id="{self._cell_id}"- data-reactive="{json.dumps(is_reactive)}"+ data-reactive="{json.dumps(resolved_is_reactive)}"><marimo-cell-output>- {output.text if output and display_output else ""}+ {output_html if output_html and resolved_display_output else ""}</marimo-cell-output>{code_block}</marimo-island>@@ -173,6 +178,61 @@ class MarimoIslandStub:)).strip()+ def to_payload(+ self,+ display_code: bool | None = None,+ display_output: bool | None = None,+ is_reactive: bool | None = None,+ ) -> MarimoIslandCellPayload:+ """Return this cell's JSON payload for the islands runtime.++ Uses the configured render defaults unless options are provided.+ """+ (+ display_code,+ display_output,+ is_reactive,+ ) = self._resolve_render_options(+ display_code=display_code,+ display_output=display_output,+ is_reactive=is_reactive,+ )+ output = self.output+ output_html = self._output_html()+ return {+ "cellId": str(self._cell_id),+ "code": self.code if is_reactive or display_code else "",+ "outputHtml": output_html if display_output else "",+ "outputMimetype": (+ output.mimetype if output is not None else "text/plain"+ ),+ "reactive": is_reactive,+ "displayCode": display_code,+ "displayOutput": display_output,+ }++ def _resolve_render_options(+ self,+ *,+ display_code: bool | None = None,+ display_output: bool | None = None,+ is_reactive: bool | None = None,+ ) -> tuple[bool, bool, bool]:+ return (+ display_code if display_code is not None else self._display_code,+ display_output+ if display_output is not None+ else self._display_output,+ is_reactive if is_reactive is not None else self._is_reactive,+ )++ def _output_html(self) -> str:+ from marimo._output.formatting import mime_to_html++ if self.output is None:+ return ""+ return mime_to_html(self.output.mimetype, self.output.data).text+class MarimoIslandGenerator:"""@@ -547,6 +607,7 @@ class MarimoIslandGenerator:self,*,include_init_island: bool = True,+ include_payload: bool = False,max_width: str | None = None,margin: str | None = None,style: str | None = None,@@ -557,6 +618,7 @@ class MarimoIslandGenerator:*Args:*- include_init_island (bool): If True, adds initialization loader.+ - include_payload (bool): If True, adds a JSON payload for hydration.- max_width (str): CSS style max_width property.- margin (str): CSS style margin property.- style (str): CSS style. Overrides max_width and margin.@@ -569,6 +631,8 @@ class MarimoIslandGenerator:if include_init_island:init_island = self.render_init_island()rendered_stubs = [init_island] + rendered_stubs+ if include_payload:+ rendered_stubs.append(self.render_payload_script())body = "\n".join(rendered_stubs)@@ -600,6 +664,7 @@ class MarimoIslandGenerator:version_override: str = __version__,_development_url: str | bool = False,include_init_island: bool = True,+ include_payload: bool = False,max_width: str | None = None,margin: str | None = None,style: str | None = None,@@ -612,6 +677,7 @@ class MarimoIslandGenerator:- version_override (str): Marimo version to use for loaded js/css.- _development_url (str): If True, uses local marimo islands js.- include_init_island (bool): If True, adds initialization loader.+ - include_payload (bool): If True, adds a JSON payload for hydration.- max_width (str): CSS style max_width property.- margin (str): CSS style margin property.- style (str): CSS style. Overrides max_width and margin.@@ -622,6 +688,7 @@ class MarimoIslandGenerator:)body = self.render_body(include_init_island=include_init_island,+ include_payload=include_payload,max_width=max_width,margin=margin,style=style,@@ -647,6 +714,19 @@ class MarimoIslandGenerator:""").strip()+ def render_payload(self) -> MarimoIslandPayload:+ """Return the JSON payload consumed by the islands runtime."""+ return {+ "schemaVersion": ISLANDS_JSON_SCHEMA_VERSION,+ "appId": self._app_id,+ "cells": [stub.to_payload() for stub in self._stubs],+ }++ def render_payload_script(self) -> str:+ """Render the island app payload in a JSON script tag."""+ payload = json_script(self.render_payload())+ return f'<script type="{ISLANDS_JSON_SCRIPT_TYPE}">{payload}</script>'+def remove_empty_lines(text: str) -> str:return "\n".join([line for line in text.split("\n") if line.strip() != ""])diff --git a/marimo/_schemas/islands.py b/marimo/_schemas/islands.pynew file mode 100644index 0000000000..0f4af5f1b2--- /dev/null+++ b/marimo/_schemas/islands.py@@ -0,0 +1,23 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import Literal, TypedDict++ISLANDS_JSON_SCRIPT_TYPE: str = "application/vnd.marimo.islands+json"+ISLANDS_JSON_SCHEMA_VERSION: Literal[1] = 1+++class MarimoIslandCellPayload(TypedDict):+ cellId: str+ code: str+ outputHtml: str+ outputMimetype: str+ reactive: bool+ displayCode: bool+ displayOutput: bool+++class MarimoIslandPayload(TypedDict):+ schemaVersion: Literal[1]+ appId: str+ cells: list[MarimoIslandCellPayload]diff --git a/packages/pytest_changed/__init__.py b/packages/pytest_changed/__init__.pyindex 3bd8899267..d6bb10a82d 100644--- a/packages/pytest_changed/__init__.py+++ b/packages/pytest_changed/__init__.py@@ -118,7 +118,7 @@ def get_dependency_graph(# uv notes `analyze graph` is experimental,# so we fix the ruff version for now# Follow project's UV_EXCLUDE_NEWER setting to avoid resolution issues- "[email protected]",+ "[email protected]","analyze","graph","--detect-string-imports",diff --git a/tests/_islands/snapshots/html-payload.txt b/tests/_islands/snapshots/html-payload.txtnew file mode 100644index 0000000000..2fca31dd75--- /dev/null+++ b/tests/_islands/snapshots/html-payload.txt@@ -0,0 +1,81 @@+<!doctype html>+ <html lang="en">+ <head>+ <meta charset="UTF-8" />+ <title> main </title>+ <script type="module" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/main.js"></script>+<link+ href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/style.css"+ rel="stylesheet"+ title="marimo-islands"+ crossorigin="anonymous"+/>+<link rel="preconnect" href="https://fonts.googleapis.com" />+<link+ rel="preconnect"+ href="https://fonts.gstatic.com"+ crossorigin+/>+<link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap" rel="stylesheet" />+<link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"+ integrity="sha384-wcIxkf4k558AjM3Yz3BBFQUbk/zgIYC2R0QpeeYb+TwlBVMrlgLqwRjRtGZiK7ww"+ crossorigin="anonymous"+/>+<marimo-filename hidden></marimo-filename>+ </head>+ <body>+ <div style="margin: auto; max-width: 740px;">+ <marimo-island+ data-app-id="main"+ data-cell-id="bkHC"+ data-reactive="false"+ >+ <marimo-cell-output>++<div class="marimo">+ <div class="flex flex-col flex-1 items-center justify-center">+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1"+ stroke-linecap="round"+ stroke-linejoin="round"+ class="size-20 animate-spin text-primary"+ >+ <path d="M21 12a9 9 0 1 1-6.219-8.56"></path>+ </svg>+ <div>Initializing...</div>+ </div>+</div>++ </marimo-cell-output>+ <marimo-cell-code hidden></marimo-cell-code>+ </marimo-island>+<marimo-island+ data-app-id="main"+ data-cell-id="Hbol"+ data-reactive="true"+>+ <marimo-cell-output>+ </marimo-cell-output>+ <marimo-cell-code hidden>import%20marimo%20as%20mo</marimo-cell-code>+</marimo-island>+<marimo-island+ data-app-id="main"+ data-cell-id="MJUe"+ data-reactive="true"+>+ <marimo-cell-output>+ </marimo-cell-output>+ <marimo-cell-code hidden>mo.md('Hello%2C%20HTML!')</marimo-cell-code>+</marimo-island>+<script type="application/vnd.marimo.islands+json">{"appId": "main", "cells": [{"cellId": "Hbol", "code": "import marimo as mo", "displayCode": false, "displayOutput": true, "outputHtml": "", "outputMimetype": "text/plain", "reactive": true}, {"cellId": "MJUe", "code": "mo.md('Hello, HTML!')", "displayCode": false, "displayOutput": true, "outputHtml": "", "outputMimetype": "text/plain", "reactive": true}], "schemaVersion": 1}</script>+ </div>+ </body>+ </html>\ No newline at end of filediff --git a/tests/_islands/test_island_generator.py b/tests/_islands/test_island_generator.pyindex c4ab31b411..fb78650517 100644--- a/tests/_islands/test_island_generator.py+++ b/tests/_islands/test_island_generator.py@@ -1,14 +1,16 @@from __future__ import annotations+import jsonfrom typing import TYPE_CHECKING, get_type_hintsimport pytestfrom marimo import __version__from marimo._ast.app_config import _AppConfig-from marimo._islands._island_generator import (- MarimoIslandGenerator,-)+from marimo._islands._island_generator import MarimoIslandGenerator+from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.errors import MarimoExceptionRaisedError+from marimo._schemas.islands import ISLANDS_JSON_SCRIPT_TYPEfrom marimo._schemas.serialization import (AppInstantiation,CellDef,@@ -35,6 +37,22 @@ def _notebook()+def _parse_payload_script(script: str) -> dict[str, object]:+ prefix = f'<script type="{ISLANDS_JSON_SCRIPT_TYPE}">'+ suffix = "</script>"+ assert script.startswith(prefix)+ assert script.endswith(suffix)+ return json.loads(script[len(prefix) : -len(suffix)])+++def _parse_payload_from_body(body: str) -> dict[str, object]:+ prefix = f'<script type="{ISLANDS_JSON_SCRIPT_TYPE}">'+ suffix = "</script>"+ start = body.index(prefix)+ end = body.index(suffix, start) + len(suffix)+ return _parse_payload_script(body[start:end])++def test_add_code():generator = MarimoIslandGenerator()generator.add_code("print('Hello, World!')")@@ -95,6 +113,158 @@ async def test_render():)+async def test_render_payload():+ generator = MarimoIslandGenerator()+ generator.add_code("import marimo as mo")+ generator.add_code("mo.md('Payload output')")++ await generator.build()++ payload = generator.render_payload()++ assert payload["schemaVersion"] == 1+ assert payload["appId"] == "main"+ assert len(payload["cells"]) == 2+ assert payload["cells"][0] == {+ "cellId": str(generator._stubs[0]._cell_id),+ "code": "import marimo as mo",+ "outputHtml": "<span></span>",+ "outputMimetype": "text/plain",+ "reactive": True,+ "displayCode": False,+ "displayOutput": True,+ }+ assert payload["cells"][1]["cellId"] == str(generator._stubs[1]._cell_id)+ assert payload["cells"][1]["code"] == "mo.md('Payload output')"+ assert "Payload output" in payload["cells"][1]["outputHtml"]+ assert payload["cells"][1]["outputMimetype"] == "text/markdown"+ assert payload["cells"][1]["reactive"] is True+++def test_render_payload_preserves_error_output_mimetype():+ generator = MarimoIslandGenerator()+ stub = generator.add_code("0 / 0")+ stub._output = CellOutput.errors(+ [+ MarimoExceptionRaisedError(+ msg="division by zero",+ exception_type="ZeroDivisionError",+ raising_cell=None,+ )+ ]+ )++ payload = generator.render_payload()++ assert (+ payload["cells"][0]["outputMimetype"] == "application/vnd.marimo+error"+ )+ assert "application/vnd.marimo+error" in payload["cells"][0]["outputHtml"]+++def test_render_payload_script_escapes_json():+ generator = MarimoIslandGenerator()+ generator.add_code('value = "</script><div>&"')++ script = generator.render_payload_script()+ payload = _parse_payload_script(script)++ assert "</script><div>" not in script+ assert payload["cells"][0]["code"] == 'value = "</script><div>&"'+++def test_render_payload_script_escapes_output_html():+ generator = MarimoIslandGenerator()+ stub = generator.add_code("x = 1")+ stub._output = CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/html",+ data="</script><div>&",+ )++ script = generator.render_payload_script()+ payload = _parse_payload_script(script)++ assert "</script><div>" not in script+ assert payload["cells"][0]["outputHtml"] == "</script><div>&"+++def test_render_body_omits_payload_by_default():+ generator = MarimoIslandGenerator()+ generator.add_code("import marimo as mo")++ body = generator.render_body()++ assert ISLANDS_JSON_SCRIPT_TYPE not in body+++def test_render_body_can_include_payload():+ generator = MarimoIslandGenerator()+ generator.add_code("import marimo as mo")++ body = generator.render_body(include_payload=True)+ payload = _parse_payload_from_body(body)++ assert f'<script type="{ISLANDS_JSON_SCRIPT_TYPE}">' in body+ assert payload["schemaVersion"] == 1+ assert payload["appId"] == "main"+ assert payload["cells"][0]["code"] == "import marimo as mo"+++def test_render_body_can_omit_payload():+ generator = MarimoIslandGenerator()+ generator.add_code("import marimo as mo")++ body = generator.render_body(include_payload=False)++ assert ISLANDS_JSON_SCRIPT_TYPE not in body+++def test_render_html_can_omit_payload():+ generator = MarimoIslandGenerator()+ generator.add_code("import marimo as mo")++ html = generator.render_html(include_payload=False)++ assert ISLANDS_JSON_SCRIPT_TYPE not in html+++def test_render_payload_uses_configured_reactive_option():+ generator = MarimoIslandGenerator()+ stub = generator.add_code("x = 1", is_reactive=False)++ stub.render(is_reactive=True)++ payload = generator.render_payload()+ assert payload["cells"][0] == {+ "cellId": str(stub._cell_id),+ "code": "",+ "outputHtml": "",+ "outputMimetype": "text/plain",+ "reactive": False,+ "displayCode": False,+ "displayOutput": True,+ }+++async def test_render_payload_uses_configured_display_option():+ generator = MarimoIslandGenerator()+ stub = generator.add_code(+ """+ import marimo as mo+ mo.md("Hidden output")+ """,+ display_output=False,+ )+ await generator.build()++ stub.render(display_output=True)++ payload = generator.render_payload()+ assert payload["cells"][0]["outputHtml"] == ""+ assert payload["cells"][0]["displayOutput"] is False++async def test_render_multiline_markdown():generator = MarimoIslandGenerator()stub = generator.add_code(@@ -549,6 +719,12 @@ async def test_render_html():assert "<body>" in htmlassert "Hello%2C%20HTML!" in htmlsnapshot("html.txt", html.replace(__version__, "0.0.0"))+ snapshot(+ "html-payload.txt",+ generator.render_html(include_payload=True).replace(+ __version__, "0.0.0"+ ),+ )def test_app_config():