Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Edit cells through the document model (#11535)

Trevor Manze89cbfe8f800
diff --git a/frontend/benchmarks/cell-editing.bench.ts b/frontend/benchmarks/cell-editing.bench.ts
index 8c9f20bfef..a41061fbc9 100644
--- a/frontend/benchmarks/cell-editing.bench.ts
+++ b/frontend/benchmarks/cell-editing.bench.ts
@@ -5,7 +5,7 @@ import { bench, describe, expect } from "vitest";
import { MockNotebook } from "@/__mocks__/notebook";
import { cellId } from "@/__tests__/branded";
import {
- type CellActions,
+ type ReducerCellActions,
cellDataAtom,
cellErrorsAtom,
cellHandleAtom,
@@ -23,7 +23,7 @@ import { layoutStateAtom } from "@/core/layout/state";
import { lastSavedNotebookAtom, needsSaveAtom } from "@/core/saving/state";
import type { DispatchedActionOf } from "@/utils/createReducer";
-type CellAction = DispatchedActionOf<CellActions>;
+type CellAction = DispatchedActionOf<ReducerCellActions>;
const options = { time: 500, warmupTime: 200, iterations: 100 };
const code = Array.from({ length: 20 }, (_, i) => `value_${i} = ${i}`).join(
diff --git a/frontend/src/__mocks__/document.tsx b/frontend/src/__mocks__/document.tsx
new file mode 100644
index 0000000000..65a04d4901
--- /dev/null
+++ b/frontend/src/__mocks__/document.tsx
@@ -0,0 +1,54 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { atom, type createStore, Provider } from "jotai";
+import type { ReactNode } from "react";
+import {
+ createDocumentModel,
+ type DocumentModel,
+ DocumentProvider,
+} from "@/core/notebook/document";
+import { document as documentFixture } from "@/core/notebook/document/__tests__/fixtures";
+import type { Document } from "@/core/notebook/replica";
+import { fakeBackend } from "@/core/notebook/replica/__tests__/fixtures";
+import { activeDocumentModelAtom } from "@/core/session/active-notebook";
+
+/** A started document model over `document`, for components that edit cells. */
+export function mockDocumentModel(
+ store: ReturnType<typeof createStore>,
+ document: Document | null = documentFixture(),
+): { model: DocumentModel; stop: () => void } {
+ const controller = new AbortController();
+ const model = createDocumentModel({
+ store,
+ documentAtom: atom(document),
+ backendAtom: atom(fakeBackend()),
+ });
+ model.start({ signal: controller.signal });
+ store.set(activeDocumentModelAtom, model);
+ return {
+ model,
+ stop: () => {
+ controller.abort();
+ if (store.get(activeDocumentModelAtom) === model) {
+ store.set(activeDocumentModelAtom, null);
+ }
+ },
+ };
+}
+
+/** Provide `store` and `model` to a rendered hook or component. */
+export function DocumentWrapper({
+ store,
+ model,
+ children,
+}: {
+ store: ReturnType<typeof createStore>;
+ model: DocumentModel;
+ children?: ReactNode;
+}) {
+ return (
+ <Provider store={store}>
+ <DocumentProvider model={model}>{children}</DocumentProvider>
+ </Provider>
+ );
+}
diff --git a/frontend/src/__mocks__/notebook.ts b/frontend/src/__mocks__/notebook.ts
index ba2da0d26b..200962d660 100644
--- a/frontend/src/__mocks__/notebook.ts
+++ b/frontend/src/__mocks__/notebook.ts
@@ -2,7 +2,8 @@
import { createRef } from "react";
import { vi } from "vitest";
-import type { CellActions, NotebookState } from "@/core/cells/cells";
+import type { CellActions } from "@/core/cells/actions";
+import type { NotebookState } from "@/core/cells/cells";
import { CellId } from "@/core/cells/ids";
import {
type CellData,
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index 81b64c5a15..47e9cf55c3 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -26,11 +26,9 @@ export const MockRequestClient = {
sendRun: vi.fn().mockResolvedValue({}),
sendRunScratchpad: vi.fn().mockResolvedValue({}),
sendInstantiate: vi.fn().mockResolvedValue({}),
- sendDeleteCell: vi.fn().mockResolvedValue({}),
sendCodeCompletionRequest: vi.fn().mockResolvedValue({ items: [] }),
saveUserConfig: vi.fn().mockResolvedValue({}),
saveAppConfig: vi.fn().mockResolvedValue({}),
- saveCellConfig: vi.fn().mockResolvedValue({}),
sendFunctionRequest: vi.fn().mockResolvedValue({}),
sendInstallMissingPackages: vi.fn().mockResolvedValue({}),
readCode: vi.fn().mockResolvedValue({ contents: "" }),
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index 39d74eda28..59fd2406ce 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -53,7 +53,7 @@ import {
type CopilotMode,
FRONTEND_TOOL_REGISTRY,
} from "@/core/ai/tools/registry";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { aiAtom, aiModelConfiguredAtom } from "@/core/config/config";
import { DEFAULT_AI_MODEL } from "@/core/config/config-schema";
import { useRequestClient } from "@/core/network/requests";
@@ -582,10 +582,10 @@ const ChatPanelBody = () => {
const store = useStore();
const { addStagedCell } = useStagedAICellsActions();
- const { createNewCell, prepareForRun } = useCellActions();
+ const { prepareForRun, createCell } = useCellActions();
const toolContext: ToolNotebookContext = {
addStagedCell,
- createNewCell,
+ createCell,
prepareForRun,
sendRun,
store,
diff --git a/frontend/src/components/datasources/__tests__/column-preview.test.tsx b/frontend/src/components/datasources/__tests__/column-preview.test.tsx
index 0202d328f6..071effbe0d 100644
--- a/frontend/src/components/datasources/__tests__/column-preview.test.tsx
+++ b/frontend/src/components/datasources/__tests__/column-preview.test.tsx
@@ -12,11 +12,10 @@ import { requestClientAtom } from "@/core/network/requests";
import { store } from "@/core/state/jotai";
import { DatasetColumnPreview } from "../column-preview";
-const { createNewCell } = vi.hoisted(() => ({ createNewCell: vi.fn() }));
+const { createCell } = vi.hoisted(() => ({ createCell: vi.fn() }));
-vi.mock("@/core/cells/cells", async (importOriginal) => ({
- ...(await importOriginal<typeof import("@/core/cells/cells")>()),
- useCellActions: () => ({ createNewCell }),
+vi.mock("@/core/cells/actions", () => ({
+ useCellActions: () => ({ createCell }),
}));
const wrapper = ({ children }: { children: React.ReactNode }) => (
@@ -179,12 +178,11 @@ describe("DatasetColumnPreview chart actions", () => {
name: `Add chart to notebook for ${column.name}`,
}),
);
- expect(createNewCell).toHaveBeenLastCalledWith({
+ expect(createCell).toHaveBeenLastCalledWith({
+ after: null,
code: `chart_${column.name}`,
- before: false,
- cellId: "__end__",
});
}
- expect(createNewCell).toHaveBeenCalledTimes(2);
+ expect(createCell).toHaveBeenCalledTimes(2);
});
});
diff --git a/frontend/src/components/datasources/column-preview.tsx b/frontend/src/components/datasources/column-preview.tsx
index ce85747d42..5f1da3e394 100644
--- a/frontend/src/components/datasources/column-preview.tsx
+++ b/frontend/src/components/datasources/column-preview.tsx
@@ -5,7 +5,7 @@ import { PlusSquareIcon } from "lucide-react";
import React, { Suspense } from "react";
import { useLocale } from "react-aria";
import { maybeAddAltairImport } from "@/core/cells/add-missing-import";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { useLastFocusedCellId } from "@/core/cells/focus";
import { autoInstantiateAtom } from "@/core/config/config";
import type { SQLTableContext } from "@/core/datasets/data-source-connections";
@@ -249,21 +249,17 @@ export const AddDataframeChart: React.FC<{
}> = ({ chartCode, columnName }) => {
const autoInstantiate = useAtomValue(autoInstantiateAtom);
const lastFocusedCellId = useLastFocusedCellId();
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
const handleAddColumn = (chartCode: string) => {
if (chartCode.includes("alt")) {
maybeAddAltairImport({
autoInstantiate,
- createNewCell,
+ createCell,
fromCellId: lastFocusedCellId,
});
}
- createNewCell({
- code: chartCode,
- before: false,
- cellId: lastFocusedCellId ?? "__end__",
- });
+ createCell({ after: lastFocusedCellId, code: chartCode });
};
return (
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsx
index b5060169ed..7017f95ebe 100644
--- a/frontend/src/components/datasources/datasources.tsx
+++ b/frontend/src/components/datasources/datasources.tsx
@@ -17,7 +17,8 @@ import { Button, buttonVariants } from "@/components/ui/button";
import { Command, CommandInput, CommandItem } from "@/components/ui/command";
import { Tooltip } from "@/components/ui/tooltip";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
-import { cellIdsAtom, useCellActions } from "@/core/cells/cells";
+import { cellIdsAtom } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { useLastFocusedCellId } from "@/core/cells/focus";
import { autoInstantiateAtom } from "@/core/config/config";
import {
@@ -849,13 +850,13 @@ const DatasetTableItem: React.FC<{
const autoInstantiate = useAtomValue(autoInstantiateAtom);
const lastFocusedCellId = useLastFocusedCellId();
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
const addCodeToNewCell = useAddCodeToNewCell();
const handleAddTable = () => {
maybeAddMarimoImport({
autoInstantiate,
- createNewCell,
+ createCell,
fromCellId: lastFocusedCellId,
});
const getCode = () => {
diff --git a/frontend/src/components/dependency-graph/minimap-content.tsx b/frontend/src/components/dependency-graph/minimap-content.tsx
index af104753cd..4aa8ccf4ba 100644
--- a/frontend/src/components/dependency-graph/minimap-content.tsx
+++ b/frontend/src/components/dependency-graph/minimap-content.tsx
@@ -7,12 +7,8 @@ import {
cellGraphsAtom,
isVariableAffectedBySelectedCell,
} from "@/components/editor/chrome/wrapper/minimap-state";
-import {
- useCellActions,
- useCellData,
- useCellIds,
- useCellRuntime,
-} from "@/core/cells/cells";
+import { useCellData, useCellIds, useCellRuntime } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { cellFocusAtom, useCellFocusActions } from "@/core/cells/focus";
import type { CellId } from "@/core/cells/ids";
import { useVariables } from "@/core/variables/state";
diff --git a/frontend/src/components/dependency-graph/panels.tsx b/frontend/src/components/dependency-graph/panels.tsx
index 6a543953cb..f881a19fb7 100644
--- a/frontend/src/components/dependency-graph/panels.tsx
+++ b/frontend/src/components/dependency-graph/panels.tsx
@@ -14,7 +14,8 @@ import {
} from "lucide-react";
import React, { memo, useId } from "react";
import { type Edge, Panel } from "reactflow";
-import { getCellEditorView, useCellActions } from "@/core/cells/cells";
+import { getCellEditorView } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import type { CellId } from "@/core/cells/ids";
import { goToVariableDefinition } from "@/core/codemirror/go-to-definition/commands";
import type { Variable, Variables } from "@/core/variables/types";
diff --git a/frontend/src/components/editor/__tests__/Output.test.tsx b/frontend/src/components/editor/__tests__/Output.test.tsx
index 4fe4b2260b..897c25063a 100644
--- a/frontend/src/components/editor/__tests__/Output.test.tsx
+++ b/frontend/src/components/editor/__tests__/Output.test.tsx
@@ -1,10 +1,16 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createStore, Provider } from "jotai";
+import { mockDocumentModel } from "@/__mocks__/document";
import { cellId } from "@/__tests__/branded";
+import { DocumentProvider } from "@/core/notebook/document";
import { TooltipProvider } from "@/components/ui/tooltip";
import { OutputArea, OutputRenderer } from "../Output";
+const store = createStore();
+const { model } = mockDocumentModel(store, null);
+
describe("OutputRenderer renderFallback prop", () => {
it("should use renderFallback for unsupported mimetypes", () => {
const renderFallback = (mimetype: string) => (
@@ -70,31 +76,39 @@ describe("OutputRenderer renderFallback prop", () => {
describe("OutputArea null/undefined handling", () => {
it("should render null when output is null", () => {
const { container } = render(
- <TooltipProvider>
- <OutputArea
- output={null}
- cellId={cellId("test")}
- stale={false}
- loading={false}
- allowExpand={true}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <OutputArea
+ output={null}
+ cellId={cellId("test")}
+ stale={false}
+ loading={false}
+ allowExpand={true}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
expect(container.innerHTML).toBe("");
});
it("should render null when output is undefined", () => {
const { container } = render(
- <TooltipProvider>
- <OutputArea
- // @ts-expect-error -- testing runtime safety for undefined output
- output={undefined}
- cellId={cellId("test")}
- stale={false}
- loading={false}
- allowExpand={true}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <OutputArea
+ // @ts-expect-error -- testing runtime safety for undefined output
+ output={undefined}
+ cellId={cellId("test")}
+ stale={false}
+ loading={false}
+ allowExpand={true}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
expect(container.innerHTML).toBe("");
});
@@ -184,19 +198,23 @@ describe("OutputArea fullscreen exit control", () => {
const renderOutput = () =>
render(
- <TooltipProvider>
- <OutputArea
- output={{
- channel: "output",
- data: "Hello World",
- mimetype: "text/plain",
- }}
- cellId={cellId("test")}
- stale={false}
- loading={false}
- allowExpand={true}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <OutputArea
+ output={{
+ channel: "output",
+ data: "Hello World",
+ mimetype: "text/plain",
+ }}
+ cellId={cellId("test")}
+ stale={false}
+ loading={false}
+ allowExpand={true}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
const enterFullscreen = (container: HTMLElement) => {
diff --git a/frontend/src/components/editor/__tests__/data-attributes.test.tsx b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
index 1c0c26309f..74df61bbb1 100644
--- a/frontend/src/components/editor/__tests__/data-attributes.test.tsx
+++ b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
@@ -3,11 +3,13 @@ import { render } from "@testing-library/react";
import { createStore, Provider } from "jotai";
import { beforeAll, describe, expect, it } from "vitest";
import { SetupMocks } from "@/__mocks__/common";
+import { mockDocumentModel } from "@/__mocks__/document";
import { MockNotebook } from "@/__mocks__/notebook";
import { MockRequestClient } from "@/__mocks__/requests";
import { cellId } from "@/__tests__/branded";
import { TooltipProvider } from "@/components/ui/tooltip";
import { notebookAtom } from "@/core/cells/cells";
+import { DocumentProvider } from "@/core/notebook/document";
import { createCellRuntimeState } from "@/core/cells/types";
import type { UserConfig } from "@/core/config/config-schema";
import type { OutputMessage } from "@/core/kernel/messages";
@@ -18,9 +20,12 @@ import { OutputArea } from "../Output";
function createTestWrapper() {
const store = createStore();
+ const { model } = mockDocumentModel(store, null);
store.set(requestClientAtom, MockRequestClient.create());
const wrapper = ({ children }: { children: React.ReactNode }) => (
- <Provider store={store}>{children}</Provider>
+ <Provider store={store}>
+ <DocumentProvider model={model}>{children}</DocumentProvider>
+ </Provider>
);
return { wrapper, store };
}
@@ -150,17 +155,23 @@ describe("Output data attributes", () => {
timestamp: 0,
};
+ const store = createStore();
+ const { model } = mockDocumentModel(store, null);
const { container } = render(
- <TooltipProvider>
- <OutputArea
- output={output}
- cellId={cid}
- stale={false}
- loading={false}
- allowExpand={true}
- className="test-output"
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <OutputArea
+ output={output}
+ cellId={cid}
+ stale={false}
+ loading={false}
+ allowExpand={true}
+ className="test-output"
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
const outputElement = container.querySelector('[data-cell-role="output"]');
diff --git a/frontend/src/components/editor/__tests__/output-persistence.test.tsx b/frontend/src/components/editor/__tests__/output-persistence.test.tsx
index 9b379126d0..745d8d9ab0 100644
--- a/frontend/src/components/editor/__tests__/output-persistence.test.tsx
+++ b/frontend/src/components/editor/__tests__/output-persistence.test.tsx
@@ -3,11 +3,13 @@ import { render } from "@testing-library/react";
import { createStore, Provider } from "jotai";
import { beforeAll, describe, expect, it } from "vitest";
import { SetupMocks } from "@/__mocks__/common";
+import { mockDocumentModel } from "@/__mocks__/document";
import { MockNotebook } from "@/__mocks__/notebook";
import { MockRequestClient } from "@/__mocks__/requests";
import { cellId } from "@/__tests__/branded";
import { TooltipProvider } from "@/components/ui/tooltip";
import { notebookAtom } from "@/core/cells/cells";
+import { DocumentProvider } from "@/core/notebook/document";
import type { CellRuntimeState } from "@/core/cells/types";
import { createCellRuntimeState } from "@/core/cells/types";
import { defaultUserConfig } from "@/core/config/config-schema";
@@ -19,9 +21,12 @@ const cid = cellId("test");
function createTestWrapper() {
const store = createStore();
+ const { model } = mockDocumentModel(store, null);
store.set(requestClientAtom, MockRequestClient.create());
const wrapper = ({ children }: { children: React.ReactNode }) => (
- <Provider store={store}>{children}</Provider>
+ <Provider store={store}>
+ <DocumentProvider model={model}>{children}</DocumentProvider>
+ </Provider>
);
return { wrapper, store };
}
diff --git a/frontend/src/components/editor/actions/__tests__/name-cell-input.test.tsx b/frontend/src/components/editor/actions/__tests__/name-cell-input.test.tsx
new file mode 100644
index 0000000000..963d20251d
--- /dev/null
+++ b/frontend/src/components/editor/actions/__tests__/name-cell-input.test.tsx
@@ -0,0 +1,69 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+// @vitest-environment jsdom
+
+import { fireEvent, render, screen } from "@testing-library/react";
+import { atom, createStore, Provider } from "jotai";
+import { afterEach, describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import {
+ createDocumentModel,
+ DocumentProvider,
+} from "@/core/notebook/document";
+import {
+ cell,
+ document as documentOf,
+ withCells,
+} from "@/core/notebook/document/__tests__/fixtures";
+import { fakeBackend } from "@/core/notebook/replica/__tests__/fixtures";
+import { NameCellContentEditable } from "../name-cell-input";
+
+const controllers: AbortController[] = [];
+
+afterEach(() => {
+ for (const controller of controllers.splice(0)) {
+ controller.abort();
+ }
+});
+
+describe("NameCellContentEditable", () => {
+ it("renames the cell in the document when the name is committed", () => {
+ const store = createStore();
+ const source = atom(
+ withCells(documentOf(), {
+ c1: cell("c1", "x = 1", { name: "first" }),
+ }),
+ );
+ const model = createDocumentModel({
+ store,
+ documentAtom: source,
+ backendAtom: atom(fakeBackend()),
+ });
+ const controller = new AbortController();
+ controllers.push(controller);
+ model.start({ signal: controller.signal });
+
+ render(
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <NameCellContentEditable
+ cellId={cellId("c1")}
+ value="first"
+ className=""
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
+ );
+
+ const field = screen.getByText("first");
+ // jsdom does not lay text out, so it has no innerText of its own.
+ Object.defineProperty(field, "innerText", { value: " renamed " });
+ fireEvent.blur(field);
+
+ expect(store.get(model.documentAtom)?.cells.get("c1")?.name).toBe(
+ "renamed",
+ );
+ });
+});
diff --git a/frontend/src/components/editor/actions/name-cell-input.tsx b/frontend/src/components/editor/actions/name-cell-input.tsx
index cebbfac39f..cead1693bd 100644
--- a/frontend/src/components/editor/actions/name-cell-input.tsx
+++ b/frontend/src/components/editor/actions/name-cell-input.tsx
@@ -3,13 +3,14 @@
import React, { useRef, useState } from "react";
import { Input } from "@/components/ui/input";
import { Tooltip } from "@/components/ui/tooltip";
-import { getCellNames, useCellActions } from "@/core/cells/cells";
+import { getCellNames } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import {
getValidName,
isInternalCellName,
normalizeName,
} from "@/core/cells/names";
+import { useNotebookDocumentEdit } from "@/core/notebook/document";
import { useOnMount } from "@/hooks/useLifecycle";
import { cn } from "@/utils/cn";
import { Events } from "@/utils/events";
@@ -71,9 +72,9 @@ export const NameCellContentEditable: React.FC<{
value: string;
className: string;
}> = ({ value, cellId, className }) => {
- const { updateCellName } = useCellActions();
+ const edit = useNotebookDocumentEdit();
const inputProps = useCellNameInput(value, (newName) =>
- updateCellName({ cellId, name: newName }),
+ edit((tx) => tx.setName(cellId, newName)),
);
// If the name is the default, don't render the content editable
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsx
index d0d3bd4b7e..1937e36bba 100644
--- a/frontend/src/components/editor/actions/useCellActionButton.tsx
+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx
@@ -37,8 +37,10 @@ import { Label } from "@/components/ui/label";
import { toast } from "@/components/ui/use-toast";
import { aiCompletionCellAtom } from "@/core/ai/state";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
-import { hasOnlyOneCellAtom, useCellActions } from "@/core/cells/cells";
+import { hasOnlyOneCellAtom } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { type CellId, SETUP_CELL_ID } from "@/core/cells/ids";
+import { useNotebookDocumentEdit } from "@/core/notebook/document";
import type { CellData } from "@/core/cells/types";
import { formatEditorViews } from "@/core/codemirror/format";
import {
@@ -53,7 +55,6 @@ import {
autoInstantiateAtom,
} from "@/core/config/config";
import { kioskModeAtom } from "@/core/mode";
-import { useRequestClient } from "@/core/network/requests";
import type { CellConfig, RuntimeState } from "@/core/network/types";
import { canLinkToCell, createCellLink } from "@/utils/cell-urls";
import { copyToClipboard } from "@/utils/copy";
@@ -83,16 +84,15 @@ interface Props {
export function useCellActionButtons({ cell, closePopover }: Props) {
const {
- createNewCell: createCell,
- updateCellConfig,
- updateCellName,
moveCell,
sendToTop,
sendToBottom,
addColumnBreakpoint,
clearCellOutput,
markUntouched,
+ createCell,
} = useCellActions();
+ const edit = useNotebookDocumentEdit();
const splitCell = useSplitCellCallback();
const runCell = useRunCell(cell?.cellId);
const hasOnlyOneCell = useAtomValue(hasOnlyOneCellAtom);
@@ -104,7 +104,6 @@ export function useCellActionButtons({ cell, closePopover }: Props) {
const autoInstantiate = useAtomValue(autoInstantiateAtom);
const kioskMode = useAtomValue(kioskModeAtom);
const appWidth = useAtomValue(appWidthAtom);
- const { saveCellConfig } = useRequestClient();
if (!cell || kioskMode) {
return [];
@@ -120,16 +119,13 @@ export function useCellActionButtons({ cell, closePopover }: Props) {
status,
} = cell;
- const toggleDisabled = async () => {
- const newConfig = { disabled: !config.disabled };
- await saveCellConfig({ configs: { [cellId]: newConfig } });
- updateCellConfig({ cellId, config: newConfig });
+ const toggleDisabled = () => {
+ edit((tx) => tx.updateConfig(cellId, { disabled: !config.disabled }));
};
- const toggleHideCode = async () => {
+ const toggleHideCode = () => {
const newConfig: Partial<CellConfig> = { hide_code: !config.hide_code };
- await saveCellConfig({ configs: { [cellId]: newConfig } });
- updateCellConfig({ cellId, config: newConfig });
+ edit((tx) => tx.updateConfig(cellId, newConfig));
const editorView = getEditorView();
// If we're hiding the code, we should blur the editor
// otherwise, we should focus it
@@ -221,20 +217,18 @@ export function useCellActionButtons({ cell, closePopover }: Props) {
if (!editorView) {
return;
}
- maybeAddMarimoImport({ autoInstantiate, createNewCell: createCell });
+ maybeAddMarimoImport({ autoInstantiate, createCell });
switchLanguage(editorView, {
language: "markdown",
keepCodeAsIs: false,
});
// Code stays visible until the user blurs the cell
if (!config.hide_code && MARKDOWN_INITIAL_HIDE_CODE) {
- await saveCellConfig({
- configs: { [cellId]: { hide_code: MARKDOWN_INITIAL_HIDE_CODE } },
- });
- updateCellConfig({
- cellId,
- config: { hide_code: MARKDOWN_INITIAL_HIDE_CODE },
- });
+ edit((tx) =>
+ tx.updateConfig(cellId, {
+ hide_code: MARKDOWN_INITIAL_HIDE_CODE,
+ }),
+ );
markUntouched({ cellId });
}
},
@@ -266,7 +260,7 @@ export function useCellActionButtons({ cell, closePopover }: Props) {
}
maybeAddMarimoImport({
autoInstantiate,
- createNewCell: createCell,
+ createCell,
});
switchLanguage(editorView, {
language: "sql",
@@ -288,7 +282,7 @@ export function useCellActionButtons({ cell, closePopover }: Props) {
),
label: "Create cell above",
hotkey: "cell.createAbove",
- handle: () => createCell({ cellId, before: true }),
+ handle: () => createCell({ before: cellId }),
hidden: isSetupCell,
redundant: true,
},
@@ -301,7 +295,7 @@ export function useCellActionButtons({ cell, closePopover }: Props) {
),
label: "Create cell below",
hotkey: "cell.createBelow",
- handle: () => createCell({ cellId, before: false }),
+ handle: () => createCell({ after: cellId }),
redundant: true,
},
{
@@ -406,7 +400,7 @@ export function useCellActionButtons({ cell, closePopover }: Props) {
}
}}
onChange={(newName) =>
- updateCellName({ cellId, name: newName })
+ edit((tx) => tx.setName(cellId, newName))
}
/>
</div>
@@ -417,7 +411,7 @@ export function useCellActionButtons({ cell, closePopover }: Props) {
<NameCellInput
placeholder={"cell name"}
value={name}
- onChange={(newName) => updateCellName({ cellId, name: newName })}
+ onChange={(newName) => edit((tx) => tx.setName(cellId, newName))}
onEnterKey={() => closePopover?.()}
/>
),
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index 07187375fd..a84d599a22 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -62,8 +62,9 @@ import {
getNotebook,
hasDisabledCellsAtom,
undoLabelAtom,
- useCellActions,
} from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
+import { useNotebookDocumentEdit } from "@/core/notebook/document";
import { disabledCellIds } from "@/core/cells/utils";
import { capabilitiesAtom } from "@/core/config/capabilities";
import { aiEnabledAtom, useResolvedMarimoConfig } from "@/core/config/config";
@@ -77,7 +78,6 @@ import { createShareableLink } from "@/core/wasm/share";
import { isWasm } from "@/core/wasm/utils";
import { useDetectedDataSources } from "@/hooks/useDataSourceDiscovery";
import { copyToClipboard } from "@/utils/copy";
-import { Objects } from "@/utils/objects";
import { Strings } from "@/utils/strings";
import { newNotebookURL } from "@/utils/urls";
import { useRunAllCells } from "../cell/useRunCells";
@@ -127,12 +127,11 @@ export function useNotebookActions({
const aiEnabled = useAtomValue(aiEnabledAtom);
const {
- updateCellConfig,
undoDeleteCell,
clearAllCellOutputs,
- addSetupCellIfDoesntExist,
collapseAllCells,
expandAllCells,
+ addSetupCell,
} = useCellActions();
const restartKernel = useRestartKernel();
const runAllCells = useRunAllCells();
@@ -142,7 +141,8 @@ export function useNotebookActions({
const { handleClick: openSettings } = useOpenSettingsToTab();
const setKeyboardShortcutsOpen = useSetAtom(keyboardShortcutsAtom);
const setExportOptions = useSetAtom(exportOptionsAtom);
- const { readCode, saveCellConfig } = useRequestClient();
+ const { readCode } = useRequestClient();
+ const edit = useNotebookDocumentEdit();
const detectedDatabaseSources = useDetectedDataSources("database");
const detectedStorageSources = useDetectedDataSources("storage");
const addDetectedDataSource = useAddDetectedDataSource();
@@ -449,18 +449,13 @@ export function useNotebookActions({
icon: <ZapIcon size={14} strokeWidth={1.5} />,
label: "Enable all cells",
hidden: !hasDisabledCells || kioskMode,
- handle: async () => {
- const notebook = getNotebook();
- const ids = disabledCellIds(notebook);
- const newConfigs = Objects.fromEntries(
- ids.map((cellId) => [cellId, { disabled: false }]),
- );
- // send to BE
- await saveCellConfig({ configs: newConfigs });
- // update on FE
- for (const cellId of ids) {
- updateCellConfig({ cellId, config: { disabled: false } });
- }
+ handle: () => {
+ const ids = disabledCellIds(getNotebook());
+ edit((tx) => {
+ for (const cellId of ids) {
+ tx.updateConfig(cellId, { disabled: false });
+ }
+ });
},
},
@@ -469,7 +464,7 @@ export function useNotebookActions({
icon: <DiamondPlusIcon size={14} strokeWidth={1.5} />,
label: "Add setup cell",
handle: () => {
- addSetupCellIfDoesntExist({});
+ addSetupCell();
},
},
{
diff --git a/frontend/src/components/editor/actions/useSetCodeVisibility.ts b/frontend/src/components/editor/actions/useSetCodeVisibility.ts
index a8d852603d..3101e40d5e 100644
--- a/frontend/src/components/editor/actions/useSetCodeVisibility.ts
+++ b/frontend/src/components/editor/actions/useSetCodeVisibility.ts
@@ -1,10 +1,10 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { useCallback } from "react";
-import { getNotebook, useCellActions } from "@/core/cells/cells";
+import { getNotebook } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { MarkdownLanguageAdapter } from "@/core/codemirror/language/languages/markdown";
-import { useRequestClient } from "@/core/network/requests";
+import { useNotebookDocumentEdit } from "@/core/notebook/document";
import type { CellConfig } from "@/core/network/types";
import { Objects } from "@/utils/objects";
@@ -21,11 +21,10 @@ const cellCodeKind = (code: string): CellCodeKind =>
* cell of the given kind.
*/
export const useSetCodeVisibility = () => {
- const { updateCellConfig } = useCellActions();
- const { saveCellConfig } = useRequestClient();
+ const edit = useNotebookDocumentEdit();
return useCallback(
- async (hidden: boolean, kind: CellCodeKind) => {
+ (hidden: boolean, kind: CellCodeKind) => {
const notebook = getNotebook();
const newConfigs: Record<CellId, Partial<CellConfig>> = {};
@@ -46,12 +45,12 @@ export const useSetCodeVisibility = () => {
return;
}
- await saveCellConfig({ configs: newConfigs });
-
- for (const [cellId, config] of entries) {
- updateCellConfig({ cellId, config });
- }
+ edit((tx) => {
+ for (const [cellId, config] of entries) {
+ tx.updateConfig(cellId, config);
+ }
+ });
},
- [updateCellConfig, saveCellConfig],
+ [edit],
);
};
diff --git a/frontend/src/components/editor/actions/useSetOutputsExpanded.ts b/frontend/src/components/editor/actions/useSetOutputsExpanded.ts
index 9e6a1e1e39..5d89e7e432 100644
--- a/frontend/src/components/editor/actions/useSetOutputsExpanded.ts
+++ b/frontend/src/components/editor/actions/useSetOutputsExpanded.ts
@@ -1,14 +1,10 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { useCallback } from "react";
-import {
- getNotebook,
- type NotebookState,
- useCellActions,
-} from "@/core/cells/cells";
+import { getNotebook, type NotebookState } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { isOutputEmpty } from "@/core/cells/outputs";
-import { useRequestClient } from "@/core/network/requests";
+import { useNotebookDocumentEdit } from "@/core/notebook/document";
import type { CellConfig } from "@/core/network/types";
import { Objects } from "@/utils/objects";
@@ -44,24 +40,23 @@ export function outputExpansionConfigs(
* every output to a fixed height, by setting each cell's `expand_output` config.
*/
export const useSetOutputsExpanded = () => {
- const { updateCellConfig } = useCellActions();
- const { saveCellConfig } = useRequestClient();
+ const edit = useNotebookDocumentEdit();
return useCallback(
- async (expanded: boolean) => {
- const newConfigs = outputExpansionConfigs(getNotebook(), expanded);
-
- const entries = Objects.entries(newConfigs);
+ (expanded: boolean) => {
+ const entries = Objects.entries(
+ outputExpansionConfigs(getNotebook(), expanded),
+ );
if (entries.length === 0) {
return;
}
- await saveCellConfig({ configs: newConfigs });
-
- for (const [cellId, config] of entries) {
- updateCellConfig({ cellId, config });
- }
+ edit((tx) => {
+ for (const [cellId, config] of entries) {
+ tx.updateConfig(cellId, config);
+ }
+ });
},
- [updateCellConfig, saveCellConfig],
+ [edit],
);
};
diff --git a/frontend/src/components/editor/cell/CreateCellButton.tsx b/frontend/src/components/editor/cell/CreateCellButton.tsx
index de5adb00eb..a5fae5f6fc 100644
--- a/frontend/src/components/editor/cell/CreateCellButton.tsx
+++ b/frontend/src/components/editor/cell/CreateCellButton.tsx
@@ -10,7 +10,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { LanguageAdapters } from "@/core/codemirror/language/LanguageAdapters";
import { MARKDOWN_INITIAL_HIDE_CODE } from "@/core/codemirror/language/languages/markdown";
import {
@@ -33,7 +33,7 @@ export const CreateCellButton = ({
onClick: ((opts: { code: string; hideCode?: boolean }) => void) | undefined;
oneClickShortcut: "shift" | "mod";
}) => {
- const { createNewCell, addSetupCellIfDoesntExist } = useCellActions();
+ const { createCell, addSetupCell } = useCellActions();
const shortcut = `${oneClickShortcut}-Click`;
const [open, setOpen] = useState(false);
// Time the dropdown last opened, to ignore the click that opened it
@@ -62,7 +62,7 @@ export const CreateCellButton = ({
// enabled; the user experience is confusing otherwise (how does the user
// know they need to run import marimo as mo. first?).
const addMarkdownCell = () => {
- maybeAddMarimoImport({ autoInstantiate: true, createNewCell });
+ maybeAddMarimoImport({ autoInstantiate: true, createCell });
onClick?.({
code: LanguageAdapters.markdown.defaultCode,
hideCode: MARKDOWN_INITIAL_HIDE_CODE,
@@ -70,14 +70,10 @@ export const CreateCellButton = ({
};
const addSQLCell = () => {
- maybeAddMarimoImport({ autoInstantiate: true, createNewCell });
+ maybeAddMarimoImport({ autoInstantiate: true, createCell });
onClick?.({ code: LanguageAdapters.sql.defaultCode });
};
- const addSetupCell = () => {
- addSetupCellIfDoesntExist({});
- };
-
const renderIcon = (icon: React.ReactNode) => {
return <div className="mr-3 text-muted-foreground">{icon}</div>;
};
@@ -170,7 +166,7 @@ export const CreateCellButton = ({
{renderIcon(<DatabaseIcon size={13} strokeWidth={1.5} />)}
SQL cell
</DropdownMenuItem>
- <DropdownMenuItem onClick={addSetupCell}>
+ <DropdownMenuItem onClick={() => addSetupCell()}>
{renderIcon(<DiamondPlusIcon size={13} strokeWidth={1.5} />)}
Setup cell
</DropdownMenuItem>
diff --git a/frontend/src/components/editor/cell/__tests__/StagedAICell.test.tsx b/frontend/src/components/editor/cell/__tests__/StagedAICell.test.tsx
index debffa24fc..f6d83d8354 100644
--- a/frontend/src/components/editor/cell/__tests__/StagedAICell.test.tsx
+++ b/frontend/src/components/editor/cell/__tests__/StagedAICell.test.tsx
@@ -14,8 +14,10 @@ vi.mock("@/components/editor/cell/useDeleteCell", () => ({
vi.mock("@/core/cells/cells", () => ({
getCellEditorView: vi.fn(),
+}));
+vi.mock("@/core/cells/actions", () => ({
useCellActions: () => ({
- createNewCell: vi.fn(),
+ createCell: vi.fn(),
updateCellCode: vi.fn(),
}),
}));
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 03ad3c8646..461960d200 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -10,7 +10,9 @@ import { Button } from "@/components/ui/button";
import { DelayMount } from "@/components/utils/delay-mount";
import { aiCompletionCellAtom } from "@/core/ai/state";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
-import { getNotebook, useCellActions } from "@/core/cells/cells";
+import { getNotebook } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
+import { useNotebookDocumentEdit } from "@/core/notebook/document";
import { SETUP_CELL_ID } from "@/core/cells/ids";
import { usePendingDeleteService } from "@/core/cells/pending-delete-service";
import type { CellData, CellRuntimeState } from "@/core/cells/types";
@@ -36,7 +38,6 @@ import { autoInstantiateAtom, isAiFeatureEnabled } from "@/core/config/config";
import type { UserConfig } from "@/core/config/config-schema";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
import { connectionAtom } from "@/core/network/connection";
-import { useRequestClient } from "@/core/network/requests";
import { canUseRtc, isRtcEnabled } from "@/core/rtc/state";
import { useSaveNotebook } from "@/core/saving/save-component";
import { isAppConnecting } from "@/core/session/connection-utils";
@@ -135,7 +136,7 @@ const CellEditorInternal = ({
const deleteCell = useDeleteCellCallback();
const { saveOrNameNotebook } = useSaveNotebook();
const pendingDeleteService = usePendingDeleteService();
- const { saveCellConfig } = useRequestClient();
+ const edit = useNotebookDocumentEdit();
const loading = status === "running" || status === "queued";
const cellActions = useCellActions();
@@ -175,9 +176,7 @@ const CellEditorInternal = ({
const toggleHideCode = useEvent(() => {
// Use cellConfig.hide_code instead of hidden, since it may be temporarily shown
const nextHidden = !cellConfig.hide_code;
- // Fire-and-forget save
- void saveCellConfig({ configs: { [cellId]: { hide_code: nextHidden } } });
- cellActions.updateCellConfig({ cellId, config: { hide_code: nextHidden } });
+ edit((tx) => tx.updateConfig(cellId, { hide_code: nextHidden }));
return nextHidden;
});
@@ -186,17 +185,13 @@ const CellEditorInternal = ({
const afterToggleMarkdown = useEvent(() => {
maybeAddMarimoImport({
autoInstantiate,
- createNewCell: cellActions.createNewCell,
+ createCell: cellActions.createCell,
});
// Code stays visible until the user blurs the cell
if (!cellConfig.hide_code && MARKDOWN_INITIAL_HIDE_CODE) {
- void saveCellConfig({
- configs: { [cellId]: { hide_code: MARKDOWN_INITIAL_HIDE_CODE } },
- });
- cellActions.updateCellConfig({
- cellId,
- config: { hide_code: MARKDOWN_INITIAL_HIDE_CODE },
- });
+ edit((tx) =>
+ tx.updateConfig(cellId, { hide_code: MARKDOWN_INITIAL_HIDE_CODE }),
+ );
cellActions.markUntouched({ cellId });
}
});
@@ -204,7 +199,7 @@ const CellEditorInternal = ({
const afterToggleSQL = useEvent(() => {
maybeAddMarimoImport({
autoInstantiate,
- createNewCell: cellActions.createNewCell,
+ createCell: cellActions.createCell,
});
});
@@ -224,11 +219,9 @@ const CellEditorInternal = ({
saveNotebook: saveOrNameNotebook,
createManyBelow: (cells) => {
for (const code of cells.toReversed()) {
- cellActions.createNewCell({
+ cellActions.createCell({
+ after: cellId,
code,
- before: false,
- cellId: cellId,
- // If the code already exists, skip creation
skipIfCodeExists: true,
});
}
@@ -237,7 +230,7 @@ const CellEditorInternal = ({
const notebook = getNotebook();
// No setup cell yet: create one with this code at the top.
if (!notebook.cellIds.setupCellExists()) {
- cellActions.addSetupCellIfDoesntExist({ code });
+ cellActions.addSetupCell({ code });
return;
}
// Setup cell exists: append the pasted code to it. Prefer updating
diff --git a/frontend/src/components/editor/cell/useAddCell.ts b/frontend/src/components/editor/cell/useAddCell.ts
index f87e051ce1..e4aebc5feb 100644
--- a/frontend/src/components/editor/cell/useAddCell.ts
+++ b/frontend/src/components/editor/cell/useAddCell.ts
@@ -2,28 +2,24 @@
import { useAtomValue } from "jotai";
import { maybeAddAltairImport } from "@/core/cells/add-missing-import";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { useLastFocusedCellId } from "@/core/cells/focus";
import { autoInstantiateAtom } from "@/core/config/config";
export function useAddCodeToNewCell(): (code: string) => void {
const autoInstantiate = useAtomValue(autoInstantiateAtom);
const lastFocusedCellId = useLastFocusedCellId();
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
return (code: string) => {
if (code.includes("alt")) {
maybeAddAltairImport({
autoInstantiate,
- createNewCell,
+ createCell,
fromCellId: lastFocusedCellId,
});
}
- createNewCell({
- code: code,
- before: false,
- cellId: lastFocusedCellId ?? "__end__",
- });
+ createCell({ after: lastFocusedCellId, code });
};
}
diff --git a/frontend/src/components/editor/cell/useDeleteCell.tsx b/frontend/src/components/editor/cell/useDeleteCell.tsx
index a90431b155..be840452ee 100644
--- a/frontend/src/components/editor/cell/useDeleteCell.tsx
+++ b/frontend/src/components/editor/cell/useDeleteCell.tsx
@@ -3,35 +3,22 @@
import useEvent from "react-use-event-hook";
import { UndoButton } from "@/components/buttons/undo-button";
import { toast } from "@/components/ui/use-toast";
-import {
- hasOnlyOneCellAtom,
- notebookAtom,
- useCellActions,
-} from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
+import { notebookAtom } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
-import { useRequestClient } from "@/core/network/requests";
import { store } from "@/core/state/jotai";
export function useDeleteCellCallback() {
- const { deleteCell, undoDeleteCell } = useCellActions();
- const { sendDeleteCell } = useRequestClient();
+ const { deleteCells, undoDeleteCell } = useCellActions();
return useEvent((opts: { cellId: CellId }) => {
- // Can't delete the last cell
- if (store.get(hasOnlyOneCellAtom)) {
- return;
- }
-
const { cellId } = opts;
const notebook = store.get(notebookAtom);
const isEmptyCell = (notebook.cellData[cellId]?.code ?? "").trim() === "";
- // Optimistic update
- deleteCell({ cellId });
- sendDeleteCell({ cellId: cellId }).catch(() => {
- // Fall back on failure
- undoDeleteCell();
- });
+ if (!deleteCells({ cellIds: [cellId] })) {
+ return;
+ }
if (!isEmptyCell) {
const { dismiss } = toast({
@@ -53,33 +40,20 @@ export function useDeleteCellCallback() {
}
export function useDeleteManyCellsCallback() {
- const { deleteCell, undoDeleteCell } = useCellActions();
- const { sendDeleteCell } = useRequestClient();
+ const { deleteCells, undoDeleteCell } = useCellActions();
- return useEvent(async (opts: { cellIds: CellId[] }) => {
- // Can't delete the last cell
- if (store.get(hasOnlyOneCellAtom)) {
+ return useEvent((opts: { cellIds: CellId[] }) => {
+ if (!deleteCells({ cellIds: opts.cellIds })) {
return;
}
- const { cellIds } = opts;
- for (const cellId of cellIds) {
- await sendDeleteCell({ cellId }).then(() => {
- deleteCell({ cellId });
- });
- }
-
const { dismiss } = toast({
title: "Cells deleted",
action: (
<UndoButton
data-testid="undo-delete-button"
onClick={() => {
- for (const _cellId of cellIds) {
- // This function does not take a cellId,
- // so we just undo the number of cells that were deleted
- undoDeleteCell();
- }
+ undoDeleteCell();
dismiss();
}}
/>
diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.ts
index 67ca79bce1..3e75095d16 100644
--- a/frontend/src/components/editor/cell/useRunCells.ts
+++ b/frontend/src/components/editor/cell/useRunCells.ts
@@ -3,11 +3,8 @@
import { closeCompletion } from "@codemirror/autocomplete";
import { atom, useSetAtom } from "jotai";
import useEvent from "react-use-event-hook";
-import {
- getNotebook,
- type NotebookState,
- useCellActions,
-} from "@/core/cells/cells";
+import { getNotebook, type NotebookState } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import type { CellId } from "@/core/cells/ids";
import { enabledCellIds, staleCellIds } from "@/core/cells/utils";
import { getCurrentLanguageAdapter } from "@/core/codemirror/language/commands";
diff --git a/frontend/src/components/editor/cell/useSplitCell.tsx b/frontend/src/components/editor/cell/useSplitCell.tsx
index e377755687..e6bf5c0b79 100644
--- a/frontend/src/components/editor/cell/useSplitCell.tsx
+++ b/frontend/src/components/editor/cell/useSplitCell.tsx
@@ -3,7 +3,8 @@
import useEvent from "react-use-event-hook";
import { UndoButton } from "@/components/buttons/undo-button";
import { toast } from "@/components/ui/use-toast";
-import { getCellEditorView, useCellActions } from "@/core/cells/cells";
+import { getCellEditorView } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import type { CellId } from "@/core/cells/ids";
import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";
diff --git a/frontend/src/components/editor/chrome/panels/logs-panel.tsx b/frontend/src/components/editor/chrome/panels/logs-panel.tsx
index 33aa87f16f..04a47e498c 100644
--- a/frontend/src/components/editor/chrome/panels/logs-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/logs-panel.tsx
@@ -3,7 +3,8 @@
import { FileTextIcon } from "lucide-react";
import React from "react";
import { ClearButton } from "@/components/buttons/clear-button";
-import { useCellActions, useCellLogs } from "@/core/cells/cells";
+import { useCellLogs } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import {
type CellLog,
formatLogTimestamp,
diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
index 4fbcd371e3..26655b3e02 100644
--- a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
@@ -22,7 +22,7 @@ import { Suspense } from "react";
import { Spinner } from "@/components/icons/spinner";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { useLastFocusedCellId } from "@/core/cells/focus";
import { useRequestClient } from "@/core/network/requests";
import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";
@@ -125,18 +125,16 @@ const SnippetViewer: React.FC<{ snippet: Snippet; onClose: () => void }> = ({
onClose,
}) => {
const { theme } = useTheme();
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
const lastFocusedCellId = useLastFocusedCellId();
const handleInsertSnippet = () => {
// Add below last focused cell in reverse order
for (const section of snippet.sections.toReversed()) {
if (section.code) {
- createNewCell({
+ createCell({
+ after: lastFocusedCellId,
code: section.code,
- before: false,
- cellId: lastFocusedCellId ?? "__end__",
- // If the code already exists, skip creation
skipIfCodeExists: true,
});
}
@@ -144,11 +142,7 @@ const SnippetViewer: React.FC<{ snippet: Snippet; onClose: () => void }> = ({
};
const handleInsertCode = (code: string) => {
- createNewCell({
- code,
- before: false,
- cellId: lastFocusedCellId ?? "__end__",
- });
+ createCell({ after: lastFocusedCellId, code });
};
return (
diff --git a/frontend/src/components/editor/chrome/wrapper/__tests__/pending-ai-cells.test.tsx b/frontend/src/components/editor/chrome/wrapper/__tests__/pending-ai-cells.test.tsx
index ca7f46a822..ad228d8236 100644
--- a/frontend/src/components/editor/chrome/wrapper/__tests__/pending-ai-cells.test.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/__tests__/pending-ai-cells.test.tsx
@@ -15,8 +15,10 @@ vi.mock("@/components/editor/cell/useDeleteCell", () => ({
vi.mock("@/core/cells/cells", () => ({
getCellEditorView: vi.fn(),
+}));
+vi.mock("@/core/cells/actions", () => ({
useCellActions: () => ({
- createNewCell: vi.fn(),
+ createCell: vi.fn(),
updateCellCode: vi.fn(),
}),
}));
diff --git a/frontend/src/components/editor/columns/sortable-column.tsx b/frontend/src/components/editor/columns/sortable-column.tsx
index 2969f7034c..9e4316ccb2 100644
--- a/frontend/src/components/editor/columns/sortable-column.tsx
+++ b/frontend/src/components/editor/columns/sortable-column.tsx
@@ -19,7 +19,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip } from "@/components/ui/tooltip";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { cn } from "@/utils/cn";
import type { CellColumnId } from "@/utils/id-tree";
import { mergeRefs } from "../../../utils/mergeRefs";
diff --git a/frontend/src/components/editor/connections/components.tsx b/frontend/src/components/editor/connections/components.tsx
index fee24f7fb0..90f3993568 100644
--- a/frontend/src/components/editor/connections/components.tsx
+++ b/frontend/src/components/editor/connections/components.tsx
@@ -18,7 +18,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { useLastFocusedCellId } from "@/core/cells/focus";
import { autoInstantiateAtom } from "@/core/config/config";
import type { DetectedDataSource } from "@/core/datasets/data-source-discovery";
@@ -112,7 +112,7 @@ export const ConnectionFormFooter = <L extends string>({
* Returns a callback that inserts code into a new cell after the last focused cell.
*/
export function useInsertCode() {
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
const lastFocusedCellId = useLastFocusedCellId();
const autoInstantiate = useAtomValue(autoInstantiateAtom);
@@ -121,17 +121,12 @@ export function useInsertCode() {
if (/\bmo\./.test(code)) {
maybeAddMarimoImport({
autoInstantiate,
- createNewCell,
+ createCell,
fromCellId: lastFocusedCellId,
});
}
- createNewCell({
- code,
- before: false,
- cellId: lastFocusedCellId ?? "__end__",
- skipIfCodeExists: true,
- });
+ createCell({ after: lastFocusedCellId, code, skipIfCodeExists: true });
};
}
diff --git a/frontend/src/components/editor/controls/Controls.tsx b/frontend/src/components/editor/controls/Controls.tsx
index dc0441d374..1e0a2b441a 100644
--- a/frontend/src/components/editor/controls/Controls.tsx
+++ b/frontend/src/components/editor/controls/Controls.tsx
@@ -28,8 +28,8 @@ import {
canUndoDeletesAtom,
needsRunAtom,
undoLabelAtom,
- useCellActions,
} from "../../../core/cells/cells";
+import { useCellActions } from "../../../core/cells/actions";
import { ConfigButton } from "../../app-config/app-config-button";
import { renderShortcut } from "../../shortcuts/renderShortcut";
import { Tooltip } from "../../ui/tooltip";
diff --git a/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx b/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx
index b9d3f11630..0b6afe8e2e 100644
--- a/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx
+++ b/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx
@@ -11,6 +11,7 @@ import { Provider } from "jotai";
import type React from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { requestId } from "@/__tests__/branded";
+import { mockDocumentModel } from "@/__mocks__/document";
import { MockRequestClient } from "@/__mocks__/requests";
import { ModalProvider } from "@/components/modal/ImperativeModal";
import { TooltipProvider } from "@/components/ui/tooltip";
@@ -19,6 +20,7 @@ import {
invalidateDataSourceDiscovery,
} from "@/core/datasets/data-source-discovery";
import { DiscoverDataSources } from "@/core/datasets/request-registry";
+import { DocumentProvider } from "@/core/notebook/document";
import { layoutStateAtom } from "@/core/layout/state";
import { kioskModeAtom, viewStateAtom } from "@/core/mode";
import { connectionAtom } from "@/core/network/connection";
@@ -73,12 +75,16 @@ global.HTMLElement.prototype.scrollIntoView = () => {
// jsdom does not implement scrollIntoView; cmdk calls it on selection.
};
+const { model } = mockDocumentModel(store, null);
+
function wrapper({ children }: { children: React.ReactNode }) {
return (
<Provider store={store}>
- <TooltipProvider>
- <ModalProvider>{children}</ModalProvider>
- </TooltipProvider>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ModalProvider>{children}</ModalProvider>
+ </TooltipProvider>
+ </DocumentProvider>
</Provider>
);
}
diff --git a/frontend/src/components/editor/documentation.css b/frontend/src/components/editor/documentation.css
index ca02c3d260..00c78349a2 100644
--- a/frontend/src/components/editor/documentation.css
+++ b/frontend/src/components/editor/documentation.css
@@ -157,18 +157,41 @@
/* Syntax highlighting for LSP hover code blocks (lezer classHighlighter tok-* classes) */
.docs-documentation,
.cm-tooltip .documentation {
- .tok-keyword { color: light-dark(#708, #c678dd); font-weight: 500; }
+ .tok-keyword {
+ color: light-dark(#708, #c678dd);
+ font-weight: 500;
+ }
.tok-string,
- .tok-string2 { color: light-dark(#a11, #98c379); }
- .tok-number { color: light-dark(#164, #d19a66); }
+ .tok-string2 {
+ color: light-dark(#a11, #98c379);
+ }
+ .tok-number {
+ color: light-dark(#164, #d19a66);
+ }
.tok-bool,
- .tok-atom { color: light-dark(#219, #d19a66); }
- .tok-comment { color: var(--cm-comment); }
- .tok-className { color: light-dark(#00f, #61afef); }
+ .tok-atom {
+ color: light-dark(#219, #d19a66);
+ }
+ .tok-comment {
+ color: var(--cm-comment);
+ }
+ .tok-className {
+ color: light-dark(#00f, #61afef);
+ }
.tok-typeName,
- .tok-namespace { color: light-dark(#085, #56b6c2); }
- .tok-operator { color: light-dark(#a2f, #56b6c2); }
- .tok-propertyName { color: light-dark(#05a, #e5c07b); }
- .tok-variableName { color: light-dark(#000, #abb2bf); }
- .tok-punctuation { color: light-dark(#000, #abb2bf); }
+ .tok-namespace {
+ color: light-dark(#085, #56b6c2);
+ }
+ .tok-operator {
+ color: light-dark(#a2f, #56b6c2);
+ }
+ .tok-propertyName {
+ color: light-dark(#05a, #e5c07b);
+ }
+ .tok-variableName {
+ color: light-dark(#000, #abb2bf);
+ }
+ .tok-punctuation {
+ color: light-dark(#000, #abb2bf);
+ }
}
diff --git a/frontend/src/components/editor/errors/auto-fix.tsx b/frontend/src/components/editor/errors/auto-fix.tsx
index 435a87ff6f..0feee3498f 100644
--- a/frontend/src/components/editor/errors/auto-fix.tsx
+++ b/frontend/src/components/editor/errors/auto-fix.tsx
@@ -18,7 +18,8 @@ import {
} from "@/components/ui/dropdown-menu";
import { Tooltip } from "@/components/ui/tooltip";
import { aiCompletionCellAtom } from "@/core/ai/state";
-import { notebookAtom, useCellActions } from "@/core/cells/cells";
+import { notebookAtom } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import type { CellId } from "@/core/cells/ids";
import { aiFeaturesEnabledAtom } from "@/core/config/config";
import { getAutoFixes } from "@/core/errors/errors";
@@ -51,7 +52,7 @@ export const AutoFixButton = ({
className?: string;
}) => {
const store = useStore();
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
const aiFeaturesEnabled = useAtomValue(aiFeaturesEnabledAtom);
const autoFixes = errors.flatMap((error) =>
getAutoFixes(error, { aiEnabled: aiFeaturesEnabled }),
@@ -72,12 +73,7 @@ export const AutoFixButton = ({
store.get(notebookAtom).cellHandles[cellId].current?.editorView;
firstFix.onFix({
addCodeBelow: (code: string) => {
- createNewCell({
- cellId: cellId,
- autoFocus: false,
- before: false,
- code: code,
- });
+ createCell({ after: cellId, code, focus: false });
},
editor: editorView,
cellId: cellId,
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index 1858a146e5..3116cfe60a 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -59,7 +59,7 @@ import {
import { Tooltip } from "@/components/ui/tooltip";
import { SearchInput } from "@/components/ui/input";
import { toast } from "@/components/ui/use-toast";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { useLastFocusedCellId } from "@/core/cells/focus";
import { disableFileDownloadsAtom } from "@/core/config/config";
import { useRequestClient } from "@/core/network/requests";
@@ -697,15 +697,11 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileTreeNode>) => {
const Icon = FILE_ICON[fileType];
const { openPrompt } = useImperativeModal();
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
const lastFocusedCellId = useLastFocusedCellId();
const handleInsertCode = (code: string) => {
- createNewCell({
- code,
- before: false,
- cellId: lastFocusedCellId ?? "__end__",
- });
+ createCell({ after: lastFocusedCellId, code });
};
const fileExplorer = use(RequestingTreeContext);
diff --git a/frontend/src/components/editor/links/__tests__/cell-link.test.tsx b/frontend/src/components/editor/links/__tests__/cell-link.test.tsx
index ac605d7de7..90ab9f8e0f 100644
--- a/frontend/src/components/editor/links/__tests__/cell-link.test.tsx
+++ b/frontend/src/components/editor/links/__tests__/cell-link.test.tsx
@@ -11,8 +11,10 @@ import { CellLink, CellLinkTraceback } from "../cell-link";
const showCellIfHidden = vi.hoisted(() => vi.fn());
const targetId = cellId("target");
-vi.mock("@/core/cells/cells", () => ({
+vi.mock("@/core/cells/actions", () => ({
useCellActions: () => ({ showCellIfHidden }),
+}));
+vi.mock("@/core/cells/cells", () => ({
useCellIds: () => ({ inOrderIds: [targetId] }),
useCellNames: () => ({ [targetId]: "Target" }),
}));
diff --git a/frontend/src/components/editor/links/cell-link.tsx b/frontend/src/components/editor/links/cell-link.tsx
index 34f5a71281..44f528400f 100644
--- a/frontend/src/components/editor/links/cell-link.tsx
+++ b/frontend/src/components/editor/links/cell-link.tsx
@@ -1,7 +1,8 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { JSX } from "react"; /* Copyright 2026 Marimo. All rights reserved. */
-import { useCellActions, useCellIds, useCellNames } from "@/core/cells/cells";
+import { useCellIds, useCellNames } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { type CellId, HTMLCellId, SCRATCH_CELL_ID } from "@/core/cells/ids";
import { displayCellName } from "@/core/cells/names";
import { goToCellLine } from "@/core/codemirror/go-to-definition/utils";
diff --git a/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts b/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
index 5f9ff34833..cb47565574 100644
--- a/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
@@ -5,15 +5,18 @@ import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { asMock, MockModules, Mocks, SetupMocks } from "@/__mocks__/common";
import { cellId } from "@/__tests__/branded";
-import type { CellActions, NotebookState } from "@/core/cells/cells";
+import type { CellActions } from "@/core/cells/actions";
+import type { NotebookState } from "@/core/cells/cells";
import { useCellClipboard } from "../clipboard";
// Mock dependencies
vi.mock("@/components/ui/use-toast", () => MockModules.toast());
+vi.mock("@/core/cells/actions", () => ({
+ useCellActions: vi.fn(),
+}));
vi.mock("@/core/cells/cells", () => ({
getNotebook: vi.fn(),
- useCellActions: vi.fn(),
}));
vi.mock("@/utils/Logger", () => ({
@@ -33,14 +36,15 @@ vi.mock("@/core/cells/pending-cut-service", () => ({
import { MockNotebook } from "@/__mocks__/notebook";
import { toast } from "@/components/ui/use-toast";
-import { getNotebook, useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
+import { getNotebook } from "@/core/cells/cells";
import { Logger } from "@/utils/Logger";
describe("useCellClipboard", () => {
const [mockCellId1, mockCellId2] = MockNotebook.cellIds();
const mockCellCode1 = "print('hello world')";
const mockCellCode2 = "x = 42";
- const mockCreateNewCell = vi.fn();
+ const mockCreateCell = vi.fn();
const mockClipboard = Mocks.clipboard();
@@ -70,7 +74,7 @@ describe("useCellClipboard", () => {
} as NotebookState);
asMock(useCellActions).mockReturnValue({
- createNewCell: mockCreateNewCell,
+ createCell: mockCreateCell,
} as unknown as CellActions);
});
@@ -330,11 +334,40 @@ describe("useCellClipboard", () => {
await result.current.pasteAtCell(mockCellId1);
});
- expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: mockCellId1,
- before: false,
+ expect(mockCreateCell).toHaveBeenCalledWith({
+ after: mockCellId1,
+ code: "x = 42",
+ config: {},
+ });
+ });
+
+ it("drops the copied column so the cell joins the column it is pasted into", async () => {
+ const clipboardData = {
+ cells: [{ code: "x = 42", config: { column: 1, hide_code: true } }],
+ version: "1.0",
+ };
+
+ const mockItem = {
+ types: ["web application/x-marimo-cell"],
+ getType: vi.fn().mockResolvedValue(
+ new Blob([JSON.stringify(clipboardData)], {
+ type: "web application/x-marimo-cell",
+ }),
+ ),
+ };
+
+ mockClipboard.read.mockResolvedValue([mockItem]);
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteAtCell(mockCellId1);
+ });
+
+ expect(mockCreateCell).toHaveBeenCalledWith({
+ after: mockCellId1,
code: "x = 42",
- autoFocus: true,
+ config: { hide_code: true },
});
});
@@ -365,24 +398,21 @@ describe("useCellClipboard", () => {
await result.current.pasteAtCell(mockCellId1);
});
- expect(mockCreateNewCell).toHaveBeenCalledTimes(3);
- expect(mockCreateNewCell).toHaveBeenNthCalledWith(3, {
- cellId: mockCellId1,
- before: false,
+ expect(mockCreateCell).toHaveBeenCalledTimes(3);
+ expect(mockCreateCell).toHaveBeenNthCalledWith(3, {
+ after: mockCellId1,
code: "x = 42",
- autoFocus: true,
+ config: {},
});
- expect(mockCreateNewCell).toHaveBeenNthCalledWith(2, {
- cellId: mockCellId1,
- before: false,
+ expect(mockCreateCell).toHaveBeenNthCalledWith(2, {
+ after: mockCellId1,
code: "y = x * 2",
- autoFocus: true,
+ config: {},
});
- expect(mockCreateNewCell).toHaveBeenNthCalledWith(1, {
- cellId: mockCellId1,
- before: false,
+ expect(mockCreateCell).toHaveBeenNthCalledWith(1, {
+ after: mockCellId1,
code: "print(y)",
- autoFocus: true,
+ config: {},
});
});
@@ -401,11 +431,9 @@ describe("useCellClipboard", () => {
await result.current.pasteAtCell(mockCellId1);
});
- expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: mockCellId1,
- before: false,
+ expect(mockCreateCell).toHaveBeenCalledWith({
+ after: mockCellId1,
code: "plain text code",
- autoFocus: true,
});
});
@@ -432,11 +460,9 @@ describe("useCellClipboard", () => {
"Failed to parse clipboard cell data",
expect.any(Error),
);
- expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: mockCellId1,
- before: false,
+ expect(mockCreateCell).toHaveBeenCalledWith({
+ after: mockCellId1,
code: "fallback text",
- autoFocus: true,
});
});
@@ -522,11 +548,9 @@ describe("useCellClipboard", () => {
"Failed to parse clipboard cell data",
expect.any(Error),
);
- expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: mockCellId1,
- before: false,
+ expect(mockCreateCell).toHaveBeenCalledWith({
+ after: mockCellId1,
code: "fallback text",
- autoFocus: true,
});
});
@@ -554,11 +578,9 @@ describe("useCellClipboard", () => {
await result.current.pasteAtCell(mockCellId1);
});
- expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: mockCellId1,
- before: false,
+ expect(mockCreateCell).toHaveBeenCalledWith({
+ after: mockCellId1,
code: "fallback text",
- autoFocus: true,
});
});
});
diff --git a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
index 44e3d57de4..4417231571 100644
--- a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
@@ -3,15 +3,37 @@
import type { EditorView } from "@codemirror/view";
import { act, renderHook } from "@testing-library/react";
-import { Provider } from "jotai";
import React, { createRef } from "react";
-import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
import { Mocks } from "@/__mocks__/common";
+
+const { mockCreateCell, mockMoveToNextCell } = vi.hoisted(() => ({
+ mockCreateCell: vi.fn(),
+ mockMoveToNextCell: vi.fn(),
+}));
+
+import { DocumentWrapper, mockDocumentModel } from "@/__mocks__/document";
import { MockNotebook } from "@/__mocks__/notebook";
import { MockRequestClient } from "@/__mocks__/requests";
import { aiCompletionCellAtom } from "@/core/ai/state";
-import type { CellActions } from "@/core/cells/cells";
+import type { CellActions } from "@/core/cells/actions";
import { notebookAtom } from "@/core/cells/cells";
+import type { CellId } from "@/core/cells/ids";
+import type { DocumentModel } from "@/core/notebook/document";
+import {
+ cell,
+ CONFIG,
+ document as documentOf,
+ withCells,
+} from "@/core/notebook/document/__tests__/fixtures";
import { LanguageAdapters } from "@/core/codemirror/language/LanguageAdapters";
import { signatureHintField } from "@/core/codemirror/completion/signature-hint";
import {
@@ -30,9 +52,11 @@ import {
} from "../navigation";
// Mock only the essential dependencies that we need to control
+vi.mock("@/core/cells/actions", () => ({
+ useCellActions: vi.fn(),
+}));
vi.mock("@/core/cells/cells", async (importOriginal) => ({
...(await importOriginal()),
- useCellActions: vi.fn(),
}));
vi.mock("@/core/cells/focus", async (importOriginal) => ({
@@ -80,7 +104,7 @@ vi.mock("@codemirror/autocomplete", () => ({
// Get mocked functions
const mockUseCellActions = vi.mocked(
- await import("@/core/cells/cells"),
+ await import("@/core/cells/actions"),
).useCellActions;
const mockUseSaveNotebook = vi.mocked(
@@ -93,6 +117,8 @@ const mockUseCellClipboard = vi.mocked(
await import("../clipboard"),
).useCellClipboard;
+afterEach(() => stopModel());
+
afterAll(() => {
vi.resetAllMocks();
});
@@ -107,11 +133,17 @@ import {
useIsCellSelected,
} from "../selection";
+// The document the hooks edit, with cellId3's code hidden
+let model: DocumentModel;
+let stopModel = () => {};
+const hideCodeOf = (id: CellId) =>
+ store.get(model.documentAtom)?.cells.get(id)?.config.hide_code;
+
// Shared render helper
const renderWithProvider = <T>(hook: () => T) => {
return renderHook(hook, {
wrapper: ({ children }) =>
- React.createElement(Provider, { store }, children),
+ React.createElement(DocumentWrapper, { store, model }, children),
});
};
@@ -125,17 +157,16 @@ const mockCutCell = vi.fn().mockResolvedValue(undefined);
const mockPasteCell = vi.fn();
const mockCellActions = MockNotebook.cellActions({
+ createCell: mockCreateCell,
+ moveToNextCell: mockMoveToNextCell,
focusCell: vi.fn(),
- moveToNextCell: vi.fn(),
focusTopCell: vi.fn(),
focusBottomCell: vi.fn(),
- createNewCell: vi.fn(),
moveCell: vi.fn(),
sendToTop: vi.fn(),
sendToBottom: vi.fn(),
- updateCellConfig: vi.fn(),
markTouched: vi.fn(),
- deleteCell: vi.fn(),
+ deleteCells: vi.fn(),
undoDeleteCell: vi.fn(),
});
@@ -207,6 +238,23 @@ describe("useCellNavigationProps", () => {
},
});
store.set(notebookAtom, notebookState);
+ stopModel();
+ ({ model, stop: stopModel } = mockDocumentModel(
+ store,
+ withCells(
+ documentOf(),
+ {
+ c1: null,
+ c2: null,
+ [cellId1]: cell(cellId1, ""),
+ [cellId2]: cell(cellId2, ""),
+ [cellId3]: cell(cellId3, "", {
+ config: { ...CONFIG, hide_code: true },
+ }),
+ },
+ [cellId1, cellId2, cellId3],
+ ),
+ ));
// Clear AI completion state
store.set(aiCompletionCellAtom, null);
@@ -367,7 +415,7 @@ describe("useCellNavigationProps", () => {
});
expect(mockRunCell).toHaveBeenCalled();
- expect(mockCellActions.moveToNextCell).toHaveBeenCalledWith({
+ expect(mockMoveToNextCell).toHaveBeenCalledWith({
cellId: mockCellId,
before: false,
});
@@ -399,11 +447,7 @@ describe("useCellNavigationProps", () => {
result.current.onKeyDown?.(mockEvent);
});
- expect(mockCellActions.createNewCell).toHaveBeenCalledWith({
- cellId: mockCellId,
- before: true,
- autoFocus: true,
- });
+ expect(mockCreateCell).toHaveBeenCalledWith({ before: mockCellId });
});
it("should create cell after when 'b' key is pressed", () => {
@@ -417,11 +461,7 @@ describe("useCellNavigationProps", () => {
result.current.onKeyDown?.(mockEvent);
});
- expect(mockCellActions.createNewCell).toHaveBeenCalledWith({
- cellId: mockCellId,
- before: false,
- autoFocus: true,
- });
+ expect(mockCreateCell).toHaveBeenCalledWith({ after: mockCellId });
});
it("should add an import before and a SQL cell after when 'q' is pressed", () => {
@@ -435,18 +475,15 @@ describe("useCellNavigationProps", () => {
result.current.onKeyDown?.(Mocks.keyboardEvent({ key: "q" }));
});
- expect(mockCellActions.createNewCell).toHaveBeenNthCalledWith(
+ expect(mockCreateCell).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
- cellId: mockCellId,
- before: true,
+ before: mockCellId,
code: "import marimo as mo",
}),
);
- expect(mockCellActions.createNewCell).toHaveBeenNthCalledWith(2, {
- cellId: mockCellId,
- before: false,
- autoFocus: true,
+ expect(mockCreateCell).toHaveBeenNthCalledWith(2, {
+ after: mockCellId,
code: LanguageAdapters.sql.defaultCode,
});
});
@@ -1034,7 +1071,7 @@ describe("useCellNavigationProps", () => {
expect(mockRunCell).toHaveBeenCalledWith([cellId1, cellId2]);
// Should move to next cell after the last selected cell
- expect(mockCellActions.moveToNextCell).toHaveBeenCalledWith({
+ expect(mockMoveToNextCell).toHaveBeenCalledWith({
cellId: cellId2,
before: false,
});
@@ -1066,7 +1103,7 @@ describe("useCellNavigationProps", () => {
expect(mockRunCell).toHaveBeenCalledWith([cellId2, cellId3]);
// Should move to previous cell before the first selected cell
- expect(mockCellActions.moveToNextCell).toHaveBeenCalledWith({
+ expect(mockMoveToNextCell).toHaveBeenCalledWith({
cellId: cellId2,
before: true,
});
@@ -1167,15 +1204,7 @@ describe("useCellNavigationProps", () => {
result.current.onKeyDown?.(mockEvent);
});
- expect(mockRequestClient.saveCellConfig).toHaveBeenCalledWith({
- configs: {
- [cellId1]: { hide_code: true },
- },
- });
- expect(mockCellActions.updateCellConfig).toHaveBeenCalledWith({
- cellId: cellId1,
- config: { hide_code: true },
- });
+ expect(hideCodeOf(cellId1)).toBe(true);
expect(mockEvent.preventDefault).toHaveBeenCalled();
});
@@ -1190,15 +1219,7 @@ describe("useCellNavigationProps", () => {
result.current.onKeyDown?.(mockEvent);
});
- expect(mockRequestClient.saveCellConfig).toHaveBeenCalledWith({
- configs: {
- [cellId3]: { hide_code: false },
- },
- });
- expect(mockCellActions.updateCellConfig).toHaveBeenCalledWith({
- cellId: cellId3,
- config: { hide_code: false },
- });
+ expect(hideCodeOf(cellId3)).toBe(false);
});
it("should toggle hide code for multiple selected cells", () => {
@@ -1220,20 +1241,8 @@ describe("useCellNavigationProps", () => {
result.current.onKeyDown?.(mockEvent);
});
- expect(mockRequestClient.saveCellConfig).toHaveBeenCalledWith({
- configs: {
- [cellId1]: { hide_code: true },
- [cellId2]: { hide_code: true },
- },
- });
- expect(mockCellActions.updateCellConfig).toHaveBeenCalledWith({
- cellId: cellId1,
- config: { hide_code: true },
- });
- expect(mockCellActions.updateCellConfig).toHaveBeenCalledWith({
- cellId: cellId2,
- config: { hide_code: true },
- });
+ expect(hideCodeOf(cellId1)).toBe(true);
+ expect(hideCodeOf(cellId2)).toBe(true);
});
});
@@ -1701,7 +1710,7 @@ describe("useCellNavigationProps", () => {
result.current.onKeyDown?.(mockEvent);
});
- expect(mockCellActions.createNewCell).not.toHaveBeenCalled();
+ expect(mockCreateCell).not.toHaveBeenCalled();
expect(mockEvent.preventDefault).not.toHaveBeenCalled();
});
@@ -1716,7 +1725,7 @@ describe("useCellNavigationProps", () => {
result.current.onKeyDown?.(mockEvent);
});
- expect(mockCellActions.createNewCell).not.toHaveBeenCalled();
+ expect(mockCreateCell).not.toHaveBeenCalled();
expect(mockEvent.preventDefault).not.toHaveBeenCalled();
});
});
diff --git a/frontend/src/components/editor/navigation/clipboard.ts b/frontend/src/components/editor/navigation/clipboard.ts
index 79aa1f58b8..7e87ccb807 100644
--- a/frontend/src/components/editor/navigation/clipboard.ts
+++ b/frontend/src/components/editor/navigation/clipboard.ts
@@ -3,7 +3,8 @@
import useEvent from "react-use-event-hook";
import { z } from "zod";
import { toast } from "@/components/ui/use-toast";
-import { getNotebook, useCellActions } from "@/core/cells/cells";
+import { getNotebook } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import type { CellId } from "@/core/cells/ids";
import {
usePendingCutActions,
@@ -73,6 +74,7 @@ async function writeCellsToClipboard(
export function useCellClipboard() {
const actions = useCellActions();
+ const { createCell } = actions;
const pendingCutActions = usePendingCutActions();
const pendingCutState = usePendingCutState();
@@ -178,14 +180,15 @@ export function useCellClipboard() {
const currentCellId = cellId;
const reversedCells = clipboardData.cells.toReversed();
for (const cell of reversedCells) {
- actions.createNewCell({
- cellId: currentCellId,
- before,
+ // The pasted cell joins the column it is pasted into.
+ const { column: _column, ...config } = cell.config ?? {};
+ createCell({
+ ...(before
+ ? { before: currentCellId }
+ : { after: currentCellId }),
code: cell.code,
name: cell.name,
- config: cell.config,
- hideCode: cell.config?.hide_code,
- autoFocus: true,
+ config,
});
}
@@ -199,11 +202,9 @@ export function useCellClipboard() {
// Fallback to plain text
const text = await navigator.clipboard.readText();
if (text.trim()) {
- actions.createNewCell({
- cellId,
- before,
+ createCell({
+ ...(before ? { before: cellId } : { after: cellId }),
code: text,
- autoFocus: true,
});
} else {
toastNothingToPaste();
diff --git a/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx b/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx
index 5a26220576..b18acbda23 100644
--- a/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx
+++ b/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx
@@ -34,14 +34,14 @@ import {
getCellEditorView,
hasOnlyOneCellAtom,
notebookAtom,
- useCellActions,
} from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
+import { useNotebookDocumentEdit } from "@/core/notebook/document";
import type { CellId } from "@/core/cells/ids";
import { usePendingDeleteService } from "@/core/cells/pending-delete-service";
import { formatEditorViews } from "@/core/codemirror/format";
import { userConfigAtom } from "@/core/config/config";
import type { HotkeyAction } from "@/core/hotkeys/hotkeys";
-import { useRequestClient } from "@/core/network/requests";
import type { CellConfig } from "@/core/network/types";
import { store } from "@/core/state/jotai";
import { useEventListener } from "@/hooks/useEventListener";
@@ -112,20 +112,15 @@ const CellStateDropdown: React.FC<{
};
export function useMultiCellActionButtons(cellIds: CellId[]) {
- const {
- updateCellConfig,
- moveCell,
- clearCellOutput,
- sendToTop,
- sendToBottom,
- } = useCellActions();
+ const { moveCell, clearCellOutput, sendToTop, sendToBottom } =
+ useCellActions();
+ const edit = useNotebookDocumentEdit();
const deleteCell = useDeleteManyCellsCallback();
const hasOnlyOneCell = useAtomValue(hasOnlyOneCellAtom);
const selectionActions = useCellSelectionActions();
const runCells = useRunCells();
const pendingDeleteService = usePendingDeleteService();
const userConfig = useAtomValue(userConfigAtom);
- const { saveCellConfig } = useRequestClient();
const selectedCount = cellIds.length;
@@ -205,16 +200,12 @@ export function useMultiCellActionButtons(cellIds: CellId[]) {
});
const toggleSelectedCellsProperty = useEvent(
- async (cellIds: CellId[], property: keyof CellConfig, value: boolean) => {
- const configs: Record<CellId, Partial<CellConfig>> = {};
- cellIds.forEach((cellId) => {
- configs[cellId] = { [property]: value };
- });
-
- await saveCellConfig({ configs });
-
- cellIds.forEach((cellId) => {
- updateCellConfig({ cellId, config: configs[cellId] });
+ (cellIds: CellId[], property: keyof CellConfig, value: boolean) => {
+ edit((tx) => {
+ for (const cellId of cellIds) {
+ const config: Partial<CellConfig> = { [property]: value };
+ tx.updateConfig(cellId, config);
+ }
});
},
);
diff --git a/frontend/src/components/editor/navigation/navigation.ts b/frontend/src/components/editor/navigation/navigation.ts
index e6e8984884..669072d713 100644
--- a/frontend/src/components/editor/navigation/navigation.ts
+++ b/frontend/src/components/editor/navigation/navigation.ts
@@ -13,7 +13,9 @@ 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, useCellActions } from "@/core/cells/cells";
+import { cellIdsAtom, notebookAtom } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
+import { useNotebookDocumentEdit } from "@/core/notebook/document";
import { useCellFocusActions } from "@/core/cells/focus";
import type { CellId } from "@/core/cells/ids";
import { HTMLCellId } from "@/core/cells/ids";
@@ -36,7 +38,6 @@ import {
} from "@/core/config/config";
import type { HotkeyAction } from "@/core/hotkeys/hotkeys";
import { parseShortcut } from "@/core/hotkeys/shortcuts";
-import { useRequestClient } from "@/core/network/requests";
import { useSaveNotebook } from "@/core/saving/save-component";
import { Events } from "@/utils/events";
import type { CollapsibleTree } from "@/utils/id-tree";
@@ -189,9 +190,10 @@ export function useCellNavigationProps(
},
) {
const { saveOrNameNotebook } = useSaveNotebook();
- const { saveCellConfig } = useRequestClient();
+ const edit = useNotebookDocumentEdit();
const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
const actions = useCellActions();
+ const { createCell, moveToNextCell } = useCellActions();
const store = useStore();
const temporarilyShownCodeActions = useTemporarilyShownCodeActions();
const runCells = useRunCells();
@@ -376,21 +378,21 @@ export function useCellNavigationProps(
"cell.runAndNewBelow": addSingleHandler((cellIds) => {
runCells(cellIds);
const lastCellId = cellIds[cellIds.length - 1];
- actions.moveToNextCell({ cellId: lastCellId, before: false });
+ moveToNextCell({ cellId: lastCellId, before: false });
return true;
}),
"cell.runAndNewAbove": addSingleHandler((cellIds) => {
runCells(cellIds);
const firstCellId = cellIds[0];
- actions.moveToNextCell({ cellId: firstCellId, before: true });
+ moveToNextCell({ cellId: firstCellId, before: true });
return true;
}),
"cell.createAbove": (cellId) => {
- actions.createNewCell({ cellId, before: true });
+ createCell({ before: cellId });
return true;
},
"cell.createBelow": (cellId) => {
- actions.createNewCell({ cellId, before: false });
+ createCell({ after: cellId });
return true;
},
"cell.moveUp": addSingleHandler((cellIds) => {
@@ -453,20 +455,12 @@ export function useCellNavigationProps(
(config) => config?.hide_code,
);
- // Fire-and-forget
- void saveCellConfig({
- configs: Object.fromEntries(
- cellIds.map((cellId) => [cellId, { hide_code: nextHideCode }]),
- ),
+ edit((tx) => {
+ for (const cellId of cellIds) {
+ tx.updateConfig(cellId, { hide_code: nextHideCode });
+ }
});
- for (const cellId of cellIds) {
- actions.updateCellConfig({
- cellId,
- config: { hide_code: nextHideCode },
- });
- }
-
// Only focus if it is a single cell
if (cellIds.length === 1) {
const cellId = cellIds[0];
@@ -543,14 +537,14 @@ export function useCellNavigationProps(
if (Events.hasModifier(evt)) {
return false;
}
- actions.createNewCell({ cellId, before: true, autoFocus: true });
+ createCell({ before: cellId });
return true;
},
"command.createCellAfter": (cellId) => {
if (Events.hasModifier(evt)) {
return false;
}
- actions.createNewCell({ cellId, before: false, autoFocus: true });
+ createCell({ after: cellId });
return true;
},
"command.createSqlCellAfter": (cellId) => {
@@ -559,14 +553,12 @@ export function useCellNavigationProps(
}
maybeAddMarimoImport({
autoInstantiate: true,
- createNewCell: actions.createNewCell,
+ createCell: createCell,
fromCellId: cellId,
before: true,
});
- actions.createNewCell({
- cellId,
- before: false,
- autoFocus: true,
+ createCell({
+ after: cellId,
code: LanguageAdapters.sql.defaultCode,
});
return true;
@@ -635,11 +627,11 @@ export function useCellNavigationProps(
return true;
},
o: () => {
- actions.createNewCell({ cellId, before: false, autoFocus: true });
+ createCell({ after: cellId });
return true;
},
"shift+o": () => {
- actions.createNewCell({ cellId, before: true, autoFocus: true });
+ createCell({ before: cellId });
return true;
},
u: () => {
diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsx
index 88652bbac4..bc598cfccc 100644
--- a/frontend/src/components/editor/notebook-cell.tsx
+++ b/frontend/src/components/editor/notebook-cell.tsx
@@ -43,13 +43,12 @@ import { useResizeObserver } from "@/hooks/useResizeObserver";
import { cn } from "@/utils/cn";
import type { Milliseconds, Seconds } from "@/utils/time";
import {
- type CellActions,
createUntouchedCellAtom,
- useCellActions,
useCellData,
useCellHandle,
useCellRuntime,
} from "../../core/cells/cells";
+import { type CellActions, useCellActions } from "../../core/cells/actions";
import { type CellId, SETUP_CELL_ID } from "../../core/cells/ids";
import {
cellNeedsRun,
@@ -216,13 +215,10 @@ function useCellHiddenLogic({
export type CellComponentActions = Pick<
CellActions,
| "updateCellCode"
- | "createNewCell"
| "focusCell"
| "moveCell"
| "collapseCell"
| "expandCell"
- | "moveToNextCell"
- | "updateCellConfig"
| "clearSerializedEditorState"
| "setStdinResponse"
| "clearCellConsoleOutput"
@@ -928,15 +924,16 @@ const CellLeftSideActions = memo(
actions: CellComponentActions;
}) => {
const connection = useAtomValue(connectionAtom);
- const { className, actions, cellId } = props;
+ const { className, cellId } = props;
+ const { createCell } = useCellActions();
const createBelow = useEvent(
- (opts: { code?: string; hideCode?: boolean } = {}) =>
- actions.createNewCell({ cellId, before: false, ...opts }),
+ ({ code, hideCode }: { code?: string; hideCode?: boolean } = {}) =>
+ createCell({ after: cellId, code, config: { hide_code: hideCode } }),
);
const createAbove = useEvent(
- (opts: { code?: string; hideCode?: boolean } = {}) =>
- actions.createNewCell({ cellId, before: true, ...opts }),
+ ({ code, hideCode }: { code?: string; hideCode?: boolean } = {}) =>
+ createCell({ before: cellId, code, config: { hide_code: hideCode } }),
);
const oneClickShortcut = "mod";
diff --git a/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx
index 6428a0904e..6520053d9d 100644
--- a/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx
+++ b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx
@@ -2,17 +2,29 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createStore, Provider } from "jotai";
import { SetupMocks } from "@/__mocks__/common";
+import { mockDocumentModel } from "@/__mocks__/document";
import { cellId } from "@/__tests__/branded";
import { TooltipProvider } from "@/components/ui/tooltip";
import type { WithResponse } from "@/core/cells/types";
+import { DocumentProvider } from "@/core/notebook/document";
import type { OutputMessage } from "@/core/kernel/messages";
import { CONSOLE_CLEAR_DEBOUNCE_MS, ConsoleOutput } from "../ConsoleOutput";
SetupMocks.resizeObserver();
+const store = createStore();
+const { model } = mockDocumentModel(store, null);
+
const renderWithProvider = (ui: React.ReactElement) => {
- return render(<TooltipProvider>{ui}</TooltipProvider>);
+ return render(
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>{ui}</TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
+ );
};
describe("ConsoleOutput integration", () => {
@@ -104,13 +116,17 @@ describe("ConsoleOutput pdb history", () => {
];
rerender(
- <TooltipProvider>
- <ConsoleOutput
- {...defaultProps}
- consoleOutputs={outputs2}
- onSubmitDebugger={onSubmitDebugger}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput
+ {...defaultProps}
+ consoleOutputs={outputs2}
+ onSubmitDebugger={onSubmitDebugger}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
// New StdInput mounted — press ArrowUp to recall previous command
@@ -138,13 +154,17 @@ describe("ConsoleOutput pdb history", () => {
fireEvent.keyDown(nameInput, { key: "Enter" });
rerender(
- <TooltipProvider>
- <ConsoleOutput
- {...defaultProps}
- consoleOutputs={[stdinPrompt("Name: ", "marimo"), passwordPrompt]}
- onSubmitDebugger={onSubmitDebugger}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput
+ {...defaultProps}
+ consoleOutputs={[stdinPrompt("Name: ", "marimo"), passwordPrompt]}
+ onSubmitDebugger={onSubmitDebugger}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
const input = screen.getByTestId("console-input");
expect(input).toHaveAttribute("type", "password");
@@ -161,16 +181,20 @@ describe("ConsoleOutput pdb history", () => {
expect(input).toHaveValue("");
rerender(
- <TooltipProvider>
- <ConsoleOutput
- {...defaultProps}
- consoleOutputs={[
- stdinPrompt("Name: ", "marimo"),
- { ...passwordPrompt, response: "" },
- stdinPrompt("Name: "),
- ]}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput
+ {...defaultProps}
+ consoleOutputs={[
+ stdinPrompt("Name: ", "marimo"),
+ { ...passwordPrompt, response: "" },
+ stdinPrompt("Name: "),
+ ]}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
const nextInput = screen.getByTestId("console-input");
fireEvent.keyDown(nextInput, { key: "ArrowUp" });
@@ -239,13 +263,17 @@ describe("ConsoleOutput pdb history", () => {
stdinPrompt("(Pdb) "),
];
rerender(
- <TooltipProvider>
- <ConsoleOutput
- {...defaultProps}
- consoleOutputs={outputs2}
- onSubmitDebugger={onSubmitDebugger}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput
+ {...defaultProps}
+ consoleOutputs={outputs2}
+ onSubmitDebugger={onSubmitDebugger}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
// Submit an empty value; this should NOT enter the history stack.
@@ -258,13 +286,17 @@ describe("ConsoleOutput pdb history", () => {
stdinPrompt("(Pdb) "),
];
rerender(
- <TooltipProvider>
- <ConsoleOutput
- {...defaultProps}
- consoleOutputs={outputs3}
- onSubmitDebugger={onSubmitDebugger}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput
+ {...defaultProps}
+ consoleOutputs={outputs3}
+ onSubmitDebugger={onSubmitDebugger}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
// ArrowUp should jump back to "step", skipping the empty submission.
@@ -299,13 +331,17 @@ describe("ConsoleOutput pdb history", () => {
];
rerender(
- <TooltipProvider>
- <ConsoleOutput
- {...defaultProps}
- consoleOutputs={outputs2}
- onSubmitDebugger={onSubmitDebugger}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput
+ {...defaultProps}
+ consoleOutputs={outputs2}
+ onSubmitDebugger={onSubmitDebugger}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
// Submit "print(x)"
@@ -321,13 +357,17 @@ describe("ConsoleOutput pdb history", () => {
];
rerender(
- <TooltipProvider>
- <ConsoleOutput
- {...defaultProps}
- consoleOutputs={outputs3}
- onSubmitDebugger={onSubmitDebugger}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput
+ {...defaultProps}
+ consoleOutputs={outputs3}
+ onSubmitDebugger={onSubmitDebugger}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
// ArrowUp should show most recent command first
@@ -370,13 +410,17 @@ describe("ConsoleOutput pdb history", () => {
// Same outputs, but the cell isn't interrupted -- this is a real
// bare-Enter submission, so we should render the (empty) placeholder.
rerender(
- <TooltipProvider>
- <ConsoleOutput
- {...defaultProps}
- consoleOutputs={interruptedOutputs}
- interrupted={false}
- />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput
+ {...defaultProps}
+ consoleOutputs={interruptedOutputs}
+ interrupted={false}
+ />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
expect(screen.getByLabelText("stdin response")).toBeInTheDocument();
@@ -426,9 +470,13 @@ describe("ConsoleOutput debounced clearing", () => {
// Clear outputs (simulates cell re-run)
rerender(
- <TooltipProvider>
- <ConsoleOutput {...defaultProps} consoleOutputs={[]} />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput {...defaultProps} consoleOutputs={[]} />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
// Old output should still be visible during debounce period
@@ -437,9 +485,13 @@ describe("ConsoleOutput debounced clearing", () => {
// New outputs arrive before debounce fires
const outputs2 = [createOutput("new output")];
rerender(
- <TooltipProvider>
- <ConsoleOutput {...defaultProps} consoleOutputs={outputs2} />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput {...defaultProps} consoleOutputs={outputs2} />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
// New output should be shown immediately
@@ -458,9 +510,13 @@ describe("ConsoleOutput debounced clearing", () => {
// Clear outputs
rerender(
- <TooltipProvider>
- <ConsoleOutput {...defaultProps} consoleOutputs={[]} />
- </TooltipProvider>,
+ <Provider store={store}>
+ <DocumentProvider model={model}>
+ <TooltipProvider>
+ <ConsoleOutput {...defaultProps} consoleOutputs={[]} />
+ </TooltipProvider>
+ </DocumentProvider>
+ </Provider>,
);
// Still visible during debounce
diff --git a/frontend/src/components/editor/renderers/cell-array.tsx b/frontend/src/components/editor/renderers/cell-array.tsx
index 1badb7cb4b..fa625d537e 100644
--- a/frontend/src/components/editor/renderers/cell-array.tsx
+++ b/frontend/src/components/editor/renderers/cell-array.tsx
@@ -33,10 +33,10 @@ import type { CellColumnId } from "@/utils/id-tree";
import { invariant } from "@/utils/invariant";
import {
columnIdsAtom,
- useCellActions,
useCellIds,
useScrollKey,
} from "../../../core/cells/cells";
+import { useCellActions } from "../../../core/cells/actions";
import { formatAll } from "../../../core/codemirror/format";
import type { AppConfig, UserConfig } from "../../../core/config/config-schema";
import type { AppMode } from "../../../core/mode";
@@ -267,7 +267,7 @@ const AddCellButtons: React.FC<{
columnId: CellColumnId;
className?: string;
}> = ({ columnId, className }) => {
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
const [isAiButtonOpen, isAiButtonOpenActions] = useBoolean(false);
const aiEnabled = useAtomValue(aiEnabledAtom);
const aiFeaturesEnabled = useAtomValue(aiFeaturesEnabledAtom);
@@ -291,12 +291,7 @@ const AddCellButtons: React.FC<{
variant="text"
size="sm"
disabled={!canInteractWithApp}
- onClick={() =>
- createNewCell({
- cellId: { type: "__end__", columnId },
- before: false,
- })
- }
+ onClick={() => createCell({ endOf: columnId })}
>
<SquareCodeIcon className="mr-2 size-4 shrink-0" />
Python
@@ -307,13 +302,12 @@ const AddCellButtons: React.FC<{
size="sm"
disabled={!canInteractWithApp}
onClick={() => {
- maybeAddMarimoImport({ autoInstantiate: true, createNewCell });
+ maybeAddMarimoImport({ autoInstantiate: true, createCell });
- createNewCell({
- cellId: { type: "__end__", columnId },
- before: false,
+ createCell({
+ endOf: columnId,
code: LanguageAdapters.markdown.defaultCode,
- hideCode: MARKDOWN_INITIAL_HIDE_CODE,
+ config: { hide_code: MARKDOWN_INITIAL_HIDE_CODE },
});
}}
>
@@ -326,11 +320,10 @@ const AddCellButtons: React.FC<{
size="sm"
disabled={!canInteractWithApp}
onClick={() => {
- maybeAddMarimoImport({ autoInstantiate: true, createNewCell });
+ maybeAddMarimoImport({ autoInstantiate: true, createCell });
- createNewCell({
- cellId: { type: "__end__", columnId },
- before: false,
+ createCell({
+ endOf: columnId,
code: LanguageAdapters.sql.defaultCode,
});
}}
diff --git a/frontend/src/components/markdown/markdown-renderer.tsx b/frontend/src/components/markdown/markdown-renderer.tsx
index 2396e60abb..abcdb0bee9 100644
--- a/frontend/src/components/markdown/markdown-renderer.tsx
+++ b/frontend/src/components/markdown/markdown-renderer.tsx
@@ -12,7 +12,7 @@ import {
} from "streamdown";
import { Button, type ButtonProps } from "@/components/ui/button";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { useLastFocusedCellId } from "@/core/cells/focus";
import { MarkdownLanguageAdapter } from "@/core/codemirror/language/languages/markdown";
import { SQLLanguageAdapter } from "@/core/codemirror/language/languages/sql/sql";
@@ -71,7 +71,7 @@ function maybeTransform(
}
const InsertCodeBlockButton = ({ code, language }: CodeBlockProps) => {
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
const lastFocusedCellId = useLastFocusedCellId();
const autoInstantiate = useAtomValue(autoInstantiateAtom);
@@ -81,15 +81,11 @@ const InsertCodeBlockButton = ({ code, language }: CodeBlockProps) => {
if (language === "sql") {
maybeAddMarimoImport({
autoInstantiate,
- createNewCell,
+ createCell,
fromCellId: lastFocusedCellId,
});
}
- createNewCell({
- code: result.code,
- before: false,
- cellId: lastFocusedCellId ?? "__end__",
- });
+ createCell({ after: lastFocusedCellId, code: result.code });
};
return (
diff --git a/frontend/src/components/pages/edit-page.tsx b/frontend/src/components/pages/edit-page.tsx
index de9bf0274c..09e23e5627 100644
--- a/frontend/src/components/pages/edit-page.tsx
+++ b/frontend/src/components/pages/edit-page.tsx
@@ -1,15 +1,17 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { lazy } from "react";
+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";
-const LazyCommandPalette = lazy(
- () => import("../editor/controls/command-palette"),
-);
-
interface Props {
userConfig: UserConfig;
appConfig: AppConfig;
@@ -20,21 +22,34 @@ const hideChrome = (() => {
return url.searchParams.get(KnownQueryParams.showChrome) === "false";
})();
+/** Own the notebook session and provide its document model to the editor and its chrome. */
const EditPage = (props: Props) => {
- if (hideChrome) {
- return (
- <>
- <EditApp hideControls={true} {...props} />
- <LazyCommandPalette />
- </>
- );
- }
+ 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 = (
+ <EditApp
+ {...props}
+ hideControls={hideChrome}
+ connection={connection}
+ reconnect={reconnect}
+ />
+ );
return (
- <AppChrome>
- <EditApp {...props} />
- <LazyCommandPalette />
- </AppChrome>
+ <DocumentProvider model={documentModel}>
+ {hideChrome ? app : <AppChrome>{app}</AppChrome>}
+ </DocumentProvider>
);
};
diff --git a/frontend/src/components/scratchpad/scratchpad.test.tsx b/frontend/src/components/scratchpad/scratchpad.test.tsx
index 04d07fc922..f544d35622 100644
--- a/frontend/src/components/scratchpad/scratchpad.test.tsx
+++ b/frontend/src/components/scratchpad/scratchpad.test.tsx
@@ -21,8 +21,10 @@ const state = vi.hoisted(() => ({
vi.mock("@/core/cells/cells", () => ({
useNotebook: () => ({ cellRuntime: {}, cellData: {} }),
+}));
+vi.mock("@/core/cells/actions", () => ({
useCellActions: () => ({
- createNewCell: vi.fn(),
+ createCell: vi.fn(),
updateCellCode: state.updateCellCode,
}),
}));
diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsx
index d9e2304a71..3210d141c2 100644
--- a/frontend/src/components/scratchpad/scratchpad.tsx
+++ b/frontend/src/components/scratchpad/scratchpad.tsx
@@ -13,7 +13,8 @@ import type React from "react";
import { Suspense, useRef, useState } from "react";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
import useEvent from "react-use-event-hook";
-import { useCellActions, useNotebook } from "@/core/cells/cells";
+import { useNotebook } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { useLastFocusedCellId } from "@/core/cells/focus";
import { HTMLCellId, SCRATCH_CELL_ID } from "@/core/cells/ids";
import { DEFAULT_CELL_NAME } from "@/core/cells/names";
@@ -55,7 +56,7 @@ export const ScratchPad: React.FC = () => {
const { theme } = useTheme();
const ref = useRef<EditorView | null>(null);
const lastFocusedCellId = useLastFocusedCellId();
- const { createNewCell, updateCellCode } = useCellActions();
+ const { updateCellCode, createCell } = useCellActions();
const { sendRunScratchpad } = useRequestClient();
const orientation = usePanelOrientation();
const section = usePanelSection();
@@ -81,11 +82,7 @@ export const ScratchPad: React.FC = () => {
if (!code.trim()) {
return;
}
- createNewCell({
- code,
- before: false,
- cellId: lastFocusedCellId ?? "__end__",
- });
+ createCell({ after: lastFocusedCellId, code });
});
const handleClearCode = useEvent(() => {
diff --git a/frontend/src/components/slides/__tests__/minimap-actions.test.tsx b/frontend/src/components/slides/__tests__/minimap-actions.test.tsx
index 803eead566..62a4da86fe 100644
--- a/frontend/src/components/slides/__tests__/minimap-actions.test.tsx
+++ b/frontend/src/components/slides/__tests__/minimap-actions.test.tsx
@@ -13,17 +13,19 @@ const A = cellId("a");
const B = cellId("b");
// Spies shared with the hoisted module mocks below.
-const { createNewCell, deleteCell, moveCellToIndex } = vi.hoisted(() => ({
- createNewCell: vi.fn(),
+const { createCell, deleteCell, moveCellToIndex } = vi.hoisted(() => ({
+ createCell: vi.fn(),
deleteCell: vi.fn(),
moveCellToIndex: vi.fn(),
}));
+vi.mock("@/core/cells/actions", () => ({
+ useCellActions: () => ({ moveCellToIndex, createCell }),
+}));
vi.mock("@/core/cells/cells", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/core/cells/cells")>();
return {
...actual,
- useCellActions: () => ({ moveCellToIndex, createNewCell }),
useCellIds: () => MultiColumn.from([[A, B]]),
};
});
@@ -91,8 +93,6 @@ function renderMinimap() {
return { ...utils, onSlideClick };
}
-const EMPTY_CELL = { code: "", autoFocus: false } as const;
-
describe("SlidesMinimap insert lines", () => {
it("inserts a blank cell above the first row and below any row", () => {
renderMinimap();
@@ -102,25 +102,13 @@ describe("SlidesMinimap insert lines", () => {
expect(inserts).toHaveLength(3);
fireEvent.click(inserts[0]);
- expect(createNewCell).toHaveBeenLastCalledWith({
- cellId: A,
- before: true,
- ...EMPTY_CELL,
- });
+ expect(createCell).toHaveBeenLastCalledWith({ before: A, focus: false });
fireEvent.click(inserts[1]);
- expect(createNewCell).toHaveBeenLastCalledWith({
- cellId: A,
- before: false,
- ...EMPTY_CELL,
- });
+ expect(createCell).toHaveBeenLastCalledWith({ after: A, focus: false });
fireEvent.click(inserts[2]);
- expect(createNewCell).toHaveBeenLastCalledWith({
- cellId: B,
- before: false,
- ...EMPTY_CELL,
- });
+ expect(createCell).toHaveBeenLastCalledWith({ after: B, focus: false });
});
});
@@ -135,11 +123,7 @@ describe("SlidesMinimap context menu", () => {
const { container } = renderMinimap();
openRowMenu(container, A);
fireEvent.click(screen.getByText("Add cell"));
- expect(createNewCell).toHaveBeenCalledWith({
- cellId: A,
- before: false,
- ...EMPTY_CELL,
- });
+ expect(createCell).toHaveBeenCalledWith({ after: A, focus: false });
});
it('"Delete cell" deletes the row\'s cell', () => {
diff --git a/frontend/src/components/slides/minimap.tsx b/frontend/src/components/slides/minimap.tsx
index 0d51fafc5f..82fd3540da 100644
--- a/frontend/src/components/slides/minimap.tsx
+++ b/frontend/src/components/slides/minimap.tsx
@@ -2,7 +2,8 @@
import { useDeleteCellCallback } from "@/components/editor/cell/useDeleteCell";
import { outputIsStale } from "@/core/cells/cell";
-import { useCellActions, useCellIds } from "@/core/cells/cells";
+import { useCellIds } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import type { CellId } from "@/core/cells/ids";
import type { CellColumnId } from "@/utils/id-tree";
import { useEffect, useRef, useState } from "react";
@@ -229,7 +230,7 @@ export const SlidesMinimap = ({
onSlideClick,
}: SlidesMinimapProps) => {
const cellIds = useCellIds();
- const { moveCellToIndex, createNewCell } = useCellActions();
+ const { moveCellToIndex, createCell } = useCellActions();
const deleteCell = useDeleteCellCallback();
const containerRef = useRef<HTMLDivElement>(null);
const visibleIds = useVisibleCellIds(containerRef);
@@ -240,7 +241,10 @@ export const SlidesMinimap = ({
const dimensions = computeThumbnailDimensions(thumbnailWidth);
const insertCell = (cellId: CellId, before: boolean) => {
- createNewCell({ cellId, before, code: "", autoFocus: false });
+ createCell({
+ ...(before ? { before: cellId } : { after: cellId }),
+ focus: false,
+ });
};
useEffect(() => {
diff --git a/frontend/src/components/slides/slide-cell-view.tsx b/frontend/src/components/slides/slide-cell-view.tsx
index e9ed2dc801..56161967c8 100644
--- a/frontend/src/components/slides/slide-cell-view.tsx
+++ b/frontend/src/components/slides/slide-cell-view.tsx
@@ -14,7 +14,7 @@ import { useRunCell } from "@/components/editor/cell/useRunCells";
import { Slide as CellOutputSlide } from "@/components/slides/slide";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
import { outputIsStale } from "@/core/cells/cell";
-import { useCellActions } from "@/core/cells/cells";
+import { useCellActions } from "@/core/cells/actions";
import { autoInstantiateAtom, useUserConfig } from "@/core/config/config";
import {
cellNeedsRun,
@@ -42,7 +42,7 @@ export const SlideCellView = ({ cell }: { cell: RuntimeCell }) => {
const { theme } = useTheme();
const runCell = useRunCell(cell.id);
const connection = useAtomValue(connectionAtom);
- const cellActions = useCellActions();
+ const { createCell } = useCellActions();
const autoInstantiate = useAtomValue(autoInstantiateAtom);
const editorViewRef = useRef<EditorView | null>(null);
const editorViewParentRef = useRef<HTMLDivElement | null>(null);
@@ -53,7 +53,7 @@ export const SlideCellView = ({ cell }: { cell: RuntimeCell }) => {
const afterToggleLanguage = useEvent(() => {
maybeAddMarimoImport({
autoInstantiate,
- createNewCell: cellActions.createNewCell,
+ createCell,
});
});
diff --git a/frontend/src/components/sort/SortableCellsProvider.tsx b/frontend/src/components/sort/SortableCellsProvider.tsx
index 2dc1d42e12..b6df2847c6 100644
--- a/frontend/src/components/sort/SortableCellsProvider.tsx
+++ b/frontend/src/components/sort/SortableCellsProvider.tsx
@@ -24,7 +24,8 @@ import { useAppConfig } from "@/core/config/config";
import { Arrays } from "@/utils/arrays";
import type { CellColumnId, MultiColumn } from "@/utils/id-tree";
import { invariant } from "@/utils/invariant";
-import { getNotebook, useCellActions } from "../../core/cells/cells";
+import { getNotebook } from "../../core/cells/cells";
+import { useCellActions } from "../../core/cells/actions";
import { useEvent } from "../../hooks/useEvent";
interface SortableCellsProviderProps {
diff --git a/frontend/src/core/ai/__tests__/staged-cells.test.ts b/frontend/src/core/ai/__tests__/staged-cells.test.ts
index fcc921bbfe..e362226235 100644
--- a/frontend/src/core/ai/__tests__/staged-cells.test.ts
+++ b/frontend/src/core/ai/__tests__/staged-cells.test.ts
@@ -21,7 +21,7 @@ const { stagedGenerationAtom, createActions, reducer, initialState } =
visibleForTesting;
// Mock the dependencies
-const mockCreateNewCell = vi.fn();
+const mockCreateCell = vi.fn();
const mockUpdateCellCode = vi.fn();
const mockDeleteCellCallback = vi.fn();
@@ -34,14 +34,16 @@ const mockCellHandle = {
},
};
+vi.mock("../../cells/actions", () => ({
+ useCellActions: () => ({
+ createCell: mockCreateCell,
+ updateCellCode: mockUpdateCellCode,
+ }),
+}));
vi.mock("../../cells/cells", async () => {
const { atom } = await import("jotai");
return {
notebookAtom: atom({ cellData: {}, cellIds: { inOrderIds: [] } }),
- useCellActions: () => ({
- createNewCell: mockCreateNewCell,
- updateCellCode: mockUpdateCellCode,
- }),
cellHandleAtom: vi.fn(() => ({
read: vi.fn(() => mockCellHandle),
})),
@@ -261,11 +263,9 @@ describe("staged-cells", () => {
const returnedCellId = result.current.createStagedCell(testCode);
expect(returnedCellId).toBe(mockCellId);
- expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: "__end__",
+ expect(mockCreateCell).toHaveBeenCalledWith({
code: testCode,
- before: false,
- newCellId: mockCellId,
+ id: mockCellId,
});
});
@@ -330,7 +330,7 @@ describe("staged-cells", () => {
// Verify it was created and added
expect(createdCellId).toBe(mockCellId);
- expect(mockCreateNewCell).toHaveBeenCalled();
+ expect(mockCreateCell).toHaveBeenCalled();
let state = store.get(stagedAICellsAtom);
expect(state.has(mockCellId)).toBe(true);
@@ -401,7 +401,7 @@ describe("staged cell generation", () => {
result.current.beginStagedCellGeneration();
// No cell or cell update should have been called
- expect(mockCreateNewCell).not.toHaveBeenCalled();
+ expect(mockCreateCell).not.toHaveBeenCalled();
expect(prepareCellCodeUpdate).not.toHaveBeenCalled();
expect(store.get(stagedGenerationInProgressAtom)).toBe(true);
});
@@ -610,11 +610,9 @@ describe("staged cell generation", () => {
},
});
- expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: "__end__",
+ expect(mockCreateCell).toHaveBeenCalledWith({
code: "print('```')",
- before: false,
- newCellId: "mock-cell-id",
+ id: "mock-cell-id",
});
});
@@ -636,16 +634,16 @@ describe("staged cell generation", () => {
},
});
- expect(mockCreateNewCell).toHaveBeenCalledWith(
+ expect(mockCreateCell).toHaveBeenCalledWith(
expect.objectContaining({
code: "value = 1",
- newCellId: "first-cell",
+ id: "first-cell",
}),
);
- expect(mockCreateNewCell).toHaveBeenCalledWith(
+ expect(mockCreateCell).toHaveBeenCalledWith(
expect.objectContaining({
code: "value",
- newCellId: "second-cell",
+ id: "second-cell",
}),
);
});
@@ -683,7 +681,7 @@ describe("staged cell generation", () => {
},
});
- expect(mockCreateNewCell).toHaveBeenCalledTimes(2);
+ expect(mockCreateCell).toHaveBeenCalledTimes(2);
expect(store.get(stagedAICellsAtom).has(cellId("first-cell"))).toBe(true);
expect(store.get(stagedAICellsAtom).has(cellId("second-cell"))).toBe(true);
expect(prepareCellCodeUpdate).toHaveBeenCalledTimes(2);
diff --git a/frontend/src/core/ai/staged-cells.ts b/frontend/src/core/ai/staged-cells.ts
index 82443ee3bb..1fd1532283 100644
--- a/frontend/src/core/ai/staged-cells.ts
+++ b/frontend/src/core/ai/staged-cells.ts
@@ -14,11 +14,8 @@ import {
notebookCellsCompletionSchema,
} from "./completion-output";
import { maybeAddMarimoImport } from "../cells/add-missing-import";
-import {
- type CreateNewCellAction,
- getCellEditorView,
- useCellActions,
-} from "../cells/cells";
+import { getCellEditorView } from "../cells/cells";
+import { type CreateCell, useCellActions } from "../cells/actions";
import { prepareCellCodeUpdate } from "../codemirror/language/cell-code";
import type { JotaiStore } from "../state/jotai";
import type { EditType } from "./tools/edit-notebook-tool";
@@ -98,18 +95,13 @@ interface UpdateStagedCellAction {
/** Manage staged cells without assuming which AI workflow owns them. */
export function useStagedCells(store: JotaiStore) {
const { addStagedCell, removeStagedCell } = useStagedAICellsActions();
- const { createNewCell, updateCellCode } = useCellActions();
+ const { updateCellCode, createCell } = useCellActions();
const deleteCellCallback = useDeleteCellCallback();
const createStagedCell = (code: string): CellId => {
const newCellId = CellId.create();
addStagedCell({ cellId: newCellId, edit: { type: "add_cell" } });
- createNewCell({
- cellId: "__end__",
- code,
- before: false,
- newCellId: newCellId,
- });
+ createCell({ code, id: newCellId });
return newCellId;
};
@@ -152,7 +144,7 @@ export function useStagedCells(store: JotaiStore) {
/** Owns the lifecycle of cells created by one structured completion flow. */
export function useStagedCellGeneration(store: JotaiStore) {
const stagedCellActions = useStagedCells(store);
- const { createNewCell } = useCellActions();
+ const { createCell } = useCellActions();
const ownedGeneration = useRef<OwnedStagedGeneration | null>(null);
// Ownership lives in a ref, so subscribe to its backing atoms to rerender
// consumers when completion or per-cell acceptance changes.
@@ -180,7 +172,7 @@ export function useStagedCellGeneration(store: JotaiStore) {
status: "in_progress",
reconciler: new StagedCellReconciler({
...stagedCellActions,
- createNewCell,
+ createCell,
}),
};
store.set(stagedGenerationAtom, {
@@ -302,7 +294,7 @@ interface StagedCellReconcilerActions {
deleteStagedCell: (cellId: CellId) => void;
removeStagedCell: (cellId: CellId) => void;
addStagedCell: (payload: { cellId: CellId; edit: Edit }) => void;
- createNewCell: (opts: CreateNewCellAction) => void;
+ createCell: CreateCell;
}
class StagedCellReconciler {
@@ -391,7 +383,7 @@ class StagedCellReconciler {
const cellId = maybeAddMarimoImport({
autoInstantiate: false,
- createNewCell: this.actions.createNewCell,
+ createCell: this.actions.createCell,
fromCellId: this.createdCells[0]?.cellId,
before: true,
});
diff --git a/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts b/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts
index c9af4ca375..6a4f50cb29 100644
--- a/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts
+++ b/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts
@@ -64,7 +64,7 @@ describe("EditNotebookTool", () => {
let cellId3: CellId;
let toolContext: {
addStagedCell: ReturnType<typeof vi.fn>;
- createNewCell: ReturnType<typeof vi.fn>;
+ createCell: ReturnType<typeof vi.fn>;
prepareForRun: ReturnType<typeof vi.fn>;
sendRun: ReturnType<typeof vi.fn>;
store: ReturnType<typeof getDefaultStore>;
@@ -81,7 +81,7 @@ describe("EditNotebookTool", () => {
const current = store.get(stagedAICellsAtom);
store.set(stagedAICellsAtom, new Map(current).set(cellId, edit));
}),
- createNewCell: vi.fn(),
+ createCell: vi.fn(),
prepareForRun: vi.fn(),
sendRun: vi.fn().mockResolvedValue(null),
store,
diff --git a/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts b/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts
index 014d107df2..ebc78f4dcc 100644
--- a/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts
+++ b/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts
@@ -29,7 +29,7 @@ describe("RunStaleCellsTool", () => {
let cellId3: CellId;
let toolContext: {
addStagedCell: ReturnType<typeof vi.fn>;
- createNewCell: ReturnType<typeof vi.fn>;
+ createCell: ReturnType<typeof vi.fn>;
prepareForRun: ReturnType<typeof vi.fn>;
sendRun: ReturnType<typeof vi.fn>;
store: ReturnType<typeof getDefaultStore>;
@@ -39,7 +39,7 @@ describe("RunStaleCellsTool", () => {
store = getDefaultStore();
toolContext = {
addStagedCell: vi.fn(),
- createNewCell: vi.fn(),
+ createCell: vi.fn(),
prepareForRun: vi.fn(),
sendRun: vi.fn().mockResolvedValue(null),
store,
diff --git a/frontend/src/core/ai/tools/base.ts b/frontend/src/core/ai/tools/base.ts
index 840ba89e00..37e1c7fbea 100644
--- a/frontend/src/core/ai/tools/base.ts
+++ b/frontend/src/core/ai/tools/base.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { z } from "zod";
-import type { CreateNewCellAction } from "@/core/cells/cells";
+import type { CreateCell } from "@/core/cells/actions";
import type { CellId } from "@/core/cells/ids";
import type { ExecuteCellsRequest } from "@/core/network/types";
import type { JotaiStore } from "@/core/state/jotai";
@@ -113,7 +113,7 @@ export interface ToolDescription {
export interface ToolNotebookContext {
store: JotaiStore;
addStagedCell: (payload: { cellId: CellId; edit: Edit }) => void;
- createNewCell: (payload: CreateNewCellAction) => void;
+ createCell: CreateCell;
prepareForRun: (payload: { cellId: CellId }) => void;
sendRun: (request: ExecuteCellsRequest) => Promise<null>;
}
diff --git a/frontend/src/core/ai/tools/edit-notebook-tool.ts b/frontend/src/core/ai/tools/edit-notebook-tool.ts
index cde445763b..2e7f1133ad 100644
--- a/frontend/src/core/ai/tools/edit-notebook-tool.ts
+++ b/frontend/src/core/ai/tools/edit-notebook-tool.ts
@@ -3,11 +3,8 @@
import type { EditorView } from "@codemirror/view";
import { z } from "zod";
import { scrollAndHighlightCell } from "@/components/editor/links/cell-link";
-import {
- type CellPosition as NotebookCellPosition,
- type NotebookState,
- notebookAtom,
-} from "@/core/cells/cells";
+import { type NotebookState, notebookAtom } from "@/core/cells/cells";
+import type { CreateCellOptions } from "@/core/cells/actions";
import { CellId } from "@/core/cells/ids";
import { prepareCellCodeUpdate } from "@/core/codemirror/language/cell-code";
import type { CellColumnId } from "@/utils/id-tree";
@@ -86,7 +83,7 @@ export class EditNotebookTool implements AiTool<
{ edit }: EditNotebookInput,
toolContext: ToolNotebookContext,
): Promise<ToolOutputBase> => {
- const { addStagedCell, createNewCell, store } = toolContext;
+ const { addStagedCell, createCell, store } = toolContext;
switch (edit.type) {
case "update_cell": {
@@ -155,8 +152,7 @@ export class EditNotebookTool implements AiTool<
case "add_cell": {
const { position, code } = edit;
- let notebookPosition: NotebookCellPosition = "__end__";
- let before = false;
+ let placement: CreateCellOptions = {};
const newCellId = CellId.create();
const notebook = store.get(notebookAtom);
@@ -186,11 +182,12 @@ export class EditNotebookTool implements AiTool<
}
this.validateCellIdExists(cellId, notebook);
- notebookPosition = cellId;
- before = position.before;
+ placement = position.before
+ ? { before: cellId }
+ : { after: cellId };
break;
}
- case "column_end": {
+ case "column_end":
if (!position.columnIndex) {
throw new ToolExecutionError(
"Column index is required for add_cell with column_end position",
@@ -203,21 +200,16 @@ export class EditNotebookTool implements AiTool<
);
}
- const columnId = this.getColumnId(position.columnIndex, notebook);
- notebookPosition = { type: "__end__", columnId };
+ placement = {
+ endOf: this.getColumnId(position.columnIndex, notebook),
+ };
break;
- }
+
case "notebook_end":
- // Use default: notebookPosition = "__end__"
break;
}
- createNewCell({
- cellId: notebookPosition,
- before,
- code,
- newCellId,
- });
+ createCell({ ...placement, code, id: newCellId });
addStagedCell({
cellId: newCellId,
diff --git a/frontend/src/core/cells/__tests__/actions.test.ts b/frontend/src/core/cells/__tests__/actions.test.ts
index 54e579727a..406a8ffa22 100644
--- a/frontend/src/core/cells/__tests__/actions.test.ts
+++ b/frontend/src/core/cells/__tests__/actions.test.ts
@@ -1,48 +1,488 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { MockNotebook } from "@/__mocks__/notebook";
-import { scrollAndHighlightCell } from "@/components/editor/links/cell-link";
-import { notebookAtom } from "@/core/cells/cells";
-import type { CellId } from "@/core/cells/ids";
-import { createCellRuntimeState } from "@/core/cells/types";
-import { store } from "@/core/state/jotai";
-import { notebookScrollToRunning } from "../actions";
-
-vi.mock("@/components/editor/links/cell-link", () => ({
- scrollAndHighlightCell: vi.fn(),
+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 type { CellIndex } from "@/utils/id-tree";
+import {
+ addSetupCellAtom,
+ createCellAtom,
+ deleteCellsAtom,
+ moveToNextCellAtom,
+ undoDeleteCellAtom,
+} from "../actions";
+import {
+ cellDataAtom,
+ cellHandleAtom,
+ exportedForTesting,
+ notebookAtom,
+ notebookReducer,
+} from "../cells";
+import { followDocument } from "../document";
+import { type CellId, SCRATCH_CELL_ID, SETUP_CELL_ID } from "../ids";
+import { focusAndScrollCellIntoView } from "../scrollCellIntoView";
+
+vi.mock("../scrollCellIntoView", () => ({
+ focusAndScrollCellIntoView: vi.fn(),
}));
-describe("notebookScrollToRunning", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- store.set(notebookAtom, MockNotebook.notebookState({ cellData: {} }));
+const c1 = cellId("c1");
+const c2 = cellId("c2");
+const c3 = cellId("c3");
+const stops: Array<() => void> = [];
+
+afterEach(() => {
+ for (const stop of stops.splice(0)) {
+ stop();
+ }
+ 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)),
+ };
+}
+
+describe("createCellAtom", () => {
+ it("creates a cell after another and focuses it once it mounts", () => {
+ const { store, order, notebook, cellIn } = setup();
+
+ const id = store.set(createCellAtom, { after: c1, code: "z = 3" });
+
+ expect(id).not.toBeNull();
+ expect(order()).toEqual([c1, id, c2]);
+ expect(cellIn(id as string)?.code).toBe("z = 3");
+ expect(notebook().scrollKey).toBe(id);
+ expect(notebook().cellRuntime[id as never]).toBeDefined();
+ });
+
+ it("appends to the first column by default", () => {
+ const { store, order } = setup();
+
+ const id = store.set(createCellAtom, {});
+
+ expect(order()).toEqual([c1, c2, id]);
+ });
+
+ it("keeps a focused hidden cell untouched until it is blurred", () => {
+ const { store, notebook } = setup();
+
+ const hidden = store.set(createCellAtom, {
+ after: c1,
+ config: { hide_code: true },
+ });
+ const unfocused = store.set(createCellAtom, {
+ after: c1,
+ config: { hide_code: true },
+ focus: false,
+ });
+
+ expect(notebook().untouchedNewCells.has(hidden as never)).toBe(true);
+ expect(notebook().untouchedNewCells.has(unfocused as never)).toBe(false);
+ expect(notebook().scrollKey).toBe(hidden);
+ });
+
+ it("names the column of a cell placed first in a later column", () => {
+ const { store, notebook, cellIn } = setup({
+ c2: cell("c2", "y = 2", { config: { ...CONFIG, column: 1 } }),
+ });
+
+ const id = store.set(createCellAtom, { before: c2 });
+
+ expect(cellIn(id as string)?.config.column).toBe(1);
+ expect(cellIn(c2)?.config.column).toBeNull();
+ expect(notebook().cellIds.atOrThrow(1).inOrderIds).toEqual([id, c2]);
+ expect(notebook().cellIds.atOrThrow(0).inOrderIds).toEqual([c1]);
+ });
+
+ it("places a cell in the column of its anchor, whatever config it carries", () => {
+ const { store, order, notebook, cellIn } = setup({
+ c2: cell("c2", "y = 2", { config: { ...CONFIG, column: 1 } }),
+ });
+
+ // A pasted cell carries the config of the cell it was copied from.
+ const id = store.set(createCellAtom, {
+ after: c2,
+ code: "z = 3",
+ config: { hide_code: true },
+ });
+
+ expect(order()).toEqual([c1, c2, id]);
+ expect(cellIn(id as string)?.config).toMatchObject({
+ hide_code: true,
+ column: null,
+ });
+ expect(notebook().cellIds.atOrThrow(1).inOrderIds).toEqual([c2, id]);
+ });
+
+ it("names the column when appending to an empty column", () => {
+ const { store, notebook, cellIn } = setup();
+ store.set(notebookAtom, (state) => ({
+ ...state,
+ cellIds: state.cellIds.addColumn(state.cellIds.atOrThrow(0).id),
+ }));
+ const empty = notebook().cellIds.atOrThrow(1).id;
+
+ const id = store.set(createCellAtom, { endOf: empty });
+
+ expect(cellIn(id as string)?.config.column).toBe(1);
+ expect(notebook().cellIds.atOrThrow(1).inOrderIds).toEqual([id]);
+ });
+
+ it("creates nothing when a cell already has the code", () => {
+ const { store, order } = setup();
+
+ const id = store.set(createCellAtom, {
+ code: "x = 1",
+ skipIfCodeExists: true,
+ });
+
+ expect(id).toBeNull();
+ expect(order()).toEqual([c1, c2]);
+ });
+
+ it("refuses without a document", () => {
+ const store = createStore();
+ store.set(notebookAtom, exportedForTesting.initialNotebookState());
+
+ expect(() => store.set(createCellAtom, {})).toThrow("no document");
+ });
+});
+
+describe("moveToNextCellAtom", () => {
+ it("focuses the neighbouring cell within the column", () => {
+ const { store, order } = setup();
+
+ store.set(moveToNextCellAtom, { cellId: c1, before: false });
+
+ expect(focusAndScrollCellIntoView).toHaveBeenCalledWith(
+ expect.objectContaining({ cellId: c2, codeFocus: "top" }),
+ );
+ expect(order()).toEqual([c1, c2]);
+ });
+
+ it("creates a cell past the edge of the column, unless told not to", () => {
+ const { store, order } = setup();
+
+ store.set(moveToNextCellAtom, { cellId: c2, before: false, create: false });
+ expect(order()).toEqual([c1, c2]);
+
+ store.set(moveToNextCellAtom, { cellId: c2, before: false });
+ expect(order()).toHaveLength(3);
+ expect(order().slice(0, 2)).toEqual([c1, c2]);
+ });
+
+ it("creates a cell before the first one", () => {
+ const { store, order } = setup();
+
+ store.set(moveToNextCellAtom, { cellId: c1, before: true });
+
+ expect(order()).toHaveLength(3);
+ expect(order().slice(1)).toEqual([c1, c2]);
+ });
+
+ it("leaves the scratchpad's focus alone", () => {
+ const { store, order } = setup();
+
+ store.set(moveToNextCellAtom, { cellId: SCRATCH_CELL_ID, before: false });
+
+ expect(focusAndScrollCellIntoView).not.toHaveBeenCalled();
+ expect(order()).toEqual([c1, c2]);
});
+});
- it("scrolls to the first running cell in notebook order", () => {
- const runtimeOnlyCellId = "runtime-only" as CellId;
- const idleCellId = "idle-cell" as CellId;
- const runningCellId = "running-cell" as CellId;
+describe("addSetupCellAtom", () => {
+ it("creates the setup cell at the top and focuses it", () => {
+ const { store, order, notebook, cellIn } = setup();
+
+ store.set(addSetupCellAtom, { code: "import marimo as mo" });
+
+ expect(order()[0]).toBe(SETUP_CELL_ID);
+ expect(cellIn(SETUP_CELL_ID)).toMatchObject({
+ name: "setup",
+ code: "import marimo as mo",
+ });
+ expect(notebook().scrollKey).toBe(SETUP_CELL_ID);
+ });
- const notebook = MockNotebook.notebookState({
- cellData: {
- [idleCellId]: {},
- [runningCellId]: {},
+ it("places the setup cell in an empty first column", () => {
+ const { store, notebook, cellIn } = setup({
+ c1: cell(c1, "x = 1", { config: { ...CONFIG, column: 1 } }),
+ });
+ expect(notebook().cellIds.atOrThrow(0).inOrderIds).toEqual([]);
+
+ store.set(addSetupCellAtom, { code: "import marimo as mo" });
+
+ expect(notebook().cellIds.atOrThrow(0).inOrderIds).toEqual([SETUP_CELL_ID]);
+ expect(cellIn(SETUP_CELL_ID)?.config.column).toBe(0);
+ expect(notebook().scrollKey).toBe(SETUP_CELL_ID);
+ });
+
+ it("only focuses a setup cell that exists", () => {
+ const { store, order, cellIn } = setup();
+ store.set(addSetupCellAtom, { code: "first" });
+
+ store.set(addSetupCellAtom, { code: "second" });
+
+ expect(order().filter((id) => id === SETUP_CELL_ID)).toHaveLength(1);
+ expect(cellIn(SETUP_CELL_ID)?.code).toBe("first");
+ });
+});
+
+describe("deleteCellsAtom", () => {
+ it("deletes a cell, focuses the one above, and remembers it", () => {
+ const { store, order, notebook } = setup();
+
+ expect(store.set(deleteCellsAtom, { cellIds: [c2] })).toBe(true);
+
+ expect(order()).toEqual([c1]);
+ expect(notebook().cellData[c2]).toBeUndefined();
+ expect(notebook().scrollKey).toBe(c1);
+ expect(notebook().history).toEqual([
+ {
+ type: "delete",
+ cells: [
+ {
+ cell: { id: c2, code: "y = 2", name: "_", config: CONFIG },
+ placement: { after: c1 },
+ serializedEditorState: null,
+ },
+ ],
},
- cellRuntime: {
- [idleCellId]: { status: "idle" },
- [runningCellId]: { status: "running" },
+ ]);
+ });
+
+ it("focuses the cell below when the first cell goes", () => {
+ const { store, notebook } = setup();
+
+ store.set(deleteCellsAtom, { cellIds: [c1] });
+
+ expect(notebook().scrollKey).toBe(c2);
+ expect(notebook().history[0]).toMatchObject({
+ cells: [{ placement: { before: c2 } }],
+ });
+ });
+
+ it("keeps the last cell", () => {
+ const { store, order, notebook } = setup();
+
+ expect(store.set(deleteCellsAtom, { cellIds: [c1, c2] })).toBe(true);
+ expect(order()).toEqual([c2]);
+
+ expect(store.set(deleteCellsAtom, { cellIds: [c2] })).toBe(false);
+ expect(order()).toEqual([c2]);
+ expect(notebook().history).toHaveLength(1);
+ });
+
+ it("skips cells the document does not have", () => {
+ const { store, order } = setup();
+
+ expect(store.set(deleteCellsAtom, { cellIds: [cellId("gone")] })).toBe(
+ false,
+ );
+
+ expect(order()).toEqual([c1, c2]);
+ });
+
+ it("names the column of a cell that followed a deleted column start", () => {
+ const { store, notebook, cellIn } = setup({
+ c2: cell("c2", "y = 2", { config: { ...CONFIG, column: 1 } }),
+ c3: cell("c3", "z = 3"),
+ });
+ expect(notebook().cellIds.atOrThrow(1).inOrderIds).toEqual([c2, c3]);
+
+ store.set(deleteCellsAtom, { cellIds: [c2] });
+
+ expect(cellIn(c3)?.config.column).toBe(1);
+ 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();
+ const id = store.set(createCellAtom, {
+ after: c1,
+ config: { hide_code: true },
+ }) as CellId;
+ const dataAtom = cellDataAtom(id);
+ const handleAtom = cellHandleAtom(id);
+
+ store.set(deleteCellsAtom, { cellIds: [id] });
+
+ expect(notebook().untouchedNewCells.has(id)).toBe(false);
+ expect(cellDataAtom(id)).not.toBe(dataAtom);
+ expect(cellHandleAtom(id)).not.toBe(handleAtom);
+ });
+});
+
+describe("undoDeleteCellAtom", () => {
+ it("brings a deleted cell back where it was, with its editor history", () => {
+ const { store, order, notebook, cellIn, mountEditor } = setup({
+ c3: cell("c3", "z = 3"),
+ });
+ const view = mountEditor(c2);
+ view.dispatch({ changes: { from: 0, insert: "# " } });
+ store.set(deleteCellsAtom, { cellIds: [c2] });
+ expect(order()).toEqual([c1, c3]);
+
+ store.set(undoDeleteCellAtom);
+
+ expect(order()).toEqual([c1, c2, c3]);
+ expect(cellIn(c2)?.code).toBe("y = 2");
+ expect(notebook().cellData[c2].serializedEditorState).toMatchObject({
+ doc: "y = 2",
+ });
+ expect(notebook().cellData[c2].edited).toBe(true);
+ expect(notebook().scrollKey).toBe(c2);
+ expect(notebook().history).toEqual([]);
+ });
+
+ it("restores the config and the id of the setup cell", () => {
+ const { store, order, cellIn } = setup({
+ [SETUP_CELL_ID]: cell(SETUP_CELL_ID, "import marimo as mo", {
+ name: "setup",
+ config: { ...CONFIG, hide_code: true, disabled: true },
+ }),
+ });
+ store.set(deleteCellsAtom, { cellIds: [SETUP_CELL_ID] });
+ expect(order()).toEqual([c1, c2]);
+
+ store.set(undoDeleteCellAtom);
+
+ expect(order()).toEqual([c1, c2, SETUP_CELL_ID]);
+ expect(cellIn(SETUP_CELL_ID)).toMatchObject({
+ name: "setup",
+ code: "import marimo as mo",
+ config: { hide_code: true, disabled: true },
+ });
+ });
+
+ it("restores every cell of one deletion at once, in order", () => {
+ const { store, order, notebook } = setup({ c3: cell("c3", "z = 3") });
+ store.set(deleteCellsAtom, { cellIds: [c1, c2] });
+ expect(order()).toEqual([c3]);
+ expect(notebook().history).toHaveLength(1);
+
+ store.set(undoDeleteCellAtom);
+
+ expect(order()).toEqual([c1, c2, c3]);
+ expect(notebook().history).toEqual([]);
+ });
+
+ it("undoes a move recorded in the history", () => {
+ const { store, model, order, notebook, dispatch } = 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 },
+ ],
},
});
- notebook.cellRuntime = {
- [runtimeOnlyCellId]: createCellRuntimeState({ status: "running" }),
- ...notebook.cellRuntime,
- };
- store.set(notebookAtom, notebook);
+ 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]);
+
+ store.set(undoDeleteCellAtom);
+ expect(order()).toEqual([c3, c1, c2]);
+
+ store.set(undoDeleteCellAtom);
+ expect(order()).toEqual([c1, c2, c3]);
+ expect(notebook().history).toEqual([]);
+ });
+
+ it("appends a restored cell whose anchor another client removed", () => {
+ const { store, order, notebook } = setup();
+ store.set(notebookAtom, (state) => ({
+ ...state,
+ history: [
+ {
+ type: "delete",
+ cells: [
+ {
+ cell: { id: "c9", code: "q = 9" },
+ placement: { after: cellId("gone") },
+ serializedEditorState: null,
+ },
+ ],
+ },
+ ],
+ }));
+
+ store.set(undoDeleteCellAtom);
+
+ expect(order()).toEqual([c1, c2, "c9"]);
+ expect(notebook().history).toEqual([]);
+ });
+
+ it("does nothing without history", () => {
+ const { store, order } = setup();
- notebookScrollToRunning();
+ store.set(undoDeleteCellAtom);
- expect(scrollAndHighlightCell).toHaveBeenCalledOnce();
- expect(scrollAndHighlightCell).toHaveBeenCalledWith(runningCellId, "focus");
+ expect(order()).toEqual([c1, c2]);
});
});
diff --git a/frontend/src/core/cells/__tests__/add-missing-import.test.ts b/frontend/src/core/cells/__tests__/add-missing-import.test.ts
index f6b4431cef..150c818a8d 100644
--- a/frontend/src/core/cells/__tests__/add-missing-import.test.ts
+++ b/frontend/src/core/cells/__tests__/add-missing-import.test.ts
@@ -107,35 +107,34 @@ describe("maybeAddMissingImport", () => {
}),
);
- const createNewCell = vi.fn();
+ const createCell = vi.fn();
const result = addImport({
autoInstantiate: false,
- createNewCell,
+ createCell,
fromCellId: Cell1,
before: false,
});
// Should not create a new cell since the import already exists
- expect(createNewCell).not.toHaveBeenCalled();
+ expect(createCell).not.toHaveBeenCalled();
expect(result).toBeNull();
}
});
it("should create a marimo import before the source cell when requested", () => {
- const createNewCell = vi.fn();
+ const createCell = vi.fn();
const result = maybeAddMarimoImport({
autoInstantiate: false,
- createNewCell,
+ createCell,
fromCellId: Cell2,
before: true,
});
expect(result).not.toBeNull();
- expect(createNewCell).toHaveBeenCalledWith(
+ expect(createCell).toHaveBeenCalledWith(
expect.objectContaining({
- cellId: Cell2,
- before: true,
+ before: Cell2,
code: "import marimo as mo",
}),
);
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 899091bba4..4382592580 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -4,6 +4,7 @@ import { python } from "@codemirror/lang-python";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { createStore } from "jotai";
+import { createRef } from "react";
import {
afterAll,
beforeAll,
@@ -17,11 +18,12 @@ import {
import { MockNotebook } from "@/__mocks__/notebook";
import { cellId } from "@/__tests__/branded";
import type { CellHandle } from "@/components/editor/notebook-cell";
-import { CellId, SCRATCH_CELL_ID, SETUP_CELL_ID } from "@/core/cells/ids";
+import { CellId, SCRATCH_CELL_ID } from "@/core/cells/ids";
import { foldAllBulk, unfoldAllBulk } from "@/core/codemirror/editing/commands";
import { adaptiveLanguageConfiguration } from "@/core/codemirror/language/extension";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
import type { OutputMessage } from "@/core/kernel/messages";
+import type { CellConfig } from "@/core/network/types";
import {
type CollapsibleTree,
MultiColumn,
@@ -39,7 +41,12 @@ import {
scrollToBottom,
scrollToTop,
} from "../scrollCellIntoView";
-import type { CellData } from "../types";
+import {
+ type CellData,
+ createCell,
+ createCellConfig,
+ createCellRuntimeState,
+} from "../types";
vi.mock("@/core/codemirror/editing/commands", () => ({
foldAllBulk: vi.fn(),
@@ -120,8 +127,7 @@ describe("cell reducer", () => {
let cells: ReturnType<typeof flattenTopLevelNotebookCells>;
let firstCellId: CellId;
- const actions = createActions((action) => {
- state = reducer(state, action);
+ const mountEditors = () => {
for (const [cellIdString, handle] of Object.entries(state.cellHandles)) {
// @ts-expect-error - Typescript Object.entries doesn't know that keys are CellId
const cid: CellId = cellIdString;
@@ -135,7 +141,76 @@ describe("cell reducer", () => {
}
}
cells = flattenTopLevelNotebookCells(state);
- });
+ };
+ const actions = createActions((action) => {
+ state = reducer(state, action);
+ mountEditors();
+ });
+
+ /** Put a cell into the notebook the way the document would. */
+ function seedCell({
+ cellId,
+ before,
+ code = "",
+ name,
+ config,
+ newCellId,
+ hideCode,
+ autoFocus = true,
+ }: {
+ cellId: CellId | "__end__" | { type: "__end__"; columnId: CellColumnId };
+ before: boolean;
+ code?: string;
+ name?: string;
+ config?: CellConfig;
+ newCellId?: CellId;
+ hideCode?: boolean;
+ autoFocus?: boolean;
+ }): CellId {
+ let column: CollapsibleTree<CellId>;
+ let cellIndex: number;
+ if (cellId === "__end__") {
+ column = state.cellIds.atOrThrow(0);
+ cellIndex = column.length;
+ } else if (typeof cellId === "string") {
+ column = state.cellIds.findWithId(cellId);
+ cellIndex = column.topLevelIds.indexOf(cellId);
+ } else {
+ column = state.cellIds.get(cellId.columnId) ?? state.cellIds.atOrThrow(0);
+ cellIndex = column.length;
+ }
+ const id = newCellId ?? CellId.create();
+ state = {
+ ...state,
+ cellIds: state.cellIds.insertId(
+ id,
+ column.id,
+ before ? cellIndex : cellIndex + 1,
+ ),
+ cellData: {
+ ...state.cellData,
+ [id]: createCell({
+ id,
+ code,
+ name,
+ config: createCellConfig({
+ ...config,
+ ...(hideCode != null && { hide_code: hideCode }),
+ }),
+ edited: Boolean(code),
+ }),
+ },
+ 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;
+ }
let i = 0;
const originalCreate = CellId.create.bind(CellId);
@@ -151,7 +226,7 @@ describe("cell reducer", () => {
state = initialNotebookState();
state.cellIds = MultiColumn.from([]);
- actions.createNewCell({ cellId: "__end__", before: false });
+ seedCell({ cellId: "__end__", before: false });
firstCellId = state.cellIds.inOrderIds[0];
});
@@ -159,181 +234,6 @@ describe("cell reducer", () => {
CellId.create = originalCreate;
});
- it("can add a cell after another cell", () => {
- actions.createNewCell({
- cellId: firstCellId,
- before: false,
- });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
-
- [1] ''
- "
- `);
- });
-
- it("can add a cell to the end with code", () => {
- actions.createNewCell({
- cellId: "__end__",
- code: "import numpy as np",
- before: false,
- });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
-
- [1] 'import numpy as np'
- "
- `);
-
- // Cell should be added to the end and edited
- expect(cells[1].code).toBe("import numpy as np");
- expect(cells[1].edited).toBe(true);
- expect(cells[1].lastCodeRun).toBe(null);
- });
-
- it("can add a cell before another cell", () => {
- actions.createNewCell({
- cellId: firstCellId,
- before: true,
- });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [1] ''
-
- [0] ''
- "
- `);
- });
-
- it("can add a cell with name and config", () => {
- actions.createNewCell({
- cellId: firstCellId,
- before: false,
- code: "x = 1",
- name: "My Cell",
- config: { hide_code: true, disabled: false },
- });
- const newCellId = state.cellIds.inOrderIds[1];
- expect(state.cellData[newCellId].name).toBe("My Cell");
- expect(state.cellData[newCellId].config.hide_code).toBe(true);
- expect(state.cellData[newCellId].config.disabled).toBe(false);
- });
-
- it("can delete a Python cell and undo delete", () => {
- actions.createNewCell({
- cellId: firstCellId,
- before: false,
- });
- actions.deleteCell({
- cellId: firstCellId,
- });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [1] ''
- "
- `);
-
- // undo
- actions.undoDeleteCell();
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [2] ''
-
- [1] ''
- "
- `);
-
- // Verify scrollKey is set to the restored cell
- expect(state.scrollKey).toBe("2");
- });
-
- it("can delete a SQL cell and undo delete", () => {
- actions.createNewCell({
- cellId: firstCellId,
- before: false,
- code: `df = mo.sql("""SELECT * FROM table""")`,
- });
- const newCellId = state.cellIds.getColumns()[0].atOrThrow(1);
- actions.deleteCell({
- cellId: newCellId,
- });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
- "
- `);
-
- // undo
- actions.undoDeleteCell();
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
-
- [2] 'df = mo.sql("""SELECT * FROM table""")'
- "
- `);
- });
-
- it("can delete a Markdown cell and undo delete", () => {
- const text = "The quick brown fox jumps over the lazy dog.";
- actions.createNewCell({
- cellId: firstCellId,
- before: false,
- code: `mo.md(r"""${text}""")`,
- });
- const newCellId = state.cellIds.getColumns()[0].atOrThrow(1);
- actions.deleteCell({
- cellId: newCellId,
- });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
- "
- `);
-
- // undo
- actions.undoDeleteCell();
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
-
- [2] 'mo.md(r"""The quick brown fox jumps over the lazy dog.""")'
- "
- `);
- });
-
- it("undo delete restores cell config (hide_code, disabled)", () => {
- actions.createNewCell({
- cellId: firstCellId,
- before: false,
- code: "x = 1",
- });
- const newCellId = state.cellIds.getColumns()[0].atOrThrow(1);
-
- // Set config to hidden and disabled
- actions.updateCellConfig({
- cellId: newCellId,
- config: { hide_code: true, disabled: true },
- });
- expect(state.cellData[newCellId].config.hide_code).toBe(true);
- expect(state.cellData[newCellId].config.disabled).toBe(true);
-
- // Delete the cell
- actions.deleteCell({ cellId: newCellId });
- expect(state.cellIds.inOrderIds).not.toContain(newCellId);
-
- // Undo delete
- actions.undoDeleteCell();
- const restoredCellId =
- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
-
- // Config should be preserved
- expect(state.cellData[restoredCellId].config.hide_code).toBe(true);
- expect(state.cellData[restoredCellId].config.disabled).toBe(true);
- });
-
it("can update a cell", () => {
actions.updateCellCode({
cellId: firstCellId,
@@ -348,7 +248,7 @@ describe("cell reducer", () => {
});
it("can move a cell", () => {
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
});
@@ -462,11 +362,11 @@ describe("cell reducer", () => {
});
it("can drag and drop a cell", () => {
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("1"),
before: false,
});
@@ -512,11 +412,11 @@ describe("cell reducer", () => {
});
it("can move a cell to an exact index within a column", () => {
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("1"),
before: false,
});
@@ -540,11 +440,11 @@ describe("cell reducer", () => {
});
it("can move a cell to an exact index across columns", () => {
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("1"),
before: false,
});
@@ -573,11 +473,11 @@ describe("cell reducer", () => {
});
it("moveCellToIndex is a no-op when moving to the same position", () => {
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("1"),
before: false,
});
@@ -595,7 +495,7 @@ describe("cell reducer", () => {
});
it("moveCellToIndex is a no-op for an invalid columnId", () => {
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
});
@@ -612,11 +512,11 @@ describe("cell reducer", () => {
});
it("can move multiple cells relative to target", () => {
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("1"),
before: false,
});
@@ -647,143 +547,6 @@ describe("cell reducer", () => {
`);
});
- it("can undo cut-paste (move with previousPlacements)", () => {
- actions.createNewCell({
- cellId: firstCellId,
- before: false,
- });
- actions.createNewCell({
- cellId: cellId("1"),
- before: false,
- });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
-
- [1] ''
-
- [2] ''
- "
- `);
-
- const col = state.cellIds.findWithId(firstCellId);
- const previousPlacements = [
- {
- columnId: col.id,
- index: col.indexOfOrThrow(
- firstCellId,
- ) as import("@/utils/id-tree").CellIndex,
- },
- {
- columnId: col.id,
- index: col.indexOfOrThrow(
- cellId("1"),
- ) as import("@/utils/id-tree").CellIndex,
- },
- ];
-
- actions.moveCellsRelativeTo({
- cellIds: [firstCellId, cellId("1")],
- targetCellId: cellId("2"),
- position: "after",
- previousPlacements,
- });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [2] ''
-
- [0] ''
-
- [1] ''
- "
- `);
-
- actions.undoDeleteCell();
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
-
- [1] ''
-
- [2] ''
- "
- `);
- });
-
- it("undo order: cut-paste then delete — first undo restores delete, second undo undoes move", () => {
- actions.createNewCell({
- cellId: firstCellId,
- before: false,
- });
- actions.createNewCell({
- cellId: cellId("1"),
- before: false,
- });
-
- const col = state.cellIds.findWithId(firstCellId);
- const previousPlacements = [
- {
- columnId: col.id,
- index: col.indexOfOrThrow(
- firstCellId,
- ) as import("@/utils/id-tree").CellIndex,
- },
- {
- columnId: col.id,
- index: col.indexOfOrThrow(
- cellId("1"),
- ) as import("@/utils/id-tree").CellIndex,
- },
- ];
-
- actions.moveCellsRelativeTo({
- cellIds: [firstCellId, cellId("1")],
- targetCellId: cellId("2"),
- position: "after",
- previousPlacements,
- });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [2] ''
-
- [0] ''
-
- [1] ''
- "
- `);
-
- actions.deleteCell({ cellId: cellId("2") });
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
-
- [1] ''
- "
- `);
-
- actions.undoDeleteCell();
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [3] ''
-
- [0] ''
-
- [1] ''
- "
- `);
-
- actions.undoDeleteCell();
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] ''
-
- [1] ''
-
- [3] ''
- "
- `);
- });
-
it("keeps error evidence after an edit and a new queued run", () => {
const code = "raise ValueError('old failure')";
const output: OutputMessage = {
@@ -1167,7 +930,7 @@ describe("cell reducer", () => {
formattingChange: false,
});
// Add cell
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
});
@@ -1272,33 +1035,6 @@ describe("cell reducer", () => {
expect(cell.edited).toBe(false);
});
- it("can update a cells config", () => {
- const firstCellId = cells[0].id;
- let cell = cells[0];
- // Starts empty
- expect(cell.config).toEqual({
- disabled: false,
- hide_code: false,
- column: null,
- expand_output: false,
- });
-
- actions.updateCellConfig({
- cellId: firstCellId,
- config: { disabled: true },
- });
- cell = cells[0];
- expect(cell.config.disabled).toBe(true);
-
- // Revert
- actions.updateCellConfig({
- cellId: firstCellId,
- config: { disabled: false },
- });
- cell = cells[0];
- expect(cell.config.disabled).toBe(false);
- });
-
it("can run a stopped cell", () => {
// Update code of first cell
actions.updateCellCode({
@@ -1704,8 +1440,8 @@ describe("cell reducer", () => {
});
it("can send a cell to the top", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
actions.sendToTop({ cellId: cellId("2") });
expect(formatCells(state)).toMatchInlineSnapshot(`
"
@@ -1719,8 +1455,8 @@ describe("cell reducer", () => {
});
it("can send a cell to the bottom", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
actions.sendToBottom({ cellId: firstCellId });
expect(formatCells(state)).toMatchInlineSnapshot(`
"
@@ -1734,8 +1470,8 @@ describe("cell reducer", () => {
});
it("can focus cells", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
actions.focusCell({ cellId: cellId("1"), where: "before" });
expect(focusAndScrollCellIntoView).toHaveBeenCalledWith(
@@ -1751,11 +1487,6 @@ describe("cell reducer", () => {
expect(scrollToBottom).toHaveBeenCalled();
});
- it("can update cell name", () => {
- actions.updateCellName({ cellId: firstCellId, name: "Test Cell" });
- expect(state.cellData[firstCellId].name).toBe("Test Cell");
- });
-
it("can fold and unfold all cells", () => {
actions.foldAll();
expect(foldAllBulk).toHaveBeenCalled();
@@ -1784,13 +1515,13 @@ describe("cell reducer", () => {
});
it("can collapse and expand cells", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({
cellId: cellId("1"),
before: false,
code: "# Header",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("2"),
before: false,
code: "## Subheader",
@@ -1812,13 +1543,13 @@ describe("cell reducer", () => {
});
it("can collapse and expand all cells in multiple columns", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({
cellId: cellId("1"),
before: false,
code: "# First Column Header",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("2"),
before: false,
code: "## First Column Subheader",
@@ -1826,12 +1557,12 @@ describe("cell reducer", () => {
actions.addColumnBreakpoint({ cellId: cellId("2") });
- actions.createNewCell({
+ seedCell({
cellId: cellId("3"),
before: false,
code: "# Second Column Header",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("4"),
before: false,
code: "## Second Column Subheader",
@@ -1879,18 +1610,18 @@ describe("cell reducer", () => {
});
it("can collapse and expand nested cells in one call", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({
cellId: cellId("1"),
before: false,
code: "# Header",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("2"),
before: false,
code: "## Subheader",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("3"),
before: false,
code: "### Subsubheader",
@@ -1934,18 +1665,18 @@ describe("cell reducer", () => {
});
it("can collapse all cells when nested heading ranges end at the same cell", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({
cellId: cellId("1"),
before: false,
code: "# Header",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("2"),
before: false,
code: "## Subheader",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("3"),
before: false,
code: "### Subsubheader",
@@ -1999,23 +1730,23 @@ describe("cell reducer", () => {
});
it("can collapse all cells when a deep chain is followed by a later section", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({
cellId: cellId("1"),
before: false,
code: "# Header",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("2"),
before: false,
code: "## Section A",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("3"),
before: false,
code: "### Sub of A",
});
- actions.createNewCell({
+ seedCell({
cellId: cellId("4"),
before: false,
code: "## Section B",
@@ -2078,8 +1809,8 @@ describe("cell reducer", () => {
});
it("can show hidden cells", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
actions.collapseCell({ cellId: firstCellId });
actions.showCellIfHidden({ cellId: cellId("1") });
@@ -2089,7 +1820,7 @@ describe("cell reducer", () => {
});
it("can split and undo split cells", () => {
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
code: "line1\nline2",
@@ -2156,9 +1887,9 @@ describe("cell reducer", () => {
});
it("can add a column breakpoint", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
- actions.createNewCell({ cellId: cellId("2"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: cellId("2"), before: false });
expect(state.cellIds.getColumns().length).toBe(1);
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -2203,16 +1934,16 @@ describe("cell reducer", () => {
it("cannot add a column breakpoint before the first cell", () => {
expect(state.cellIds.getColumns().length).toBe(1);
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
actions.addColumnBreakpoint({ cellId: firstCellId });
expect(state.cellIds.getColumns().length).toBe(1);
});
it("can delete a column", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
- actions.createNewCell({ cellId: cellId("2"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: cellId("2"), before: false });
actions.addColumnBreakpoint({ cellId: cellId("2") });
expect(state.cellIds.getColumns().length).toBe(2);
@@ -2256,8 +1987,8 @@ describe("cell reducer", () => {
});
it("deleting the last column does nothing", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
const initialState = { ...state };
@@ -2268,9 +1999,9 @@ describe("cell reducer", () => {
});
it("can drop a cell over another cell", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
- actions.createNewCell({ cellId: cellId("2"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: cellId("2"), before: false });
expect(formatCells(state)).toMatchInlineSnapshot(`
"
@@ -2303,8 +2034,8 @@ describe("cell reducer", () => {
});
it("can drop a cell over a new column", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
expect(state.cellIds.getColumns().length).toBe(1);
expect(formatCells(state)).toMatchInlineSnapshot(`
@@ -2341,9 +2072,9 @@ describe("cell reducer", () => {
});
it("can drop a column over another column", () => {
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
- actions.createNewCell({ cellId: cellId("2"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: cellId("2"), before: false });
actions.addColumnBreakpoint({ cellId: cellId("2") });
expect(state.cellIds.getColumns().length).toBe(2);
@@ -2394,8 +2125,8 @@ describe("cell reducer", () => {
it("can compact columns", () => {
// Create initial state with 3 columns, including an empty one
- actions.createNewCell({ cellId: firstCellId, before: false });
- actions.createNewCell({ cellId: cellId("1"), before: false });
+ seedCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: cellId("1"), before: false });
actions.addColumnBreakpoint({ cellId: cellId("1") });
actions.addColumnBreakpoint({ cellId: cellId("2") });
actions.dropOverNewColumn({ cellId: cellId("2") });
@@ -2534,7 +2265,7 @@ describe("cell reducer", () => {
it("can clear output of all cells", () => {
// Create multiple cells with output
- actions.createNewCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: firstCellId, before: false });
const secondCellId = state.cellIds.atOrThrow(FIRST_COLUMN).atOrThrow(1);
// Add output to both cells
@@ -2581,121 +2312,9 @@ describe("cell reducer", () => {
expect(state.cellRuntime[secondCellId].consoleOutputs).toEqual([]);
});
- it("skips creating new cell if code exists and skipIfCodeExists is true", () => {
- // Add initial cell with code
- actions.updateCellCode({
- cellId: firstCellId,
- code: "import numpy as np",
- formattingChange: false,
- });
-
- // Try to create new cell with same code and skipIfCodeExists
- actions.createNewCell({
- cellId: "__end__",
- code: "import numpy as np",
- before: false,
- skipIfCodeExists: true,
- });
-
- // Should still only have one cell
- expect(state.cellIds.inOrderIds.length).toBe(1);
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] 'import numpy as np'
- "
- `);
-
- // Verify we can still add cell with different code
- actions.createNewCell({
- cellId: "__end__",
- code: "import pandas as pd",
- before: false,
- skipIfCodeExists: true,
- });
-
- expect(state.cellIds.inOrderIds.length).toBe(2);
- expect(formatCells(state)).toMatchInlineSnapshot(`
- "
- [0] 'import numpy as np'
-
- [1] 'import pandas as pd'
- "
- `);
- });
-
- it("can create and noop-update a setup cell", () => {
- // Create the setup cell
- actions.addSetupCellIfDoesntExist({ code: "# Setup code" });
-
- // Check that setup cell was created
- expect(state.cellData[SETUP_CELL_ID].id).toBe(SETUP_CELL_ID);
- expect(state.cellData[SETUP_CELL_ID].name).toBe("setup");
- expect(state.cellData[SETUP_CELL_ID].code).toBe("# Setup code");
- expect(state.cellData[SETUP_CELL_ID].edited).toBe(true);
- expect(state.cellIds.inOrderIds).toContain(SETUP_CELL_ID);
-
- // Update the setup cell
- actions.addSetupCellIfDoesntExist({ code: "# Updated setup code" });
-
- // Check that the setup cell did not change, since it already exists
- expect(state.cellData[SETUP_CELL_ID].code).toBe("# Setup code");
- expect(state.cellData[SETUP_CELL_ID].edited).toBe(true);
- expect(state.cellIds.inOrderIds).toContain(SETUP_CELL_ID);
- });
-
- it("can delete and undelete the setup cell", () => {
- // Create the setup cell
- actions.addSetupCellIfDoesntExist({ code: "# Setup code" });
-
- // Check that setup cell was created
- expect(state.cellData[SETUP_CELL_ID].id).toBe(SETUP_CELL_ID);
- expect(state.cellData[SETUP_CELL_ID].name).toBe("setup");
- expect(state.cellData[SETUP_CELL_ID].code).toBe("# Setup code");
- expect(state.cellData[SETUP_CELL_ID].edited).toBe(true);
- expect(state.cellIds.inOrderIds).toContain(SETUP_CELL_ID);
-
- // Delete the setup cell
- actions.deleteCell({ cellId: SETUP_CELL_ID });
-
- // Check that setup cell was deleted
- expect(state.cellData[SETUP_CELL_ID]).toBeDefined(); // we keep old state
- expect(state.cellIds.inOrderIds).not.toContain(SETUP_CELL_ID);
-
- // Undo delete the setup cell
- actions.undoDeleteCell();
-
- // Check that setup cell was restored
- expect(state.cellData[SETUP_CELL_ID].id).toBe(SETUP_CELL_ID);
- expect(state.cellData[SETUP_CELL_ID].name).toBe("setup");
- expect(state.cellData[SETUP_CELL_ID].code).toBe("# Setup code");
- expect(state.cellData[SETUP_CELL_ID].edited).toBe(true);
- expect(state.cellIds.inOrderIds).toContain(SETUP_CELL_ID);
-
- // Verify scrollKey is set to the restored setup cell
- expect(state.scrollKey).toBe(SETUP_CELL_ID);
- });
-
- it("can delete and then create a new setup cell", () => {
- // Create the setup cell
- actions.addSetupCellIfDoesntExist({ code: "# Setup code" });
-
- // Delete the setup cell
- actions.deleteCell({ cellId: SETUP_CELL_ID });
-
- // Create a new setup cell
- actions.addSetupCellIfDoesntExist({ code: "# New code" });
-
- // Check that the new setup cell was created
- expect(state.cellData[SETUP_CELL_ID].id).toBe(SETUP_CELL_ID);
- expect(state.cellData[SETUP_CELL_ID].name).toBe("setup");
- expect(state.cellData[SETUP_CELL_ID].code).toBe("# New code");
- expect(state.cellData[SETUP_CELL_ID].edited).toBe(true);
- expect(state.cellIds.inOrderIds).toContain(SETUP_CELL_ID);
- });
-
it("can clear all outputs", () => {
// Add a cell and give it output
- actions.createNewCell({
+ seedCell({
cellId: firstCellId,
before: false,
});
@@ -2723,202 +2342,14 @@ describe("cell reducer", () => {
expect(state.cellRuntime[cell2Id].output).toBeNull();
});
- describe("moveToNextCell", () => {
- let cell1Id: CellId;
- let cell2Id: CellId;
- let cell3Id: CellId;
-
- beforeEach(() => {
- // Create a few cells to work with
- actions.createNewCell({ cellId: "__end__", before: false });
- actions.createNewCell({ cellId: "__end__", before: false });
-
- cell1Id = state.cellIds.inOrderIds[0];
- cell2Id = state.cellIds.inOrderIds[1];
- cell3Id = state.cellIds.inOrderIds[2];
- });
-
- it("creates new cell when moving after last cell with noCreate=false", () => {
- const initialCellCount = state.cellIds.inOrderIds.length;
-
- actions.moveToNextCell({
- cellId: cell3Id,
- before: false,
- noCreate: false,
- });
-
- expect(state.cellIds.inOrderIds.length).toBe(initialCellCount + 1);
- });
-
- it("creates new cell when moving before first cell with noCreate=false", () => {
- const initialCellCount = state.cellIds.inOrderIds.length;
-
- actions.moveToNextCell({
- cellId: cell1Id,
- before: true,
- noCreate: false,
- });
-
- expect(state.cellIds.inOrderIds.length).toBe(initialCellCount + 1);
- });
-
- it("does not create new cell when moving after last cell with noCreate=true", () => {
- const initialCellCount = state.cellIds.inOrderIds.length;
- const initialState = { ...state };
-
- actions.moveToNextCell({
- cellId: cell3Id,
- before: false,
- noCreate: true,
- });
-
- // Should not create a new cell
- expect(state.cellIds.inOrderIds.length).toBe(initialCellCount);
- // Should not crash or throw an error
- expect(state.cellIds.inOrderIds).toEqual(initialState.cellIds.inOrderIds);
- });
-
- it("does not create new cell when moving before first cell with noCreate=true", () => {
- const initialCellCount = state.cellIds.inOrderIds.length;
- const initialState = { ...state };
-
- actions.moveToNextCell({ cellId: cell1Id, before: true, noCreate: true });
-
- // Should not create a new cell
- expect(state.cellIds.inOrderIds.length).toBe(initialCellCount);
- // Should not crash or throw an error
- expect(state.cellIds.inOrderIds).toEqual(initialState.cellIds.inOrderIds);
- });
-
- it("focuses next cell when moving within bounds", () => {
- const focusSpy = vi.mocked(focusAndScrollCellIntoView);
- focusSpy.mockClear();
-
- actions.moveToNextCell({
- cellId: cell1Id,
- before: false,
- noCreate: true,
- });
-
- expect(focusSpy).toHaveBeenCalledWith({
- cellId: cell2Id,
- cell: state.cellHandles[cell2Id],
- isCodeHidden: false,
- codeFocus: "top",
- variableName: undefined,
- });
- });
-
- it("focuses previous cell when moving backward within bounds", () => {
- const focusSpy = vi.mocked(focusAndScrollCellIntoView);
- focusSpy.mockClear();
-
- actions.moveToNextCell({ cellId: cell2Id, before: true, noCreate: true });
-
- expect(focusSpy).toHaveBeenCalledWith({
- cellId: cell1Id,
- cell: state.cellHandles[cell1Id],
- isCodeHidden: false,
- codeFocus: "bottom",
- variableName: undefined,
- });
- });
-
- it("does not move focus from scratch cell", () => {
- const focusSpy = vi.mocked(focusAndScrollCellIntoView);
- focusSpy.mockClear();
- const initialState = { ...state };
-
- actions.moveToNextCell({
- cellId: SCRATCH_CELL_ID,
- before: false,
- noCreate: false,
- });
-
- expect(focusSpy).not.toHaveBeenCalled();
- expect(state.cellIds.inOrderIds).toEqual(initialState.cellIds.inOrderIds);
- });
- });
-
describe("untouched cells functionality", () => {
it("starts with empty untouchedNewCells set", () => {
expect(state.untouchedNewCells).toEqual(new Set());
});
- it("can create a new cell with hideCode option", () => {
- const initialCellCount = state.cellIds.inOrderIds.length;
-
- actions.createNewCell({
- cellId: "__end__",
- before: false,
- hideCode: true,
- });
-
- expect(state.cellIds.inOrderIds.length).toBe(initialCellCount + 1);
- const newCellId =
- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
- expect(state.untouchedNewCells.has(newCellId)).toBe(true);
- });
-
- it("adds interactively-created hidden cell with boilerplate code to untouchedNewCells", () => {
- // Markdown cells are created with hideCode and non-empty default code
- // (e.g. `mo.md(r"""\n""")`). They are user-initiated, so their editor
- // should be shown until first blur.
- actions.createNewCell({
- cellId: "__end__",
- before: false,
- code: 'mo.md(r"""\n""")',
- hideCode: true,
- autoFocus: true,
- });
-
- const newCellId =
- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
- expect(state.untouchedNewCells.has(newCellId)).toBe(true);
- });
-
- it("does not add programmatically-created hidden cell with code to untouchedNewCells", () => {
- // Cells created by the kernel (e.g. via code_mode) carry code and
- // autoFocus=false; their hide_code must take effect immediately.
- actions.createNewCell({
- cellId: "__end__",
- before: false,
- code: "x = 1",
- hideCode: true,
- autoFocus: false,
- });
-
- const newCellId =
- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
- expect(state.untouchedNewCells.has(newCellId)).toBe(false);
- });
-
- it("does not add cell to untouchedNewCells when hideCode is false", () => {
- actions.createNewCell({
- cellId: "__end__",
- before: false,
- hideCode: false,
- });
-
- const newCellId =
- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
- expect(state.untouchedNewCells.has(newCellId)).toBe(false);
- });
-
- it("does not add cell to untouchedNewCells when hideCode is undefined", () => {
- actions.createNewCell({
- cellId: "__end__",
- before: false,
- });
-
- const newCellId =
- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
- expect(state.untouchedNewCells.has(newCellId)).toBe(false);
- });
-
it("can mark a cell as touched", () => {
// Create a cell with hideCode
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: true,
@@ -2936,7 +2367,7 @@ describe("cell reducer", () => {
it("markTouched is idempotent", () => {
// Create a cell with hideCode
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: true,
@@ -2966,17 +2397,17 @@ describe("cell reducer", () => {
it("can handle multiple untouched cells", () => {
// Create multiple cells with hideCode
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: true,
});
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: true,
});
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: false,
@@ -3001,12 +2432,12 @@ describe("cell reducer", () => {
it("preserves untouched state when cells are moved", () => {
// Create cells with hideCode
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: true,
});
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: true,
@@ -3030,58 +2461,9 @@ describe("cell reducer", () => {
expect(state.untouchedNewCells.has(cell2Id)).toBe(true);
});
- it("does not remove untouched state when cell is deleted", () => {
- // We could implement this, but it doesn't actually affect downstream behavior.
- // It is easier to leave it, so `undo` works as expected.
-
- // Create a cell with hideCode
- actions.createNewCell({
- cellId: "__end__",
- before: false,
- hideCode: true,
- });
-
- const newCellId =
- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
- expect(state.untouchedNewCells.has(newCellId)).toBe(true);
-
- // Delete the cell
- actions.deleteCell({ cellId: newCellId });
-
- // Does not actually remove untouched state
- expect(state.untouchedNewCells.has(newCellId)).toBe(true);
- });
-
- it("restores untouched state when cell deletion is undone", () => {
- // Create a cell with hideCode
- actions.createNewCell({
- cellId: "__end__",
- before: false,
- hideCode: true,
- });
-
- const newCellId =
- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
- expect(state.untouchedNewCells.has(newCellId)).toBe(true);
-
- // Delete the cell
- actions.deleteCell({ cellId: newCellId });
- // Still exists in untouchedNewCells
- expect(state.untouchedNewCells.has(newCellId)).toBe(true);
-
- // Undo the deletion
- actions.undoDeleteCell();
-
- // The cell should be restored but no longer untouched
- // (this is expected behavior - undoing doesn't restore untouched state)
- const restoredCellId =
- state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
- expect(state.untouchedNewCells.has(restoredCellId)).toBe(false);
- });
-
it("untouched cell behavior with hide_code config", () => {
// Create a cell with hideCode and hide_code config
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: true,
@@ -3090,11 +2472,11 @@ describe("cell reducer", () => {
const newCellId =
state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];
- // Update the cell config to hide code
- actions.updateCellConfig({
- cellId: newCellId,
- config: { hide_code: true },
- });
+ // 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);
@@ -3113,7 +2495,7 @@ describe("cell reducer", () => {
it("can mark an existing cell as untouched", () => {
// Create a cell without hideCode (not in untouchedNewCells)
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: false,
@@ -3131,7 +2513,7 @@ describe("cell reducer", () => {
it("markUntouched is idempotent", () => {
// Create a cell without hideCode
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: false,
@@ -3151,7 +2533,7 @@ describe("cell reducer", () => {
it("markUntouched does not affect already untouched cells", () => {
// Create a cell with hideCode (already in untouchedNewCells)
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: true,
@@ -3169,7 +2551,7 @@ describe("cell reducer", () => {
it("markTouched and markUntouched can toggle cell state", () => {
// Create a cell without hideCode
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: false,
@@ -3197,7 +2579,7 @@ describe("cell reducer", () => {
it("markUntouched works for markdown cell conversion scenario", () => {
// Simulates converting a Python cell to Markdown
// 1. Create a regular cell (no hideCode)
- actions.createNewCell({
+ seedCell({
cellId: "__end__",
before: false,
hideCode: false,
@@ -3211,11 +2593,12 @@ describe("cell reducer", () => {
expect(state.untouchedNewCells.has(cellId)).toBe(false);
expect(exportedForTesting.isCellCodeHidden(state, cellId)).toBe(false);
- // 2. Convert to markdown: set hide_code and mark as untouched
- actions.updateCellConfig({
- cellId,
- config: { hide_code: true },
- });
+ // 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)
@@ -3237,7 +2620,7 @@ describe("cell reducer", () => {
const { cellDataAtom, cellRuntimeAtom, cellHandleAtom } =
exportedForTesting;
- actions.createNewCell({ cellId: firstCellId, before: false });
+ seedCell({ cellId: firstCellId, before: false });
const newCellId = state.cellIds.inOrderIds[1];
const dataAtom1 = cellDataAtom(newCellId);
@@ -3253,31 +2636,6 @@ describe("cell reducer", () => {
expect(runtimeAtom2).toBe(runtimeAtom1);
expect(handleAtom2).toBe(handleAtom1);
});
-
- it("cleans up atom family cache when cells are deleted", () => {
- const { cellDataAtom, cellRuntimeAtom, cellHandleAtom } =
- exportedForTesting;
-
- actions.createNewCell({ cellId: firstCellId, before: false });
- const newCellId = state.cellIds.inOrderIds[1];
-
- // Access to create cache entries
- const dataAtom1 = cellDataAtom(newCellId);
- const runtimeAtom1 = cellRuntimeAtom(newCellId);
- const handleAtom1 = cellHandleAtom(newCellId);
-
- // Triggers purge
- actions.deleteCell({ cellId: newCellId });
-
- // Access again (should be new instances after cleanup)
- const dataAtom2 = cellDataAtom(newCellId);
- const runtimeAtom2 = cellRuntimeAtom(newCellId);
- const handleAtom2 = cellHandleAtom(newCellId);
-
- expect(dataAtom2).not.toBe(dataAtom1);
- expect(runtimeAtom2).not.toBe(runtimeAtom1);
- expect(handleAtom2).not.toBe(handleAtom1);
- });
});
});
diff --git a/frontend/src/core/cells/__tests__/document.test.ts b/frontend/src/core/cells/__tests__/document.test.ts
index 0b77940d24..3c99fabccc 100644
--- a/frontend/src/core/cells/__tests__/document.test.ts
+++ b/frontend/src/core/cells/__tests__/document.test.ts
@@ -107,9 +107,10 @@ describe("applyDocument", () => {
expect(state.cellData[a]).toMatchObject({
code: "a = 1",
name: "_",
- edited: false,
+ edited: true,
lastCodeRun: null,
});
+ expect(state.cellData[b].edited).toBe(false);
expect(state.cellRuntime[a]).toBeDefined();
expect(state.cellHandles[a]).toBeDefined();
expect(state.cellData[SCRATCH_CELL_ID]).toBeDefined();
@@ -190,7 +191,7 @@ describe("applyDocument", () => {
expect(next.cellData[a]).toMatchObject({
name: "renamed",
config: { hide_code: true },
- edited: false,
+ edited: true,
});
});
@@ -282,45 +283,14 @@ describe("documentEditMiddleware", () => {
store.set(activeDocumentModelAtom, null);
});
- it("creates a cell at the end without setting the order", () => {
- actions.createNewCell({
- cellId: c,
- before: false,
- code: "d = 1",
- newCellId: d,
- });
-
- expect(calls.map((call) => call[0])).toEqual(["createCell"]);
- expect(calls[0][1]).toMatchObject({ id: d, code: "d = 1" });
- });
-
- it("creates a cell elsewhere and sets the order", () => {
- actions.createNewCell({ cellId: a, before: true, newCellId: d });
-
- expect(calls.map((call) => call[0])).toEqual(["createCell", "setOrder"]);
- expect(calls[1][1]).toEqual([d, a, b, c]);
- });
-
- it("deletes a cell", () => {
- actions.deleteCell({ cellId: b });
-
- expect(calls).toEqual([["deleteCell", b]]);
- });
-
- it("writes code, name, and config", () => {
+ it("writes code", () => {
actions.updateCellCode({
cellId: a,
code: "a = 2",
formattingChange: false,
});
- actions.updateCellName({ cellId: a, name: "first" });
- actions.updateCellConfig({ cellId: a, config: { hide_code: true } });
- expect(calls).toEqual([
- ["setCode", a, "a = 2"],
- ["setName", a, "first"],
- ["updateConfig", a, { hide_code: true }],
- ]);
+ expect(calls).toEqual([["setCode", a, "a = 2"]]);
});
it("sets the order when a cell moves", () => {
diff --git a/frontend/src/core/cells/__tests__/notebook-outline.test.ts b/frontend/src/core/cells/__tests__/notebook-outline.test.ts
index febb375e0f..412cfeaf0b 100644
--- a/frontend/src/core/cells/__tests__/notebook-outline.test.ts
+++ b/frontend/src/core/cells/__tests__/notebook-outline.test.ts
@@ -4,6 +4,7 @@ import { createStore } from "jotai";
import { describe, expect, it, vi } from "vitest";
import { MockNotebook } from "@/__mocks__/notebook";
import { cellId } from "@/__tests__/branded";
+import { CONFIG } from "@/core/notebook/document/__tests__/fixtures";
import {
createNotebookActions,
notebookAtom,
@@ -84,7 +85,12 @@ describe("notebookOutline", () => {
items: [...secondOutline.items, ...firstOutline.items],
});
- actions.deleteCell({ cellId: second });
+ actions.reconcileDocument({
+ order: [first],
+ cells: new Map([
+ [first, { id: first, code: "x = 1", name: "_", config: CONFIG }],
+ ]),
+ });
expect(store.get(notebookOutline)).toEqual(firstOutline);
});
diff --git a/frontend/src/core/cells/__tests__/outputs.test.tsx b/frontend/src/core/cells/__tests__/outputs.test.tsx
index 8475b8825f..f81a95c70f 100644
--- a/frontend/src/core/cells/__tests__/outputs.test.tsx
+++ b/frontend/src/core/cells/__tests__/outputs.test.tsx
@@ -2,116 +2,134 @@
import { act, renderHook } from "@testing-library/react";
import { createStore, Provider } from "jotai";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { MockNotebook } from "@/__mocks__/notebook";
-import { notebookAtom } from "@/core/cells/cells";
+import { afterEach, describe, expect, it } from "vitest";
+import { mockDocumentModel } from "@/__mocks__/document";
import { CellId } from "@/core/cells/ids";
+import { DocumentProvider } from "@/core/notebook/document";
+import {
+ cell,
+ CONFIG,
+ document as documentOf,
+ withCells,
+} from "@/core/notebook/document/__tests__/fixtures";
import { type AppMode, viewStateAtom } from "@/core/mode";
import { useExpandedConsoleOutput, useExpandedOutput } from "../outputs";
-const saveCellConfig = vi.fn().mockResolvedValue(null);
+const stops: Array<() => void> = [];
-vi.mock("@/core/network/requests", () => ({
- getRequestClient: () => ({ saveCellConfig }),
-}));
+afterEach(() => {
+ for (const stop of stops.splice(0)) {
+ stop();
+ }
+});
function setup(opts: { mode: AppMode; expandOutput?: boolean }) {
const cellId = CellId.create();
const store = createStore();
- store.set(
- notebookAtom,
- MockNotebook.notebookState({
- cellData: {
- [cellId]: { config: { expand_output: opts.expandOutput ?? false } },
+ const { model, stop } = mockDocumentModel(
+ store,
+ withCells(
+ documentOf(),
+ {
+ c1: null,
+ c2: null,
+ [cellId]: cell(cellId, "", {
+ config: { ...CONFIG, expand_output: opts.expandOutput ?? false },
+ }),
},
- }),
+ [cellId],
+ ),
);
+ stops.push(stop);
store.set(viewStateAtom, { mode: opts.mode, cellAnchor: null });
- const { result } = renderHook(() => useExpandedOutput(cellId), {
- wrapper: ({ children }) => <Provider store={store}>{children}</Provider>,
- });
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <Provider store={store}>
+ <DocumentProvider model={model}>{children}</DocumentProvider>
+ </Provider>
+ );
+ const expanded = () =>
+ store.get(model.documentAtom)?.cells.get(cellId)?.config.expand_output;
- return { cellId, store, result };
+ return { cellId, store, wrapper, expanded };
}
-const configOf = (store: ReturnType<typeof createStore>, cellId: CellId) =>
- store.get(notebookAtom).cellData[cellId].config;
-
describe("useExpandedOutput", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
it("reads the initial state from the cell's expand_output config", () => {
- expect(setup({ mode: "edit" }).result.current[0]).toBe(false);
- expect(setup({ mode: "edit", expandOutput: true }).result.current[0]).toBe(
- true,
- );
+ const collapsed = setup({ mode: "edit" });
+ expect(
+ renderHook(() => useExpandedOutput(collapsed.cellId), {
+ wrapper: collapsed.wrapper,
+ }).result.current[0],
+ ).toBe(false);
+
+ const expanded = setup({ mode: "edit", expandOutput: true });
+ expect(
+ renderHook(() => useExpandedOutput(expanded.cellId), {
+ wrapper: expanded.wrapper,
+ }).result.current[0],
+ ).toBe(true);
});
it("persists the toggle to the cell's config in edit mode", () => {
- const { cellId, store, result } = setup({ mode: "edit" });
+ const { cellId, wrapper, expanded } = setup({ mode: "edit" });
+ const { result } = renderHook(() => useExpandedOutput(cellId), {
+ wrapper,
+ });
act(() => result.current[1](true));
expect(result.current[0]).toBe(true);
- expect(configOf(store, cellId).expand_output).toBe(true);
- expect(saveCellConfig).toHaveBeenCalledWith({
- configs: { [cellId]: { expand_output: true } },
- });
+ expect(expanded()).toBe(true);
});
it("collapses by clearing the config", () => {
- const { cellId, store, result } = setup({
+ const { cellId, wrapper, expanded } = setup({
mode: "edit",
expandOutput: true,
});
+ const { result } = renderHook(() => useExpandedOutput(cellId), {
+ wrapper,
+ });
act(() => result.current[1](false));
expect(result.current[0]).toBe(false);
- expect(configOf(store, cellId).expand_output).toBe(false);
- expect(saveCellConfig).toHaveBeenCalledWith({
- configs: { [cellId]: { expand_output: false } },
- });
+ expect(expanded()).toBe(false);
});
it("keeps the toggle in memory outside of edit mode", () => {
- const { cellId, store, result } = setup({ mode: "read" });
+ const { cellId, wrapper, expanded } = setup({ mode: "read" });
+ const { result } = renderHook(() => useExpandedOutput(cellId), {
+ wrapper,
+ });
act(() => result.current[1](true));
expect(result.current[0]).toBe(true);
// Cell configs are read-only outside of edit mode.
- expect(configOf(store, cellId).expand_output).toBe(false);
- expect(saveCellConfig).not.toHaveBeenCalled();
+ expect(expanded()).toBe(false);
});
it("still honors expand_output outside of edit mode", () => {
- const { result } = setup({ mode: "read", expandOutput: true });
+ const { cellId, wrapper } = setup({ mode: "read", expandOutput: true });
+ const { result } = renderHook(() => useExpandedOutput(cellId), {
+ wrapper,
+ });
expect(result.current[0]).toBe(true);
});
// `expand_output` covers the cell's output area only. Console output is
// clamped independently and stays an in-memory, per-session toggle.
it("does not touch the config when console output is expanded", () => {
- const cellId = CellId.create();
- const store = createStore();
- store.set(
- notebookAtom,
- MockNotebook.notebookState({ cellData: { [cellId]: {} } }),
- );
- store.set(viewStateAtom, { mode: "edit", cellAnchor: null });
-
+ const { cellId, wrapper, expanded } = setup({ mode: "edit" });
const { result } = renderHook(() => useExpandedConsoleOutput(cellId), {
- wrapper: ({ children }) => <Provider store={store}>{children}</Provider>,
+ wrapper,
});
act(() => result.current[1](true));
expect(result.current[0]).toBe(true);
- expect(configOf(store, cellId).expand_output).toBe(false);
- expect(saveCellConfig).not.toHaveBeenCalled();
+ expect(expanded()).toBe(false);
});
});
diff --git a/frontend/src/core/cells/actions.ts b/frontend/src/core/cells/actions.ts
index c5c3cee900..172a3b4bc8 100644
--- a/frontend/src/core/cells/actions.ts
+++ b/frontend/src/core/cells/actions.ts
@@ -1,14 +1,402 @@
/* Copyright 2026 Marimo. All rights reserved. */
+/** 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 { useMemo } from "react";
import { scrollAndHighlightCell } from "@/components/editor/links/cell-link";
+import type { DocumentModel, EditableDocument } from "@/core/notebook/document";
+import type { CellColumnId } from "@/utils/id-tree";
+import { Logger } from "@/utils/Logger";
+import type { SerializedEditorState } from "../codemirror/types";
+import type { CellConfig } from "../network/types";
import { store } from "../state/jotai";
-import { notebookAtom } from "./cells";
+import { activeDocumentModelAtom } from "../session/active-notebook";
+import {
+ type DeletedCell,
+ notebookAtom,
+ notebookReducer,
+ releaseCellAtoms,
+ useReducerActions,
+} from "./cells";
+import { resolveColumns } from "./columns";
+import { CellId, SCRATCH_CELL_ID, SETUP_CELL_ID } from "./ids";
+import { focusAndScrollCellIntoView } from "./scrollCellIntoView";
+
+export interface CreateCellOptions {
+ /** Place the cell after this one. */
+ after?: CellId | null;
+ /** Place the cell before this one. */
+ before?: CellId | null;
+ /** Without an anchor, the column to append to. The first by default. */
+ endOf?: CellColumnId;
+ /** The id to create with, for callers that refer to the cell before it exists. */
+ id?: CellId;
+ code?: string;
+ name?: string;
+ /** The cell's config. Its column follows from the placement. */
+ config?: Partial<Omit<CellConfig, "column">>;
+ /** Scroll to and focus the cell once it mounts. On by default. */
+ focus?: boolean;
+ /** Create nothing when a cell already has this code. */
+ skipIfCodeExists?: boolean;
+}
+
+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) {
+ return true;
+ }
+ }
+ 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,
+ (get, set, options: CreateCellOptions = {}): CellId | null => {
+ const { code = "", focus = true } = options;
+ const document = documentOf(get);
+ if (options.skipIfCodeExists && hasCellWithCode(document, code)) {
+ return null;
+ }
+ const { cellIds } = get(notebookAtom);
+
+ // The document knows cells and order. Columns come from each cell's
+ // `column` config, which the cell before it provides unless it starts a
+ // column, so a cell placed first in a later column names its column.
+ let placement: { after?: CellId; before?: CellId } = {};
+ let column: number | null = null;
+ if (options.after) {
+ placement = { after: options.after };
+ } else if (options.before) {
+ const tree = cellIds.findWithId(options.before);
+ const index = cellIds.indexOf(tree);
+ placement = { before: options.before };
+ if (index > 0 && tree.indexOfOrThrow(options.before) === 0) {
+ column = index;
+ }
+ } else {
+ const tree =
+ (options.endOf && cellIds.get(options.endOf)) ?? cellIds.atOrThrow(0);
+ if (tree.length > 0) {
+ placement = { after: tree.last() };
+ } else if (cellIds.colLength > 1) {
+ column = cellIds.indexOf(tree);
+ }
+ }
+
+ const id = options.id ?? CellId.create();
+ const config = { ...options.config, column };
+ set(modelOf(get).editAtom, (tx) => {
+ tx.createCell({ id, code, name: options.name, config }, placement);
+ // Only a column's first cell carries its index, as the file is written.
+ if (column !== null && options.before) {
+ tx.updateConfig(options.before, { column: null });
+ }
+ });
+ if (focus) {
+ focusWhenMounted(set, id);
+ // Hidden code stays visible until the cell is blurred for the first time.
+ if (config.hide_code) {
+ set(notebookAtom, (state) => ({
+ ...state,
+ untouchedNewCells: new Set([...state.untouchedNewCells, id]),
+ }));
+ }
+ }
+ return id;
+ },
+);
+
+/**
+ * Focus the cell before or after `cellId`. Past the edge of the column,
+ * create one there, unless `create` is false.
+ */
+export const moveToNextCellAtom = atom(
+ null,
+ (
+ get,
+ set,
+ {
+ cellId,
+ before,
+ create = true,
+ }: { cellId: CellId; before: boolean; create?: boolean },
+ ): void => {
+ if (cellId === SCRATCH_CELL_ID) {
+ return;
+ }
+ const notebook = get(notebookAtom);
+ const column = notebook.cellIds.findWithId(cellId);
+ const index = column.indexOfOrThrow(cellId);
+ const nextIndex = before ? index - 1 : index + 1;
+ if (nextIndex < 0 || nextIndex >= column.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,
+ });
+ },
+);
+
+/** Focus the setup cell, creating it at the top with `code` if it is missing. */
+export const addSetupCellAtom = atom(
+ null,
+ (get, set, { code }: { code?: string } = {}): void => {
+ const { cellIds } = get(notebookAtom);
+ if (cellIds.setupCellExists()) {
+ focusWhenMounted(set, SETUP_CELL_ID);
+ return;
+ }
+ // The setup cell leads the first column, which may be empty.
+ const first = cellIds.atOrThrow(0);
+ set(createCellAtom, {
+ id: SETUP_CELL_ID,
+ name: SETUP_CELL_ID,
+ code: code ?? "",
+ ...(first.length > 0
+ ? { before: first.atOrThrow(0) }
+ : { endOf: first.id }),
+ });
+ },
+);
/**
- * Scroll to the first cell that is currently in "running" state.
+ * Delete cells, keeping them in the history for undo. The notebook keeps at
+ * least one cell. Returns false when nothing was deleted.
*/
+export const deleteCellsAtom = atom(
+ null,
+ (get, set, { cellIds }: { cellIds: CellId[] }): boolean => {
+ const document = documentOf(get);
+ const notebook = get(notebookAtom);
+ const requested = new Set(cellIds);
+ for (const id of cellIds) {
+ if (!document.cells.has(id)) {
+ // Expected for kernel-only cells or a cell another client removed.
+ Logger.warn("Skipping delete for missing cellId", { cellId: id });
+ }
+ }
+ const order = document.order as CellId[];
+ const deleting = order.flatMap((id) => {
+ const cell = document.cells.get(id);
+ return cell !== undefined && requested.has(id) ? [cell] : [];
+ });
+ if (deleting.length === order.length) {
+ deleting.pop();
+ }
+ if (deleting.length === 0) {
+ return false;
+ }
+ const gone = new Set(deleting.map((cell) => cell.id as CellId));
+ const firstSurvivor = order.find((id) => !gone.has(id));
+
+ const cells: DeletedCell[] = deleting.map((cell) => {
+ const id = cell.id as CellId;
+ const index = order.indexOf(id);
+ const code = cell.code ?? notebook.cellData[id]?.code ?? "";
+ const editorView = notebook.cellHandles[id]?.current?.editorView;
+ const serializedEditorState: SerializedEditorState | null =
+ editorView?.state.toJSON({ history: historyField }) ?? null;
+ if (serializedEditorState) {
+ serializedEditorState.doc = code;
+ }
+ return {
+ cell: { id, code, name: cell.name, config: cell.config },
+ // Anchor to the cell before it, which undo restores first if it is
+ // also being deleted. The first cell anchors to the next survivor.
+ placement:
+ index > 0 ? { after: order[index - 1] } : { before: firstSurvivor },
+ serializedEditorState,
+ };
+ });
+
+ // Focus the nearest survivor in the column, looking up before down.
+ const first = deleting[0].id as CellId;
+ const ids = notebook.cellIds.findWithId(first).inOrderIds;
+ const at = ids.indexOf(first);
+ const scrollKey =
+ ids.slice(0, at).findLast((id) => !gone.has(id)) ??
+ ids.slice(at + 1).find((id) => !gone.has(id)) ??
+ null;
+
+ const columns = resolveColumns(document);
+ set(modelOf(get).editAtom, (tx) => {
+ // A cell without a `column` config takes the column of the cell before
+ // it, so a survivor that followed a deleted cell names its own.
+ let previous: CellId | null = null;
+ let followsDeleted = false;
+ for (const id of order) {
+ if (gone.has(id)) {
+ followsDeleted = true;
+ continue;
+ }
+ const inherited = previous === null ? 0 : columns.get(previous);
+ if (
+ followsDeleted &&
+ document.cells.get(id)?.config.column == null &&
+ inherited !== columns.get(id)
+ ) {
+ tx.updateConfig(id, { column: columns.get(id) });
+ }
+ previous = id;
+ followsDeleted = false;
+ }
+ for (const id of gone) {
+ tx.deleteCell(id);
+ }
+ });
+ for (const id of gone) {
+ releaseCellAtoms(id);
+ }
+ set(notebookAtom, (state) => ({
+ ...state,
+ history: [...state.history, { type: "delete", cells }],
+ untouchedNewCells: new Set(
+ [...state.untouchedNewCells].filter((id) => !gone.has(id)),
+ ),
+ scrollKey,
+ }));
+ return true;
+ },
+);
+
+/** Undo the last deletion or move. */
+export const undoDeleteCellAtom = atom(null, (get, set): void => {
+ const last = get(notebookAtom).history.at(-1);
+ if (last === undefined) {
+ return;
+ }
+ if (last.type === "move") {
+ set(notebookAtom, (state) =>
+ notebookReducer(
+ { ...state, history: state.history.slice(0, -1) },
+ { type: "undoMoveCells", payload: last },
+ ),
+ );
+ return;
+ }
+ const model = modelOf(get);
+ const before = documentOf(get);
+ set(model.editAtom, (tx) => {
+ // Each cell anchors to the one before it, restored just before it. An
+ // anchor another client has removed since falls back to the end.
+ const restored = new Set<string>();
+ for (const { cell, placement } of last.cells) {
+ const anchor = placement.after ?? placement.before;
+ const anchored =
+ anchor === undefined ||
+ before.cells.has(anchor) ||
+ restored.has(anchor);
+ tx.createCell(cell, anchored ? placement : {});
+ 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;
+ 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 },
+ };
+ }
+ }
+ return {
+ ...state,
+ cellData,
+ history: state.history.slice(0, -1),
+ scrollKey: last.cells[0].cell.id as CellId,
+ };
+ });
+});
+
+/**
+ * Every notebook operation, for components. Stable for the store's lifetime.
+ *
+ * The reducer's actions are included while the reducer still has cases.
+ * Outside React, set the atoms on the store directly.
+ */
+export function useCellActions() {
+ // The session feeds the kernel's messages and the document into the
+ // notebook through `useReducerActions`; components get the operations.
+ const {
+ handleCellMessage: _handleCellMessage,
+ addLogs: _addLogs,
+ reconcileDocument: _reconcileDocument,
+ setLastRun: _setLastRun,
+ resetCellRuntimes: _resetCellRuntimes,
+ ...operations
+ } = useReducerActions();
+ const createCell = useSetAtom(createCellAtom);
+ const moveToNextCell = useSetAtom(moveToNextCellAtom);
+ const addSetupCell = useSetAtom(addSetupCellAtom);
+ const deleteCells = useSetAtom(deleteCellsAtom);
+ const undoDeleteCell = useSetAtom(undoDeleteCellAtom);
+ return useMemo(
+ () => ({
+ ...operations,
+ createCell,
+ moveToNextCell,
+ addSetupCell,
+ deleteCells,
+ undoDeleteCell,
+ }),
+ // The reducer's actions are stable for the store's lifetime.
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
+ [createCell, moveToNextCell, addSetupCell, deleteCells, undoDeleteCell],
+ );
+}
+
+export type CellActions = ReturnType<typeof useCellActions>;
+
+/** Scroll to the first cell that is currently running. */
export function notebookScrollToRunning() {
- // find cell that is currently in "running" state
const { cellIds, cellRuntime } = store.get(notebookAtom);
const cellId = cellIds.inOrderIds.find(
(id) => cellRuntime[id]?.status === "running",
diff --git a/frontend/src/core/cells/add-missing-import.ts b/frontend/src/core/cells/add-missing-import.ts
index fa8b9f3907..27c61ebe87 100644
--- a/frontend/src/core/cells/add-missing-import.ts
+++ b/frontend/src/core/cells/add-missing-import.ts
@@ -3,7 +3,8 @@
import { getRequestClient } from "../network/requests";
import { store } from "../state/jotai";
import { variablesAtom } from "../variables/state";
-import { type CellActions, notebookAtom } from "./cells";
+import { notebookAtom } from "./cells";
+import type { CreateCell, CreateCellOptions } from "./actions";
import { CellId } from "./ids";
/**
@@ -50,82 +51,85 @@ export function maybeAddMissingImport({
/**
* Adds a marimo import to the notebook if not already present.
* @param autoInstantiate Whether to automatically run the cell.
- * @param createNewCell The function to create a new cell.
- * @param fromCellId The cell to add the import to.
+ * @param createCell The command that creates a cell.
+ * @param fromCellId The cell to add the import next to.
* @param before Whether to add the import before or after the cell.
*
* Returns the ID of the new cell if added, otherwise null.
*/
export function maybeAddMarimoImport({
autoInstantiate,
- createNewCell,
+ createCell,
fromCellId,
before,
}: {
autoInstantiate: boolean;
- createNewCell: CellActions["createNewCell"];
+ createCell: CreateCell;
fromCellId?: CellId | null;
before?: boolean;
}): CellId | null {
- const client = getRequestClient();
- let newCellId: CellId | null = null;
- const added = maybeAddMissingImport({
+ return addImport({
moduleName: "marimo",
variableName: "mo",
- onAddImport: (importStatement) => {
- newCellId = CellId.create();
- createNewCell({
- cellId: fromCellId ?? "__end__",
- before: before ?? false,
- code: importStatement,
- lastCodeRun: autoInstantiate ? importStatement : undefined,
- newCellId: newCellId,
- skipIfCodeExists: true,
- autoFocus: false,
- });
- if (autoInstantiate) {
- void client.sendRun({
- cellIds: [newCellId],
- codes: [importStatement],
- });
- }
- },
+ autoInstantiate,
+ createCell,
+ placement: before ? { before: fromCellId } : { after: fromCellId },
});
- return added ? newCellId : null;
}
export function maybeAddAltairImport({
autoInstantiate,
- createNewCell,
+ createCell,
fromCellId,
}: {
autoInstantiate: boolean;
- createNewCell: CellActions["createNewCell"];
+ createCell: CreateCell;
fromCellId?: CellId | null;
}): CellId | null {
- const client = getRequestClient();
- let newCellId: CellId | null = null;
- const added = maybeAddMissingImport({
+ return addImport({
moduleName: "altair",
variableName: "alt",
+ autoInstantiate,
+ createCell,
+ placement: { after: fromCellId },
+ });
+}
+
+/** Create the import cell, and run it when the notebook runs on its own. */
+function addImport({
+ moduleName,
+ variableName,
+ autoInstantiate,
+ createCell,
+ placement,
+}: {
+ moduleName: string;
+ variableName: string;
+ autoInstantiate: boolean;
+ createCell: CreateCell;
+ placement: Pick<CreateCellOptions, "after" | "before">;
+}): CellId | null {
+ let newCellId: CellId | null = null;
+ maybeAddMissingImport({
+ moduleName,
+ variableName,
onAddImport: (importStatement) => {
- newCellId = CellId.create();
- createNewCell({
- cellId: fromCellId ?? "__end__",
- before: false,
+ const id = CellId.create();
+ const created = createCell({
+ ...placement,
+ id,
code: importStatement,
- lastCodeRun: autoInstantiate ? importStatement : undefined,
- newCellId: newCellId,
skipIfCodeExists: true,
- autoFocus: false,
+ focus: false,
});
- if (autoInstantiate) {
- void client.sendRun({
+ newCellId = created === null ? null : id;
+ if (autoInstantiate && newCellId !== null) {
+ void getRequestClient().sendRun({
cellIds: [newCellId],
codes: [importStatement],
});
}
},
});
- return added ? newCellId : null;
+ return newCellId;
}
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index cdd2702f37..cba00c4bc4 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -1,12 +1,11 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { historyField } from "@codemirror/commands";
+import type * as Protocol from "@marimo-team/client/protocol";
import { type Atom, atom, useAtom, useAtomValue } from "jotai";
import { atomFamily, selectAtom, splitAtom } from "jotai/utils";
import { createRef, type ReducerWithoutAction } from "react";
import type { CellHandle } from "@/components/editor/notebook-cell";
-import type { EditableDocument } from "@/core/notebook/document";
-import type { CollapsibleTree } from "@/utils/id-tree";
+import type { EditableDocument, Placement } from "@/core/notebook/document";
import {
type CellColumnId,
type CellIndex,
@@ -31,7 +30,7 @@ import { createDeepEqualAtom, store } from "../state/jotai";
import { isWasm } from "../wasm/utils";
import { prepareCellForExecution, transitionCell } from "./cell";
import { applyDocument, documentEditMiddleware } from "./document";
-import { CellId, SCRATCH_CELL_ID, SETUP_CELL_ID } from "./ids";
+import { CellId, SCRATCH_CELL_ID } from "./ids";
import { type CellLog, getCellLogsForMessage } from "./logs";
import {
focusAndScrollCellIntoView,
@@ -42,7 +41,6 @@ import {
type CellData,
type CellRuntimeState,
createCell,
- createCellConfig,
createCellRuntimeState,
isEdited,
} from "./types";
@@ -56,17 +54,21 @@ import {
notebookQueueOrRunningCount,
} from "./utils";
+/** A deleted cell as it was, with where it went in the document. */
+export interface DeletedCell {
+ cell: Protocol.CellInput;
+ placement: Placement;
+ /** The editor's state at deletion, so undo brings its history back. */
+ serializedEditorState: SerializedEditorState | null;
+}
+
/**
- * History entry for undoing a cell deletion.
+ * History entry for undoing one deletion, of one or more cells.
*/
export interface UndoDeleteEntry {
type: "delete";
- name: string;
- serializedEditorState: SerializedEditorState;
- column: CellColumnId;
- index: CellIndex;
- isSetupCell: boolean;
- config: CellConfig;
+ /** In document order. Each cell is placed after the one before it. */
+ cells: DeletedCell[];
}
/**
@@ -162,40 +164,6 @@ export function initialNotebookState(): NotebookState {
});
}
-/** The target cell ID to create a new cell relative to. Can be:
- * - A CellId string for an existing cell
- * - "__end__" to append at the end of the first column
- * - {type: "__end__", columnId} to append at the end of a specific column
- */
-export type CellPosition =
- | CellId
- | "__end__"
- | { type: "__end__"; columnId: CellColumnId };
-
-export interface CreateNewCellAction {
- cellId: CellPosition;
- /** Whether to insert before (true) or after (false) the target cell */
- before: boolean;
- /** Initial code content for the new cell */
- code?: string;
- /** Optional name for the new cell */
- name?: string;
- /** Optional cell configuration */
- config?: CellConfig;
- /** The last executed code for the new cell */
- lastCodeRun?: string;
- /** Timestamp of the last execution */
- lastExecutionTime?: number;
- /** Optional custom ID for the new cell. Auto-generated if not provided */
- newCellId?: CellId;
- /** Whether to focus the new cell after creation */
- autoFocus?: boolean;
- /** If true, skip creation if code already exists */
- skipIfCodeExists?: boolean;
- /** Hide the code in the new cell. This will be initially shown until the cell is blurred for the first time. */
- hideCode?: boolean;
-}
-
/**
* Actions and reducer for the notebook state.
*/
@@ -206,85 +174,6 @@ const {
useActions,
valueAtom: notebookAtom,
} = createReducerAndAtoms(initialNotebookState, {
- createNewCell: (state, action: CreateNewCellAction) => {
- const {
- cellId,
- before,
- code,
- name,
- config,
- lastCodeRun = null,
- lastExecutionTime = null,
- autoFocus = true,
- skipIfCodeExists = false,
- hideCode = undefined,
- } = action;
-
- let columnId: CellColumnId;
- let cellIndex: number;
-
- // If skipIfCodeExists is true, check if the code already exists in the notebook
- if (skipIfCodeExists) {
- for (const cellId of state.cellIds.inOrderIds) {
- if (state.cellData[cellId]?.code === code) {
- return state;
- }
- }
- }
-
- if (cellId === "__end__") {
- const column = state.cellIds.atOrThrow(0);
- columnId = column.id;
- cellIndex = column.length;
- } else if (typeof cellId === "string") {
- const column = state.cellIds.findWithId(cellId);
- columnId = column.id;
- cellIndex = column.topLevelIds.indexOf(cellId);
- } else if (cellId.type === "__end__") {
- const column =
- state.cellIds.get(cellId.columnId) || state.cellIds.atOrThrow(0);
- columnId = column.id;
- cellIndex = column.length;
- } else {
- throw new Error("Invalid cellId");
- }
-
- const newCellId = action.newCellId || CellId.create();
- const insertionIndex = before ? cellIndex : cellIndex + 1;
-
- return {
- ...state,
- cellIds: state.cellIds.insertId(newCellId, columnId, insertionIndex),
- cellData: {
- ...state.cellData,
- [newCellId]: createCell({
- id: newCellId,
- code,
- name,
- lastCodeRun,
- config: createCellConfig({
- ...config,
- ...(hideCode != null && { hide_code: hideCode }),
- }),
- lastExecutionTime,
- edited: Boolean(code) && code !== lastCodeRun,
- }),
- },
- cellRuntime: {
- ...state.cellRuntime,
- [newCellId]: createCellRuntimeState(),
- },
- cellHandles: {
- ...state.cellHandles,
- [newCellId]: createRef(),
- },
- scrollKey: autoFocus ? newCellId : null,
- untouchedNewCells:
- hideCode && autoFocus
- ? new Set([...state.untouchedNewCells, newCellId])
- : state.untouchedNewCells,
- };
- },
moveCell: (
state,
action: {
@@ -679,128 +568,29 @@ const {
cellIds: state.cellIds.compact(),
};
},
- deleteCell: (state, action: { cellId: CellId }) => {
- const cellId = action.cellId;
-
- // Can't delete the last cell, across all columns
- if (state.cellIds.hasOnlyOneId()) {
- return state;
- }
-
- let column: CollapsibleTree<CellId>;
- try {
- column = state.cellIds.findWithId(cellId);
- } catch (error) {
- // Expected for kernel-only cells or out-of-order transactions.
- Logger.warn("Skipping delete for missing cellId", {
- cellId,
- error,
- });
- return state;
- }
-
- const cellIndex = column.indexOfOrThrow(cellId);
- const focusIndex = cellIndex === 0 ? 1 : cellIndex - 1;
- let scrollKey: CellId | null = null;
- if (column.length > 1) {
- scrollKey = column.atOrThrow(focusIndex);
- }
-
- const editorView = state.cellHandles[cellId].current?.editorView;
- const serializedEditorState = editorView?.state.toJSON({
- history: historyField,
- });
- if (serializedEditorState) {
- serializedEditorState.doc = state.cellData[cellId].code;
- }
-
- // release the granular atom(s) created for this cell
- releaseCellAtoms(cellId);
- const prevData = state.cellData[cellId];
- return {
- ...state,
- cellIds: state.cellIds.deleteById(cellId),
- history: [
- ...state.history,
- {
- type: "delete",
- name: prevData.name,
- serializedEditorState: serializedEditorState,
- column: column.id,
- index: cellIndex,
- isSetupCell: cellId === SETUP_CELL_ID,
- config: prevData.config,
- },
- ],
- scrollKey: scrollKey,
- };
- },
- undoDeleteCell: (state) => {
- if (state.history.length === 0) {
+ /**
+ * Put moved cells back where they were.
+ *
+ * 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 last = state.history[state.history.length - 1];
-
- if (last.type === "move") {
- const { cellIds, placements } = last;
- if (
- cellIds.length === 0 ||
- placements.length !== cellIds.length ||
- cellIds.some((id) => !state.cellData[id])
- ) {
- return { ...state, history: state.history.slice(0, -1) };
- }
- const toRestore = cellIds.map((id, i) => ({
- id,
- columnId: placements[i].columnId,
- index: placements[i].index,
- }));
- return {
- ...state,
- cellIds: state.cellIds.placeCells(toRestore),
- history: state.history.slice(0, -1),
- scrollKey: cellIds[0] ?? null,
- };
- }
-
- const {
- name,
- serializedEditorState = { doc: "" },
- column,
- index,
- isSetupCell,
- config,
- } = last;
-
- const cellId = isSetupCell ? SETUP_CELL_ID : CellId.create();
- const undoCell = createCell({
- id: cellId,
- name,
- code: serializedEditorState.doc,
- edited: serializedEditorState.doc.trim().length > 0,
- serializedEditorState,
- config,
- });
-
+ const toRestore = cellIds.map((id, i) => ({
+ id,
+ columnId: placements[i].columnId,
+ index: placements[i].index,
+ }));
return {
...state,
- cellIds: state.cellIds.insertId(cellId, column, index),
- cellData: {
- ...state.cellData,
- [cellId]: undoCell,
- },
- cellRuntime: {
- ...state.cellRuntime,
- [cellId]: createCellRuntimeState(),
- },
- cellHandles: {
- ...state.cellHandles,
- [cellId]: createRef(),
- },
- history: state.history.slice(0, -1),
- // Scroll to the newly created cell
- scrollKey: cellId,
+ cellIds: state.cellIds.placeCells(toRestore),
+ scrollKey: cellIds[0] ?? null,
};
},
clearSerializedEditorState: (state, action: { cellId: CellId }) => {
@@ -853,35 +643,6 @@ const {
},
});
},
- updateCellName: (state, action: { cellId: CellId; name: string }) => {
- const { cellId, name } = action;
- return updateCellData({
- state,
- cellId,
- cellReducer: (cell) => {
- return {
- ...cell,
- name: name,
- };
- },
- });
- },
- updateCellConfig: (
- state,
- action: { cellId: CellId; config: Partial<CellConfig> },
- ) => {
- const { cellId, config } = action;
- return updateCellData({
- state,
- cellId,
- cellReducer: (cell) => {
- return {
- ...cell,
- config: createCellConfig({ ...cell.config, ...config }),
- };
- },
- });
- },
prepareForRun: (state, action: { cellId: CellId }) => {
const newState = updateCellRuntimeState({
state,
@@ -1020,97 +781,6 @@ const {
}
return { ...state, cellRuntime };
},
- /**
- * Move focus to next cell
- *
- * Creates a new cell if the current cell is the last one in the array.
- *
- * If needed, scrolls newly created or focused cell into view.
- *
- * Replicates Shift+Enter functionality of Jupyter
- */
- moveToNextCell: (
- state,
- action: { cellId: CellId; before: boolean; noCreate?: boolean },
- ) => {
- const { cellId, before, noCreate = false } = action;
-
- // Can't move focus of scratch cell
- if (cellId === SCRATCH_CELL_ID) {
- return state;
- }
-
- const column = state.cellIds.findWithId(cellId);
- const index = column.indexOfOrThrow(cellId);
- const nextCellIndex = before ? index - 1 : index + 1;
-
- const isPastLastCell = nextCellIndex === column.length;
- const isBeforeFirstCell = nextCellIndex === -1;
-
- // Create a new cell at the end and set scrollKey to focus it
- if (isPastLastCell && !noCreate) {
- const newCellId = CellId.create();
- return {
- ...state,
- cellIds: state.cellIds.insertId(newCellId, column.id, nextCellIndex),
- cellData: {
- ...state.cellData,
- [newCellId]: createCell({ id: newCellId }),
- },
- cellRuntime: {
- ...state.cellRuntime,
- [newCellId]: createCellRuntimeState(),
- },
- cellHandles: {
- ...state.cellHandles,
- [newCellId]: createRef(),
- },
- scrollKey: newCellId,
- };
- }
-
- if (isBeforeFirstCell && !noCreate) {
- const newCellId = CellId.create();
- return {
- ...state,
- cellIds: state.cellIds.insertId(newCellId, column.id, 0),
- cellData: {
- ...state.cellData,
- [newCellId]: createCell({ id: newCellId }),
- },
- cellRuntime: {
- ...state.cellRuntime,
- [newCellId]: createCellRuntimeState(),
- },
- cellHandles: {
- ...state.cellHandles,
- [newCellId]: createRef(),
- },
- scrollKey: newCellId,
- };
- }
-
- if ((isPastLastCell || isBeforeFirstCell) && noCreate) {
- // Trying to move past the last cell or before the first cell
- // with noCreate=true - do nothing
- return state;
- }
-
- if (nextCellIndex >= 0 && nextCellIndex < column.length) {
- // Move to valid cell within bounds
- const nextCellId = column.atOrThrow(nextCellIndex);
- // Just focus, no state change
- focusAndScrollCellIntoView({
- cellId: nextCellId,
- cell: state.cellHandles[nextCellId],
- isCodeHidden: isCellCodeHidden(state, nextCellId),
- codeFocus: before ? "bottom" : "top",
- variableName: undefined,
- });
- }
-
- return state;
- },
markTouched: (state, action: { cellId: CellId }) => {
const { cellId } = action;
@@ -1431,44 +1101,6 @@ const {
cellRuntime: newCellRuntime,
};
},
- addSetupCellIfDoesntExist: (state, action: { code?: string }) => {
- const { code } = action;
-
- if (state.cellIds.setupCellExists()) {
- // Just focus on the existing setup cell
- return {
- ...state,
- scrollKey: SETUP_CELL_ID,
- };
- }
-
- return {
- ...state,
- cellIds: state.cellIds.insertId(
- SETUP_CELL_ID,
- state.cellIds.atOrThrow(0).id,
- 0,
- ),
- cellData: {
- ...state.cellData,
- [SETUP_CELL_ID]: createCell({
- id: SETUP_CELL_ID,
- name: SETUP_CELL_ID,
- code,
- edited: Boolean(code),
- }),
- },
- cellRuntime: {
- ...state.cellRuntime,
- [SETUP_CELL_ID]: createCellRuntimeState(),
- },
- cellHandles: {
- ...state.cellHandles,
- [SETUP_CELL_ID]: createRef(),
- },
- scrollKey: SETUP_CELL_ID,
- };
- },
});
// We apply the middleware here (rather than inline in createReducerAndAtoms)
@@ -1876,20 +1508,13 @@ export function createTracebackInfoAtom(
});
}
-/**
- * Use this hook to dispatch cell actions. This hook will not cause a re-render
- * when cells change.
- */
-export function useCellActions(
- options: { skipMiddleware?: boolean } = {},
-): CellActions {
- return useActions(options);
+/** The reducer's actions. Components use `useCellActions` from `./actions`. */
+export function useReducerActions(): ReducerCellActions {
+ return useActions();
}
-/**
- * Map of cell actions
- */
-export type CellActions = ReturnType<typeof createActions>;
+/** The actions the reducer still handles. */
+export type ReducerCellActions = ReturnType<typeof createActions>;
/**
* This is exported for testing purposes only.
diff --git a/frontend/src/core/cells/document.ts b/frontend/src/core/cells/document.ts
index e0fe29cca5..12dd063527 100644
--- a/frontend/src/core/cells/document.ts
+++ b/frontend/src/core/cells/document.ts
@@ -27,7 +27,7 @@ import type { CellConfig } from "../network/types";
import { canUseRtc, isRtcEnabled } from "../rtc/state";
import { store } from "../state/jotai";
import { activeDocumentModelAtom } from "../session/active-notebook";
-import type { CellActions, NotebookState } from "./cells";
+import type { NotebookState, ReducerCellActions } from "./cells";
import { groupByColumn } from "./columns";
import type { CellId } from "./ids";
import {
@@ -38,7 +38,7 @@ import {
isEdited,
} from "./types";
-type CellAction = DispatchedActionOf<CellActions>;
+type CellAction = DispatchedActionOf<ReducerCellActions>;
// Following the document ----------------------------------------------------
@@ -126,14 +126,17 @@ export function applyDocument(
continue;
}
if (current === undefined) {
- // A new cell has no run to be edited from.
+ // A new cell with code is stale until it runs. The kernel's last run
+ // settles it on kernel-ready.
+ const code = cell.code ?? "";
cellData = {
...cellData,
[id]: createCell({
id,
- code: cell.code ?? "",
+ code,
name: cell.name,
config: createCellConfig(cell.config),
+ edited: code.trim().length > 0,
}),
};
cellRuntime = { ...cellRuntime, [id]: createCellRuntimeState() };
diff --git a/frontend/src/core/cells/outputs.ts b/frontend/src/core/cells/outputs.ts
index a700144b17..22b268c8ab 100644
--- a/frontend/src/core/cells/outputs.ts
+++ b/frontend/src/core/cells/outputs.ts
@@ -1,15 +1,15 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { useAtomValue } from "jotai";
-import { selectAtom } from "jotai/utils";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useState } from "react";
import { useEvent } from "@/hooks/useEvent";
-import { Logger } from "@/utils/Logger";
+import {
+ useNotebookCellConfig,
+ useNotebookDocumentEdit,
+} from "../notebook/document";
import type { OutputMessage } from "../kernel/messages";
import { viewStateAtom } from "../mode";
-import { getRequestClient } from "../network/requests";
-import { cellDataAtom, useCellActions } from "./cells";
-import type { CellId } from "./ids";
+import { type CellId, SCRATCH_CELL_ID } from "./ids";
// This does not need to be overcomplicated. We can just store the expanded
// state in a global map instead of Jotai since state is not shared between cells.
@@ -27,20 +27,9 @@ const expandedConsoleOutputs: Record<CellId, boolean> = {};
*/
export function useExpandedOutput(cellId: CellId) {
const { mode } = useAtomValue(viewStateAtom);
- const { updateCellConfig } = useCellActions();
- // Select just the flag: every output would otherwise re-render on each
- // keystroke in its cell.
- const isConfigExpanded = useAtomValue(
- useMemo(
- () =>
- selectAtom(
- cellDataAtom(cellId),
- (data) => data?.config.expand_output ?? false,
- Object.is,
- ),
- [cellId],
- ),
- );
+ const edit = useNotebookDocumentEdit();
+ const isConfigExpanded =
+ useNotebookCellConfig(cellId)?.expand_output ?? false;
const [isSessionExpanded, setIsSessionExpanded] = useState(
() => expandedOutputs[cellId] ?? isConfigExpanded,
);
@@ -55,16 +44,11 @@ export function useExpandedOutput(cellId: CellId) {
const setIsExpanded = useEvent((expanded: boolean) => {
setIsSessionExpanded(expanded);
- if (!isEditable) {
+ // The scratchpad is not in the document.
+ if (!isEditable || cellId === SCRATCH_CELL_ID) {
return;
}
- const config = { expand_output: expanded };
- updateCellConfig({ cellId, config });
- getRequestClient()
- .saveCellConfig({ configs: { [cellId]: config } })
- .catch((error) => {
- Logger.error("Failed to save expand_output config", error);
- });
+ edit((tx) => tx.updateConfig(cellId, { expand_output: expanded }));
});
return [isExpanded, setIsExpanded] as const;
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index f3d2de0401..7969f520ec 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -190,7 +190,7 @@ function cellKeymaps({
if (isAtStartOfEditor(ev)) {
const actions = ev.state.facet(cellActionsState);
- actions.moveToNextCell({ cellId, before: true, noCreate: true });
+ actions.moveToNextCell({ cellId, before: true, create: false });
return true;
}
return false;
@@ -207,7 +207,7 @@ function cellKeymaps({
if (isAtEndOfEditor(ev)) {
const actions = ev.state.facet(cellActionsState);
- actions.moveToNextCell({ cellId, before: false, noCreate: true });
+ actions.moveToNextCell({ cellId, before: false, create: false });
return true;
}
return false;
@@ -219,7 +219,7 @@ function cellKeymaps({
stopPropagation: true,
run: (ev) => {
const actions = ev.state.facet(cellActionsState);
- actions.moveToNextCell({ cellId, before: false, noCreate: true });
+ actions.moveToNextCell({ cellId, before: false, create: false });
return true;
},
},
@@ -229,7 +229,7 @@ function cellKeymaps({
stopPropagation: true,
run: (ev) => {
const actions = ev.state.facet(cellActionsState);
- actions.moveToNextCell({ cellId, before: true, noCreate: true });
+ actions.moveToNextCell({ cellId, before: true, create: false });
return true;
},
},
@@ -260,7 +260,7 @@ function cellKeymaps({
run: (ev) => {
ev.contentDOM.blur();
const actions = ev.state.facet(cellActionsState);
- actions.createNewCell({ cellId, before: true });
+ actions.createCell({ before: cellId });
return true;
},
},
@@ -271,7 +271,7 @@ function cellKeymaps({
run: (ev) => {
ev.contentDOM.blur();
const actions = ev.state.facet(cellActionsState);
- actions.createNewCell({ cellId, before: false });
+ actions.createCell({ after: cellId });
return true;
},
},
diff --git a/frontend/src/core/codemirror/cells/state.ts b/frontend/src/core/codemirror/cells/state.ts
index dd9721c40f..6c53efc761 100644
--- a/frontend/src/core/codemirror/cells/state.ts
+++ b/frontend/src/core/codemirror/cells/state.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { Facet } from "@codemirror/state";
-import type { CellActions } from "@/core/cells/cells";
+import type { CellActions } from "@/core/cells/actions";
import type { CellId } from "@/core/cells/ids";
export interface CodemirrorCellActions extends CellActions {
diff --git a/frontend/src/core/codemirror/keymaps/vim.ts b/frontend/src/core/codemirror/keymaps/vim.ts
index 09041a2ec5..904d8b9695 100644
--- a/frontend/src/core/codemirror/keymaps/vim.ts
+++ b/frontend/src/core/codemirror/keymaps/vim.ts
@@ -37,7 +37,7 @@ export function vimKeymapExtension(): Extension[] {
if (isAtEndOfEditor(ev, true) && isInVimNormalMode(ev)) {
const actions = ev.state.facet(cellActionsState);
const cellId = ev.state.facet(cellIdState);
- actions.moveToNextCell({ cellId, before: false, noCreate: true });
+ actions.moveToNextCell({ cellId, before: false, create: false });
return true;
}
return false;
@@ -51,7 +51,7 @@ export function vimKeymapExtension(): Extension[] {
if (isAtStartOfEditor(ev) && isInVimNormalMode(ev)) {
const actions = ev.state.facet(cellActionsState);
const cellId = ev.state.facet(cellIdState);
- actions.moveToNextCell({ cellId, before: true, noCreate: true });
+ actions.moveToNextCell({ cellId, before: true, create: false });
return true;
}
return false;
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 780d0d9e87..39094cfc6d 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -5,8 +5,8 @@ import { Tooltip } from "radix-ui";
const TooltipProvider = Tooltip.Provider;
-import { useAtomValue, useSetAtom, useStore } from "jotai";
-import { useEffect } from "react";
+import { useAtomValue } from "jotai";
+import { lazy, useEffect } from "react";
import { NotStartedConnectionAlert } from "@/components/editor/alerts/connecting-alert";
import { Controls } from "@/components/editor/controls/Controls";
import { SandboxController } from "@/components/editor/chrome/panels/sandbox-controller";
@@ -29,24 +29,23 @@ import { CellsRenderer } from "../components/editor/renderers/cells-renderer";
import { useHotkey } from "../hooks/useHotkey";
import {
hasCellsAtom,
- notebookAtom,
notebookIsRunningAtom,
numColumnsAtom,
- useCellActions,
} from "./cells/cells";
-import { notebookCells } from "./cells/utils";
+import { useCellActions } from "./cells/actions";
import type { AppConfig, UserConfig } from "./config/config-schema";
-import { DocumentProvider } from "./notebook/document";
import { RuntimeState } from "./kernel/RuntimeState";
-import { getSessionId } from "./kernel/session";
import { useTogglePresenting } from "./layout/useTogglePresenting";
import { viewStateAtom } from "./mode";
import { useRequestClient } from "./network/requests";
import { useFilename } from "./saving/filename";
-import { lastSavedNotebookAtom } from "./saving/state";
-import { useNotebookSession } from "./session/useNotebookSession";
+import type { ConnectionStatus } from "./session/types";
-interface AppProps {
+const LazyCommandPalette = lazy(
+ () => import("../components/editor/controls/command-palette"),
+);
+
+export interface EditAppProps {
/**
* The user config.
*/
@@ -59,20 +58,24 @@ interface AppProps {
* If true, the floating controls will be hidden.
*/
hideControls?: boolean;
+ /** The session's connection, which the page owns with the document model. */
+ connection: ConnectionStatus;
+ reconnect: () => Promise<void>;
}
-export const EditApp: React.FC<AppProps> = ({
+/** The notebook editor. Rendered inside the page's `DocumentProvider`. */
+export const EditApp: React.FC<EditAppProps> = ({
userConfig,
appConfig,
hideControls = false,
+ connection,
+ reconnect,
}) => {
const { mergeAllColumns, collapseAllCells, expandAllCells } =
useCellActions();
- const store = useStore();
const viewState = useAtomValue(viewStateAtom);
const numColumns = useAtomValue(numColumnsAtom);
const filename = useFilename();
- const setLastSavedNotebook = useSetAtom(lastSavedNotebookAtom);
const { sendComponentValues, sendInterrupt } = useRequestClient();
const isEditing = viewState.mode === "edit";
@@ -87,18 +90,6 @@ export const EditApp: React.FC<AppProps> = ({
};
}, [sendComponentValues]);
- const { connection, reconnect, documentModel } = useNotebookSession({
- autoInstantiate: 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(),
- });
-
// Update document title whenever filename or app_title changes
useEffect(() => {
// Set document title: app_title takes precedence, then filename, then default
@@ -178,7 +169,7 @@ export const EditApp: React.FC<AppProps> = ({
);
return (
- <DocumentProvider model={documentModel}>
+ <>
<SandboxController onReconnect={reconnect} />
<AppContainer
connection={connection}
@@ -232,6 +223,7 @@ export const EditApp: React.FC<AppProps> = ({
/>
</TooltipProvider>
)}
- </DocumentProvider>
+ <LazyCommandPalette />
+ </>
);
};
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index a0833bc456..38b536515b 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -383,12 +383,10 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
public sendInterrupt = throwNotImplemented;
public sendShutdown = throwNotImplemented;
public sendFormat = throwNotImplemented;
- public sendDeleteCell = throwNotImplemented;
public sendInstallMissingPackages = throwNotImplemented;
public sendCodeCompletionRequest = throwNotImplemented;
public saveUserConfig = throwNotImplemented;
public saveAppConfig = throwNotImplemented;
- public saveCellConfig = throwNotImplemented;
public sendRestart = throwNotImplemented;
public readCode = throwNotImplemented;
public readSnippets = throwNotImplemented;
diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.ts
index 9e98cc3e8b..efcc227d2f 100644
--- a/frontend/src/core/kernel/handlers.ts
+++ b/frontend/src/core/kernel/handlers.ts
@@ -3,7 +3,7 @@ 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 { CellActions } from "../cells/cells";
+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";
@@ -63,8 +63,8 @@ export function handleKernelReady(
autoInstantiate: boolean;
/** The notebook's cells, as the host document provided them. */
cells: CellData[];
- setLastRun: CellActions["setLastRun"];
- resetCellRuntimes: CellActions["resetCellRuntimes"];
+ setLastRun: ReducerCellActions["setLastRun"];
+ resetCellRuntimes: ReducerCellActions["resetCellRuntimes"];
setLayoutData: (payload: {
layoutView: LayoutType;
data: LayoutData;
diff --git a/frontend/src/core/network/__tests__/requests-lazy.test.ts b/frontend/src/core/network/__tests__/requests-lazy.test.ts
index 91fc895ec7..888b7568c7 100644
--- a/frontend/src/core/network/__tests__/requests-lazy.test.ts
+++ b/frontend/src/core/network/__tests__/requests-lazy.test.ts
@@ -53,7 +53,6 @@ describe("createLazyRequests", () => {
sendInstantiate: vi.fn().mockResolvedValue({ instantiated: true }),
sendFunctionRequest: vi.fn().mockResolvedValue({ result: "data" }),
sendRestart: vi.fn().mockResolvedValue({ restarted: true }),
- sendDeleteCell: vi.fn().mockResolvedValue({ deleted: true }),
sendInterrupt: vi.fn().mockResolvedValue({ interrupted: true }),
sendPdb: vi.fn().mockResolvedValue({ pdb: true }),
sendRunScratchpad: vi.fn().mockResolvedValue({ run: true }),
@@ -320,7 +319,6 @@ describe("createLazyRequests", () => {
cellIds: [cellId("cell1")],
codes: ["code"],
});
- await lazyRequests.sendDeleteCell({ cellId: cellId("cell2") });
await lazyRequests.sendInstantiate({
objectIds: [uiElementId("obj1")],
values: [],
@@ -328,7 +326,7 @@ describe("createLazyRequests", () => {
// Init should only be called once
expect(mockInit).toHaveBeenCalledTimes(1);
- expect(mockGetRuntimeManager).toHaveBeenCalledTimes(3);
+ expect(mockGetRuntimeManager).toHaveBeenCalledTimes(2);
});
});
});
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index 4946f31305..fb65507f5c 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -52,10 +52,8 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
sendModelValue: "startConnection",
sendInstantiate: "startConnectionWithoutKernel",
sendRun: "startConnection",
- sendDeleteCell: "startConnection",
sendRunScratchpad: "startConnection",
saveAppConfig: "startConnection",
- saveCellConfig: "startConnection",
discoverDataSources: "startConnection",
// Export operations start a connection
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index d931c61ea1..85c498c3c9 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -142,14 +142,6 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
- sendDeleteCell: (request) => {
- return getClient()
- .POST("/api/kernel/delete", {
- body: request,
- params: getParams(),
- })
- .then(handleResponseReturnNull);
- },
sendCodeCompletionRequest: async (request) => {
await waitForConnectionOpen();
return getClient()
@@ -175,14 +167,6 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
- saveCellConfig: (request) => {
- return getClient()
- .POST("/api/kernel/set_cell_config", {
- body: request,
- params: getParams(),
- })
- .then(handleResponseReturnNull);
- },
sendFunctionRequest: (request) => {
return getClient()
.POST("/api/kernel/function_call", {
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 4d027e98cd..b27792e5d9 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -48,11 +48,9 @@ export function createStaticRequests(): EditRequests & RunRequests {
sendInterrupt: throwNotInEditMode,
sendShutdown: throwNotInEditMode,
sendFormat: throwNotInEditMode,
- sendDeleteCell: throwNotInEditMode,
sendCodeCompletionRequest: throwNotInEditMode,
saveUserConfig: throwNotInEditMode,
saveAppConfig: throwNotInEditMode,
- saveCellConfig: throwNotInEditMode,
sendStdin: throwNotInEditMode,
readCode: throwNotInEditMode,
readSnippets: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index a98659c9b6..3c058b7986 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -29,11 +29,9 @@ export function createErrorToastingRequests(
sendInterrupt: "Failed to interrupt",
sendShutdown: "Failed to shutdown",
sendFormat: "Failed to format",
- sendDeleteCell: "Failed to delete cell",
sendCodeCompletionRequest: "Failed to complete code",
saveUserConfig: "Failed to save user config",
saveAppConfig: "Failed to save app config",
- saveCellConfig: "Failed to save cell config",
sendStdin: "Failed to send stdin",
readCode: "Failed to read code",
readSnippets: "Failed to fetch snippets",
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index fbd809d8ca..a1725a4a2a 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -1,6 +1,5 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { components, paths } from "@marimo-team/marimo-api";
-import type { CellId } from "../cells/ids";
export type schemas = components["schemas"];
export type AiCompletionRequest = schemas["AiCompletionRequest"];
@@ -16,7 +15,6 @@ export type CellConfig = schemas["CellConfig"];
*/
export type RuntimeState = schemas["CellNotification"]["status"];
export type CodeCompletionRequest = schemas["CodeCompletionRequest"];
-export type DeleteCellRequest = schemas["DeleteCellRequest"];
export type AutoExportAsIPYNBRequest = schemas["AutoExportAsIPYNBRequest"];
export type AutoExportAsMarkdownRequest =
schemas["AutoExportAsMarkdownRequest"];
@@ -101,9 +99,6 @@ export type SaveNotebookRequest = schemas["SaveNotebookRequest"];
export type CopyNotebookRequest = schemas["CopyNotebookRequest"];
export type SaveUserConfigurationRequest =
schemas["SaveUserConfigurationRequest"];
-export interface SetCellConfigRequest {
- configs: Record<CellId, Partial<CellConfig>>;
-}
/**
* Client-side shape for creating a file/directory/notebook. The HTTP
* transport sends this as multipart/form-data; the WASM bridge base64-encodes
@@ -171,11 +166,9 @@ export interface EditRequests {
sendInterrupt: () => Promise<null>;
sendShutdown: () => Promise<null>;
sendFormat: (request: FormatCellsRequest) => Promise<FormatResponse>;
- sendDeleteCell: (request: DeleteCellRequest) => Promise<null>;
sendCodeCompletionRequest: (request: CodeCompletionRequest) => Promise<null>;
saveUserConfig: (request: SaveUserConfigurationRequest) => Promise<null>;
saveAppConfig: (request: SaveAppConfigurationRequest) => Promise<null>;
- saveCellConfig: (request: SetCellConfigRequest) => Promise<null>;
sendRestart: () => Promise<null>;
sendInstallMissingPackages: (
request: InstallPackagesRequest,
diff --git a/frontend/src/core/notebook/document/__tests__/codemirror.test.ts b/frontend/src/core/notebook/document/__tests__/codemirror.test.ts
index 51a7ade0bb..ad8b22303c 100644
--- a/frontend/src/core/notebook/document/__tests__/codemirror.test.ts
+++ b/frontend/src/core/notebook/document/__tests__/codemirror.test.ts
@@ -60,6 +60,11 @@ function languages(id: CellId) {
aiCellCompletion: () => false,
createManyBelow: vi.fn(),
addOrAppendSetupCell: vi.fn(),
+ createCell: vi.fn(),
+ moveToNextCell: vi.fn(),
+ addSetupCell: vi.fn(),
+ deleteCells: vi.fn(),
+ undoDeleteCell: vi.fn(),
onRun: vi.fn(),
deleteCell: vi.fn(),
afterToggleMarkdown: vi.fn(),
diff --git a/frontend/src/core/notebook/document/__tests__/draft.test.ts b/frontend/src/core/notebook/document/__tests__/draft.test.ts
index f470c6e30d..4d2c005930 100644
--- a/frontend/src/core/notebook/document/__tests__/draft.test.ts
+++ b/frontend/src/core/notebook/document/__tests__/draft.test.ts
@@ -9,6 +9,7 @@ import {
type EditableCell,
editCell,
EMPTY_DRAFT,
+ restoreCell,
setOrder,
toChanges,
viewDocument,
@@ -99,6 +100,46 @@ describe("createCell and deleteCell", () => {
expect(toChanges(confirmed, draft)).toEqual([]);
expect(viewDocument(confirmed, draft).order).toEqual(["c1", "c2"]);
});
+
+ it("restores a deleted cell as an edit at the requested place", () => {
+ const deleted = deleteCell(EMPTY_DRAFT, "c1");
+ const back = { id: "c1", code: "back" };
+ const put = {
+ kind: "put_cell",
+ base_etag: "c1-etag",
+ cell: { ...back, name: "_", config: CONFIG },
+ };
+ const inPlace = restoreCell(confirmed, deleted, back, { before: "c2" });
+ const moved = restoreCell(confirmed, deleted, back, { after: "c2" });
+ expect(viewDocument(confirmed, inPlace).cells.get("c1")?.code).toBe("back");
+ expect(viewDocument(confirmed, inPlace).order).toEqual(["c1", "c2"]);
+ expect(toChanges(confirmed, inPlace)).toEqual([put]);
+ expect(viewDocument(confirmed, moved).order).toEqual(["c2", "c1"]);
+ expect(toChanges(confirmed, moved)).toEqual([
+ put,
+ { kind: "set_order", base_etag: "order-1", order: ["c2", "c1"] },
+ ]);
+ });
+
+ it("recreates a cell whose deletion is in flight once the host removes it", () => {
+ const sent = deleteCell(EMPTY_DRAFT, "c1");
+ const back = { id: "c1", code: "back" };
+ const draft = restoreCell(confirmed, sent, back, { before: "c2" }, sent);
+ expect(viewDocument(confirmed, draft).cells.get("c1")?.code).toBe("back");
+ expect(viewDocument(confirmed, draft).order).toEqual(["c1", "c2"]);
+
+ const removed = withCells(confirmed, { c1: null });
+ const settled = acknowledge(draft, sent);
+ expect(viewDocument(removed, settled).order).toEqual(["c1", "c2"]);
+ expect(toChanges(removed, settled)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: null,
+ cell: { ...back, name: "_", config: CONFIG },
+ before: "c2",
+ },
+ ]);
+ });
});
describe("viewDocument", () => {
diff --git a/frontend/src/core/notebook/document/__tests__/state.test.ts b/frontend/src/core/notebook/document/__tests__/state.test.ts
index 5a7366668d..89c2e91b67 100644
--- a/frontend/src/core/notebook/document/__tests__/state.test.ts
+++ b/frontend/src/core/notebook/document/__tests__/state.test.ts
@@ -124,6 +124,27 @@ describe("document model", () => {
},
);
+ it("brings back a cell deleted earlier in the draft with new content", () => {
+ const { store, cellAtom, orderAtom, changesAtom, edit } = setup();
+ edit((tx) => tx.deleteCell("c1"));
+ edit((tx) => tx.createCell({ id: "c1", code: "back" }, { after: "c2" }));
+ expect(store.get(cellAtom("c1"))?.code).toBe("back");
+ expect(store.get(orderAtom)).toEqual(["c2", "c1"]);
+ expect(store.get(changesAtom)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: "c1-etag",
+ cell: {
+ id: "c1",
+ code: "back",
+ name: "_",
+ config: cell("c1", "").config,
+ },
+ },
+ { kind: "set_order", base_etag: "order-1", order: ["c2", "c1"] },
+ ]);
+ });
+
it("publishes the visible order when an anchor is deleted later in the draft", () => {
const { store, orderAtom, changesAtom, edit } = setup();
edit((tx) => {
diff --git a/frontend/src/core/notebook/document/draft.ts b/frontend/src/core/notebook/document/draft.ts
index dc1f2591fb..7920a1a08a 100644
--- a/frontend/src/core/notebook/document/draft.ts
+++ b/frontend/src/core/notebook/document/draft.ts
@@ -253,17 +253,47 @@ export function createCell(
input: Protocol.CellInput,
placement: Placement = {},
): Draft {
+ const cell = parseCell(input);
+ const next = withCell(draft, cell.id, { kind: "create", cell, placement });
+ return draft.order === null
+ ? next
+ : { ...next, order: insertAt(draft.order, cell.id, placement) };
+}
+
+/**
+ * Bring back a cell this draft deletes, with the given content.
+ *
+ * A deletion not yet sent is withdrawn and the cell edited in place. One in
+ * flight is superseded by a creation, so the cell returns once the host has
+ * removed it. Either way the cell takes the requested placement.
+ */
+export function restoreCell(
+ confirmed: Document,
+ draft: Draft,
+ input: Protocol.CellInput,
+ placement: Placement = {},
+ sent: Draft = EMPTY_DRAFT,
+): Draft {
+ const { id, code, name, config } = parseCell(input);
+ const withdrawn = withCell(draft, id, undefined);
+ const next =
+ sent.cells.get(id)?.kind === "delete"
+ ? createCell(withdrawn, input, placement)
+ : editCell(confirmed, withdrawn, id, { code, name, config });
+ const { order } = viewDocument(confirmed, next);
+ const placed = insertAt(order, id, placement);
+ return sameOrder(order, placed) ? next : setOrder(next, placed);
+}
+
+/** A cell input with the protocol's defaults filled in. */
+function parseCell(input: Protocol.CellInput): CellWithSource {
const parsed = Protocol.CellInput.parse(input);
- const cell: CellWithSource = {
+ return {
id: parsed.id,
code: parsed.code,
name: parsed.name,
config: parsed.config ?? Protocol.CellConfigInput.parse({}),
};
- const next = withCell(draft, cell.id, { kind: "create", cell, placement });
- return draft.order === null
- ? next
- : { ...next, order: insertAt(draft.order, cell.id, placement) };
}
/** Forget an unsent creation; otherwise retain the deletion until confirmed. */
diff --git a/frontend/src/core/notebook/document/index.ts b/frontend/src/core/notebook/document/index.ts
index 24be4f54bb..e28c1d4a35 100644
--- a/frontend/src/core/notebook/document/index.ts
+++ b/frontend/src/core/notebook/document/index.ts
@@ -21,3 +21,4 @@ export {
type EditableCell,
type EditableDocument,
} from "./model";
+export type { Placement } from "./draft";
diff --git a/frontend/src/core/notebook/document/state.ts b/frontend/src/core/notebook/document/state.ts
index c51934552c..25e1c8c962 100644
--- a/frontend/src/core/notebook/document/state.ts
+++ b/frontend/src/core/notebook/document/state.ts
@@ -13,6 +13,7 @@ import {
type CellEdit,
createCell,
deleteCell,
+ restoreCell,
type Draft,
type EditableDocument,
editCell,
@@ -30,6 +31,7 @@ export interface DocumentEditor {
setCode(id: Protocol.CellId, code: string): void;
setName(id: Protocol.CellId, name: string): void;
updateConfig(id: Protocol.CellId, patch: Partial<Protocol.CellConfig>): void;
+ /** Create a cell, or bring back one this draft deletes with this content. */
createCell(cell: Protocol.CellInput, placement?: Placement): void;
deleteCell(id: Protocol.CellId): void;
/** A permutation of the cells present at this point in the transaction. */
@@ -330,7 +332,7 @@ function editDocument(
updateCell(id, { config: Protocol.CellConfig.partial().parse(patch) }),
createCell: (cell, placement = {}) => {
assertActive();
- if (confirmed.cells.has(cell.id) || hasCell(cell.id)) {
+ if (hasCell(cell.id)) {
throw new Error(`Cell ${cell.id} already exists`);
}
if (placement.after !== undefined && placement.before !== undefined) {
@@ -340,7 +342,9 @@ function editDocument(
if (anchor !== undefined) {
requireCell(anchor);
}
- next = createCell(next, cell, { ...placement });
+ next = confirmed.cells.has(cell.id)
+ ? restoreCell(confirmed, next, cell, { ...placement }, sent)
+ : createCell(next, cell, { ...placement });
},
deleteCell: (id) => {
requireCell(id);
diff --git a/frontend/src/core/session/useNotebookSession.tsx b/frontend/src/core/session/useNotebookSession.tsx
index 1b809da475..0aaf0a807c 100644
--- a/frontend/src/core/session/useNotebookSession.tsx
+++ b/frontend/src/core/session/useNotebookSession.tsx
@@ -5,7 +5,11 @@ import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";
import { useEffect, useLayoutEffect, useMemo } from "react";
import { useErrorBoundary } from "react-error-boundary";
import { toast } from "@/components/ui/use-toast";
-import { getNotebook, notebookAtom, useCellActions } from "@/core/cells/cells";
+import {
+ getNotebook,
+ notebookAtom,
+ useReducerActions,
+} from "@/core/cells/cells";
import { followDocument } from "@/core/cells/document";
import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";
import { createDocumentModel } from "@/core/notebook/document";
@@ -91,7 +95,7 @@ export function useNotebookSession(opts: {
reconcileDocument,
setLastRun,
resetCellRuntimes,
- } = useCellActions();
+ } = useReducerActions();
const { addCellNotification } = useRunsActions();
const setKernelState = useSetAtom(kernelStateAtom);
const setInitialRunCompleted = useSetAtom(initialRunCompletedAtom);
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 0cb53f3ac0..f7692cce63 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -345,14 +345,6 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FormatResponse;
};
- public sendDeleteCell: EditRequests["sendDeleteCell"] = async (request) => {
- await this.putControlRequest({
- type: "delete-cell",
- ...request,
- });
- return null;
- };
-
public sendInstallMissingPackages: EditRequests["sendInstallMissingPackages"] =
async (request) => {
this.putControlRequest({
@@ -403,14 +395,6 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- public saveCellConfig: EditRequests["saveCellConfig"] = async (request) => {
- await this.putControlRequest({
- type: "update-cell-config",
- ...request,
- });
- return null;
- };
-
public sendRestart = async (): Promise<null> => {
// Save first
const code = await this.readCode();
diff --git a/frontend/src/css/globals.css b/frontend/src/css/globals.css
index 258fd03691..346a5416de 100644
--- a/frontend/src/css/globals.css
+++ b/frontend/src/css/globals.css
@@ -55,21 +55,29 @@
--background: light-dark(hsl(0deg 0% 100%), hsl(150deg 7.7% 10.2%));
--foreground: light-dark(hsl(222.2deg 47.4% 11.2%), hsl(155deg 7% 93%));
--muted: light-dark(hsl(210deg 40% 96.1%), hsl(180deg 14% 1%));
- --muted-foreground: light-dark(hsl(215.4deg 16.3% 46.9%),
- hsl(155deg 5% 68.3%));
+ --muted-foreground: light-dark(
+ hsl(215.4deg 16.3% 46.9%),
+ hsl(155deg 5% 68.3%)
+ );
--popover: light-dark(hsl(0deg 0% 100%), hsl(151deg 5.5% 15.2%));
- --popover-foreground: light-dark(hsl(222.2deg 47.4% 11.2%),
- hsl(155deg 5% 68.3%));
+ --popover-foreground: light-dark(
+ hsl(222.2deg 47.4% 11.2%),
+ hsl(155deg 5% 68.3%)
+ );
--card: light-dark(hsl(0deg 0% 100%), hsl(151deg 5.5% 15.2%));
- --card-foreground: light-dark(hsl(222.2deg 47.4% 11.2%),
- hsl(155deg 5% 76.3%));
+ --card-foreground: light-dark(
+ hsl(222.2deg 47.4% 11.2%),
+ hsl(155deg 5% 76.3%)
+ );
--border: light-dark(hsl(214.3deg 31.8% 91.4%), hsl(153deg 3.7% 24.2%));
--input: light-dark(hsl(0deg 0% 64%), hsl(154deg 3.3% 28.7%));
--primary: light-dark(hsl(208deg 93.5% 47.4%), hsl(192deg 59.8% 39%));
--primary-foreground: light-dark(hsl(210deg 40% 98%), hsl(190deg 80% 84%));
--secondary: light-dark(hsl(210deg 40% 96.1%), hsl(155deg 7% 93%));
- --secondary-foreground: light-dark(hsl(222.2deg 47.4% 11.2%),
- hsl(151deg 5.5% 15.2%));
+ --secondary-foreground: light-dark(
+ hsl(222.2deg 47.4% 11.2%),
+ hsl(151deg 5.5% 15.2%)
+ );
--accent: light-dark(hsl(209deg 100% 96.5%), hsl(192deg 56.6% 26.5%));
--accent-foreground: light-dark(hsl(211deg 90% 42%), hsl(190deg 80% 84%));
--ring: hsl(215deg 20.2% 65.1%);
@@ -101,8 +109,10 @@
/* Base shadows. */
--base-shadow: light-dark(hsl(0deg 0% 85% / 40%), hsla(0deg 0% 36% / 60%));
- --base-shadow-darker: light-dark(hsl(0deg 0% 50% / 40%),
- hsl(0deg 0% 50% / 60%));
+ --base-shadow-darker: light-dark(
+ hsl(0deg 0% 50% / 40%),
+ hsl(0deg 0% 50% / 60%)
+ );
--base-shadow-opacity: 5%;
/* Codemirror editor */
@@ -219,40 +229,64 @@
--shadow-xxs: 0px 0px 2px 0px var(--base-shadow-darker);
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-xs: 1px 1px 2px 0px var(--base-shadow), 0px 0px 2px 0px hsl(0deg 0% 25% / var(--base-shadow-opacity));
+ --shadow-xs:
+ 1px 1px 2px 0px var(--base-shadow),
+ 0px 0px 2px 0px hsl(0deg 0% 25% / var(--base-shadow-opacity));
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-sm: 2px 2px 2px 0px var(--base-shadow), 0px 0px 2px 0px hsl(0deg 0% 25% / var(--base-shadow-opacity));
+ --shadow-sm:
+ 2px 2px 2px 0px var(--base-shadow),
+ 0px 0px 2px 0px hsl(0deg 0% 25% / var(--base-shadow-opacity));
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-md: 4px 4px 4px 0px var(--base-shadow), 0 0px 4px 0px hsl(0deg 0% 60% / var(--base-shadow-opacity));
+ --shadow-md:
+ 4px 4px 4px 0px var(--base-shadow),
+ 0 0px 4px 0px hsl(0deg 0% 60% / var(--base-shadow-opacity));
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-lg: 5px 6px 4px 0px var(--base-shadow), 0 0px 4px 0px hsl(0deg 0% 75% / var(--base-shadow-opacity));
+ --shadow-lg:
+ 5px 6px 4px 0px var(--base-shadow),
+ 0 0px 4px 0px hsl(0deg 0% 75% / var(--base-shadow-opacity));
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-xl: 8px 9px 4px 0px var(--base-shadow), 0 0px 6px 0px hsl(0deg 0% 85% / var(--base-shadow-opacity));
+ --shadow-xl:
+ 8px 9px 4px 0px var(--base-shadow),
+ 0 0px 6px 0px hsl(0deg 0% 85% / var(--base-shadow-opacity));
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-2xl: 10px 12px 10px 0px var(--base-shadow), 0 0px 8px 0px hsl(0deg 0% 90% / var(--base-shadow-opacity));
+ --shadow-2xl:
+ 10px 12px 10px 0px var(--base-shadow),
+ 0 0px 8px 0px hsl(0deg 0% 90% / var(--base-shadow-opacity));
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-xs-solid: 1px 1px 0px 0px var(--base-shadow-darker), 0px 0px 2px 0px hsl(0deg 0% 50% / 20%);
+ --shadow-xs-solid:
+ 1px 1px 0px 0px var(--base-shadow-darker),
+ 0px 0px 2px 0px hsl(0deg 0% 50% / 20%);
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-sm-solid: 2px 2px 0px 0px var(--base-shadow-darker), 0px 0px 2px 0px hsl(0deg 0% 50% / 20%);
+ --shadow-sm-solid:
+ 2px 2px 0px 0px var(--base-shadow-darker),
+ 0px 0px 2px 0px hsl(0deg 0% 50% / 20%);
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-md-solid: 4px 4px 0px 0px var(--base-shadow-darker), 0 0px 2px 0px hsl(0deg 0% 60% / 50%);
+ --shadow-md-solid:
+ 4px 4px 0px 0px var(--base-shadow-darker),
+ 0 0px 2px 0px hsl(0deg 0% 60% / 50%);
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-lg-solid: 5px 6px 0px 0px var(--base-shadow-darker), 0 0px 4px 0px hsl(0deg 0% 75% / 50%);
+ --shadow-lg-solid:
+ 5px 6px 0px 0px var(--base-shadow-darker),
+ 0 0px 4px 0px hsl(0deg 0% 75% / 50%);
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-xl-solid: 7px 8px 0px 0px var(--base-shadow-darker), 0 0px 4px 0px hsl(0deg 0% 85% / 50%);
+ --shadow-xl-solid:
+ 7px 8px 0px 0px var(--base-shadow-darker),
+ 0 0px 4px 0px hsl(0deg 0% 85% / 50%);
/* oxfmt-ignore: definition needs to be oneline or breaks variants */
- --shadow-2xl-solid: 10px 12px 0px 0px var(--base-shadow-darker), 0 0px 8px 0px hsl(0deg 0% 90% / 50%);
+ --shadow-2xl-solid:
+ 10px 12px 0px 0px var(--base-shadow-darker),
+ 0 0px 8px 0px hsl(0deg 0% 90% / 50%);
/* Solid shadows with lighter shade color */
diff --git a/frontend/src/stories/runtime-story.tsx b/frontend/src/stories/runtime-story.tsx
index 2b49dd98c1..bd21bbb259 100644
--- a/frontend/src/stories/runtime-story.tsx
+++ b/frontend/src/stories/runtime-story.tsx
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { Meta } from "@storybook/react-vite";
import { createStore, Provider, useAtomValue, useStore } from "jotai";
-import { useEffect, useRef, useState } from "react";
+import { createRef, useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { ConnectionNotice } from "@/components/editor/alerts/connection-notice";
import PackagesPanel from "@/components/editor/chrome/panels/packages-panel";
@@ -13,11 +13,10 @@ import { Cell } from "@/components/editor/notebook-cell";
import { VerticalLayoutWrapper } from "@/components/editor/renderers/vertical-layout/vertical-layout-wrapper";
import { alertAtom } from "@/core/alerts/state";
import type { EnvironmentOperation } from "@/core/alerts/environment";
-import {
- createNotebookActions,
- notebookAtom,
- notebookReducer,
-} from "@/core/cells/cells";
+import { notebookAtom } from "@/core/cells/cells";
+import { CellId } from "@/core/cells/ids";
+import { createCell, createCellRuntimeState } from "@/core/cells/types";
+import { MultiColumn } from "@/utils/id-tree";
import { userConfigAtom } from "@/core/config/config";
import {
type AppConfig,
@@ -349,15 +348,23 @@ export function RuntimeStory(props: Props) {
log_mode: "replace",
});
if (props.existingCells) {
- const actions = createNotebookActions((action) =>
- state.set(notebookAtom, (value) => notebookReducer(value, action)),
- );
- actions.createNewCell({
- cellId: "__end__",
- before: false,
- code: 'import polars as pl\n\ntrips = pl.read_csv("bike_trips.csv")\ntrips.head()',
- autoFocus: false,
- });
+ const cellId = CellId.create();
+ state.set(notebookAtom, (value) => ({
+ ...value,
+ cellIds: MultiColumn.from([[cellId]]),
+ cellData: {
+ ...value.cellData,
+ [cellId]: createCell({
+ id: cellId,
+ code: 'import polars as pl\n\ntrips = pl.read_csv("bike_trips.csv")\ntrips.head()',
+ }),
+ },
+ cellRuntime: {
+ ...value.cellRuntime,
+ [cellId]: createCellRuntimeState(),
+ },
+ cellHandles: { ...value.cellHandles, [cellId]: createRef() },
+ }));
}
state.set(requestClientAtom, {
...createStaticRequests(),
diff --git a/marimo/_cli/development/schema.py b/marimo/_cli/development/schema.py
index bf3ad21f06..bb0a8a1a03 100644
--- a/marimo/_cli/development/schema.py
+++ b/marimo/_cli/development/schema.py
@@ -353,7 +353,6 @@ def generate_server_api_schema() -> dict[str, Any]:
models.CodeCompletionRequest,
models.CopyNotebookRequest,
models.DebugCellRequest,
- models.DeleteCellRequest,
models.DiscoverDataSourcesRequest,
models.ExecuteScratchpadRequest,
models.FormatCellsRequest,
@@ -384,7 +383,6 @@ def generate_server_api_schema() -> dict[str, Any]:
models.SaveUserConfigurationRequest,
models.StdinRequest,
models.SuccessResponse,
- models.UpdateCellConfigRequest,
models.FocusCellRequest,
session_requests.UpdateUIElementValuesRequest,
models.UpdateUIElementRequest,
diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.py
index 038400b6af..feea3e8657 100644
--- a/marimo/_server/api/endpoints/editing.py
+++ b/marimo/_server/api/endpoints/editing.py
@@ -17,14 +17,12 @@ from marimo._server.api.utils import (
from marimo._server.models.models import (
BaseResponse,
CodeCompletionRequest,
- DeleteCellRequest,
FocusCellRequest,
FormatCellsRequest,
FormatResponse,
InstallPackagesRequest,
StdinRequest,
SuccessResponse,
- UpdateCellConfigRequest,
)
from marimo._server.router import APIRouter
from marimo._utils.formatter import DefaultFormatter
@@ -62,32 +60,6 @@ async def code_complete(request: Request) -> BaseResponse:
return await dispatch_control_request(request, cls=CodeCompletionRequest)
-@requires("edit")
-async def delete_cell(request: Request) -> BaseResponse:
- """
- parameters:
- - in: header
- name: Marimo-Session-Id
- schema:
- type: string
- required: true
- requestBody:
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/DeleteCellRequest"
- responses:
- 200:
- description: Delete a cell
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/SuccessResponse"
- """
- return await dispatch_control_request(request, DeleteCellRequest)
-
-
@router.post("/focus_cell")
@requires("edit")
async def focus_cell(request: Request) -> BaseResponse:
@@ -165,32 +137,6 @@ async def format_cell(request: Request) -> FormatResponse:
) from None
[email protected]("/set_cell_config")
-@requires("edit")
-async def set_cell_config(request: Request) -> BaseResponse:
- """
- parameters:
- - in: header
- name: Marimo-Session-Id
- schema:
- type: string
- required: true
- requestBody:
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/UpdateCellConfigRequest"
- responses:
- 200:
- description: Set the configuration of a cell
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/SuccessResponse"
- """
- return await dispatch_control_request(request, UpdateCellConfigRequest)
-
-
@router.post("/stdin")
@requires("edit")
async def stdin(request: Request) -> BaseResponse:
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index 84f249b2d3..294872f91e 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -10,7 +10,6 @@ from marimo._runtime.commands import (
ClearCacheCommand,
CodeCompletionCommand,
DebugCellCommand,
- DeleteCellCommand,
DiscoverDataSourcesCommand,
ExecuteCellsCommand,
ExecuteScratchpadCommand,
@@ -28,7 +27,6 @@ from marimo._runtime.commands import (
SetBreakpointsCommand,
StorageDownloadCommand,
StorageListEntriesCommand,
- UpdateCellConfigCommand,
UpdateUIElementCommand,
UpdateUserConfigCommand,
ValidateSQLCommand,
@@ -190,11 +188,6 @@ class UpdateUserConfigRequest(UpdateUserConfigCommand, tag=False):
return UpdateUserConfigCommand(config=self.config)
-class DeleteCellRequest(DeleteCellCommand, tag=False):
- def as_command(self) -> DeleteCellCommand:
- return DeleteCellCommand(cell_id=self.cell_id)
-
-
class InstallPackagesRequest(InstallPackagesCommand, tag=False):
def as_command(self) -> InstallPackagesCommand:
return InstallPackagesCommand(
@@ -202,11 +195,6 @@ class InstallPackagesRequest(InstallPackagesCommand, tag=False):
)
-class UpdateCellConfigRequest(UpdateCellConfigCommand, tag=False):
- def as_command(self) -> UpdateCellConfigCommand:
- return UpdateCellConfigCommand(configs=self.configs)
-
-
class CodeCompletionRequest(CodeCompletionCommand, tag=False):
def as_command(self) -> CodeCompletionCommand:
return CodeCompletionCommand(
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 8b52a6784c..257e8e41ce 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -1452,14 +1452,6 @@ components:
- cellId
title: DeleteCellCommand
type: object
- DeleteCellRequest:
- properties:
- cellId:
- $ref: '#/components/schemas/CellId'
- required:
- - cellId
- title: DeleteCellRequest
- type: object
DeleteSecretRequest:
properties:
key:
@@ -6018,16 +6010,6 @@ components:
- configs
title: UpdateCellConfigCommand
type: object
- UpdateCellConfigRequest:
- properties:
- configs:
- additionalProperties:
- type: object
- type: object
- required:
- - configs
- title: UpdateCellConfigRequest
- type: object
UpdateCellOutputsRequest:
properties:
cellIdsToOutput:
@@ -7304,26 +7286,6 @@ paths:
schema:
type: string
description: Copy notebook
- /api/kernel/delete:
- post:
- parameters:
- - in: header
- name: Marimo-Session-Id
- required: true
- schema:
- type: string
- requestBody:
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/DeleteCellRequest'
- responses:
- 200:
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/SuccessResponse'
- description: Delete a cell
/api/kernel/focus_cell:
post:
parameters:
@@ -7630,26 +7592,6 @@ paths:
schema:
$ref: '#/components/schemas/SuccessResponse'
description: Run the scratchpad
- /api/kernel/set_cell_config:
- post:
- parameters:
- - in: header
- name: Marimo-Session-Id
- required: true
- schema:
- type: string
- requestBody:
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/UpdateCellConfigRequest'
- responses:
- 200:
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/SuccessResponse'
- description: Set the configuration of a cell
/api/kernel/set_model_value:
post:
parameters:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index a40737b615..bb235a3298 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -1934,47 +1934,6 @@ export interface paths {
patch?: never;
trace?: never;
};
- "/api/kernel/delete": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- post: {
- parameters: {
- query?: never;
- header: {
- "Marimo-Session-Id": string;
- };
- path?: never;
- cookie?: never;
- };
- requestBody?: {
- content: {
- "application/json": components["schemas"]["DeleteCellRequest"];
- };
- };
- responses: {
- /** @description Delete a cell */
- 200: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["SuccessResponse"];
- };
- };
- };
- };
- delete?: never;
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
"/api/kernel/focus_cell": {
parameters: {
query?: never;
@@ -2631,47 +2590,6 @@ export interface paths {
patch?: never;
trace?: never;
};
- "/api/kernel/set_cell_config": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- post: {
- parameters: {
- query?: never;
- header: {
- "Marimo-Session-Id": string;
- };
- path?: never;
- cookie?: never;
- };
- requestBody?: {
- content: {
- "application/json": components["schemas"]["UpdateCellConfigRequest"];
- };
- };
- responses: {
- /** @description Set the configuration of a cell */
- 200: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["SuccessResponse"];
- };
- };
- };
- };
- delete?: never;
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
"/api/kernel/set_model_value": {
parameters: {
query?: never;
@@ -4667,10 +4585,6 @@ export interface components {
/** @enum {unknown} */
type: "delete-cell";
};
- /** DeleteCellRequest */
- DeleteCellRequest: {
- cellId: components["schemas"]["CellId"];
- };
/** DeleteSecretRequest */
DeleteSecretRequest: {
key: string;
@@ -7394,12 +7308,6 @@ export interface components {
/** @enum {unknown} */
type: "update-cell-config";
};
- /** UpdateCellConfigRequest */
- UpdateCellConfigRequest: {
- configs: {
- [key: string]: Record<string, any>;
- };
- };
/** UpdateCellOutputsRequest */
UpdateCellOutputsRequest: {
cellIdsToOutput: {
diff --git a/tests/_server/api/endpoints/test_editing.py b/tests/_server/api/endpoints/test_editing.py
index ec510ae42c..1a44cce775 100644
--- a/tests/_server/api/endpoints/test_editing.py
+++ b/tests/_server/api/endpoints/test_editing.py
@@ -41,20 +41,6 @@ def test_code_autocomplete(client: TestClient) -> None:
assert "success" in response.json()
-@with_session(SESSION_ID)
-def test_delete_cell(client: TestClient) -> None:
- response = client.post(
- "/api/kernel/delete",
- headers=HEADERS,
- json={
- "cellId": "cell-123",
- },
- )
- assert response.status_code == 200, response.text
- assert response.headers["content-type"] == "application/json"
- assert "success" in response.json()
-
-
@pytest.mark.skipif(not HAS_FORMATTER, reason="ruff or black not installed")
@with_session(SESSION_ID)
def test_format_cell(client: TestClient) -> None:
@@ -148,22 +134,6 @@ def test_install_missing_packages_server_source(client: TestClient) -> None:
install_packages.assert_awaited_once_with({"nbformat": ""})
-@with_session(SESSION_ID)
-def test_set_cell_config(client: TestClient) -> None:
- response = client.post(
- "/api/kernel/set_cell_config",
- headers=HEADERS,
- json={
- "configs": {
- "cell-123": {"runnable": True},
- },
- },
- )
- assert response.status_code == 200, response.text
- assert response.headers["content-type"] == "application/json"
- assert "success" in response.json()
-
-
@with_session(SESSION_ID)
def test_stdin(client: TestClient) -> None:
response = client.post(