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
Read notebook state from the host document (#11575)
Trevor Manz6f6b4bea7f9b
diff --git a/frontend/benchmarks/cell-editing.bench.ts b/frontend/benchmarks/cell-editing.bench.tsindex a41061fbc9..a9e2ef8380 100644--- a/frontend/benchmarks/cell-editing.bench.ts+++ b/frontend/benchmarks/cell-editing.bench.ts@@ -19,8 +19,6 @@ import {notebookReducer,} from "@/core/cells/cells";import type { CellData } from "@/core/cells/types";-import { layoutStateAtom } from "@/core/layout/state";-import { lastSavedNotebookAtom, needsSaveAtom } from "@/core/saving/state";import type { DispatchedActionOf } from "@/utils/createReducer";type CellAction = DispatchedActionOf<ReducerCellActions>;@@ -74,12 +72,6 @@ for (const count of [10, 25, 100, 1000]) {state = MockNotebook.notebookState({ cellData });iteration = 0;store.set(notebookAtom, state);- store.set(lastSavedNotebookAtom, {- codes: ids.map(() => code),- names: ids.map((id) => state.cellData[id].name),- configs: ids.map((id) => state.cellData[id].config),- layout: store.get(layoutStateAtom),- });const subscribe = (value: Atom<unknown>) => {unsubscribes.push(store.sub(value, () => undefined));};@@ -98,7 +90,6 @@ for (const count of [10, 25, 100, 1000]) {notebookIsRunningAtom,notebookQueuedOrRunningCountAtom,needsRunAtom,- needsSaveAtom,]) {subscribe(value);}diff --git a/frontend/src/__mocks__/notebook.ts b/frontend/src/__mocks__/notebook.tsindex 200962d660..ab5b801f48 100644--- a/frontend/src/__mocks__/notebook.ts+++ b/frontend/src/__mocks__/notebook.ts@@ -54,7 +54,6 @@ export const MockNotebook = {cellLogs: [],history: [],scrollKey: null,- untouchedNewCells: new Set(),};},diff --git a/frontend/src/__mocks__/partial.ts b/frontend/src/__mocks__/partial.tsnew file mode 100644index 0000000000..c79e7b043e--- /dev/null+++ b/frontend/src/__mocks__/partial.ts@@ -0,0 +1,26 @@+/* Copyright 2026 Marimo. All rights reserved. */++/**+ * A partial mock of `T` that throws when a member the test did not provide+ * is read, so a test cannot silently depend on an undefined field.+ */+export function partial<T extends object>(+ members: Partial<T>,+ name = "mock",+): T {+ return new Proxy(members as T, {+ get(target, key, receiver) {+ // Only the members the test gave count as provided, not those every+ // object inherits. Promise detection and well-known symbols may probe+ // any object.+ if (+ Object.hasOwn(target, key) ||+ typeof key === "symbol" ||+ key === "then"+ ) {+ return Reflect.get(target, key, receiver);+ }+ throw new Error(`${name}.${String(key)} is not implemented in this test`);+ },+ });+}diff --git a/frontend/src/__tests__/main.test.tsx b/frontend/src/__tests__/main.test.tsxindex 101c778dea..a8fd43d2b4 100644--- a/frontend/src/__tests__/main.test.tsx+++ b/frontend/src/__tests__/main.test.tsx@@ -10,8 +10,11 @@ import {import {appConfigAtom,configOverridesAtom,+ pageAppConfigAtom,userConfigAtom,} from "../core/config/config";+import { exportedForTesting, notebookAtom } from "../core/cells/cells";+import { SCRATCH_CELL_ID } from "../core/cells/ids";import { marimoVersionAtom, showCodeInRunModeAtom } from "../core/meta/state";import { type AppMode, viewStateAtom } from "../core/mode";import { codeAtom, filenameAtom } from "../core/saving/file-state";@@ -40,7 +43,8 @@ describe("main", () => {store.set(filenameAtom, null);store.set(showCodeInRunModeAtom, false);store.set(marimoVersionAtom, "unknown");- store.set(appConfigAtom, parseAppConfig({}));+ store.set(notebookAtom, exportedForTesting.initialNotebookState());+ store.set(pageAppConfigAtom, {});store.set(userConfigAtom, defaultUserConfig());store.set(configOverridesAtom, {});});@@ -99,6 +103,25 @@ describe("main", () => {expect(store.get(viewStateAtom).mode).toBe("edit");});+ it("seeds runtime from a session snapshot without dropping the scratch cell", () => {+ const el = document.createElement("div");+ const error = mount(+ {+ mode: "edit",+ session: {+ version: "1",+ metadata: { marimo_version: "1", script_metadata_hash: null },+ cells: [{ id: "cell-1", code_hash: null, console: [], outputs: [] }],+ },+ },+ el,+ );+ expect(error).toBeUndefined();+ const { cellRuntime } = store.get(notebookAtom);+ expect(cellRuntime["cell-1" as never]).toBeDefined();+ expect(cellRuntime[SCRATCH_CELL_ID]).toBeDefined();+ });+it("should mount with empty config", () => {const el = document.createElement("div");const error = mount(diff --git a/frontend/src/components/app-config/app-config-form.tsx b/frontend/src/components/app-config/app-config-form.tsxindex c52ed602ef..2b9e0e57af 100644--- a/frontend/src/components/app-config/app-config-form.tsx+++ b/frontend/src/components/app-config/app-config-form.tsx@@ -37,7 +37,7 @@ import {const FORM_DEBOUNCE = 100; // ms;export const AppConfigForm: React.FC = () => {- const [config, setConfig] = useAppConfig();+ const config = useAppConfig();const { saveAppConfig } = useRequestClient();const htmlCheckboxId = useId();const ipynbCheckboxId = useId();@@ -50,18 +50,14 @@ export const AppConfigForm: React.FC = () => {defaultValues: config,});+ // The host document carries the saved config back.const onSubmit = async (values: AppConfig) => {- await saveAppConfig({ config: values })- .then(() => {- setConfig(values);- })- .catch(() => {- setConfig(values);- });+ await saveAppConfig({ config: values });};const debouncedSubmit = useDebouncedCallback((v: AppConfig) => {- onSubmit(v);+ // The request client reports a failed save, so nothing is left to handle.+ onSubmit(v).catch(() => undefined);}, FORM_DEBOUNCE);// When width is changed, dispatch a resize event so widgets know to resizediff --git a/frontend/src/components/editor/__tests__/data-attributes.test.tsx b/frontend/src/components/editor/__tests__/data-attributes.test.tsxindex 74df61bbb1..e961be2997 100644--- a/frontend/src/components/editor/__tests__/data-attributes.test.tsx+++ b/frontend/src/components/editor/__tests__/data-attributes.test.tsx@@ -94,7 +94,6 @@ describe("Cell data attributes", () => {code: "",name: cellName,edited: false,- serializedEditorState: null,config: {disabled: false,hide_code: false,diff --git a/frontend/src/components/editor/__tests__/output-persistence.test.tsx b/frontend/src/components/editor/__tests__/output-persistence.test.tsxindex 745d8d9ab0..2665cd4104 100644--- a/frontend/src/components/editor/__tests__/output-persistence.test.tsx+++ b/frontend/src/components/editor/__tests__/output-persistence.test.tsx@@ -41,7 +41,6 @@ function seedNotebook(code: "1 + 1",name: "test_cell",edited: false,- serializedEditorState: null,config: {disabled: false,hide_code: false,diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex 1937e36bba..ff2e0d0b1f 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -39,6 +39,7 @@ import { aiCompletionCellAtom } from "@/core/ai/state";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { hasOnlyOneCellAtom } from "@/core/cells/cells";import { useCellActions } from "@/core/cells/actions";+import { showHiddenCodeAtom } from "@/core/cells/editor";import { type CellId, SETUP_CELL_ID } from "@/core/cells/ids";import { useNotebookDocumentEdit } from "@/core/notebook/document";import type { CellData } from "@/core/cells/types";@@ -54,8 +55,8 @@ import {appWidthAtom,autoInstantiateAtom,} from "@/core/config/config";-import { kioskModeAtom } from "@/core/mode";import type { CellConfig, RuntimeState } from "@/core/network/types";+import { canEditAtom } from "@/core/notebook";import { canLinkToCell, createCellLink } from "@/utils/cell-urls";import { copyToClipboard } from "@/utils/copy";import { downloadCellOutputAsImage } from "@/utils/download";@@ -89,9 +90,9 @@ export function useCellActionButtons({ cell, closePopover }: Props) {sendToBottom,addColumnBreakpoint,clearCellOutput,- markUntouched,createCell,} = useCellActions();+ const showHiddenCode = useSetAtom(showHiddenCodeAtom);const edit = useNotebookDocumentEdit();const splitCell = useSplitCellCallback();const runCell = useRunCell(cell?.cellId);@@ -102,10 +103,10 @@ export function useCellActionButtons({ cell, closePopover }: Props) {const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);const aiFeaturesEnabled = useAtomValue(aiFeaturesEnabledAtom);const autoInstantiate = useAtomValue(autoInstantiateAtom);- const kioskMode = useAtomValue(kioskModeAtom);+ const canEdit = useAtomValue(canEditAtom);const appWidth = useAtomValue(appWidthAtom);- if (!cell || kioskMode) {+ if (!cell || !canEdit) {return [];}@@ -229,7 +230,7 @@ export function useCellActionButtons({ cell, closePopover }: Props) {hide_code: MARKDOWN_INITIAL_HIDE_CODE,}),);- markUntouched({ cellId });+ showHiddenCode({ cellId });}},hidden: isSetupCell,diff --git a/frontend/src/components/editor/actions/useConfigActions.tsx b/frontend/src/components/editor/actions/useConfigActions.tsxindex f3b4d078e7..a27b1506d9 100644--- a/frontend/src/components/editor/actions/useConfigActions.tsx+++ b/frontend/src/components/editor/actions/useConfigActions.tsx@@ -8,7 +8,7 @@ import type { ActionButton } from "./types";export function useConfigActions() {const [config, setConfig] = useResolvedMarimoConfig();- const [appConfig, setAppConfig] = useAppConfig();+ const appConfig = useAppConfig();const { saveAppConfig, saveUserConfig } = useRequestClient();const handleUserConfig = async (values: Partial<UserConfig>) => {@@ -17,10 +17,9 @@ export function useConfigActions() {});};+ // The host document carries the saved config back.const handleAppConfig = async (values: AppConfig) => {- await saveAppConfig({ config: values }).then(() => {- setAppConfig(values);- });+ await saveAppConfig({ config: values });};const actions: ActionButton[] = [diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex 5215b4568f..9ab1e61c70 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -65,13 +65,14 @@ import {} from "@/core/cells/cells";import { useCellActions } from "@/core/cells/actions";import { useNotebookDocumentEdit } from "@/core/notebook/document";+import { canEditAtom } from "@/core/notebook";import { disabledCellIds } from "@/core/cells/utils";import { capabilitiesAtom } from "@/core/config/capabilities";import { aiEnabledAtom, useResolvedMarimoConfig } from "@/core/config/config";import { Constants } from "@/core/constants";import { useLayoutActions, useLayoutState } from "@/core/layout/state";import { useTogglePresenting } from "@/core/layout/useTogglePresenting";-import { kioskModeAtom, viewStateAtom } from "@/core/mode";+import { viewStateAtom } from "@/core/mode";import { useRequestClient } from "@/core/network/requests";import { useFilename } from "@/core/saving/filename";import { createShareableLink } from "@/core/wasm/share";@@ -119,7 +120,7 @@ export function useNotebookActions({const { toggleApplication } = useChromeActions();const { selectedPanel } = useChromeState();const [viewState] = useAtom(viewStateAtom);- const kioskMode = useAtomValue(kioskModeAtom);+ const canEdit = useAtomValue(canEditAtom);const setCodeVisibility = useSetCodeVisibility();const setOutputsExpanded = useSetOutputsExpanded();const [resolvedConfig] = useResolvedMarimoConfig();@@ -448,7 +449,7 @@ export function useNotebookActions({{icon: <ZapIcon size={14} strokeWidth={1.5} />,label: "Enable all cells",- hidden: !hasDisabledCells || kioskMode,+ hidden: !hasDisabledCells || !canEdit,handle: () => {const ids = disabledCellIds(getNotebook());edit((tx) => {@@ -538,7 +539,7 @@ export function useNotebookActions({{icon: <Undo2Icon size={14} strokeWidth={1.5} />,label: undoLabel,- hidden: !canUndoDeletes || kioskMode,+ hidden: !canUndoDeletes || !canEdit,handle: () => {undoDeleteCell();},diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 461960d200..1575c4ebe7 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -3,7 +3,7 @@ import { historyField } from "@codemirror/commands";import { EditorState, type Extension, StateEffect } from "@codemirror/state";import { EditorView, ViewPlugin } from "@codemirror/view";import { useIntersectionObserver } from "@uidotdev/usehooks";-import { useAtom, useAtomValue } from "jotai";+import { useAtom, useAtomValue, useSetAtom } from "jotai";import React, { memo, useEffect, useMemo, useRef, useState } from "react";import useEvent from "react-use-event-hook";import { Button } from "@/components/ui/button";@@ -12,6 +12,11 @@ import { aiCompletionCellAtom } from "@/core/ai/state";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { getNotebook } from "@/core/cells/cells";import { useCellActions } from "@/core/cells/actions";+import {+ showHiddenCodeAtom,+ takeRestoredEditorStateAtom,+ useRestoredEditorState,+} from "@/core/cells/editor";import { useNotebookDocumentEdit } from "@/core/notebook/document";import { SETUP_CELL_ID } from "@/core/cells/ids";import { usePendingDeleteService } from "@/core/cells/pending-delete-service";@@ -58,7 +63,7 @@ import { LanguageToggles } from "./language-toggle";export interface CellEditorPropsextendsPick<CellRuntimeState, "status">,- Pick<CellData, "id" | "code" | "serializedEditorState" | "config"> {+ Pick<CellData, "id" | "code" | "config"> {runCell: () => void;theme: Theme;showPlaceholder: boolean;@@ -116,7 +121,6 @@ const CellEditorInternal = ({config: cellConfig,code,status,- serializedEditorState,setEditorView,runCell,userConfig,@@ -133,6 +137,9 @@ const CellEditorInternal = ({tooltipParentSelector,}: CellEditorProps) => {const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom);+ const serializedEditorState = useRestoredEditorState(cellId);+ const takeRestoredEditorState = useSetAtom(takeRestoredEditorStateAtom);+ const showHiddenCodeNow = useSetAtom(showHiddenCodeAtom);const deleteCell = useDeleteCellCallback();const { saveOrNameNotebook } = useSaveNotebook();const pendingDeleteService = usePendingDeleteService();@@ -192,7 +199,7 @@ const CellEditorInternal = ({edit((tx) =>tx.updateConfig(cellId, { hide_code: MARKDOWN_INITIAL_HIDE_CODE }),);- cellActions.markUntouched({ cellId });+ showHiddenCodeNow({ cellId });}});@@ -422,8 +429,8 @@ const CellEditorInternal = ({});}setEditorView(ev);- // Clear the serialized state so that we don't re-create the editor next time- cellActions.clearSerializedEditorState({ cellId });+ // The restored state is used once; the next mount builds a fresh editor.+ takeRestoredEditorState({ cellId });});const [isEditorMounted, setIsEditorMounted] = useState(serializedEditorState !== null,diff --git a/frontend/src/components/editor/cell/collapse.tsx b/frontend/src/components/editor/cell/collapse.tsxindex d518b62611..8cf9e799a2 100644--- a/frontend/src/components/editor/cell/collapse.tsx+++ b/frontend/src/components/editor/cell/collapse.tsx@@ -14,6 +14,7 @@ import { Toolbar } from "@/components/layout/toolbar";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";import { useNotebook } from "@/core/cells/cells";+import { columnOf, useLayout } from "@/core/cells/layout";import type { CellId } from "@/core/cells/ids";import { getDescendantsStatus } from "@/core/cells/utils";import { cn } from "@/utils/cn";@@ -64,7 +65,11 @@ export const CollapsedCellBanner: React.FC<{count: number;}> = memo(({ onClick, count, cellId }) => {const notebook = useNotebook();- const states = getDescendantsStatus(notebook, cellId);+ const layout = useLayout();+ const states = getDescendantsStatus(+ notebook,+ columnOf(layout, cellId).folds.get(cellId) ?? [],+ );return (<buttondiff --git a/frontend/src/components/editor/chrome/components/feedback-button.tsx b/frontend/src/components/editor/chrome/components/feedback-button.tsxindex cd67980c8c..71db47f8f6 100644--- a/frontend/src/components/editor/chrome/components/feedback-button.tsx+++ b/frontend/src/components/editor/chrome/components/feedback-button.tsx@@ -18,7 +18,6 @@ import {DialogTitle,} from "@/components/ui/dialog";import { Skeleton } from "@/components/ui/skeleton";-import { notebookAtom } from "@/core/cells/cells";import { Constants } from "@/core/constants";import {buildBugReportUrl,@@ -116,13 +115,8 @@ export const FeedbackModal: React.FC<{return requestClient.getEnvironmentInfo();}, [requestClient]);- const notebook = useAtomValue(notebookAtom);const errors = getCellErrorEntries(store);-- const cells = notebook.cellIds.inOrderIds.map(- (cellId) => notebook.cellData[cellId],- );- const codeAvailable = useNotebookCodeAvailable(cells);+ const codeAvailable = useNotebookCodeAvailable();const filename = useAtomValue(filenameAtom);const connection = useAtomValue(connectionAtom);const notebookSourceReason = getNotebookSourceUnavailableReason({diff --git a/frontend/src/components/editor/controls/Controls.tsx b/frontend/src/components/editor/controls/Controls.tsxindex 1e0a2b441a..831765f171 100644--- a/frontend/src/components/editor/controls/Controls.tsx+++ b/frontend/src/components/editor/controls/Controls.tsx@@ -111,7 +111,7 @@ export const Controls = ({className={cn(bottomRightControls)}><HideInKioskMode>- <SaveComponent kioskMode={false} />+ <SaveComponent /></HideInKioskMode><Tooltip content={renderShortcut("global.hideCode")}>diff --git a/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx b/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsxindex a7fc2e1876..34584690d6 100644--- a/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx+++ b/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx@@ -24,7 +24,7 @@ import {ERROR_MESSAGE_INSTRUCTIONS,} from "@/core/cells/error-report";import { pairConfigAtom } from "@/core/config/pair";-import { notebookStateFromSession } from "@/core/cells/session";+import { readExport } from "@/core/cells/session";import type { MarimoError, OutputMessage } from "@/core/kernel/messages";import {type StableSessionId,@@ -317,8 +317,8 @@ describe("SendErrorReportButton", () => {});it("sends the restored exception type and complete traceback", async () => {- const state = notebookStateFromSession(- {+ const { cellRuntime } = readExport({+ session: {version: "1",metadata: { marimo_version: "1", script_metadata_hash: null },cells: [@@ -342,9 +342,11 @@ describe("SendErrorReportButton", () => {},],},- null,- );- const message = state?.cellRuntime[CELL_ID].output;+ notebook: null,+ filename: null,+ appConfig: {},+ });+ const message = cellRuntime[CELL_ID].output;expect(message).toBeDefined();renderButton({content: message && <OutputRenderer cellId={CELL_ID} message={message} />,diff --git a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts b/frontend/src/components/editor/navigation/__tests__/navigation.test.tsindex 4417231571..29c29bca42 100644--- a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts+++ b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts@@ -27,6 +27,7 @@ import { aiCompletionCellAtom } from "@/core/ai/state";import type { CellActions } from "@/core/cells/actions";import { notebookAtom } from "@/core/cells/cells";import type { CellId } from "@/core/cells/ids";+import { layoutAtom } from "@/core/cells/layout";import type { DocumentModel } from "@/core/notebook/document";import {cell,@@ -165,7 +166,6 @@ const mockCellActions = MockNotebook.cellActions({moveCell: vi.fn(),sendToTop: vi.fn(),sendToBottom: vi.fn(),- markTouched: vi.fn(),deleteCells: vi.fn(),undoDeleteCell: vi.fn(),});@@ -318,7 +318,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId2,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -850,7 +850,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId2,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -873,7 +873,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId3,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -896,7 +896,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId3,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -919,7 +919,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId2 });selectionActions.extend({cellId: cellId3,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -954,7 +954,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId2,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -990,7 +990,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId2 });selectionActions.extend({cellId: cellId3,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -1023,7 +1023,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId2,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -1056,7 +1056,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId2,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -1084,7 +1084,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId2 });selectionActions.extend({cellId: cellId3,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -1138,7 +1138,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId2,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -1166,7 +1166,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId2,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -1228,7 +1228,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId2,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>@@ -1622,7 +1622,7 @@ describe("useCellNavigationProps", () => {selectionActions.select({ cellId: cellId1 });selectionActions.extend({cellId: cellId2,- allCellIds: store.get(notebookAtom).cellIds,+ layout: store.get(layoutAtom),});const { result } = renderWithProvider(() =>diff --git a/frontend/src/components/editor/navigation/__tests__/selection.test.ts b/frontend/src/components/editor/navigation/__tests__/selection.test.tsindex e8e2602676..23aebd8bc4 100644--- a/frontend/src/components/editor/navigation/__tests__/selection.test.ts+++ b/frontend/src/components/editor/navigation/__tests__/selection.test.ts@@ -2,7 +2,9 @@import { beforeEach, describe, expect, it } from "vitest";import { cellId } from "@/__tests__/branded";-import { MultiColumn } from "@/utils/id-tree";+import type { CellId } from "@/core/cells/ids";+import type { Layout } from "@/core/cells/layout";+import type { CellColumnId } from "@/utils/id-tree";import type { CellSelectionState } from "../selection";import { exportedForTesting } from "../selection";@@ -16,6 +18,14 @@ const CellIds = {e: cellId("e"),};+/** A one-column page of `ids`, with `hidden` folded away under the cell before them. */+function page(ids: CellId[], hidden: CellId[] = []): Layout {+ const visible = ids.filter((id) => !hidden.includes(id));+ return {+ columns: [{ id: "column" as CellColumnId, ids, visible, folds: new Map() }],+ };+}+describe("cell selection reducer", () => {let state: CellSelectionState;@@ -57,15 +67,13 @@ describe("cell selection reducer", () => {});it("should extend selection forward", () => {- const allCellIds = MultiColumn.from([- [CellIds.a, CellIds.b, CellIds.c, CellIds.d],- ]);+ const layout = page([CellIds.a, CellIds.b, CellIds.c, CellIds.d]);// First select cell aactions.select({ cellId: CellIds.a });// Then extend to cell c- actions.extend({ cellId: CellIds.c, allCellIds });+ actions.extend({ cellId: CellIds.c, layout });expect(state).toEqual({selectionStart: CellIds.a,@@ -75,15 +83,13 @@ describe("cell selection reducer", () => {});it("should extend selection backward", () => {- const allCellIds = MultiColumn.from([- [CellIds.a, CellIds.b, CellIds.c, CellIds.d],- ]);+ const layout = page([CellIds.a, CellIds.b, CellIds.c, CellIds.d]);// First select cell cactions.select({ cellId: CellIds.c });// Then extend to cell a (backward)- actions.extend({ cellId: CellIds.a, allCellIds });+ actions.extend({ cellId: CellIds.a, layout });expect(state).toEqual({selectionStart: CellIds.c,@@ -93,13 +99,13 @@ describe("cell selection reducer", () => {});it("should extend selection to same cell", () => {- const allCellIds = MultiColumn.from([[CellIds.a, CellIds.b, CellIds.c]]);+ const layout = page([CellIds.a, CellIds.b, CellIds.c]);// First select cell bactions.select({ cellId: CellIds.b });// Then extend to same cell- actions.extend({ cellId: CellIds.b, allCellIds });+ actions.extend({ cellId: CellIds.b, layout });expect(state).toEqual({selectionStart: CellIds.b,@@ -109,10 +115,10 @@ describe("cell selection reducer", () => {});it("should fallback to single select when extending without selectionStart", () => {- const allCellIds = MultiColumn.from([[CellIds.a, CellIds.b, CellIds.c]]);+ const layout = page([CellIds.a, CellIds.b, CellIds.c]);// Try to extend without any previous selection- actions.extend({ cellId: CellIds.b, allCellIds });+ actions.extend({ cellId: CellIds.b, layout });expect(state).toEqual({selectionStart: CellIds.b,@@ -122,11 +128,11 @@ describe("cell selection reducer", () => {});it("should fallback to single select when extending with invalid cell ids", () => {- const allCellIds = MultiColumn.from([[CellIds.a, CellIds.b, CellIds.c]]);+ const layout = page([CellIds.a, CellIds.b, CellIds.c]);- // Create a state with invalid selection start (not in allCellIds)+ // Create a state with invalid selection start (not on the page)const invalidState = {- selectionStart: CellIds.d, // not in allCellIds+ selectionStart: CellIds.d, // not on the pageselectionEnd: CellIds.d,selected: new Set([CellIds.d]),};@@ -134,7 +140,7 @@ describe("cell selection reducer", () => {// Test reducer directly since we need to start with custom stateconst result = reducer(invalidState, {type: "extend",- payload: { cellId: CellIds.b, allCellIds },+ payload: { cellId: CellIds.b, layout },});expect(result).toEqual({@@ -144,6 +150,19 @@ describe("cell selection reducer", () => {});});+ it("steps over the cells a fold hides", () => {+ const layout = page(+ [CellIds.a, CellIds.b, CellIds.c, CellIds.d, CellIds.e],+ [CellIds.b, CellIds.c],+ );++ actions.select({ cellId: CellIds.a });+ actions.extend({ cellId: CellIds.d, layout });++ expect(state.selected).toEqual(new Set([CellIds.a, CellIds.d]));+ expect(state.selectionEnd).toBe(CellIds.d);+ });+it("should clear selection", () => {// First select some cellsactions.select({ cellId: CellIds.a });@@ -171,19 +190,23 @@ describe("cell selection reducer", () => {});it("should handle complex selection scenarios", () => {- const allCellIds = MultiColumn.from([- [CellIds.a, CellIds.b, CellIds.c, CellIds.d, CellIds.e],+ const layout = page([+ CellIds.a,+ CellIds.b,+ CellIds.c,+ CellIds.d,+ CellIds.e,]);// Select middle cellactions.select({ cellId: CellIds.c });// Extend to end- actions.extend({ cellId: CellIds.e, allCellIds });+ actions.extend({ cellId: CellIds.e, layout });expect(state.selected).toEqual(new Set([CellIds.c, CellIds.d, CellIds.e]));// Extend to beginning (should reverse)- actions.extend({ cellId: CellIds.a, allCellIds });+ actions.extend({ cellId: CellIds.a, layout });expect(state.selected).toEqual(new Set([CellIds.a, CellIds.b, CellIds.c]));expect(state.selectionStart).toBe(CellIds.c);expect(state.selectionEnd).toBe(CellIds.a);diff --git a/frontend/src/components/editor/navigation/__tests__/state.test.ts b/frontend/src/components/editor/navigation/__tests__/state.test.tsdeleted file mode 100644index 06042d9ff7..0000000000--- a/frontend/src/components/editor/navigation/__tests__/state.test.ts+++ /dev/null@@ -1,81 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cellId } from "@/__tests__/branded";-import { type CellId, HTMLCellId } from "@/core/cells/ids";--const mockScrollCellIntoView = vi.fn();-const mockRaf2 = vi.fn((callback: () => void) => callback());--vi.mock("../focus-utils", () => ({- scrollCellIntoView: mockScrollCellIntoView,- raf2: mockRaf2,-}));--type TemporarilyShownCodeState = Set<CellId>;--describe("temporarilyShownCodeActions", () => {- const cid = cellId("cell-1");- let cellElement: HTMLElement;-- beforeEach(() => {- cellElement = document.createElement("div");- cellElement.id = HTMLCellId.create(cid);- document.body.append(cellElement);- cellElement.focus();-- vi.spyOn(HTMLCellId, "findElementThroughShadowDOMs").mockReturnValue(- cellElement as HTMLElement & { id: HTMLCellId },- );-- mockScrollCellIntoView.mockClear();- mockRaf2.mockClear();- });-- afterEach(() => {- cellElement.remove();- vi.restoreAllMocks();- });-- it("should scroll cell into view when removing cell causes layout shift", () => {- const state = new Set<CellId>([cid]);- removeCell(state, cid);-- expect(mockScrollCellIntoView).toHaveBeenCalledWith(cid);- });-- it("should not scroll when focused cell is not found", () => {- vi.spyOn(HTMLCellId, "findElementThroughShadowDOMs").mockReturnValue(null);-- const state = new Set<CellId>([cid]);- removeCell(state, cid);-- expect(mockScrollCellIntoView).not.toHaveBeenCalled();- });-});--// Helper function that replicates the remove reducer logic-function removeCell(- state: TemporarilyShownCodeState,- cellId: CellId,-): TemporarilyShownCodeState {- if (!state.has(cellId)) {- return state;- }- const newState = new Set(state);- newState.delete(cellId);-- mockRaf2(() => {- const activeElement = document.activeElement;- if (!activeElement) {- return;- }- const focusedCell = HTMLCellId.findElementThroughShadowDOMs(activeElement);- if (!focusedCell) {- return;- }- mockScrollCellIntoView(HTMLCellId.parse(focusedCell.id));- });-- return newState;-}diff --git a/frontend/src/components/editor/navigation/focus-utils.ts b/frontend/src/components/editor/navigation/focus-utils.tsindex 38de58f25e..950326171a 100644--- a/frontend/src/components/editor/navigation/focus-utils.ts+++ b/frontend/src/components/editor/navigation/focus-utils.ts@@ -3,6 +3,7 @@import type { createStore } from "jotai";import { getCellEditorView } from "@/core/cells/cells";import { type CellId, HTMLCellId } from "@/core/cells/ids";+import { scrollCellIntoView } from "@/core/cells/scrollCellIntoView";import { Logger } from "@/utils/Logger";export function focusCellEditor(@@ -38,6 +39,24 @@ export function raf2(callback: () => void): void {});}+/**+ * Keep the focused cell in view after a layout shift, such as its code being+ * hidden again.+ */+export function keepFocusedCellInView(): void {+ raf2(() => {+ const activeElement = document.activeElement;+ if (!activeElement) {+ return;+ }+ const focusedCell = HTMLCellId.findElementThroughShadowDOMs(activeElement);+ if (!focusedCell) {+ return;+ }+ scrollCellIntoView(HTMLCellId.parse(focusedCell.id));+ });+}+/*** Checks if the cell is focused at the top level.*/diff --git a/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx b/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsxindex b18acbda23..64f2e1c9ea 100644--- a/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx+++ b/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx@@ -30,12 +30,9 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";-import {- getCellEditorView,- hasOnlyOneCellAtom,- notebookAtom,-} from "@/core/cells/cells";+import { getCellEditorView, hasOnlyOneCellAtom } from "@/core/cells/cells";import { useCellActions } from "@/core/cells/actions";+import { columnOf, layoutAtom } from "@/core/cells/layout";import { useNotebookDocumentEdit } from "@/core/notebook/document";import type { CellId } from "@/core/cells/ids";import { usePendingDeleteService } from "@/core/cells/pending-delete-service";@@ -142,10 +139,8 @@ export function useMultiCellActionButtons(cellIds: CellId[]) {/// If moving down, make sure the last cell is not at the bottom of the notebookif (direction === "down") {const lastCellId = cellIds[cellIds.length - 1];- const notebook = store.get(notebookAtom);- const isLast =- notebook.cellIds.findWithId(lastCellId).last() === lastCellId;- if (isLast) {+ const layout = store.get(layoutAtom);+ if (columnOf(layout, lastCellId).visible.at(-1) === lastCellId) {return;}}@@ -153,10 +148,8 @@ export function useMultiCellActionButtons(cellIds: CellId[]) {// If moving up, make sure the first cell is not at the top of the notebookif (direction === "up") {const firstCellId = cellIds[0];- const notebook = store.get(notebookAtom);- const isFirst =- notebook.cellIds.findWithId(firstCellId).first() === firstCellId;- if (isFirst) {+ const layout = store.get(layoutAtom);+ if (columnOf(layout, firstCellId).visible[0] === firstCellId) {return;}}diff --git a/frontend/src/components/editor/navigation/navigation.ts b/frontend/src/components/editor/navigation/navigation.tsindex 669072d713..dbcf6cdd30 100644--- a/frontend/src/components/editor/navigation/navigation.ts+++ b/frontend/src/components/editor/navigation/navigation.ts@@ -13,7 +13,14 @@ import { mergeProps, useFocusWithin, useKeyboard } from "react-aria";import { DATA_FOR_CELL_ID } from "@/components/data-table/cell-utils";import { aiCompletionCellAtom } from "@/core/ai/state";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";-import { cellIdsAtom, notebookAtom } from "@/core/cells/cells";+import { notebookAtom } from "@/core/cells/cells";+import { hideShownCodeAtom, showHiddenCodeAtom } from "@/core/cells/editor";+import {+ columnOf,+ type LayoutColumn,+ layoutAtom,+ visibleNeighbor,+} from "@/core/cells/layout";import { useCellActions } from "@/core/cells/actions";import { useNotebookDocumentEdit } from "@/core/notebook/document";import { useCellFocusActions } from "@/core/cells/focus";@@ -40,18 +47,21 @@ import type { HotkeyAction } from "@/core/hotkeys/hotkeys";import { parseShortcut } from "@/core/hotkeys/shortcuts";import { useSaveNotebook } from "@/core/saving/save-component";import { Events } from "@/utils/events";-import type { CollapsibleTree } from "@/utils/id-tree";import type { CellActionsDropdownHandle } from "../cell/cell-actions";import { useDeleteManyCellsCallback } from "../cell/useDeleteCell";import { useRunCells } from "../cell/useRunCells";import { useCellClipboard } from "./clipboard";-import { focusCell, focusCellEditor, raf2 } from "./focus-utils";+import {+ focusCell,+ focusCellEditor,+ keepFocusedCellInView,+ raf2,+} from "./focus-utils";import {getSelectedCells,useCellSelectionActions,useIsCellSelected,} from "./selection";-import { useTemporarilyShownCodeActions } from "./state";import { handleVimKeybinding } from "./vim-bindings";interface HotkeyHandler {@@ -105,8 +115,7 @@ function useCellFocusProps(editorView: React.RefObject<EditorView | null>,) {const focusActions = useCellFocusActions();- const actions = useCellActions();- const temporarilyShownCodeActions = useTemporarilyShownCodeActions();+ const hideShownCode = useSetAtom(hideShownCodeAtom);// This occurs at the cell level and descedants.const { focusWithinProps } = useFocusWithin({@@ -131,9 +140,11 @@ function useCellFocusProps(return;}- // On blur, hide the code if it was temporarily shown.- temporarilyShownCodeActions.remove(cellId);- actions.markTouched({ cellId });+ // On blur, hide the code if it was showing for now. That shifts the+ // layout, so the cell that took the focus is kept in view.+ if (hideShownCode({ cellId })) {+ keepFocusedCellInView();+ }focusActions.blurCell();// Close signature help when clicking outside the cellif (editorView.current) {@@ -195,7 +206,7 @@ export function useCellNavigationProps(const actions = useCellActions();const { createCell, moveToNextCell } = useCellActions();const store = useStore();- const temporarilyShownCodeActions = useTemporarilyShownCodeActions();+ const showHiddenCode = useSetAtom(showHiddenCodeAtom);const runCells = useRunCells();const keymapPreset = useAtomValue(keymapPresetAtom);const { copyCells, pasteAtCell, cutCells } = useCellClipboard();@@ -268,12 +279,13 @@ export function useCellNavigationProps(// Move left across columnsArrowLeft: () => {if (canMoveX) {- const notebook = store.get(notebookAtom);- const column = notebook.cellIds.findWithId(cellId);- const columnIndex = notebook.cellIds.indexOf(column);- const leftColumn = notebook.cellIds.at(columnIndex - 1);+ const layout = store.get(layoutAtom);+ const columnIndex = layout.columns.indexOf(+ columnOf(layout, cellId),+ );+ const leftColumn = layout.columns[columnIndex - 1];- if (leftColumn && leftColumn.length > 0) {+ if (leftColumn && leftColumn.visible.length > 0) {const leftCellId = findClosestAdjacentCell(cellId, leftColumn);actions.focusCell({ cellId: leftCellId, where: "exact" });@@ -286,12 +298,13 @@ export function useCellNavigationProps(// Move right across columnsArrowRight: () => {if (canMoveX) {- const notebook = store.get(notebookAtom);- const column = notebook.cellIds.findWithId(cellId);- const columnIndex = notebook.cellIds.indexOf(column);- const rightColumn = notebook.cellIds.at(columnIndex + 1);+ const layout = store.get(layoutAtom);+ const columnIndex = layout.columns.indexOf(+ columnOf(layout, cellId),+ );+ const rightColumn = layout.columns[columnIndex + 1];- if (rightColumn && rightColumn.length > 0) {+ if (rightColumn && rightColumn.visible.length > 0) {const rightCellId = findClosestAdjacentCell(cellId, rightColumn);actions.focusCell({ cellId: rightCellId, where: "exact" });@@ -304,12 +317,12 @@ export function useCellNavigationProps(// Select up"Shift+ArrowUp": () => {// Select self- const allCellIds = store.get(cellIdsAtom);- selectionActions.extend({ cellId, allCellIds });+ const layout = store.get(layoutAtom);+ selectionActions.extend({ cellId, layout });// Select to where focus is going- const beforeCellId = allCellIds.findWithId(cellId).before(cellId);+ const beforeCellId = visibleNeighbor(layout, cellId, -1);if (beforeCellId) {- selectionActions.extend({ cellId: beforeCellId, allCellIds });+ selectionActions.extend({ cellId: beforeCellId, layout });}// Focus the cellactions.focusCell({ cellId, where: "before" });@@ -318,12 +331,12 @@ export function useCellNavigationProps(// Select down"Shift+ArrowDown": () => {// Select self- const allCellIds = store.get(cellIdsAtom);- selectionActions.extend({ cellId, allCellIds });+ const layout = store.get(layoutAtom);+ selectionActions.extend({ cellId, layout });// Select to where focus is going- const afterCellId = allCellIds.findWithId(cellId).after(cellId);+ const afterCellId = visibleNeighbor(layout, cellId, 1);if (afterCellId) {- selectionActions.extend({ cellId: afterCellId, allCellIds });+ selectionActions.extend({ cellId: afterCellId, layout });}// Focus the cellactions.focusCell({ cellId, where: "after" });@@ -345,7 +358,7 @@ export function useCellNavigationProps(},// Enter will focus the cell editor.Enter: () => {- temporarilyShownCodeActions.add(cellId);+ showHiddenCode({ cellId });focusCellEditor(store, cellId);selectionActions.clear();return true;@@ -398,10 +411,8 @@ export function useCellNavigationProps("cell.moveUp": addSingleHandler((cellIds) => {// If moving up, make sure the first cell is not at the top of the notebookconst firstCellId = cellIds[0];- const notebook = store.get(notebookAtom);- const isFirst =- notebook.cellIds.findWithId(firstCellId).first() === firstCellId;- if (isFirst) {+ const layout = store.get(layoutAtom);+ if (columnOf(layout, firstCellId).visible[0] === firstCellId) {return false;}@@ -413,10 +424,8 @@ export function useCellNavigationProps("cell.moveDown": addSingleHandler((cellIds) => {// If moving down, make sure the last cell is not at the bottom of the notebookconst lastCellId = cellIds[cellIds.length - 1];- const notebook = store.get(notebookAtom);- const isLast =- notebook.cellIds.findWithId(lastCellId).last() === lastCellId;- if (isLast) {+ const layout = store.get(layoutAtom);+ if (columnOf(layout, lastCellId).visible.at(-1) === lastCellId) {return false;}@@ -693,7 +702,7 @@ export function useCellEditorNavigationProps(cellId: CellId,editorView: React.RefObject<EditorView | null>,) {- const temporarilyShownCodeActions = useTemporarilyShownCodeActions();+ const hideShownCode = useSetAtom(hideShownCodeAtom);const keymapPreset = useAtomValue(keymapPresetAtom);const hotkeys = useAtomValue(hotkeysAtom);@@ -703,7 +712,7 @@ export function useCellEditorNavigationProps(}, [hotkeys]);const exitToCommandMode = () => {- temporarilyShownCodeActions.remove(cellId);+ hideShownCode({ cellId });focusCell(cellId);// Scroll to cell in case it is not in view because of layout shifts.raf2(() => {@@ -770,18 +779,18 @@ export function useCellEditorNavigationProps(function findClosestAdjacentCell(currentCellId: CellId,- adjacentColumn: CollapsibleTree<CellId>,+ adjacentColumn: LayoutColumn,): CellId {const current = document.getElementById(HTMLCellId.create(currentCellId));if (!current) {// fallback to first- return adjacentColumn.first();+ return adjacentColumn.visible[0];}const currentRect = current.getBoundingClientRect();// first to to either overlap or contain the current cell's top edge- for (const candidateId of adjacentColumn.topLevelIds) {+ for (const candidateId of adjacentColumn.visible) {const candidate = document.getElementById(HTMLCellId.create(candidateId));if (candidate) {const candidateRect = candidate.getBoundingClientRect();@@ -795,7 +804,7 @@ function findClosestAdjacentCell(}// no aligned cells (column beyond other), jump to last element- return adjacentColumn.last();+ return adjacentColumn.visible[adjacentColumn.visible.length - 1];}export function closeSignatureHelp(view: EditorView) {diff --git a/frontend/src/components/editor/navigation/selection.ts b/frontend/src/components/editor/navigation/selection.tsindex bb3c66f6d5..1db04656a4 100644--- a/frontend/src/components/editor/navigation/selection.ts+++ b/frontend/src/components/editor/navigation/selection.ts@@ -2,8 +2,8 @@import { atom, type createStore, useAtomValue } from "jotai";import { useMemo } from "react";import type { CellId } from "@/core/cells/ids";+import type { Layout } from "@/core/cells/layout";import { createReducerAndAtoms } from "@/utils/createReducer";-import type { MultiColumn } from "@/utils/id-tree";export interface CellSelectionState {selectionStart: CellId | null;@@ -34,43 +34,44 @@ const {selected: new Set([payload.cellId]),}),+ /**+ * Extend the selection from where it started to `cellId`, over the cells+ * the page shows between them. Cells a fold hides are stepped over, as+ * the focus steps over them.+ */extend: (state: CellSelectionState,- payload: {- cellId: CellId;- allCellIds: MultiColumn<CellId>;- },+ payload: { cellId: CellId; layout: Layout },): CellSelectionState => {- if (!state.selectionStart) {- // fallback to single select- return {- selectionStart: payload.cellId,- selectionEnd: payload.cellId,- selected: new Set([payload.cellId]),- };- }- const { cellId, allCellIds } = payload;-- try {- const column = allCellIds.findWithId(state.selectionStart);- const startIdx = column.indexOfOrThrow(state.selectionStart);- const endIdx = column.indexOfOrThrow(cellId);- const [from, to] =- startIdx < endIdx ? [startIdx, endIdx] : [endIdx, startIdx];- const selected = column.slice(from, to + 1);- return {- selectionStart: state.selectionStart,- selectionEnd: cellId,- selected: new Set(selected),- };- } catch {- // fallback to single select+ const { cellId, layout } = payload;+ const start = state.selectionStart;+ const column =+ start === null+ ? undefined+ : layout.columns.find((column) => column.visible.includes(start));+ const startIdx =+ start === null ? -1 : (column?.visible.indexOf(start) ?? -1);+ const endIdx = column?.visible.indexOf(cellId) ?? -1;+ if (+ start === null ||+ column === undefined ||+ startIdx === -1 ||+ endIdx === -1+ ) {+ // Nothing to extend from, or the cells are not on the page together.return {selectionStart: cellId,selectionEnd: cellId,selected: new Set([cellId]),};}+ const [from, to] =+ startIdx < endIdx ? [startIdx, endIdx] : [endIdx, startIdx];+ return {+ selectionStart: start,+ selectionEnd: cellId,+ selected: new Set(column.visible.slice(from, to + 1)),+ };},clear: (state: CellSelectionState): CellSelectionState => {diff --git a/frontend/src/components/editor/navigation/state.ts b/frontend/src/components/editor/navigation/state.tsdeleted file mode 100644index e28750c399..0000000000--- a/frontend/src/components/editor/navigation/state.ts+++ /dev/null@@ -1,65 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import { atom, useAtomValue } from "jotai";-import { useMemo } from "react";-import { type CellId, HTMLCellId } from "@/core/cells/ids";-import { scrollCellIntoView } from "@/core/cells/scrollCellIntoView";-import { createReducerAndAtoms } from "@/utils/createReducer";-import { raf2 } from "./focus-utils";--type TemporarilyShownCodeState = Set<CellId>;--// This previously used jotai-scope, but unfortunately this bug creates unnecessary work:-// https://github.com/jotaijs/jotai-scope/issues/25--const {- valueAtom: temporarilyShownCodeAtom,- useActions: useTemporarilyShownCodeActions,-} = createReducerAndAtoms(() => new Set<CellId>(), {- add: (state: TemporarilyShownCodeState, cellId: CellId) => {- if (state.has(cellId)) {- // no-op- return state;- }- const newState = new Set(state);- newState.add(cellId);- return newState;- },- remove: (state: TemporarilyShownCodeState, cellId: CellId) => {- if (!state.has(cellId)) {- // no-op- return state;- }- const newState = new Set(state);- newState.delete(cellId);-- // If we are hiding the code, this will cause a layout shift- // so we need to scroll cursor/activeElement into view.- raf2(() => {- // Get the active- const activeElement = document.activeElement;- if (!activeElement) {- return;- }- // Get the current focused cell id- const focusedCell =- HTMLCellId.findElementThroughShadowDOMs(activeElement);- if (!focusedCell) {- return;- }- scrollCellIntoView(HTMLCellId.parse(focusedCell.id));- });-- return newState;- },-});--const createTemporarilyShownCodeAtom = (cellId: CellId) =>- atom((get) => get(temporarilyShownCodeAtom).has(cellId));--export function useTemporarilyShownCode(cellId: CellId) {- const atom = useMemo(() => createTemporarilyShownCodeAtom(cellId), [cellId]);- return useAtomValue(atom);-}--export { temporarilyShownCodeAtom, useTemporarilyShownCodeActions };diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsxindex bc598cfccc..19fbb59d17 100644--- a/frontend/src/components/editor/notebook-cell.tsx+++ b/frontend/src/components/editor/notebook-cell.tsx@@ -16,7 +16,6 @@ import {useCallback,useEffect,useImperativeHandle,- useMemo,useRef,useState,} from "react";@@ -43,12 +42,15 @@ import { useResizeObserver } from "@/hooks/useResizeObserver";import { cn } from "@/utils/cn";import type { Milliseconds, Seconds } from "@/utils/time";import {- createUntouchedCellAtom,useCellData,useCellHandle,useCellRuntime,} from "../../core/cells/cells";import { type CellActions, useCellActions } from "../../core/cells/actions";+import {+ showHiddenCodeAtom,+ useShowsHiddenCode,+} from "../../core/cells/editor";import { type CellId, SETUP_CELL_ID } from "../../core/cells/ids";import {cellNeedsRun,@@ -85,10 +87,6 @@ import { useRunCell } from "./cell/useRunCells";import { cellDomProps } from "./common";import { SqlValidationErrorBanner } from "./errors/sql-validation-errors";import { useCellNavigationProps } from "./navigation/navigation";-import {- useTemporarilyShownCode,- useTemporarilyShownCodeActions,-} from "./navigation/state";import { type OnRefactorWithAI, OutputArea } from "./Output";import { ConsoleOutput } from "./output/console/ConsoleOutput";import { CellDragHandle, SortableCell } from "./SortableCell";@@ -167,15 +165,12 @@ function useCellHiddenLogic({editorView: React.RefObject<EditorView | null>;editorViewParentRef: React.RefObject<HTMLDivElement | null>;}) {- const temporarilyVisible = useTemporarilyShownCode(cellId);- const temporarilyShownCodeActions = useTemporarilyShownCodeActions();- const isUntouched = useAtomValue(- useMemo(() => createUntouchedCellAtom(cellId), [cellId]),- );+ const showsHiddenCode = useShowsHiddenCode(cellId);+ const showHiddenCodeNow = useSetAtom(showHiddenCodeAtom);- // The cell code is shown if the cell is not configured to be hidden or if the code is temporarily visible (i.e. when focused).- const isCellCodeShown =- !cellConfig.hide_code || temporarilyVisible || isUntouched;+ // The code is shown unless the cell hides it, and then still while it is+ // being edited or was just created.+ const isCellCodeShown = !cellConfig.hide_code || showsHiddenCode;const isMarkdown = languageAdapter === "markdown";const isMarkdownCodeHidden = isMarkdown && !isCellCodeShown;@@ -188,7 +183,7 @@ function useCellHiddenLogic({// Default to trueconst focus = opts?.focus ?? true;- temporarilyShownCodeActions.add(cellId);+ showHiddenCodeNow({ cellId });if (focus) {editorView.current?.focus();@@ -219,7 +214,6 @@ export type CellComponentActions = Pick<| "moveCell"| "collapseCell"| "expandCell"- | "clearSerializedEditorState"| "setStdinResponse"| "clearCellConsoleOutput"| "sendToBottom"@@ -704,7 +698,6 @@ const EditableCellComponent = ({code={cellData.code}config={cellData.config}status={cellRuntime.status}- serializedEditorState={cellData.serializedEditorState}runCell={runCell}setEditorView={setEditorView}userConfig={userConfig}@@ -1233,7 +1226,6 @@ const SetupCellComponent = ({code={cellData.code}config={cellData.config}status={cellRuntime.status}- serializedEditorState={cellData.serializedEditorState}runCell={runCell}setEditorView={setEditorView}userConfig={userConfig}diff --git a/frontend/src/components/editor/renderers/cell-array.tsx b/frontend/src/components/editor/renderers/cell-array.tsxindex fa625d537e..daddeeee8a 100644--- a/frontend/src/components/editor/renderers/cell-array.tsx+++ b/frontend/src/components/editor/renderers/cell-array.tsx@@ -29,6 +29,7 @@ import { canInteractWithAppAtom } from "@/core/network/connection";import { useBoolean } from "@/hooks/useBoolean";import { cn } from "@/utils/cn";import { Functions } from "@/utils/functions";+import { findColumn, useLayout } from "@/core/cells/layout";import type { CellColumnId } from "@/utils/id-tree";import { invariant } from "@/utils/invariant";import {@@ -188,7 +189,7 @@ const CellColumn: React.FC<{hideControls,}) => {const cellIds = useCellIds();- const column = cellIds.get(columnId);+ const column = findColumn(useLayout(), columnId);invariant(column, `Expected column for: ${columnId}`);const hasOnlyOneCell = cellIds.hasOnlyOneId();@@ -218,7 +219,7 @@ const CellColumn: React.FC<{><SortableContextid={`column-${index + 1}`}- items={column.topLevelIds}+ items={[...column.visible]}strategy={verticalListSortingStrategy}>{/* Render the setup cell first, always */}@@ -237,7 +238,7 @@ const CellColumn: React.FC<{/>)}- {column.topLevelIds.map((cellId) => {+ {column.visible.map((cellId) => {// Skip the setup cell laterif (cellId === SETUP_CELL_ID) {return null;@@ -252,8 +253,8 @@ const CellColumn: React.FC<{canDelete={!hasOnlyOneCell}mode={mode}userConfig={userConfig}- isCollapsed={column.isCollapsed(cellId)}- collapseCount={column.getCount(cellId)}+ isCollapsed={column.folds.has(cellId)}+ collapseCount={column.folds.get(cellId)?.length ?? 0}canMoveX={appConfig.width === "columns"}/>);diff --git a/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts b/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.tsindex 802679ed91..1c462a164d 100644--- a/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts+++ b/frontend/src/components/editor/renderers/slides-layout/__tests__/plugin.test.ts@@ -17,7 +17,6 @@ function makeCell(id: string, code = "print('hi')"): CellData {lastCodeRun: null,lastExecutionTime: null,config: { hide_code: false, disabled: false, column: null },- serializedEditorState: null,};}diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex dfae9bb998..8ceea25afd 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -81,7 +81,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({getInitialShowCode({ showCodeInRunModePreference, kioskMode }),);- const canShowCode = useNotebookCodeAvailable(cells);+ const canShowCode = useNotebookCodeAvailable();const handleToggleShowCode = () => {setShowCode((currentShowCode) => {diff --git a/frontend/src/components/pages/edit-page.tsx b/frontend/src/components/pages/edit-page.tsxindex 09e23e5627..7cf95f8025 100644--- a/frontend/src/components/pages/edit-page.tsx+++ b/frontend/src/components/pages/edit-page.tsx@@ -1,14 +1,10 @@/* Copyright 2026 Marimo. All rights reserved. */-import { useSetAtom, useStore } from "jotai";-import { notebookAtom } from "@/core/cells/cells";-import { notebookCells } from "@/core/cells/utils";import type { AppConfig, UserConfig } from "@/core/config/config-schema";import { KnownQueryParams } from "@/core/constants";import { EditApp } from "@/core/edit-app";import { getSessionId } from "@/core/kernel/session";import { DocumentProvider } from "@/core/notebook/document";-import { lastSavedNotebookAtom } from "@/core/saving/state";import { useNotebookSession } from "@/core/session/useNotebookSession";import { AppChrome } from "../editor/chrome/wrapper/app-chrome";@@ -24,17 +20,8 @@ const hideChrome = (() => {/** Own the notebook session and provide its document model to the editor and its chrome. */const EditPage = (props: Props) => {- const store = useStore();- const setLastSavedNotebook = useSetAtom(lastSavedNotebookAtom);const { connection, reconnect, documentModel } = useNotebookSession({autoInstantiate: props.userConfig.runtime.auto_instantiate,- 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);- setLastSavedNotebook({ names, codes, configs, layout });- },sessionId: getSessionId(),});const app = (diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsxindex 3210d141c2..c8d509543e 100644--- a/frontend/src/components/scratchpad/scratchpad.tsx+++ b/frontend/src/components/scratchpad/scratchpad.tsx@@ -259,7 +259,6 @@ export const ScratchPad: React.FC = () => {code={code}config={scratchpadCellConfig}status="idle"- serializedEditorState={null}runCell={handleRun}userConfig={userConfig}editorViewRef={ref}diff --git a/frontend/src/components/slides/reveal-component.tsx b/frontend/src/components/slides/reveal-component.tsxindex 50dd0839fc..f323b01541 100644--- a/frontend/src/components/slides/reveal-component.tsx+++ b/frontend/src/components/slides/reveal-component.tsx@@ -519,7 +519,7 @@ const RevealSlidesComponent = ({const [showCodeOverrides, setShowCodeOverrides] = useState<ReadonlySet<CellId>>(() => new Set());- const codeAvailable = useNotebookCodeAvailable(slideCells);+ const codeAvailable = useNotebookCodeAvailable();const codeRenderingEnabled = !isIslands() && codeAvailable;const isSpeakerReceiver = isSpeakerViewReceiver(kioskMode,diff --git a/frontend/src/components/slides/slide-cell-view.tsx b/frontend/src/components/slides/slide-cell-view.tsxindex 56161967c8..586fb4387c 100644--- a/frontend/src/components/slides/slide-cell-view.tsx+++ b/frontend/src/components/slides/slide-cell-view.tsx@@ -149,7 +149,6 @@ export const SlideCellView = ({ cell }: { cell: RuntimeCell }) => {code={cell.code}config={cell.config}status={cell.status}- serializedEditorState={cell.serializedEditorState}runCell={runCell}setEditorView={(ev) => {editorViewRef.current = ev;diff --git a/frontend/src/components/sort/SortableCellsProvider.tsx b/frontend/src/components/sort/SortableCellsProvider.tsxindex b6df2847c6..9997db977a 100644--- a/frontend/src/components/sort/SortableCellsProvider.tsx+++ b/frontend/src/components/sort/SortableCellsProvider.tsx@@ -25,6 +25,8 @@ import { Arrays } from "@/utils/arrays";import type { CellColumnId, MultiColumn } from "@/utils/id-tree";import { invariant } from "@/utils/invariant";import { getNotebook } from "../../core/cells/cells";+import { findColumn, layoutAtom } from "../../core/cells/layout";+import { store } from "../../core/state/jotai";import { useCellActions } from "../../core/cells/actions";import { useEvent } from "../../hooks/useEvent";@@ -52,7 +54,7 @@ const SortableCellsProviderInternal = ({null,);- const [config] = useAppConfig();+ const config = useAppConfig();const modifiers = useMemo(() => {if (config.width === "columns") {return Arrays.EMPTY;@@ -136,16 +138,15 @@ const SortableCellsProviderInternal = ({invariant(isColumnId(overId), `Expected column id. Got: ${overId}`);// If column is empty, we can drop on it- const notebook = getNotebook();- const column = notebook.cellIds.get(overId);+ const column = findColumn(store.get(layoutAtom), overId);invariant(column, `Expected column. Got: ${overId}`);- if (column && column.topLevelIds.length === 0) {+ if (column.visible.length === 0) {// Return the columnreturn [{ id: overId }];}// If the column is not empty, we only consider the cells in the same column- const cellIdSet = new Set(column.topLevelIds);+ const cellIdSet = new Set(column.visible);const collisions = closestCenter({...args,droppableContainers: args.droppableContainers.filter(diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsxindex 235dc09936..792110d60b 100644--- a/frontend/src/core/MarimoApp.tsx+++ b/frontend/src/core/MarimoApp.tsx@@ -59,7 +59,7 @@ export function preloadPage(mode: string) {*/export const MarimoApp: React.FC = memo(() => {const [userConfig] = useResolvedMarimoConfig();- const [appConfig] = useAppConfig();+ const appConfig = useAppConfig();const editorFontSize = toRem(userConfig.display.code_editor_font_size);const renderBody = () => {diff --git a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snapindex 027b977dd9..eed0d98bc5 100644--- a/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap+++ b/frontend/src/core/cells/__tests__/__snapshots__/cells.test.ts.snap@@ -23,7 +23,6 @@ exports[`cell reducer > can initialize stdin > initial state 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -53,7 +52,6 @@ exports[`cell reducer > can initialize stdin > prepared for run 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": false,@@ -83,7 +81,6 @@ exports[`cell reducer > can initialize stdin > queued message received 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": false,@@ -113,7 +110,6 @@ exports[`cell reducer > can initialize stdin > running message received 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -165,7 +161,6 @@ exports[`cell reducer > can initialize stdin > second stdin requested 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -210,7 +205,6 @@ exports[`cell reducer > can initialize stdin > stdin answered 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -254,7 +248,6 @@ exports[`cell reducer > can initialize stdin > stdin requested 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -291,7 +284,6 @@ exports[`cell reducer > can initialize stdin > stdout received 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -328,7 +320,6 @@ exports[`cell reducer > can initialize stdin > stdout verified 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -358,7 +349,6 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -395,7 +385,6 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"output": null,"runElapsedTimeMs": 2000,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -425,7 +414,6 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -462,7 +450,6 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": false,@@ -499,7 +486,6 @@ exports[`cell reducer > can receive console when the cell is idle and will clear"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": false,@@ -529,7 +515,6 @@ exports[`cell reducer > can run a stale cell > queued message received 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": false,@@ -559,7 +544,6 @@ exports[`cell reducer > can run a stale cell > stale inputs received 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": true,"status": "queued","stopped": false,@@ -600,7 +584,6 @@ exports[`cell reducer > can run a stopped cell > ancestor stopped 1`] = `},"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": true,@@ -630,7 +613,6 @@ exports[`cell reducer > can run a stopped cell > idle message received 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -671,7 +653,6 @@ exports[`cell reducer > can run a stopped cell > queued after stop 1`] = `},"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": true,@@ -701,7 +682,6 @@ exports[`cell reducer > can run a stopped cell > queued message received 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": false,@@ -731,7 +711,6 @@ exports[`cell reducer > can run a stopped cell > running after stop 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 40,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -774,7 +753,6 @@ import numpy",},"runElapsedTimeMs": 13000,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -804,7 +782,6 @@ exports[`cell reducer > can run cell and receive cell messages > code edited 1`]"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -847,7 +824,6 @@ import numpy",},"runElapsedTimeMs": 13000,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -889,7 +865,6 @@ exports[`cell reducer > can run cell and receive cell messages > code reverted 1},"runElapsedTimeMs": 13000,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -926,7 +901,6 @@ exports[`cell reducer > can run cell and receive cell messages > console message"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -976,7 +950,6 @@ import numpy",},"runElapsedTimeMs": 11000,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -1006,7 +979,6 @@ exports[`cell reducer > can run cell and receive cell messages > initial state 1"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -1054,7 +1026,6 @@ import numpy",},"runElapsedTimeMs": 11000,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -1096,7 +1067,6 @@ exports[`cell reducer > can run cell and receive cell messages > output received},"runElapsedTimeMs": 13000,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -1126,7 +1096,6 @@ exports[`cell reducer > can run cell and receive cell messages > prepared for ru"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": false,@@ -1156,7 +1125,6 @@ exports[`cell reducer > can run cell and receive cell messages > queued message"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": false,@@ -1186,7 +1154,6 @@ exports[`cell reducer > can run cell and receive cell messages > running message"output": null,"runElapsedTimeMs": null,"runStartTimestamp": 20,- "serializedEditorState": null,"staleInputs": false,"status": "running","stopped": false,@@ -1216,7 +1183,6 @@ exports[`cell reducer > errors reset status to idle > code edited 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -1257,7 +1223,6 @@ exports[`cell reducer > errors reset status to idle > error response received 1`},"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -1287,7 +1252,6 @@ exports[`cell reducer > errors reset status to idle > initial state 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "idle","stopped": false,@@ -1317,7 +1281,6 @@ exports[`cell reducer > errors reset status to idle > prepared for run 1`] = `"output": null,"runElapsedTimeMs": null,"runStartTimestamp": null,- "serializedEditorState": null,"staleInputs": false,"status": "queued","stopped": false,diff --git a/frontend/src/core/cells/__tests__/actions.test.ts b/frontend/src/core/cells/__tests__/actions.test.tsindex 406a8ffa22..e2b7015795 100644--- a/frontend/src/core/cells/__tests__/actions.test.ts+++ b/frontend/src/core/cells/__tests__/actions.test.ts@@ -1,36 +1,39 @@/* Copyright 2026 Marimo. All rights reserved. */-import { history } from "@codemirror/commands";-import { EditorState } from "@codemirror/state";-import { EditorView } from "@codemirror/view";import type * as Protocol from "@marimo-team/client/protocol";-import { createStore } from "jotai";import { afterEach, describe, expect, it, vi } from "vitest";-import { mockDocumentModel } from "@/__mocks__/document";import { cellId } from "@/__tests__/branded";-import {- cell,- CONFIG,- document as documentOf,- withCells,-} from "@/core/notebook/document/__tests__/fixtures";+import { createStore } from "jotai";+import { cell, CONFIG } from "@/core/notebook/document/__tests__/fixtures";import type { CellIndex } from "@/utils/id-tree";import {addSetupCellAtom,+ collapseAllCellsAtom,+ collapseCellAtom,createCellAtom,deleteCellsAtom,+ expandAllCellsAtom,+ expandCellAtom,+ focusCellAtom,moveToNextCellAtom,+ showCellIfHiddenAtom,undoDeleteCellAtom,} from "../actions";+import { moveCellsRelativeToAtom } from "../arrange";import {cellDataAtom,cellHandleAtom,exportedForTesting,notebookAtom,- notebookReducer,} from "../cells";-import { followDocument } from "../document";+import {+ hideShownCodeAtom,+ restoredEditorStatesAtom,+ shownHiddenCodeAtom,+} from "../editor";+import { collapsedAtom, layoutAtom } from "../layout";import { type CellId, SCRATCH_CELL_ID, SETUP_CELL_ID } from "../ids";+import { setupNotebook } from "./harness";import { focusAndScrollCellIntoView } from "../scrollCellIntoView";vi.mock("../scrollCellIntoView", () => ({@@ -49,53 +52,8 @@ afterEach(() => {vi.clearAllMocks();});-/** A store whose notebook follows a document model, as the session wires it. */-function setup(cells?: Record<string, Protocol.Cell | null>) {- const store = createStore();- store.set(notebookAtom, exportedForTesting.initialNotebookState());- const { model, stop } = mockDocumentModel(- store,- cells ? withCells(documentOf(), cells) : documentOf(),- );- const controller = new AbortController();- stops.push(stop, () => controller.abort());- followDocument({- store,- model,- reconcile: (document) =>- store.set(notebookAtom, (state) =>- notebookReducer(state, {- type: "reconcileDocument",- payload: document,- }),- ),- signal: controller.signal,- });- return {- store,- model,- order: () => store.get(notebookAtom).cellIds.inOrderIds,- notebook: () => store.get(notebookAtom),- cellIn: (id: string) => store.get(model.documentAtom)?.cells.get(id),- /** Give a cell an editor, as mounting it would. */- mountEditor: (id: string) => {- const view = new EditorView({- state: EditorState.create({- doc: store.get(model.documentAtom)?.cells.get(id)?.code ?? "",- extensions: [history()],- }),- });- store.get(notebookAtom).cellHandles[id as never].current = {- editorView: view,- editorViewOrNull: view,- };- return view;- },- /** Apply a reducer action, as `useReducerActions()` does. */- dispatch: (action: Parameters<typeof notebookReducer>[1]) =>- store.set(notebookAtom, (state) => notebookReducer(state, action)),- };-}+const setup = (cells?: Record<string, Protocol.Cell | null>) =>+ setupNotebook(stops, cells);describe("createCellAtom", () => {it("creates a cell after another and focuses it once it mounts", () => {@@ -131,8 +89,8 @@ describe("createCellAtom", () => {focus: false,});- expect(notebook().untouchedNewCells.has(hidden as never)).toBe(true);- expect(notebook().untouchedNewCells.has(unfocused as never)).toBe(false);+ expect(store.get(shownHiddenCodeAtom).has(hidden as CellId)).toBe(true);+ expect(store.get(shownHiddenCodeAtom).has(unfocused as CellId)).toBe(false);expect(notebook().scrollKey).toBe(hidden);});@@ -351,18 +309,20 @@ describe("deleteCellsAtom", () => {expect(notebook().cellIds.atOrThrow(1).inOrderIds).toEqual([c3]);});- it("forgets the untouched state and the cell atoms of a deleted cell", () => {- const { store, notebook } = setup();+ it("forgets a deleted cell's editor-only state and its atoms", () => {+ const { store } = setup();const id = store.set(createCellAtom, {after: c1,config: { hide_code: true },}) as CellId;+ store.set(restoredEditorStatesAtom, new Map([[id, { doc: "" }]]));const dataAtom = cellDataAtom(id);const handleAtom = cellHandleAtom(id);store.set(deleteCellsAtom, { cellIds: [id] });- expect(notebook().untouchedNewCells.has(id)).toBe(false);+ expect(store.get(shownHiddenCodeAtom).has(id)).toBe(false);+ expect(store.get(restoredEditorStatesAtom).has(id)).toBe(false);expect(cellDataAtom(id)).not.toBe(dataAtom);expect(cellHandleAtom(id)).not.toBe(handleAtom);});@@ -382,7 +342,7 @@ describe("undoDeleteCellAtom", () => {expect(order()).toEqual([c1, c2, c3]);expect(cellIn(c2)?.code).toBe("y = 2");- expect(notebook().cellData[c2].serializedEditorState).toMatchObject({+ expect(store.get(restoredEditorStatesAtom).get(c2)).toMatchObject({doc: "y = 2",});expect(notebook().cellData[c2].edited).toBe(true);@@ -423,25 +383,20 @@ describe("undoDeleteCellAtom", () => {});it("undoes a move recorded in the history", () => {- const { store, model, order, notebook, dispatch } = setup({+ const { store, order, notebook } = setup({c3: cell("c3", "z = 3"),});const column = notebook().cellIds.atOrThrow(0);- dispatch({- type: "moveCellsRelativeTo",- payload: {- cellIds: [c1, c2],- targetCellId: c3,- position: "after",- previousPlacements: [- { columnId: column.id, index: 0 as CellIndex },- { columnId: column.id, index: 1 as CellIndex },- ],- },+ store.set(moveCellsRelativeToAtom, {+ cellIds: [c1, c2],+ targetCellId: c3,+ position: "after",+ previousPlacements: [+ { columnId: column.id, index: 0 as CellIndex },+ { columnId: column.id, index: 1 as CellIndex },+ ],});expect(order()).toEqual([c3, c1, c2]);- // The middleware would write the order to the document.- store.set(model.editAtom, (tx) => tx.setOrder([c3, c1, c2]));store.set(deleteCellsAtom, { cellIds: [c3] });expect(order()).toEqual([c1, c2]);@@ -486,3 +441,158 @@ describe("undoDeleteCellAtom", () => {expect(order()).toEqual([c1, c2]);});});++describe("folding", () => {+ it("folds a header's section and unfolds it, focusing the header", () => {+ const { store, notebook, visible, heading } = setup({+ c3: cell("c3", "z = 3"),+ });+ heading(c1, 1);++ store.set(collapseCellAtom, { cellId: c1 });+ expect(visible()).toEqual([c1]);+ expect(store.get(layoutAtom).columns[0].folds.get(c1)).toEqual([c2, c3]);+ expect(notebook().scrollKey).toBe(c1);++ store.set(expandCellAtom, { cellId: c1 });+ expect(visible()).toEqual([c1, c2, c3]);+ expect(store.get(collapsedAtom).size).toBe(0);+ });++ it("creates after a folded header below its fold and opens the section", () => {+ const { store, order, visible, heading } = setup({+ c3: cell("c3", "z = 3"),+ });+ heading(c1, 1);+ store.set(collapseCellAtom, { cellId: c1 });++ const id = store.set(createCellAtom, { after: c1, code: "w = 4" });++ // The section runs to the next heading, so the new cell is in it.+ expect(order()).toEqual([c1, c2, c3, id]);+ expect(visible()).toEqual([c1, c2, c3, id]);+ expect(store.get(collapsedAtom).size).toBe(0);+ });++ it("opens every section a new cell lands in", () => {+ const { store, order, visible, heading } = setup({+ c3: cell("c3", "z = 3"),+ });+ heading(c1, 1);+ heading(c2, 2);+ store.set(collapseAllCellsAtom);++ // After the H1, the cell lands past the folded H2 too, inside both.+ const id = store.set(createCellAtom, { after: c1, code: "w = 4" });++ expect(order()).toEqual([c1, c2, c3, id]);+ expect(visible()).toEqual([c1, c2, c3, id]);+ expect(store.get(collapsedAtom).size).toBe(0);+ });++ it("opens the fold a cell created before or at the end lands in", () => {+ const { store, order, visible, heading } = setup({+ c3: cell("c3", "z = 3"),+ });+ heading(c1, 1);+ heading(c3, 1);+ store.set(collapseCellAtom, { cellId: c1 });++ // Before the second header, the cell follows the first header's fold.+ const before = store.set(createCellAtom, { before: c3, code: "w = 4" });+ expect(order()).toEqual([c1, c2, before, c3]);+ expect(visible()).toEqual([c1, c2, before, c3]);++ store.set(collapseCellAtom, { cellId: c3 });+ expect(visible()).toEqual([c1, c2, before, c3]);++ // At the end of the column, the cell falls under the last header.+ const end = store.set(createCellAtom, { code: "v = 5" });+ expect(order()).toEqual([c1, c2, before, c3, end]);+ expect(visible()).toEqual([c1, c2, before, c3, end]);+ expect(store.get(collapsedAtom).size).toBe(0);+ });++ it("leaves a fold closed over a cell created without focus", () => {+ const { store, order, visible, heading } = setup({+ c3: cell("c3", "z = 3"),+ });+ heading(c1, 1);+ store.set(collapseCellAtom, { cellId: c1 });++ const id = store.set(createCellAtom, {+ after: c1,+ code: "w = 4",+ focus: false,+ });++ expect(order()).toEqual([c1, c2, c3, id]);+ expect(visible()).toEqual([c1]);+ });++ it("does not fold a cell without a heading", () => {+ const { store, visible } = setup();++ store.set(collapseCellAtom, { cellId: c1 });++ expect(visible()).toEqual([c1, c2]);+ expect(store.get(collapsedAtom).size).toBe(0);+ });++ it("folds and unfolds every section", () => {+ const { store, visible, heading } = setup({ c3: cell("c3", "z = 3") });+ heading(c1, 1);+ heading(c2, 2);++ store.set(collapseAllCellsAtom);+ expect(visible()).toEqual([c1]);+ expect([...store.get(collapsedAtom)]).toEqual([c1, c2]);++ store.set(expandAllCellsAtom);+ expect(visible()).toEqual([c1, c2, c3]);+ });++ it("unfolds whatever hides a cell", () => {+ const { store, visible, heading } = setup({ c3: cell("c3", "z = 3") });+ heading(c1, 1);+ heading(c2, 2);+ store.set(collapseAllCellsAtom);++ store.set(showCellIfHiddenAtom, { cellId: c3 });++ expect(visible()).toEqual([c1, c2, c3]);+ expect(store.get(collapsedAtom).size).toBe(0);+ });++ it("moves focus over folded cells", () => {+ const { store, heading } = setup({ c3: cell("c3", "z = 3") });+ heading(c2, 1);+ store.set(collapseCellAtom, { cellId: c2 });++ store.set(focusCellAtom, { cellId: c1, where: "after" });+ expect(focusAndScrollCellIntoView).toHaveBeenLastCalledWith(+ expect.objectContaining({ cellId: c2, codeFocus: "top" }),+ );++ store.set(moveToNextCellAtom, { cellId: c2, before: false, create: false });+ expect(focusAndScrollCellIntoView).toHaveBeenCalledTimes(1);+ });+});++describe("hidden code showing for now", () => {+ it("shows a new hidden cell's code until it is hidden again", () => {+ const { store } = setup();+ const id = store.set(createCellAtom, {+ after: c1,+ config: { hide_code: true },+ }) as CellId;+ expect(store.get(shownHiddenCodeAtom).has(id)).toBe(true);++ const before = store.get(shownHiddenCodeAtom);+ store.set(hideShownCodeAtom, { cellId: id });+ store.set(hideShownCodeAtom, { cellId: id });++ expect(store.get(shownHiddenCodeAtom).has(id)).toBe(false);+ expect(store.get(shownHiddenCodeAtom)).not.toBe(before);+ });+});diff --git a/frontend/src/core/cells/__tests__/arrange.test.ts b/frontend/src/core/cells/__tests__/arrange.test.tsnew file mode 100644index 0000000000..27ca8232a9--- /dev/null+++ b/frontend/src/core/cells/__tests__/arrange.test.ts@@ -0,0 +1,263 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type * as Protocol from "@marimo-team/client/protocol";+import { afterEach, describe, expect, it, vi } from "vitest";+import { cellId } from "@/__tests__/branded";+import { cell, CONFIG } from "@/core/notebook/document/__tests__/fixtures";+import type { CellIndex } from "@/utils/id-tree";+import { collapseCellAtom, undoDeleteCellAtom } from "../actions";+import {+ dropCellOverCellAtom,+ dropCellOverColumnAtom,+ moveCellAtom,+ moveCellsRelativeToAtom,+ moveCellToIndexAtom,+ sendToBottomAtom,+ sendToTopAtom,+} from "../arrange";+import { layoutAtom } from "../layout";+import { setupNotebook } from "./harness";++vi.mock("../scrollCellIntoView", () => ({+ focusAndScrollCellIntoView: vi.fn(),+}));++const c1 = cellId("c1");+const c2 = cellId("c2");+const c3 = cellId("c3");+const c4 = cellId("c4");+const stops: Array<() => void> = [];++afterEach(() => {+ for (const stop of stops.splice(0)) {+ stop();+ }+});++const setup = (cells?: Record<string, Protocol.Cell | null>) =>+ setupNotebook(stops, cells);++/** Four cells, the last two in a second column. */+function twoColumns() {+ return setup({+ c3: cell("c3", "z = 3", { config: { ...CONFIG, column: 1 } }),+ c4: cell("c4", "w = 4"),+ });+}++describe("moveCellAtom", () => {+ it("moves a cell up and down its column and focuses it", () => {+ const { store, order, notebook } = setup({ c3: cell("c3", "z = 3") });++ store.set(moveCellAtom, { cellId: c3, before: true });+ expect(order()).toEqual([c1, c3, c2]);+ expect(notebook().scrollKey).toBe(c3);++ store.set(moveCellAtom, { cellId: c3, before: false });+ expect(order()).toEqual([c1, c2, c3]);+ });++ it("stays at the edge of its column, still focusing", () => {+ const { store, order, notebook } = setup();+ store.set(moveCellAtom, { cellId: c1, before: true });+ expect(order()).toEqual([c1, c2]);+ expect(notebook().scrollKey).toBe(c1);+ });++ it("carries a folded header's section with it", () => {+ const { store, order, visible, heading } = setup({+ c3: cell("c3", "z = 3"),+ c4: cell("c4", "w = 4"),+ });+ heading(c2, 1);+ store.set(collapseCellAtom, { cellId: c2 });+ expect(visible()).toEqual([c1, c2]);++ store.set(moveCellAtom, { cellId: c2, before: true });++ expect(order()).toEqual([c2, c3, c4, c1]);+ // The section runs to the next heading, so the cell it passed joins it.+ expect(visible()).toEqual([c2]);+ });++ it("steps over a folded section below it", () => {+ const { store, order, heading } = setup({+ c3: cell("c3", "z = 3"),+ c4: cell("c4", "w = 4"),+ });+ heading(c2, 1);+ store.set(collapseCellAtom, { cellId: c2 });++ store.set(moveCellAtom, { cellId: c1, before: false });+ expect(order()).toEqual([c2, c3, c4, c1]);+ });++ it("moves to the start of the neighbouring column and names it", () => {+ const { store, columns, cellIn } = twoColumns();+ expect(columns()).toEqual([+ [c1, c2],+ [c3, c4],+ ]);++ store.set(moveCellAtom, { cellId: c2, direction: "right" });+ expect(columns()).toEqual([[c1], [c2, c3, c4]]);+ expect(cellIn(c2)?.config.column).toBe(1);+ expect(cellIn(c3)?.config.column).toBeNull();++ store.set(moveCellAtom, { cellId: c2, direction: "left" });+ expect(columns()).toEqual([+ [c2, c1],+ [c3, c4],+ ]);+ expect(cellIn(c2)?.config.column).toBe(0);+ });++ it("does nothing past the last column", () => {+ const { store, model, columns } = twoColumns();+ const before = store.get(model.documentAtom);+ store.set(moveCellAtom, { cellId: c3, direction: "right" });+ expect(store.get(model.documentAtom)).toBe(before);+ expect(columns()).toEqual([+ [c1, c2],+ [c3, c4],+ ]);+ });+});++describe("sendToTopAtom and sendToBottomAtom", () => {+ it("move a cell to the ends of its column", () => {+ const { store, order, notebook } = setup({ c3: cell("c3", "z = 3") });++ store.set(sendToBottomAtom, { cellId: c1 });+ expect(order()).toEqual([c2, c3, c1]);+ expect(notebook().scrollKey).toBe(c1);++ store.set(sendToTopAtom, { cellId: c1, scroll: false });+ expect(order()).toEqual([c1, c2, c3]);+ });++ it("send a folded header with its section and leave an edge cell alone", () => {+ const { store, model, order, heading } = setup({+ c3: cell("c3", "z = 3"),+ });+ heading(c1, 1);+ store.set(collapseCellAtom, { cellId: c1 });+ const before = store.get(model.documentAtom);++ store.set(sendToTopAtom, { cellId: c1 });+ expect(store.get(model.documentAtom)).toBe(before);++ store.set(sendToBottomAtom, { cellId: c1 });+ expect(order()).toEqual([c1, c2, c3]);+ });+});++describe("drag and drop", () => {+ it("drops a cell where another cell is, in its own column", () => {+ const { store, order } = setup({ c3: cell("c3", "z = 3") });+ store.set(dropCellOverCellAtom, { cellId: c1, overCellId: c3 });+ expect(order()).toEqual([c2, c3, c1]);+ store.set(dropCellOverCellAtom, { cellId: c1, overCellId: c2 });+ expect(order()).toEqual([c1, c2, c3]);+ });++ it("drops a cell before another cell in another column", () => {+ const { store, columns, cellIn } = twoColumns();+ store.set(dropCellOverCellAtom, { cellId: c1, overCellId: c4 });+ expect(columns()).toEqual([[c2], [c3, c1, c4]]);+ expect(cellIn(c2)?.config.column).toBe(0);+ expect(cellIn(c3)?.config.column).toBe(1);+ });++ it("drops a cell at the start of a column", () => {+ const { store, columns } = twoColumns();+ const column = store.get(layoutAtom).columns[0].id;+ store.set(dropCellOverColumnAtom, { cellId: c4, columnId: column });+ expect(columns()).toEqual([[c4, c1, c2], [c3]]);+ });++ it("ignores a drop on a column that is gone", () => {+ const { store, model, columns } = twoColumns();+ const before = store.get(model.documentAtom);+ store.set(dropCellOverColumnAtom, {+ cellId: c4,+ columnId: "gone" as never,+ });+ expect(store.get(model.documentAtom)).toBe(before);+ expect(columns()).toEqual([+ [c1, c2],+ [c3, c4],+ ]);+ });+});++describe("moveCellToIndexAtom", () => {+ it("moves a cell to an index in its column or another", () => {+ const { store, columns } = twoColumns();+ const [first, second] = store.get(layoutAtom).columns.map((c) => c.id);++ store.set(moveCellToIndexAtom, { cellId: c1, columnId: first, index: 2 });+ expect(columns()).toEqual([+ [c2, c1],+ [c3, c4],+ ]);++ store.set(moveCellToIndexAtom, { cellId: c1, columnId: second, index: 1 });+ expect(columns()).toEqual([[c2], [c3, c1, c4]]);++ store.set(moveCellToIndexAtom, { cellId: c2, columnId: second, index: 99 });+ expect(columns()).toEqual([[], [c3, c1, c4, c2]]);+ });+});++describe("moveCellsRelativeToAtom", () => {+ it("moves cells after a target and records how to undo it", () => {+ const { store, order, notebook } = setup({ c3: cell("c3", "z = 3") });+ const column = store.get(layoutAtom).columns[0].id;++ store.set(moveCellsRelativeToAtom, {+ cellIds: [c1, c2],+ targetCellId: c3,+ position: "after",+ previousPlacements: [+ { columnId: column, index: 0 as CellIndex },+ { columnId: column, index: 1 as CellIndex },+ ],+ });+ expect(order()).toEqual([c3, c1, c2]);+ expect(notebook().history).toEqual([+ {+ type: "move",+ cellIds: [c1, c2],+ placements: [+ { columnId: column, index: 0 },+ { columnId: column, index: 1 },+ ],+ },+ ]);++ store.set(undoDeleteCellAtom);+ expect(order()).toEqual([c1, c2, c3]);+ expect(notebook().history).toEqual([]);+ expect(notebook().scrollKey).toBe(c1);+ });++ it("moves cells before a target, and to the end when the target moves too", () => {+ const { store, order, notebook } = setup({ c3: cell("c3", "z = 3") });++ store.set(moveCellsRelativeToAtom, {+ cellIds: [c3],+ targetCellId: c1,+ position: "before",+ });+ expect(order()).toEqual([c3, c1, c2]);+ expect(notebook().history).toEqual([]);++ store.set(moveCellsRelativeToAtom, {+ cellIds: [c3, c1],+ targetCellId: c1,+ position: "before",+ });+ expect(order()).toEqual([c2, c3, c1]);+ });+});diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 4382592580..da87c14655 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -36,11 +36,6 @@ import {type NotebookState,notebookAtom,} from "../cells";-import {- focusAndScrollCellIntoView,- scrollToBottom,- scrollToTop,-} from "../scrollCellIntoView";import {type CellData,createCell,@@ -67,7 +62,6 @@ vi.mock("../scrollCellIntoView", async (importOriginal) => {});const FIRST_COLUMN = 0;-const SECOND_COLUMN = 1;const { initialNotebookState, reducer, createActions } = exportedForTesting;@@ -203,10 +197,6 @@ describe("cell reducer", () => {cellRuntime: { ...state.cellRuntime, [id]: createCellRuntimeState() },cellHandles: { ...state.cellHandles, [id]: createRef() },scrollKey: autoFocus ? id : null,- untouchedNewCells:- hideCode && autoFocus- ? new Set([...state.untouchedNewCells, id])- : state.untouchedNewCells,};mountEditors();return id;@@ -247,306 +237,6 @@ describe("cell reducer", () => {`);});- it("can move a cell", () => {- seedCell({- cellId: firstCellId,- before: false,- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [0] ''-- [1] ''- "- `);-- // move first cell to the end- actions.moveCell({- cellId: firstCellId,- before: false,- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [1] ''-- [0] ''- "- `);-- // move it back- actions.moveCell({- cellId: firstCellId,- before: true,- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [0] ''-- [1] ''- "- `);-- // Add a column breakpoint to test left/right movement- actions.addColumnBreakpoint({ cellId: cellId("1") });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- > col 0- [0] ''-- > col 1- [1] ''- "- `);-- // Move cell right- actions.moveCell({- cellId: firstCellId,- direction: "right",- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- > col 0--- > col 1- [0] ''-- [1] ''- "- `);-- // Move cell left- actions.moveCell({- cellId: firstCellId,- direction: "left",- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- > col 0- [0] ''-- > col 1- [1] ''- "- `);-- // Try to move cell left when it's already in leftmost column (should noop)- actions.moveCell({- cellId: firstCellId,- direction: "left",- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- > col 0- [0] ''-- > col 1- [1] ''- "- `);-- // Try to move cell right when it's already in rightmost column (should noop)- actions.moveCell({- cellId: cellId("1"),- direction: "right",- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- > col 0- [0] ''-- > col 1- [1] ''- "- `);- });-- it("can drag and drop a cell", () => {- seedCell({- cellId: firstCellId,- before: false,- });- seedCell({- cellId: cellId("1"),- before: false,- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [0] ''-- [1] ''-- [2] ''- "- `);-- // drag first cell to the end- actions.dropCellOverCell({- cellId: firstCellId,- overCellId: cellId("2"),- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [1] ''-- [2] ''-- [0] ''- "- `);-- // drag it back to the middle- actions.dropCellOverCell({- cellId: firstCellId,- overCellId: cellId("2"),- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [1] ''-- [0] ''-- [2] ''- "- `);- });-- it("can move a cell to an exact index within a column", () => {- seedCell({- cellId: firstCellId,- before: false,- });- seedCell({- cellId: cellId("1"),- before: false,- });-- const columnId = state.cellIds.atOrThrow(0).id;- actions.moveCellToIndex({- cellId: firstCellId,- columnId,- index: 3,- });-- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [1] ''-- [2] ''-- [0] ''- "- `);- });-- it("can move a cell to an exact index across columns", () => {- seedCell({- cellId: firstCellId,- before: false,- });- seedCell({- cellId: cellId("1"),- before: false,- });- actions.addColumnBreakpoint({ cellId: cellId("1") });-- const secondColumnId = state.cellIds.atOrThrow(1).id;- actions.moveCellToIndex({- cellId: firstCellId,- columnId: secondColumnId,- index: 1,- });-- expect(formatCells(state)).toMatchInlineSnapshot(`- "- > col 0--- > col 1- [1] ''-- [0] ''-- [2] ''- "- `);- });-- it("moveCellToIndex is a no-op when moving to the same position", () => {- seedCell({- cellId: firstCellId,- before: false,- });- seedCell({- cellId: cellId("1"),- before: false,- });-- const columnId = state.cellIds.atOrThrow(0).id;- const before = formatCells(state);-- actions.moveCellToIndex({- cellId: firstCellId,- columnId,- index: 0,- });-- expect(formatCells(state)).toBe(before);- });-- it("moveCellToIndex is a no-op for an invalid columnId", () => {- seedCell({- cellId: firstCellId,- before: false,- });-- const before = formatCells(state);-- actions.moveCellToIndex({- cellId: firstCellId,- columnId: "nonexistent-column" as CellColumnId,- index: 0,- });-- expect(formatCells(state)).toBe(before);- });-- it("can move multiple cells relative to target", () => {- seedCell({- cellId: firstCellId,- before: false,- });- seedCell({- cellId: cellId("1"),- before: false,- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [0] ''-- [1] ''-- [2] ''- "- `);-- // Move first two cells after the third- actions.moveCellsRelativeTo({- cellIds: [firstCellId, cellId("1")],- targetCellId: cellId("2"),- position: "after",- });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [2] ''-- [0] ''-- [1] ''- "- `);- });-it("keeps error evidence after an edit and a new queued run", () => {const code = "raise ValueError('old failure')";const output: OutputMessage = {@@ -1439,61 +1129,13 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot("console received while idle");});- it("can send a cell to the top", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({ cellId: cellId("1"), before: false });- actions.sendToTop({ cellId: cellId("2") });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [2] ''+ it("can fold and unfold all cells", () => {+ actions.foldAll();+ expect(foldAllBulk).toHaveBeenCalled();- [0] ''-- [1] ''- "- `);- });-- it("can send a cell to the bottom", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({ cellId: cellId("1"), before: false });- actions.sendToBottom({ cellId: firstCellId });- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [1] ''-- [2] ''-- [0] ''- "- `);- });-- it("can focus cells", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({ cellId: cellId("1"), before: false });-- actions.focusCell({ cellId: cellId("1"), where: "before" });- expect(focusAndScrollCellIntoView).toHaveBeenCalledWith(- expect.objectContaining({- cellId: cellId("0"),- }),- );-- actions.focusTopCell();- expect(scrollToTop).toHaveBeenCalled();-- actions.focusBottomCell();- expect(scrollToBottom).toHaveBeenCalled();- });-- it("can fold and unfold all cells", () => {- actions.foldAll();- expect(foldAllBulk).toHaveBeenCalled();-- actions.unfoldAll();- expect(unfoldAllBulk).toHaveBeenCalled();- });+ actions.unfoldAll();+ expect(unfoldAllBulk).toHaveBeenCalled();+ });it("can clear logs", () => {state.cellLogs = [@@ -1514,311 +1156,6 @@ describe("cell reducer", () => {expect(state.cellLogs).toEqual([]);});- it("can collapse and expand cells", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({- cellId: cellId("1"),- before: false,- code: "# Header",- });- seedCell({- cellId: cellId("2"),- before: false,- code: "## Subheader",- });-- const id = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(1);- state.cellRuntime[id] = {- ...state.cellRuntime[id],- outline: {- items: [{ name: "Header", level: 1, by: { id: "header" } }],- },- };-- actions.collapseCell({ cellId: id });- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(id)).toBe(true);-- actions.expandCell({ cellId: id });- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(id)).toBe(false);- });-- it("can collapse and expand all cells in multiple columns", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({- cellId: cellId("1"),- before: false,- code: "# First Column Header",- });- seedCell({- cellId: cellId("2"),- before: false,- code: "## First Column Subheader",- });-- actions.addColumnBreakpoint({ cellId: cellId("2") });-- seedCell({- cellId: cellId("3"),- before: false,- code: "# Second Column Header",- });- seedCell({- cellId: cellId("4"),- before: false,- code: "## Second Column Subheader",- });-- const firstColumnHeaderId = state.cellIds- .atOrThrow(FIRST_COLUMN)- .atOrThrow(1);- state.cellRuntime[firstColumnHeaderId] = {- ...state.cellRuntime[firstColumnHeaderId],- outline: {- items: [- { name: "First Column Header", level: 1, by: { id: "header" } },- ],- },- };-- const secondColumnHeaderId = state.cellIds- .atOrThrow(SECOND_COLUMN)- .atOrThrow(0);- state.cellRuntime[secondColumnHeaderId] = {- ...state.cellRuntime[secondColumnHeaderId],- outline: {- items: [- { name: "Second Column Header", level: 1, by: { id: "header" } },- ],- },- };-- actions.collapseAllCells();- expect(- state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(firstColumnHeaderId),- ).toBe(true);- expect(- state.cellIds.atOrThrow(SECOND_COLUMN).isCollapsed(secondColumnHeaderId),- ).toBe(true);-- actions.expandAllCells();- expect(- state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(firstColumnHeaderId),- ).toBe(false);- expect(- state.cellIds.atOrThrow(SECOND_COLUMN).isCollapsed(secondColumnHeaderId),- ).toBe(false);- });-- it("can collapse and expand nested cells in one call", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({- cellId: cellId("1"),- before: false,- code: "# Header",- });- seedCell({- cellId: cellId("2"),- before: false,- code: "## Subheader",- });- seedCell({- cellId: cellId("3"),- before: false,- code: "### Subsubheader",- });-- const headerId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(1);- state.cellRuntime[headerId] = {- ...state.cellRuntime[headerId],- outline: {- items: [{ name: "Header", level: 1, by: { id: "header" } }],- },- };-- const subheaderId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(2);- state.cellRuntime[subheaderId] = {- ...state.cellRuntime[subheaderId],- outline: {- items: [{ name: "Subheader", level: 2, by: { id: "subheader" } }],- },- };-- // Check if both the parent and child are collapsed- actions.collapseAllCells();- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(headerId)).toBe(- true,- );- actions.expandCell({ cellId: headerId });- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(subheaderId)).toBe(- true,- );- actions.collapseCell({ cellId: headerId });-- // Check if both the parent and child are expanded- actions.expandAllCells();- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(headerId)).toBe(- false,- );- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(subheaderId)).toBe(- false,- );- });-- it("can collapse all cells when nested heading ranges end at the same cell", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({- cellId: cellId("1"),- before: false,- code: "# Header",- });- seedCell({- cellId: cellId("2"),- before: false,- code: "## Subheader",- });- seedCell({- cellId: cellId("3"),- before: false,- code: "### Subsubheader",- });-- const headerId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(1);- state.cellRuntime[headerId] = {- ...state.cellRuntime[headerId],- outline: {- items: [{ name: "Header", level: 1, by: { id: "header" } }],- },- };-- const subheaderId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(2);- state.cellRuntime[subheaderId] = {- ...state.cellRuntime[subheaderId],- outline: {- items: [{ name: "Subheader", level: 2, by: { id: "subheader" } }],- },- };-- const subsubheaderId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(3);- state.cellRuntime[subsubheaderId] = {- ...state.cellRuntime[subsubheaderId],- outline: {- items: [{ name: "Subsubheader", level: 3, by: { id: "subsubheader" } }],- },- };-- // The header, subheader and subsubheader ranges all end at the last- // cell. Collapsing all used to throw "Node ... not found in tree" and- // leave the whole notebook unchanged.- actions.collapseAllCells();- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(headerId)).toBe(- true,- );- expect(state.cellIds.atOrThrow(FIRST_COLUMN).topLevelIds).toEqual([- firstCellId,- headerId,- ]);-- // Each level is nested under its parent, collapsed- actions.expandCell({ cellId: headerId });- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(subheaderId)).toBe(- true,- );- actions.expandCell({ cellId: subheaderId });- expect(- state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(subsubheaderId),- ).toBe(true);- });-- it("can collapse all cells when a deep chain is followed by a later section", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({- cellId: cellId("1"),- before: false,- code: "# Header",- });- seedCell({- cellId: cellId("2"),- before: false,- code: "## Section A",- });- seedCell({- cellId: cellId("3"),- before: false,- code: "### Sub of A",- });- seedCell({- cellId: cellId("4"),- before: false,- code: "## Section B",- });-- const headerId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(1);- state.cellRuntime[headerId] = {- ...state.cellRuntime[headerId],- outline: {- items: [{ name: "Header", level: 1, by: { id: "header" } }],- },- };-- const sectionAId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(2);- state.cellRuntime[sectionAId] = {- ...state.cellRuntime[sectionAId],- outline: {- items: [{ name: "Section A", level: 2, by: { id: "section-a" } }],- },- };-- const subsectionId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(3);- state.cellRuntime[subsectionId] = {- ...state.cellRuntime[subsectionId],- outline: {- items: [{ name: "Sub of A", level: 3, by: { id: "sub-of-a" } }],- },- };-- const sectionBId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(4);- state.cellRuntime[sectionBId] = {- ...state.cellRuntime[sectionBId],- outline: {- items: [{ name: "Section B", level: 2, by: { id: "section-b" } }],- },- };-- actions.collapseAllCells();- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(headerId)).toBe(- true,- );- expect(state.cellIds.atOrThrow(FIRST_COLUMN).topLevelIds).toEqual([- firstCellId,- headerId,- ]);-- // Both sections sit under the header, collapsed, with the subsection- // nested under section A- actions.expandCell({ cellId: headerId });- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(sectionAId)).toBe(- true,- );- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(sectionBId)).toBe(- true,- );- actions.expandCell({ cellId: sectionAId });- expect(- state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(subsectionId),- ).toBe(true);- });-- it("can show hidden cells", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({ cellId: cellId("1"), before: false });- actions.collapseCell({ cellId: firstCellId });-- actions.showCellIfHidden({ cellId: cellId("1") });- expect(state.cellIds.atOrThrow(FIRST_COLUMN).isCollapsed(firstCellId)).toBe(- false,- );- });-it("can split and undo split cells", () => {seedCell({cellId: firstCellId,@@ -1998,79 +1335,6 @@ describe("cell reducer", () => {expect(state).toEqual(initialState);});- it("can drop a cell over another cell", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({ cellId: cellId("1"), before: false });- seedCell({ cellId: cellId("2"), before: false });-- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [0] ''-- [1] ''-- [2] ''-- [3] ''- "- `);-- actions.dropCellOverCell({- cellId: cellId("0"),- overCellId: cellId("3"),- });-- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [1] ''-- [2] ''-- [3] ''-- [0] ''- "- `);- });-- it("can drop a cell over a new column", () => {- seedCell({ cellId: firstCellId, before: false });- seedCell({ cellId: cellId("1"), before: false });-- expect(state.cellIds.getColumns().length).toBe(1);- expect(formatCells(state)).toMatchInlineSnapshot(`- "- [0] ''-- [1] ''-- [2] ''- "- `);-- actions.dropOverNewColumn({ cellId: cellId("1") });-- expect(state.cellIds.getColumns().length).toBe(2);- expect(formatCells(state)).toMatchInlineSnapshot(`- "- > col 0- [0] ''-- [2] ''-- > col 1- [1] ''- "- `);-- // Check that the cells are in the correct columns- expect(state.cellIds.getColumns()[0].topLevelIds).toEqual([- cellId("0"),- cellId("2"),- ]);- expect(state.cellIds.getColumns()[1].topLevelIds).toEqual([cellId("1")]);- });-it("can drop a column over another column", () => {seedCell({ cellId: firstCellId, before: false });seedCell({ cellId: cellId("1"), before: false });@@ -2129,7 +1393,11 @@ describe("cell reducer", () => {seedCell({ cellId: cellId("1"), before: false });actions.addColumnBreakpoint({ cellId: cellId("1") });actions.addColumnBreakpoint({ cellId: cellId("2") });- actions.dropOverNewColumn({ cellId: cellId("2") });+ // A column emptied by a drag stays until the drop compacts it.+ state = {+ ...state,+ cellIds: state.cellIds.addColumn(state.cellIds.getColumnIds()[1]),+ };expect(state.cellIds.getColumns().length).toBe(4);expect(formatCells(state)).toMatchInlineSnapshot(`@@ -2342,279 +1610,6 @@ describe("cell reducer", () => {expect(state.cellRuntime[cell2Id].output).toBeNull();});- describe("untouched cells functionality", () => {- it("starts with empty untouchedNewCells set", () => {- expect(state.untouchedNewCells).toEqual(new Set());- });-- it("can mark a cell as touched", () => {- // Create a cell with hideCode- seedCell({- cellId: "__end__",- before: false,- hideCode: true,- });-- const newCellId =- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];- expect(state.untouchedNewCells.has(newCellId)).toBe(true);-- // Mark it as touched- actions.markTouched({ cellId: newCellId });-- expect(state.untouchedNewCells.has(newCellId)).toBe(false);- });-- it("markTouched is idempotent", () => {- // Create a cell with hideCode- seedCell({- cellId: "__end__",- before: false,- hideCode: true,- });-- const newCellId =- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];- expect(state.untouchedNewCells.has(newCellId)).toBe(true);-- // Mark it as touched multiple times- actions.markTouched({ cellId: newCellId });- actions.markTouched({ cellId: newCellId });- actions.markTouched({ cellId: newCellId });-- expect(state.untouchedNewCells.has(newCellId)).toBe(false);- });-- it("can mark a non-existent cell as touched without error", () => {- const nonExistentCellId = cellId("non-existent");-- expect(() => {- actions.markTouched({ cellId: nonExistentCellId });- }).not.toThrow();-- expect(state.untouchedNewCells.has(nonExistentCellId)).toBe(false);- });-- it("can handle multiple untouched cells", () => {- // Create multiple cells with hideCode- seedCell({- cellId: "__end__",- before: false,- hideCode: true,- });- seedCell({- cellId: "__end__",- before: false,- hideCode: true,- });- seedCell({- cellId: "__end__",- before: false,- hideCode: false,- });-- const cellIds = state.cellIds.inOrderIds;- const cell1Id = cellIds[cellIds.length - 3];- const cell2Id = cellIds[cellIds.length - 2];- const cell3Id = cellIds[cellIds.length - 1];-- expect(state.untouchedNewCells.has(cell1Id)).toBe(true);- expect(state.untouchedNewCells.has(cell2Id)).toBe(true);- expect(state.untouchedNewCells.has(cell3Id)).toBe(false);-- // Mark one as touched- actions.markTouched({ cellId: cell1Id });-- expect(state.untouchedNewCells.has(cell1Id)).toBe(false);- expect(state.untouchedNewCells.has(cell2Id)).toBe(true);- expect(state.untouchedNewCells.has(cell3Id)).toBe(false);- });-- it("preserves untouched state when cells are moved", () => {- // Create cells with hideCode- seedCell({- cellId: "__end__",- before: false,- hideCode: true,- });- seedCell({- cellId: "__end__",- before: false,- hideCode: true,- });-- const cellIds = state.cellIds.inOrderIds;- const cell1Id = cellIds[cellIds.length - 2];- const cell2Id = cellIds[cellIds.length - 1];-- expect(state.untouchedNewCells.has(cell1Id)).toBe(true);- expect(state.untouchedNewCells.has(cell2Id)).toBe(true);-- // Move cell1 to the end- actions.moveCell({- cellId: cell1Id,- before: false,- });-- // Both cells should still be untouched- expect(state.untouchedNewCells.has(cell1Id)).toBe(true);- expect(state.untouchedNewCells.has(cell2Id)).toBe(true);- });-- it("untouched cell behavior with hide_code config", () => {- // Create a cell with hideCode and hide_code config- seedCell({- cellId: "__end__",- before: false,- hideCode: true,- });-- const newCellId =- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];-- // The document hides the cell's code- state.cellData[newCellId] = {- ...state.cellData[newCellId],- config: { ...state.cellData[newCellId].config, hide_code: true },- };-- // Cell should be untouched and have hide_code config- expect(state.untouchedNewCells.has(newCellId)).toBe(true);- expect(state.cellData[newCellId].config.hide_code).toBe(true);-- // Code should not be hidden because cell is untouched- expect(exportedForTesting.isCellCodeHidden(state, newCellId)).toBe(false);-- // Mark as touched- actions.markTouched({ cellId: newCellId });-- // Now code should be hidden- expect(state.untouchedNewCells.has(newCellId)).toBe(false);- expect(exportedForTesting.isCellCodeHidden(state, newCellId)).toBe(true);- });-- it("can mark an existing cell as untouched", () => {- // Create a cell without hideCode (not in untouchedNewCells)- seedCell({- cellId: "__end__",- before: false,- hideCode: false,- });-- const newCellId =- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];- expect(state.untouchedNewCells.has(newCellId)).toBe(false);-- // Mark it as untouched- actions.markUntouched({ cellId: newCellId });-- expect(state.untouchedNewCells.has(newCellId)).toBe(true);- });-- it("markUntouched is idempotent", () => {- // Create a cell without hideCode- seedCell({- cellId: "__end__",- before: false,- hideCode: false,- });-- const newCellId =- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];- expect(state.untouchedNewCells.has(newCellId)).toBe(false);-- // Mark as untouched multiple times- actions.markUntouched({ cellId: newCellId });- actions.markUntouched({ cellId: newCellId });- actions.markUntouched({ cellId: newCellId });-- expect(state.untouchedNewCells.has(newCellId)).toBe(true);- });-- it("markUntouched does not affect already untouched cells", () => {- // Create a cell with hideCode (already in untouchedNewCells)- seedCell({- cellId: "__end__",- before: false,- hideCode: true,- });-- const newCellId =- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];- expect(state.untouchedNewCells.has(newCellId)).toBe(true);-- // Calling markUntouched should not change anything- actions.markUntouched({ cellId: newCellId });-- expect(state.untouchedNewCells.has(newCellId)).toBe(true);- });-- it("markTouched and markUntouched can toggle cell state", () => {- // Create a cell without hideCode- seedCell({- cellId: "__end__",- before: false,- hideCode: false,- });-- const newCellId =- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];-- // Initially not untouched- expect(state.untouchedNewCells.has(newCellId)).toBe(false);-- // Mark as untouched- actions.markUntouched({ cellId: newCellId });- expect(state.untouchedNewCells.has(newCellId)).toBe(true);-- // Mark as touched- actions.markTouched({ cellId: newCellId });- expect(state.untouchedNewCells.has(newCellId)).toBe(false);-- // Mark as untouched again- actions.markUntouched({ cellId: newCellId });- expect(state.untouchedNewCells.has(newCellId)).toBe(true);- });-- it("markUntouched works for markdown cell conversion scenario", () => {- // Simulates converting a Python cell to Markdown- // 1. Create a regular cell (no hideCode)- seedCell({- cellId: "__end__",- before: false,- hideCode: false,- });-- const cellId =- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];-- // Cell starts without hide_code and not in untouchedNewCells- expect(state.cellData[cellId].config.hide_code).toBe(false);- expect(state.untouchedNewCells.has(cellId)).toBe(false);- expect(exportedForTesting.isCellCodeHidden(state, cellId)).toBe(false);-- // 2. Convert to markdown: the document hides the code, and the cell- // is marked untouched- state.cellData[cellId] = {- ...state.cellData[cellId],- config: { ...state.cellData[cellId].config, hide_code: true },- };- actions.markUntouched({ cellId });-- // Code should NOT be hidden because cell is untouched (user can edit)- expect(state.cellData[cellId].config.hide_code).toBe(true);- expect(state.untouchedNewCells.has(cellId)).toBe(true);- expect(exportedForTesting.isCellCodeHidden(state, cellId)).toBe(false);-- // 3. User blurs the cell (markTouched)- actions.markTouched({ cellId });-- // Now code should be hidden- expect(state.untouchedNewCells.has(cellId)).toBe(false);- expect(exportedForTesting.isCellCodeHidden(state, cellId)).toBe(true);- });- });-describe("releaseCellAtoms", () => {it("atom families cache atoms until explicitly removed", () => {const { cellDataAtom, cellRuntimeAtom, cellHandleAtom } =@@ -2639,91 +1634,6 @@ describe("cell reducer", () => {});});-describe("isCellCodeHidden", () => {- const state = initialNotebookState();- const firstCellId = state.cellIds.inOrderIds[0];-- it("returns false when hide_code is false and cell is not untouched", () => {- const testCellId = cellId("test-cell");- const testState: NotebookState = {- ...state,- cellData: {- ...state.cellData,- [testCellId]: {- ...state.cellData[firstCellId],- id: testCellId,- config: { hide_code: false, disabled: false, column: null },- },- },- untouchedNewCells: new Set(),- };-- expect(exportedForTesting.isCellCodeHidden(testState, testCellId)).toBe(- false,- );- });-- it("returns true when hide_code is true and cell is not untouched", () => {- const testCellId = cellId("test-cell");- const testState: NotebookState = {- ...state,- cellData: {- ...state.cellData,- [testCellId]: {- ...state.cellData[firstCellId],- id: testCellId,- config: { hide_code: true, disabled: false, column: null },- },- },- untouchedNewCells: new Set(),- };-- expect(exportedForTesting.isCellCodeHidden(testState, testCellId)).toBe(- true,- );- });-- it("returns false when hide_code is true but cell is untouched", () => {- const testCellId = cellId("test-cell");- const testState: NotebookState = {- ...state,- cellData: {- ...state.cellData,- [testCellId]: {- ...state.cellData[firstCellId],- id: testCellId,- config: { hide_code: true, disabled: false, column: null },- },- },- untouchedNewCells: new Set([testCellId]),- };-- expect(exportedForTesting.isCellCodeHidden(testState, testCellId)).toBe(- false,- );- });-- it("returns false when hide_code is false and cell is untouched", () => {- const testCellId = cellId("test-cell");- const testState: NotebookState = {- ...state,- cellData: {- ...state.cellData,- [testCellId]: {- ...state.cellData[firstCellId],- id: testCellId,- config: { hide_code: false, disabled: false, column: null },- },- },- untouchedNewCells: new Set([testCellId]),- };-- expect(exportedForTesting.isCellCodeHidden(testState, testCellId)).toBe(- false,- );- });-});-describe("createTracebackInfoAtom", () => {const store = createStore();diff --git a/frontend/src/core/cells/__tests__/document.test.ts b/frontend/src/core/cells/__tests__/document.test.tsindex 3c99fabccc..d054806835 100644--- a/frontend/src/core/cells/__tests__/document.test.ts+++ b/frontend/src/core/cells/__tests__/document.test.ts@@ -21,7 +21,6 @@ import {import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";import { store } from "@/core/state/jotai";import { activeDocumentModelAtom } from "@/core/session/active-notebook";-import { MultiColumn } from "@/utils/id-tree";import { isRtcEnabled } from "../../rtc/state";import {createNotebookActions,@@ -206,7 +205,7 @@ describe("applyDocument", () => {expect(next.cellHandles[b]).toBeUndefined();});- it("regroups columns from the cells' configs, keeping column ids and collapsed sections", () => {+ it("regroups columns from the cells' configs, keeping column ids", () => {const column1 = { ...cell(d).config, column: 1 };const state = notebookOf([cell(a),@@ -214,22 +213,13 @@ describe("applyDocument", () => {cell(c),cell(d, { config: column1 }),]);- const [first, second] = state.cellIds.getColumns();- const collapsed = {- ...state,- cellIds: new MultiColumn([first.collapse(a, b), second]),- };-const next = applyDocument(- collapsed,+ state,documentOf([cell(c), cell(a), cell(b), cell(d, { config: column1 })]),);expect(next.cellIds.inOrderIds).toEqual([c, a, b, d]);- expect(next.cellIds.getColumnIds()).toEqual(- collapsed.cellIds.getColumnIds(),- );- expect(next.cellIds.atOrThrow(0).isCollapsed(a)).toBe(true);+ expect(next.cellIds.getColumnIds()).toEqual(state.cellIds.getColumnIds());expect(next.cellIds.atOrThrow(1).inOrderIds).toEqual([d]);});@@ -293,25 +283,6 @@ describe("documentEditMiddleware", () => {expect(calls).toEqual([["setCode", a, "a = 2"]]);});- it("sets the order when a cell moves", () => {- actions.moveCell({ cellId: c, before: true });-- expect(calls).toEqual([["setOrder", [a, c, b]]]);- });-- it("sets the column of a cell that changes column", () => {- state = notebookOf([- cell(a),- cell(b),- cell(c, { config: { ...cell(c).config, column: 1 } }),- ]);-- actions.moveCell({ cellId: b, direction: "right" });-- expect(state.cellIds.atOrThrow(1).inOrderIds).toEqual([b, c]);- expect(calls).toEqual([["updateConfig", b, { column: 1 }]]);- });-it("clears columns merged into one", () => {state = notebookOf([cell(a),diff --git a/frontend/src/core/cells/__tests__/editor.test.ts b/frontend/src/core/cells/__tests__/editor.test.tsnew file mode 100644index 0000000000..a3354a6ec7--- /dev/null+++ b/frontend/src/core/cells/__tests__/editor.test.ts@@ -0,0 +1,57 @@+/* Copyright 2026 Marimo. All rights reserved. */+// @vitest-environment jsdom++import { act, renderHook } from "@testing-library/react";+import { createStore, Provider } from "jotai";+import { createElement, type PropsWithChildren } from "react";+import { describe, expect, it } from "vitest";+import { cellId } from "@/__tests__/branded";+import {+ hideShownCodeAtom,+ isCodeHidden,+ restoredEditorStatesAtom,+ showHiddenCodeAtom,+ shownHiddenCodeAtom,+ takeRestoredEditorStateAtom,+ useRestoredEditorState,+} from "../editor";++const a = cellId("a");+const b = cellId("b");++describe("hidden code showing for now", () => {+ it("hides code unless the cell is showing it", () => {+ const shown = new Set([a]);+ expect(isCodeHidden(true, shown, a)).toBe(false);+ expect(isCodeHidden(true, shown, b)).toBe(true);+ expect(isCodeHidden(false, shown, b)).toBe(false);+ expect(isCodeHidden(undefined, shown, b)).toBe(false);+ });++ it("shows a cell's code and hides it again, saying whether it was showing", () => {+ const store = createStore();+ store.set(showHiddenCodeAtom, { cellId: a });+ expect(store.get(shownHiddenCodeAtom).has(a)).toBe(true);+ expect(store.set(hideShownCodeAtom, { cellId: a })).toBe(true);+ expect(store.get(shownHiddenCodeAtom).has(a)).toBe(false);+ expect(store.set(hideShownCodeAtom, { cellId: a })).toBe(false);+ });+});++describe("restored editor states", () => {+ it("hands a state over once", () => {+ const store = createStore();+ store.set(restoredEditorStatesAtom, new Map([[a, { doc: "x = 1" }]]));+ const wrapper = ({ children }: PropsWithChildren) =>+ createElement(Provider, { store }, children);+ const { result } = renderHook(() => useRestoredEditorState(a), {+ wrapper,+ });+ expect(result.current).toEqual({ doc: "x = 1" });++ act(() => store.set(takeRestoredEditorStateAtom, { cellId: a }));++ expect(result.current).toBeNull();+ expect(store.get(restoredEditorStatesAtom).size).toBe(0);+ });+});diff --git a/frontend/src/core/cells/__tests__/harness.ts b/frontend/src/core/cells/__tests__/harness.tsnew file mode 100644index 0000000000..d5de57d1b2--- /dev/null+++ b/frontend/src/core/cells/__tests__/harness.ts@@ -0,0 +1,82 @@+/* Copyright 2026 Marimo. All rights reserved. */++/** A store whose notebook follows a document model, as the session wires it. */++import { history } from "@codemirror/commands";+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import type * as Protocol from "@marimo-team/client/protocol";+import { createStore } from "jotai";+import { mockDocumentModel } from "@/__mocks__/document";+import {+ document as documentOf,+ withCells,+} from "@/core/notebook/document/__tests__/fixtures";+import { exportedForTesting, notebookAtom, notebookReducer } from "../cells";+import { followDocument } from "../document";+import { layoutAtom } from "../layout";++export function setupNotebook(+ stops: Array<() => void>,+ cells?: Record<string, Protocol.Cell | null>,+) {+ const store = createStore();+ store.set(notebookAtom, exportedForTesting.initialNotebookState());+ const { model, stop } = mockDocumentModel(+ store,+ cells ? withCells(documentOf(), cells) : documentOf(),+ );+ const controller = new AbortController();+ stops.push(stop, () => controller.abort());+ followDocument({+ store,+ model,+ reconcile: (document) =>+ store.set(notebookAtom, (state) =>+ notebookReducer(state, {+ type: "reconcileDocument",+ payload: document,+ }),+ ),+ signal: controller.signal,+ });+ return {+ store,+ model,+ order: () => store.get(notebookAtom).cellIds.inOrderIds,+ /** The cells of each column, as the page lays them out. */+ columns: () => store.get(layoutAtom).columns.map((column) => column.ids),+ notebook: () => store.get(notebookAtom),+ cellIn: (id: string) => store.get(model.documentAtom)?.cells.get(id),+ /** Give a cell an editor, as mounting it would. */+ mountEditor: (id: string) => {+ const view = new EditorView({+ state: EditorState.create({+ doc: store.get(model.documentAtom)?.cells.get(id)?.code ?? "",+ extensions: [history()],+ }),+ });+ store.get(notebookAtom).cellHandles[id as never].current = {+ editorView: view,+ editorViewOrNull: view,+ };+ return view;+ },+ /** Give a cell's output a heading, as the kernel's outline would. */+ heading: (id: string, level: number) =>+ store.set(notebookAtom, (state) => ({+ ...state,+ cellRuntime: {+ ...state.cellRuntime,+ [id]: {+ ...state.cellRuntime[id as never],+ outline: { items: [{ name: `H${level}`, level, by: { id } }] },+ },+ },+ })),+ visible: () => store.get(layoutAtom).columns[0].visible,+ /** Apply a reducer action, as `useReducerActions()` does. */+ dispatch: (action: Parameters<typeof notebookReducer>[1]) =>+ store.set(notebookAtom, (state) => notebookReducer(state, action)),+ };+}diff --git a/frontend/src/core/cells/__tests__/layout.test.ts b/frontend/src/core/cells/__tests__/layout.test.tsnew file mode 100644index 0000000000..de285d69ba--- /dev/null+++ b/frontend/src/core/cells/__tests__/layout.test.ts@@ -0,0 +1,189 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { createStore } from "jotai";+import { describe, expect, it } from "vitest";+import { cellId } from "@/__tests__/branded";+import type { EditableCell } from "@/core/notebook/document";+import type { CellColumnId } from "@/utils/id-tree";+import { exportedForTesting, notebookAtom, notebookReducer } from "../cells";+import { applyDocument } from "../document";+import type { CellId } from "../ids";+import {+ collapsedAtom,+ columnOf,+ deriveLayout,+ foldSections,+ foldsAfter,+ foldsHiding,+ layoutAtom,+ visibleNeighbor,+} from "../layout";+import type { Outline } from "../outline";++const [h1, a, h2, b, c, h1b, d] = ["h1", "a", "h2", "b", "c", "h1b", "d"].map(+ cellId,+);+const ids = [h1, a, h2, b, c, h1b, d];++function heading(level: number): Outline {+ return { items: [{ name: `H${level}`, level, by: { id: `h${level}` } }] };+}+const outlines = new Map<CellId, Outline>([+ [h1, heading(1)],+ [h2, heading(2)],+ [h1b, heading(1)],+]);+const outlineOf = (id: CellId) => outlines.get(id) ?? null;+const column = (id: string, cells: CellId[]) => ({+ id: id as CellColumnId,+ ids: cells,+});++describe("foldSections", () => {+ it("folds a header until the next header of its level or higher", () => {+ const folds = foldSections(ids, ids.map(outlineOf), new Set([h2]));+ expect([...folds]).toEqual([[h2, [b, c]]]);+ });++ it("hides a folded section inside a folded section", () => {+ const folds = foldSections(ids, ids.map(outlineOf), new Set([h1, h2]));+ expect(folds.get(h1)).toEqual([a, h2, b, c]);+ expect(folds.get(h2)).toEqual([b, c]);+ });++ it("folds the last section to the end", () => {+ const folds = foldSections(ids, ids.map(outlineOf), new Set([h1b]));+ expect(folds.get(h1b)).toEqual([d]);+ });++ it("ignores cells without a heading", () => {+ const folds = foldSections([h1, a], [heading(1), null], new Set([a]));+ expect(folds.size).toBe(0);+ });++ it("keeps an empty fold for a header with nothing under it yet", () => {+ const folds = foldSections(+ [h1, a, h1b],+ [heading(1), null, heading(1)],+ new Set([h1b]),+ );+ expect(folds.get(h1b)).toEqual([]);+ });+});++describe("deriveLayout", () => {+ const layout = deriveLayout(+ [column("left", ids), column("right", [])],+ outlineOf,+ new Set([h2]),+ );++ it("lists visible cells per column and keeps empty columns", () => {+ expect(layout.columns.map((c) => c.id)).toEqual(["left", "right"]);+ expect(layout.columns[0].visible).toEqual([h1, a, h2, h1b, d]);+ expect(layout.columns[0].ids).toEqual(ids);+ expect(layout.columns[1].visible).toEqual([]);+ });++ it("finds a cell's column, the folds hiding it, and its visible neighbours", () => {+ expect(columnOf(layout, b).id).toBe("left");+ expect(() => columnOf(layout, cellId("missing"))).toThrow(+ "not in the layout",+ );+ expect(foldsHiding(layout, c)).toEqual([h2]);+ expect(foldsHiding(layout, a)).toEqual([]);+ expect(visibleNeighbor(layout, h2, 1)).toBe(h1b);+ expect(visibleNeighbor(layout, h1b, -1)).toBe(h2);+ expect(visibleNeighbor(layout, h1, -1)).toBeUndefined();+ expect(visibleNeighbor(layout, b, 1)).toBeUndefined();+ });++ it("names the folds a cell placed after another would fall into", () => {+ // After the folded header or the last cell of its fold, inside it.+ expect(foldsAfter(layout, h2)).toEqual([h2]);+ expect(foldsAfter(layout, c)).toEqual([h2]);+ // After a visible cell no fold reaches, nothing.+ expect(foldsAfter(layout, a)).toEqual([]);+ expect(foldsAfter(layout, h1b)).toEqual([]);++ const nested = deriveLayout(+ [column("left", ids)],+ outlineOf,+ new Set([h1, h2]),+ );+ expect(foldsAfter(nested, c)).toEqual([h1, h2]);+ });+});++describe("layoutAtom", () => {+ /** A store whose notebook holds `ids`, in that order, with nothing run. */+ function notebookOf(...ids: CellId[]) {+ const store = createStore();+ const cells = ids.map((id): EditableCell => ({+ id,+ code: "",+ name: "_",+ config: {+ column: null,+ disabled: false,+ hide_code: false,+ expand_output: false,+ },+ }));+ store.set(+ notebookAtom,+ applyDocument(exportedForTesting.initialNotebookState(), {+ order: ids,+ cells: new Map(cells.map((cell) => [cell.id, cell])),+ }),+ );+ return store;+ }++ /** Deliver `html` as a cell's output, as the kernel's message does. */+ function output(+ store: ReturnType<typeof createStore>,+ id: CellId,+ html: string,+ ) {+ store.set(notebookAtom, (state) =>+ notebookReducer(state, {+ type: "handleCellMessage",+ payload: {+ cell_id: id,+ output: {+ channel: "output",+ mimetype: "text/html",+ data: html,+ timestamp: 1,+ },+ console: null,+ status: "idle",+ stale_inputs: null,+ timestamp: 1,+ },+ }),+ );+ }++ it("is the same layout after output that changes no heading", () => {+ const store = notebookOf(h1, a);+ output(store, h1, "<h1>Title</h1>");+ const layout = store.get(layoutAtom);++ output(store, a, "<p>1</p>");+ output(store, h1, "<h1>Title</h1>");++ expect(store.get(layoutAtom)).toBe(layout);+ });++ it("follows a heading arriving in a cell's output", () => {+ const store = notebookOf(h1, a);+ store.set(collapsedAtom, new Set([h1]));+ expect(store.get(layoutAtom).columns[0].folds.size).toBe(0);++ output(store, h1, "<h1>Title</h1>");++ expect(store.get(layoutAtom).columns[0].folds.get(h1)).toEqual([a]);+ });+});diff --git a/frontend/src/core/cells/__tests__/notebook-outline.test.ts b/frontend/src/core/cells/__tests__/notebook-outline.test.tsindex 412cfeaf0b..ebb6ba96ea 100644--- a/frontend/src/core/cells/__tests__/notebook-outline.test.ts+++ b/frontend/src/core/cells/__tests__/notebook-outline.test.ts@@ -80,7 +80,13 @@ describe("notebookOutline", () => {it("keeps headings in cell order after moving and deleting cells", () => {const { store, actions } = setup();- actions.moveCell({ cellId: second, before: true });+ actions.reconcileDocument({+ order: [second, first],+ cells: new Map([+ [first, { id: first, code: "x = 1", name: "_", config: CONFIG }],+ [second, { id: second, code: "y = 2", name: "_", config: CONFIG }],+ ]),+ });expect(store.get(notebookOutline)).toEqual({items: [...secondOutline.items, ...firstOutline.items],});diff --git a/frontend/src/core/cells/__tests__/session.test.ts b/frontend/src/core/cells/__tests__/session.test.tsindex cc78b837aa..42b7cd85e0 100644--- a/frontend/src/core/cells/__tests__/session.test.ts+++ b/frontend/src/core/cells/__tests__/session.test.ts@@ -6,11 +6,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { Mocks } from "@/__mocks__/common";import { cellId } from "@/__tests__/branded";import { parseOutline } from "@/core/dom/outline";-import { MultiColumn, visibleForTesting } from "@/utils/id-tree";+import { visibleForTesting } from "@/utils/id-tree";import { invariant } from "@/utils/invariant";import { Logger } from "@/utils/Logger";import { SETUP_CELL_ID } from "../ids";-import { notebookStateFromSession } from "../session";+import { readExport } from "../session";// Mock dependenciesvi.mock("@/utils/Logger", () => ({ Logger: Mocks.quietLogger() }));@@ -25,7 +25,14 @@ type NotebookCell = api.Notebook["NotebookV1"]["cells"][0];// Test constantsconst CELL_1 = cellId("cell-1");-describe("notebookStateFromSession", () => {+/** The snapshot's record of a cell. */+function cellIn(result: ReturnType<typeof readExport>, id: string) {+ const cell = result.snapshot?.cells.find((cell) => cell.id === id);+ invariant(cell, `no cell ${id}`);+ return cell;+}++describe("readExport", () => {beforeEach(() => {vi.clearAllMocks();visibleForTesting.reset();@@ -88,72 +95,113 @@ describe("notebookStateFromSession", () => {describe("validation", () => {it("logs error for both session and notebook null/undefined", () => {- const result = notebookStateFromSession(null, null);- expect(result).toBeNull();+ const result = readExport({+ session: null,+ notebook: null,+ filename: null,+ appConfig: {},+ });+ expect(result.snapshot).toBeNull();});it("logs error when session and notebook have different cells", () => {const session = createSession([createSessionCell("cell-1")]);const notebook = createNotebook([createNotebookCell("cell-2", {})]);- const result = notebookStateFromSession(session, notebook);+ const result = readExport({+ session: session,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });expect(Logger.warn).toHaveBeenCalledWith("Session and notebook have different cells, attempted merge.",);// Should have the same cell structure as notebook- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([["cell-2"]]).inOrderIds,- );+ invariant(result.snapshot, "no snapshot");+ expect(result.snapshot.document.order).toEqual(["cell-2"]);});});describe("null/undefined inputs", () => {it("returns null when both session and notebook are null", () => {- const result = notebookStateFromSession(null, null);- expect(result).toBeNull();+ const result = readExport({+ session: null,+ notebook: null,+ filename: null,+ appConfig: {},+ });+ expect(result.snapshot).toBeNull();});it("returns null when both session and notebook are undefined", () => {- const result = notebookStateFromSession(undefined, undefined);- expect(result).toBeNull();+ const result = readExport({+ session: undefined,+ notebook: undefined,+ filename: null,+ appConfig: {},+ });+ expect(result.snapshot).toBeNull();});it("returns null when session is null and notebook is undefined", () => {- const result = notebookStateFromSession(null, undefined);- expect(result).toBeNull();+ const result = readExport({+ session: null,+ notebook: undefined,+ filename: null,+ appConfig: {},+ });+ expect(result.snapshot).toBeNull();});});describe("session only scenarios", () => {it("creates state from session with single cell", () => {const session = createSession([createSessionCell("cell-1")]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([[CELL_1]]).inOrderIds,- );- expect(result.cellData[CELL_1].code).toBe("");+ invariant(result.snapshot, "no snapshot");+ expect(result.snapshot.document.order).toEqual([CELL_1]);+ // The session knows outputs, not source; the host withholds it as null.+ expect(cellIn(result, CELL_1).code).toBeNull();expect(result.cellRuntime[CELL_1]).toBeDefined();});+ it("carries the page's filename and app config into the snapshot", () => {+ const session = createSession([createSessionCell("cell-1")]);+ const result = readExport({+ session,+ notebook: null,+ filename: "notebook.py",+ appConfig: { width: "full" },+ });++ invariant(result.snapshot, "no snapshot");+ expect(result.snapshot.notebook.name).toBe("notebook.py");+ expect(result.snapshot.document.app_config).toEqual({ width: "full" });+ });+it("creates state from session with multiple cells", () => {const session = createSession([createSessionCell("cell-1"),createSessionCell("cell-2"),]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([["cell-1", "cell-2"]]).inOrderIds,- );- expect(Object.keys((result as any).cellData)).toEqual([+ invariant(result.snapshot, "no snapshot");+ expect(result.snapshot.document.order).toEqual(["cell-1", "cell-2"]);+ expect(result.snapshot.cells.map((cell) => cell.id)).toEqual(["cell-1","cell-2",]);@@ -173,10 +221,14 @@ describe("notebookStateFromSession", () => {const session = createSession([createSessionCell("cell-1", [errorOutput]),]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].output).toEqual({channel: "marimo-error",data: [@@ -219,8 +271,13 @@ describe("notebookStateFromSession", () => {],),]);- const state = notebookStateFromSession(session, null);- invariant(state, "state is null");+ const state = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });+ invariant(state.snapshot, "no snapshot");expect(state.cellRuntime[CELL_1].output).toMatchObject({code,data: [@@ -249,10 +306,14 @@ describe("notebookStateFromSession", () => {const session = createSession([createSessionCell("cell-1", [dataOutput]),]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].output).toEqual({channel: "output",data: "Hello World",@@ -279,10 +340,14 @@ describe("notebookStateFromSession", () => {const session = createSession([createSessionCell("cell-1", [], consoleOutputs),]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].consoleOutputs).toEqual([{channel: "stdout",@@ -310,7 +375,12 @@ describe("notebookStateFromSession", () => {const session = createSession([createSessionCell("cell-1", [dataOutput]),]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });expect(parseOutline).toHaveBeenCalledWith({channel: "output",@@ -318,16 +388,21 @@ describe("notebookStateFromSession", () => {mimetype: "text/html",timestamp: 0,});- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].outline).toBe(mockOutline);});it("sets outline to null when no output exists", () => {const session = createSession([createSessionCell("cell-1")]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });expect(parseOutline).not.toHaveBeenCalled();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].outline).toBeNull();});});@@ -340,27 +415,29 @@ describe("notebookStateFromSession", () => {name: "my_cell",}),]);- const result = notebookStateFromSession(null, notebook);+ const result = readExport({+ session: null,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([[CELL_1]]).inOrderIds,- );- expect(result.cellData[CELL_1]).toEqual({- id: "cell-1",+ invariant(result.snapshot, "no snapshot");+ expect(result.snapshot.document.order).toEqual([CELL_1]);+ expect(cellIn(result, CELL_1)).toEqual({+ id: CELL_1,+ notebook_id: "embedded",name: "my_cell",code: "print('hello')",- edited: false,- lastCodeRun: null,- lastExecutionTime: null,config: {hide_code: false,disabled: false,column: null,expand_output: false,},- serializedEditorState: null,+ etag: `embedded:${CELL_1}`,+ code_hash: `embedded:${CELL_1}:code`,+ version: 1,});});@@ -377,11 +454,15 @@ describe("notebookStateFromSession", () => {},}),]);- const result = notebookStateFromSession(null, notebook);+ const result = readExport({+ session: null,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellData[CELL_1].config).toEqual({+ invariant(result.snapshot, "no snapshot");+ expect(cellIn(result, CELL_1).config).toEqual({hide_code: true,disabled: true,column: 1,@@ -402,24 +483,28 @@ describe("notebookStateFromSession", () => {},};const notebook = createNotebook([notebookCell]);- const result = notebookStateFromSession(null, notebook);+ const result = readExport({+ session: null,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellData[CELL_1]).toEqual({- id: "cell-1",- name: "",- code: "",- edited: false,- lastCodeRun: null,- lastExecutionTime: null,+ invariant(result.snapshot, "no snapshot");+ expect(cellIn(result, CELL_1)).toEqual({+ id: CELL_1,+ notebook_id: "embedded",+ name: "_",+ code: null,config: {hide_code: false,disabled: false,column: null,expand_output: false,},- serializedEditorState: null,+ etag: `embedded:${CELL_1}`,+ code_hash: `embedded:${CELL_1}:code`,+ version: 1,});});@@ -436,27 +521,29 @@ describe("notebookStateFromSession", () => {},};const notebook = createNotebook([notebookCell as any]);- const result = notebookStateFromSession(null, notebook);+ const result = readExport({+ session: null,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([[SETUP_CELL_ID]]).inOrderIds,- );- expect(result.cellData[SETUP_CELL_ID]).toEqual({+ invariant(result.snapshot, "no snapshot");+ expect(result.snapshot.document.order).toEqual([SETUP_CELL_ID]);+ expect(cellIn(result, SETUP_CELL_ID)).toEqual({id: SETUP_CELL_ID,+ notebook_id: "embedded",name: "setup",code: "import marimo as mo",- edited: false,- lastCodeRun: null,- lastExecutionTime: null,config: {hide_code: false,disabled: false,column: null,expand_output: false,},- serializedEditorState: null,+ etag: `embedded:${SETUP_CELL_ID}`,+ code_hash: `embedded:${SETUP_CELL_ID}:code`,+ version: 1,});});});@@ -483,24 +570,28 @@ describe("notebookStateFromSession", () => {name: "my_cell",}),]);- const result = notebookStateFromSession(session, notebook);+ const result = readExport({+ session: session,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellData[CELL_1]).toEqual({- id: "cell-1",+ invariant(result.snapshot, "no snapshot");+ expect(cellIn(result, CELL_1)).toEqual({+ id: CELL_1,+ notebook_id: "embedded",name: "my_cell",code: "print('hello')",- edited: false,- lastCodeRun: null,- lastExecutionTime: null,config: {hide_code: false,disabled: false,column: null,expand_output: false,},- serializedEditorState: null,+ etag: `embedded:${CELL_1}`,+ code_hash: `embedded:${CELL_1}:code`,+ version: 1,});// Null result means no output.expect(result.cellRuntime[CELL_1].consoleOutputs).toEqual([]);@@ -516,13 +607,15 @@ describe("notebookStateFromSession", () => {createNotebookCell("cell-1", {}),]);- const result = notebookStateFromSession(session, notebook);+ const result = readExport({+ session: session,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([["cell-2", "cell-1"]]).inOrderIds,- );+ invariant(result.snapshot, "no snapshot");+ expect(result.snapshot.document.order).toEqual(["cell-2", "cell-1"]);});it("creates state when session and notebook have identical cell arrays", () => {@@ -535,48 +628,69 @@ describe("notebookStateFromSession", () => {createNotebookCell("cell-2", {}),]);- const result = notebookStateFromSession(session, notebook);+ const result = readExport({+ session: session,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });expect(Logger.error).not.toHaveBeenCalled();- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([["cell-1", "cell-2"]]).inOrderIds,- );+ invariant(result.snapshot, "no snapshot");+ expect(result.snapshot.document.order).toEqual(["cell-1", "cell-2"]);});});describe("empty cells scenarios", () => {it("warns and returns null when session has empty cells array", () => {const session = createSession([]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).toBeNull();+ expect(result.snapshot).toBeNull();});it("warns and returns null when notebook has empty cells array", () => {const notebook = createNotebook([]);- const result = notebookStateFromSession(null, notebook);+ const result = readExport({+ session: null,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).toBeNull();+ expect(result.snapshot).toBeNull();});it("warns and returns null when both have empty cells arrays", () => {const session = createSession([]);const notebook = createNotebook([]);- const result = notebookStateFromSession(session, notebook);+ const result = readExport({+ session: session,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).toBeNull();+ expect(result.snapshot).toBeNull();});});describe("edge cases", () => {it("handles session cell with no outputs", () => {const session = createSession([createSessionCell("cell-1", [])]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].output).toBeNull();expect(result.cellRuntime[CELL_1].consoleOutputs).toEqual([]);expect(result.cellRuntime[CELL_1].outline).toBeNull();@@ -584,10 +698,14 @@ describe("notebookStateFromSession", () => {it("handles session cell with empty console array", () => {const session = createSession([createSessionCell("cell-1", [], [])]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].consoleOutputs).toEqual([]);});@@ -597,10 +715,14 @@ describe("notebookStateFromSession", () => {{ type: "data" as const, data: { "text/plain": "Second" } },];const session = createSession([createSessionCell("cell-1", outputs)]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].output).toEqual({channel: "output",data: "First",@@ -620,10 +742,14 @@ describe("notebookStateFromSession", () => {const session = createSession([createSessionCell("cell-1", [dataOutput]),]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].output).toEqual({channel: "output",data: "Plain text",@@ -640,10 +766,14 @@ describe("notebookStateFromSession", () => {const session = createSession([createSessionCell("cell-1", [dataOutput]),]);- const result = notebookStateFromSession(session, null);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");expect(result.cellRuntime[CELL_1].output).toEqual({channel: "output",data: undefined,@@ -654,22 +784,29 @@ describe("notebookStateFromSession", () => {it("returns correct structure with all expected properties", () => {const session = createSession([createSessionCell("cell-1")]);- const result = notebookStateFromSession(session, null);-- expect(result).not.toBeNull();- invariant(result, "result is null");- expect(result).toHaveProperty("cellIds");- expect(result).toHaveProperty("cellData");- expect(result).toHaveProperty("cellRuntime");- expect(result).toHaveProperty("cellHandles");- expect(result).toHaveProperty("history");- expect(result).toHaveProperty("scrollKey");- expect(result).toHaveProperty("cellLogs");-- expect(result.cellHandles).toEqual({});- expect(result.history).toEqual([]);- expect(result.scrollKey).toBeNull();- expect(result.cellLogs).toEqual([]);+ const result = readExport({+ session: session,+ notebook: null,+ filename: null,+ appConfig: {},+ });++ invariant(result.snapshot, "no snapshot");+ expect(result.snapshot.notebook).toEqual({+ id: "embedded",+ project_id: "embedded",+ path: null,+ name: "",+ updated_at: null,+ });+ expect(result.snapshot.document).toMatchObject({+ notebook_id: "embedded",+ order: result.snapshot.cells.map((cell) => cell.id),+ version: 1,+ });+ expect(Object.keys(result.cellRuntime)).toEqual(+ result.snapshot.document.order,+ );});});@@ -764,19 +901,26 @@ describe("notebookStateFromSession", () => {];const session = createSession(sessionCells);const notebook = createNotebook(notebookCells);- const result = notebookStateFromSession(session, notebook);- expect(result).not.toBeNull();- invariant(result, "result is null");+ const result = readExport({+ session: session,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });+ invariant(result.snapshot, "no snapshot");// Should have all cell IDs in order- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([- ["cell-a", "cell-b", "cell-c", "cell-d", "cell-e", "cell-f"],- ]).inOrderIds,- );+ expect(result.snapshot.document.order).toEqual([+ "cell-a",+ "cell-b",+ "cell-c",+ "cell-d",+ "cell-e",+ "cell-f",+ ]);// Should have correct code and output for each cellfor (const code of ["a", "b", "c", "d", "e", "f"]) {const cid = cellId(`cell-${code}`);- expect(result.cellData[cid].code).toBe(code);+ expect(cellIn(result, cid).code).toBe(code);expect(result.cellRuntime[cid].output).toEqual({channel: "output",data: `${code.toUpperCase()}!`,@@ -868,23 +1012,30 @@ describe("notebookStateFromSession", () => {const session = createSession(sessionCells);const notebook = createNotebook(notebookCells);- const result = notebookStateFromSession(session, notebook);+ const result = readExport({+ session: session,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");// Should have notebook cell IDs in order (notebook is canonical)- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([["cell-a", "cell-c", "cell-z", "cell-e", "cell-g"]])- .inOrderIds,- );+ expect(result.snapshot.document.order).toEqual([+ "cell-a",+ "cell-c",+ "cell-z",+ "cell-e",+ "cell-g",+ ]);// Should have correct code for each cell- expect(result.cellData[cellId("cell-a")].code).toBe("a");- expect(result.cellData[cellId("cell-c")].code).toBe("c");- expect(result.cellData[cellId("cell-z")].code).toBe("z");- expect(result.cellData[cellId("cell-e")].code).toBe("e");- expect(result.cellData[cellId("cell-g")].code).toBe("g");+ expect(cellIn(result, "cell-a").code).toBe("a");+ expect(cellIn(result, "cell-c").code).toBe("c");+ expect(cellIn(result, "cell-z").code).toBe("z");+ expect(cellIn(result, "cell-e").code).toBe("e");+ expect(cellIn(result, "cell-g").code).toBe("g");// Should have session outputs for matching cells (a, c, e)expect(result.cellRuntime[cellId("cell-a")].output).toEqual({@@ -1002,22 +1153,26 @@ describe("notebookStateFromSession", () => {const session = createSession(sessionCells);const notebook = createNotebook(notebookCells);- const result = notebookStateFromSession(session, notebook);+ const result = readExport({+ session: session,+ notebook: notebook,+ filename: null,+ appConfig: {},+ });- expect(result).not.toBeNull();- invariant(result, "result is null");+ invariant(result.snapshot, "no snapshot");// Should have notebook cell IDs in order (notebook is canonical)- expect(result.cellIds.inOrderIds).toEqual(- MultiColumn.from([["cell-1", "cell-2", "cell-3"]]).inOrderIds,- );+ expect(result.snapshot.document.order).toEqual([+ "cell-1",+ "cell-2",+ "cell-3",+ ]);// Should have correct code from notebook- expect(result.cellData[cellId("cell-1")].code).toBe("1 / 0");- expect(result.cellData[cellId("cell-2")].code).toBe('mo.md("Hello")');- expect(result.cellData[cellId("cell-3")].code).toBe(- "x = mo.ui.slider(0, 10)",- );+ expect(cellIn(result, "cell-1").code).toBe("1 / 0");+ expect(cellIn(result, "cell-2").code).toBe('mo.md("Hello")');+ expect(cellIn(result, "cell-3").code).toBe("x = mo.ui.slider(0, 10)");// cell-1: No matching session cell (hash is null), gets stub session cellexpect(result.cellRuntime[cellId("cell-1")].output).toBeNull();diff --git a/frontend/src/core/cells/__tests__/utils.test.ts b/frontend/src/core/cells/__tests__/utils.test.tsindex 79217a34e7..b0b5519209 100644--- a/frontend/src/core/cells/__tests__/utils.test.ts+++ b/frontend/src/core/cells/__tests__/utils.test.ts@@ -95,7 +95,6 @@ describe("getCellConfigs", () => {config: { hide_code: false, disabled: false },} as CellData,},- untouchedNewCells: new Set(),};const result = getCellConfigs(mockState);diff --git a/frontend/src/core/cells/actions.ts b/frontend/src/core/cells/actions.tsindex 172a3b4bc8..152ed754e8 100644--- a/frontend/src/core/cells/actions.ts+++ b/frontend/src/core/cells/actions.ts@@ -3,26 +3,54 @@/** Notebook operations that edit the document and then adjust the editor. */import { historyField } from "@codemirror/commands";-import { atom, type Getter, type Setter, useSetAtom } from "jotai";+import { atom, type Getter, useSetAtom } from "jotai";import { useMemo } from "react";import { scrollAndHighlightCell } from "@/components/editor/links/cell-link";-import type { DocumentModel, EditableDocument } from "@/core/notebook/document";+import type { EditableDocument } from "@/core/notebook/document";import type { CellColumnId } from "@/utils/id-tree";import { Logger } from "@/utils/Logger";+import { clamp } from "@/utils/math";import type { SerializedEditorState } from "../codemirror/types";+import { canCollapseOutline } from "../dom/outline";import type { CellConfig } from "../network/types";import { store } from "../state/jotai";-import { activeDocumentModelAtom } from "../session/active-notebook";+import {+ dropCellOverCellAtom,+ dropCellOverColumnAtom,+ moveCellAtom,+ moveCellsRelativeToAtom,+ moveCellToIndexAtom,+ placeCells,+ sendToBottomAtom,+ sendToTopAtom,+} from "./arrange";import {type DeletedCell,notebookAtom,- notebookReducer,releaseCellAtoms,useReducerActions,} from "./cells";import { resolveColumns } from "./columns";+import { documentOf, focusWhenMounted, modelOf } from "./edit";+import {+ isCodeHidden,+ restoredEditorStatesAtom,+ shownHiddenCodeAtom,+} from "./editor";import { CellId, SCRATCH_CELL_ID, SETUP_CELL_ID } from "./ids";-import { focusAndScrollCellIntoView } from "./scrollCellIntoView";+import {+ collapsedAtom,+ columnOf,+ foldOf,+ foldsAfter,+ foldsHiding,+ layoutAtom,+} from "./layout";+import {+ focusAndScrollCellIntoView,+ scrollToBottom,+ scrollToTop,+} from "./scrollCellIntoView";export interface CreateCellOptions {/** Place the cell after this one. */@@ -45,22 +73,6 @@ export interface CreateCellOptions {export type CreateCell = (options?: CreateCellOptions) => CellId | null;-function modelOf(get: Getter): DocumentModel {- const model = get(activeDocumentModelAtom);- if (!model) {- throw new Error("The notebook has no document to edit");- }- return model;-}--function documentOf(get: Getter): EditableDocument {- const document = get(modelOf(get).documentAtom);- if (!document) {- throw new Error("The notebook has no document to edit");- }- return document;-}-function hasCellWithCode(document: EditableDocument, code: string): boolean {for (const cell of document.cells.values()) {if (cell.code === code) {@@ -70,11 +82,6 @@ function hasCellWithCode(document: EditableDocument, code: string): boolean {return false;}-/** Scroll to and focus the cell once it mounts. */-function focusWhenMounted(set: Setter, cellId: CellId): void {- set(notebookAtom, (state) => ({ ...state, scrollKey: cellId }));-}-/** Create a cell. Returns its id, or null when it was skipped. */export const createCellAtom = atom(null,@@ -91,12 +98,19 @@ export const createCellAtom = atom(// column, so a cell placed first in a later column names its column.let placement: { after?: CellId; before?: CellId } = {};let column: number | null = null;+ // The cell the new one comes right after, whose folds would hide it.+ let follows: CellId | undefined;+ const layout = get(layoutAtom);if (options.after) {- placement = { after: options.after };+ // A folded header hides the cells after it, so a cell placed after+ // the header goes after its fold.+ follows = foldOf(layout, options.after)?.at(-1) ?? options.after;+ placement = { after: follows };} else if (options.before) {const tree = cellIds.findWithId(options.before);const index = cellIds.indexOf(tree);placement = { before: options.before };+ follows = tree.before(options.before);if (index > 0 && tree.indexOfOrThrow(options.before) === 0) {column = index;}@@ -104,7 +118,8 @@ export const createCellAtom = atom(const tree =(options.endOf && cellIds.get(options.endOf)) ?? cellIds.atOrThrow(0);if (tree.length > 0) {- placement = { after: tree.last() };+ follows = tree.last();+ placement = { after: follows };} else if (cellIds.colLength > 1) {column = cellIds.indexOf(tree);}@@ -120,13 +135,22 @@ export const createCellAtom = atom(}});if (focus) {+ // The new cell has no heading, so every section that runs past the+ // cell before it holds it too. Those open, so the cell is on the page.+ const hiding = follows === undefined ? [] : foldsAfter(layout, follows);+ if (hiding.length > 0) {+ set(collapsedAtom, (collapsed) => {+ const next = new Set(collapsed);+ for (const header of hiding) {+ next.delete(header);+ }+ return next;+ });+ }focusWhenMounted(set, id);- // Hidden code stays visible until the cell is blurred for the first time.+ // Hidden code stays showing until the cell is blurred for the first time.if (config.hide_code) {- set(notebookAtom, (state) => ({- ...state,- untouchedNewCells: new Set([...state.untouchedNewCells, id]),- }));+ set(shownHiddenCodeAtom, (cells) => new Set([...cells, id]));}}return id;@@ -151,26 +175,140 @@ export const moveToNextCellAtom = atom(if (cellId === SCRATCH_CELL_ID) {return;}- const notebook = get(notebookAtom);- const column = notebook.cellIds.findWithId(cellId);- const index = column.indexOfOrThrow(cellId);+ const { visible } = columnOf(get(layoutAtom), cellId);+ const index = visible.indexOf(cellId);const nextIndex = before ? index - 1 : index + 1;- if (nextIndex < 0 || nextIndex >= column.length) {+ if (index === -1 || nextIndex < 0 || nextIndex >= visible.length) {if (create) {set(createCellAtom, before ? { before: cellId } : { after: cellId });}return;}- const nextCellId = column.atOrThrow(nextIndex);- const cell = notebook.cellData[nextCellId];- focusAndScrollCellIntoView({- cellId: nextCellId,- cell: notebook.cellHandles[nextCellId],- isCodeHidden:- Boolean(cell.config.hide_code) &&- !notebook.untouchedNewCells.has(nextCellId),- codeFocus: before ? "bottom" : "top",- variableName: undefined,+ focusOnPage(get, visible[nextIndex], before ? "bottom" : "top");+ },+);++/** Focus a cell on the page, scrolling to it. */+function focusOnPage(+ get: Getter,+ cellId: CellId,+ codeFocus: "top" | "bottom" | undefined,+): void {+ const notebook = get(notebookAtom);+ focusAndScrollCellIntoView({+ cellId,+ cell: notebook.cellHandles[cellId],+ isCodeHidden: isCodeHidden(+ notebook.cellData[cellId]?.config.hide_code,+ get(shownHiddenCodeAtom),+ cellId,+ ),+ codeFocus,+ variableName: undefined,+ });+}++/** Focus the visible cell before, after, or at `cellId` within its column. */+export const focusCellAtom = atom(+ null,+ (+ get,+ _set,+ { cellId, where }: { cellId: CellId; where: "before" | "after" | "exact" },+ ): void => {+ const { visible } = columnOf(get(layoutAtom), cellId);+ const index = visible.indexOf(cellId);+ if (index === -1) {+ return;+ }+ const offset = where === "before" ? -1 : where === "after" ? 1 : 0;+ const target = clamp(index + offset, 0, visible.length - 1);+ focusOnPage(get, visible[target], where === "after" ? "top" : "bottom");+ },+);++/** Focus the first visible cell of the first column. */+export const focusTopCellAtom = atom(null, (get): void => {+ const first = get(layoutAtom).columns[0]?.visible[0];+ if (first === undefined) {+ return;+ }+ focusOnPage(get, first, undefined);+ scrollToTop();+});++/** Focus the last visible cell of the last column. */+export const focusBottomCellAtom = atom(null, (get): void => {+ const last = get(layoutAtom).columns.at(-1)?.visible.at(-1);+ if (last === undefined) {+ return;+ }+ focusOnPage(get, last, undefined);+ scrollToBottom();+});++// Folding ---------------------------------------------------------------------+//+// A folded header hides the cells of its section. Which headers are folded is+// editor state; the section each one hides derives from the outlines.++/** Fold the section under `cellId`, if its output has a heading. */+export const collapseCellAtom = atom(+ null,+ (get, set, { cellId }: { cellId: CellId }): void => {+ if (!canCollapseOutline(get(notebookAtom).cellRuntime[cellId]?.outline)) {+ return;+ }+ set(collapsedAtom, (collapsed) => new Set([...collapsed, cellId]));+ focusWhenMounted(set, cellId);+ },+);++/** Unfold the section under `cellId`. */+export const expandCellAtom = atom(+ null,+ (_get, set, { cellId }: { cellId: CellId }): void => {+ set(collapsedAtom, (collapsed) => {+ const next = new Set(collapsed);+ next.delete(cellId);+ return next;+ });+ focusWhenMounted(set, cellId);+ },+);++/** Fold every section in the notebook. */+export const collapseAllCellsAtom = atom(null, (get, set): void => {+ const { cellIds, cellRuntime } = get(notebookAtom);+ set(+ collapsedAtom,+ new Set(+ cellIds.inOrderIds.filter((id) =>+ canCollapseOutline(cellRuntime[id]?.outline),+ ),+ ),+ );+});++/** Unfold every section. */+export const expandAllCellsAtom = atom(null, (_get, set): void => {+ set(collapsedAtom, new Set());+});++/** Unfold whatever hides `cellId`, so it is on the page. */+export const showCellIfHiddenAtom = atom(+ null,+ (get, set, { cellId }: { cellId: CellId }): void => {+ const hiding = foldsHiding(get(layoutAtom), cellId);+ if (hiding.length === 0) {+ return;+ }+ set(collapsedAtom, (collapsed) => {+ const next = new Set(collapsed);+ for (const header of hiding) {+ next.delete(header);+ }+ return next;});},);@@ -247,9 +385,10 @@ export const deleteCellsAtom = atom(};});- // Focus the nearest survivor in the column, looking up before down.+ // Focus the nearest visible survivor in the column, looking up before down.const first = deleting[0].id as CellId;- const ids = notebook.cellIds.findWithId(first).inOrderIds;+ const column = columnOf(get(layoutAtom), first);+ const ids = column.visible.includes(first) ? column.visible : column.ids;const at = ids.indexOf(first);const scrollKey =ids.slice(0, at).findLast((id) => !gone.has(id)) ??@@ -285,12 +424,19 @@ export const deleteCellsAtom = atom(for (const id of gone) {releaseCellAtoms(id);}+ set(shownHiddenCodeAtom, (cells) =>+ cells.size === 0+ ? cells+ : new Set([...cells].filter((id) => !gone.has(id))),+ );+ set(restoredEditorStatesAtom, (states) =>+ [...states.keys()].some((id) => gone.has(id))+ ? new Map([...states].filter(([id]) => !gone.has(id)))+ : states,+ );set(notebookAtom, (state) => ({...state,history: [...state.history, { type: "delete", cells }],- untouchedNewCells: new Set(- [...state.untouchedNewCells].filter((id) => !gone.has(id)),- ),scrollKey,}));return true;@@ -304,12 +450,12 @@ export const undoDeleteCellAtom = atom(null, (get, set): void => {return;}if (last.type === "move") {- set(notebookAtom, (state) =>- notebookReducer(- { ...state, history: state.history.slice(0, -1) },- { type: "undoMoveCells", payload: last },- ),- );+ set(notebookAtom, (state) => ({+ ...state,+ history: state.history.slice(0, -1),+ }));+ placeCells(get, set, last.cellIds, last.placements);+ focusWhenMounted(set, last.cellIds[0]);return;}const model = modelOf(get);@@ -328,32 +474,21 @@ export const undoDeleteCellAtom = atom(null, (get, set): void => {restored.add(cell.id);}});- // Subscribers hear of the edit after the outermost set, so the notebook- // has not followed the document yet. Catch it up to reach the new cells.- const document = get(model.documentAtom);- if (document !== null) {- set(notebookAtom, (state) =>- notebookReducer(state, { type: "reconcileDocument", payload: document }),- );- }- set(notebookAtom, (state) => {- let { cellData } = state;+ // The editors take their history back when they mount.+ set(restoredEditorStatesAtom, (states) => {+ const next = new Map(states);for (const { cell, serializedEditorState } of last.cells) {- const id = cell.id as CellId;- if (serializedEditorState !== null && cellData[id] !== undefined) {- cellData = {- ...cellData,- [id]: { ...cellData[id], serializedEditorState },- };+ if (serializedEditorState !== null) {+ next.set(cell.id as CellId, serializedEditorState);}}- return {- ...state,- cellData,- history: state.history.slice(0, -1),- scrollKey: last.cells[0].cell.id as CellId,- };+ return next;});+ set(notebookAtom, (state) => ({+ ...state,+ history: state.history.slice(0, -1),+ scrollKey: last.cells[0].cell.id as CellId,+ }));});/**@@ -378,18 +513,48 @@ export function useCellActions() {const addSetupCell = useSetAtom(addSetupCellAtom);const deleteCells = useSetAtom(deleteCellsAtom);const undoDeleteCell = useSetAtom(undoDeleteCellAtom);+ const focusCell = useSetAtom(focusCellAtom);+ const focusTopCell = useSetAtom(focusTopCellAtom);+ const focusBottomCell = useSetAtom(focusBottomCellAtom);+ const collapseCell = useSetAtom(collapseCellAtom);+ const expandCell = useSetAtom(expandCellAtom);+ const collapseAllCells = useSetAtom(collapseAllCellsAtom);+ const expandAllCells = useSetAtom(expandAllCellsAtom);+ const showCellIfHidden = useSetAtom(showCellIfHiddenAtom);+ const moveCell = useSetAtom(moveCellAtom);+ const moveCellToIndex = useSetAtom(moveCellToIndexAtom);+ const moveCellsRelativeTo = useSetAtom(moveCellsRelativeToAtom);+ const dropCellOverCell = useSetAtom(dropCellOverCellAtom);+ const dropCellOverColumn = useSetAtom(dropCellOverColumnAtom);+ const sendToTop = useSetAtom(sendToTopAtom);+ const sendToBottom = useSetAtom(sendToBottomAtom);return useMemo(() => ({...operations,+ moveCell,+ moveCellToIndex,+ moveCellsRelativeTo,+ dropCellOverCell,+ dropCellOverColumn,+ sendToTop,+ sendToBottom,createCell,moveToNextCell,addSetupCell,deleteCells,undoDeleteCell,+ focusCell,+ focusTopCell,+ focusBottomCell,+ collapseCell,+ expandCell,+ collapseAllCells,+ expandAllCells,+ showCellIfHidden,}),- // The reducer's actions are stable for the store's lifetime.+ // The reducer's actions and the atom setters are stable for the store's lifetime.// oxlint-disable-next-line react-hooks/exhaustive-deps- [createCell, moveToNextCell, addSetupCell, deleteCells, undoDeleteCell],+ [],);}diff --git a/frontend/src/core/cells/arrange.ts b/frontend/src/core/cells/arrange.tsnew file mode 100644index 0000000000..14a28794e1--- /dev/null+++ b/frontend/src/core/cells/arrange.ts@@ -0,0 +1,341 @@+/* Copyright 2026 Marimo. All rights reserved. */++/** Notebook operations that move cells within and across columns. */++import { dequal as isEqual } from "dequal";+import { atom, type Getter, type Setter } from "jotai";+import type { CellColumnId, CellIndex } from "@/utils/id-tree";+import { arrayMove } from "@/utils/arrays";+import { notebookAtom, type UndoMoveEntry } from "./cells";+import { documentOf, focusWhenMounted, modelOf } from "./edit";+import type { CellId } from "./ids";+import {+ columnOf,+ findColumn,+ type Layout,+ type LayoutColumn,+ layoutAtom,+} from "./layout";++/** A placement to restore a cell to: its column and its index there. */+export interface Placement {+ columnId: CellColumnId;+ index: CellIndex;+}++/** A cell with the cells its fold hides, which move with it. */+function blockOf(column: LayoutColumn, id: CellId): CellId[] {+ return [id, ...(column.folds.get(id) ?? [])];+}++/** A column as the blocks the page shows, in order. Together they hold every cell. */+function blocksOf(column: LayoutColumn): CellId[][] {+ return column.visible.map((id) => blockOf(column, id));+}++/** The cells of every column, as arrays to rearrange. */+function columnsOf(layout: Layout): CellId[][] {+ return layout.columns.map((column) => [...column.ids]);+}++function without(columns: CellId[][], ids: ReadonlySet<CellId>): CellId[][] {+ return columns.map((column) => column.filter((id) => !ids.has(id)));+}++/**+ * The `column` configs that make the document's columns match `columns`,+ * in the form the file is written in: with one column no cell carries a+ * column, and with several only the first cell of each carries its index.+ * An emptied column keeps its place as a gap, since the next column's first+ * cell still names its index, until a drop compacts it.+ */+function columnConfigs(+ columns: readonly (readonly CellId[])[],+ configured: (id: CellId) => number | null,+): Array<[CellId, number | null]> {+ const fixes: Array<[CellId, number | null]> = [];+ const single = columns.length === 1;+ columns.forEach((column, index) => {+ column.forEach((id, position) => {+ const target = !single && position === 0 ? index : null;+ if (configured(id) !== target) {+ fixes.push([id, target]);+ }+ });+ });+ return fixes;+}++/**+ * Make the document's cells fall into `columns`, in that order, as one edit.+ * Nothing is written when they already do.+ */+export function arrange(get: Getter, set: Setter, columns: CellId[][]): void {+ const document = documentOf(get);+ const order = columns.flat();+ const fixes = columnConfigs(+ columns,+ (id) => document.cells.get(id)?.config.column ?? null,+ );+ const reordered = !isEqual(order, document.order);+ if (!reordered && fixes.length === 0) {+ return;+ }+ set(modelOf(get).editAtom, (tx) => {+ if (reordered) {+ tx.setOrder(order);+ }+ for (const [id, column] of fixes) {+ tx.updateConfig(id, { column });+ }+ });+}++/**+ * Move a cell one block up or down its column, or to the start of the+ * neighbouring column. A folded header moves with its section.+ */+export const moveCellAtom = atom(+ null,+ (+ get,+ set,+ {+ cellId,+ before,+ direction,+ }: { cellId: CellId; before?: boolean; direction?: "left" | "right" },+ ): void => {+ const layout = get(layoutAtom);+ const column = columnOf(layout, cellId);+ const at = layout.columns.indexOf(column);+ const columns = columnsOf(layout);+ if (direction) {+ const to = direction === "left" ? at - 1 : at + 1;+ if (to < 0 || to >= columns.length) {+ return;+ }+ const block = blockOf(column, cellId);+ const cleaned = without(columns, new Set(block));+ cleaned[to] = [...block, ...cleaned[to]];+ arrange(get, set, cleaned);+ focusWhenMounted(set, cellId);+ return;+ }+ const blocks = blocksOf(column);+ const index = blocks.findIndex((block) => block[0] === cellId);+ const target = before ? index - 1 : index + 1;+ if (index !== -1 && target >= 0 && target < blocks.length) {+ columns[at] = arrayMove(blocks, index, target).flat();+ arrange(get, set, columns);+ }+ focusWhenMounted(set, cellId);+ },+);++function sendTo(+ get: Getter,+ set: Setter,+ { cellId, scroll = true }: { cellId: CellId; scroll?: boolean },+ edge: "top" | "bottom",+): void {+ const layout = get(layoutAtom);+ const column = columnOf(layout, cellId);+ const blocks = blocksOf(column);+ const index = blocks.findIndex((block) => block[0] === cellId);+ const target = edge === "top" ? 0 : blocks.length - 1;+ if (index === -1 || index === target) {+ return;+ }+ const columns = columnsOf(layout);+ columns[layout.columns.indexOf(column)] = arrayMove(+ blocks,+ index,+ target,+ ).flat();+ arrange(get, set, columns);+ if (scroll) {+ focusWhenMounted(set, cellId);+ }+}++/** Move a cell, with its fold, to the top of its column. */+export const sendToTopAtom = atom(+ null,+ (get, set, options: { cellId: CellId; scroll?: boolean }): void =>+ sendTo(get, set, options, "top"),+);++/** Move a cell, with its fold, to the bottom of its column. */+export const sendToBottomAtom = atom(+ null,+ (get, set, options: { cellId: CellId; scroll?: boolean }): void =>+ sendTo(get, set, options, "bottom"),+);++/** Drop a dragged cell, with its fold, where another cell is. */+export const dropCellOverCellAtom = atom(+ null,+ (+ get,+ set,+ { cellId, overCellId }: { cellId: CellId; overCellId: CellId },+ ): void => {+ const layout = get(layoutAtom);+ const from = columnOf(layout, cellId);+ const to = columnOf(layout, overCellId);+ const columns = columnsOf(layout);+ if (from === to) {+ const blocks = blocksOf(from);+ const index = blocks.findIndex((block) => block[0] === cellId);+ const target = blocks.findIndex((block) => block[0] === overCellId);+ if (index === -1 || target === -1 || index === target) {+ return;+ }+ columns[layout.columns.indexOf(from)] = arrayMove(+ blocks,+ index,+ target,+ ).flat();+ arrange(get, set, columns);+ return;+ }+ const block = blockOf(from, cellId);+ const cleaned = without(columns, new Set(block));+ const target = cleaned[layout.columns.indexOf(to)];+ const at = target.indexOf(overCellId);+ target.splice(at, 0, ...block);+ arrange(get, set, cleaned);+ },+);++/** Drop a dragged cell, with its fold, at the start of a column. */+export const dropCellOverColumnAtom = atom(+ null,+ (+ get,+ set,+ { cellId, columnId }: { cellId: CellId; columnId: CellColumnId },+ ): void => {+ const layout = get(layoutAtom);+ const to = findColumn(layout, columnId);+ if (to === undefined) {+ return;+ }+ const block = blockOf(columnOf(layout, cellId), cellId);+ const cleaned = without(columnsOf(layout), new Set(block));+ cleaned[layout.columns.indexOf(to)].unshift(...block);+ arrange(get, set, cleaned);+ },+);++/** Move a cell, with its fold, to an index in a column. Out of range clamps. */+export const moveCellToIndexAtom = atom(+ null,+ (+ get,+ set,+ {+ cellId,+ columnId,+ index,+ }: { cellId: CellId; columnId: CellColumnId; index: number },+ ): void => {+ const layout = get(layoutAtom);+ const to = findColumn(layout, columnId);+ if (to === undefined) {+ return;+ }+ const from = columnOf(layout, cellId);+ const block = blockOf(from, cellId);+ const columns = columnsOf(layout);+ const fromIndex = from.ids.indexOf(cellId);+ const cleaned = without(columns, new Set(block));+ const target = cleaned[layout.columns.indexOf(to)];+ let at = Math.max(0, Math.min(index, to.ids.length));+ if (from === to && fromIndex < at) {+ at -= block.length;+ }+ target.splice(Math.max(0, Math.min(at, target.length)), 0, ...block);+ arrange(get, set, cleaned);+ },+);++/**+ * Move cells to just before or after a target cell, in their order. With+ * the cells' previous placements, the move can be undone.+ */+export const moveCellsRelativeToAtom = atom(+ null,+ (+ get,+ set,+ {+ cellIds,+ targetCellId,+ position,+ previousPlacements,+ }: {+ cellIds: CellId[];+ targetCellId: CellId;+ position: "before" | "after";+ previousPlacements?: Placement[];+ },+ ): void => {+ if (cellIds.length === 0) {+ return;+ }+ const layout = get(layoutAtom);+ const moving = new Set(cellIds);+ const cleaned = without(columnsOf(layout), moving);+ const target =+ cleaned[layout.columns.indexOf(columnOf(layout, targetCellId))];+ let at = target.indexOf(targetCellId);+ if (at === -1) {+ // The target moves too, so the cells go to the end of its column.+ at = target.length;+ } else if (position === "after") {+ at += 1;+ }+ target.splice(at, 0, ...cellIds);+ arrange(get, set, cleaned);+ if (previousPlacements && previousPlacements.length === cellIds.length) {+ const entry: UndoMoveEntry = {+ type: "move",+ cellIds,+ placements: previousPlacements,+ };+ set(notebookAtom, (state) => ({+ ...state,+ history: [...state.history, entry],+ }));+ }+ },+);++/** Put cells back where they were, by column and index. A vanished column takes the last. */+export function placeCells(+ get: Getter,+ set: Setter,+ cellIds: readonly CellId[],+ placements: readonly Placement[],+): void {+ const layout = get(layoutAtom);+ const cleaned = without(columnsOf(layout), new Set(cellIds));+ const columnIndex = (columnId: CellColumnId) => {+ const index = layout.columns.findIndex((column) => column.id === columnId);+ return index === -1 ? cleaned.length - 1 : index;+ };+ const sorted = cellIds+ .map((id, i) => ({+ id,+ column: columnIndex(placements[i].columnId),+ index: placements[i].index,+ }))+ .toSorted((a, b) => a.column - b.column || a.index - b.index);+ for (const { id, column, index } of sorted) {+ const target = cleaned[column];+ target.splice(Math.max(0, Math.min(index, target.length)), 0, id);+ }+ arrange(get, set, cleaned);+}diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex cba00c4bc4..82400de26b 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -13,7 +13,6 @@ import {} from "@/utils/id-tree";import { invariant } from "@/utils/invariant";import { Logger } from "@/utils/Logger";-import { clamp } from "@/utils/math";import { Objects } from "@/utils/objects";import { extractAllTracebackInfo, type TracebackInfo } from "@/utils/traceback";import { createReducerAndAtoms } from "../../utils/createReducer";@@ -22,7 +21,7 @@ import { editorMountScheduler } from "../codemirror/editor-mount-scheduler";import { prepareCellCodeUpdate } from "../codemirror/language/cell-code";import { splitEditor } from "../codemirror/language/utils";import type { SerializedEditorState } from "../codemirror/types";-import { findCollapseRange, mergeOutlines } from "../dom/outline";+import { mergeOutlines } from "../dom/outline";import type { CellMessage } from "../kernel/messages";import { isErrorMime } from "../mime";import type { CellConfig } from "../network/types";@@ -30,13 +29,11 @@ import { createDeepEqualAtom, store } from "../state/jotai";import { isWasm } from "../wasm/utils";import { prepareCellForExecution, transitionCell } from "./cell";import { applyDocument, documentEditMiddleware } from "./document";+import { isCodeHidden, shownHiddenCodeAtom } from "./editor";import { CellId, SCRATCH_CELL_ID } from "./ids";import { type CellLog, getCellLogsForMessage } from "./logs";-import {- focusAndScrollCellIntoView,- scrollToBottom,- scrollToTop,-} from "./scrollCellIntoView";+import type { Outline } from "./outline";+import { focusAndScrollCellIntoView } from "./scrollCellIntoView";import {type CellData,type CellRuntimeState,@@ -116,12 +113,6 @@ export interface NotebookState {* Logs of all cell messages*/cellLogs: CellLog[];- /**- * Set of cells that have been created that are initialized with `hide_code`.- *- * These start temporarily open until their first blur event.- */- untouchedNewCells: Set<CellId>;}function withScratchCell(notebookState: NotebookState): NotebookState {@@ -160,7 +151,6 @@ export function initialNotebookState(): NotebookState {history: [],scrollKey: null,cellLogs: [],- untouchedNewCells: new Set<CellId>(),});}@@ -174,226 +164,6 @@ const {useActions,valueAtom: notebookAtom,} = createReducerAndAtoms(initialNotebookState, {- moveCell: (- state,- action: {- cellId: CellId;- before?: boolean;- direction?: "left" | "right";- },- ) => {- const { cellId, before, direction } = action;-- if (before !== undefined && direction !== undefined) {- Logger.warn(- "Both before and direction specified for moveCell. Ignoring one.",- );- }-- // Handle left/right movement- if (direction) {- const fromColumn = state.cellIds.findWithId(cellId);- const fromColumnIndex = state.cellIds.indexOf(fromColumn);- const toColumnIndex =- direction === "left" ? fromColumnIndex - 1 : fromColumnIndex + 1;- const toColumn = state.cellIds.at(toColumnIndex);-- // If no column to move to, return unchanged state- if (!toColumn) {- return state;- }-- return {- ...state,- cellIds: state.cellIds.moveAcrossColumns(- fromColumn.id,- cellId,- toColumn.id,- undefined,- ),- scrollKey: cellId,- };- }-- // Handle up/down movement- const column = state.cellIds.findWithId(cellId);- const cellIndex = column.indexOfOrThrow(cellId);-- if (before && cellIndex === 0) {- return {- ...state,- cellIds: state.cellIds.moveWithinColumn(column.id, cellIndex, 0),- scrollKey: cellId,- };- }- if (!before && cellIndex === column.length - 1) {- return {- ...state,- cellIds: state.cellIds.moveWithinColumn(- column.id,- cellIndex,- column.length - 1,- ),- scrollKey: cellId,- };- }-- return before- ? {- ...state,- cellIds: state.cellIds.moveWithinColumn(- column.id,- cellIndex,- cellIndex - 1,- ),- scrollKey: cellId,- }- : {- ...state,- cellIds: state.cellIds.moveWithinColumn(- column.id,- cellIndex,- cellIndex + 1,- ),- scrollKey: cellId,- };- },- moveCellToIndex: (- state,- action: {- cellId: CellId;- columnId: CellColumnId;- index: number;- },- ) => {- const { cellId, columnId, index } = action;- const fromColumn = state.cellIds.findWithId(cellId);- const fromIndex = fromColumn.indexOfOrThrow(cellId);-- const destinationColumn = state.cellIds.get(columnId);- if (!destinationColumn) {- return state;- }-- const clampedIndex = Math.max(0, Math.min(index, destinationColumn.length));- const adjustedIndex =- fromColumn.id === columnId && fromIndex < clampedIndex- ? clampedIndex - 1- : clampedIndex;-- if (fromColumn.id === columnId && fromIndex === adjustedIndex) {- return state;- }-- const withoutCell = state.cellIds.deleteById(cellId);- const updatedColumn = withoutCell.get(columnId);- if (!updatedColumn) {- return state;- }-- return {- ...state,- cellIds: withoutCell.insertId(- cellId,- columnId,- Math.max(0, Math.min(adjustedIndex, updatedColumn.length)),- ),- scrollKey: null,- };- },- dropCellOverCell: (state, action: { cellId: CellId; overCellId: CellId }) => {- const { cellId, overCellId } = action;-- const fromColumn = state.cellIds.findWithId(cellId);- const toColumn = state.cellIds.findWithId(overCellId);-- const fromIndex = fromColumn.indexOfOrThrow(cellId);- const toIndex = toColumn.indexOfOrThrow(overCellId);-- if (fromColumn.id === toColumn.id) {- if (fromIndex === toIndex) {- return state;- }- return {- ...state,- cellIds: state.cellIds.moveWithinColumn(- fromColumn.id,- fromIndex,- toIndex,- ),- scrollKey: null,- };- }-- return {- ...state,- cellIds: state.cellIds.moveAcrossColumns(- fromColumn.id,- cellId,- toColumn.id,- overCellId,- ),- scrollKey: null,- };- },- moveCellsRelativeTo: (- state,- action: {- cellIds: CellId[];- targetCellId: CellId;- position: "before" | "after";- previousPlacements?: Array<{ columnId: CellColumnId; index: CellIndex }>;- },- ) => {- const { cellIds, targetCellId, position, previousPlacements } = action;- if (cellIds.length === 0) {- return state;- }- const newCellIds = state.cellIds.moveCellsRelativeTo(- cellIds,- targetCellId,- position,- );- // Only record undo when caller provided full before-state- const canUndoMove =- previousPlacements && previousPlacements.length === cellIds.length;- const history = canUndoMove- ? [- ...state.history,- { type: "move" as const, cellIds, placements: previousPlacements },- ]- : state.history;- return {- ...state,- cellIds: newCellIds,- history,- scrollKey: null,- };- },- dropCellOverColumn: (- state,- action: { cellId: CellId; columnId: CellColumnId },- ) => {- const { cellId, columnId } = action;- const fromColumn = state.cellIds.findWithId(cellId);-- return {- ...state,- cellIds: state.cellIds.moveAcrossColumns(- fromColumn.id,- cellId,- columnId,- undefined,- ),- };- },- dropOverNewColumn: (state, action: { cellId: CellId }) => {- const { cellId } = action;- return {- ...state,- cellIds: state.cellIds.moveToNewColumn(cellId),- };- },moveColumn: (state,action: {@@ -409,112 +179,6 @@ const {cellIds: state.cellIds.moveColumn(action.column, action.overColumn),};},- focusCell: (- state,- action: { cellId: CellId; where: "before" | "after" | "exact" },- ) => {- const column = state.cellIds.findWithId(action.cellId);- if (column.length === 0) {- return state;- }-- const { cellId, where } = action;- const index = column.indexOfOrThrow(cellId);-- let focusIndex: number;- if (where === "before") {- focusIndex = clamp(index - 1, 0, column.length - 1);- } else if (where === "after") {- focusIndex = clamp(index + 1, 0, column.length - 1);- } else {- focusIndex = index;- }- const focusCellId = column.atOrThrow(focusIndex);- // can scroll immediately, without setting scrollKey in state, because- // CellArray won't need to re-render- focusAndScrollCellIntoView({- cellId: focusCellId,- cell: state.cellHandles[focusCellId],- isCodeHidden: isCellCodeHidden(state, focusCellId),- codeFocus: where === "after" ? "top" : "bottom",- variableName: undefined,- });- return state;- },- focusTopCell: (state) => {- // TODO: focus the existing column, not the first column- const column = state.cellIds.getColumns().at(0);- if (column === undefined || column.length === 0) {- return state;- }-- const cellId = column.first();- focusAndScrollCellIntoView({- cellId: cellId,- cell: state.cellHandles[cellId],- isCodeHidden: isCellCodeHidden(state, cellId),- codeFocus: undefined,- variableName: undefined,- });- scrollToTop();- return state;- },- focusBottomCell: (state) => {- // TODO: focus the existing column, not the last column- const column = state.cellIds.getColumns().at(-1);- if (column === undefined || column.length === 0) {- return state;- }-- const cellId = column.last();- focusAndScrollCellIntoView({- cellId: cellId,- cell: state.cellHandles[cellId],- isCodeHidden: isCellCodeHidden(state, cellId),- codeFocus: undefined,- variableName: undefined,- });- scrollToBottom();- return state;- },- sendToTop: (state, action: { cellId: CellId; scroll?: boolean }) => {- const column = state.cellIds.findWithId(action.cellId);- if (column.length === 0) {- return state;- }-- const { cellId, scroll = true } = action;- const cellIndex = column.indexOfOrThrow(cellId);- if (cellIndex === 0) {- return state;- }-- return {- ...state,- cellIds: state.cellIds.moveWithinColumn(column.id, cellIndex, 0),- scrollKey: scroll ? cellId : null,- };- },- sendToBottom: (state, action: { cellId: CellId; scroll?: boolean }) => {- const column = state.cellIds.findWithId(action.cellId);- if (column.length === 0) {- return state;- }-- const { cellId, scroll = true } = action;- const cellIndex = column.indexOfOrThrow(cellId);- const newIndex = column.length - 1;-- if (cellIndex === newIndex) {- return state;- }-- return {- ...state,- cellIds: state.cellIds.moveWithinColumn(column.id, cellIndex, newIndex),- scrollKey: scroll ? cellId : null,- };- },addColumn: (state, action: { columnId: CellColumnId }) => {// Add column and new cellconst newCellId = CellId.create();@@ -573,39 +237,6 @@ const {** TODO(MO-8028): Move to `undoDeleteCellAtom` with the order family.*/- undoMoveCells: (state, action: UndoMoveEntry) => {- const { cellIds, placements } = action;- if (- cellIds.length === 0 ||- placements.length !== cellIds.length ||- cellIds.some((id) => !state.cellData[id])- ) {- return state;- }- const toRestore = cellIds.map((id, i) => ({- id,- columnId: placements[i].columnId,- index: placements[i].index,- }));- return {- ...state,- cellIds: state.cellIds.placeCells(toRestore),- scrollKey: cellIds[0] ?? null,- };- },- clearSerializedEditorState: (state, action: { cellId: CellId }) => {- const { cellId } = action;- return updateCellData({- state,- cellId,- cellReducer: (cell) => {- return {- ...cell,- serializedEditorState: null,- };- },- });- },updateCellCode: (state,action: {@@ -781,34 +412,6 @@ const {}return { ...state, cellRuntime };},- markTouched: (state, action: { cellId: CellId }) => {- const { cellId } = action;-- if (state.untouchedNewCells.has(cellId)) {- const nextUntouchedNewCells = new Set(state.untouchedNewCells);- nextUntouchedNewCells.delete(cellId);- return {- ...state,- untouchedNewCells: nextUntouchedNewCells,- };- }-- return state;- },- markUntouched: (state, action: { cellId: CellId }) => {- const { cellId } = action;-- if (!state.untouchedNewCells.has(cellId)) {- const nextUntouchedNewCells = new Set(state.untouchedNewCells);- nextUntouchedNewCells.add(cellId);- return {- ...state,- untouchedNewCells: nextUntouchedNewCells,- };- }-- return state;- },scrollToTarget: (state) => {// Scroll to the specified cell and clear the scroll key.const scrollKey = state.scrollKey;@@ -825,7 +428,11 @@ const {focusAndScrollCellIntoView({cellId: cellId,cell: state.cellHandles[cellId],- isCodeHidden: isCellCodeHidden(state, cellId),+ isCodeHidden: isCodeHidden(+ state.cellData[cellId]?.config.hide_code,+ store.get(shownHiddenCodeAtom),+ cellId,+ ),codeFocus: undefined,variableName: undefined,});@@ -855,108 +462,6 @@ const {cellLogs: [],};},- collapseCell: (state, action: { cellId: CellId }) => {- const { cellId } = action;- const column = state.cellIds.findWithId(cellId);-- // Get all the top-level outlines- const outlines = column.topLevelIds.map((id) => {- const cell = state.cellRuntime[id];- return cell.outline;- });-- // Find the start/end of the collapsed range- const startIndex = column.indexOfOrThrow(cellId);- const range = findCollapseRange(startIndex, outlines);- if (!range) {- return state;- }- const endCellId = column.atOrThrow(range[1]);-- return {- ...state,- // Collapse the range- cellIds: state.cellIds.transformWithCellId(cellId, (column) =>- column.collapse(cellId, endCellId),- ),- scrollKey: cellId,- };- },- expandCell: (state, action: { cellId: CellId }) => {- const { cellId } = action;- return {- ...state,- cellIds: state.cellIds.transformWithCellId(cellId, (column) =>- column.expand(cellId),- ),- scrollKey: cellId,- };- },- collapseAllCells: (state) => {- return {- ...state,- cellIds: state.cellIds.transformAll((column) => {- // Get all the top-level outlines- const outlines = column.topLevelIds.map((id) => {- const cell = state.cellRuntime[id];- return cell.outline;- });-- // Find the start/end of the collapsed ranges- const nodes = [...column.nodes];- const visibleEndByOriginalEnd = new Map<CellIndex, CellIndex>();- const reversedCollapseRanges = [];-- // Iterate in reverse order (bottom-up) to process children first- let i = nodes.length - 1;- while (i >= 0) {- const range = findCollapseRange(i, outlines);- if (range) {- const startIndex = i;- const originalEnd = range[1];- const endIndex =- visibleEndByOriginalEnd.get(originalEnd) ?? originalEnd;-- // After this section collapses, its heading represents this- // endpoint for any enclosing section that shares it.- visibleEndByOriginalEnd.set(originalEnd, startIndex);-- // Add the range to the list of ranges- const cellId = column.atOrThrow(startIndex);- const until = column.atOrThrow(endIndex);- reversedCollapseRanges.push({ id: cellId, until });- } else {- reversedCollapseRanges.push(null);- }- i--;- }-- const collapseRanges = reversedCollapseRanges.toReversed();- return column.collapseAll(collapseRanges);- }),- };- },- expandAllCells: (state) => {- return {- ...state,- cellIds: state.cellIds.transformAll((column) => column.expandAll()),- };- },- showCellIfHidden: (state, action: { cellId: CellId }) => {- const { cellId } = action;- const column = state.cellIds.findWithId(cellId);- const prev = column;- const result = column.findAndExpandDeep(cellId);-- if (result.equals(prev)) {- return state;- }-- return {- ...state,- cellIds: state.cellIds.transformWithCellId(cellId, () => result),- };- },splitCell: (state, action: { cellId: CellId }) => {const { cellId } = action;const column = state.cellIds.findWithId(cellId);@@ -1108,13 +613,6 @@ const {// strictly type the dispatched actions without creating a circular dependency.addMiddleware(documentEditMiddleware);-function isCellCodeHidden(state: NotebookState, cellId: CellId): boolean {- return (- Boolean(state.cellData[cellId].config.hide_code) &&- !state.untouchedNewCells.has(cellId)- );-}-// Helper function to update a cell in the arrayfunction updateCellRuntimeState({state,@@ -1266,6 +764,24 @@ export const cellErrorsAtom = atom((get) => {return errors;});+/**+ * The outline of each cell whose output has a heading. Compared by value, so+ * readers are left alone by the runtime messages that change no heading.+ */+export const cellOutlinesAtom = createDeepEqualAtom(+ atom((get) => {+ const outlines: Partial<Record<CellId, Outline>> = {};+ for (const [id, runtime] of Objects.entries(+ get(notebookAtom).cellRuntime,+ )) {+ if (runtime.outline !== null && runtime.outline.items.length > 0) {+ outlines[id] = runtime.outline;+ }+ }+ return outlines;+ }),+);+export const notebookOutline = atom((get) => {const cellIds = get(cellIdsAtom);const cellRuntime = get(cellsRuntimeAtom);@@ -1445,10 +961,6 @@ export function flattenTopLevelNotebookCells();}-export function createUntouchedCellAtom(cellId: CellId): Atom<boolean> {- return atom((get) => get(notebookAtom).untouchedNewCells.has(cellId));-}-export function createTracebackInfoAtom(cellId: CellId,): Atom<TracebackInfo[] | undefined> {@@ -1523,7 +1035,6 @@ export const exportedForTesting = {reducer,createActions,initialNotebookState,- isCellCodeHidden,// Export atom families for testing cleanupcellDataAtom,cellRuntimeAtom,diff --git a/frontend/src/core/cells/document.ts b/frontend/src/core/cells/document.tsindex 12dd063527..7d9582b3d7 100644--- a/frontend/src/core/cells/document.ts+++ b/frontend/src/core/cells/document.ts@@ -42,7 +42,7 @@ type CellAction = DispatchedActionOf<ReducerCellActions>;// Following the document -----------------------------------------------------/** Rebuild the tree for `columns`, keeping column ids and collapsed sections. */+/** Rebuild the tree for `columns`, keeping column ids. */function reconcileColumns(current: MultiColumn<CellId>,columns: CellId[][],@@ -59,9 +59,7 @@ function reconcileColumns(return current;}return new MultiColumn(- columns.map((ids, index) =>- CollapsibleTree.fromWithPreviousShape(ids, previous[index]),- ),+ columns.map((ids, index) => CollapsibleTree.from(ids, previous[index]?.id)),);}@@ -139,7 +137,10 @@ export function applyDocument(edited: code.trim().length > 0,}),};- cellRuntime = { ...cellRuntime, [id]: createCellRuntimeState() };+ cellRuntime = {+ ...cellRuntime,+ [id]: cellRuntime[id] ?? createCellRuntimeState(),+ };cellHandles = { ...cellHandles, [id]: createRef() };continue;}diff --git a/frontend/src/core/cells/edit.ts b/frontend/src/core/cells/edit.tsnew file mode 100644index 0000000000..766d04b4c1--- /dev/null+++ b/frontend/src/core/cells/edit.ts@@ -0,0 +1,30 @@+/* Copyright 2026 Marimo. All rights reserved. */++/** The active document model, as the notebook operations reach it. */++import type { Getter, Setter } from "jotai";+import type { DocumentModel, EditableDocument } from "@/core/notebook/document";+import { activeDocumentModelAtom } from "../session/active-notebook";+import { notebookAtom } from "./cells";+import type { CellId } from "./ids";++export function modelOf(get: Getter): DocumentModel {+ const model = get(activeDocumentModelAtom);+ if (!model) {+ throw new Error("The notebook has no document to edit");+ }+ return model;+}++export function documentOf(get: Getter): EditableDocument {+ const document = get(modelOf(get).documentAtom);+ if (!document) {+ throw new Error("The notebook has no document to edit");+ }+ return document;+}++/** Scroll to and focus the cell once it mounts. */+export function focusWhenMounted(set: Setter, cellId: CellId): void {+ set(notebookAtom, (state) => ({ ...state, scrollKey: cellId }));+}diff --git a/frontend/src/core/cells/editor.ts b/frontend/src/core/cells/editor.tsnew file mode 100644index 0000000000..64eff3ea16--- /dev/null+++ b/frontend/src/core/cells/editor.ts@@ -0,0 +1,82 @@+/* Copyright 2026 Marimo. All rights reserved. */++/** What only this browser knows about cells: hidden code showing for now, and editor state to restore. */++import { atom, useAtomValue } from "jotai";+import { useMemo } from "react";+import type { SerializedEditorState } from "../codemirror/types";+import type { CellId } from "./ids";++/**+ * Hidden cells whose code is showing for now: a cell being edited, one just+ * created, or one just made hidden. Blurring the cell hides it again.+ */+export const shownHiddenCodeAtom = atom<ReadonlySet<CellId>>(new Set<CellId>());++export const useShowsHiddenCode = (cellId: CellId) =>+ useAtomValue(+ useMemo(+ () => atom((get) => get(shownHiddenCodeAtom).has(cellId)),+ [cellId],+ ),+ );++/** Whether a cell's code is hidden on the page. */+export function isCodeHidden(+ hideCode: boolean | undefined,+ shown: ReadonlySet<CellId>,+ cellId: CellId,+): boolean {+ return Boolean(hideCode) && !shown.has(cellId);+}++export const showHiddenCodeAtom = atom(+ null,+ (_get, set, { cellId }: { cellId: CellId }): void => {+ set(shownHiddenCodeAtom, (cells) => new Set([...cells, cellId]));+ },+);++/** Hide a cell's code again. Returns whether it was showing. */+export const hideShownCodeAtom = atom(+ null,+ (get, set, { cellId }: { cellId: CellId }): boolean => {+ if (!get(shownHiddenCodeAtom).has(cellId)) {+ return false;+ }+ set(shownHiddenCodeAtom, (cells) => {+ const next = new Set(cells);+ next.delete(cellId);+ return next;+ });+ return true;+ },+);++/**+ * Editor state for cells about to mount again, such as a cell undo brings+ * back. The editor takes its entry when it mounts, and deleting the cell+ * drops it.+ */+export const restoredEditorStatesAtom = atom<+ ReadonlyMap<CellId, SerializedEditorState>+>(new Map<CellId, SerializedEditorState>());++export const useRestoredEditorState = (cellId: CellId) =>+ useAtomValue(+ useMemo(+ () => atom((get) => get(restoredEditorStatesAtom).get(cellId) ?? null),+ [cellId],+ ),+ );++export const takeRestoredEditorStateAtom = atom(+ null,+ (_get, set, { cellId }: { cellId: CellId }): void => {+ set(restoredEditorStatesAtom, (states) => {+ const next = new Map(states);+ next.delete(cellId);+ return next;+ });+ },+);diff --git a/frontend/src/core/cells/layout.ts b/frontend/src/core/cells/layout.tsnew file mode 100644index 0000000000..6407b1235e--- /dev/null+++ b/frontend/src/core/cells/layout.ts@@ -0,0 +1,152 @@+/* Copyright 2026 Marimo. All rights reserved. */++/** The cells as they appear on the page: by column, with folded sections hidden. */++import { atom, useAtomValue } from "jotai";+import type { CellColumnId } from "@/utils/id-tree";+import { findCollapseRange } from "../dom/outline";+import { cellIdsAtom, cellOutlinesAtom } from "./cells";+import type { CellId } from "./ids";+import type { Outline } from "./outline";++/** The headers whose sections the user folded. Only this browser knows. */+export const collapsedAtom = atom<ReadonlySet<CellId>>(new Set<CellId>());++export interface LayoutColumn {+ readonly id: CellColumnId;+ /** Every cell of the column, in order. */+ readonly ids: readonly CellId[];+ /** The cells on the page: those no fold hides. */+ readonly visible: readonly CellId[];+ /**+ * Each folded header and the cells it hides, nested sections included. A+ * folded header with nothing under it yet has an empty fold.+ */+ readonly folds: ReadonlyMap<CellId, readonly CellId[]>;+}++export interface Layout {+ readonly columns: readonly LayoutColumn[];+}++/**+ * The cells each folded header hides. A section runs from its header to the+ * cell before the next header of the same or a higher level, so a folded+ * header inside a folded section is hidden along with its own section.+ */+export function foldSections(+ ids: readonly CellId[],+ outlines: (Outline | null)[],+ collapsed: ReadonlySet<CellId>,+): Map<CellId, readonly CellId[]> {+ const folds = new Map<CellId, readonly CellId[]>();+ ids.forEach((id, index) => {+ const outline = outlines[index];+ if (!collapsed.has(id) || !outline || outline.items.length === 0) {+ return;+ }+ const range = findCollapseRange(index, outlines);+ if (range === null) {+ return;+ }+ folds.set(id, ids.slice(index + 1, range[1] + 1));+ });+ return folds;+}++export function deriveLayout(+ columns: ReadonlyArray<{ id: CellColumnId; ids: readonly CellId[] }>,+ outlineOf: (id: CellId) => Outline | null,+ collapsed: ReadonlySet<CellId>,+): Layout {+ return {+ columns: columns.map(({ id, ids }) => {+ const folds = foldSections(ids, ids.map(outlineOf), collapsed);+ const hidden = new Set([...folds.values()].flat());+ return { id, ids, visible: ids.filter((c) => !hidden.has(c)), folds };+ }),+ };+}++/**+ * The layout of the notebook's cells.+ *+ * TODO(MO-8028): Order and columns come from the reducer's tree until the+ * arrange family edits the document; then they derive from the document and+ * the column ids this browser keeps. Outlines come from executions later.+ */+export const layoutAtom = atom((get): Layout => {+ const outlines = get(cellOutlinesAtom);+ return deriveLayout(+ get(cellIdsAtom)+ .getColumns()+ .map((column) => ({ id: column.id, ids: column.inOrderIds })),+ (id) => outlines[id] ?? null,+ get(collapsedAtom),+ );+});++export const useLayout = () => useAtomValue(layoutAtom);++export function findColumn(+ layout: Layout,+ columnId: CellColumnId,+): LayoutColumn | undefined {+ return layout.columns.find((column) => column.id === columnId);+}++/** The column holding `id`. Throws for a cell the layout does not have. */+export function columnOf(layout: Layout, id: CellId): LayoutColumn {+ const column = layout.columns.find((column) => column.ids.includes(id));+ if (column === undefined) {+ throw new Error(`Cell ${id} is not in the layout`);+ }+ return column;+}++/** The cells a folded header hides, or undefined when `id` is not a folded header. */+export function foldOf(+ layout: Layout,+ id: CellId,+): readonly CellId[] | undefined {+ for (const column of layout.columns) {+ const fold = column.folds.get(id);+ if (fold !== undefined) {+ return fold;+ }+ }+ return undefined;+}++/** The headers whose folds hide `id`. */+export function foldsHiding(layout: Layout, id: CellId): CellId[] {+ const column = layout.columns.find((column) => column.ids.includes(id));+ if (column === undefined) {+ return [];+ }+ return [...column.folds]+ .filter(([, hidden]) => hidden.includes(id))+ .map(([header]) => header);+}++/**+ * The folded headers whose sections a cell without a heading would fall+ * into, placed right after `id`: those hiding `id`, and `id` itself when it+ * is a folded header. A section runs until the next heading, so a cell+ * placed after the last cell of a fold is still inside it.+ */+export function foldsAfter(layout: Layout, id: CellId): CellId[] {+ const hiding = foldsHiding(layout, id);+ return foldOf(layout, id) === undefined ? hiding : [...hiding, id];+}++/** The visible cell `offset` places from `id` in its column, if there is one. */+export function visibleNeighbor(+ layout: Layout,+ id: CellId,+ offset: -1 | 1,+): CellId | undefined {+ const { visible } = columnOf(layout, id);+ const index = visible.indexOf(id);+ return index === -1 ? undefined : visible[index + offset];+}diff --git a/frontend/src/core/cells/session.ts b/frontend/src/core/cells/session.tsindex 47fac79417..6779c09b4b 100644--- a/frontend/src/core/cells/session.ts+++ b/frontend/src/core/cells/session.ts@@ -1,17 +1,19 @@/* Copyright 2026 Marimo. All rights reserved. */+/** Read the notebook a page was served with: its cells as a host snapshot, and their outputs. */++import type * as Protocol from "@marimo-team/client/protocol";import type * as api from "@marimo-team/marimo-api";import { mergeArray } from "@/utils/edit-distance";-import { MultiColumn } from "@/utils/id-tree";import { Logger } from "@/utils/Logger";import { parseOutline } from "../dom/outline";-import type { NotebookState } from "./cells";+import type { StaticNotebookSnapshot } from "../transports/static";import { CellId, SETUP_CELL_ID } from "./ids";-import {- type CellData,- type CellRuntimeState,- createCellRuntimeState,-} from "./types";+import { DEFAULT_CELL_NAME } from "./names";+import { type CellRuntimeState, createCellRuntimeState } from "./types";++/** The identity of a snapshot the page carries. A host's own stream replaces it. */+const EMBEDDED = "embedded";// Constantsconst DEFAULT_TIMESTAMP = 0;@@ -143,7 +145,7 @@ function createEmptyNotebookCell(): NotebookCell {return {id: CellId.create(),name: EMPTY_STRING,- code: EMPTY_STRING,+ code: null,code_hash: null,config: {column: null,@@ -163,24 +165,22 @@ function createEmptySessionCell(): SessionCell {};}-function createCellDataFromNotebook(- cellId: CellId,- notebookCell: NotebookCell,-): CellData {+/** The cell as a host would describe it. A snapshot never changes, so its etags only need to be distinct. */+function cellRecord(cellId: CellId, cell: NotebookCell): Protocol.Cell {return {id: cellId,- name: notebookCell.name ?? EMPTY_STRING,- code: notebookCell.code ?? EMPTY_STRING,- edited: false,- lastCodeRun: null,- lastExecutionTime: null,+ notebook_id: EMBEDDED,+ code: cell.code,+ name: cell.name || DEFAULT_CELL_NAME,config: {- column: notebookCell.config?.column ?? null,- disabled: notebookCell.config?.disabled ?? false,- hide_code: notebookCell.config?.hide_code ?? false,- expand_output: notebookCell.config?.expand_output ?? false,+ column: cell.config?.column ?? null,+ disabled: cell.config?.disabled ?? false,+ hide_code: cell.config?.hide_code ?? false,+ expand_output: cell.config?.expand_output ?? false,},- serializedEditorState: null,+ etag: `${EMBEDDED}:${cellId}`,+ code_hash: cell.code_hash ?? `${EMBEDDED}:${cellId}:code`,+ version: 1,};}@@ -278,45 +278,68 @@ function createCellRuntimeFromSession(};}-export function notebookStateFromSession(- session: api.Session["NotebookSessionV1"] | null | undefined,- notebook: api.Notebook["NotebookV1"] | null | undefined,-): NotebookState | null {- // Merge session and notebook cells using edit distance+/**+ * Read the session and notebook a page embeds.+ *+ * The cells become a host snapshot the replica starts from, and the session's+ * outputs seed each cell's runtime until the kernel speaks. Null when the page+ * carries no cells.+ */+export function readExport({+ session,+ notebook,+ filename,+ appConfig,+}: {+ session: api.Session["NotebookSessionV1"] | null | undefined;+ notebook: api.Notebook["NotebookV1"] | null | undefined;+ filename: string | null;+ appConfig: Record<string, unknown>;+}): {+ snapshot: StaticNotebookSnapshot | null;+ cellRuntime: Record<CellId, CellRuntimeState>;+} {const { cellIds, sessionCellData, notebookCellData } =mergeSessionAndNotebookCells(session, notebook);-if (cellIds.length === 0) {- return null;+ return { snapshot: null, cellRuntime: {} };}- const cellData: Record<CellId, CellData> = {};+ const cells: Protocol.Cell[] = [];const cellRuntime: Record<CellId, CellRuntimeState> = {};-- // Process each cellfor (const cellId of cellIds) {- const sessionCell = sessionCellData.get(cellId);- const notebookCell = notebookCellData.get(cellId);-- // Create cell data from notebook if available- if (notebookCell) {- cellData[cellId] = createCellDataFromNotebook(cellId, notebookCell);- }-- // Create cell runtime- // This needs always be created even if there is no session cell- // in order to display the cell in the correct state- cellRuntime[cellId] = createCellRuntimeFromSession(sessionCell);+ cells.push(+ cellRecord(+ cellId,+ notebookCellData.get(cellId) ?? createEmptyNotebookCell(),+ ),+ );+ cellRuntime[cellId] = createCellRuntimeFromSession(+ sessionCellData.get(cellId),+ );}return {- cellIds: MultiColumn.from([cellIds]),- cellData: cellData,- cellRuntime: cellRuntime,- cellHandles: {},- history: [],- scrollKey: null,- cellLogs: [],- untouchedNewCells: new Set(),+ snapshot: {+ notebook: {+ id: EMBEDDED,+ project_id: EMBEDDED,+ path: filename,+ name: filename ?? EMPTY_STRING,+ updated_at: null,+ },+ document: {+ notebook_id: EMBEDDED,+ order: cellIds,+ app_config: appConfig,+ etag: `${EMBEDDED}:document`,+ saved_etag: `${EMBEDDED}:document`,+ order_etag: `${EMBEDDED}:order`,+ app_config_etag: `${EMBEDDED}:app_config`,+ version: 1,+ },+ cells,+ },+ cellRuntime,};}diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.tsindex 351c6fa4b8..20483b46c1 100644--- a/frontend/src/core/cells/types.ts+++ b/frontend/src/core/cells/types.ts@@ -1,7 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */import type { Milliseconds, Seconds } from "@/utils/time";-import type { SerializedEditorState } from "../codemirror/types";import type { OutputMessage } from "../kernel/messages";import type { CellConfig, RuntimeState } from "../network/types";import type { CellId } from "./ids";@@ -31,7 +30,6 @@ export function createCell({lastExecutionTime = null,edited = false,config,- serializedEditorState = null,}: Partial<CellData> & { id: CellId }): CellData {return {id: id,@@ -46,7 +44,6 @@ export function createCell({edited: edited,lastCodeRun: lastCodeRun,lastExecutionTime: lastExecutionTime,- serializedEditorState: serializedEditorState,};}@@ -97,8 +94,6 @@ export interface CellData {lastExecutionTime: number | null;/** cell configuration */config: CellConfig;- /** serialized state of the underlying editor */- serializedEditorState: SerializedEditorState | null;}export interface CellRuntimeState {diff --git a/frontend/src/core/cells/utils.ts b/frontend/src/core/cells/utils.tsindex ca2780de7c..13c36c5d62 100644--- a/frontend/src/core/cells/utils.ts+++ b/frontend/src/core/cells/utils.ts@@ -79,11 +79,13 @@ export function getUndoLabel(state: NotebookState): string {}/**- * Get the status of the descendants of the given cell.+ * Summarize the run state of the given descendants, whether any is stale,+ * errored, or running.*/-export function getDescendantsStatus(state: NotebookState, cellId: CellId) {- const column = state.cellIds.findWithId(cellId);- const descendants = column.getDescendants(cellId);+export function getDescendantsStatus(+ state: NotebookState,+ descendants: readonly CellId[],+) {const stale = descendants.some((id) => state.cellRuntime[id]?.staleInputs || state.cellData[id]?.edited,);diff --git a/frontend/src/core/config/__tests__/app-config.test.ts b/frontend/src/core/config/__tests__/app-config.test.tsnew file mode 100644index 0000000000..e45b0a867e--- /dev/null+++ b/frontend/src/core/config/__tests__/app-config.test.ts@@ -0,0 +1,64 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { atom, createStore } from "jotai";+import { describe, expect, it } from "vitest";+import { partial } from "@/__mocks__/partial";+import type { Document, NotebookReplica } from "@/core/notebook/replica";+import { activeNotebookReplicaAtom } from "@/core/session/active-notebook";+import { appConfigAtom, pageAppConfigAtom } from "../config";++function document(app_config: Record<string, unknown>, version = 1): Document {+ return {+ revision: {+ notebook_id: "nb",+ order: [],+ app_config,+ etag: `etag-${version}`,+ saved_etag: null,+ order_etag: "order",+ app_config_etag: "config",+ version,+ },+ cells: new Map(),+ };+}++function connect(store: ReturnType<typeof createStore>, current: Document) {+ store.set(+ activeNotebookReplicaAtom,+ partial<NotebookReplica>({ documentAtom: atom(current) }, "replica"),+ );+}++describe("appConfigAtom", () => {+ it("reads the page's config until the host document arrives", () => {+ const store = createStore();+ expect(store.get(appConfigAtom).width).toBe("compact");+ store.set(pageAppConfigAtom, { width: "full" });+ expect(store.get(appConfigAtom).width).toBe("full");+ connect(store, document({ width: "compact" }));+ expect(store.get(appConfigAtom).width).toBe("compact");+ });++ it("fills what the host document leaves out with Python's defaults", () => {+ const store = createStore();+ store.set(pageAppConfigAtom, { width: "full" });+ // The document carries only the options that differ from the defaults.+ connect(store, document({}));+ expect(store.get(appConfigAtom)).toEqual({+ width: "compact",+ auto_download: [],+ sql_output: "auto",+ });+ });++ it("keeps the same object while the record is unchanged", () => {+ const store = createStore();+ connect(store, document({ width: "full" }, 1));+ const first = store.get(appConfigAtom);+ connect(store, document({ width: "full" }, 2));+ expect(store.get(appConfigAtom)).toBe(first);+ connect(store, document({ width: "medium" }, 3));+ expect(store.get(appConfigAtom).width).toBe("medium");+ });+});diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.tsindex 02f2e2859d..074db7f353 100644--- a/frontend/src/core/config/__tests__/config-schema.test.ts+++ b/frontend/src/core/config/__tests__/config-schema.test.ts@@ -27,7 +27,7 @@ test("default AppConfig", () => {{"auto_download": [],"sql_output": "auto",- "width": "medium",+ "width": "compact",}`);});diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 47317db787..eefbc476ea 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -278,11 +278,15 @@ export const SqlOutputSchema = z.enum(VALID_SQL_OUTPUT_FORMATS).prefault("auto");+/**+ * The notebook's app config. The defaults are Python's `_AppConfig` defaults,+ * since the host document carries only what differs from them.+ */export const AppConfigSchema = z.object({width: z.enum(VALID_APP_WIDTHS)- .prefault("medium")+ .prefault("compact").transform((width) => {if (width === "normal") {return "compact";@@ -296,7 +300,7 @@ export const AppConfigSchema = zsql_output: SqlOutputSchema,}).prefault(() => ({- width: "medium" as const,+ width: "compact" as const,auto_download: [],sql_output: "auto" as const,}));diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.tsindex 4ec7106845..bfcc101629 100644--- a/frontend/src/core/config/config.ts+++ b/frontend/src/core/config/config.ts@@ -1,8 +1,11 @@/* Copyright 2026 Marimo. All rights reserved. */+import { dequal } from "dequal";import { atom, useAtom, useAtomValue, useSetAtom } from "jotai";+import { selectAtom } from "jotai/vanilla/utils";import { mergeWith } from "lodash-es";import { OverridingHotkeyProvider } from "../hotkeys/hotkeys";import { type Platform, resolvePlatform } from "../hotkeys/shortcuts";+import { confirmedDocumentAtom } from "../session/active-notebook";import { store } from "../state/jotai";import {type AppConfig,@@ -134,19 +137,30 @@ export function isAiFeatureEnabled(config: UserConfig) {}/**- * Atom for storing the app config.+ * The app config the page was served with, as the server wrote it.+ *+ * The host document carries the current one; this holds its place until+ * that document arrives. It goes once every page carries its document.*/-export const appConfigAtom = atom<AppConfig>(parseAppConfig({}));--/**- * Returns the app config.- */-export function useAppConfig() {- return useAtom(appConfigAtom);-}--export function useSetAppConfig() {- return useSetAtom(appConfigAtom);+export const pageAppConfigAtom = atom<unknown>({});++/** The app config record in force, stable while its contents are. */+const appConfigRecordAtom = selectAtom(+ atom(+ (get) =>+ get(confirmedDocumentAtom)?.revision.app_config ?? get(pageAppConfigAtom),+ ),+ (record) => record,+ dequal,+);++/** The notebook's app config, as the host document carries it. */+export const appConfigAtom = atom((get) =>+ parseAppConfig(get(appConfigRecordAtom)),+);++export function useAppConfig(): AppConfig {+ return useAtomValue(appConfigAtom);}export function getAppConfig() {diff --git a/frontend/src/core/islands/bootstrap.ts b/frontend/src/core/islands/bootstrap.tsindex dfef7aacaf..d611eb6349 100644--- a/frontend/src/core/islands/bootstrap.ts+++ b/frontend/src/core/islands/bootstrap.ts@@ -221,7 +221,6 @@ function handleNotification(setLastRun: actions.setLastRun,resetCellRuntimes: actions.resetCellRuntimes,setLayoutData: Functions.NOOP,- setAppConfig: Functions.NOOP,setCapabilities: Functions.NOOP,setKernelState: Functions.NOOP,onError: Logger.error,diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.tsindex efcc227d2f..4996fcf669 100644--- a/frontend/src/core/kernel/handlers.ts+++ b/frontend/src/core/kernel/handlers.ts@@ -1,11 +1,9 @@/* Copyright 2026 Marimo. All rights reserved. */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 { ReducerCellActions } 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";import type { LayoutData, LayoutState } from "../layout/state";@@ -71,7 +69,6 @@ export function handleKernelReady(}) => void;setCapabilities: (capabilities: Capabilities) => void;setKernelState: (state: KernelState) => void;- setAppConfig: (config: AppConfig) => void;onError: (error: Error) => void;},): LayoutState {@@ -81,13 +78,11 @@ export function handleKernelReady(setLastRun,resetCellRuntimes,setLayoutData,- setAppConfig,setCapabilities,setKernelState,onError,} = opts;- const { resumed, ui_values, app_config, capabilities, auto_instantiated } =- data;+ const { resumed, ui_values, capabilities, auto_instantiated } = data;resetCellRuntimes();setLastRun({@@ -96,13 +91,6 @@ export function handleKernelReady(});const layoutState = buildLayoutState(data, cells, setLayoutData);- // Set app config and capabilities- const parsedAppConfig = AppConfigSchema.safeParse(app_config);- if (parsedAppConfig.success) {- setAppConfig(parsedAppConfig.data);- } else {- Logger.error("Failed to parse app config", parsedAppConfig.error);- }setCapabilities(capabilities);// If the kernel was already instantiated server-side (e.g. run mode), we're donediff --git a/frontend/src/core/meta/__tests__/code-visibility.test.tsx b/frontend/src/core/meta/__tests__/code-visibility.test.tsxindex 4ebdc55def..f92449a783 100644--- a/frontend/src/core/meta/__tests__/code-visibility.test.tsx+++ b/frontend/src/core/meta/__tests__/code-visibility.test.tsx@@ -1,17 +1,21 @@/* Copyright 2026 Marimo. All rights reserved. */import { renderHook } from "@testing-library/react";-import { createStore, Provider } from "jotai";+import type * as Protocol from "@marimo-team/client/protocol";+import { atom, createStore, Provider } from "jotai";import type { ReactNode } from "react";import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { partial } from "@/__mocks__/partial";import { showCodeInRunModeAtom } from "@/core/meta/state";import { type AppMode, kioskModeAtom, viewStateAtom } from "@/core/mode";+import type { Document, NotebookReplica } from "@/core/notebook/replica";import {remoteAdapter,runtimeAdapterAtom,staticAdapter,type RuntimeAdapter,} from "@/core/runtime/adapter";+import { activeNotebookReplicaAtom } from "@/core/session/active-notebook";import { useNotebookCodeAvailable } from "../code-visibility";interface StoreOpts {@@ -19,6 +23,39 @@ interface StoreOpts {kiosk?: boolean;showInRunMode?: boolean;runtime?: RuntimeAdapter;+ /** Each cell's source as the host sent it; null is withheld. */+ codes?: ReadonlyArray<string | null>;+}++function document(codes: ReadonlyArray<string | null>): Document {+ const cells = codes.map((code, index): Protocol.Cell => ({+ id: `cell-${index}` as Protocol.CellId,+ notebook_id: "nb",+ code,+ name: "_",+ config: {+ column: null,+ disabled: false,+ hide_code: false,+ expand_output: false,+ },+ etag: `etag-${index}`,+ code_hash: `hash-${index}`,+ version: 1,+ }));+ return {+ revision: {+ notebook_id: "nb",+ order: cells.map((cell) => cell.id),+ app_config: {},+ etag: "etag",+ saved_etag: "etag",+ order_etag: "order",+ app_config_etag: "config",+ version: 1,+ },+ cells: new Map(cells.map((cell) => [cell.id, cell])),+ };}function makeStore({@@ -26,23 +63,32 @@ function makeStore({kiosk = false,showInRunMode = true,runtime = remoteAdapter,+ codes = ["x = 1", ""],}: StoreOpts = {}) {const store = createStore();store.set(viewStateAtom, { mode, cellAnchor: null });store.set(kioskModeAtom, kiosk);store.set(showCodeInRunModeAtom, showInRunMode);store.set(runtimeAdapterAtom, runtime);+ store.set(+ activeNotebookReplicaAtom,+ partial<NotebookReplica>(+ { documentAtom: atom(document(codes)) },+ "replica",+ ),+ );return store;}-function wrap(store: ReturnType<typeof createStore>) {- return ({ children }: { children: ReactNode }) => (+function render(store: ReturnType<typeof createStore>) {+ const wrapper = ({ children }: { children: ReactNode }) => (<Provider store={store}>{children}</Provider>);+ return renderHook(() => useNotebookCodeAvailable(), { wrapper }).result+ .current;}-const cellsWithCode = [{ code: "x = 1" }, { code: "" }];-const cellsWithoutCode = [{ code: "" }, { code: "" }];+const withheld = [null, null];const originalHref = window.location.href;@@ -60,21 +106,11 @@ describe("useNotebookCodeAvailable", () => {});it("returns true in edit mode regardless of cells", () => {- const store = makeStore({ mode: "edit" });- const { result } = renderHook(- () => useNotebookCodeAvailable(cellsWithoutCode),- { wrapper: wrap(store) },- );- expect(result.current).toBe(true);+ expect(render(makeStore({ mode: "edit", codes: withheld }))).toBe(true);});it("returns true in present mode (only reachable from edit)", () => {- const store = makeStore({ mode: "present" });- const { result } = renderHook(- () => useNotebookCodeAvailable(cellsWithoutCode),- { wrapper: wrap(store) },- );- expect(result.current).toBe(true);+ expect(render(makeStore({ mode: "present", codes: withheld }))).toBe(true);});it("returns true in kiosk mode even when read mode and no code", () => {@@ -82,88 +118,60 @@ describe("useNotebookCodeAvailable", () => {mode: "read",kiosk: true,showInRunMode: false,+ codes: withheld,});- const { result } = renderHook(- () => useNotebookCodeAvailable(cellsWithoutCode),- { wrapper: wrap(store) },- );- expect(result.current).toBe(true);+ expect(render(store)).toBe(true);});it("returns true in read mode when at least one cell has code", () => {- const store = makeStore({ mode: "read" });- const { result } = renderHook(- () => useNotebookCodeAvailable(cellsWithCode),- { wrapper: wrap(store) },- );- expect(result.current).toBe(true);+ expect(render(makeStore({ mode: "read" }))).toBe(true);+ });++ it("counts an empty cell as code the host sent", () => {+ expect(render(makeStore({ mode: "read", codes: ["", null] }))).toBe(true);+ });++ it("returns false in read mode when the host withheld every source", () => {+ expect(render(makeStore({ mode: "read", codes: withheld }))).toBe(false);});- it("returns false in read mode when every cell.code is empty (server stripped)", () => {+ it("returns false in read mode before a document arrives", () => {const store = makeStore({ mode: "read" });- const { result } = renderHook(- () => useNotebookCodeAvailable(cellsWithoutCode),- { wrapper: wrap(store) },- );- expect(result.current).toBe(false);+ store.set(activeNotebookReplicaAtom, null);+ expect(render(store)).toBe(false);});it("returns false in read mode when host opts out via showAppCode", () => {- const store = makeStore({ mode: "read", showInRunMode: false });- const { result } = renderHook(- () => useNotebookCodeAvailable(cellsWithCode),- { wrapper: wrap(store) },+ expect(render(makeStore({ mode: "read", showInRunMode: false }))).toBe(+ false,);- expect(result.current).toBe(false);});it("returns false in read mode when ?include-code=false", () => {setSearch("?include-code=false");- const store = makeStore({ mode: "read" });- const { result } = renderHook(- () => useNotebookCodeAvailable(cellsWithCode),- { wrapper: wrap(store) },- );- expect(result.current).toBe(false);+ expect(render(makeStore({ mode: "read" }))).toBe(false);});it("ignores ?include-code=false in kiosk mode", () => {setSearch("?include-code=false");- const store = makeStore({ mode: "read", kiosk: true });- const { result } = renderHook(- () => useNotebookCodeAvailable(cellsWithoutCode),- { wrapper: wrap(store) },- );- expect(result.current).toBe(true);+ expect(+ render(makeStore({ mode: "read", kiosk: true, codes: withheld })),+ ).toBe(true);});it("checks embedded code in a static kiosk", () => {- const store = makeStore({+ const options = {mode: "read",kiosk: true,runtime: staticAdapter,- });-- const withoutCode = renderHook(- () => useNotebookCodeAvailable(cellsWithoutCode),- { wrapper: wrap(store) },- );- const withCode = renderHook(() => useNotebookCodeAvailable(cellsWithCode), {- wrapper: wrap(store),- });-- expect(withoutCode.result.current).toBe(false);- expect(withCode.result.current).toBe(true);+ } as const;+ expect(render(makeStore({ ...options, codes: withheld }))).toBe(false);+ expect(render(makeStore(options))).toBe(true);});it("returns false for non-edit/non-read modes (home, gallery)", () => {for (const mode of ["home", "gallery"] as const) {- const store = makeStore({ mode });- const { result } = renderHook(- () => useNotebookCodeAvailable(cellsWithCode),- { wrapper: wrap(store) },- );- expect(result.current).toBe(false);+ expect(render(makeStore({ mode }))).toBe(false);}});});diff --git a/frontend/src/core/meta/code-visibility.ts b/frontend/src/core/meta/code-visibility.tsindex d825d6789a..afaf2cc347 100644--- a/frontend/src/core/meta/code-visibility.ts+++ b/frontend/src/core/meta/code-visibility.ts@@ -1,22 +1,31 @@/* Copyright 2026 Marimo. All rights reserved. */-import { useAtomValue } from "jotai";+import { atom, useAtomValue } from "jotai";import { KnownQueryParams } from "@/core/constants";import { showCodeInRunModeAtom } from "@/core/meta/state";import { kioskModeAtom, viewStateAtom } from "@/core/mode";import { runtimeAdapterAtom } from "@/core/runtime/adapter";+import { confirmedDocumentAtom } from "@/core/session/active-notebook";import { logNever } from "@/utils/assertNever";+/** Whether any cell's source reached this client. A host withholds source as null. */+export const codeAvailableAtom = atom((get) => {+ const document = get(confirmedDocumentAtom);+ return (+ document !== null &&+ [...document.cells.values()].some((cell) => cell.code !== null)+ );+});+/**- * Whether the notebook source code reached the frontend and can be rendered.+ * Whether the notebook source code can be rendered.*- * In `marimo run` the server omits cell sources unless `--include-code` is- * set (every `cell.code` arrives as `""`). Use this to gate any "show code"- * / "copy code" / "download .py" affordance.+ * In `marimo run` the server withholds cell sources unless `--include-code`+ * is set. Use this to gate any "show code" / "copy code" / "download .py"+ * affordance.*/-export function useNotebookCodeAvailable(- cells: ReadonlyArray<{ code: string }>,-): boolean {+export function useNotebookCodeAvailable(): boolean {+ const available = useAtomValue(codeAvailableAtom);const kioskMode = useAtomValue(kioskModeAtom);const { mode } = useAtomValue(viewStateAtom);const showInRunMode = useAtomValue(showCodeInRunModeAtom);@@ -41,7 +50,7 @@ export function useNotebookCodeAvailable(if (params.get(KnownQueryParams.includeCode) === "false") {return false;}- return cells.some((cell) => Boolean(cell.code));+ return available;}default:logNever(mode);diff --git a/frontend/src/core/notebook/__tests__/operations.test.ts b/frontend/src/core/notebook/__tests__/operations.test.tsnew file mode 100644index 0000000000..f6786028c9--- /dev/null+++ b/frontend/src/core/notebook/__tests__/operations.test.ts@@ -0,0 +1,51 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { NotebookOutput } from "@marimo-team/client/protocol";+import { atom, createStore } from "jotai";+import { describe, expect, it } from "vitest";+import { partial } from "@/__mocks__/partial";+import { kioskModeAtom } from "@/core/mode";+import type { NotebookReplica } from "@/core/notebook/replica";+import { activeNotebookReplicaAtom } from "@/core/session/active-notebook";+import { canEditAtom, notebookOperationsAtom } from "../operations";++function connect(+ store: ReturnType<typeof createStore>,+ operations: readonly string[] | null,+) {+ const notebook =+ operations === null+ ? null+ : ({ id: "nb", operations } as unknown as NotebookOutput);+ store.set(+ activeNotebookReplicaAtom,+ partial<NotebookReplica>({ notebookAtom: atom(notebook) }, "replica"),+ );+}++describe("notebook operations", () => {+ it("advertises nothing until the notebook is ready", () => {+ const store = createStore();+ expect(store.get(notebookOperationsAtom)).toEqual([]);+ expect(store.get(canEditAtom)).toBe(false);+ connect(store, null);+ expect(store.get(canEditAtom)).toBe(false);+ });++ it("allows editing when the host lists notebook.edit", () => {+ const store = createStore();+ connect(store, ["notebook.edit", "runtime.run"]);+ expect(store.get(canEditAtom)).toBe(true);+ connect(store, ["runtime.run"]);+ expect(store.get(canEditAtom)).toBe(false);+ });++ it("withholds editing from a kiosk connection", () => {+ const store = createStore();+ connect(store, ["notebook.edit"]);+ store.set(kioskModeAtom, true);+ expect(store.get(canEditAtom)).toBe(false);+ store.set(kioskModeAtom, false);+ expect(store.get(canEditAtom)).toBe(true);+ });+});diff --git a/frontend/src/core/notebook/document/__tests__/codemirror.test.ts b/frontend/src/core/notebook/document/__tests__/codemirror.test.tsindex ad8b22303c..67a5bd8ce0 100644--- a/frontend/src/core/notebook/document/__tests__/codemirror.test.ts+++ b/frontend/src/core/notebook/document/__tests__/codemirror.test.ts@@ -65,6 +65,21 @@ function languages(id: CellId) {addSetupCell: vi.fn(),deleteCells: vi.fn(),undoDeleteCell: vi.fn(),+ focusCell: vi.fn(),+ focusTopCell: vi.fn(),+ focusBottomCell: vi.fn(),+ collapseCell: vi.fn(),+ expandCell: vi.fn(),+ collapseAllCells: vi.fn(),+ expandAllCells: vi.fn(),+ showCellIfHidden: vi.fn(),+ moveCell: vi.fn(),+ moveCellToIndex: vi.fn(),+ moveCellsRelativeTo: vi.fn(),+ dropCellOverCell: vi.fn(),+ dropCellOverColumn: vi.fn(),+ sendToTop: vi.fn(),+ sendToBottom: vi.fn(),onRun: vi.fn(),deleteCell: vi.fn(),afterToggleMarkdown: vi.fn(),diff --git a/frontend/src/core/notebook/index.ts b/frontend/src/core/notebook/index.tsindex 35f2d6ef04..9c96756aa3 100644--- a/frontend/src/core/notebook/index.ts+++ b/frontend/src/core/notebook/index.ts@@ -1,6 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */-/** React hooks for the current notebook. */+/** What the editor reads about the current notebook. */export {useNotebookAttachments,@@ -16,3 +16,4 @@ export {useNotebookDocumentEdit,useNotebookDocumentSync,} from "./document";+export { canEditAtom, notebookOperationsAtom } from "./operations";diff --git a/frontend/src/core/notebook/operations.ts b/frontend/src/core/notebook/operations.tsnew file mode 100644index 0000000000..37d2edcfb1--- /dev/null+++ b/frontend/src/core/notebook/operations.ts@@ -0,0 +1,30 @@+/* Copyright 2026 Marimo. All rights reserved. */++/** What the host lets this client do to the notebook. */++import { atom } from "jotai";+import { kioskModeAtom } from "../mode";+import { activeNotebookReplicaAtom } from "../session/active-notebook";++const NO_OPERATIONS: readonly string[] = [];++/** Operations the host advertises for this notebook, none until its stream is ready. */+export const notebookOperationsAtom = atom((get) => {+ const replica = get(activeNotebookReplicaAtom);+ const notebook = replica === null ? null : get(replica.notebookAtom);+ return notebook?.operations ?? NO_OPERATIONS;+});++/**+ * Whether this client may edit the document.+ *+ * TODO(MO-8028): The host advertises the same operations to every+ * connection of a notebook, so a kiosk connection, an interactor that may+ * not edit, narrows it here. Once the host narrows `operations` per+ * connection by consumer capability, the kiosk term goes.+ */+export const canEditAtom = atom(+ (get) =>+ !get(kioskModeAtom) &&+ get(notebookOperationsAtom).includes("notebook.edit"),+);diff --git a/frontend/src/core/saving/__tests__/state.test.ts b/frontend/src/core/saving/__tests__/state.test.tsnew file mode 100644index 0000000000..98c056d403--- /dev/null+++ b/frontend/src/core/saving/__tests__/state.test.ts@@ -0,0 +1,111 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type * as Protocol from "@marimo-team/client/protocol";+import { atom, createStore } from "jotai";+import { describe, expect, it } from "vitest";+import { partial } from "@/__mocks__/partial";+import type {+ DocumentModel,+ DocumentSyncStatus,+} from "@/core/notebook/document";+import type { Document, NotebookReplica } from "@/core/notebook/replica";+import {+ activeDocumentModelAtom,+ activeNotebookReplicaAtom,+} from "@/core/session/active-notebook";+import { initialLayoutState, layoutStateAtom } from "../../layout/state";+import { documentVersionAtom, needsSaveAtom, savedLayoutAtom } from "../state";++function revision(+ overrides: Partial<Protocol.Document> = {},+): Protocol.Document {+ return {+ notebook_id: "nb",+ order: [],+ app_config: {},+ etag: "v2",+ saved_etag: "v2",+ order_etag: "order",+ app_config_etag: "config",+ version: 2,+ ...overrides,+ };+}++function connect(+ store: ReturnType<typeof createStore>,+ document: Document | null,+ status: DocumentSyncStatus["status"] = "idle",+) {+ store.set(+ activeNotebookReplicaAtom,+ partial<NotebookReplica>({ documentAtom: atom(document) }, "replica"),+ );+ store.set(+ activeDocumentModelAtom,+ partial<DocumentModel>(+ { syncStatusAtom: atom({ status } as DocumentSyncStatus) },+ "model",+ ),+ );+}++describe("needsSaveAtom", () => {+ it("is false without a connected document", () => {+ const store = createStore();+ expect(store.get(needsSaveAtom)).toBe(false);+ expect(store.get(documentVersionAtom)).toBeNull();+ connect(store, null);+ expect(store.get(needsSaveAtom)).toBe(false);+ });++ it("compares the host's etag with what it last wrote", () => {+ const store = createStore();+ connect(store, { revision: revision(), cells: new Map() });+ expect(store.get(needsSaveAtom)).toBe(false);+ expect(store.get(documentVersionAtom)).toBe(2);+ connect(store, { revision: revision({ etag: "v3" }), cells: new Map() });+ expect(store.get(needsSaveAtom)).toBe(true);+ });++ it("treats a document never written as unsaved", () => {+ const store = createStore();+ connect(store, {+ revision: revision({ saved_etag: null }),+ cells: new Map(),+ });+ expect(store.get(needsSaveAtom)).toBe(true);+ });++ it.each(["pending", "sending", "confirming", "error"] as const)(+ "counts edits the host has not confirmed (%s)",+ (status) => {+ const store = createStore();+ connect(store, { revision: revision(), cells: new Map() }, status);+ expect(store.get(needsSaveAtom)).toBe(true);+ },+ );++ it("ignores a model that is not running", () => {+ const store = createStore();+ connect(store, { revision: revision(), cells: new Map() }, "unavailable");+ expect(store.get(needsSaveAtom)).toBe(false);+ });++ it("compares the layout with the one last saved", () => {+ const store = createStore();+ connect(store, { revision: revision(), cells: new Map() });+ store.set(layoutStateAtom, {+ selectedLayout: "grid",+ layoutData: { grid: null },+ });+ expect(store.get(needsSaveAtom)).toBe(false);+ store.set(savedLayoutAtom, initialLayoutState());+ expect(store.get(needsSaveAtom)).toBe(true);+ store.set(savedLayoutAtom, {+ selectedLayout: "grid",+ layoutData: { grid: null },+ });+ expect(store.get(needsSaveAtom)).toBe(false);+ });+});diff --git a/frontend/src/core/saving/save-component.tsx b/frontend/src/core/saving/save-component.tsxindex 5d2c2e9279..365aba85e1 100644--- a/frontend/src/core/saving/save-component.tsx+++ b/frontend/src/core/saving/save-component.tsx@@ -1,6 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */-import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";+import { useAtom, useAtomValue, useStore } from "jotai";import { SaveIcon } from "lucide-react";import { useState } from "react";import { FilenameInput } from "@/components/editor/header/filename-input";@@ -20,7 +20,7 @@ import {import { Label } from "../../components/ui/label";import { useEvent } from "../../hooks/useEvent";import { Logger } from "../../utils/Logger";-import { getCellConfigs, getNotebook, useNotebook } from "../cells/cells";+import { getCellConfigs, getNotebook } from "../cells/cells";import { flushDocument, withDocumentSave } from "../cells/document";import { notebookCells } from "../cells/utils";import { formatAll } from "../codemirror/format";@@ -28,20 +28,16 @@ import { autoSaveConfigAtom } from "../config/config";import { useAutoExport } from "../export/hooks";import { getSerializedLayout } from "../layout/layout";import { layoutStateAtom } from "../layout/state";-import { kioskModeAtom } from "../mode";import { connectionAtom } from "../network/connection";+import { canEditAtom } from "@/core/notebook";import { useRequestClient } from "../network/requests";import { ConnectionState } from "../session/types";import { isWasm } from "../wasm/utils";import { filenameAtom } from "./file-state";import { useFilename, useUpdateFilename } from "./filename";-import { lastSavedNotebookAtom, needsSaveAtom } from "./state";+import { documentVersionAtom, needsSaveAtom, savedLayoutAtom } from "./state";import { useAutoSave } from "./useAutoSave";-interface SaveNotebookProps {- kioskMode: boolean;-}-let notebookSaveQueue: Promise<void> = Promise.resolve();export function enqueueNotebookSave<T>(save: () => Promise<T>): Promise<T> {@@ -53,12 +49,12 @@ export function enqueueNotebookSave<T>(save: () => Promise<T>): Promise<T> {return result;}-export const SaveComponent = ({ kioskMode }: SaveNotebookProps) => {+export const SaveComponent = () => {const filename = useFilename();const needsSave = useAtomValue(needsSaveAtom);const closed = useAtomValue(connectionAtom).state === ConnectionState.CLOSED;const { saveOrNameNotebook, saveIfNotebookIsPersistent } = useSaveNotebook();- useAutoSaveNotebook({ onSave: saveIfNotebookIsPersistent, kioskMode });+ useAutoSaveNotebook({ onSave: saveIfNotebookIsPersistent });useAutoExport();@@ -105,7 +101,6 @@ export const SaveComponent = ({ kioskMode }: SaveNotebookProps) => {export function useSaveNotebook() {const { sendSave } = useRequestClient();const { openModal, closeModal, openAlert } = useImperativeModal();- const setLastSavedNotebook = useSetAtom(lastSavedNotebookAtom);const updateFilename = useUpdateFilename();const store = useStore();@@ -114,11 +109,6 @@ export function useSaveNotebook() {enqueueNotebookSave(async () => {const connection = store.get(connectionAtom);const autoSaveConfig = store.get(autoSaveConfigAtom);- const kioskMode = store.get(kioskModeAtom);-- if (kioskMode) {- return;- }// Don't save if we are not connected to a kernelif (connection.state !== ConnectionState.OPEN) {@@ -126,6 +116,11 @@ export function useSaveNotebook() {return;}+ // The host may not let this consumer edit, or may not have said yet.+ if (!store.get(canEditAtom)) {+ return;+ }+Logger.log("saving to ", filename);if (userInitiated && autoSaveConfig.format_on_save) {@@ -157,14 +152,14 @@ export function useSaveNotebook() {layout: getSerializedLayout(),persist: true,});- return { names: cellNames, codes, configs, layout };+ return layout;};// TODO(MO-7955): Remove this conditional once all frontend saves use// the host protocol. Host saves cannot recover edits from an editor snapshot.- const savedNotebook = isWasm()+ const savedLayout = isWasm()? await flushDocument().then(save): await withDocumentSave(save);- setLastSavedNotebook(savedNotebook);+ store.set(savedLayoutAtom, savedLayout);}),);@@ -224,29 +219,20 @@ export function isNamedPersistentFile();}-export function useAutoSaveNotebook(opts: {- onSave: () => void;- kioskMode: boolean;-}) {+export function useAutoSaveNotebook(opts: { onSave: () => void }) {const autoSaveConfig = useAtomValue(autoSaveConfigAtom);- const notebook = useNotebook();+ const canEdit = useAtomValue(canEditAtom);const [connection] = useAtom(connectionAtom);const needsSave = useAtomValue(needsSaveAtom);-- const cells = notebookCells(notebook);- const codes = cells.map((cell) => cell.code);- const cellNames = cells.map((cell) => cell.name);- const configs = getCellConfigs(notebook);+ const version = useAtomValue(documentVersionAtom);useAutoSave({onSave: opts.onSave,needsSave: needsSave,- codes: codes,- cellConfigs: configs,- cellNames: cellNames,+ version,connStatus: connection,config: autoSaveConfig,- kioskMode: opts.kioskMode,+ canEdit,});}diff --git a/frontend/src/core/saving/state.ts b/frontend/src/core/saving/state.tsindex 36ce63ed55..03d92f8e71 100644--- a/frontend/src/core/saving/state.ts+++ b/frontend/src/core/saving/state.ts@@ -1,52 +1,51 @@/* Copyright 2026 Marimo. All rights reserved. */+/** Whether the notebook has changes the host has not written to its store. */+import { dequal as isEqual } from "dequal";import { atom } from "jotai";-import { arrayShallowEquals } from "@/utils/arrays";-import { type NotebookState, notebookAtom } from "../cells/cells";import { type LayoutState, layoutStateAtom } from "../layout/state";-import type { CellConfig } from "../network/types";--export interface LastSavedNotebook {- codes: string[];- configs: CellConfig[];- names: string[];- layout: LayoutState;-}+import {+ activeDocumentModelAtom,+ confirmedDocumentAtom,+} from "../session/active-notebook";-export const lastSavedNotebookAtom = atom<LastSavedNotebook | undefined>(- undefined,+/** The document version, which counts confirmed changes. Null without a document. */+export const documentVersionAtom = atom(+ (get) => get(confirmedDocumentAtom)?.revision.version ?? null,);-export const needsSaveAtom = atom((get) => {- const lastSavedNotebook = get(lastSavedNotebookAtom);- const state = get(notebookAtom);- const layout = get(layoutStateAtom);- return notebookNeedsSave({ state, layout, lastSavedNotebook });-});+/**+ * The layout as the file last had it. The host document does not carry+ * the layout file, so this client compares it itself until it does.+ */+export const savedLayoutAtom = atom<LayoutState | undefined>(undefined);-function notebookNeedsSave({- state,- layout,- lastSavedNotebook,-}: {- state: NotebookState;- layout: LayoutState;- lastSavedNotebook: LastSavedNotebook | undefined;-}) {- if (!lastSavedNotebook) {+/**+ * Whether saving would change the file: the host's document differs from+ * what it last wrote, this client has edits the host has not confirmed,+ * or the layout changed. A document never written reports as unsaved.+ */+export const needsSaveAtom = atom((get) => {+ const document = get(confirmedDocumentAtom);+ if (document === null) {return false;}- const { cellIds, cellData } = state;- const data = cellIds.inOrderIds.map((cellId) => cellData[cellId]);- const codes = data.map((d) => d.code);- const configs = data.map((d) => d.config);- const names = data.map((d) => d.name);+ if (document.revision.etag !== document.revision.saved_etag) {+ return true;+ }+ const model = get(activeDocumentModelAtom);+ if (model !== null) {+ const { status } = get(model.syncStatusAtom);+ if (status !== "idle" && status !== "unavailable") {+ return true;+ }+ }+ const saved = get(savedLayoutAtom);+ const layout = get(layoutStateAtom);return (- !arrayShallowEquals(codes, lastSavedNotebook.codes) ||- !arrayShallowEquals(names, lastSavedNotebook.names) ||- !isEqual(configs, lastSavedNotebook.configs) ||- !isEqual(layout.selectedLayout, lastSavedNotebook.layout.selectedLayout) ||- !isEqual(layout.layoutData, lastSavedNotebook.layout.layoutData)+ saved !== undefined &&+ (layout.selectedLayout !== saved.selectedLayout ||+ !isEqual(layout.layoutData, saved.layoutData)));-}+});diff --git a/frontend/src/core/saving/useAutoSave.ts b/frontend/src/core/saving/useAutoSave.tsindex 62a115c18c..ed5f874940 100644--- a/frontend/src/core/saving/useAutoSave.ts+++ b/frontend/src/core/saving/useAutoSave.ts@@ -1,40 +1,23 @@/* Copyright 2026 Marimo. All rights reserved. */import { useEffect, useRef } from "react";import type { UserConfig } from "../config/config-schema";-import type { CellConfig } from "../network/types";import { type ConnectionStatus, ConnectionState } from "../session/types";+/** Save after a delay while the notebook needs it, restarting on every confirmed change. */export function useAutoSave(opts: {- codes: string[];- cellConfigs: CellConfig[];- cellNames: string[];+ /** The document version, which counts confirmed changes. */+ version: number | null;config: UserConfig["save"];connStatus: ConnectionStatus;needsSave: boolean;- kioskMode: boolean;+ canEdit: boolean;onSave: () => void;}) {- const {- codes,- cellConfigs,- config,- connStatus,- cellNames,- needsSave,- kioskMode,- onSave,- } = opts;+ const { version, config, connStatus, needsSave, canEdit, onSave } = opts;const autosaveTimeoutId = useRef<NodeJS.Timeout | null>(null);- const codesString = codes.join(":");- const cellConfigsString = cellConfigs- .map((config) => JSON.stringify(config))- .join(":");- const cellNamesString = cellNames.join(":");-useEffect(() => {- // If kiosk mode is enabled, do not autosave- if (kioskMode) {+ if (!canEdit) {return;}@@ -53,16 +36,6 @@ export function useAutoSave(opts: {clearTimeout(autosaveTimeoutId.current);}};- // codes, cellConfigs, cellNames needed in deps array to prevent race condition- // with needsSave when user changes state rapidly- }, [- codesString,- cellConfigsString,- cellNamesString,- config,- connStatus.state,- onSave,- kioskMode,- needsSave,- ]);+ // `version` restarts the delay on every confirmed change.+ }, [version, config, connStatus.state, onSave, canEdit, needsSave]);}diff --git a/frontend/src/core/session/__tests__/backend.test.ts b/frontend/src/core/session/__tests__/backend.test.tsindex a93dd65471..3cb991b84c 100644--- a/frontend/src/core/session/__tests__/backend.test.ts+++ b/frontend/src/core/session/__tests__/backend.test.ts@@ -27,6 +27,7 @@ afterEach(() => {const options = {static: false,+ snapshot: null,transportType: "websocket" as const,url: () => "ws://localhost/ws",headers: () => ({}),diff --git a/frontend/src/core/session/__tests__/useNotebookReplica.hook.test.tsx b/frontend/src/core/session/__tests__/useNotebookReplica.hook.test.tsxindex 9e248b48af..148a64d3a8 100644--- a/frontend/src/core/session/__tests__/useNotebookReplica.hook.test.tsx+++ b/frontend/src/core/session/__tests__/useNotebookReplica.hook.test.tsx@@ -48,6 +48,7 @@ function setup(strict = false) {const store = createStore();const options = {static: false,+ snapshot: null,transportType: "websocket" as const,url: () => "ws://localhost/ws",headers: () => ({}),diff --git a/frontend/src/core/session/active-notebook.ts b/frontend/src/core/session/active-notebook.tsindex d474272712..b8c749061a 100644--- a/frontend/src/core/session/active-notebook.ts+++ b/frontend/src/core/session/active-notebook.ts@@ -9,3 +9,14 @@ export const activeNotebookReplicaAtom = atom<NotebookReplica | null>(null);/** The document model owned by the mounted notebook session. */export const activeDocumentModelAtom = atom<DocumentModel | null>(null);++/**+ * The document the host last confirmed, or null while no notebook is+ * connected. Facts the host owns read this one, such as permission, the+ * app config, saved state and whether source is available. What the user+ * is editing reads the model's document, which adds this browser's drafts.+ */+export const confirmedDocumentAtom = atom((get) => {+ const replica = get(activeNotebookReplicaAtom);+ return replica === null ? null : get(replica.documentAtom);+});diff --git a/frontend/src/core/session/backend.ts b/frontend/src/core/session/backend.tsindex b7f9b77f80..0d22fd7226 100644--- a/frontend/src/core/session/backend.ts+++ b/frontend/src/core/session/backend.ts@@ -8,11 +8,18 @@ import type { NotebookBackend } from "../notebook/replica";import { PyodideBridge } from "../wasm/bridge";import { isWasm } from "../wasm/utils";import { sessionSse, websocket, withHeaders } from "../transports/server";-import { idle } from "../transports/static";+import {+ createStaticNotebookBackend,+ emptySnapshot,+ type StaticNotebookSnapshot,+ startWithSnapshot,+} from "../transports/static";/** How the editor follows its notebook. */export interface EditorBackendOptions {static: boolean;+ /** The notebook the page was served with, shown until the host answers. */+ snapshot: StaticNotebookSnapshot | null;transportType: "websocket" | "sse";/** The session route, read before each connection. */url: () => string;@@ -86,30 +93,21 @@ function wasm(): NotebookBackend {};}-/** Commands for a notebook the editor cannot change through its backend. */-function uneditable(): ReturnType<NotebookBackend["notebook"]> {- const unsupported: NotebookClient["save"] = async () => ({- ok: false,- status: 501,- problem: {- type: "tag:marimo.io,2026:host/unsupported-operation",- title: "Document mutations are unavailable on this connection",- status: 501,- },- });- return { edit: () => unsupported(), save: unsupported };-}-/** Choose the backend for the editor's notebook. */export function createEditorBackend(options: EditorBackendOptions,): NotebookBackend {if (options.static) {- return { transport: idle, notebook: uneditable };- }- if (isWasm()) {- return wasm();+ return createStaticNotebookBackend(+ options.snapshot ?? emptySnapshot("static"),+ );}+ const live = isWasm() ? wasm() : server(options);+ return options.snapshot ? startWithSnapshot(options.snapshot, live) : live;+}++/** Follow the notebook on the server, over SSE or a WebSocket. */+function server(options: EditorBackendOptions): NotebookBackend {const url = afterStartup(options);return {transport:diff --git a/frontend/src/core/session/embedded.ts b/frontend/src/core/session/embedded.tsnew file mode 100644index 0000000000..0a67620923--- /dev/null+++ b/frontend/src/core/session/embedded.ts@@ -0,0 +1,7 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { atom } from "jotai";+import type { StaticNotebookSnapshot } from "../transports/static";++/** The notebook the page was served with, read at mount. Null when none was. */+export const embeddedSnapshotAtom = atom<StaticNotebookSnapshot | null>(null);diff --git a/frontend/src/core/session/useNotebookReplica.ts b/frontend/src/core/session/useNotebookReplica.tsindex 1ad3e2a6dc..f934bf7cec 100644--- a/frontend/src/core/session/useNotebookReplica.ts+++ b/frontend/src/core/session/useNotebookReplica.ts@@ -22,7 +22,7 @@ type Options = EditorBackendOptions & {export function useNotebookReplica(options: Options): NotebookReplica {const store = useStore();- const { static: isStatic, transportType } = options;+ const { static: isStatic, snapshot, transportType } = options;const replica = useMemo(() => createNotebookReplica(store), [store]);const url = useEvent(options.url);const headers = useEvent(options.headers);@@ -35,6 +35,7 @@ export function useNotebookReplica(options: Options): NotebookReplica {() =>createEditorBackend({static: isStatic,+ snapshot,transportType,url,headers,@@ -44,6 +45,7 @@ export function useNotebookReplica(options: Options): NotebookReplica {}),[isStatic,+ snapshot,transportType,url,headers,diff --git a/frontend/src/core/session/useNotebookSession.tsx b/frontend/src/core/session/useNotebookSession.tsxindex 0aaf0a807c..00e6b6bf9f 100644--- a/frontend/src/core/session/useNotebookSession.tsx+++ b/frontend/src/core/session/useNotebookSession.tsx@@ -35,7 +35,7 @@ import {} from "../codemirror/cells/debugger-state";import { notebookCells } from "../cells/utils";import { capabilitiesAtom } from "../config/capabilities";-import { connectionTransportTypeAtom, useSetAppConfig } from "../config/config";+import { connectionTransportTypeAtom } from "../config/config";import { useDataSourceActions } from "../datasets/data-source-connections";import { invalidateDataSourceDiscovery } from "../datasets/data-source-discovery";import type { ConnectionName } from "../datasets/engines";@@ -62,9 +62,10 @@ import {stableSessionIdAtom,} from "../kernel/session";import { initialRunCompletedAtom, kernelStateAtom } from "../kernel/state";-import { type LayoutState, useLayoutActions } from "../layout/state";+import { useLayoutActions } from "../layout/state";import { kioskModeAtom } from "../mode";import { connectionAtom, startupProgressAtom } from "../network/connection";+import { savedLayoutAtom } from "../saving/state";import type { RequestId } from "../network/DeferredRequestRegistry";import { useRuntimeManager } from "../runtime/config";import { SECRETS_REGISTRY } from "../secrets/request-registry";@@ -77,16 +78,15 @@ import { useStorageActions } from "../storage/state";import { useVariablesActions } from "../variables/state";import type { VariableName } from "../variables/types";import { activeDocumentModelAtom } from "./active-notebook";+import { embeddedSnapshotAtom } from "./embedded";import { WebSocketClosedReason, ConnectionState } from "./types";/** Coordinate session startup and apply notifications to the editor. */export function useNotebookSession(opts: {sessionId: SessionId;autoInstantiate: boolean;- /** Called with the layout the kernel reported, after its cells are ready. */- onKernelReady?: (layout: LayoutState) => void;}) {- const { autoInstantiate, sessionId, onKernelReady } = opts;+ const { autoInstantiate, sessionId } = opts;const { showBoundary } = useErrorBoundary();const store = useStore();@@ -99,7 +99,6 @@ export function useNotebookSession(opts: {const { addCellNotification } = useRunsActions();const setKernelState = useSetAtom(kernelStateAtom);const setInitialRunCompleted = useSetAtom(initialRunCompletedAtom);- const setAppConfig = useSetAppConfig();const { setVariables, setMetadata } = useVariablesActions();const { addColumnPreview } = useDatasetsActions();const { addDatasets, filterDatasetsFromVariables } = useDatasetsActions();@@ -156,12 +155,11 @@ export function useNotebookSession(opts: {setLastRun,resetCellRuntimes,setLayoutData,- setAppConfig,setCapabilities,setKernelState,onError: showBoundary,});- onKernelReady?.(layout);+ store.set(savedLayoutAtom, 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@@ -399,6 +397,7 @@ export function useNotebookSession(opts: {};const replica = useNotebookReplica({static: isStaticNotebook(),+ snapshot: useAtomValue(embeddedSnapshotAtom),transportType,url: () =>transportType === "sse"diff --git a/frontend/src/core/transports/__tests__/static.test.ts b/frontend/src/core/transports/__tests__/static.test.tsindex 08601bcd25..cda8e48314 100644--- a/frontend/src/core/transports/__tests__/static.test.ts+++ b/frontend/src/core/transports/__tests__/static.test.ts@@ -3,10 +3,13 @@import { createNotebookReducer, NotebookEvents } from "@marimo-team/client";import * as Protocol from "@marimo-team/client/protocol";import { afterEach, assert, describe, expect, it, vi } from "vitest";+import type { NotebookBackend } from "../../notebook/replica";import { document as documentResource } from "../../notebook/replica/resources/document";import {createStaticNotebookBackend,+ emptySnapshot,type StaticNotebookSnapshot,+ startWithSnapshot,} from "../static";import { fixtureEvents } from "../../notebook/replica/__tests__/fixtures";@@ -34,24 +37,48 @@ afterEach(async () => {vi.useRealTimers();});-async function read(- backend: ReturnType<typeof createStaticNotebookBackend>,- cursor?: string,-) {- const stream = new NotebookEvents(backend.transport, { cursor });- streams.push(stream);+/** Collect a stream's events up to and including its next `ready`. */+function untilReady(stream: NotebookEvents): Promise<Protocol.EventOutput[]> {const events: Protocol.EventOutput[] = [];- await new Promise<void>((resolve, reject) => {+ return new Promise((resolve, reject) => {stream.subscribe((event) => {events.push(Protocol.Event.parse(event));if (event.event === "ready") {- resolve();+ resolve(events);}}, reject);});+}++/** Open a backend's stream and read until it is ready. */+async function read(+ backend: ReturnType<typeof createStaticNotebookBackend>,+ cursor?: string,+) {+ const stream = new NotebookEvents(backend.transport, { cursor });+ streams.push(stream);+ const events = await untilReady(stream);return { stream, events };}+/** A live backend whose stream sends nothing until `release` is called. */+function silentUntilReleased(backend: NotebookBackend) {+ let release = () => {};+ const released = new Promise<void>((resolve) => {+ release = resolve;+ });+ const attempts: Array<string | null> = [];+ const silent: NotebookBackend = {+ ...backend,+ transport: async (attempt, handlers) => {+ attempts.push(attempt.cursor);+ await released;+ return backend.transport(attempt, handlers);+ },+ };+ return { backend: silent, release: () => release(), attempts };+}+describe("static notebook backend", () => {it("supplies a complete document through the normal event reader and reducer", async () => {const source = snapshot();@@ -173,3 +200,107 @@ describe("static notebook backend", () => {expect(message).toHaveBeenCalledOnce();});});++describe("starting from an embedded snapshot", () => {+ it("shows the snapshot until the host answers, then resets into its stream", async () => {+ const embedded = snapshot();+ const live = silentUntilReleased(+ createStaticNotebookBackend(emptySnapshot("live")),+ );+ const reducer = createNotebookReducer({ document: documentResource });++ // The snapshot is published on its own, with the host still silent.+ const { stream, events } = await read(+ startWithSnapshot(embedded, live.backend),+ );+ expect(events.map((event) => event.event)).toEqual([+ "notebook",+ "cell",+ "cell",+ "cell",+ "document",+ "ready",+ ]);+ const shown = events.reduce(reducer.reduce, reducer.initial);+ expect(shown.notebook?.id).toBe(embedded.notebook.id);+ expect(shown.resources.document.current?.cells.size).toBe(3);+ expect(live.attempts).toEqual([null]);++ // The host's first frame discards it, and the host's snapshot follows.+ const host = untilReady(stream);+ live.release();+ const rest = await host;+ expect(rest.map((event) => event.event)).toEqual([+ "reset",+ "notebook",+ "document",+ "ready",+ ]);+ const state = rest.reduce(reducer.reduce, shown);+ expect(state.notebook?.id).toBe("live");+ expect(state.resources.document.current?.cells.size).toBe(0);+ expect(stream.status).toBe("connected");+ });++ it("does not open the host when cancelled while showing the snapshot", async () => {+ const attempts: Array<string | null> = [];+ const live: NotebookBackend = {+ ...createStaticNotebookBackend(emptySnapshot("live")),+ transport: async (attempt) => {+ attempts.push(attempt.cursor);+ },+ };+ const controller = new AbortController();+ const message = vi.fn(() => controller.abort());++ await startWithSnapshot(snapshot(), live).transport(+ { cursor: null, signal: controller.signal },+ { open: vi.fn(), message },+ );++ expect(message).toHaveBeenCalledOnce();+ expect(attempts).toEqual([]);+ });++ it("starts the host connection fresh when resuming from the snapshot's cursor", async () => {+ const embedded = snapshot();+ const live = silentUntilReleased(+ createStaticNotebookBackend(emptySnapshot("live")),+ );+ live.release();+ const { events } = await read(+ startWithSnapshot(embedded, live.backend),+ `${embedded.notebook.id}:snapshot`,+ );+ expect(live.attempts).toEqual([null]);+ expect(events.map((event) => event.event)).toEqual([+ "reset",+ "notebook",+ "document",+ "ready",+ ]);+ });++ it("skips the snapshot when a connection resumes", async () => {+ const backend = startWithSnapshot(+ snapshot(),+ createStaticNotebookBackend(emptySnapshot("live")),+ );+ const { events } = await read(backend, "static");+ expect(events.map((event) => event.event)).toEqual([+ "reset",+ "notebook",+ "document",+ "ready",+ ]);+ });++ it("keeps the live backend's commands", async () => {+ const backend = startWithSnapshot(+ snapshot(),+ createStaticNotebookBackend(emptySnapshot("live")),+ );+ const result = await backend.notebook("live").save();+ expect(result).toMatchObject({ ok: false, status: 501 });+ });+});diff --git a/frontend/src/core/transports/static.ts b/frontend/src/core/transports/static.tsindex 0db4f1b9f7..b908b95ebb 100644--- a/frontend/src/core/transports/static.ts+++ b/frontend/src/core/transports/static.ts@@ -2,7 +2,7 @@/** A backend that serves a document snapshot without a host. */-import type { NotebookClient, NotebookTransport } from "@marimo-team/client";+import type { NotebookClient } from "@marimo-team/client";import type * as Protocol from "@marimo-team/client/protocol";import type { NotebookBackend } from "../notebook/replica";@@ -13,14 +13,9 @@ export interface StaticNotebookSnapshot {readonly cells: readonly Protocol.Cell[];}-/**- * Serve a document without a server, runtime, or mutation operations.- * Callers and readers must treat the snapshot records as immutable.- */-export function createStaticNotebookBackend(- snapshot: StaticNotebookSnapshot,-): NotebookBackend {- const frames: Protocol.Event[] = [+/** The events that describe a snapshot, in the order a host sends them. */+function snapshotFrames(snapshot: StaticNotebookSnapshot): Protocol.Event[] {+ return [{event: "notebook",data: { notebook: { ...snapshot.notebook, operations: [] } },@@ -30,6 +25,100 @@ export function createStaticNotebookBackend(data: { cell },})),{ event: "document", data: { document: snapshot.document } },+ ];+}++/** A snapshot of a notebook with no cells. */+export function emptySnapshot(notebookId: string): StaticNotebookSnapshot {+ return {+ notebook: {+ id: notebookId,+ project_id: notebookId,+ path: null,+ name: "",+ updated_at: null,+ },+ document: {+ notebook_id: notebookId,+ order: [],+ app_config: {},+ etag: `${notebookId}:document`,+ saved_etag: `${notebookId}:document`,+ order_etag: `${notebookId}:order`,+ app_config_etag: `${notebookId}:app_config`,+ version: 1,+ },+ cells: [],+ };+}++/**+ * Show a snapshot until `live` answers.+ *+ * The page carries the notebook it was served with, so cells appear before+ * the host connects. The snapshot ends in a `ready` of its own, like a+ * static notebook's, so the replica publishes it. At the host's first sign+ * of life a `reset` discards it, and the host's snapshot takes over. A+ * connection that resumes from a host cursor skips the snapshot; one that+ * resumes from the snapshot's cursor starts the host connection fresh,+ * since the host never issued it.+ */+export function startWithSnapshot(+ snapshot: StaticNotebookSnapshot,+ live: NotebookBackend,+): NotebookBackend {+ const cursor = `${snapshot.notebook.id}:snapshot`;+ return {+ ...live,+ transport: (attempt, handlers) => {+ if (attempt.cursor !== null && attempt.cursor !== cursor) {+ return live.transport(attempt, handlers);+ }+ if (attempt.cursor === null) {+ for (const frame of snapshotFrames(snapshot)) {+ if (attempt.signal.aborted) {+ break;+ }+ handlers.message(frame);+ }+ if (attempt.signal.aborted) {+ return Promise.resolve();+ }+ handlers.message({ event: "ready", id: cursor, data: {} });+ }+ let shown = true;+ const discard = () => {+ if (shown) {+ shown = false;+ handlers.message({ event: "reset", data: {} });+ }+ };+ return live.transport(+ { ...attempt, cursor: null },+ {+ open: () => {+ discard();+ handlers.open();+ },+ message: (frame) => {+ discard();+ handlers.message(frame);+ },+ },+ );+ },+ };+}++/**+ * Serve a document without a server, runtime, or mutation operations.+ * Callers and readers must treat the snapshot records as immutable.+ */+export function createStaticNotebookBackend(+ snapshot: StaticNotebookSnapshot,+): NotebookBackend {+ const frames: Protocol.Event[] = [+ ...snapshotFrames(snapshot),{ event: "ready", id: "static", data: {} },];@@ -75,10 +164,3 @@ export function createStaticNotebookBackend(},};}--/** A connection that opens and delivers nothing, for static notebooks. */-export const idle: NotebookTransport = ({ signal }, { open }) =>- new Promise((settle) => {- open();- signal.addEventListener("abort", () => settle(), { once: true });- });diff --git a/frontend/src/core/wasm/__tests__/bridge.test.ts b/frontend/src/core/wasm/__tests__/bridge.test.tsindex 9b74bbd9ef..ba6f929bd4 100644--- a/frontend/src/core/wasm/__tests__/bridge.test.ts+++ b/frontend/src/core/wasm/__tests__/bridge.test.ts@@ -235,6 +235,7 @@ describe("PyodideBridge.sendSave", () => {store.set(activeNotebookReplicaAtom, replica);const backend = createEditorBackend({static: false,+ snapshot: null,transportType: "sse",url: () => "http://localhost/",headers: () => ({}),diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsxindex 5ec0f0a2f1..e4528aa530 100644--- a/frontend/src/mount.tsx+++ b/frontend/src/mount.tsx@@ -5,8 +5,8 @@ import { Provider } from "jotai";import { createRoot } from "react-dom/client";import { z } from "zod";import {- appConfigAtom,configOverridesAtom,+ pageAppConfigAtom,userConfigAtom,} from "@/core/config/config";import { KnownQueryParams } from "@/core/constants";@@ -21,7 +21,7 @@ import {import { Logger } from "@/utils/Logger";import { ErrorBoundary } from "./components/editor/boundary/ErrorBoundary";import { notebookAtom } from "./core/cells/cells";-import { notebookStateFromSession } from "./core/cells/session";+import { readExport } from "./core/cells/session";import {parseAppConfig,parseConfigOverrides,@@ -62,6 +62,7 @@ import {import { maybeRegisterVSCodeBindings } from "./core/vscode/vscode-bindings";import type { FileStore } from "./core/wasm/store";import { notebookFileStore } from "./core/wasm/store";+import { embeddedSnapshotAtom } from "./core/session/embedded";import { ConnectionState } from "./core/session/types";import {handleWidgetMessage,@@ -346,7 +347,8 @@ function initStore(options: unknown) {parseConfigOverrides(parsedOptions.data.configOverrides),);store.set(userConfigAtom, parseUserConfig(parsedOptions.data.config));- store.set(appConfigAtom, parseAppConfig(parsedOptions.data.appConfig));+ store.set(pageAppConfigAtom, parsedOptions.data.appConfig);+ const appConfig = parseAppConfig(parsedOptions.data.appConfig);store.set(pairConfigAtom, parsedOptions.data.pairConfig);// Runtime config@@ -369,14 +371,21 @@ function initStore(options: unknown) {});}- // Session/notebook- const notebook = notebookStateFromSession(- parsedOptions.data.session,- parsedOptions.data.notebook,- );+ // The notebook the page was served with shows until the host answers.+ const { snapshot, cellRuntime } = readExport({+ session: parsedOptions.data.session,+ notebook: parsedOptions.data.notebook,+ filename: parsedOptions.data.filename,+ appConfig,+ });+ store.set(embeddedSnapshotAtom, snapshot);store.set(layoutStateAtom, initialLayoutState(parsedOptions.data.layout));- if (notebook) {- store.set(notebookAtom, notebook);+ if (snapshot !== null) {+ // The scratch cell keeps its own runtime; the snapshot has none for it.+ store.set(notebookAtom, (state) => ({+ ...state,+ cellRuntime: { ...state.cellRuntime, ...cellRuntime },+ }));}}diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex e61b587493..d7e2c04845 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -46,7 +46,6 @@ const Cell: React.FC<{name: "cell_1",code: "import marimo as mo",edited: overrides.edited ?? false,- serializedEditorState: null,config: {hide_code: overrides.config?.hide_code ?? false,disabled: overrides.config?.disabled ?? false,@@ -79,7 +78,6 @@ const Cell: React.FC<{cellLogs: [],history: [],scrollKey: null,- untouchedNewCells: new Set(),};const store = createStore();diff --git a/frontend/src/stories/layout/vertical/one-column.stories.tsx b/frontend/src/stories/layout/vertical/one-column.stories.tsxindex 9cfdfffbd3..1cdc87dee4 100644--- a/frontend/src/stories/layout/vertical/one-column.stories.tsx+++ b/frontend/src/stories/layout/vertical/one-column.stories.tsx@@ -36,7 +36,6 @@ const createLongReprNotebook = (print('hello')LongReprA()`,edited: false,- serializedEditorState: null,config: {hide_code: hideCode,disabled: false,@@ -88,7 +87,6 @@ LongReprA()`,cellLogs: [],history: [],scrollKey: null,- untouchedNewCells: new Set(),});export default {diff --git a/frontend/src/utils/__tests__/id-tree.test.ts b/frontend/src/utils/__tests__/id-tree.test.tsindex 7c4f2b9c14..38f48b35cc 100644--- a/frontend/src/utils/__tests__/id-tree.test.ts+++ b/frontend/src/utils/__tests__/id-tree.test.ts@@ -25,240 +25,6 @@ describe("CollapsibleTree", () => {`);});- it("collapses nodes correctly with no end", () => {- const collapsedTree = tree.collapse("two", undefined);- expect(collapsedTree.nodes[1].isCollapsed).toBe(true);- expect(collapsedTree.isCollapsed("two")).toBe(true);- expect(collapsedTree.toString()).toMatchInlineSnapshot(`- "one- two (collapsed)- three- four- "- `);- });-- it("collapses nodes correctly with an 'until' in the middle", () => {- const collapsedTree = tree.collapse("two", "three");- expect(collapsedTree.nodes[1].isCollapsed).toBe(true);- expect(collapsedTree.toString()).toMatchInlineSnapshot(`- "one- two (collapsed)- three- four- "- `);- });-- it("collapses nodes correctly with an 'until' at the end", () => {- const collapsedTree = tree.collapse("two", "four");- expect(collapsedTree.nodes[1].isCollapsed).toBe(true);- expect(collapsedTree.toString()).toMatchInlineSnapshot(`- "one- two (collapsed)- three- four- "- `);- });-- it("collapses nodes correctly if just the last node", () => {- const collapsedTree = tree.collapse("four", undefined);- expect(collapsedTree.nodes[3].isCollapsed).toBe(true);- expect(collapsedTree.toString()).toMatchInlineSnapshot(`- "one- two- three- four (collapsed)- "- `);- });-- it("collapses nodes correctly if just the first node", () => {- const collapsedTree = tree.collapse("one", undefined);- expect(collapsedTree.nodes[0].isCollapsed).toBe(true);- expect(collapsedTree.toString()).toMatchInlineSnapshot(`- "one (collapsed)- two- three- four- "- `);- });-- it("can double collapse", () => {- const collapsedTree = tree- .collapse("three", undefined)- .collapse("two", undefined);- expect(collapsedTree.toString()).toMatchInlineSnapshot(`- "one- two (collapsed)- three (collapsed)- four- "- `);- });-- it("failures to collapse", () => {- expect(() =>- tree.collapse("five", undefined),- ).toThrowErrorMatchingInlineSnapshot(- "[Error: Node five not found in tree. Valid ids: one,two,three,four]",- );- expect(() =>- tree.collapse("one", "five"),- ).toThrowErrorMatchingInlineSnapshot(- "[Error: Node five not found in tree]",- );- expect(() =>- tree.collapse("two", "one"),- ).toThrowErrorMatchingInlineSnapshot(- "[Error: Node one is before node two]",- );- expect(() => {- tree = tree.collapse("two", undefined);- tree = tree.collapse("two", undefined);- }).toThrowErrorMatchingInlineSnapshot(- "[Error: Node two is already collapsed]",- );- });-- it("collapses all nodes from leaves to root in one call", () => {- const collapsedTree = tree.collapseAll([- { id: "one", until: undefined },- { id: "two", until: undefined },- { id: "three", until: undefined },- { id: "four", until: undefined },- ]);- expect(collapsedTree.toString()).toMatchInlineSnapshot(`- "one (collapsed)- two (collapsed)- three (collapsed)- four (collapsed)- "- `);- });-- it("collapses some nodes from leaves to root in one call", () => {- const collapsedTree = tree.collapseAll([- { id: "one", until: undefined },- null,- { id: "three", until: "four" },- null,- ]);- expect(collapsedTree.toString()).toMatchInlineSnapshot(`- "one (collapsed)- two- three (collapsed)- four- "- `);- });-- it("failures to collapse all", () => {- expect(() => tree.collapseAll([])).toThrowErrorMatchingInlineSnapshot(- "[Error: No collapse ranges provided]",- );- expect(() =>- tree.collapseAll([- { id: "one", until: undefined },- { id: "two", until: undefined },- ]),- ).toThrowErrorMatchingInlineSnapshot(- "[Error: Collapse ranges length 2 does not match tree length 4]",- );- expect(() =>- tree.collapseAll([null, { id: "one", until: undefined }, null, null]),- ).toThrowErrorMatchingInlineSnapshot(- "[Error: Node two does not match collapse range id one]",- );- expect(() =>- tree.collapseAll([{ id: "one", until: "five" }, null, null, null]),- ).toThrowErrorMatchingInlineSnapshot(- "[Error: Node five not found in tree]",- );- expect(() =>- tree.collapseAll([null, { id: "two", until: "one" }, null, null]),- ).toThrowErrorMatchingInlineSnapshot(- "[Error: Node one is before node two]",- );- });-- it("expands nodes correctly", () => {- const collapsed = tree.collapse("two", undefined);- expect(collapsed.nodes[1].isCollapsed).toBe(true);- const expandedTree = collapsed.expand("two");- expect(expandedTree.nodes[1].isCollapsed).toBe(false);- expect(expandedTree.toString()).toMatchInlineSnapshot(`- "one- two- three- four- "- `);- });-- it("expands all nested collapsed nodes correctly in one call", () => {- let collapsed = tree.collapse("three", undefined);- expect(collapsed.nodes[2].isCollapsed).toBe(true);- collapsed = collapsed.collapse("two", undefined);- expect(collapsed.nodes[1].isCollapsed).toBe(true);- const expandedTree = collapsed.expandAll();- expect(expandedTree.nodes[1].isCollapsed).toBe(false);- expect(expandedTree.toString()).toMatchInlineSnapshot(`- "one- two- three- four- "- `);- });-- it("fails to expand when node not found", () => {- expect(() => tree.expand("five")).toThrowErrorMatchingInlineSnapshot(- "[Error: Node five not found in tree. Valid ids: one,two,three,four]",- );- });-- it("expand on already expanded node is a no-op", () => {- // Expanding an already expanded node should return the same tree (no-op)- const result = tree.expand("one");- expect(result).toBe(tree);- // Can call multiple times without error- const result2 = tree.expand("one");- expect(result2).toBe(tree);- });-- it("moves nodes correctly", () => {- const movedTree = tree.move(0, 1);- expect(movedTree.toString()).toMatchInlineSnapshot(`- "two- one- three- four- "- `);- });-- it("moves a collapsed node correctly", () => {- const collapsed = tree.collapse("two", "three");- expect(collapsed.toString()).toMatchInlineSnapshot(`- "one- two (collapsed)- three- four- "- `);- const movedTree = collapsed.move(1, 2);- expect(movedTree.toString()).toMatchInlineSnapshot(`- "one- four- two (collapsed)- three- "- `);- });-it("inserts nodes correctly", () => {tree = tree.insert("newNode", 1);expect(tree.toString()).toMatchInlineSnapshot(`@@ -294,93 +60,6 @@ describe("CollapsibleTree", () => {`);});- it("counts children correctly", () => {- expect(tree.getCount("who")).toBe(0);- expect(tree.getCount("one")).toBe(0);- // Collapse three and get count- tree = tree.collapse("three", undefined);- expect(tree.getCount("three")).toBe(1);- // Collapse two and get count- tree = tree.collapse("two", undefined);- expect(tree.getCount("two")).toBe(2);- });-- it("finds deep correctly", () => {- expect(tree.find("three")).toEqual(["three"]);- tree = tree.collapse("three", undefined).collapse("two", undefined);- expect(tree.find("three")).toEqual(["two", "three"]);- expect(tree.find("four")).toEqual(["two", "three", "four"]);- expect(tree.toString()).toMatchInlineSnapshot(`- "one- two (collapsed)- three (collapsed)- four- "- `);- });-- it("finds and expands correctly at a leaf", () => {- tree = tree.collapse("three", undefined).collapse("two", undefined);- expect(tree.toString()).toMatchInlineSnapshot(`- "one- two (collapsed)- three (collapsed)- four- "- `);- const prevTree = tree;- tree = tree.findAndExpandDeep("four");- expect(tree.toString()).toMatchInlineSnapshot(`- "one- two- three- four- "- `);- // doesn't mutate- expect(prevTree.toString()).not.toEqual(tree.toString());- });-- it("finds and expands correctly at a non-leaf", () => {- tree = tree.collapse("three", undefined).collapse("two", undefined);- expect(tree.toString()).toMatchInlineSnapshot(`- "one- two (collapsed)- three (collapsed)- four- "- `);- const prevTree = tree;- tree = tree.findAndExpandDeep("three");- expect(tree.toString()).toMatchInlineSnapshot(`- "one- two- three- four- "- `);- // doesn't mutate- expect(prevTree.toString()).not.toEqual(tree.toString());- });-- it("can delete nodes", () => {- tree = tree.collapse("three", undefined).collapse("two", undefined);- expect(tree.toString()).toMatchInlineSnapshot(`- "one- two (collapsed)- three (collapsed)- four- "- `);- tree = tree.deleteAtIndex(1);- expect(tree.toString()).toMatchInlineSnapshot(`- "one- three (collapsed)- four- "- `);- });-it("can delete non-collapsed nodes without throwing", () => {// Deleting a non-collapsed node should not throw// (previously this would throw "Node is already expanded" internally)@@ -399,50 +78,6 @@ describe("CollapsibleTree", () => {);});- it("top-level ids are correct", () => {- expect(tree.topLevelIds).toMatchInlineSnapshot(`- [- "one",- "two",- "three",- "four",- ]- `);-- const collapsed = tree.collapse("two", undefined);- expect(collapsed.topLevelIds).toMatchInlineSnapshot(`- [- "one",- "two",- ]- `);- });-- it("in order ids are correct", () => {- expect(tree.inOrderIds).toMatchInlineSnapshot(`- [- "one",- "two",- "three",- "four",- ]- `);-- const collapsed = tree.collapse("two", undefined);-- // Not mutable- expect(tree.inOrderIds).toEqual(tree.inOrderIds);-- expect(collapsed.inOrderIds).toMatchInlineSnapshot(`- [- "one",- "two",- "three",- "four",- ]- `);- });-it("atOrThrow throws if not found", () => {expect(() => tree.atOrThrow(5)).toThrowErrorMatchingInlineSnapshot("[Error: Node at index 5 not found in tree]",@@ -454,49 +89,6 @@ describe("CollapsibleTree", () => {expect(tree.last()).toBe("four");});- it("length is correct", () => {- expect(tree.length).toBe(4);-- const collapsed = tree.collapse("two", undefined);- expect(collapsed.length).toBe(2);- });-- it("moves to front and back correctly", () => {- tree = tree.collapse("three", undefined).moveToBack("three");- expect(tree.toString()).toMatchInlineSnapshot(`- "one- two- three (collapsed)- four- "- `);-- tree = tree.moveToFront("two");- expect(tree.toString()).toMatchInlineSnapshot(`- "two- one- three (collapsed)- four- "- `);- });-- it("getDescendants correctly", () => {- expect(tree.getDescendants("two")).toEqual([]);- expect(tree.getDescendants("who")).toEqual([]);-- tree = tree.collapse("three", undefined).collapse("two", undefined);- expect(tree.getDescendants("two")).toMatchInlineSnapshot(`- [- "three",- "four",- ]- `);-- // We only get descendants of the top level- expect(tree.getDescendants("three")).toMatchInlineSnapshot("[]");- });-it("handles slice correctly", () => {// Normal slice in middleexpect(tree.slice(1, 3)).toEqual(["two", "three"]);@@ -526,14 +118,6 @@ describe("CollapsibleTree", () => {expect(tree.slice(1, 2)).toEqual(["two"]);});- it("handles slice with collapsed nodes", () => {- const collapsed = tree.collapse("two", "three");-- // Should only return top-level nodes, not descendants- expect(collapsed.slice(0, 2)).toEqual(["one", "two"]);- expect(collapsed.slice(1, 3)).toEqual(["two", "four"]);- });-it("handles after correctly", () => {// Normal case - get next nodeexpect(tree.after("one")).toBe("two");@@ -549,20 +133,6 @@ describe("CollapsibleTree", () => {);});- it("handles after with collapsed nodes", () => {- const collapsed = tree.collapse("two", "three");-- // Should return next top-level node- expect(collapsed.after("one")).toBe("two");- expect(collapsed.after("two")).toBe("four");- expect(collapsed.after("four")).toBeUndefined();-- // Should throw for collapsed children that aren't top-level- expect(() => collapsed.after("three")).toThrow(- "Node three not found in tree. Valid ids: one,two,four",- );- });-it("handles before correctly", () => {// Normal case - get previous nodeexpect(tree.before("two")).toBe("one");@@ -578,20 +148,6 @@ describe("CollapsibleTree", () => {);});- it("handles before with collapsed nodes", () => {- const collapsed = tree.collapse("two", "three");-- // Should return previous top-level node- expect(collapsed.before("two")).toBe("one");- expect(collapsed.before("four")).toBe("two");- expect(collapsed.before("one")).toBeUndefined();-- // Should throw for collapsed children that aren't top-level- expect(() => collapsed.before("three")).toThrow(- "Node three not found in tree. Valid ids: one,two,four",- );- });-it("handles slice on empty tree", () => {const emptyTree = CollapsibleTree.from([]);expect(emptyTree.slice(0, 1)).toEqual([]);@@ -665,45 +221,6 @@ describe("CollapsibleTree edge cases", () => {expect(tree.topLevelIds).toEqual(["Z", "A", "B", "C", "D", "Y"]);});- it("handles delete with expand", () => {- tree = tree.collapse("B", "D");- tree = tree.deleteAtIndex(1);- expect(tree.topLevelIds).toEqual(["A", "C", "D"]);- });-- it("finds nodes correctly", () => {- tree = tree.collapse("B", "D");- expect(tree.find("C")).toEqual(["B", "C"]);- expect(tree.find("E")).toEqual([]);- });-- it("handles equality check", () => {- const tree2 = CollapsibleTree.from(["A", "B", "C", "D"]);- expect(tree.equals(tree2)).toBe(true);- tree2.collapse("B", "C");- expect(tree.equals(tree2)).toBe(true);- });-- it("handles getCount correctly", () => {- tree = tree.collapse("B", "D");- expect(tree.getCount("A")).toBe(0);- expect(tree.getCount("B")).toBe(2);- expect(tree.getCount("C")).toBe(0);- });-- it("handles findAndExpandDeep", () => {- tree = tree.collapse("B", "D");- tree = tree.findAndExpandDeep("C");- expect(tree.topLevelIds).toEqual(["A", "B", "C", "D"]);- });-- it("handles multiple collapses and expands", () => {- tree = tree.collapse("B", "C").collapse("A", "D");- expect(tree.topLevelIds).toEqual(["A"]);- tree = tree.expand("A").expand("B");- expect(tree.topLevelIds).toEqual(["A", "B", "C", "D"]);- });-it("handles edge cases for first and last", () => {expect(tree.first()).toBe("A");expect(tree.last()).toBe("D");@@ -711,21 +228,6 @@ describe("CollapsibleTree edge cases", () => {expect(() => tree.first()).toThrow("Node at index 0 not found in tree");expect(() => tree.last()).toThrow("Node at index -1 not found in tree");});-- it("handles inOrderIds with nested structure", () => {- tree = tree.collapse("B", "C");- expect(tree.inOrderIds).toEqual(["A", "B", "C", "D"]);- });-- it("handles moving within bounds", () => {- tree = tree.move(0, 2);- expect(tree.topLevelIds).toEqual(["B", "C", "A", "D"]);- });-- it("handles moving out of bounds", () => {- tree = tree.move(0, 10);- expect(tree.topLevelIds).toEqual(["B", "C", "D", "A"]);- });});describe("MultiColumn", () => {@@ -862,29 +364,6 @@ describe("MultiColumn", () => {]);});- it("moves within a column", () => {- const moved = multiColumn.moveWithinColumn(- columnIds[0],- 0 as CellIndex,- 2 as CellIndex,- );- expect(moved.topLevelIds[0]).toEqual(["A2", "A3", "A1"]);- });-- it("moves across columns", () => {- const moved = multiColumn.moveAcrossColumns(- columnIds[0],- "A1",- columnIds[1],- "B1",- );- expect(moved.topLevelIds).toEqual([- ["A2", "A3"],- ["A1", "B1", "B2"],- ["C1", "C2", "C3", "C4"],- ]);- });-it("moves a column", () => {const moved = multiColumn.moveColumn(columnIds[0], columnIds[2]);expect(moved.topLevelIds).toEqual([@@ -921,17 +400,6 @@ describe("MultiColumn", () => {]);});- it("moves to a new column", () => {- const newColumn = multiColumn.moveToNewColumn("B1");- expect(newColumn.colLength).toBe(4);- expect(newColumn.topLevelIds).toEqual([- ["A1", "A2", "A3"],- ["B2"],- ["C1", "C2", "C3", "C4"],- ["B1"],- ]);- });-it("gets column with id", () => {const column = multiColumn.findWithId("B2");expect(multiColumn.indexOf(column)).toBe(1);@@ -940,9 +408,9 @@ describe("MultiColumn", () => {it("transforms by id", () => {const transformed = multiColumn.transformWithCellId("B1", (tree) =>- tree.moveToFront("B2"),+ tree.delete("B1"),);- expect(transformed.topLevelIds[1]).toEqual(["B2", "B1"]);+ expect(transformed.topLevelIds[1]).toEqual(["B2"]);});it("transforms all columns", () => {@@ -961,82 +429,6 @@ describe("MultiColumn", () => {expect(inserted.topLevelIds[1]).toEqual(["B1", "D1", "B2"]);});- describe("moveCellsRelativeTo", () => {- it("moves a single cell before target in same column", () => {- const moved = multiColumn.moveCellsRelativeTo(["A3"], "A1", "before");- expect(moved.topLevelIds).toEqual([- ["A3", "A1", "A2"],- ["B1", "B2"],- ["C1", "C2", "C3", "C4"],- ]);- });-- it("moves a single cell after target in same column", () => {- const moved = multiColumn.moveCellsRelativeTo(["A1"], "A3", "after");- expect(moved.topLevelIds).toEqual([- ["A2", "A3", "A1"],- ["B1", "B2"],- ["C1", "C2", "C3", "C4"],- ]);- });-- it("moves multiple cells before target", () => {- const moved = multiColumn.moveCellsRelativeTo(- ["A1", "A2"],- "B2",- "before",- );- expect(moved.topLevelIds).toEqual([- ["A3"],- ["B1", "A1", "A2", "B2"],- ["C1", "C2", "C3", "C4"],- ]);- });-- it("moves multiple cells after target", () => {- const moved = multiColumn.moveCellsRelativeTo(- ["A2", "A3"],- "B1",- "after",- );- expect(moved.topLevelIds).toEqual([- ["A1"],- ["B1", "A2", "A3", "B2"],- ["C1", "C2", "C3", "C4"],- ]);- });-- it("returns same MultiColumn when cellIds is empty", () => {- const moved = multiColumn.moveCellsRelativeTo([], "A1", "before");- expect(moved).toBe(multiColumn);- });-- it("inserts at end when target is among moved cells", () => {- const moved = multiColumn.moveCellsRelativeTo(- ["A1", "A2"],- "A2",- "after",- );- // Target A2 was removed; insert at end of column 0- expect(moved.topLevelIds).toEqual([- ["A3", "A1", "A2"],- ["B1", "B2"],- ["C1", "C2", "C3", "C4"],- ]);- });-- it("throws when node not found", () => {- expect(() =>- multiColumn.moveCellsRelativeTo(["Z1"], "A1", "before"),- ).toThrow("Cell Z1 not found in any column");- });- });-- it("deletes by id", () => {- const deleted = multiColumn.deleteById("B1");- expect(deleted.topLevelIds[1]).toEqual(["B2"]);- });-it("compacts", () => {const withEmpty = MultiColumn.from([["A1"], [], ["C1"], []]);const compacted = withEmpty.compact();@@ -1079,36 +471,6 @@ describe("MultiColumn", () => {expect(() => multiColumn.atOrThrow(5)).toThrow("Column 5 not found");});- it("handles moving the last item in a column", () => {- const multiColumn = MultiColumn.from([["A1", "A2"], ["B1"]]);- const columnIds = multiColumn.getColumns().map((c) => c.id);- const moved = multiColumn.moveAcrossColumns(- columnIds[1],- "B1",- columnIds[0],- "A2",- );- expect(moved.topLevelIds).toEqual([["A1", "B1", "A2"], []]);- expect(moved.colLength).toBe(2);- });-- it("handles moving all items from a column", () => {- const multiColumn = MultiColumn.from([- ["A1", "A2"],- ["B1", "B2"],- ]);- const columnIds = multiColumn.getColumns().map((c) => c.id);- let moved = multiColumn.moveAcrossColumns(- columnIds[1],- "B1",- columnIds[0],- "A2",- );- moved = moved.moveAcrossColumns(columnIds[1], "B2", columnIds[0], "A2");- expect(moved.topLevelIds).toEqual([["A1", "B1", "B2", "A2"], []]);- expect(moved.colLength).toBe(2);- });-it("handles inserting at out-of-bounds indices", () => {const multiColumn = MultiColumn.from([["A1"], ["B1"]]);const columnId = multiColumn.atOrThrow(1).id;@@ -1116,24 +478,6 @@ describe("MultiColumn", () => {expect(inserted.topLevelIds).toEqual([["A1"], ["B1", "C1"]]);});- it("handles collapsing and expanding in multi-column setup", () => {- let multiColumn = MultiColumn.from([- ["A1", "A2", "A3"],- ["B1", "B2"],- ]);- multiColumn = multiColumn.transformWithCellId("A1", (tree) =>- tree.collapse("A1", "A3"),- );- expect(multiColumn.topLevelIds).toEqual([["A1"], ["B1", "B2"]]);- multiColumn = multiColumn.transformWithCellId("A1", (tree) =>- tree.expand("A1"),- );- expect(multiColumn.topLevelIds).toEqual([- ["A1", "A2", "A3"],- ["B1", "B2"],- ]);- });-it("handles moving a column to its own position", () => {const multiColumn = MultiColumn.from([["A1"], ["B1"], ["C1"]]);const moved = multiColumn.moveColumn(columnIds[1], columnIds[1]);@@ -1155,39 +499,6 @@ describe("MultiColumn", () => {expect(transformed).toBe(multiColumn);});- it("handles nested collapses and expands", () => {- let multiColumn = MultiColumn.from([["A1", "A2", "A3", "A4", "A5"]]);- multiColumn = multiColumn.transformWithCellId("A1", (tree) =>- tree.collapse("A2", "A4"),- );- multiColumn = multiColumn.transformWithCellId("A1", (tree) =>- tree.collapse("A1", undefined),- );- expect(multiColumn.topLevelIds).toEqual([["A1"]]);- multiColumn = multiColumn.transformWithCellId("A1", (tree) =>- tree.expand("A1"),- );- expect(multiColumn.topLevelIds).toEqual([["A1", "A2", "A5"]]);- multiColumn = multiColumn.transformWithCellId("A1", (tree) =>- tree.expand("A2"),- );- expect(multiColumn.topLevelIds).toEqual([["A1", "A2", "A3", "A4", "A5"]]);- });-- it("handles moving to a new column when it's the last item", () => {- let multiColumn = MultiColumn.from([["A1"], ["B1"]]);- multiColumn = multiColumn.moveToNewColumn("B1");- expect(multiColumn.colLength).toBe(3);- expect(multiColumn.topLevelIds).toEqual([["A1"], [], ["B1"]]);- });-- it("handles deleting the last item in a column", () => {- let multiColumn = MultiColumn.from([["A1"], ["B1"], ["C1"]]);- multiColumn = multiColumn.deleteById("B1");- expect(multiColumn.colLength).toBe(3);- expect(multiColumn.topLevelIds).toEqual([["A1"], [], ["C1"]]);- });-it("handles multiple operations in sequence", () => {let multiColumn = MultiColumn.from([["A1", "A2"],@@ -1195,40 +506,31 @@ describe("MultiColumn", () => {["C1", "C2"],]);const columnIds = multiColumn.getColumns().map((c) => c.id);- multiColumn = multiColumn.moveAcrossColumns(- columnIds[0],- "A2",- columnIds[1],- "B1",- );- expect(multiColumn.topLevelIds).toEqual([- ["A1"],- ["A2", "B1", "B2"],- ["C1", "C2"],- ]);multiColumn = multiColumn.insertId("D1", columnIds[2], 1 as CellIndex);expect(multiColumn.topLevelIds).toEqual([- ["A1"],- ["A2", "B1", "B2"],+ ["A1", "A2"],+ ["B1", "B2"],["C1", "D1", "C2"],]);- multiColumn = multiColumn.deleteById("B1");+ multiColumn = multiColumn.transformWithCellId("B1", (tree) =>+ tree.delete("B1"),+ );expect(multiColumn.topLevelIds).toEqual([- ["A1"],- ["A2", "B2"],+ ["A1", "A2"],+ ["B2"],["C1", "D1", "C2"],]);multiColumn = multiColumn.moveColumn(columnIds[0], columnIds[2]);expect(multiColumn.topLevelIds).toEqual([- ["A2", "B2"],+ ["B2"],["C1", "D1", "C2"],- ["A1"],+ ["A1", "A2"],]);multiColumn = multiColumn.compact();expect(multiColumn.topLevelIds).toEqual([- ["A2", "B2"],+ ["B2"],["C1", "D1", "C2"],- ["A1"],+ ["A1", "A2"],]);});@@ -1238,7 +540,10 @@ describe("MultiColumn", () => {expect(multiColumn.setupCellExists()).toBe(false);const multiColumn2 = multiColumn.insertId(SETUP_CELL_ID, columnIds[0], 0);expect(multiColumn2.setupCellExists()).toBe(true);- const multiColumn3 = multiColumn2.deleteById(SETUP_CELL_ID);+ const multiColumn3 = multiColumn2.transformWithCellId(+ SETUP_CELL_ID,+ (tree) => tree.delete(SETUP_CELL_ID),+ );expect(multiColumn3.setupCellExists()).toBe(false);});@@ -1264,15 +569,15 @@ describe("MultiColumn", () => {it("handles transform method", () => {const transformed = multiColumn.transform(columnIds[1], (tree) =>- tree.moveToFront("B2"),+ tree.delete("B1"),);- expect(transformed.topLevelIds[1]).toEqual(["B2", "B1"]);+ expect(transformed.topLevelIds[1]).toEqual(["B2"]);});it("handles transform method with non-existent column id", () => {const transformed = multiColumn.transform("non-existent-id" as CellColumnId,- (tree) => tree.moveToFront("B2"),+ (tree) => tree.delete("B2"),);const columns1 = multiColumn.getColumns();const columns2 = transformed.getColumns();@@ -1281,37 +586,6 @@ describe("MultiColumn", () => {expect(transformed).toBe(multiColumn);});- it("handles moving across columns with undefined toId", () => {- const moved = multiColumn.moveAcrossColumns(- columnIds[0],- "A1",- columnIds[1],- undefined,- );- expect(moved.topLevelIds).toEqual([- ["A2", "A3"],- ["A1", "B1", "B2"],- ["C1", "C2", "C3", "C4"],- ]);- });-- it("handles moving across columns to an empty column", () => {- const emptyColumnMultiColumn = multiColumn- .deleteById("B1")- .deleteById("B2");- const moved = emptyColumnMultiColumn.moveAcrossColumns(- columnIds[0],- "A1",- columnIds[1],- undefined,- );- expect(moved.topLevelIds).toEqual([- ["A2", "A3"],- ["A1"],- ["C1", "C2", "C3", "C4"],- ]);- });-it("handles inserting a breakpoint at the start of a column", () => {const withBreakpoint = multiColumn.insertBreakpoint("A1");expect(withBreakpoint.colLength).toBe(4);@@ -1341,805 +615,3 @@ describe("MultiColumn", () => {expect(withBreakpoint.topLevelIds).toEqual([["A1"], [], ["B1"], ["C1"]]);});});--describe("MultiColumn.fromWithPreviousShape", () => {- it("creates a new MultiColumn with a single column when no previous shape is provided", () => {- const ids = ["A1", "A2", "A3"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- MultiColumn.from([]),- );-- expect(multiColumn.colLength).toBe(1);- expect(multiColumn.topLevelIds).toEqual([ids]);- expect(multiColumn.inOrderIds).toEqual(ids);- });-- it("preserves column structure when ids exist in previous columns", () => {- const previousMultiColumn = MultiColumn.from([- ["A1", "A2"],- ["B1", "B2"],- ["C1", "C2"],- ]);-- // Subset of ids from different columns- const ids = ["A1", "B2", "C1"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- expect(multiColumn.colLength).toBe(3);- expect(multiColumn.topLevelIds).toEqual([["A1"], ["B2"], ["C1"]]);- });-- it("preserves column structure with different ordering", () => {- const previousMultiColumn = MultiColumn.from([- ["A1", "A2", "A3"],- ["B1", "B2", "B3"],- ]);-- // Same ids but different order- const ids = ["A3", "B1", "A1", "B3"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([- ["A3", "A1"],- ["B1", "B3"],- ]);- });-- it("handles ids not present in previous shape", () => {- const previousMultiColumn = MultiColumn.from([- ["A1", "A2"],- ["B1", "B2"],- ]);-- // Include new ids not in previous shape- const ids = ["A1", "B1", "C1", "D1"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // New ids should be added to the last column- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([["A1"], ["B1", "C1", "D1"]]);- expect(multiColumn.inOrderIds).toEqual(["A1", "B1", "C1", "D1"]);- });-- it("preserves collapsed state from previous shape", () => {- // Create a previous shape with collapsed nodes- let previousMultiColumn = MultiColumn.from([- ["A1", "A2", "A3"],- ["B1", "B2", "B3"],- ]);-- // Collapse A1 to include A2- const columnIds = previousMultiColumn.getColumnIds();- previousMultiColumn = previousMultiColumn.transform(columnIds[0], (tree) =>- tree.collapse("A1", "A2"),- );-- // Create new shape with same ids- const ids = ["A1", "A2", "A3", "B1", "B2", "B3"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Check that A1 is still collapsed- const column = multiColumn.atOrThrow(0);- expect(column.isCollapsed("A1")).toBe(true);-- // Check that the structure is preserved- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([- ["A1", "A3"],- ["B1", "B2", "B3"],- ]);- });-- it("handles empty columns in previous shape", () => {- // Create a previous shape with an empty column- const previousMultiColumn = MultiColumn.from([- ["A1", "A2"],- [],- ["C1", "C2"],- ]);-- const ids = ["A1", "C2"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Should preserve the column structure- expect(multiColumn.colLength).toBe(3);- expect(multiColumn.topLevelIds).toEqual([["A1"], [], ["C2"]]);- });-- it("handles subset of ids with nested collapsed structure", () => {- // Create a previous shape with nested collapsed structure- let previousMultiColumn = MultiColumn.from([- ["A1", "A2", "A3", "A4", "A5"],- ["B1", "B2", "B3"],- ]);-- // Collapse A1 to include A2, A3- const columnIds = previousMultiColumn.getColumnIds();- previousMultiColumn = previousMultiColumn.transform(columnIds[0], (tree) =>- tree.collapse("A1", "A3"),- );-- // Create new shape with subset of ids- const ids = ["A1", "A2", "A3", "A4", "B1"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Check that collapsed state is preserved- const column = multiColumn.atOrThrow(0);- expect(column.isCollapsed("A1")).toBe(true);-- // Check that the structure is preserved- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([["A1", "A4"], ["B1"]]);- expect(multiColumn.inOrderIds).toEqual(["A1", "A2", "A3", "A4", "B1"]);- });-- it("handles reordering of columns", () => {- // Create a previous shape with specific column order- const previousMultiColumn = MultiColumn.from([- ["A1", "A2"],- ["B1", "B2"],- ["C1", "C2"],- ]);-- // Create new shape with ids in different order- const ids = ["C1", "A1", "B1"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Column order should be preserved- expect(multiColumn.colLength).toBe(3);- expect(multiColumn.topLevelIds).toEqual([["A1"], ["B1"], ["C1"]]);- });-- it("handles completely different set of ids", () => {- const previousMultiColumn = MultiColumn.from([- ["A1", "A2"],- ["B1", "B2"],- ]);-- // Completely different set of ids- const ids = ["X1", "X2", "X3"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // New ids should be added to the last column- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([["X1", "X2", "X3"], []]);- expect(multiColumn.inOrderIds).toEqual(["X1", "X2", "X3"]);- });-- it("preserves tree structure within columns", () => {- // Create a previous shape with complex tree structure- let previousMultiColumn = MultiColumn.from([- ["A1", "A2", "A3", "A4"],- ["B1", "B2", "B3"],- ]);-- // Create complex tree structure by collapsing nodes- const columnIds = previousMultiColumn.getColumnIds();- previousMultiColumn = previousMultiColumn.transform(columnIds[0], (tree) =>- tree.collapse("A1", "A2"),- );- previousMultiColumn = previousMultiColumn.transform(columnIds[1], (tree) =>- tree.collapse("B1", "B2"),- );-- // Create new shape with same ids- const ids = ["A1", "A2", "A3", "A4", "B1", "B2", "B3"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Check that collapsed state is preserved in both columns- expect(multiColumn.atOrThrow(0).isCollapsed("A1")).toBe(true);- expect(multiColumn.atOrThrow(1).isCollapsed("B1")).toBe(true);-- // Check that the structure is preserved- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([- ["A1", "A3", "A4"],- ["B1", "B3"],- ]);- });-- it("handles empty array of ids", () => {- const previousMultiColumn = MultiColumn.from([- ["A1", "A2"],- ["B1", "B2"],- ]);-- const multiColumn = MultiColumn.fromWithPreviousShape(- [],- previousMultiColumn,- );-- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([[], []]);- expect(multiColumn.inOrderIds).toEqual([]);- });-- it("handles single id", () => {- const previousMultiColumn = MultiColumn.from([- ["A1", "A2"],- ["B1", "B2"],- ]);-- const multiColumn = MultiColumn.fromWithPreviousShape(- ["A1"],- previousMultiColumn,- );-- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([["A1"], []]);- expect(multiColumn.inOrderIds).toEqual(["A1"]);- });-- it("preserves complex nested structure across multiple columns", () => {- // Create a complex structure with multiple columns and nested collapsed nodes- let previousMultiColumn = MultiColumn.from([- ["A1", "A2", "A3", "A4", "A5"],- ["B1", "B2", "B3", "B4"],- ["C1", "C2", "C3"],- ]);-- // Create complex nested structure- const columnIds = previousMultiColumn.getColumnIds();-- // Collapse in first column- previousMultiColumn = previousMultiColumn.transform(columnIds[0], (tree) =>- tree.collapse("A1", "A2"),- );- previousMultiColumn = previousMultiColumn.transform(columnIds[0], (tree) =>- tree.collapse("A3", "A4"),- );-- // Collapse in second column- previousMultiColumn = previousMultiColumn.transform(columnIds[1], (tree) =>- tree.collapse("B1", "B2"),- );-- // Collapse in third column- previousMultiColumn = previousMultiColumn.transform(columnIds[2], (tree) =>- tree.collapse("C1", "C2"),- );-- // Create new shape with all ids- const ids = [- "A1",- "A2",- "A3",- "A4",- "A5",- "B1",- "B2",- "B3",- "B4",- "C1",- "C2",- "C3",- ];-- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Check that all collapsed states are preserved- expect(multiColumn.atOrThrow(0).isCollapsed("A1")).toBe(true);- expect(multiColumn.atOrThrow(0).isCollapsed("A3")).toBe(true);- expect(multiColumn.atOrThrow(1).isCollapsed("B1")).toBe(true);- expect(multiColumn.atOrThrow(2).isCollapsed("C1")).toBe(true);-- // Check that the structure is preserved- expect(multiColumn.colLength).toBe(3);- expect(multiColumn.topLevelIds).toEqual([- ["A1", "A3", "A5"],- ["B1", "B3", "B4"],- ["C1", "C3"],- ]);- });-- it("handles case where ids are distributed differently than in previous shape", () => {- const previousMultiColumn = MultiColumn.from([- ["A1", "A2"],- ["B1", "B2"],- ["C1", "C2"],- ]);-- // Create new shape with ids from different columns grouped together- const ids = ["A1", "B1", "C1", "A2", "B2", "C2"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Should preserve the original column structure- expect(multiColumn.colLength).toBe(3);- expect(multiColumn.topLevelIds).toEqual([- ["A1", "A2"],- ["B1", "B2"],- ["C1", "C2"],- ]);- });-- it("handles case where previous shape has collapsed nodes but new ids don't include children", () => {- // Create a previous shape with collapsed nodes- let previousMultiColumn = MultiColumn.from([- ["A1", "A2", "A3"],- ["B1", "B2", "B3"],- ]);-- // Collapse nodes in both columns- const columnIds = previousMultiColumn.getColumnIds();- previousMultiColumn = previousMultiColumn.transform(columnIds[0], (tree) =>- tree.collapse("A1", "A2"),- );- previousMultiColumn = previousMultiColumn.transform(columnIds[1], (tree) =>- tree.collapse("B1", "B2"),- );-- // Create new shape without the collapsed children- const ids = ["A1", "A3", "B1", "B3"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Nodes should not be collapsed since children are missing- expect(multiColumn.atOrThrow(0).isCollapsed("A1")).toBe(false);- expect(multiColumn.atOrThrow(1).isCollapsed("B1")).toBe(false);-- // Check that the structure is preserved- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([- ["A1", "A3"],- ["B1", "B3"],- ]);- });-- it("handles deeply nested collapsed structure", () => {- // Create a tree with deeply nested collapsed structure- let previousTree = CollapsibleTree.from([- "one",- "two",- "three",- "four",- "five",- "six",- "seven",- "eight",- ]);-- // Create nested collapses- previousTree = previousTree.collapse("one", "two");-- // Get the collapsed node and collapse its children- const oneNode = previousTree._nodeMap.get("one");- expect(oneNode).toBeDefined();-- // Create a new tree with the same structure- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "two", "three", "four", "five", "six", "seven", "eight"],- previousTree,- );-- // Check that collapsed state is preserved- expect(tree.isCollapsed("one")).toBe(true);- expect(tree.topLevelIds).toEqual([- "one",- "three",- "four",- "five",- "six",- "seven",- "eight",- ]);- });-- it("handles case where collapsed node is at the end", () => {- // Create a tree with collapsed node at the end- let previousTree = CollapsibleTree.from([- "one",- "two",- "three",- "four",- "five",- ]);- previousTree = previousTree.collapse("four", "five");-- // Create new tree with same ids- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "two", "three", "four", "five"],- previousTree,- );-- // Check that collapsed state is preserved- expect(tree.isCollapsed("four")).toBe(true);- expect(tree.topLevelIds).toEqual(["one", "two", "three", "four"]);- });-- it("handles case with multiple collapsed nodes in the same column", () => {- // Create a previous shape with multiple collapsed nodes in the same column- let previousMultiColumn = MultiColumn.from([- ["A1", "A2", "A3", "A4", "A5", "A6"],- ["B1", "B2"],- ]);-- // Collapse multiple nodes in the first column- const columnIds = previousMultiColumn.getColumnIds();- previousMultiColumn = previousMultiColumn.transform(columnIds[0], (tree) =>- tree.collapse("A1", "A2"),- );- previousMultiColumn = previousMultiColumn.transform(columnIds[0], (tree) =>- tree.collapse("A3", "A4"),- );- previousMultiColumn = previousMultiColumn.transform(columnIds[0], (tree) =>- tree.collapse("A5", "A6"),- );-- // Create new shape with same ids- const ids = ["A1", "A2", "A3", "A4", "A5", "A6", "B1", "B2"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Check that all collapsed states are preserved- expect(multiColumn.atOrThrow(0).isCollapsed("A1")).toBe(true);- expect(multiColumn.atOrThrow(0).isCollapsed("A3")).toBe(true);- expect(multiColumn.atOrThrow(0).isCollapsed("A5")).toBe(true);-- // Check that the structure is preserved- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds).toEqual([- ["A1", "A3", "A5"],- ["B1", "B2"],- ]);- });-- it("handles case where all columns are empty in previous shape", () => {- // Create a previous shape with all empty columns- const previousMultiColumn = MultiColumn.from([[], [], []]);-- // Create new shape with new ids- const ids = ["A1", "B1", "C1"];- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // New ids should be added to the last column- expect(multiColumn.colLength).toBe(3);- expect(multiColumn.topLevelIds).toEqual([["A1", "B1", "C1"], [], []]);- expect(multiColumn.inOrderIds).toEqual(["A1", "B1", "C1"]);- });-- it("handles case with very large number of ids", () => {- // Create a previous shape with a reasonable number of ids- const previousIds1 = Array.from({ length: 50 }, (_, i) => `A${i}`);- const previousIds2 = Array.from({ length: 50 }, (_, i) => `B${i}`);- const previousMultiColumn = MultiColumn.from([previousIds1, previousIds2]);-- // Create a large set of ids- const ids = [- ...Array.from({ length: 50 }, (_, i) => `A${i}`),- ...Array.from({ length: 50 }, (_, i) => `B${i}`),- ...Array.from({ length: 50 }, (_, i) => `C${i}`),- ];-- const multiColumn = MultiColumn.fromWithPreviousShape(- ids,- previousMultiColumn,- );-- // Should preserve the column structure for existing ids and add new ids to last column- expect(multiColumn.colLength).toBe(2);- expect(multiColumn.topLevelIds[0].length).toBe(50);- expect(multiColumn.topLevelIds[1].length).toBe(100); // 50 B ids + 50 C ids- expect(multiColumn.inOrderIds.length).toBe(150); // All ids should be included- });-});--describe("CollapsibleTree.fromWithPreviousShape", () => {- it("creates a new tree when no previous tree is provided", () => {- const ids = ["one", "two", "three"];- const tree = CollapsibleTree.fromWithPreviousShape(ids);-- expect(tree.topLevelIds).toEqual(ids);- expect(tree.inOrderIds).toEqual(ids);- expect(tree.nodes.length).toBe(3);- expect(tree.nodes.every((node) => !node.isCollapsed)).toBe(true);- });-- it("preserves the tree ID when previous tree is provided", () => {- const previousTree = CollapsibleTree.from(["one", "two", "three"]);- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "two"],- previousTree,- );-- expect(tree.id).toBe(previousTree.id);- });-- it("preserves collapsed state from previous tree", () => {- // Create a tree with collapsed nodes- let previousTree = CollapsibleTree.from(["one", "two", "three", "four"]);- previousTree = previousTree.collapse("one", "two");-- // Create new tree with same ids- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "two", "three", "four"],- previousTree,- );-- // Check that one is still collapsed- expect(tree.isCollapsed("one")).toBe(true);- expect(tree.topLevelIds).toEqual(["one", "three", "four"]);- });-- it("handles subset of ids from previous tree", () => {- // Create a tree with collapsed nodes- let previousTree = CollapsibleTree.from([- "one",- "two",- "three",- "four",- "five",- ]);- previousTree = previousTree.collapse("one", "two");- previousTree = previousTree.collapse("three", "four");-- // Create new tree with subset of ids- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "two", "three"],- previousTree,- );-- // Check that collapsed state is preserved for existing nodes- expect(tree.isCollapsed("one")).toBe(true);- expect(tree.topLevelIds).toEqual(["one", "three"]);- });-- it("handles different ordering of ids", () => {- // Create a tree with collapsed nodes- let previousTree = CollapsibleTree.from(["one", "two", "three", "four"]);- previousTree = previousTree.collapse("one", "two");-- // Create new tree with different order- const tree = CollapsibleTree.fromWithPreviousShape(- ["three", "one", "two", "four"],- previousTree,- );-- // Check that collapsed state is preserved- expect(tree.isCollapsed("one")).toBe(true);- expect(tree.topLevelIds).toEqual(["three", "one", "four"]);- });-- it("handles new ids not in previous tree", () => {- // Create a tree with collapsed nodes- let previousTree = CollapsibleTree.from(["one", "two", "three"]);- previousTree = previousTree.collapse("one", "two");-- // Create new tree with new ids- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "two", "three", "four", "five"],- previousTree,- );-- // Check that collapsed state is preserved for existing nodes- expect(tree.isCollapsed("one")).toBe(true);- expect(tree.topLevelIds).toEqual(["one", "three", "four", "five"]);- });-- it("handles completely different set of ids", () => {- // Create a tree with collapsed nodes- let previousTree = CollapsibleTree.from(["one", "two", "three"]);- previousTree = previousTree.collapse("one", "two");-- // Create new tree with completely different ids- const tree = CollapsibleTree.fromWithPreviousShape(- ["four", "five", "six"],- previousTree,- );-- // Should have no collapsed nodes- expect(tree.nodes.every((node) => !node.isCollapsed)).toBe(true);- expect(tree.topLevelIds).toEqual(["four", "five", "six"]);- });-- it("preserves nested collapsed structure", () => {- // Create a tree with nested collapsed structure- let previousTree = CollapsibleTree.from([- "one",- "two",- "three",- "four",- "five",- "six",- ]);- previousTree = previousTree.collapse("one", "two");-- // Collapse the node that contains the collapsed children- const oneNode = previousTree.nodes.find((n) => n.value === "one");- expect(oneNode).toBeDefined();- expect(oneNode?.children.length).toBeGreaterThan(0);-- // Create a new tree with the same structure- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "two", "three", "four", "five", "six"],- previousTree,- );-- // Check that collapsed state is preserved- expect(tree.isCollapsed("one")).toBe(true);- expect(tree.topLevelIds).toEqual(["one", "three", "four", "five", "six"]);- });-- it("collapses using the last available child when some children are missing", () => {- // Create a tree with collapsed nodes- let previousTree = CollapsibleTree.from(["one", "two", "three", "four"]);- previousTree = previousTree.collapse("one", "three");-- // Create new tree without "two" but with "three"- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "three", "four"],- previousTree,- );-- // Should still collapse "one" with "three" as the child- expect(tree.isCollapsed("one")).toBe(true);- expect(tree.topLevelIds).toEqual(["one", "four"]);- });-- it("preserves collapse state when children order changes", () => {- // Create a tree with collapsed nodes- let previousTree = CollapsibleTree.from(["one", "two", "three", "four"]);- previousTree = previousTree.collapse("one", "two");-- // Create new tree with children in different order- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "three", "two", "four"],- previousTree,- );-- // Should still be collapsed- expect(tree.isCollapsed("one")).toBe(true);- // But the topLevelIds will be different because the children order changed- expect(tree.topLevelIds).toEqual(["one", "four"]);- });-- it("handles empty arrays correctly", () => {- const previousTree = CollapsibleTree.from(["one", "two", "three"]);- const tree = CollapsibleTree.fromWithPreviousShape([], previousTree);-- expect(tree.nodes.length).toBe(0);- expect(tree.topLevelIds).toEqual([]);- expect(tree.inOrderIds).toEqual([]);- });-- it("handles single item arrays correctly", () => {- let previousTree = CollapsibleTree.from(["one", "two", "three"]);- previousTree = previousTree.collapse("one", "two");-- const tree = CollapsibleTree.fromWithPreviousShape(["one"], previousTree);-- expect(tree.nodes.length).toBe(1);- expect(tree.topLevelIds).toEqual(["one"]);- expect(tree.inOrderIds).toEqual(["one"]);- // Should not be collapsed since there are no children- expect(tree.isCollapsed("one")).toBe(false);- });-- it("handles multiple collapsed nodes in sequence", () => {- let previousTree = CollapsibleTree.from([- "one",- "two",- "three",- "four",- "five",- "six",- ]);- previousTree = previousTree.collapse("one", "two");- previousTree = previousTree.collapse("three", "four");- previousTree = previousTree.collapse("five", "six");-- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "two", "three", "four", "five", "six"],- previousTree,- );-- expect(tree.isCollapsed("one")).toBe(true);- expect(tree.isCollapsed("three")).toBe(true);- expect(tree.isCollapsed("five")).toBe(true);- expect(tree.topLevelIds).toEqual(["one", "three", "five"]);- });-- it("handles case where collapsed node's children are not in new ids", () => {- let previousTree = CollapsibleTree.from(["one", "two", "three", "four"]);- previousTree = previousTree.collapse("one", "two");-- // Create new tree without the collapsed child- const tree = CollapsibleTree.fromWithPreviousShape(- ["one", "three", "four"],- previousTree,- );-- // Should not be collapsed since the child is missing- expect(tree.isCollapsed("one")).toBe(false);- expect(tree.topLevelIds).toEqual(["one", "three", "four"]);- });-- it("reproduces GitHub issue #6188: inOrderIds with nested collapses", () => {- // Simplified reproduction case:- // Cell A (markdown): # Section 1 Header- // Cell B (markdown): ## Subsection 1.1 Header- // Cell C (python): print("This cell should be in Subsection 1.1")- // Cell D (python): print("This cell should also be in Subsection 1.1")- // Cell E (markdown): ## Subsection 1.2 Header- // Cell F (python): print("This cell should be in Subsection 1.2")-- const originalOrder = [- "CellA", // # Section 1 Header- "CellB", // ## Subsection 1.1 Header- "CellC", // print("This cell should be in Subsection 1.1")- "CellD", // print("This cell should also be in Subsection 1.1")- "CellE", // ## Subsection 1.2 Header- "CellF", // print("This cell should be in Subsection 1.2")- ];-- // Create notebook with one column- let notebook = MultiColumn.from([originalOrder]);-- // Before collapsing, order should be correct- expect(notebook.inOrderIds).toEqual(originalOrder);-- const columnId = notebook.getColumnIds()[0];-- // Follow the exact reproduction steps from the GitHub issue:- // 1. Collapse B (subsection 1.1) - includes C, D (stops before E)- notebook = notebook.transform(columnId, (tree) =>- tree.collapse("CellB", "CellD"),- );-- // 2. Collapse E (subsection 1.2) - includes F (to end)- notebook = notebook.transform(columnId, (tree) =>- tree.collapse("CellE", undefined),- );-- // 3. Collapse A (section 1) - includes all the rest (B, E and their children)- notebook = notebook.transform(columnId, (tree) =>- tree.collapse("CellA", undefined),- );-- const finalOrder = notebook.inOrderIds;-- // inOrderIds now correctly preserves logical order even with nested collapses- expect(finalOrder).toEqual(originalOrder);- });-});diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsxindex 5e44d94803..0f595d8abc 100644--- a/frontend/src/utils/id-tree.tsx+++ b/frontend/src/utils/id-tree.tsx@@ -3,7 +3,7 @@import { Memoize } from "typescript-memoize";import { reorderColumnSizes } from "@/components/editor/columns/storage";import { SETUP_CELL_ID } from "@/core/cells/ids";-import { arrayDelete, arrayInsert, arrayInsertMany, arrayMove } from "./arrays";+import { arrayDelete, arrayInsert, arrayMove } from "./arrays";import { Logger } from "./Logger";/**@@ -25,79 +25,12 @@ export type CellIndex = number & { __brand?: "CellIndex" };*/export class TreeNode<T> {public value: T;- public isCollapsed: boolean;- public children: TreeNode<T>[];- public constructor(value: T, isCollapsed: boolean, children: TreeNode<T>[]) {+ public constructor(value: T) {this.value = value;- this.isCollapsed = isCollapsed;- this.children = children;- }-- /**- * Recursively count the number of nodes in the tree- */- @Memoize()- public geDescendantCount(): number {- let count = 0;- const stack = [...this.children];-- while (stack.length > 0) {- // oxlint-disable-next-line typescript/no-non-null-assertion- const node = stack.pop()!;- count++;-- // Add children to stack- for (let i = node.children.length - 1; i >= 0; i--) {- stack.push(node.children[i]);- }- }-- return count;- }-- @Memoize()- public getDescendants(): T[] {- const result: T[] = [];- const stack = [...this.children];-- while (stack.length > 0) {- // oxlint-disable-next-line typescript/no-non-null-assertion- const node = stack.pop()!;- result.push(node.value);-- // Add children to stack in reverse order to maintain correct traversal order- for (let i = node.children.length - 1; i >= 0; i--) {- stack.push(node.children[i]);- }- }-- return result;- }-- @Memoize()- public get inOrderIds(): T[] {- const result: T[] = [];-- // Use depth-first traversal to preserve logical document order- const traverse = (node: TreeNode<T>) => {- result.push(node.value);- for (const child of node.children) {- traverse(child);- }- };-- for (const child of this.children) {- traverse(child);- }-- return result;}public toString(): string {- if (this.isCollapsed) {- return `${this.value} (collapsed)`;- }return String(this.value);}@@ -117,52 +50,14 @@ export class CollapsibleTree<T> {this.id = id;}- public static from<T>(ids: T[]): CollapsibleTree<T> {- const id = `tree_${uniqueId++}` as CellColumnId;+ /** A column of `ids`, keeping `id` when a column is rebuilt. */+ public static from<T>(ids: T[], id?: CellColumnId): CollapsibleTree<T> {return new CollapsibleTree(- ids.map((id) => new TreeNode(id, false, [])),- id,+ ids.map((id) => new TreeNode(id)),+ id ?? (`tree_${uniqueId++}` as CellColumnId),);}- /**- * Create a new tree from ids, preserving structure from previous tree if possible- */- public static fromWithPreviousShape<T>(- ids: T[],- previousTree?: CollapsibleTree<T>,- ): CollapsibleTree<T> {- if (!previousTree) {- return CollapsibleTree.from(ids);- }-- // Reuse the previous tree's id if possible- const id = previousTree.id;-- // Create new tree with nothing collapsed- let newTree = new CollapsibleTree(- ids.map((id) => new TreeNode(id, false, [])),- id,- );-- // Collapse nodes that were collapsed in the previous tree- for (const id of ids) {- if (previousTree.isCollapsed(id)) {- const children = previousTree._nodeMap.get(id)?.children ?? [];- // Find the first child that is also in the new tree, going backwards- for (let i = children.length - 1; i >= 0; i--) {- const child = children[i];- if (newTree._nodeMap.has(child.value)) {- newTree = newTree.collapse(id, child.value);- break;- }- }- }- }-- return newTree;- }-public withNodes(nodes: TreeNode<T>[]): CollapsibleTree<T> {return new CollapsibleTree(nodes, this.id);}@@ -172,9 +67,8 @@ export class CollapsibleTree<T> {return this.nodes.map((n) => n.value);}- @Memoize()public get inOrderIds(): T[] {- return this.nodes.flatMap((n) => [n.value, ...n.inOrderIds]);+ return this.topLevelIds;}@Memoize()@@ -195,38 +89,6 @@ export class CollapsibleTree<T> {return result;}- /**- * Get the descendants of the given node- *- * Only works for the top-level nodes- */- public getDescendants(id: T): T[] {- const node = this._nodeMap.get(id);- if (!node) {- Logger.warn(- `Node ${id} not found in tree. Valid ids: ${this.topLevelIds}`,- );- return [];- }- return node.getDescendants();- }-- /**- * Check if the given node is collapsed- *- * Only works for the top-level nodes- */- public isCollapsed(id: T): boolean {- const node = this._nodeMap.get(id);- if (!node) {- Logger.warn(- `Node ${id} not found in tree. Valid ids: ${this.topLevelIds}`,- );- return false;- }- return node.isCollapsed;- }-/*** Get the index of the given node, or throw*/@@ -248,173 +110,6 @@ export class CollapsibleTree<T> {return this.nodes.slice(start, end).map((n) => n.value);}- /**- * Move the given node to the front- */- public moveToFront(id: T): CollapsibleTree<T> {- const index = this.indexOfOrThrow(id);- return this.withNodes(arrayMove(this.nodes, index, 0));- }-- /**- * Move the given node to the back- */- public moveToBack(id: T): CollapsibleTree<T> {- const index = this.indexOfOrThrow(id);- return this.withNodes(arrayMove(this.nodes, index, this.nodes.length - 1));- }-- /**- * Collapse everything past the given node @param id- * until @param until or the end of the tree- */- public collapse(id: T, until: T | undefined): CollapsibleTree<T> {- const nodeIndex = this.nodes.findIndex((n) => n.value === id);- if (nodeIndex === -1) {- throw new Error(- `Node ${id} not found in tree. Valid ids: ${this.topLevelIds}`,- );- }-- const untilIndex =- until === undefined- ? this.nodes.length- : this.nodes.findIndex((n) => n.value === until);-- if (untilIndex === -1) {- throw new Error(`Node ${until} not found in tree`);- }- if (untilIndex < nodeIndex) {- throw new Error(`Node ${until} is before node ${id}`);- }-- const nodes = [...this.nodes];- const node = nodes[nodeIndex];- if (node.isCollapsed) {- throw new Error(`Node ${id} is already collapsed`);- }-- // Fold the next nodes into the current node- const children = nodes.splice(nodeIndex + 1, untilIndex - nodeIndex);- nodes[nodeIndex] = new TreeNode(node.value, true, children);-- return this.withNodes(nodes);- }-- /**- * Collapse all nodes in the tree, including nested ones- *- * Only works for the top-level nodes- * Does not collapse the children of already collapsed nodes- */- public collapseAll(- collapseRanges: ({ id: T; until: T | undefined } | null)[],- ): CollapsibleTree<T> {- const nodes = [...this.nodes];- if (collapseRanges.length === 0) {- throw new Error("No collapse ranges provided");- }-- if (collapseRanges.length !== nodes.length) {- throw new Error(- `Collapse ranges length ${collapseRanges.length} does not match tree length ${nodes.length}`,- );- }-- // Start from the end of the list and collapse nodes children first- let nodeIndex = nodes.length - 1;- while (nodeIndex >= 0) {- const node = nodes[nodeIndex];- const range = collapseRanges[nodeIndex];-- if (!node.isCollapsed && range) {- const { id, until } = range;- if (id !== node.value) {- throw new Error(- `Node ${node.value} does not match collapse range id ${id}`,- );- }- const untilIndex =- until === undefined- ? nodes.length- : nodes.findIndex((n) => n.value === until);-- if (untilIndex === -1) {- throw new Error(`Node ${until} not found in tree`);- }- if (untilIndex < nodeIndex) {- throw new Error(`Node ${until} is before node ${id}`);- }-- // Fold the next nodes into the current node- const children = nodes.splice(nodeIndex + 1, untilIndex - nodeIndex);- nodes[nodeIndex] = new TreeNode(node.value, true, children);- nodeIndex--;- } else {- // Move to the next node- nodeIndex--;- }- }-- return this.withNodes(nodes);- }-- /**- * Expand a node and all of its children.- * If the node is already expanded, returns the same tree (no-op).- */- public expand(id: T): CollapsibleTree<T> {- const nodeIndex = this.nodes.findIndex((n) => n.value === id);- if (nodeIndex === -1) {- throw new Error(- `Node ${id} not found in tree. Valid ids: ${this.topLevelIds}`,- );- }-- let nodes = [...this.nodes];- const node = nodes[nodeIndex];- if (!node.isCollapsed) {- // Already expanded, no-op- return this;- }-- nodes[nodeIndex] = new TreeNode(node.value, false, []);- nodes = arrayInsertMany(nodes, nodeIndex + 1, node.children);-- return this.withNodes(nodes);- }-- /**- * Expand all collapsed nodes in the tree, including nested ones- */- public expandAll(): CollapsibleTree<T> {- let nodes = [...this.nodes];- let nodeIndex = 0;-- while (nodeIndex < nodes.length) {- const node = nodes[nodeIndex];- if (node.isCollapsed) {- // Replace the collapsed node with an expanded one- nodes[nodeIndex] = new TreeNode(node.value, false, []);- // Add the children of the collapsed node to the list- nodes = arrayInsertMany(nodes, nodeIndex + 1, node.children);- nodeIndex++;- } else {- // Move to the next node- nodeIndex++;- }- }-- return this.withNodes(nodes);- }-- /**- * Move a node from one index to another- */- public move(fromIdx: number, toIdx: number): CollapsibleTree<T> {- return this.withNodes(arrayMove(this.nodes, fromIdx, toIdx));- }-/*** Get the node at the given index*/@@ -473,9 +168,7 @@ export class CollapsibleTree<T> {* Insert a node at the given index*/public insert(id: T, index: number): CollapsibleTree<T> {- return this.withNodes(- arrayInsert(this.nodes, index, new TreeNode(id, false, [])),- );+ return this.withNodes(arrayInsert(this.nodes, index, new TreeNode(id)));}/**@@ -492,14 +185,9 @@ export class CollapsibleTree<T> {return this.insert(id, 0);}- /**- * Delete a node, expand if it was collapsed- */public deleteAtIndex(idx: number): CollapsibleTree<T> {- const id = this.atOrThrow(idx);- // Expand the node first (if collapsed) to bring children back to top level- const tree = this.expand(id);- return tree.withNodes(arrayDelete(tree.nodes, idx));+ this.atOrThrow(idx);+ return this.withNodes(arrayDelete(this.nodes, idx));}public delete(id: T): CollapsibleTree<T> {@@ -507,49 +195,6 @@ export class CollapsibleTree<T> {return this.deleteAtIndex(index);}- /**- * Get the number of nodes in the tree, not-including the given node- */- public getCount(id: T): number {- return this._nodeMap.get(id)?.geDescendantCount() ?? 0;- }-- /**- * Find and expand the node and all of its children- */- public findAndExpandDeep(id: T): CollapsibleTree<T> {- const found = this.find(id);- if (found.length === 0) {- return this;- }- return found.reduce<CollapsibleTree<T>>(- (acc, node) => acc.expand(node),- this,- );- }-- /**- * Find a node, returning the path to it- * With the last element being the node itself- */- public find(id: T): T[] {- // We need to recursively find the node- function findNode(nodes: TreeNode<T>[], path: T[]): T[] {- for (const node of nodes) {- if (node.value === id) {- return [...path, id];- }- const result = findNode(node.children, [...path, node.value]);- if (result.length > 0) {- return result;- }- }- return [];- }-- return findNode(this.nodes, []);- }-/*** Split the tree into two trees* @param id the id of the node to split at@@ -578,18 +223,7 @@ export class CollapsibleTree<T> {}public toString(): string {- let depth = 0;- let result = "";- const asString = (nodes: TreeNode<T>[]) => {- for (const node of nodes) {- result += `${" ".repeat(depth * 2)}${node.toString()}\n`;- depth += 1;- asString(node.children);- depth -= 1;- }- };- asString(this.nodes);- return result;+ return this.nodes.map((node) => `${node.toString()}\n`).join("");}}@@ -642,7 +276,7 @@ export class MultiColumn<T> {}const newColumns = splitIds.map((ids, idx) =>- CollapsibleTree.fromWithPreviousShape(ids, previousColumns[idx]),+ CollapsibleTree.from(ids, previousColumns[idx].id),);return new MultiColumn(newColumns);@@ -814,117 +448,6 @@ export class MultiColumn<T> {return new MultiColumn([firstColumn.withNodes(nodes)]);}- public moveWithinColumn(- col: CellColumnId,- fromIdx: CellIndex,- toIdx: CellIndex,- ): MultiColumn<T> {- return this.transform(col, (c) => {- return c.move(fromIdx, toIdx);- });- }-- public moveAcrossColumns(- fromCol: CellColumnId,- fromId: T,- toCol: CellColumnId,- toId: T | undefined,- ): MultiColumn<T> {- // Find indices once to avoid repeated lookups- const fromColumnIndex = this.indexOfOrThrow(fromCol);- const toColumnIndex = this.indexOfOrThrow(toCol);-- // Only copy the columns we're modifying- const newColumns = [...this.columns];- const fromColumn = newColumns[fromColumnIndex];-- // Find the node once- const nodeIndex = fromColumn.nodes.findIndex((n) => n.value === fromId);- if (nodeIndex === -1) {- throw new Error(`Node ${fromId} not found in column ${fromCol}`);- }-- const node = fromColumn.nodes[nodeIndex];-- // Create new columns with the changes- newColumns[fromColumnIndex] = fromColumn.withNodes(- fromColumn.nodes.filter((_, i) => i !== nodeIndex),- );-- const toColumn = newColumns[toColumnIndex];- if (toId) {- const toIndex = toColumn.indexOfOrThrow(toId);- newColumns[toColumnIndex] = toColumn.withNodes(- arrayInsert(toColumn.nodes, toIndex, node),- );- } else {- newColumns[toColumnIndex] = toColumn.withNodes([node, ...toColumn.nodes]);- }-- return new MultiColumn(newColumns);- }-- /**- * Move multiple cells to be immediately before (or after) a target cell.- * Cells are inserted in their original order.- *- * @throws Error if any cellId is not found in any column.- * If targetId is among the moved cells, cells are inserted at the end of the target column.- */- public moveCellsRelativeTo(- cellIds: T[],- targetId: T,- position: "before" | "after",- ): MultiColumn<T> {- if (cellIds.length === 0) {- return this;- }-- const cellIdSet = new Set(cellIds);- const targetColumn = this.findWithId(targetId);- const targetColIndex = this.indexOfOrThrow(targetColumn.id);-- // Collect nodes to move- const nodesToMove: TreeNode<T>[] = [];- for (const id of cellIds) {- const col = this.findWithId(id);- const node = col.nodes.find((n) => n.value === id);- if (!node) {- throw new Error(`Node ${id} not found in column ${col.id}`);- }- nodesToMove.push(node);- }-- // Remove moved cells from all columns- const columnsWithRemovals = this.columns.map((col) =>- col.withNodes(col.nodes.filter((n) => !cellIdSet.has(n.value))),- );-- // Find target index in the cleaned column- const cleanedTargetCol = columnsWithRemovals[targetColIndex];- let insertIndex = cleanedTargetCol.nodes.findIndex(- (n) => n.value === targetId,- );-- // If target was one of the moved cells, insert at end- if (insertIndex === -1) {- insertIndex = cleanedTargetCol.nodes.length;- } else if (position === "after") {- insertIndex += 1;- }-- // Insert all moved nodes at target position- const newTargetNodes = arrayInsertMany(- cleanedTargetCol.nodes,- insertIndex,- nodesToMove,- );- columnsWithRemovals[targetColIndex] =- cleanedTargetCol.withNodes(newTargetNodes);-- return new MultiColumn(columnsWithRemovals);- }-public indexOfOrThrow(id: CellColumnId): number {const index = this.columns.findIndex((c) => c.id === id);if (index === -1) {@@ -954,22 +477,6 @@ export class MultiColumn<T> {return new MultiColumn(arrayMove([...this.columns], fromIdx, toIdx));}- public moveToNewColumn(cellId: T): MultiColumn<T> {- const fromColumn = this.findWithId(cellId);-- // Create new columns array with the cell removed from its original column- const columns = this.columns.map((c) => {- if (c.id === fromColumn.id) {- return c.delete(cellId);- }- return c;- });-- // Insert into new column- const newColumn = CollapsibleTree.from([cellId]);- return new MultiColumn([...columns, newColumn]);- }-public findWithId(id: T): CollapsibleTree<T> {const found = this.columns.find((c) => {return c.inOrderIds.includes(id);@@ -1023,38 +530,6 @@ export class MultiColumn<T> {return this.transform(col, (c) => c.insert(id, index));}- public deleteById(cellId: T): MultiColumn<T> {- return this.transformWithCellId(cellId, (c) => c.delete(cellId));- }-- /**- * Remove the given cells from the tree, then re-insert each at its- * (columnId, index). Used to undo a move (e.g. cut-paste) by restoring- * cells to their previous positions. Placements are sorted by- * (columnId, index) so insert order keeps indices valid.- */- public placeCells(- placements: Array<{ id: T; columnId: CellColumnId; index: CellIndex }>,- ): MultiColumn<T> {- if (placements.length === 0) {- return this;- }- let result = this.deleteById(placements[0].id);- for (const { id } of placements.slice(1)) {- result = result.deleteById(id);- }- const sorted = [...placements].toSorted((a, b) => {- if (a.columnId !== b.columnId) {- return a.columnId.localeCompare(b.columnId);- }- return (a.index as number) - (b.index as number);- });- for (const { id, columnId, index } of sorted) {- result = result.insertId(id, columnId, index);- }- return result;- }-public compact(): MultiColumn<T> {// Don't compact if there's only one columnif (this.columns.length === 1) {diff --git a/marimo/_server/host/bridge.py b/marimo/_server/host/bridge.pyindex 7ed01c0601..ceae80d10f 100644--- a/marimo/_server/host/bridge.py+++ b/marimo/_server/host/bridge.py@@ -457,6 +457,7 @@ class SessionBridge(SessionEventListener):notebook = self.host.peek_notebook(notebook_id)if session is None or notebook is None:return+ self._follow_config(notebook_id, session)if self.app_sessions is not None:cells, app_config = documents.from_session(session)notebook.replace(cells, app_config, saved=True)@@ -471,6 +472,26 @@ class SessionBridge(SessionEventListener):cells, app_config = documents.from_session(session)notebook.replace(cells, app_config, saved=True)+ # TODO(MO-7927): Following the editor's config ends when the notebook+ # owns the app config and the editor changes it through the host.+ def _follow_config(+ self, notebook_id: protocol.NotebookId, session: Session+ ) -> None:+ """Mirror the document when the editor changes the app config.++ The legacy endpoint changes it in the session, which fires no+ document transaction, so the file manager reports it instead.+ """+ loop = asyncio.get_running_loop()++ def config_changed() -> None:+ if _running_loop() is loop:+ self._mirror(notebook_id)+ else:+ loop.call_soon_threadsafe(self._mirror, notebook_id)++ session.app_file_manager.on_config_changed = config_changed+# TODO(MO-7927): Following the editor's writes ends when the notebook# owns persistence and the editor saves through it.def _follow_saves(@@ -506,6 +527,7 @@ class SessionBridge(SessionEventListener):Its baseline for external changes is the file as the editorleft it, read off the event loop before the next save compares."""+ session.app_file_manager.on_config_changed = Noneif self.app_sessions is not None:returnsession.app_file_manager.on_persisted = Nonediff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.pyindex 524b6dab8a..66a0a4a9d2 100644--- a/marimo/_session/notebook/file_manager.py+++ b/marimo/_session/notebook/file_manager.py@@ -79,8 +79,8 @@ class AppFileManager:# Load the appself.app = self._load_app(self.path)- # TODO(MO-7927): The host follows the editor's writes through this- # hook until the notebook owns persistence and no second writer+ # TODO(MO-7927): The host follows the editor's writes through these+ # hooks until the notebook owns persistence and no second writer# remains to follow.self.on_persisted: (Callable[[Sequence[NotebookCell], dict[str, Any]], None] | None@@ -90,6 +90,8 @@ class AppFileManager:The cells are the snapshot the save was given, not the livedocument, which another thread may have changed meanwhile."""+ self.on_config_changed: Callable[[], None] | None = None+ """Called after the app config changes, on the changing thread."""# Serializes concurrent writers. Public entry points wrap the full# "mutate app + _save_file" sequence and the writer re-acquires.@@ -391,16 +393,35 @@ class AppFileManager:Serialized notebook content"""with self._save_lock:- self.app.update_config(config)+ self._update_config(config)if self._filename is not None:self._invalidate_autosaves()- return self._save_file(+ contents = self._save_file(self._filename,notebook=self.app.to_ir(),persist=True,)+ self._persisted(+ [+ NotebookCell(+ id=data.cell_id,+ code=data.code,+ name=data.name,+ config=data.config,+ )+ for data in self.app.cell_manager.cell_data()+ ]+ )+ return contentsreturn ""+ def _update_config(self, config: dict[str, Any]) -> None:+ before = self.app.config.asdict()+ self.app.update_config(config)+ callback = self.on_config_changed+ if callback is not None and self.app.config.asdict() != before:+ callback()+def save(self,request: SaveNotebookRequest,@@ -456,10 +477,10 @@ class AppFileManager:layout_filename = save_layout_config(app_dir, app_name, LayoutConfig(**layout))- self.app.update_config({"layout_file": layout_filename})+ self._update_config({"layout_file": layout_filename})else:# Remove the layout from the config- self.app.update_config({"layout_file": None})+ self._update_config({"layout_file": None})if request.persist:self._invalidate_autosaves()diff --git a/tests/_server/host/test_host_bridge.py b/tests/_server/host/test_host_bridge.pyindex e02d5cce3d..dad6723cfd 100644--- a/tests/_server/host/test_host_bridge.py+++ b/tests/_server/host/test_host_bridge.py@@ -850,6 +850,45 @@ async def test_save_with_a_session_writes_through_the_editors_file_manager(bridge.close()+async def test_the_editor_changing_the_app_config_is_mirrored(+ manager: FakeManager, tmp_path: Path+) -> None:+ from marimo._session.notebook import AppFileManager++ prepare(manager, tmp_path, "a.py")+ path = tmp_path / "a.py"+ path.write_text(NOTEBOOK)+ bridge = SessionBridge(manager) # type: ignore[arg-type]+ await bridge.open()+ record = bridge.index.notebook_for(str(path))+ assert record is not None+ notebook = await bridge.host.notebook(record.id)+ session = FakeSession(str(path))+ session.app_file_manager = AppFileManager(str(path))+ session.document = session.app_file_manager.app.cell_manager.document+ manager.sessions["browser-1"] = session+ await manager.event_bus.emit_session_created(session) # type: ignore[arg-type]+ events: list[RoutedEvent] = []+ bridge.host.subscribe(events.append, notebook_id=record.id)+ assert notebook.document.app_config == {}++ # The legacy endpoint changes the config in the session and writes+ # the file; the host document follows, and the write counts as saved.+ session.app_file_manager.save_app_config({"width": "full"})++ assert notebook.document.app_config == {"width": "full"}+ assert notebook.saved_etag == notebook.document.etag+ # One revision for the change, one for the write that saved it.+ assert names(events) == ["document", "document"]+ last = events[-1].event.data.document # type: ignore[union-attr]+ assert last.saved_etag == last.etag+ assert 'width="full"' in path.read_text()++ manager.close_session("browser-1")+ assert session.app_file_manager.on_config_changed is None+ bridge.close()++async def test_the_editor_saving_marks_the_host_document_saved(manager: FakeManager, tmp_path: Path) -> None:diff --git a/tests/_session/notebook/test_app_file_manager.py b/tests/_session/notebook/test_app_file_manager.pyindex 0ddb519ef9..590aae0797 100644--- a/tests/_session/notebook/test_app_file_manager.py+++ b/tests/_session/notebook/test_app_file_manager.py@@ -373,3 +373,22 @@ def test_on_persisted_reports_the_cells_and_config_written(fm.save_from_cells(cells)assert seen == [(cells, {"width": "full"})]+++def test_on_config_changed_fires_only_when_the_config_changes(+ tmp_path: Path,+) -> None:+ nb = tmp_path / "nb.py"+ nb.write_text(_NOTEBOOK_SOURCE)+ fm = AppFileManager(str(nb))+ changes: list[None] = []+ fm.on_config_changed = lambda: changes.append(None)++ fm.save_app_config({})+ assert changes == []++ fm.save_app_config({"width": "full"})+ assert len(changes) == 1++ fm.save_app_config({"width": "full"})+ assert len(changes) == 1