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
Initialize cells from the host document (#11532)
Trevor Manze7049767e931
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 9105763b81..899091bba4 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -7,6 +7,7 @@ import { createStore } from "jotai";import {afterAll,beforeAll,+ afterEach,beforeEach,describe,expect,@@ -3591,31 +3592,9 @@ describe("createTracebackInfoAtom", () => {});});-describe("setCells snapshot preservation", () => {+describe("kernel-ready", () => {const CELL_A = cellId("A");const CELL_B = cellId("B");- const newCells: CellData[] = [- {- id: CELL_A,- name: "a",- code: "1",- edited: false,- lastCodeRun: null,- lastExecutionTime: null,- config: { hide_code: false, disabled: false, column: null },- serializedEditorState: null,- },- {- id: CELL_B,- name: "b",- code: "2",- edited: false,- lastCodeRun: null,- lastExecutionTime: null,- config: { hide_code: false, disabled: false, column: null },- serializedEditorState: null,- },- ];const hydratedState = () =>MockNotebook.notebookState({@@ -3645,44 +3624,97 @@ describe("setCells snapshot preservation", () => {},});- beforeEach(async () => {- const { isWasm } = await import("@/core/wasm/utils");- vi.mocked(isWasm).mockReturnValue(true);+ it("setLastRun records what the kernel last ran", () => {+ const state = hydratedState();+ const next = exportedForTesting.reducer(state, {+ type: "setLastRun",+ payload: {+ lastCodeRun: { [CELL_A]: "0" },+ lastExecutionTime: { [CELL_A]: 5 },+ },+ });++ expect(next.cellData[CELL_A]).toMatchObject({+ lastCodeRun: "0",+ lastExecutionTime: 5,+ edited: true,+ });+ expect(next.cellData[CELL_B]).toMatchObject({+ lastCodeRun: null,+ lastExecutionTime: null,+ edited: false,+ });+ expect(next.cellRuntime).toBe(state.cellRuntime);});- it("preserves hydrated output in WASM", () => {+ it("resetCellRuntimes starts every cell's runtime over", () => {const next = exportedForTesting.reducer(hydratedState(), {- type: "setCells",- payload: newCells,+ type: "resetCellRuntimes",+ payload: undefined,});- expect(next.cellRuntime[CELL_A].output).toMatchObject({- data: "hydrated-A",+ expect(next.cellRuntime[CELL_A].output).toBeNull();+ expect(next.cellRuntime[CELL_B].consoleOutputs).toEqual([]);+ });++ it("resetCellRuntimes starts the scratch cell over too", () => {+ const state = MockNotebook.notebookState({+ cellData: { [CELL_A]: { id: CELL_A, code: "1" } },+ cellRuntime: {+ [SCRATCH_CELL_ID]: {+ output: {+ channel: "output",+ mimetype: "text/plain",+ data: "scratch",+ timestamp: 0,+ },+ },+ },+ });+ const next = exportedForTesting.reducer(state, {+ type: "resetCellRuntimes",+ payload: undefined,});++ expect(next.cellRuntime[SCRATCH_CELL_ID].output).toBeNull();});- it("preserves console-only hydration in WASM", () => {- const next = exportedForTesting.reducer(hydratedState(), {- type: "setCells",- payload: newCells,+ describe("resetCellRuntimes in WASM", () => {+ beforeEach(async () => {+ const { isWasm } = await import("@/core/wasm/utils");+ vi.mocked(isWasm).mockReturnValue(true);});- expect(next.cellRuntime[CELL_B].consoleOutputs).toHaveLength(1);- expect(next.cellRuntime[CELL_B].consoleOutputs[0]).toMatchObject({- data: "hydrated-B-stdout",+ afterEach(async () => {+ const { isWasm } = await import("@/core/wasm/utils");+ vi.mocked(isWasm).mockReturnValue(false);});- });- it("resets cells with no prior runtime even in WASM", () => {- const empty = MockNotebook.notebookState({ cellData: {} });- const next = exportedForTesting.reducer(empty, {- type: "setCells",- payload: newCells,+ it("keeps hydrated outputs and console", () => {+ const next = exportedForTesting.reducer(hydratedState(), {+ type: "resetCellRuntimes",+ payload: undefined,+ });++ expect(next.cellRuntime[CELL_A].output).toMatchObject({+ data: "hydrated-A",+ });+ expect(next.cellRuntime[CELL_B].consoleOutputs[0]).toMatchObject({+ data: "hydrated-B-stdout",+ });});- expect(next.cellRuntime[CELL_A].output).toBeNull();- expect(next.cellRuntime[CELL_A].consoleOutputs).toEqual([]);- expect(next.cellRuntime[CELL_B].output).toBeNull();- expect(next.cellRuntime[CELL_B].consoleOutputs).toEqual([]);+ it("starts cells with no prior runtime over", () => {+ const state = MockNotebook.notebookState({+ cellData: { [CELL_A]: { id: CELL_A, code: "1" } },+ });+ const next = exportedForTesting.reducer(state, {+ type: "resetCellRuntimes",+ payload: undefined,+ });++ expect(next.cellRuntime[CELL_A].output).toBeNull();+ expect(next.cellRuntime[CELL_A].consoleOutputs).toEqual([]);+ });});});diff --git a/frontend/src/core/cells/__tests__/document.test.ts b/frontend/src/core/cells/__tests__/document.test.tsindex b60d3513dd..0b77940d24 100644--- a/frontend/src/core/cells/__tests__/document.test.ts+++ b/frontend/src/core/cells/__tests__/document.test.ts@@ -29,7 +29,12 @@ import {type NotebookState,notebookReducer,} from "../cells";-import { applyDocument, flushDocument, withDocumentSave } from "../document";+import {+ applyDocument,+ flushDocument,+ followDocument,+ withDocumentSave,+} from "../document";import { type CellId, SCRATCH_CELL_ID } from "../ids";vi.mock("../../rtc/state", async (importOriginal) => ({@@ -349,9 +354,14 @@ describe("documentEditMiddleware", () => {expect(calls).toEqual([["updateConfig", c, { column: null }]]);});- it("ignores the kernel's cells and runtime state", () => {+ it("ignores the document and the kernel's run state", () => {actions.prepareForRun({ cellId: a });- actions.setCells([state.cellData[a]]);+ actions.setLastRun({+ lastCodeRun: { [a]: "a = 0" },+ lastExecutionTime: {},+ });+ actions.resetCellRuntimes();+ actions.reconcileDocument(documentOf([cell(a)]));expect(calls).toEqual([]);});@@ -367,6 +377,30 @@ describe("documentEditMiddleware", () => {});});+describe("followDocument", () => {+ it("reconciles the document now and on each change, until aborted", () => {+ const documentAtom = atom<EditableDocument | null>(null);+ const reconcile = vi.fn();+ const controller = new AbortController();++ followDocument({+ store,+ model: { documentAtom },+ reconcile,+ signal: controller.signal,+ });+ expect(reconcile).not.toHaveBeenCalled();++ const first = documentOf([cell(a)]);+ store.set(documentAtom, first);+ expect(reconcile).toHaveBeenCalledWith(first);++ controller.abort();+ store.set(documentAtom, documentOf([cell(b)]));+ expect(reconcile).toHaveBeenCalledOnce();+ });+});+describe("flushing before host commands", () => {const model = {syncStatusAtom: atom<DocumentSyncStatus>({ status: "idle" }),diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 32af48af27..cdd2702f37 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -44,6 +44,7 @@ import {createCell,createCellConfig,createCellRuntimeState,+ isEdited,} from "./types";import {canUndoDeletes,@@ -936,12 +937,7 @@ const {cellLogs: [...state.cellLogs, ...action.logs],};},- /**- * Follow the host document's cells and order.- *- * Dispatched without middleware, since the document already has these- * changes.- */+ /** Follow the host document's cells and order. */reconcileDocument: (state, document: EditableDocument) => {const nextState = applyDocument(state, document);for (const cellId of state.cellIds.inOrderIds) {@@ -985,36 +981,44 @@ const {},});},- setCells: (state, cells: CellData[]) => {- const cellData = Object.fromEntries(cells.map((cell) => [cell.id, cell]));-- // WASM has no server-side SessionView to replay outputs, so the- // snapshot hydrated by notebookStateFromSession is the only source.+ /** Record what the kernel last ran for each cell. */+ setLastRun: (+ state,+ action: {+ lastCodeRun: Record<CellId, string>;+ lastExecutionTime: Record<CellId, number>;+ },+ ) => {+ const cellData = { ...state.cellData };+ for (const cellId of state.cellIds.inOrderIds) {+ const cell = state.cellData[cellId];+ const lastCodeRun = action.lastCodeRun[cellId] ?? null;+ cellData[cellId] = {+ ...cell,+ lastCodeRun,+ lastExecutionTime: action.lastExecutionTime[cellId] ?? null,+ // A cell the kernel never ran is not stale on load.+ edited: lastCodeRun !== null && isEdited(lastCodeRun, cell.code),+ };+ }+ return { ...state, cellData };+ },+ /**+ * Start each cell's runtime over for a new kernel. WASM keeps the outputs+ * its mount-time snapshot gave it.+ */+ resetCellRuntimes: (state) => {const preserveSnapshot = isWasm();- const runtimeFor = (cellId: CellId): CellRuntimeState => {- if (!preserveSnapshot) {- return createCellRuntimeState();- }- const prev = state.cellRuntime[cellId];+ const cellRuntime = { ...state.cellRuntime };+ for (const cellId of [...state.cellIds.inOrderIds, SCRATCH_CELL_ID]) {+ const previous = state.cellRuntime[cellId];const hasSnapshot =- prev && (prev.output != null || prev.consoleOutputs.length > 0);- return hasSnapshot ? prev : createCellRuntimeState();- };- const cellRuntime = Object.fromEntries(- cells.map((cell) => [cell.id, runtimeFor(cell.id)]),- );-- return withScratchCell({- ...state,- cellIds: MultiColumn.fromIdsAndColumns(- cells.map((cell) => [cell.id, cell.config.column]),- ),- cellData: cellData,- cellRuntime: cellRuntime,- cellHandles: Object.fromEntries(- cells.map((cell) => [cell.id, createRef()]),- ),- });+ preserveSnapshot &&+ previous !== undefined &&+ (previous.output != null || previous.consoleOutputs.length > 0);+ cellRuntime[cellId] = hasSnapshot ? previous : createCellRuntimeState();+ }+ return { ...state, cellRuntime };},/*** Move focus to next celldiff --git a/frontend/src/core/cells/document.ts b/frontend/src/core/cells/document.tsindex c8b5eb20f1..e0fe29cca5 100644--- a/frontend/src/core/cells/document.ts+++ b/frontend/src/core/cells/document.ts@@ -10,11 +10,13 @@import type * as Protocol from "@marimo-team/client/protocol";import { dequal as isEqual } from "dequal";+import type { createStore } from "jotai";import { createRef, type RefObject } from "react";import type { CellHandle } from "@/components/editor/notebook-cell";import type {DocumentEdit,DocumentEditor,+ DocumentModel,EditableCell,EditableDocument,} from "@/core/notebook/document";@@ -165,6 +167,33 @@ export function applyDocument(return { ...state, cellIds, cellData, cellRuntime, cellHandles };}+/**+ * Reconcile the model's document now and on each change, until the signal aborts.+ *+ * TODO(MO-8028): Delete with `applyDocument`.+ */+export function followDocument({+ store,+ model,+ reconcile,+ signal,+}: {+ store: ReturnType<typeof createStore>;+ model: Pick<DocumentModel, "documentAtom">;+ reconcile: (document: EditableDocument) => void;+ signal: AbortSignal;+}): void {+ const follow = () => {+ const document = store.get(model.documentAtom);+ if (document !== null) {+ reconcile(document);+ }+ };+ const unsubscribe = store.sub(model.documentAtom, follow);+ signal.addEventListener("abort", unsubscribe, { once: true });+ follow();+}+// Editing the document ------------------------------------------------------const CONFIG_FIELDS = ["disabled", "hide_code", "expand_output"] as const;@@ -291,8 +320,8 @@ export function documentEditMiddleware(next: NotebookState,action: CellAction,): void {- // The kernel's cells replace the notebook rather than edit it.- if (action.type === "setCells") {+ // The document replaces the notebook's cells, so following it is no edit.+ if (action.type === "reconcileDocument") {return;}if (prev.cellIds === next.cellIds && prev.cellData === next.cellData) {diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsxindex 96005720af..780d0d9e87 100644--- a/frontend/src/core/edit-app.tsx+++ b/frontend/src/core/edit-app.tsx@@ -5,7 +5,7 @@ import { Tooltip } from "radix-ui";const TooltipProvider = Tooltip.Provider;-import { useAtomValue, useSetAtom } from "jotai";+import { useAtomValue, useSetAtom, useStore } from "jotai";import { useEffect } from "react";import { NotStartedConnectionAlert } from "@/components/editor/alerts/connecting-alert";import { Controls } from "@/components/editor/controls/Controls";@@ -29,10 +29,12 @@ import { CellsRenderer } from "../components/editor/renderers/cells-renderer";import { useHotkey } from "../hooks/useHotkey";import {hasCellsAtom,+ notebookAtom,notebookIsRunningAtom,numColumnsAtom,useCellActions,} from "./cells/cells";+import { notebookCells } from "./cells/utils";import type { AppConfig, UserConfig } from "./config/config-schema";import { DocumentProvider } from "./notebook/document";import { RuntimeState } from "./kernel/RuntimeState";@@ -64,8 +66,9 @@ export const EditApp: React.FC<AppProps> = ({appConfig,hideControls = false,}) => {- const { setCells, mergeAllColumns, collapseAllCells, expandAllCells } =+ const { mergeAllColumns, collapseAllCells, expandAllCells } =useCellActions();+ const store = useStore();const viewState = useAtomValue(viewStateAtom);const numColumns = useAtomValue(numColumnsAtom);const filename = useFilename();@@ -86,8 +89,8 @@ export const EditApp: React.FC<AppProps> = ({const { connection, reconnect, documentModel } = useNotebookSession({autoInstantiate: userConfig.runtime.auto_instantiate,- setCells: (cells, layout) => {- setCells(cells);+ onKernelReady: (layout) => {+ const cells = notebookCells(store.get(notebookAtom));const names = cells.map((cell) => cell.name);const codes = cells.map((cell) => cell.code);const configs = cells.map((cell) => cell.config);diff --git a/frontend/src/core/islands/__tests__/bootstrap.test.ts b/frontend/src/core/islands/__tests__/bootstrap.test.tsindex 8eae7a0b01..cf4f02849b 100644--- a/frontend/src/core/islands/__tests__/bootstrap.test.ts+++ b/frontend/src/core/islands/__tests__/bootstrap.test.ts@@ -1,7 +1,14 @@/* Copyright 2026 Marimo. All rights reserved. */+import type { NotebookTransport } from "@marimo-team/client";import { createStore } from "jotai";import { afterEach, describe, expect, it, vi } from "vitest";+import { cellId } from "@/__tests__/branded";+import { notebookAtom } from "@/core/cells/cells";+import {+ fakeBackend,+ fixtureMessages,+} from "@/core/notebook/replica/__tests__/fixtures";import { RuntimeState } from "@/core/kernel/RuntimeState";import { initializeIslands } from "../bootstrap";import type { IslandsPyodideBridge } from "../bridge";@@ -32,6 +39,7 @@ describe("initializeIslands", () => {consumeMessage = consumer;},sendComponentValues: vi.fn(),+ notebookBackend: fakeBackend(),} as unknown as IslandsPyodideBridge;const store = createStore();vi.spyOn(RuntimeState.INSTANCE, "start").mockImplementation(@@ -59,3 +67,51 @@ describe("initializeIslands", () => {expect(store.get(islandsHydratedAtom)).toBe(true);});});++describe("initializeIslands document", () => {+ afterEach(vi.restoreAllMocks);++ it("fills the notebook's cells from the managed session's host document", async () => {+ const root = document.createElement("div");+ root.innerHTML =+ '<marimo-island data-app-id="app-1" data-reactive="true"></marimo-island>';+ let handlers: Parameters<NotebookTransport>[1] | undefined;+ const transport: NotebookTransport = (_attempt, opened) =>+ new Promise(() => {+ handlers = opened;+ opened.open();+ });+ const bridge = {+ consumeNotifications: vi.fn(),+ sendComponentValues: vi.fn(),+ notebookBackend: fakeBackend({ transport }),+ } as unknown as IslandsPyodideBridge;+ const store = createStore();+ vi.spyOn(RuntimeState.INSTANCE, "start").mockImplementation(+ () => undefined,+ );++ await initializeIslands({+ bridge,+ store,+ root,+ autoInitializePlugins: false,+ });+ await vi.waitFor(() => expect(handlers).toBeDefined());+ for (const message of fixtureMessages("notebook-events.sse")) {+ handlers?.message(message);+ }++ const notebook = store.get(notebookAtom);+ expect(notebook.cellIds.inOrderIds).toEqual(["c1", "c3", "k7f2"]);+ expect(notebook.cellData[cellId("c3")].code).toBe("x = 21");+ expect(notebook.cellRuntime[cellId("c3")]).toBeDefined();++ handlers?.message({ event: "reset", data: {} });+ expect(store.get(notebookAtom).cellIds.inOrderIds).toEqual([+ "c1",+ "c3",+ "k7f2",+ ]);+ });+});diff --git a/frontend/src/core/islands/__tests__/bridge.test.ts b/frontend/src/core/islands/__tests__/bridge.test.tsindex 5ab1e288ec..7909e85c91 100644--- a/frontend/src/core/islands/__tests__/bridge.test.ts+++ b/frontend/src/core/islands/__tests__/bridge.test.ts@@ -396,6 +396,48 @@ describe("IslandsPyodideBridge", () => {expect(consumeMessage.mock.calls).toEqual([notification]);});+ it("forwards the managed session's host events to the notebook stream", async () => {+ await initializeSingleApp();+ const handlers = { open: vi.fn(), message: vi.fn() };+ void bridge.notebookBackend.transport(+ { signal: new AbortController().signal, cursor: null },+ handlers,+ );+ expect(handlers.open).toHaveBeenCalledOnce();++ const cell = { event: "cell", id: "1", data: { cell: { id: "c1" } } };+ sendNotebookEvent(1, cell);+ sendNotebookEvent(2, { event: "ready", id: "2", data: {} });+ sendKernelMessage(1);++ expect(handlers.message.mock.calls).toEqual([[cell]]);+ expect(() => bridge.notebookBackend.notebook("n1")).toThrow(+ "Islands do not edit",+ );+ });++ it("resets the notebook stream when the managed session is replaced or stopped", async () => {+ await initializeSingleApp();+ const handlers = { open: vi.fn(), message: vi.fn() };+ void bridge.notebookBackend.transport(+ { signal: new AbortController().signal, cursor: null },+ handlers,+ );++ mockSingleApp("generated app 2");+ await bridge.initializeApps();+ const ready = { event: "ready", id: "2", data: {} };+ sendNotebookEvent(1, { event: "ready", id: "1", data: {} });+ sendNotebookEvent(2, ready);+ await bridge.stopSession("app-1");++ expect(handlers.message.mock.calls).toEqual([+ [{ event: "reset", data: {} }],+ [ready],+ [{ event: "reset", data: {} }],+ ]);+ });+it("holds controls until the first app session is ready", async () => {setSingleApp();diff --git a/frontend/src/core/islands/bootstrap.ts b/frontend/src/core/islands/bootstrap.tsindex 818a144ce4..dfef7aacaf 100644--- a/frontend/src/core/islands/bootstrap.ts+++ b/frontend/src/core/islands/bootstrap.ts@@ -17,10 +17,14 @@ import {notebookAtom,notebookReducer,} from "../cells/cells";+import { followDocument } from "../cells/document";+import { notebookCells } from "../cells/utils";+import { createDocumentModel } from "../notebook/document";import { defineCustomElement } from "../dom/defineCustomElement";import { MarimoValueInputEvent } from "../dom/events";import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";+import { createNotebookReplica } from "../notebook/replica";import {handleCellNotificationeration,handleKernelReady,@@ -124,6 +128,23 @@ export async function initializeIslands(handleNotification(notification, actions, store, sessionGeneration);});+ // The notebook's cells follow the managed session's host document.+ const replica = createNotebookReplica(store);+ replica.connect(bridge.notebookBackend, { onNotification: Functions.NOOP });+ const documentModel = createDocumentModel({+ store,+ documentAtom: replica.documentAtom,+ backendAtom: replica.backendAtom,+ });+ const lifetime = new AbortController();+ documentModel.start({ signal: lifetime.signal });+ followDocument({+ store,+ model: documentModel,+ reconcile: actions.reconcileDocument,+ signal: lifetime.signal,+ });+// Track first user interaction before initialization completesdocument.addEventListener(MarimoValueInputEvent.TYPE,@@ -196,7 +217,9 @@ function handleNotification(case "kernel-ready":handleKernelReady(msg, {autoInstantiate: true,- setCells: actions.setCells,+ cells: notebookCells(store.get(notebookAtom)),+ setLastRun: actions.setLastRun,+ resetCellRuntimes: actions.resetCellRuntimes,setLayoutData: Functions.NOOP,setAppConfig: Functions.NOOP,setCapabilities: Functions.NOOP,diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.tsindex 5668b9f3f0..a0833bc456 100644--- a/frontend/src/core/islands/bridge.ts+++ b/frontend/src/core/islands/bridge.ts@@ -1,6 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. *//* oxlint-disable typescript/no-explicit-any */+import type { NotebookTransport } from "@marimo-team/client";import { getWorkerRPC } from "@/core/wasm/rpc";import { Deferred } from "@/utils/Deferred";import { throwNotImplemented } from "@/utils/functions";@@ -8,6 +9,7 @@ import { Logger } from "@/utils/Logger";import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";import { generateUUID } from "@/utils/uuid";import { initialNotebookState, notebookAtom } from "../cells/cells";+import type { NotebookBackend } from "../notebook/replica";import type { ClientCommand, NotificationMessage } from "../kernel/messages";import type { EditRequests, RunRequests } from "../network/types";import { store as defaultStore } from "../state/jotai";@@ -70,9 +72,37 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {private readonly activeSessionGenerations = new Set<number>();private appTransition = Promise.resolve();private workerReady = new Deferred<void>();+ /** Where the managed session's host events go while a replica follows them. */+ private stream: Parameters<NotebookTransport>[1] | undefined;public initialized = new Deferred<void>();+ /**+ * The managed session's host stream, for a replica to follow. Replacing+ * or stopping the session resets the stream, and the next session's+ * snapshot follows.+ */+ public readonly notebookBackend: NotebookBackend = {+ transport: ({ signal }, handlers) =>+ new Promise((resolve) => {+ this.stream = handlers;+ handlers.open();+ signal.addEventListener(+ "abort",+ () => {+ if (this.stream === handlers) {+ this.stream = undefined;+ }+ resolve();+ },+ { once: true },+ );+ }),+ notebook: () => {+ throw new Error("Islands do not edit notebooks");+ },+ };+public constructor(config: IslandsBridgeConfig = {}) {this.store = config.store || defaultStore;this.root = config.root || document;@@ -119,18 +149,29 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {if (!this.activeSessionGenerations.has(sessionGeneration)) {return;}- // Islands follow only the notebook's marimo notifications.const frame = jsonParseWithSpecialChar(event) as {event: string;data: { marimo?: NotificationMessage };};- if (frame.event === "marimo" && frame.data.marimo) {- this.notificationConsumer?.(frame.data.marimo, sessionGeneration);+ if (frame.event === "marimo") {+ if (frame.data.marimo) {+ this.notificationConsumer?.(frame.data.marimo, sessionGeneration);+ }+ return;+ }+ // The replica follows the managed session's host document.+ if (sessionGeneration === this.session?.sessionGeneration) {+ this.stream?.message(frame);}},);}+ /** The managed session is gone, so its stream starts over. */+ private resetNotebookStream(): void {+ this.stream?.message({ event: "reset", data: {} });+ }+public async initializeApps(): Promise<void> {await this.enqueueAppTransition(async () => {await this.workerReady.promise;@@ -185,6 +226,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {const replacesSession = managesSingleApp && previousSession !== undefined;this.activeSessionGenerations.add(request.sessionGeneration);if (replacesSession) {+ this.resetNotebookStream();this.store.set(notebookAtom, initialNotebookState());}if (managesSingleApp || !previousSession) {@@ -236,6 +278,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {this.store.set(islandsPendingInitialRunsAtom, null);this.session = undefined;this.sessionReady = new Deferred<AppSession>();+ this.resetNotebookStream();this.store.set(notebookAtom, initialNotebookState());});}diff --git a/frontend/src/core/kernel/__tests__/handlers.test.ts b/frontend/src/core/kernel/__tests__/handlers.test.tsindex fa295242c1..de220e998c 100644--- a/frontend/src/core/kernel/__tests__/handlers.test.ts+++ b/frontend/src/core/kernel/__tests__/handlers.test.ts@@ -1,7 +1,8 @@/* Copyright 2026 Marimo. All rights reserved. */import { describe, expect, it, vi } from "vitest";import { cellId } from "@/__tests__/branded";-import { buildCellData, buildLayoutState } from "../handlers";+import { createCell } from "@/core/cells/types";+import { buildLayoutState } from "../handlers";import type { NotificationMessageData } from "../messages";import { queryParamHandlers } from "../queryParamHandlers";@@ -63,152 +64,9 @@ describe("queryParamHandlers", () => {});});-describe("buildCellData", () => {- it("should build cell data from kernel-ready data", () => {- const kernelReadyData: NotificationMessageData<"kernel-ready"> = {- cell_ids: [cellId("cell1"), cellId("cell2")],- codes: ["x = 1", "y = 2"],- names: ["__", "__"],- configs: [- { disabled: false, hide_code: false },- { disabled: false, hide_code: false },- ],- layout: null,- resumed: false,- ui_values: {},- last_executed_code: {},- last_execution_time: {},- app_config: {- width: "normal",- app_title: null,- layout_file: null,- css_file: null,- auto_download: [],- },- kiosk: false,- capabilities: {- terminal: false,- },- auto_instantiated: false,- consumer_capabilities: { edit: true, interact: true },- };-- const cells = buildCellData(kernelReadyData);-- expect(cells).toMatchInlineSnapshot(`- [- {- "code": "x = 1",- "config": {- "disabled": false,- "hide_code": false,- },- "edited": false,- "id": "cell1",- "lastCodeRun": null,- "lastExecutionTime": null,- "name": "__",- "serializedEditorState": null,- },- {- "code": "y = 2",- "config": {- "disabled": false,- "hide_code": false,- },- "edited": false,- "id": "cell2",- "lastCodeRun": null,- "lastExecutionTime": null,- "name": "__",- "serializedEditorState": null,- },- ]- `);- });-- it("should mark cells as edited when code differs from last executed code", () => {- const kernelReadyData: NotificationMessageData<"kernel-ready"> = {- cell_ids: [cellId("cell1"), cellId("cell2")],- codes: ["x = 1", "y = 3"],- names: ["__", "__"],- configs: [- { disabled: false, hide_code: false },- { disabled: false, hide_code: false },- ],- layout: null,- resumed: false,- ui_values: {},- last_executed_code: {- cell1: "x = 1",- cell2: "y = 2",- },- last_execution_time: {- cell1: 1_234_567_890,- cell2: 1_234_567_891,- },- app_config: {- width: "normal",- app_title: null,- layout_file: null,- css_file: null,- auto_download: [],- },- kiosk: false,- capabilities: {- terminal: false,- },- auto_instantiated: false,- consumer_capabilities: { edit: true, interact: true },- };-- const cells = buildCellData(kernelReadyData);-- expect(cells[0].edited).toBe(false);- expect(cells[1].edited).toBe(true);- expect(cells[0].lastCodeRun).toBe("x = 1");- expect(cells[1].lastCodeRun).toBe("y = 2");- });-- it("should handle empty cell data", () => {- const kernelReadyData: NotificationMessageData<"kernel-ready"> = {- cell_ids: [],- codes: [],- names: [],- configs: [],- layout: null,- resumed: false,- ui_values: {},- last_executed_code: {},- last_execution_time: {},- app_config: {- width: "normal",- app_title: null,- layout_file: null,- css_file: null,- auto_download: [],- },- kiosk: false,- capabilities: {- terminal: false,- },- auto_instantiated: false,- consumer_capabilities: { edit: true, interact: true },- };-- const cells = buildCellData(kernelReadyData);-- expect(cells).toMatchInlineSnapshot("[]");- });-});-describe("buildLayoutState", () => {it("should build default layout state when no layout is provided", () => {const kernelReadyData: NotificationMessageData<"kernel-ready"> = {- cell_ids: [cellId("cell1")],- codes: ["x = 1"],- names: ["__"],- configs: [{ disabled: false, hide_code: false }],layout: null,resumed: false,ui_values: {},@@ -229,7 +87,7 @@ describe("buildLayoutState", () => {consumer_capabilities: { edit: true, interact: true },};- const cells = buildCellData(kernelReadyData);+ const cells = [createCell({ id: cellId("cell1") })];const mockSetLayoutData = vi.fn();const layoutState = buildLayoutState(kernelReadyData,@@ -248,13 +106,6 @@ describe("buildLayoutState", () => {it("should build layout state with vertical layout", () => {const kernelReadyData: NotificationMessageData<"kernel-ready"> = {- cell_ids: [cellId("cell1"), cellId("cell2")],- codes: ["x = 1", "y = 2"],- names: ["__", "__"],- configs: [- { disabled: false, hide_code: false },- { disabled: false, hide_code: false },- ],layout: {type: "vertical",data: [],@@ -278,7 +129,10 @@ describe("buildLayoutState", () => {consumer_capabilities: { edit: true, interact: true },};- const cells = buildCellData(kernelReadyData);+ const cells = [+ createCell({ id: cellId("cell1") }),+ createCell({ id: cellId("cell2") }),+ ];const mockSetLayoutData = vi.fn();const layoutState = buildLayoutState(kernelReadyData,diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.tsindex d616b73aa8..9e98cc3e8b 100644--- a/frontend/src/core/kernel/handlers.ts+++ b/frontend/src/core/kernel/handlers.ts@@ -3,7 +3,8 @@ import type { LayoutType } from "@/components/editor/renderers/types";import { Logger } from "@/utils/Logger";import { Objects } from "@/utils/objects";import type { UIElementId } from "../cells/ids";-import { type CellData, createCell } from "../cells/types";+import type { CellActions } from "../cells/cells";+import type { CellData } from "../cells/types";import { type AppConfig, AppConfigSchema } from "../config/config-schema";import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";import { deserializeLayoutState } from "../layout/layout";@@ -19,41 +20,6 @@ import type { KernelState } from "./state";type KernelReadyData = NotificationMessageData<"kernel-ready">;-/**- * Build cells from kernel-ready data.- */-export function buildCellData(data: KernelReadyData): CellData[] {- const {- codes,- names,- configs,- cell_ids,- last_executed_code,- last_execution_time,- } = data;-- const lastExecutedCode = last_executed_code || {};- const lastExecutionTime = last_execution_time || {};-- return codes.map((code, i) => {- const cellId = cell_ids[i];- const lastCodeRun = lastExecutedCode[cellId];-- // A cell is edited if the code has changed since the last time it was run- const edited = lastCodeRun ? lastCodeRun !== code : false;-- return createCell({- id: cellId,- code,- edited,- name: names[i],- lastCodeRun: lastExecutedCode[cellId] ?? null,- lastExecutionTime: lastExecutionTime[cellId] ?? null,- config: configs[i],- });- });-}-/*** Build layout state from kernel-ready data.*/@@ -95,7 +61,10 @@ export function handleKernelReady(data: KernelReadyData,opts: {autoInstantiate: boolean;- setCells: (cells: CellData[], layout: LayoutState) => void;+ /** The notebook's cells, as the host document provided them. */+ cells: CellData[];+ setLastRun: CellActions["setLastRun"];+ resetCellRuntimes: CellActions["resetCellRuntimes"];setLayoutData: (payload: {layoutView: LayoutType;data: LayoutData;@@ -104,17 +73,13 @@ export function handleKernelReady(setKernelState: (state: KernelState) => void;setAppConfig: (config: AppConfig) => void;onError: (error: Error) => void;- /**- * If provided, these cells will be used instead of the cells from- * kernel-ready. This allows preserving local edits made before connecting.- */- existingCells?: CellData[];},-) {+): LayoutState {const {- existingCells,autoInstantiate,- setCells,+ cells,+ setLastRun,+ resetCellRuntimes,setLayoutData,setAppConfig,setCapabilities,@@ -124,15 +89,12 @@ export function handleKernelReady(const { resumed, ui_values, app_config, capabilities, auto_instantiated } =data;- // Use existing cells if provided (local pre-connect edits), otherwise build from kernel-ready- // If the kernel was resumed, we don't want to use the existing cells because they may be stale.- const hasExistingCells = existingCells && existingCells.length > 0;- const cells =- hasExistingCells && !resumed ? existingCells : buildCellData(data);-- // Set up layout and cells+ resetCellRuntimes();+ setLastRun({+ lastCodeRun: data.last_executed_code ?? {},+ lastExecutionTime: data.last_execution_time ?? {},+ });const layoutState = buildLayoutState(data, cells, setLayoutData);- setCells(cells, layoutState);// Set app config and capabilitiesconst parsedAppConfig = AppConfigSchema.safeParse(app_config);@@ -145,7 +107,7 @@ export function handleKernelReady(// If the kernel was already instantiated server-side (e.g. run mode), we're doneif (auto_instantiated) {- return;+ return layoutState;}// If resumed, restore UI element values from kernel and we're done@@ -156,16 +118,13 @@ export function handleKernelReady(const uiObjectId: UIElementId = objectId;UI_ELEMENT_REGISTRY.set(uiObjectId, value);}- return;+ return layoutState;}// If we already have values for some objects, we should// send them to the kernel. This may happen after re-connecting// to the kernel after the computer wakes from sleep.const { objectIds, values } = collectUIElementValues();- const codesToSend = hasExistingCells- ? Object.fromEntries(existingCells.map((c) => [c.id, c.code]))- : undefined;// Send instantiate request to kernelvoid getRequestClient()@@ -173,7 +132,6 @@ export function handleKernelReady(objectIds,values,autoRun: autoInstantiate,- codes: codesToSend,}).then(() => {setKernelState({ isInstantiated: true, error: null });@@ -182,6 +140,7 @@ export function handleKernelReady(setKernelState({ isInstantiated: false, error: error });onError(new Error("Failed to instantiate", { cause: error }));});+ return layoutState;}export function handleRemoveUIElements(diff --git a/frontend/src/core/run-app.tsx b/frontend/src/core/run-app.tsxindex a113ead911..e152a9c37b 100644--- a/frontend/src/core/run-app.tsx+++ b/frontend/src/core/run-app.tsx@@ -11,11 +11,7 @@ import { Spinner } from "@/components/icons/spinner";import { buttonVariants } from "@/components/ui/button";import { cn } from "@/utils/cn";import { CellsRenderer } from "../components/editor/renderers/cells-renderer";-import {- hasCellsAtom,- notebookIsRunningAtom,- useCellActions,-} from "./cells/cells";+import { hasCellsAtom, notebookIsRunningAtom } from "./cells/cells";import type { AppConfig } from "./config/config-schema";import { DocumentProvider } from "./notebook/document";import { RuntimeState } from "./kernel/RuntimeState";@@ -41,7 +37,6 @@ const canPaintRunAppAtom = atom();export const RunApp: React.FC<AppProps> = ({ appConfig, hideHeader }) => {- const { setCells } = useCellActions();const { sendComponentValues } = useRequestClient();// Initialize RuntimeState event-listeners@@ -54,7 +49,6 @@ export const RunApp: React.FC<AppProps> = ({ appConfig, hideHeader }) => {const { connection, reconnect, documentModel } = useNotebookSession({autoInstantiate: true,- setCells: setCells,sessionId: getSessionId(),});diff --git a/frontend/src/core/session/__tests__/useNotebookSession.hook.test.tsx b/frontend/src/core/session/__tests__/useNotebookSession.hook.test.tsxindex 478c806eb3..ede233c036 100644--- a/frontend/src/core/session/__tests__/useNotebookSession.hook.test.tsx+++ b/frontend/src/core/session/__tests__/useNotebookSession.hook.test.tsx@@ -159,7 +159,6 @@ function renderConnectionHook(useNotebookSession({sessionId: SESSION_ID,autoInstantiate: false,- setCells: vi.fn(),}),{ wrapper, reactStrictMode },);@@ -334,10 +333,6 @@ it.each(["kernel-ready", "reconnected"])(act(() =>conn.send({op,- cell_ids: [],- codes: [],- names: [],- configs: [],layout: null,resumed: true,ui_values: {},@@ -367,7 +362,6 @@ describe("connection notice", () => {const { reconnect } = useNotebookSession({sessionId: SESSION_ID,autoInstantiate: false,- setCells: vi.fn(),});return (<ConnectionNoticediff --git a/frontend/src/core/session/useNotebookSession.tsx b/frontend/src/core/session/useNotebookSession.tsxindex 0a4cb7cd7a..1b809da475 100644--- a/frontend/src/core/session/useNotebookSession.tsx+++ b/frontend/src/core/session/useNotebookSession.tsx@@ -5,7 +5,8 @@ import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";import { useEffect, useLayoutEffect, useMemo } from "react";import { useErrorBoundary } from "react-error-boundary";import { toast } from "@/components/ui/use-toast";-import { getNotebook, useCellActions } from "@/core/cells/cells";+import { getNotebook, notebookAtom, useCellActions } from "@/core/cells/cells";+import { followDocument } from "@/core/cells/document";import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";import { createDocumentModel } from "@/core/notebook/document";import type { NotificationPayload } from "@/core/kernel/messages";@@ -22,14 +23,13 @@ import { Logger } from "@/utils/Logger";import { reloadSafe } from "@/utils/reload-safe";import { useAlertActions } from "../alerts/state";import { cacheInfoAtom } from "../cache/requests";-import { SCRATCH_CELL_ID } from "../cells/ids";import { useRunsActions } from "../cells/runs";import { focusAndScrollCellOutputIntoView } from "../cells/scrollCellIntoView";import {resyncBreakpoints,setActiveLine,} from "../codemirror/cells/debugger-state";-import type { CellData } from "../cells/types";+import { notebookCells } from "../cells/utils";import { capabilitiesAtom } from "../config/capabilities";import { connectionTransportTypeAtom, useSetAppConfig } from "../config/config";import { useDataSourceActions } from "../datasets/data-source-connections";@@ -75,30 +75,23 @@ import type { VariableName } from "../variables/types";import { activeDocumentModelAtom } from "./active-notebook";import { WebSocketClosedReason, ConnectionState } from "./types";-const SUPPORTS_LAZY_KERNELS = true;--function getExistingCells(): CellData[] | undefined {- if (!SUPPORTS_LAZY_KERNELS) {- return undefined;- }-- // Remove scratch pad- return Object.values(getNotebook().cellData).filter(- (cell) => cell.id !== SCRATCH_CELL_ID,- );-}-/** Coordinate session startup and apply notifications to the editor. */export function useNotebookSession(opts: {sessionId: SessionId;autoInstantiate: boolean;- setCells: (cells: CellData[], layout: LayoutState) => void;+ /** Called with the layout the kernel reported, after its cells are ready. */+ onKernelReady?: (layout: LayoutState) => void;}) {- const { autoInstantiate, sessionId, setCells } = opts;+ const { autoInstantiate, sessionId, onKernelReady } = opts;const { showBoundary } = useErrorBoundary();+ const store = useStore();- const { handleCellMessage } = useCellActions();- const { reconcileDocument } = useCellActions({ skipMiddleware: true });+ const {+ handleCellMessage,+ reconcileDocument,+ setLastRun,+ resetCellRuntimes,+ } = useCellActions();const { addCellNotification } = useRunsActions();const setKernelState = useSetAtom(kernelStateAtom);const setInitialRunCompleted = useSetAtom(initialRunCompletedAtom);@@ -153,18 +146,18 @@ export function useNotebookSession(opts: {setInitialRunCompleted(Boolean(msg.data.resumed || msg.data.auto_instantiated),);- const existingCells = getExistingCells();-- handleKernelReady(msg.data, {+ const layout = handleKernelReady(msg.data, {autoInstantiate,- setCells,+ cells: notebookCells(store.get(notebookAtom)),+ setLastRun,+ resetCellRuntimes,setLayoutData,setAppConfig,setCapabilities,setKernelState,onError: showBoundary,- existingCells,});+ onKernelReady?.(layout);if (!msg.data.resumed) {// A freshly started kernel may expose a different environment// (e.g. new env vars); re-run discovery instead of reusing stale@@ -393,7 +386,6 @@ export function useNotebookSession(opts: {}};- const store = useStore();const onMessageError = (error: unknown) => {toast({title: "Failed to handle message",@@ -443,16 +435,13 @@ export function useNotebookSession(opts: {const controller = new AbortController();documentModel.start({ signal: controller.signal });store.set(activeDocumentModelAtom, documentModel);- const follow = () => {- const document = store.get(documentModel.documentAtom);- if (document !== null) {- reconcileDocument(document);- }- };- const unsubscribe = store.sub(documentModel.documentAtom, follow);- follow();+ followDocument({+ store,+ model: documentModel,+ reconcile: reconcileDocument,+ signal: controller.signal,+ });return () => {- unsubscribe();controller.abort();if (store.get(activeDocumentModelAtom) === documentModel) {store.set(activeDocumentModelAtom, null);diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.pyindex 42755c35db..d0b55d0659 100644--- a/marimo/_messaging/notification.py+++ b/marimo/_messaging/notification.py@@ -17,7 +17,7 @@ import msgspecfrom marimo import _loggers as loggersfrom marimo._ast.app_config import _AppConfig-from marimo._ast.cell import CellConfig, RuntimeStateType+from marimo._ast.cell import RuntimeStateTypefrom marimo._core.protocol import Revisionfrom marimo._data._external_storage.models import (StorageEntry,@@ -439,11 +439,7 @@ class KernelReadyNotification(Notification, tag="kernel-ready"):"""Kernel ready for execution. First notification sent at startup.Attributes:- cell_ids: Cell IDs in order.- codes: Source code for each cell.- names: Cell names/titles.layout: Notebook layout config.- configs: Per-cell configuration.resumed: Whether resumed from previous session.ui_values: Previous UI element values if resumed.last_executed_code: Last executed code per cell if resumed.@@ -457,11 +453,7 @@ class KernelReadyNotification(Notification, tag="kernel-ready"):"""name: ClassVar[str] = "kernel-ready"- cell_ids: tuple[CellId_t, ...]- codes: tuple[str, ...]- names: tuple[str, ...]layout: LayoutConfig | None- configs: tuple[CellConfig, ...]resumed: boolui_values: dict[str, JSONType] | Nonelast_executed_code: dict[CellId_t, str] | Nonediff --git a/marimo/_pyodide/kernel_ready.py b/marimo/_pyodide/kernel_ready.pyindex 04dc3d1c85..b86f9de647 100644--- a/marimo/_pyodide/kernel_ready.py+++ b/marimo/_pyodide/kernel_ready.py@@ -19,13 +19,9 @@ if TYPE_CHECKING:def kernel_ready(app_manager: AppFileManager, view: SessionView | None) -> KernelReadyNotification:- """Describe the app's cells, resumed from `view` when the session has run."""+ """Describe the kernel's run state, resumed from `view` when the session has run."""app = app_manager.appreturn KernelReadyNotification(- codes=tuple(app.cell_manager.codes()),- names=tuple(app.cell_manager.names()),- configs=tuple(app.cell_manager.configs()),- cell_ids=tuple(app.cell_manager.cell_ids()),layout=app_manager.read_layout_config(),resumed=view is not None,ui_values=dict(view.ui_values) if view else {},diff --git a/marimo/_server/api/endpoints/ws/session_handler.py b/marimo/_server/api/endpoints/ws/session_handler.pyindex 6d958f6624..a3e3611655 100644--- a/marimo/_server/api/endpoints/ws/session_handler.py+++ b/marimo/_server/api/endpoints/ws/session_handler.py@@ -220,7 +220,6 @@ class SessionHandler(SessionConsumer, abc.ABC):# Build kernel ready messagekernel_ready_msg = build_kernel_ready(session=session,- manager=self.manager,resumed=resumed,ui_values=ui_values,last_executed_code=last_executed_code if should_send else {},diff --git a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py b/marimo/_server/api/endpoints/ws/ws_kernel_ready.pyindex ae4aac6bca..bdd353de12 100644--- a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py+++ b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py@@ -5,7 +5,6 @@ import asynciofrom typing import TYPE_CHECKING, Anyfrom marimo import _loggers-from marimo._ast.cell import CellConfigfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.notebook.document import NotebookDocumentfrom marimo._messaging.notification import (@@ -19,7 +18,6 @@ from marimo._types.ids import CellId_tif TYPE_CHECKING:from marimo._server.rtc.doc import LoroDocManager- from marimo._server.session_manager import SessionManagerfrom marimo._server.workspace import MarimoFileKeyfrom marimo._session import Session@@ -31,7 +29,6 @@ _background_tasks: set[asyncio.Task[Any]] = set()def build_kernel_ready(session: Session,- manager: SessionManager,resumed: bool,ui_values: dict[str, JSONType],last_executed_code: dict[CellId_t, str],@@ -47,7 +44,6 @@ def build_kernel_ready(Args:session: Current session- manager: Session managerresumed: Whether this is a resumed sessionui_values: UI element valueslast_executed_code: Last executed code for each cell@@ -64,19 +60,12 @@ def build_kernel_ready(Returns:KernelReady message operation."""- document = session.document- codes, names, configs, cell_ids = _extract_cell_data(document, manager)-# Initialize RTC if neededif _should_init_rtc(rtc_enabled, mode):- _try_init_rtc_doc(cell_ids, codes, file_key, doc_manager)+ _try_init_rtc_doc(session.document, file_key, doc_manager)return KernelReadyNotification(- codes=codes,- names=names,- configs=configs,layout=session.app_file_manager.read_layout_config(),- cell_ids=cell_ids,resumed=resumed,ui_values=ui_values,last_executed_code=last_executed_code,@@ -94,58 +83,6 @@ def build_kernel_ready()-def _extract_cell_data(- document: NotebookDocument,- manager: SessionManager,-) -> tuple[- tuple[str, ...],- tuple[str, ...],- tuple[CellConfig, ...],- tuple[CellId_t, ...],-]:- """Extract cell data based on mode.-- Args:- document: Current document- manager: Session manager-- Returns:- Tuple of (codes, names, configs, cell_ids).- """- if not document.cells:- return ((), (), (), ())-- if manager.should_send_code_to_frontend():- # Send full cell data to frontend- codes, names, configs, cell_ids = tuple(- zip(- *tuple(- (- cell.code,- cell.name,- cell.config,- cell.id,- )- for cell in document.cells- ),- strict=False,- )- )- return codes, names, configs, cell_ids- else:- # Don't send code to frontend in run mode- codes, names, configs, cell_ids = tuple(- zip(- *tuple(- ("", cell.name, cell.config, cell.id)- for cell in document.cells- ),- strict=False,- )- )- return codes, names, configs, cell_ids--def is_rtc_available() -> bool:"""Check if RTC (Loro) is available on this system.@@ -169,18 +106,16 @@ def _should_init_rtc(rtc_enabled: bool, mode: SessionMode) -> bool:def _try_init_rtc_doc(- cell_ids: tuple[CellId_t, ...],- codes: tuple[str, ...],+ document: NotebookDocument,file_key: MarimoFileKey,doc_manager: LoroDocManager,) -> None:- """Try to initialize RTC document with cell data.+ """Try to initialize the RTC document with the session document's cells.Logs a warning if Loro is not available but does not fail.Args:- cell_ids: Cell IDs to initialize- codes: Cell codes to initialize+ document: The session's documentfile_key: File key for the documentdoc_manager: LoroDoc manager"""@@ -189,6 +124,8 @@ def _try_init_rtc_doc("RTC: Loro is not installed, disabling real-time collaboration")else:+ cell_ids = tuple(cell.id for cell in document.cells)+ codes = tuple(cell.code for cell in document.cells)task = asyncio.create_task(doc_manager.create_doc(file_key, cell_ids, codes))diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 38dc1c70c1..8b52a6784c 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -3034,17 +3034,15 @@ components:type: objectKernelReadyNotification:description: "Kernel ready for execution. First notification sent at startup.\n\- \n Attributes:\n cell_ids: Cell IDs in order.\n codes: Source\- \ code for each cell.\n names: Cell names/titles.\n layout:\- \ Notebook layout config.\n configs: Per-cell configuration.\n \- \ resumed: Whether resumed from previous session.\n ui_values: Previous\- \ UI element values if resumed.\n last_executed_code: Last executed\- \ code per cell if resumed.\n last_execution_time: Last execution time\- \ per cell if resumed.\n app_config: Application configuration.\n \- \ kiosk: Whether running in kiosk mode.\n capabilities: Available\- \ kernel capabilities.\n auto_instantiated: Whether cells already executed\- \ (run mode).\n stable_session_id: Server-owned Session identity that\- \ survives\n browser reconnects. None where no server Session exists."+ \n Attributes:\n layout: Notebook layout config.\n resumed:\+ \ Whether resumed from previous session.\n ui_values: Previous UI element\+ \ values if resumed.\n last_executed_code: Last executed code per cell\+ \ if resumed.\n last_execution_time: Last execution time per cell if\+ \ resumed.\n app_config: Application configuration.\n kiosk:\+ \ Whether running in kiosk mode.\n capabilities: Available kernel capabilities.\n\+ \ auto_instantiated: Whether cells already executed (run mode).\n \+ \ stable_session_id: Server-owned Session identity that survives\n \+ \ browser reconnects. None where no server Session exists."properties:app_config:$ref: '#/components/schemas/_AppConfig'@@ -3053,18 +3051,6 @@ components:type: booleancapabilities:$ref: '#/components/schemas/KernelCapabilitiesNotification'- cell_ids:- items:- $ref: '#/components/schemas/CellId'- type: array- codes:- items:- type: string- type: array- configs:- items:- $ref: '#/components/schemas/CellConfig'- type: arrayconsumer_capabilities:$ref: '#/components/schemas/ConsumerCapabilities'kiosk:@@ -3085,10 +3071,6 @@ components:anyOf:- $ref: '#/components/schemas/LayoutConfig'- type: 'null'- names:- items:- type: string- type: arrayop:enum:- kernel-ready@@ -3105,11 +3087,7 @@ components:- type: 'null'required:- op- - cell_ids- - codes- - names- layout- - configs- resumed- ui_values- last_executed_codediff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 414bbc0e62..a40737b615 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -5584,11 +5584,7 @@ export interface components {* @description Kernel ready for execution. First notification sent at startup.** Attributes:- * cell_ids: Cell IDs in order.- * codes: Source code for each cell.- * names: Cell names/titles.* layout: Notebook layout config.- * configs: Per-cell configuration.* resumed: Whether resumed from previous session.* ui_values: Previous UI element values if resumed.* last_executed_code: Last executed code per cell if resumed.@@ -5605,9 +5601,6 @@ export interface components {/** @default false */auto_instantiated?: boolean;capabilities: components["schemas"]["KernelCapabilitiesNotification"];- cell_ids: components["schemas"]["CellId"][];- codes: string[];- configs: components["schemas"]["CellConfig"][];consumer_capabilities: components["schemas"]["ConsumerCapabilities"];kiosk: boolean;last_executed_code: {@@ -5617,7 +5610,6 @@ export interface components {[key: string]: number;} | null;layout: components["schemas"]["LayoutConfig"] | null;- names: string[];/** @enum {unknown} */op: "kernel-ready";resumed: boolean;diff --git a/tests/_messaging/test_serde.py b/tests/_messaging/test_serde.pyindex 6afea3e943..24549ca98f 100644--- a/tests/_messaging/test_serde.py+++ b/tests/_messaging/test_serde.py@@ -100,7 +100,7 @@ class TestDeserializeKernelMessage:message_dict = {"name": "kernel-ready"- # Missing required fields: cell_ids, codes+ # Missing required fields, such as layout and resumed}kernel_message = KernelMessage(json.dumps(message_dict).encode())diff --git a/tests/_pyodide/test_pyodide_notebook.py b/tests/_pyodide/test_pyodide_notebook.pyindex aeb7674bdc..05e9a04285 100644--- a/tests/_pyodide/test_pyodide_notebook.py+++ b/tests/_pyodide/test_pyodide_notebook.py@@ -268,7 +268,7 @@ async def test_kernel_ready_follows_the_snapshot(bridge):assert set(kinds[4:]) == {"marimo"}kernel_ready = frames[4]["data"]["marimo"]assert kernel_ready["op"] == "kernel-ready"- assert kernel_ready["codes"] == ["x = 1"]+ assert "codes" not in kernel_readyassert kernel_ready["resumed"] is Falsediff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.pyindex a293138f6e..551753b6a0 100644--- a/tests/_server/api/endpoints/test_kiosk.py+++ b/tests/_server/api/endpoints/test_kiosk.py@@ -44,7 +44,9 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123", headers=_HEADERS) as websocket:- notebook_id = notebook_id_of(socket_snapshot(websocket))+ snapshot = socket_snapshot(websocket)+ notebook_id = notebook_id_of(snapshot)+ cells = [e["data"]["cell"] for e in snapshot if e["event"] == "cell"]editor_ready = receive_notification(websocket)assert_kernel_ready_response(editor_ready)@@ -90,19 +92,19 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:# 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"+ replacement_code = cells[0]["code"] + "\n# saved"response = client.post("/api/kernel/save",headers=HEADERS,json={- "cellIds": editor_ready["data"]["cell_ids"],+ "cellIds": [cell["id"] for cell in cells],"filename": filename,"codes": [replacement_code,- *editor_ready["data"]["codes"][1:],+ *(cell["code"] for cell in cells[1:]),],- "names": editor_ready["data"]["names"],- "configs": editor_ready["data"]["configs"],+ "names": [cell["name"] for cell in cells],+ "configs": [cell["config"] for cell in cells],},)assert response.status_code == 200, response.textdiff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pyindex cbc4985dc2..2a4c96ebf2 100644--- a/tests/_server/api/endpoints/test_resume_session.py+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -217,30 +217,12 @@ def test_save_session(client: TestClient) -> None:data = receive_notification(websocket)assert_kernel_ready_response(data,- create_response(- {- # The cell IDs that were saved should be the ones that are- # resumed- "cell_ids": ["2", "1"],- "names": ["cell_0", "cell_1"],- "codes": [- "slider = mo.ui.slider(0, 100)",- "import marimo as mo",- ],- "configs": [- {- "hideCode": True,- "disabled": True,- },- {- "hideCode": False,- "disabled": False,- },- ],- "resumed": True,- }- ),+ create_response({"resumed": True}),)+ # The saved cells are the resumed session's document+ session = get_session(client, SessionId("456"))+ assert session is not None+ assert list(session.document.cell_ids) == ["2", "1"]# Check the session switch IDsassert not get_session(client, "123")diff --git a/tests/_server/api/endpoints/test_sse.py b/tests/_server/api/endpoints/test_sse.pyindex 96e83f922c..119dbc78f5 100644--- a/tests/_server/api/endpoints/test_sse.py+++ b/tests/_server/api/endpoints/test_sse.py@@ -314,9 +314,7 @@ async def test_sse_hides_code_when_include_code_false(event = await connection.next_notification()message = json.loads(event["data"])assert message["op"] == "kernel-ready"- assert message["data"]["codes"] == [""] # hiddenassert message["data"]["last_executed_code"] == {} # hidden- assert message["data"]["cell_ids"] == ["Hbol"] # preservedasync def test_sse_kernel_startup_error(client: TestClient) -> None:diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 96c6cddaf0..eb0d6521e0 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -386,40 +386,6 @@ async def test_cannot_connect_kiosk_with_run_session(assert exc_info.value.reason == "MARIMO_KIOSK_NOT_ALLOWED"-async def test_kernel_ready_sends_names_but_not_code_when_include_code_false(- client: TestClient,-) -> None:- """Cell names are sent in kernel-ready even when include_code=False.-- This ensures data-cell-name attributes are populated in the DOM when- running with marimo run (without --include-code).-- The 4 fields from _extract_cell_data (ws_kernel_ready.py) behave as:- - codes -> blanked ("") to hide source code- - names -> preserved (needed for data-cell-name DOM attribute)- - configs -> preserved (needed for cell rendering)- - cell_ids -> preserved (needed for cell identity)- """- session_manager = get_session_manager(client)- session_manager.mode = SessionMode.RUN- session_manager.include_code = False- with client.websocket_connect(WS_URL) as websocket:- data = receive_notification(websocket)- assert_kernel_ready_response(- data,- create_response(- {- "codes": [""], # hidden- "names": ["__"], # preserved- "configs": [- {"disabled": False, "hide_code": False}- ], # preserved- "cell_ids": ["Hbol"], # preserved- }- ),- )--async def test_connects_to_existing_session_with_same_file(client: TestClient,temp_marimo_file: str,diff --git a/tests/_server/api/endpoints/ws/test_ws_kernel_ready.py b/tests/_server/api/endpoints/ws/test_ws_kernel_ready.pydeleted file mode 100644index 41442a0a0a..0000000000--- a/tests/_server/api/endpoints/ws/test_ws_kernel_ready.py+++ /dev/null@@ -1,144 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-"""Tests for _extract_cell_data reading from the NotebookDocument.--The key change under test: `_extract_cell_data` now reads from-`session.document` (a `NotebookDocument`) rather than directly from-`session.app_file_manager.app.cell_manager`. This means that-document-level mutations (applied via `notebook-document-transaction`)-are reflected when a new client connects and receives `kernel-ready`.-"""--from __future__ import annotations--from unittest.mock import MagicMock--from marimo._ast.cell import CellConfig-from marimo._messaging.notebook.changes import (- CreateCell,- DeleteCell,- SetCode,- Transaction,-)-from marimo._messaging.notebook.document import NotebookCell, NotebookDocument-from marimo._server.api.endpoints.ws.ws_kernel_ready import _extract_cell_data-from marimo._types.ids import CellId_t---def _make_doc(*cells: tuple[str, str, str]) -> NotebookDocument:- """Build a NotebookDocument from (id, code, name) triples."""- return NotebookDocument(- [- NotebookCell(- id=CellId_t(cid),- code=code,- name=name,- config=CellConfig(),- )- for cid, code, name in cells- ]- )---def _manager(send_code: bool) -> MagicMock:- mgr = MagicMock()- mgr.should_send_code_to_frontend.return_value = send_code- return mgr---class TestExtractCellDataFromDocument:- """_extract_cell_data reads the document, not the cell_manager."""-- def test_empty_document(self) -> None:- doc = NotebookDocument()- result = _extract_cell_data(doc, _manager(send_code=True))- assert result == ((), (), (), ())- # Run mode should also handle empty document- result = _extract_cell_data(doc, _manager(send_code=False))- assert result == ((), (), (), ())-- def test_basic_extraction(self) -> None:- doc = _make_doc(- ("a", "x = 1", "setup"),- ("b", "y = 2", "compute"),- )- codes, names, configs, cell_ids = _extract_cell_data(- doc, _manager(send_code=True)- )- assert codes == ("x = 1", "y = 2")- assert names == ("setup", "compute")- assert cell_ids == (CellId_t("a"), CellId_t("b"))- assert len(configs) == 2-- def test_hides_code_in_run_mode(self) -> None:- doc = _make_doc(("a", "secret()", "fn"))- codes, names, _, _ = _extract_cell_data(doc, _manager(send_code=False))- assert codes == ("",)- assert names == ("fn",)-- def test_document_mutations_reflected(self) -> None:- """Mutations applied to the document are visible in _extract_cell_data.-- This is the core scenario: the kernel applies a transaction- (e.g. from notebook-document-transaction) which mutates the- document. A subsequent call to build_kernel_ready (during- reconnection) should see the mutated state.- """- doc = _make_doc(- ("a", "x = 1", "cell_a"),- ("b", "y = 2", "cell_b"),- ("c", "z = 3", "cell_c"),- )-- # Simulate a transaction that deletes cell "b" and adds a new cell- tx = Transaction(- changes=(- DeleteCell(cell_id=CellId_t("b")),- CreateCell(- cell_id=CellId_t("new"),- code="import altair",- name="chart",- config=CellConfig(hide_code=True),- ),- ),- source="kernel",- )- doc.apply(tx)-- codes, names, configs, cell_ids = _extract_cell_data(- doc, _manager(send_code=True)- )- assert cell_ids == (- CellId_t("a"),- CellId_t("c"),- CellId_t("new"),- )- assert codes == ("x = 1", "z = 3", "import altair")- assert names == ("cell_a", "cell_c", "chart")- # The new cell's config should be preserved- assert configs[2].hide_code is True-- def test_set_code_transaction_reflected(self) -> None:- """SetCode mutations are visible on reconnection."""- doc = _make_doc(("a", "original", "cell_a"))- tx = Transaction(- changes=(SetCode(cell_id=CellId_t("a"), code="modified"),),- source="kernel",- )- doc.apply(tx)-- codes, _, _, _ = _extract_cell_data(doc, _manager(send_code=True))- assert codes == ("modified",)-- def test_set_code_hidden_in_run_mode(self) -> None:- """Even after SetCode, run-mode still hides code."""- doc = _make_doc(("a", "original", "cell_a"))- doc.apply(- Transaction(- changes=(SetCode(cell_id=CellId_t("a"), code="modified"),),- source="kernel",- )- )-- codes, names, _, _ = _extract_cell_data(doc, _manager(send_code=False))- assert codes == ("",)- assert names == ("cell_a",)diff --git a/tests/_server/api/endpoints/ws_helpers.py b/tests/_server/api/endpoints/ws_helpers.pyindex 7b59e4e618..7db4b3a0bf 100644--- a/tests/_server/api/endpoints/ws_helpers.py+++ b/tests/_server/api/endpoints/ws_helpers.py@@ -38,16 +38,12 @@ def create_response(partial_response: dict[str, Any],) -> dict[str, Any]:response: dict[str, Any] = {- "cell_ids": ["Hbol"],- "codes": ["import marimo as mo"],- "names": ["__"],"layout": None,"resumed": False,"ui_values": {},"last_executed_code": {},"last_execution_time": {},"kiosk": False,- "configs": [{"disabled": False, "hide_code": False}],"app_config": {"width": "full"},"capabilities": asdict(KernelCapabilitiesNotification()),}@@ -87,13 +83,9 @@ def assert_kernel_ready_response(response = create_response({})data = parse_raw(raw_data["data"], KernelReadyNotification)expected = parse_raw(response, KernelReadyNotification)- assert data.cell_ids == expected.cell_ids- assert data.codes == expected.codes- assert data.names == expected.namesassert data.layout == expected.layoutassert data.resumed == expected.resumedassert data.ui_values == expected.ui_values- assert data.configs == expected.configsassert data.app_config == expected.app_configassert data.kiosk == expected.kioskassert data.last_execution_time == expected.last_execution_timediff --git a/tests/_server/host/test_app_websocket.py b/tests/_server/host/test_app_websocket.pyindex ae15fb4f3e..55e4f7069d 100644--- a/tests/_server/host/test_app_websocket.py+++ b/tests/_server/host/test_app_websocket.py@@ -60,9 +60,6 @@ def test_app_executes_with_hidden_source_and_retained_hashes(snapshot = socket_snapshot(ws)ready = receive_notification(ws, "kernel-ready")assert ready["auto_instantiated"] is True- assert ready["codes"] == (- ["import marimo as mo"] if include_code else [""]- )cell = next(e["data"]["cell"] for e in snapshot if e["event"] == "cell")diff --git a/tests/_server/host/test_editor_websocket.py b/tests/_server/host/test_editor_websocket.pyindex 63d8bf5a4c..64d83ab054 100644--- a/tests/_server/host/test_editor_websocket.py+++ b/tests/_server/host/test_editor_websocket.py@@ -22,7 +22,7 @@ from marimo._server.host import HOST_API_PATHfrom marimo._server.host.bridge import SessionBridgefrom marimo._server.host.context import HostContextfrom marimo._session.managers.ipc import KernelStartupError-from marimo._types.ids import ConsumerId, SessionId+from marimo._types.ids import CellId_t, ConsumerId, SessionIdfrom tests._server.api.endpoints.ws_helpers import headersfrom tests._server.host.drive import socket_snapshotfrom tests._server.mocks import get_session_manager@@ -34,6 +34,13 @@ if TYPE_CHECKING:from starlette.testclient import TestClient, WebSocketTestSession+def first_cell_id(client: TestClient, session_id: str) -> CellId_t:+ """The first cell of the session's document, as the host stream has it."""+ session = get_session_manager(client).get_session(SessionId(session_id))+ assert session is not None+ return session.document.cell_ids[0]++@pytest.fixturedef editor_host(client: TestClient) -> Iterator[SessionBridge]:bridge = SessionBridge(get_session_manager(client))@@ -93,7 +100,7 @@ def test_editor_starts_and_runs_through_the_host_socket(names = [event["event"] for event in messages[:boundary]]assert names[0] == "notebook"assert names.index("cell") < names.index("document")- cell_id = ready["cell_ids"][0]+ cell_id = first_cell_id(client, "s1")response = client.post("/api/kernel/run",headers=headers("s1"),@@ -171,8 +178,8 @@ def test_reconnect_keeps_state_and_refresh_replays_it() -> None:url = f"{socket_url(editor_host)}&types=marimo"with client.websocket_connect(url) as websocket:- ready = receive_notification(websocket, "kernel-ready")- cell_id = ready["cell_ids"][0]+ receive_notification(websocket, "kernel-ready")+ cell_id = first_cell_id(client, "s1")response = client.post("/api/kernel/run",headers=headers("s1"),@@ -213,12 +220,12 @@ def test_reconnect_recovers_offline_notifications(url = f"{socket_url(editor_host)}&types=marimo"with client.websocket_connect(url) as socket:cursor = socket_snapshot(socket)[-1]["id"]- ready = receive_notification(socket, "kernel-ready")+ receive_notification(socket, "kernel-ready")session = get_session_manager(client).get_session(SessionId("s1"))assert session is not Noneassert client.portal is not Noneupdate = CellNotification(- cell_id=ready["cell_ids"][0],+ cell_id=session.document.cell_ids[0],status="idle",output=CellOutput(channel=CellChannel.OUTPUT,@@ -484,7 +491,7 @@ def test_untitled_editor_bootstraps_and_reconnects_with_host_events(try:with client.websocket_connect(url) as ws:snapshot = socket_snapshot(ws)- ready = receive_notification(ws, "kernel-ready")+ receive_notification(ws, "kernel-ready")notebook_id = next(e["data"]["notebook"]["id"]for e in snapshot@@ -493,7 +500,10 @@ def test_untitled_editor_bootstraps_and_reconnects_with_host_events(response = client.post("/api/kernel/run",headers=headers("new"),- json={"cellIds": ready["cell_ids"], "codes": ["x = 42"]},+ json={+ "cellIds": [first_cell_id(client, "new")],+ "codes": ["x = 42"],+ },)assert response.status_code == 200receive_notification(ws, "completed-run")