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.

fix(islands): retain static output through initial hydration (#10298)

Péter Gyarmatie17dd29d2405
diff --git a/frontend/src/core/islands/__tests__/bootstrap.test.ts b/frontend/src/core/islands/__tests__/bootstrap.test.ts
new file mode 100644
index 0000000000..fb21cf3f2f
--- /dev/null
+++ b/frontend/src/core/islands/__tests__/bootstrap.test.ts
@@ -0,0 +1,61 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { createStore } from "jotai";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { RuntimeState } from "@/core/kernel/RuntimeState";
+import { initializeIslands } from "../bootstrap";
+import type { IslandsPyodideBridge } from "../bridge";
+import { islandsHydratedAtom, islandsPendingInitialRunsAtom } from "../state";
+import type { IslandsKernelMessage } from "../worker/worker";
+
+function completedRun(sessionGeneration: number): IslandsKernelMessage {
+ return {
+ sessionGeneration,
+ message: JSON.stringify({
+ op: "completed-run",
+ data: { op: "completed-run", run_id: null },
+ }) as IslandsKernelMessage["message"],
+ };
+}
+
+describe("initializeIslands", () => {
+ afterEach(vi.restoreAllMocks);
+
+ it("waits for each initial session to complete", async () => {
+ const root = document.createElement("div");
+ root.innerHTML =
+ '<marimo-island data-app-id="app-1" data-reactive="true"></marimo-island>';
+
+ let consumeMessage: ((message: IslandsKernelMessage) => void) | undefined;
+ const bridge = {
+ consumeMessages: (consumer: (message: IslandsKernelMessage) => void) => {
+ consumeMessage = consumer;
+ },
+ sendComponentValues: vi.fn(),
+ } as unknown as IslandsPyodideBridge;
+ const store = createStore();
+ vi.spyOn(RuntimeState.INSTANCE, "start").mockImplementation(
+ () => undefined,
+ );
+
+ await initializeIslands({
+ bridge,
+ store,
+ root,
+ autoInitializePlugins: false,
+ });
+
+ expect(store.get(islandsHydratedAtom)).toBe(false);
+ store.set(islandsPendingInitialRunsAtom, new Set([1, 2]));
+
+ consumeMessage?.(completedRun(1));
+ expect(store.get(islandsHydratedAtom)).toBe(false);
+
+ consumeMessage?.(completedRun(1));
+ consumeMessage?.(completedRun(0));
+ expect(store.get(islandsHydratedAtom)).toBe(false);
+
+ consumeMessage?.(completedRun(2));
+ expect(store.get(islandsHydratedAtom)).toBe(true);
+ });
+});
diff --git a/frontend/src/core/islands/__tests__/bridge.test.ts b/frontend/src/core/islands/__tests__/bridge.test.ts
index 4115c0ee01..b6d42162a4 100644
--- a/frontend/src/core/islands/__tests__/bridge.test.ts
+++ b/frontend/src/core/islands/__tests__/bridge.test.ts
@@ -8,6 +8,8 @@ import {
uiElementId,
widgetModelId,
} from "@/__tests__/branded";
+import { notebookAtom } from "@/core/cells/cells";
+import { islandsPendingInitialRunsAtom } from "@/core/islands/state";
type Base64String = components["schemas"]["Base64String"];
interface TestIslandApp {
@@ -61,7 +63,12 @@ const {
mockStartSessionRequest: vi.fn(),
mockMessageListeners: new Map<string, (payload: never) => void>(),
mockStoreSet: vi.fn(),
- mockParseMarimoIslandApps: vi.fn<() => TestIslandApp[]>(() => []),
+ mockParseMarimoIslandApps: vi.fn<
+ (
+ root?: Document | Element,
+ options?: { materialize?: boolean },
+ ) => TestIslandApp[]
+ >(() => []),
mockCreateMarimoFile: vi.fn(),
mockGetMarimoExportContext: vi.fn<() => TestExportContext | undefined>(
() => undefined,
@@ -235,6 +242,10 @@ describe("IslandsPyodideBridge", () => {
code: "generated app 2",
sessionGeneration: 2,
});
+ expect(mockStoreSet).toHaveBeenCalledWith(
+ islandsPendingInitialRunsAtom,
+ new Set([1, 2]),
+ );
await sendSlider();
await bridge.stopSession();
@@ -309,7 +320,17 @@ describe("IslandsPyodideBridge", () => {
sessionGeneration: 1,
}),
);
+ const events: string[] = [];
mockCreateMarimoFile.mockReturnValue("generated app 2");
+ mockParseMarimoIslandApps.mockImplementation((_root, options) => {
+ events.push(options?.materialize === false ? "inspect" : "materialize");
+ return [app()];
+ });
+ mockStoreSet.mockImplementation((target) => {
+ if (target === islandsPendingInitialRunsAtom) {
+ events.push("reset");
+ }
+ });
await bridge.initializeApps();
expect(mockReplaceSessionRequest).toHaveBeenCalledOnce();
@@ -318,12 +339,17 @@ describe("IslandsPyodideBridge", () => {
code: "generated app 2",
sessionGeneration: 2,
});
- expect(mockStoreSet).toHaveBeenCalledOnce();
+ expect(mockStoreSet).toHaveBeenCalledWith(
+ islandsPendingInitialRunsAtom,
+ new Set([2]),
+ );
+ expect(events).toEqual(["inspect", "reset", "materialize"]);
});
it("stops the matching active app", async () => {
mockSingleApp();
await bridge.initializeApps();
+ mockStoreSet.mockClear();
await bridge.stopSession("other-app");
await bridge.stopSession("app-1");
@@ -333,6 +359,11 @@ describe("IslandsPyodideBridge", () => {
appId: "app-1",
sessionGeneration: 1,
});
+ expect(mockStoreSet.mock.calls[0]).toEqual([
+ islandsPendingInitialRunsAtom,
+ null,
+ ]);
+ expect(mockStoreSet.mock.calls[1]?.[0]).toBe(notebookAtom);
mockBridge.mockClear();
const control = sendSlider();
diff --git a/frontend/src/core/islands/bootstrap.ts b/frontend/src/core/islands/bootstrap.ts
index f132080665..6dc2e6aa01 100644
--- a/frontend/src/core/islands/bootstrap.ts
+++ b/frontend/src/core/islands/bootstrap.ts
@@ -42,6 +42,7 @@ import { store as defaultStore } from "../state/jotai";
import type { IslandsPyodideBridge } from "./bridge";
import { MarimoIslandElement } from "./components/web-components";
import {
+ islandsPendingInitialRunsAtom,
shouldShowIslandsWarningIndicatorAtom,
userTriedToInteractWithIslandsAtom,
} from "./state";
@@ -74,6 +75,7 @@ export async function initializeIslands(
// Setup networking
store.set(requestClientAtom, bridge);
store.set(initialModeAtom, "read");
+ store.set(islandsPendingInitialRunsAtom, null);
// Initialize plugins for rendering static HTML
if (config.autoInitializePlugins !== false) {
@@ -129,10 +131,13 @@ export async function initializeIslands(
// the envelope and the payload carry the op. The bridge types the message
// as NotificationPayload (just {data}), but the actual wire format
// includes the outer op too.
- bridge.consumeMessages((message) => {
+ // Worker metadata identifies the session that emitted the message.
+ bridge.consumeMessages(({ message, sessionGeneration }) => {
handleMessage(
message as unknown as JsonString<IslandsNotificationMessage>,
actions,
+ store,
+ sessionGeneration,
);
});
@@ -161,9 +166,12 @@ type IslandsNotificationMessage = {
*
* Wire format from Python: {"op": "<name>", "data": {"op": "<name>", ...}}
*/
+// oxlint-disable-next-line marimo/prefer-object-params
function handleMessage(
message: JsonString<IslandsNotificationMessage>,
actions: NotebookActions,
+ store: Store,
+ sessionGeneration: number,
): void {
try {
const msg = jsonParseWithSpecialChar(message);
@@ -192,7 +200,6 @@ function handleMessage(
case "storage-download-ready":
case "secret-keys-result":
case "startup-logs":
- case "completed-run":
case "interrupted":
case "reconnected":
case "cache-cleared":
@@ -201,6 +208,17 @@ function handleMessage(
case "notebook-document-transaction":
return;
+ case "completed-run":
+ store.set(islandsPendingInitialRunsAtom, (pending) => {
+ if (!pending?.has(sessionGeneration)) {
+ return pending;
+ }
+ const next = new Set(pending);
+ next.delete(sessionGeneration);
+ return next;
+ });
+ return;
+
case "kernel-ready":
handleKernelReady(msg.data, {
autoInstantiate: true,
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index c2d06367b5..2bfe8de5df 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -4,17 +4,16 @@
import { getWorkerRPC } from "@/core/wasm/rpc";
import { Deferred } from "@/utils/Deferred";
import { throwNotImplemented } from "@/utils/functions";
-import type { JsonString } from "@/utils/json/base64";
import { Logger } from "@/utils/Logger";
import { generateUUID } from "@/utils/uuid";
import { initialNotebookState, notebookAtom } from "../cells/cells";
-import type { CommandMessage, NotificationPayload } from "../kernel/messages";
+import type { CommandMessage } from "../kernel/messages";
import type { EditRequests, RunRequests } from "../network/types";
import { store as defaultStore } from "../state/jotai";
import { getMarimoExportContext } from "../static/export-context";
import { createMarimoFile, parseMarimoIslandApps } from "./parse";
-import { islandsInitializedAtom } from "./state";
-import type { WorkerSchema } from "./worker/worker";
+import { islandsInitializedAtom, islandsPendingInitialRunsAtom } from "./state";
+import type { IslandsKernelMessage, WorkerSchema } from "./worker/worker";
import type { WorkerFactory } from "./worker-factory";
import { DefaultWorkerFactory } from "./worker-factory";
@@ -60,7 +59,7 @@ interface AppSession {
export class IslandsPyodideBridge implements RunRequests, EditRequests {
private rpc: ReturnType<typeof getWorkerRPC<WorkerSchema>>;
private messageConsumer:
- | ((message: JsonString<NotificationPayload>) => void)
+ | ((message: IslandsKernelMessage) => void)
| undefined;
private readonly store: typeof defaultStore;
private readonly root: Document | Element;
@@ -110,12 +109,9 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
},
);
- this.rpc.addMessageListener(
- "kernelMessage",
- ({ message }: { message: JsonString<NotificationPayload> }) => {
- this.messageConsumer?.(message);
- },
- );
+ this.rpc.addMessageListener("kernelMessage", (message) => {
+ this.messageConsumer?.(message);
+ });
}
async initializeApps(): Promise<void> {
@@ -126,7 +122,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
}
private async startApps(): Promise<void> {
- const apps = parseMarimoIslandApps(this.root);
+ const apps = parseMarimoIslandApps(this.root, { materialize: false });
const managesSingleApp = apps.length === 1;
Logger.debug(
`Starting sessions for ${apps.length} app(s):`,
@@ -140,15 +136,27 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
? getMarimoExportContext()
: undefined;
const notebookCode = exportContext?.notebookCode;
+ const singleApp = managesSingleApp ? apps[0] : undefined;
+ const singleAppFile = singleApp
+ ? notebookCode || createMarimoFile(singleApp)
+ : undefined;
+ if (
+ singleApp &&
+ this.session?.appId === singleApp.id &&
+ this.session.code === singleAppFile
+ ) {
+ parseMarimoIslandApps(this.root);
+ return;
+ }
+ if (apps.length > 0) {
+ this.store.set(
+ islandsPendingInitialRunsAtom,
+ new Set(apps.map((_, index) => this.nextSessionGeneration + index + 1)),
+ );
+ }
+ parseMarimoIslandApps(this.root);
for (const app of apps) {
- const file = notebookCode || createMarimoFile(app);
- if (
- managesSingleApp &&
- this.session?.appId === app.id &&
- this.session.code === file
- ) {
- return;
- }
+ const file = singleAppFile || createMarimoFile(app);
Logger.debug(`App ${app.id} marimo file:\n`, file);
const request = {
code: file,
@@ -199,6 +207,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
appId: session.appId,
sessionGeneration: session.sessionGeneration,
});
+ this.store.set(islandsPendingInitialRunsAtom, null);
this.session = undefined;
this.sessionReady = new Deferred<AppSession>();
this.store.set(notebookAtom, initialNotebookState());
@@ -225,9 +234,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
/**
* Sets up a consumer for kernel messages
*/
- consumeMessages(
- consumer: (message: JsonString<NotificationPayload>) => void,
- ): void {
+ consumeMessages(consumer: (message: IslandsKernelMessage) => void): void {
this.messageConsumer = consumer;
this.rpc.proxy.send.consumerReady({});
}
diff --git a/frontend/src/core/islands/components/__tests__/web-components.test.tsx b/frontend/src/core/islands/components/__tests__/web-components.test.tsx
index 68895dd3fb..9c50b53ce2 100644
--- a/frontend/src/core/islands/components/__tests__/web-components.test.tsx
+++ b/frontend/src/core/islands/components/__tests__/web-components.test.tsx
@@ -19,6 +19,7 @@ import {
ISLAND_TAG_NAMES,
ISLANDS_JSON_SCRIPT_TYPE,
} from "@/core/islands/constants";
+import { islandsPendingInitialRunsAtom } from "@/core/islands/state";
import { requestClientAtom } from "@/core/network/requests";
import { store } from "@/core/state/jotai";
import { parseMarimoIslandApps } from "../../parse";
@@ -37,6 +38,7 @@ afterAll(() => {
beforeEach(() => {
store.set(notebookAtom, MockNotebook.notebookState({ cellData: {} }));
+ store.set(islandsPendingInitialRunsAtom, new Set());
store.set(requestClientAtom, MockRequestClient.create());
});
@@ -46,6 +48,38 @@ afterEach(async () => {
});
describe("MarimoIslandElement lifecycle", () => {
+ it("keeps static output until the initial run completes", async () => {
+ store.set(islandsPendingInitialRunsAtom, new Set([1]));
+ setNotebook("runtime-cell", "runtime output");
+ const container = document.createElement("div");
+ container.innerHTML = `
+ <marimo-island
+ data-app-id="app-1"
+ data-cell-id="runtime-cell"
+ data-cell-idx="0"
+ data-reactive="true"
+ >
+ <marimo-cell-output><div>static output</div></marimo-cell-output>
+ <marimo-cell-code hidden>${encodeURIComponent("value = 1")}</marimo-cell-code>
+ </marimo-island>
+ `;
+
+ await actAndFlush(() => document.body.append(container));
+
+ const island = container.querySelector<HTMLElement>(
+ ISLAND_TAG_NAMES.ISLAND,
+ );
+ expect(island?.textContent).toContain("static output");
+ expect(island?.textContent).not.toContain("runtime output");
+
+ await actAndFlush(() => {
+ store.set(islandsPendingInitialRunsAtom, new Set());
+ });
+
+ expect(island?.textContent).toContain("runtime output");
+ expect(island?.textContent).not.toContain("static output");
+ });
+
it("binds a reactive island after its runtime cell index is materialized", async () => {
setNotebook("outgoing-cell", "outgoing runtime output");
const container = document.createElement("div");
diff --git a/frontend/src/core/islands/components/output-wrapper.tsx b/frontend/src/core/islands/components/output-wrapper.tsx
index d65fcfd67c..277252081c 100644
--- a/frontend/src/core/islands/components/output-wrapper.tsx
+++ b/frontend/src/core/islands/components/output-wrapper.tsx
@@ -15,6 +15,7 @@ import type { CellId } from "@/core/cells/ids";
import { isOutputEmpty } from "@/core/cells/outputs";
import type { CellRuntimeState } from "@/core/cells/types";
import { ISLAND_TAG_NAMES } from "../constants";
+import { islandsHydratedAtom } from "../state";
import { IslandControls } from "./IslandControls";
import { useIslandControls } from "./useIslandControls";
@@ -64,6 +65,7 @@ export const MarimoOutputWrapper: React.FC<MarimoOutputWrapperProps> = ({
[cellId],
);
const runtime = useAtomValue(selectAtom(notebookAtom, selector));
+ const isHydrated = useAtomValue(islandsHydratedAtom);
// Sync cell status to the host <marimo-island> element as a data attribute
// so downstream consumers can style based on status (e.g. [data-status="running"])
@@ -71,7 +73,8 @@ export const MarimoOutputWrapper: React.FC<MarimoOutputWrapperProps> = ({
useSyncStatusToIsland(wrapperRef, status);
// If no runtime yet, show static content
- if (!runtime?.output) {
+ // Keep static content mounted while the initial run is pending.
+ if (!isHydrated || !runtime?.output) {
return (
<div ref={wrapperRef} className="relative min-h-6 empty:hidden">
{children}
diff --git a/frontend/src/core/islands/state.ts b/frontend/src/core/islands/state.ts
index a683a2bb09..d19cc51d72 100644
--- a/frontend/src/core/islands/state.ts
+++ b/frontend/src/core/islands/state.ts
@@ -11,6 +11,15 @@ import { atom } from "jotai";
*/
export const islandsInitializedAtom = atom<boolean | string>(false);
+/** Pending initial session generations. Null waits for a session to start. */
+export const islandsPendingInitialRunsAtom = atom<ReadonlySet<number> | null>(
+ new Set<number>(),
+);
+
+export const islandsHydratedAtom = atom(
+ (get) => get(islandsPendingInitialRunsAtom)?.size === 0,
+);
+
/**
* Whether the user has tried to interact with the islands.
*/
diff --git a/frontend/src/core/islands/worker/worker.tsx b/frontend/src/core/islands/worker/worker.tsx
index f17668c6e6..ea0bec7954 100644
--- a/frontend/src/core/islands/worker/worker.tsx
+++ b/frontend/src/core/islands/worker/worker.tsx
@@ -45,11 +45,14 @@ async function loadPyodideAndPackages() {
}
const pyodideReadyPromise = loadPyodideAndPackages();
-const messageBuffer = new MessageBuffer(
- (message: JsonString<NotificationPayload>) => {
- rpc.send.kernelMessage({ message });
- },
-);
+export interface IslandsKernelMessage {
+ message: JsonString<NotificationPayload>;
+ sessionGeneration: number;
+}
+
+const messageBuffer = new MessageBuffer<IslandsKernelMessage>((payload) => {
+ rpc.send.kernelMessage(payload);
+});
interface SessionRequest {
code: string;
appId: string;
@@ -78,7 +81,12 @@ async function startSession(
});
const nextBridge = await self.controller.startSession({
...notebook,
- onMessage: messageBuffer.push,
+ onMessage: (message) => {
+ messageBuffer.push({
+ message,
+ sessionGeneration: opts.sessionGeneration,
+ });
+ },
});
if (activeSession) {
(nextBridge as unknown as PyProxy).destroy();
@@ -236,7 +244,7 @@ export type WorkerSchema = RPCSchema<
// Emitted when the worker is ready
ready: {};
// Emitted when the kernel sends a message
- kernelMessage: { message: JsonString<NotificationPayload> };
+ kernelMessage: IslandsKernelMessage;
// Emitted when the Pyodide is initialized
initialized: {};
// Emitted when the Pyodide fails to initialize
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 4d6907cbc7..6fcb306418 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -1,7 +1,9 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import { useAtomValue } from "jotai";
import { useEffect, useRef, useState } from "react";
import { z } from "zod";
+import { islandsHydratedAtom } from "@/core/islands/state";
import { createPlugin } from "@/plugins/core/builder";
import type { IPluginProps } from "@/plugins/types";
import { ErrorBanner } from "../common/error-banner";
@@ -46,8 +48,12 @@ const AnyWidgetSlot = (props: IPluginProps<ModelIdRef, Data>) => {
const { modelId } = props.data;
const htmlRef = useRef<HTMLDivElement>(null);
const [error, setError] = useState<Error>();
+ const canCreateView = useAtomValue(islandsHydratedAtom);
useEffect(() => {
+ if (!canCreateView) {
+ return;
+ }
const el = htmlRef.current;
if (!el) {
return;
@@ -64,7 +70,7 @@ const AnyWidgetSlot = (props: IPluginProps<ModelIdRef, Data>) => {
}
});
return () => controller.abort();
- }, [modelId]);
+ }, [canCreateView, modelId]);
return (
<>
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
index 3fe96e971c..2a46fad5e1 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { render, waitFor } from "@testing-library/react";
+import { act, render, waitFor } from "@testing-library/react";
+import { Provider, createStore } from "jotai";
import {
afterEach,
beforeEach,
@@ -10,6 +11,7 @@ import {
type MockInstance,
vi,
} from "vitest";
+import { islandsPendingInitialRunsAtom } from "@/core/islands/state";
import type { IPluginProps } from "@/plugins/types";
import { visibleForTesting } from "../AnyWidgetPlugin";
import { Model } from "../model";
@@ -88,6 +90,29 @@ describe("AnyWidgetSlot", () => {
});
});
+ it("waits for islands hydration before resolving the model", async () => {
+ const islandsStore = createStore();
+ islandsStore.set(islandsPendingInitialRunsAtom, new Set([1]));
+ const createViewSpy = vi.spyOn(WIDGET_REGISTRY, "createView");
+
+ render(
+ <Provider store={islandsStore}>
+ <AnyWidgetSlot {...props(modelId)} />
+ </Provider>,
+ );
+
+ expect(createViewSpy).not.toHaveBeenCalled();
+
+ act(() => {
+ islandsStore.set(islandsPendingInitialRunsAtom, new Set());
+ });
+
+ await waitFor(() => {
+ expect(createViewSpy).toHaveBeenCalledOnce();
+ });
+ createViewSpy.mockRestore();
+ });
+
it("aborts the runtime-owned view on unmount", async () => {
const { unmount } = render(<AnyWidgetSlot {...props(modelId)} />);
await waitFor(() => {