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.

Save the notebook through the host (#11553)

Trevor Manzbfe1ee7f1697
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index 47e9cf55c3..6e8cc2cb7f 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -17,7 +17,7 @@ export const MockRequestClient = {
sendModelValue: vi.fn().mockResolvedValue({}),
sendRename: vi.fn().mockResolvedValue({}),
sendRestart: vi.fn().mockResolvedValue({}),
- sendSave: vi.fn().mockResolvedValue({}),
+ saveLayout: vi.fn().mockResolvedValue({}),
sendCopy: vi.fn().mockResolvedValue({}),
sendStdin: vi.fn().mockResolvedValue({}),
sendFormat: vi.fn().mockResolvedValue({ codes: {} }),
diff --git a/frontend/src/components/editor/header/__tests__/filename-form.test.tsx b/frontend/src/components/editor/header/__tests__/filename-form.test.tsx
index 261165f84d..397dce8f91 100644
--- a/frontend/src/components/editor/header/__tests__/filename-form.test.tsx
+++ b/frontend/src/components/editor/header/__tests__/filename-form.test.tsx
@@ -73,10 +73,7 @@ describe("FilenameForm", () => {
});
await waitFor(() => {
- expect(mockSaveNotebook).toHaveBeenCalledWith(
- "/path/to/new-file.py",
- true,
- );
+ expect(mockSaveNotebook).toHaveBeenCalledWith(true);
});
});
diff --git a/frontend/src/components/editor/header/filename-form.tsx b/frontend/src/components/editor/header/filename-form.tsx
index 6e25e6e876..73921a680c 100644
--- a/frontend/src/components/editor/header/filename-form.tsx
+++ b/frontend/src/components/editor/header/filename-form.tsx
@@ -19,7 +19,7 @@ export const FilenameForm = ({
updateFilename(newFilename).then((name) => {
// When creating a new file (was unnamed), also save the content
if (name !== null && wasUnnamed) {
- saveNotebook(name, true);
+ saveNotebook(true);
}
});
};
diff --git a/frontend/src/core/cells/__tests__/document.test.ts b/frontend/src/core/cells/__tests__/document.test.ts
index 4480db451d..f6c4d23692 100644
--- a/frontend/src/core/cells/__tests__/document.test.ts
+++ b/frontend/src/core/cells/__tests__/document.test.ts
@@ -28,12 +28,7 @@ import {
type NotebookState,
notebookReducer,
} from "../cells";
-import {
- applyDocument,
- flushDocument,
- followDocument,
- withDocumentSave,
-} from "../document";
+import { applyDocument, flushDocument, followDocument } from "../document";
import { type CellId, SCRATCH_CELL_ID } from "../ids";
vi.mock("../../rtc/state", async (importOriginal) => ({
@@ -224,7 +219,6 @@ describe("documentEditMiddleware", () => {
syncStatusAtom: atom<DocumentSyncStatus>({ status: "idle" }),
flush: vi.fn(),
retry: vi.fn(),
- hold: () => () => undefined,
start: vi.fn(),
};
const actions = createNotebookActions((action) => {
@@ -303,7 +297,6 @@ describe("flushing before host commands", () => {
syncStatusAtom: atom<DocumentSyncStatus>({ status: "idle" }),
flush: vi.fn<() => Promise<never>>(),
retry: vi.fn<() => Promise<never>>(),
- hold: () => () => undefined,
} as unknown as DocumentModel;
beforeEach(() => {
@@ -324,18 +317,4 @@ describe("flushing before host commands", () => {
store.set(activeDocumentModelAtom, null);
await expect(flushDocument()).resolves.toBeUndefined();
});
-
- it("saves after a flush and resumes the model when the flush failed", async () => {
- vi.mocked(model.flush).mockRejectedValue(new Error("conflict"));
- vi.mocked(model.retry).mockResolvedValue(undefined as never);
- const save = vi.fn().mockResolvedValue("saved");
-
- await expect(withDocumentSave(save)).resolves.toBe("saved");
- expect(save).toHaveBeenCalledOnce();
- expect(model.retry).toHaveBeenCalledOnce();
-
- vi.mocked(model.flush).mockResolvedValue(undefined as never);
- await withDocumentSave(save);
- expect(model.retry).toHaveBeenCalledOnce();
- });
});
diff --git a/frontend/src/core/cells/__tests__/with-document-save.test.ts b/frontend/src/core/cells/__tests__/with-document-save.test.ts
deleted file mode 100644
index 3e2a72c78c..0000000000
--- a/frontend/src/core/cells/__tests__/with-document-save.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import { atom } from "jotai";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { createDocumentModel } from "@/core/notebook/document";
-import { document } from "@/core/notebook/document/__tests__/fixtures";
-import type { Document } from "@/core/notebook/replica/resources/document";
-import {
- type FakeEdit,
- fakeBackend,
-} from "@/core/notebook/replica/__tests__/fixtures";
-import { activeDocumentModelAtom } from "@/core/session/active-notebook";
-import { store } from "@/core/state/jotai";
-import { Deferred } from "@/utils/Deferred";
-import { withDocumentSave } from "../document";
-
-const lifetimes: AbortController[] = [];
-
-afterEach(() => {
- lifetimes.splice(0).forEach((controller) => controller.abort());
- store.set(activeDocumentModelAtom, null);
-});
-
-describe("withDocumentSave", () => {
- it("sends an edit made during the save only after the save finishes", async () => {
- const source = atom<Document | null>(document());
- const base = document();
- const accepted: Document = {
- ...base,
- revision: { ...base.revision, version: 2, etag: "document-2" },
- };
- // Answer the edit, then publish the accepted document as the host would.
- const edit = vi.fn<FakeEdit>().mockImplementation(async () => {
- queueMicrotask(() => store.set(source, accepted));
- return {
- ok: true,
- status: 200,
- data: { document: accepted.revision, cells: {} },
- };
- });
- const model = createDocumentModel({
- store,
- documentAtom: source,
- backendAtom: atom(fakeBackend({ edit })),
- });
- const controller = new AbortController();
- lifetimes.push(controller);
- model.start({ signal: controller.signal });
- store.set(activeDocumentModelAtom, model);
-
- const saving = new Deferred<void>();
- let flushing: Promise<unknown> | undefined;
- const saved = withDocumentSave(async () => {
- store.set(model.editAtom, (tx) => tx.setCode("c1", "x = 2"));
- flushing = model.flush();
- await Promise.resolve();
- expect(edit).not.toHaveBeenCalled();
- await saving.promise;
- return "saved";
- });
-
- saving.resolve();
- await expect(saved).resolves.toBe("saved");
- await flushing;
- expect(edit).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/frontend/src/core/cells/document.ts b/frontend/src/core/cells/document.ts
index d1fb040e40..d0be7c4040 100644
--- a/frontend/src/core/cells/document.ts
+++ b/frontend/src/core/cells/document.ts
@@ -254,36 +254,3 @@ export async function flushDocument(): Promise<void> {
}
await model.flush();
}
-
-/**
- * Run a legacy save after this client's edits reach the host, and keep
- * later edits local until it finishes. The save carries the whole
- * notebook and the host takes it as the document, so an edit sent
- * meanwhile would be overwritten. When the edits cannot be sent the save
- * still runs, and the model resumes against the saved document.
- *
- * TODO(MO-8028): Goes with the legacy save, along with the hold.
- */
-export async function withDocumentSave<T>(save: () => Promise<T>): Promise<T> {
- const model = store.get(activeDocumentModelAtom);
- if (model === null) {
- return save();
- }
- let flushed = true;
- try {
- await model.flush();
- } catch {
- flushed = false;
- }
- const release = model.hold();
- let result: T;
- try {
- result = await save();
- } finally {
- release();
- }
- if (!flushed) {
- void model.retry().catch(() => undefined);
- }
- return result;
-}
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 38b536515b..ab53481151 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -376,7 +376,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
public getUsageStats = throwNotImplemented;
public getEnvironmentInfo = throwNotImplemented;
public sendRename = throwNotImplemented;
- public sendSave = throwNotImplemented;
+ public saveLayout = throwNotImplemented;
public sendCopy = throwNotImplemented;
public sendRunScratchpad = throwNotImplemented;
public sendStdin = throwNotImplemented;
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index fb65507f5c..9866108a89 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -70,7 +70,7 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
sendRestart: "throwError",
// These wait until the connection is open, but don't start a connection
- sendSave: "waitForConnectionOpen",
+ saveLayout: "waitForConnectionOpen",
invokeAiTool: "waitForConnectionOpen",
sendFunctionRequest: "waitForConnectionOpen",
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index 85c498c3c9..f3d43f0853 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -78,15 +78,6 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
- sendSave: (request) => {
- return getClient()
- .POST("/api/kernel/save", {
- body: request,
- parseAs: "text",
- params: getParams(),
- })
- .then(handleResponseReturnNull);
- },
sendCopy: (request) => {
return getClient()
.POST("/api/kernel/copy", {
@@ -158,6 +149,14 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
+ saveLayout: (request) => {
+ return getClient()
+ .POST("/api/kernel/save_layout", {
+ body: request,
+ params: getParams(),
+ })
+ .then(handleResponseReturnNull);
+ },
saveAppConfig: (request) => {
return getClient()
.POST("/api/kernel/save_app_config", {
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index b27792e5d9..a7056faedb 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -43,7 +43,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
sendRun: throwNotInEditMode,
sendRunScratchpad: throwNotInEditMode,
sendRename: throwNotInEditMode,
- sendSave: throwNotInEditMode,
+ saveLayout: throwNotInEditMode,
sendCopy: throwNotInEditMode,
sendInterrupt: throwNotInEditMode,
sendShutdown: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index 3c058b7986..b0bc09181f 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -24,7 +24,7 @@ export function createErrorToastingRequests(
sendRun: "Failed to run",
sendRunScratchpad: "Failed to run scratchpad",
sendRename: "Failed to rename",
- sendSave: "Failed to save",
+ saveLayout: "", // The save reports it
sendCopy: "Failed to copy",
sendInterrupt: "Failed to interrupt",
sendShutdown: "Failed to shutdown",
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index a1725a4a2a..ca77110bdf 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -95,7 +95,7 @@ export type ExecuteCellsRequest = schemas["ExecuteCellsRequest"];
export type ExecuteScratchpadRequest = schemas["ExecuteScratchpadRequest"];
export type SaveAppConfigurationRequest =
schemas["SaveAppConfigurationRequest"];
-export type SaveNotebookRequest = schemas["SaveNotebookRequest"];
+export type SaveLayoutRequest = schemas["SaveLayoutRequest"];
export type CopyNotebookRequest = schemas["CopyNotebookRequest"];
export type SaveUserConfigurationRequest =
schemas["SaveUserConfigurationRequest"];
@@ -158,7 +158,11 @@ export interface RunRequests {
*/
export interface EditRequests {
sendRename: (request: RenameNotebookRequest) => Promise<null>;
- sendSave: (request: SaveNotebookRequest) => Promise<null>;
+ /**
+ * Write the notebook's layout beside it. The host protocol carries no
+ * layout yet, so this stays a request to the host serving the page.
+ */
+ saveLayout: (request: SaveLayoutRequest) => Promise<null>;
sendCopy: (request: CopyNotebookRequest) => Promise<null>;
sendStdin: (request: StdinRequest) => Promise<null>;
sendRun: (request: ExecuteCellsRequest) => Promise<null>;
diff --git a/frontend/src/core/notebook/document/__tests__/hold.test.ts b/frontend/src/core/notebook/document/__tests__/hold.test.ts
deleted file mode 100644
index 8f09dd762b..0000000000
--- a/frontend/src/core/notebook/document/__tests__/hold.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import { atom, createStore } from "jotai";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import type { Document } from "../../replica/resources/document";
-import { createDocumentModel } from "..";
-import { type FakeEdit, fakeBackend } from "../../replica/__tests__/fixtures";
-import { document } from "./fixtures";
-
-const lifetimes: AbortController[] = [];
-
-afterEach(() => {
- lifetimes.splice(0).forEach((controller) => controller.abort());
-});
-
-/** The document after the host accepts one edit. */
-function accepted(): Document {
- const base = document();
- return {
- ...base,
- revision: { ...base.revision, version: 2, etag: "document-2" },
- };
-}
-
-function setup() {
- const store = createStore();
- const source = atom<Document | null>(document());
- // Answer the edit, then publish the accepted document as the host would.
- const edit = vi.fn<FakeEdit>().mockImplementation(async () => {
- queueMicrotask(() => store.set(source, accepted()));
- return {
- ok: true,
- status: 200,
- data: { document: accepted().revision, cells: {} },
- };
- });
- const model = createDocumentModel({
- store,
- documentAtom: source,
- backendAtom: atom(fakeBackend({ edit })),
- });
- const controller = new AbortController();
- lifetimes.push(controller);
- model.start({ signal: controller.signal });
- return { store, model, edit, controller };
-}
-
-describe("document sync hold", () => {
- it("keeps an edit local until released, then lets a waiting flush send it", async () => {
- const { store, model, edit } = setup();
- const release = model.hold();
- store.set(model.editAtom, (tx) => tx.setCode("c1", "x = 2"));
- const flushing = model.flush();
- await Promise.resolve();
- expect(edit).not.toHaveBeenCalled();
- expect(store.get(model.syncStatusAtom)).toEqual({ status: "pending" });
-
- release();
- await flushing;
- expect(edit).toHaveBeenCalledTimes(1);
- });
-
- it("releases once the last of nested holds is released", async () => {
- const { store, model, edit } = setup();
- const outer = model.hold();
- const inner = model.hold();
- store.set(model.editAtom, (tx) => tx.setCode("c1", "x = 2"));
- const flushing = model.flush();
-
- inner();
- inner();
- await Promise.resolve();
- expect(edit).not.toHaveBeenCalled();
-
- outer();
- await flushing;
- expect(edit).toHaveBeenCalledTimes(1);
- });
-
- it("rejects a flush waiting on a hold when the model stops", async () => {
- const { store, model, controller } = setup();
- model.hold();
- store.set(model.editAtom, (tx) => tx.setCode("c1", "x = 2"));
- const flushing = model.flush();
- controller.abort(new Error("session ended"));
- await expect(flushing).rejects.toThrow("session ended");
- });
-});
diff --git a/frontend/src/core/notebook/document/model.ts b/frontend/src/core/notebook/document/model.ts
index 01fa0625de..7df2af90ab 100644
--- a/frontend/src/core/notebook/document/model.ts
+++ b/frontend/src/core/notebook/document/model.ts
@@ -31,8 +31,6 @@ export interface DocumentModel {
flush(): Promise<Protocol.Document>;
/** Retry a rejection against fresh state, or repeat an uncertain request exactly. */
retry(): Promise<Protocol.Document>;
- /** Keep edits local until the returned release is called. A no-op while stopped. */
- hold(): () => void;
/**
* Edit and synchronize until the signal aborts, which discards local drafts.
* The model can start again once stopped.
@@ -80,7 +78,6 @@ export function createDocumentModel({
}),
flush: () => store.get(runningAtom)?.sync.flush() ?? stopped(),
retry: () => store.get(runningAtom)?.sync.retry() ?? stopped(),
- hold: () => store.get(runningAtom)?.sync.hold() ?? (() => undefined),
start({ signal }) {
signal.throwIfAborted();
if (store.get(runningAtom)) {
diff --git a/frontend/src/core/notebook/document/sync.ts b/frontend/src/core/notebook/document/sync.ts
index 873c6bf9ea..81b6fb9a78 100644
--- a/frontend/src/core/notebook/document/sync.ts
+++ b/frontend/src/core/notebook/document/sync.ts
@@ -97,13 +97,6 @@ export function createDocumentSync({
let failure: Extract<DocumentSyncStatus, { status: "error" }> | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
let refreshing = false;
- // Holds keep edits local, as a legacy save needs while it writes the
- // notebook the flush before it produced.
- let holds = 0;
- let releaseWaiters: Array<{
- resolve: () => void;
- reject: (reason: unknown) => void;
- }> = [];
function clearTimer() {
clearTimeout(timer);
@@ -146,11 +139,9 @@ export function createDocumentSync({
store.set(statusAtom, { status: "idle" });
} else {
store.set(statusAtom, { status: "pending" });
- if (holds === 0) {
- timer = setTimeout(() => {
- void flush().catch(() => undefined);
- }, DEBOUNCE_MS);
- }
+ timer = setTimeout(() => {
+ void flush().catch(() => undefined);
+ }, DEBOUNCE_MS);
}
} finally {
refreshing = false;
@@ -323,11 +314,6 @@ export function createDocumentSync({
if (running) {
return running;
}
- if (holds > 0) {
- return new Promise<void>((resolve, reject) => {
- releaseWaiters.push({ resolve, reject });
- }).then(flush);
- }
const notebookId =
active?.submission.notebookId ?? store.get(source)?.revision.notebook_id;
if (notebookId === undefined) {
@@ -367,52 +353,17 @@ export function createDocumentSync({
return flush();
}
- /**
- * Keep edits local until the returned release is called. Flushes
- * requested meanwhile wait for it. Holds nest, and a release is
- * idempotent.
- *
- * TODO(MO-8028): Only the legacy save needs this, since the host takes
- * the notebook it writes as the document. Saving through the host
- * removes both.
- */
- function hold(): () => void {
- holds += 1;
- let held = true;
- return () => {
- if (!held) {
- return;
- }
- held = false;
- holds -= 1;
- if (holds > 0) {
- return;
- }
- const waiters = releaseWaiters;
- releaseWaiters = [];
- for (const waiter of waiters) {
- waiter.resolve();
- }
- refresh();
- };
- }
-
const unsubscribe = store.sub(observed, refresh);
function stop() {
clearTimer();
unsubscribe();
signal.removeEventListener("abort", stop);
active?.controller.abort(signal.reason);
- const waiters = releaseWaiters;
- releaseWaiters = [];
- for (const waiter of waiters) {
- waiter.reject(signal.reason);
- }
}
signal.addEventListener("abort", stop, { once: true });
if (signal.aborted) {
stop();
}
refresh();
- return { statusAtom, flush, retry, hold };
+ return { statusAtom, flush, retry };
}
diff --git a/frontend/src/core/saving/__tests__/document.test.tsx b/frontend/src/core/saving/__tests__/document.test.tsx
new file mode 100644
index 0000000000..3726802633
--- /dev/null
+++ b/frontend/src/core/saving/__tests__/document.test.tsx
@@ -0,0 +1,123 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type * as Protocol from "@marimo-team/client/protocol";
+import { renderHook } from "@testing-library/react";
+import { atom, createStore } from "jotai";
+import type { PropsWithChildren } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { DocumentWrapper } from "@/__mocks__/document";
+import { partial } from "@/__mocks__/partial";
+import type {
+ DocumentModel,
+ DocumentSyncStatus,
+} from "@/core/notebook/document";
+import type { NotebookReplica } from "@/core/notebook/replica";
+import {
+ type FakeSave,
+ fakeBackend,
+} from "@/core/notebook/replica/__tests__/fixtures";
+import { activeNotebookReplicaAtom } from "@/core/session/active-notebook";
+import { Deferred } from "@/utils/Deferred";
+import { useNotebookDocumentSave } from "../document";
+
+const confirmed: Protocol.Document = {
+ notebook_id: "n1",
+ order: [],
+ app_config: {},
+ etag: "e1",
+ saved_etag: null,
+ order_etag: "o1",
+ app_config_etag: "a1",
+ version: 1,
+};
+
+const saved: FakeSave = async () => ({
+ ok: true,
+ status: 200,
+ data: { document: confirmed, cells: {} },
+});
+
+function setup({
+ flush = vi.fn(async () => confirmed),
+ save = vi.fn(saved),
+ connected = true,
+}: {
+ flush?: DocumentModel["flush"];
+ save?: FakeSave;
+ connected?: boolean;
+} = {}) {
+ const store = createStore();
+ const model = partial<DocumentModel>(
+ {
+ flush,
+ retry: vi.fn(),
+ syncStatusAtom: atom<DocumentSyncStatus>({ status: "idle" }),
+ },
+ "model",
+ );
+ if (connected) {
+ store.set(
+ activeNotebookReplicaAtom,
+ partial<NotebookReplica>(
+ { backendAtom: atom(fakeBackend({ save })) },
+ "replica",
+ ),
+ );
+ }
+ const wrapper = ({ children }: PropsWithChildren) => (
+ <DocumentWrapper store={store} model={model}>
+ {children}
+ </DocumentWrapper>
+ );
+ const { result } = renderHook(() => useNotebookDocumentSave(), { wrapper });
+ return { saveDocument: result.current, flush, save };
+}
+
+describe("useNotebookDocumentSave", () => {
+ it("flushes this client's edits, then saves the flushed notebook", async () => {
+ const flushed = new Deferred<Protocol.Document>();
+ const save = vi.fn(saved);
+ const { saveDocument } = setup({ flush: () => flushed.promise, save });
+ const saving = saveDocument();
+ await Promise.resolve();
+ expect(save).not.toHaveBeenCalled();
+ flushed.resolve(confirmed);
+ await saving;
+ expect(save).toHaveBeenCalledWith("n1");
+ });
+
+ it("does not save when flushing fails", async () => {
+ const save = vi.fn(saved);
+ const { saveDocument } = setup({
+ flush: () => Promise.reject(new Error("unsynchronized edit")),
+ save,
+ });
+ await expect(saveDocument()).rejects.toThrow("unsynchronized edit");
+ expect(save).not.toHaveBeenCalled();
+ });
+
+ it("reports the host's refusal", async () => {
+ const { saveDocument } = setup({
+ save: async () => ({
+ ok: false,
+ status: 409,
+ problem: {
+ type: "about:blank",
+ title: "Conflict",
+ status: 409,
+ detail: "storage full",
+ },
+ }),
+ });
+ await expect(saveDocument()).rejects.toThrow("storage full");
+ });
+
+ it("does not save while no notebook is connected", async () => {
+ const flush = vi.fn(async () => confirmed);
+ const { saveDocument } = setup({ flush, connected: false });
+ await expect(saveDocument()).rejects.toThrow(
+ "The notebook is not connected",
+ );
+ expect(flush).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/core/saving/document.ts b/frontend/src/core/saving/document.ts
new file mode 100644
index 0000000000..cc1a6821e4
--- /dev/null
+++ b/frontend/src/core/saving/document.ts
@@ -0,0 +1,33 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/** Save the host's document from React. */
+
+import { useAtomValue } from "jotai";
+import { useCallback } from "react";
+import { useNotebookDocumentSync } from "@/core/notebook/document";
+import { activeNotebookBackendAtom } from "../session/active-notebook";
+
+/**
+ * Save the notebook's document through its host. This client's edits are
+ * flushed first, so the host writes nothing older than what the editor
+ * shows, and a failure at either step rejects.
+ *
+ * ```ts
+ * const saveDocument = useNotebookDocumentSave();
+ * await saveDocument();
+ * ```
+ */
+export function useNotebookDocumentSave() {
+ const { flush } = useNotebookDocumentSync();
+ const backend = useAtomValue(activeNotebookBackendAtom);
+ return useCallback(async () => {
+ if (backend === null) {
+ throw new Error("The notebook is not connected");
+ }
+ const { notebook_id } = await flush();
+ const result = await backend.notebook(notebook_id).save();
+ if (!result.ok) {
+ throw new Error(result.problem.detail ?? result.problem.title);
+ }
+ }, [flush, backend]);
+}
diff --git a/frontend/src/core/saving/save-component.tsx b/frontend/src/core/saving/save-component.tsx
index 365aba85e1..a05beeb946 100644
--- a/frontend/src/core/saving/save-component.tsx
+++ b/frontend/src/core/saving/save-component.tsx
@@ -20,8 +20,8 @@ import {
import { Label } from "../../components/ui/label";
import { useEvent } from "../../hooks/useEvent";
import { Logger } from "../../utils/Logger";
-import { getCellConfigs, getNotebook } from "../cells/cells";
-import { flushDocument, withDocumentSave } from "../cells/document";
+import { toast } from "@/components/ui/use-toast";
+import { getNotebook } from "../cells/cells";
import { notebookCells } from "../cells/utils";
import { formatAll } from "../codemirror/format";
import { autoSaveConfigAtom } from "../config/config";
@@ -32,9 +32,9 @@ import { connectionAtom } from "../network/connection";
import { canEditAtom } from "@/core/notebook";
import { useRequestClient } from "../network/requests";
import { ConnectionState } from "../session/types";
-import { isWasm } from "../wasm/utils";
import { filenameAtom } from "./file-state";
import { useFilename, useUpdateFilename } from "./filename";
+import { useNotebookDocumentSave } from "./document";
import { documentVersionAtom, needsSaveAtom, savedLayoutAtom } from "./state";
import { useAutoSave } from "./useAutoSave";
@@ -99,13 +99,14 @@ export const SaveComponent = () => {
};
export function useSaveNotebook() {
- const { sendSave } = useRequestClient();
+ const { saveLayout } = useRequestClient();
+ const saveDocument = useNotebookDocumentSave();
const { openModal, closeModal, openAlert } = useImperativeModal();
const updateFilename = useUpdateFilename();
const store = useStore();
- // Save the notebook with the given filename
- const saveNotebook = useEvent((filename: string, userInitiated: boolean) =>
+ // Save the notebook the host has a file for.
+ const saveNotebook = useEvent((userInitiated: boolean) =>
enqueueNotebookSave(async () => {
const connection = store.get(connectionAtom);
const autoSaveConfig = store.get(autoSaveConfigAtom);
@@ -121,8 +122,6 @@ export function useSaveNotebook() {
return;
}
- Logger.log("saving to ", filename);
-
if (userInitiated && autoSaveConfig.format_on_save) {
Logger.log("formatting notebook (onSave)");
await formatAll();
@@ -132,34 +131,22 @@ export function useSaveNotebook() {
return;
}
- const save = async () => {
- // Grab the latest notebook state after formatting and after every
- // earlier document transaction has reached the server.
- const notebook = getNotebook();
- const cells = notebookCells(notebook);
- const cellIds = cells.map((cell) => cell.id);
- const codes = cells.map((cell) => cell.code);
- const cellNames = cells.map((cell) => cell.name);
- const configs = getCellConfigs(notebook);
- const layout = store.get(layoutStateAtom);
-
- await sendSave({
- cellIds: cellIds,
- codes,
- names: cellNames,
- filename,
- configs,
- layout: getSerializedLayout(),
- persist: true,
+ // The notebook is the host's document plus a layout the editor keeps
+ // beside it. TODO: fold the layout into the host document.
+ const layout = store.get(layoutStateAtom);
+ try {
+ await saveLayout({ layout: getSerializedLayout() });
+ await saveDocument();
+ } catch (error) {
+ Logger.error("Failed to save notebook", error);
+ toast({
+ title: "Failed to save",
+ description: error instanceof Error ? error.message : String(error),
+ variant: "danger",
});
- return layout;
- };
- // TODO(MO-7955): Remove this conditional once all frontend saves use
- // the host protocol. Host saves cannot recover edits from an editor snapshot.
- const savedLayout = isWasm()
- ? await flushDocument().then(save)
- : await withDocumentSave(save);
- store.set(savedLayoutAtom, savedLayout);
+ return;
+ }
+ store.set(savedLayoutAtom, layout);
}),
);
@@ -171,14 +158,14 @@ export function useSaveNotebook() {
isNamedPersistentFile(filename) &&
connection.state === ConnectionState.OPEN
) {
- saveNotebook(filename, userInitiated);
+ saveNotebook(userInitiated);
}
});
const handleSaveDialog = (pythonFilename: string) => {
updateFilename(pythonFilename).then((name) => {
if (name !== null) {
- saveNotebook(name, true);
+ saveNotebook(true);
}
});
};
diff --git a/frontend/src/core/session/active-notebook.ts b/frontend/src/core/session/active-notebook.ts
index b8c749061a..482258e0d5 100644
--- a/frontend/src/core/session/active-notebook.ts
+++ b/frontend/src/core/session/active-notebook.ts
@@ -10,6 +10,12 @@ export const activeNotebookReplicaAtom = atom<NotebookReplica | null>(null);
/** The document model owned by the mounted notebook session. */
export const activeDocumentModelAtom = atom<DocumentModel | null>(null);
+/** The backend of the connected notebook, or null while none is. */
+export const activeNotebookBackendAtom = atom((get) => {
+ const replica = get(activeNotebookReplicaAtom);
+ return replica === null ? null : get(replica.backendAtom);
+});
+
/**
* The document the host last confirmed, or null while no notebook is
* connected. Facts the host owns read this one, such as permission, the
diff --git a/frontend/src/core/wasm/__tests__/bridge.test.ts b/frontend/src/core/wasm/__tests__/bridge.test.ts
index ba6f929bd4..f85f70260a 100644
--- a/frontend/src/core/wasm/__tests__/bridge.test.ts
+++ b/frontend/src/core/wasm/__tests__/bridge.test.ts
@@ -1,7 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cellId } from "@/__tests__/branded";
import { Deferred } from "@/utils/Deferred";
const {
@@ -11,7 +10,6 @@ const {
mockWriteNotebook,
mockNotebookCall,
mockSetNotebookLayout,
- mockFlush,
parentRequests,
mockBootstrap,
rpcListeners,
@@ -24,7 +22,6 @@ const {
mockWriteNotebook: vi.fn(),
mockNotebookCall: vi.fn(),
mockSetNotebookLayout: vi.fn(),
- mockFlush: vi.fn(),
parentRequests: {} as {
persistNotebook?: (snapshot: {
filename: string;
@@ -101,18 +98,9 @@ vi.mock("@/core/wasm/store", () => ({
notebookFileStore: { readFile: mockNotebookReadFile, saveFile: vi.fn() },
}));
-vi.mock("@/core/cells/document", async (importOriginal) => ({
- ...(await importOriginal<typeof import("@/core/cells/document")>()),
- flushDocument: mockFlush,
-}));
-
// Import after all mocks are set up
import { store } from "@/core/state/jotai";
import { initialModeAtom } from "@/core/mode";
-import { fixtureEvents } from "@/core/notebook/replica/__tests__/fixtures";
-import { createNotebookReplica } from "@/core/notebook/replica";
-import { activeNotebookReplicaAtom } from "@/core/session/active-notebook";
-import { createEditorBackend } from "@/core/session/backend";
import { fallbackFileStore, notebookFileStore } from "../store";
import { getWasmWorkerName, PyodideBridge } from "../bridge";
@@ -200,130 +188,18 @@ describe("PyodideBridge.exportAsScript", () => {
});
});
-describe("PyodideBridge.sendSave", () => {
- let disconnect: () => void;
- const request = {
- cellIds: [cellId("cell-1")],
- codes: ['value = "NEW"'],
- names: ["_"],
- filename: "notebook.py",
- configs: [{}],
- layout: null,
- persist: true,
- };
-
- beforeEach(async () => {
+describe("PyodideBridge notebook persistence", () => {
+ beforeEach(() => {
vi.clearAllMocks();
store.set(initialModeAtom, "edit");
rpcListeners.initialized();
- mockFlush.mockResolvedValue(undefined);
mockWriteNotebook.mockResolvedValue(undefined);
- mockNotebookUnsubscribe.mockResolvedValue(undefined);
- const document = fixtureEvents("notebook-events.sse").find(
- (event) => event.event === "document",
- )?.data.document;
- mockNotebookCall.mockResolvedValue({
- status: 200,
- body: { document, cells: {} },
- });
- mockNotebookSubscribe.mockImplementation(async ({ id }) => {
- for (const event of fixtureEvents("notebook-events.sse")) {
- rpcListeners.notebookEvent({ id, event: JSON.stringify(event) });
- }
- });
- const replica = createNotebookReplica(store);
- store.set(activeNotebookReplicaAtom, replica);
- const backend = createEditorBackend({
- static: false,
- snapshot: null,
- transportType: "sse",
- url: () => "http://localhost/",
- headers: () => ({}),
- notebookUrl: (id) => new URL(`http://localhost/notebooks/${id}`),
- waitUntilReady: async () => undefined,
- checkHealth: async () => true,
- });
- disconnect = replica.connect(backend, { onNotification: vi.fn() });
- await vi.waitFor(() =>
- expect(store.get(replica.notebookAtom)?.id).toBe("n1"),
- );
});
afterEach(() => {
- disconnect();
- store.set(activeNotebookReplicaAtom, null);
store.set(initialModeAtom, undefined);
});
- it("saves through the connected backend using the stream's notebook ID", async () => {
- const bridge = PyodideBridge.INSTANCE;
- const createBackend = vi.spyOn(bridge, "createNotebookBackend");
- await bridge.sendSave(request);
- expect(createBackend).not.toHaveBeenCalled();
- expect(mockNotebookCall).toHaveBeenCalledWith(
- expect.objectContaining({
- operation: "notebook.save",
- params: { notebook_id: "n1" },
- body: {},
- }),
- );
- });
-
- it.each(["unmounted", "not ready", "disconnected"])(
- "does not save when the notebook is %s",
- async (state) => {
- if (state === "unmounted") {
- store.set(activeNotebookReplicaAtom, null);
- } else if (state === "not ready") {
- store.set(activeNotebookReplicaAtom, createNotebookReplica(store));
- } else {
- disconnect();
- }
- await expect(PyodideBridge.INSTANCE.sendSave(request)).rejects.toThrow(
- "The notebook is not connected",
- );
- expect(mockNotebookCall).not.toHaveBeenCalled();
- },
- );
-
- it("flushes edits before asking the host to save without an editor snapshot", async () => {
- const flushed = new Deferred<void>();
- mockFlush.mockReturnValueOnce(flushed.promise);
- const saving = PyodideBridge.INSTANCE.sendSave(request);
- await Promise.resolve();
- expect(mockNotebookCall).not.toHaveBeenCalled();
- flushed.resolve();
- await saving;
- expect(mockSetNotebookLayout).toHaveBeenCalledWith(null);
- expect(mockNotebookCall).toHaveBeenCalledWith(
- expect.objectContaining({ operation: "notebook.save", body: {} }),
- );
- expect(mockWriteNotebook).not.toHaveBeenCalled();
- });
-
- it("does not save when flushing fails", async () => {
- mockFlush.mockRejectedValueOnce(new Error("unsynchronized edit"));
- await expect(PyodideBridge.INSTANCE.sendSave(request)).rejects.toThrow(
- "unsynchronized edit",
- );
- expect(mockNotebookCall).not.toHaveBeenCalled();
- });
-
- it("reports host persistence failures", async () => {
- mockNotebookCall.mockResolvedValueOnce({
- status: 409,
- body: {
- type: "tag:marimo.io,2026:host/conflict",
- title: "Conflict",
- status: 409,
- detail: "storage full",
- },
- });
- await expect(PyodideBridge.INSTANCE.sendSave(request)).rejects.toThrow(
- "storage full",
- );
- });
-
it("persists exactly the host's content before acknowledging storage", async () => {
const durable = new Deferred<void>();
const snapshot = { filename: "notebook.py", contents: "# host revision" };
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index f7692cce63..c203236c4c 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -42,7 +42,6 @@ import type {
} from "../network/types";
import { filenameAtom } from "../saving/file-state";
import { store } from "../state/jotai";
-import { activeNotebookReplicaAtom } from "../session/active-notebook";
import { PyodideRouter } from "./router";
import { getWorkerRPC, type PersistNotebookRequest } from "./rpc";
import { getWasmRuntimeConfig } from "./runtime-config";
@@ -266,23 +265,8 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- private async saveHostNotebook() {
- const replica = store.get(activeNotebookReplicaAtom);
- const notebook = replica && store.get(replica.notebookAtom);
- const backend = replica && store.get(replica.backendAtom);
- if (!notebook || !backend) {
- throw new Error("The notebook is not connected");
- }
- const result = await backend.notebook(notebook.id).save();
- if (!result.ok) {
- throw new Error(result.problem.detail ?? result.problem.title);
- }
- }
-
- public sendSave: EditRequests["sendSave"] = async ({ layout }) => {
- await flushDocument();
+ public saveLayout: EditRequests["saveLayout"] = async ({ layout }) => {
await this.rpc.proxy.request.setNotebookLayout(layout ?? null);
- await this.saveHostNotebook();
return null;
};
@@ -391,7 +375,6 @@ export class PyodideBridge implements RunRequests, EditRequests {
functionName: "save_app_config",
payload: request,
});
- await this.saveHostNotebook();
return null;
};
diff --git a/frontend/src/core/wasm/worker/worker.ts b/frontend/src/core/wasm/worker/worker.ts
index e5e6eb426c..d16896b1c8 100644
--- a/frontend/src/core/wasm/worker/worker.ts
+++ b/frontend/src/core/wasm/worker/worker.ts
@@ -12,7 +12,7 @@ import type { UserConfig } from "@/core/config/config-schema";
import type {
ListPackagesResponse,
PackageOperationResponse,
- SaveNotebookRequest,
+ SaveLayoutRequest,
} from "@/core/network/types";
import { decodeUtf8 } from "@/utils/strings";
import { Deferred } from "../../../utils/Deferred";
@@ -301,7 +301,7 @@ const requestHandler = createRPCRequestHandler({
};
},
- setNotebookLayout: async (layout: SaveNotebookRequest["layout"]) => {
+ setNotebookLayout: async (layout: SaveLayoutRequest["layout"]) => {
const notebook = await getNotebook();
try {
await notebook.set_layout(JSON.stringify(layout));
diff --git a/marimo/_cli/development/schema.py b/marimo/_cli/development/schema.py
index bb0a8a1a03..a22b2fd7ca 100644
--- a/marimo/_cli/development/schema.py
+++ b/marimo/_cli/development/schema.py
@@ -379,7 +379,7 @@ def generate_server_api_schema() -> dict[str, Any]:
models.RenameNotebookRequest,
models.ExecuteCellsRequest,
models.SaveAppConfigurationRequest,
- models.SaveNotebookRequest,
+ models.SaveLayoutRequest,
models.SaveUserConfigurationRequest,
models.StdinRequest,
models.SuccessResponse,
diff --git a/marimo/_pyodide/notebook.py b/marimo/_pyodide/notebook.py
index 8e7e843500..8e254a481b 100644
--- a/marimo/_pyodide/notebook.py
+++ b/marimo/_pyodide/notebook.py
@@ -4,6 +4,7 @@
from __future__ import annotations
import asyncio
+import uuid
from pathlib import Path
from typing import TYPE_CHECKING
@@ -241,6 +242,17 @@ class PyodideNotebook:
self._session.app_manager.app.config.asdict_difference(),
)
+ async def save_app_config(self, config: dict[str, Any]) -> None:
+ """Apply the config and write the notebook, as the server does."""
+ await self.update_config(config)
+ if self._persist is not None:
+ await self.save(
+ self.id,
+ if_match=None,
+ decisions={},
+ request_id=f"app-config:{uuid.uuid4()}",
+ )
+
async def set_layout(self, raw: str) -> None:
layout = msgspec.json.decode(raw, type=LayoutConfig | None)
# Inline layouts survive URL/local-storage reloads along with the source.
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 2bd1d9c847..c56987ebd2 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -331,7 +331,7 @@ class PyodideBridge:
async def save_app_config(self, request: str) -> None:
parsed = self._parse(request, SaveAppConfigurationRequest)
- await self.notebook.update_config(parsed.config)
+ await self.notebook.save_app_config(parsed.config)
def save_user_config(self, request: str) -> None:
parsed = self._parse(request, SaveUserConfigurationRequest)
diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.py
index 0f2e39fe99..7336148298 100644
--- a/marimo/_server/api/endpoints/files.py
+++ b/marimo/_server/api/endpoints/files.py
@@ -9,9 +9,6 @@ from starlette.exceptions import HTTPException
from starlette.responses import PlainTextResponse
from marimo import _loggers
-from marimo._messaging.notification import (
- NotebookDocumentTransactionNotification,
-)
from marimo._runtime.commands import RenameNotebookCommand
from marimo._server.api.deps import AppState
from marimo._server.api.utils import (
@@ -25,7 +22,7 @@ from marimo._server.models.models import (
ReadCodeResponse,
RenameNotebookRequest,
SaveAppConfigurationRequest,
- SaveNotebookRequest,
+ SaveLayoutRequest,
SuccessResponse,
)
from marimo._server.router import APIRouter
@@ -149,12 +146,12 @@ async def rename_file(
return SuccessResponse()
[email protected]("/save_layout")
@requires("edit")
-async def save(
+async def save_layout(
*,
request: Request,
-) -> PlainTextResponse:
+) -> BaseResponse:
"""
parameters:
- in: header
@@ -166,41 +163,21 @@ async def save(
content:
application/json:
schema:
- $ref: "#/components/schemas/SaveNotebookRequest"
+ $ref: "#/components/schemas/SaveLayoutRequest"
responses:
200:
- description: Save the current app
+ description: Write the notebook's layout file and point its app config at it
content:
- text/plain:
+ application/json:
schema:
- type: string
+ $ref: "#/components/schemas/SuccessResponse"
"""
app_state = AppState(request)
- body = await parse_request(request, cls=SaveNotebookRequest)
- directory = app_state.session_manager.workspace.directory
-
- # Resolve relative filenames against the workspace's directory
- if body.filename and not Path(body.filename).is_absolute():
- if directory:
- body.filename = str(Path(directory) / body.filename)
-
- # Prevent path traversal: ensure target is inside the router's directory
- if directory and body.filename:
- PathValidator().validate_inside_directory(
- Path(directory), Path(body.filename)
- )
-
- session = app_state.require_current_session()
- session_id = app_state.require_current_session_id()
- contents = session.app_file_manager.save(
- body,
- on_document_transaction=lambda transaction: session.notify(
- NotebookDocumentTransactionNotification(transaction=transaction),
- from_consumer_id=ConsumerId(session_id),
- ),
+ body = await parse_request(request, cls=SaveLayoutRequest)
+ app_state.require_current_session().app_file_manager.save_layout(
+ body.layout
)
-
- return PlainTextResponse(content=contents)
+ return SuccessResponse()
@router.post("/copy")
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index 294872f91e..14a7dfb93e 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -5,7 +5,6 @@ from typing import Any, Literal
import msgspec
-from marimo._ast.cell import CellConfig
from marimo._runtime.commands import (
ClearCacheCommand,
CodeCompletionCommand,
@@ -267,33 +266,10 @@ class ExecuteCellsRequest(msgspec.Struct, rename="camel"):
)
-class SaveNotebookRequest(msgspec.Struct, rename="camel"):
- # id of each cell
- cell_ids: list[CellId_t]
- # code for each cell
- codes: list[str]
- # name of each cell
- names: list[str]
- # config for each cell
- configs: list[CellConfig]
- # path to app
- filename: str
- # layout of app
- layout: dict[str, Any] | None = None
- # persist the file to disk
- persist: bool = True
+class SaveLayoutRequest(msgspec.Struct, rename="camel"):
+ """The notebook's layout, written beside it; `None` removes it."""
- # Validate same length
- def __post_init__(self) -> None:
- assert len(self.cell_ids) == len(self.codes), (
- "Mismatched cell_ids and codes"
- )
- assert len(self.cell_ids) == len(self.names), (
- "Mismatched cell_ids and names"
- )
- assert len(self.cell_ids) == len(self.configs), (
- "Mismatched cell_ids and configs"
- )
+ layout: dict[str, Any] | None = None
class CopyNotebookRequest(msgspec.Struct, rename="camel"):
diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.py
index 66a0a4a9d2..e076cdd692 100644
--- a/marimo/_session/notebook/file_manager.py
+++ b/marimo/_session/notebook/file_manager.py
@@ -39,7 +39,6 @@ if TYPE_CHECKING:
from marimo._config.manager import MarimoConfigManager
from marimo._server.models.models import (
CopyNotebookRequest,
- SaveNotebookRequest,
)
@@ -422,83 +421,28 @@ class AppFileManager:
if callback is not None and self.app.config.asdict() != before:
callback()
- def save(
- self,
- request: SaveNotebookRequest,
- *,
- on_document_transaction: Callable[[Transaction], None] | None = None,
- ) -> str:
- """Save the notebook.
-
- Args:
- request: Save request with cell data and options
- on_document_transaction: Called with the applied in-memory
- document transaction before the file is persisted.
-
- Returns:
- Serialized notebook content
+ def save_layout(self, layout: dict[str, Any] | None) -> None:
+ """Write the layout file beside the notebook and point the app config
+ at it, or clear the config when `layout` is None.
Raises:
- HTTPException: If save fails or tries to rename
+ HTTPException: If the notebook has no file to sit beside.
"""
- cell_ids, codes, configs, names, filename, layout = (
- request.cell_ids,
- request.codes,
- request.configs,
- request.names,
- request.filename,
- request.layout,
- )
-
- filename_path = Path(canonicalize_filename(filename))
-
with self._save_lock:
- if self.is_notebook_named and not self._is_same_path(
- filename_path
- ):
+ if self._filename is None:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
- detail="Save handler cannot rename files.",
+ detail="Save the notebook before saving its layout.",
)
-
- transaction = self.app.apply_data(
- cell_ids=cell_ids,
- codes=codes,
- names=names,
- configs=configs,
- )
- if on_document_transaction is not None and transaction.changes:
- on_document_transaction(transaction)
-
- # Save layout if provided
- if layout is not None:
- app_dir = filename_path.parent
- app_name = filename_path.name
- layout_filename = save_layout_config(
- app_dir, app_name, LayoutConfig(**layout)
- )
- self._update_config({"layout_file": layout_filename})
- else:
- # Remove the layout from the config
+ if layout is None:
self._update_config({"layout_file": None})
-
- if request.persist:
- self._invalidate_autosaves()
- contents = self._save_file(
- filename_path,
- notebook=self.app.to_ir(),
- persist=request.persist,
+ return
+ layout_filename = save_layout_config(
+ self._filename.parent,
+ self._filename.name,
+ LayoutConfig(**layout),
)
- if request.persist:
- self._persisted(
- [
- NotebookCell(id=i, code=c, name=n, config=f)
- for i, c, n, f in zip(
- cell_ids, codes, names, configs, strict=True
- )
- ]
- )
- return contents
+ self._update_config({"layout_file": layout_filename})
def _persisted(self, cells: Sequence[NotebookCell]) -> None:
callback = self.on_persisted
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index af93baab2b..f74120d455 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -5113,41 +5113,16 @@ components:
- format_on_save
title: SaveConfig
type: object
- SaveNotebookRequest:
+ SaveLayoutRequest:
+ description: The notebook's layout, written beside it; `None` removes it.
properties:
- cellIds:
- items:
- $ref: '#/components/schemas/CellId'
- type: array
- codes:
- items:
- type: string
- type: array
- configs:
- items:
- $ref: '#/components/schemas/CellConfig'
- type: array
- filename:
- type: string
layout:
anyOf:
- type: object
- type: 'null'
default: null
- names:
- items:
- type: string
- type: array
- persist:
- default: true
- type: boolean
- required:
- - cellIds
- - codes
- - names
- - configs
- - filename
- title: SaveNotebookRequest
+ required: []
+ title: SaveLayoutRequest
type: object
SaveUserConfigurationRequest:
properties:
@@ -7512,7 +7487,7 @@ paths:
$ref: '#/components/schemas/SuccessResponse'
description: Run a cell. Updates cell code in the kernel if needed; registers
new cells for unseen cell IDs. Only allowed in edit mode.
- /api/kernel/save:
+ /api/kernel/save_app_config:
post:
parameters:
- in: header
@@ -7524,15 +7499,15 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/SaveNotebookRequest'
+ $ref: '#/components/schemas/SaveAppConfigurationRequest'
responses:
200:
content:
text/plain:
schema:
type: string
- description: Save the current app
- /api/kernel/save_app_config:
+ description: Save the app configuration
+ /api/kernel/save_layout:
post:
parameters:
- in: header
@@ -7544,14 +7519,15 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/SaveAppConfigurationRequest'
+ $ref: '#/components/schemas/SaveLayoutRequest'
responses:
200:
content:
- text/plain:
+ application/json:
schema:
- type: string
- description: Save the app configuration
+ $ref: '#/components/schemas/SuccessResponse'
+ description: Write the notebook's layout file and point its app config at
+ it
/api/kernel/save_user_config:
post:
parameters:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 54648b26a9..7b8c0edc7f 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -2426,7 +2426,7 @@ export interface paths {
patch?: never;
trace?: never;
};
- "/api/kernel/save": {
+ "/api/kernel/save_app_config": {
parameters: {
query?: never;
header?: never;
@@ -2446,11 +2446,11 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["SaveNotebookRequest"];
+ "application/json": components["schemas"]["SaveAppConfigurationRequest"];
};
};
responses: {
- /** @description Save the current app */
+ /** @description Save the app configuration */
200: {
headers: {
[name: string]: unknown;
@@ -2467,7 +2467,7 @@ export interface paths {
patch?: never;
trace?: never;
};
- "/api/kernel/save_app_config": {
+ "/api/kernel/save_layout": {
parameters: {
query?: never;
header?: never;
@@ -2487,17 +2487,17 @@ export interface paths {
};
requestBody?: {
content: {
- "application/json": components["schemas"]["SaveAppConfigurationRequest"];
+ "application/json": components["schemas"]["SaveLayoutRequest"];
};
};
responses: {
- /** @description Save the app configuration */
+ /** @description Write the notebook's layout file and point its app config at it */
200: {
headers: {
[name: string]: unknown;
};
content: {
- "text/plain": string;
+ "application/json": components["schemas"]["SuccessResponse"];
};
};
};
@@ -6766,17 +6766,13 @@ export interface components {
autosave_delay: number;
format_on_save: boolean;
};
- /** SaveNotebookRequest */
- SaveNotebookRequest: {
- cellIds: components["schemas"]["CellId"][];
- codes: string[];
- configs: components["schemas"]["CellConfig"][];
- filename: string;
+ /**
+ * SaveLayoutRequest
+ * @description The notebook's layout, written beside it; `None` removes it.
+ */
+ SaveLayoutRequest: {
/** @default null */
layout?: Record<string, any> | null;
- names: string[];
- /** @default true */
- persist?: boolean;
};
/** SaveUserConfigurationRequest */
SaveUserConfigurationRequest: {
diff --git a/tests/_cli/test_cli_check.py b/tests/_cli/test_cli_check.py
index 3990c063b4..3a03120c2d 100644
--- a/tests/_cli/test_cli_check.py
+++ b/tests/_cli/test_cli_check.py
@@ -14,7 +14,7 @@ from marimo._ast.cell import CellConfig
from marimo._ast.codegen import generate_filecontents
from marimo._cli.cli import check
from marimo._config.manager import UserConfigStore, get_default_config_manager
-from marimo._server.models.models import SaveNotebookRequest
+from marimo._messaging.notebook.document import NotebookCell
from marimo._session.notebook import load_notebook
@@ -75,15 +75,16 @@ def test_fix_uses_each_notebooks_formatting_config(
assert signature in contents
manager = load_notebook(file)
manager.config_reader = get_default_config_manager(current_path=file)
- cells = manager.app.cell_manager
- manager.save(
- SaveNotebookRequest(
- cell_ids=list(cells.cell_ids()),
- codes=list(cells.codes()),
- names=list(cells.names()),
- configs=list(cells.configs()),
- filename=file,
- )
+ manager.save_from_cells(
+ [
+ NotebookCell(
+ id=data.cell_id,
+ code=data.code,
+ name=data.name,
+ config=data.config,
+ )
+ for data in manager.app.cell_manager.cell_data()
+ ]
)
assert Path(file).read_text() == contents
diff --git a/tests/_pyodide/test_pyodide_notebook.py b/tests/_pyodide/test_pyodide_notebook.py
index 05e9a04285..6db072e4bd 100644
--- a/tests/_pyodide/test_pyodide_notebook.py
+++ b/tests/_pyodide/test_pyodide_notebook.py
@@ -538,6 +538,18 @@ async def test_host_edits_config_layout_and_reload(bridge):
]
+async def test_app_config_changes_are_written_when_persistence_is_set(bridge):
+ await snapshot(bridge)
+ notebook = await bridge.notebook.host.notebook(bridge.notebook.id)
+ persist = AsyncMock()
+ bridge.notebook.set_persistence(persist)
+ await bridge.save_app_config(json.dumps({"config": {"width": "full"}}))
+ persist.assert_awaited_once()
+ contents, _filename = persist.await_args.args
+ assert 'width="full"' in contents
+ assert notebook.saved_etag == notebook.document.etag
+
+
async def test_save_includes_kernel_document_edits(bridge):
await snapshot(bridge)
persist = AsyncMock()
diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.py
index 1bf0ec6365..438f29b015 100644
--- a/tests/_server/api/endpoints/test_export.py
+++ b/tests/_server/api/endpoints/test_export.py
@@ -17,12 +17,13 @@ import pytest
from marimo import App, __version__
from marimo._ast.app import InternalApp
+from marimo._ast.cell import CellConfig
from marimo._convert.markdown.flavor.base import MarkdownFlavorName
from marimo._dependencies.dependencies import DependencyManager
from marimo._export.requests import PDFExportRequest
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.notebook import Transaction
-from marimo._messaging.notebook.changes import SetCode
+from marimo._messaging.notebook.changes import CreateCell, SetCode
from marimo._messaging.notification import CellNotification
from marimo._output.utils import uri_encode_component
from marimo._runtime.layout.layout import LayoutConfig
@@ -1274,7 +1275,20 @@ def test_auto_export_ipynb_with_new_cell(
assert session
session.app_file_manager.filename = temp_marimo_file
- # First, create and run a cell with constant value 1
+ # The editor creates the cell in the document, then runs it.
+ session.document.apply(
+ Transaction(
+ changes=(
+ CreateCell(
+ cell_id=CellId_t("new_cell"),
+ code="3.14",
+ name="_",
+ config=CellConfig(),
+ ),
+ ),
+ source="frontend",
+ )
+ )
create_cell_response = client.post(
"/api/kernel/run",
headers=HEADERS,
@@ -1287,25 +1301,6 @@ def test_auto_export_ipynb_with_new_cell(
time.sleep(0.5)
- # Save the session
- save_response = client.post(
- "/api/kernel/save",
- headers=HEADERS,
- json={
- "cellIds": ["new_cell"],
- "filename": temp_marimo_file,
- "codes": ["3.14"],
- "names": ["_"],
- "configs": [
- {
- "hideCode": True,
- "disabled": False,
- }
- ],
- },
- )
- assert save_response.status_code == 200, save_response.text
-
# Clean up the marimo directory
marimo_dir = Path(temp_marimo_file).parent / "__marimo__"
shutil.rmtree(marimo_dir, ignore_errors=True)
diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.py
index 027b001c58..18285ff842 100644
--- a/tests/_server/api/endpoints/test_files.py
+++ b/tests/_server/api/endpoints/test_files.py
@@ -4,12 +4,10 @@ from __future__ import annotations
import os
import random
import tempfile
-from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING
from unittest.mock import Mock, patch
-import msgspec
import pytest
from marimo._utils.platform import is_windows
@@ -166,185 +164,39 @@ def test_read_code_in_run_mode_without_include_code(
@pytest.mark.flaky(reruns=5)
@with_session(SESSION_ID)
-def test_save_file(client: TestClient) -> None:
+def test_save_layout(client: TestClient) -> None:
filename = get_session_manager(client).workspace.get_unique_file_key()
assert filename
path = Path(filename)
-
response = client.post(
- "/api/kernel/save",
+ "/api/kernel/rename",
headers=HEADERS,
- json={
- "cellIds": ["1"],
- "filename": str(path),
- "codes": ["import marimo as mo"],
- "names": ["my_cell"],
- "configs": [
- {
- "hide_code": True,
- "disabled": False,
- }
- ],
- },
+ json={"filename": str(path)},
)
assert response.status_code == 200, response.text
-
- def _assert_contents():
- file_contents = path.read_text()
- assert "import marimo" in response.text
- assert "import marimo as mo" in file_contents
- assert "@app.cell(hide_code=True)" in file_contents
- assert "my_cell" in file_contents
-
- try_assert_n_times(5, _assert_contents)
-
- # save back
- response = client.post(
- "/api/kernel/save",
- headers=HEADERS,
- json={
- "cellIds": ["1"],
- "filename": str(path),
- "codes": ["import marimo as mo"],
- "names": ["__"],
- "configs": [
- {
- "hide_code": False,
- }
- ],
- },
- )
-
-
- reason="Flaky in CI, can't repro locally",
-)
-@with_session(SESSION_ID)
-def test_save_with_header(client: TestClient) -> None:
- filename = get_session_manager(client).workspace.get_unique_file_key()
- assert filename
- path = Path(filename)
- assert path.exists()
-
- copyright_year = datetime.now().year
- header = (
- '"""This is a docstring"""\n\n'
- + f"# Copyright {copyright_year}\n# Linter ignore\n"
- )
- # Prepend a header to the file
- contents = path.read_text()
- contents = header + contents
- path.write_text(contents, encoding="UTF-8")
+ manager = get_session_manager(client).get_session(SESSION_ID)
+ assert manager is not None
+ app = manager.app_file_manager.app
response = client.post(
- "/api/kernel/save",
+ "/api/kernel/save_layout",
headers=HEADERS,
json={
- "cellIds": ["1"],
- "filename": str(path),
- "codes": ["import marimo as mo"],
- "names": ["my_cell"],
- "configs": [
- {
- "hide_code": True,
- "disabled": False,
- }
- ],
+ "layout": {"type": "grid", "data": {"columns": 24, "cells": []}}
},
)
-
assert response.status_code == 200, response.text
- assert "import marimo" in response.text
-
- def _assert_contents():
- file_contents = path.read_text()
- assert "import marimo as mo" in file_contents
- # Race condition with uv (seen in python 3.10)
- if file_contents.startswith("# ///"):
- file_contents = file_contents.split("# ///")[2].lstrip()
- assert file_contents.startswith(header.rstrip()), "Header was removed"
- assert "@app.cell(hide_code=True)" in file_contents
- assert "my_cell" in file_contents
-
- try_assert_n_times(5, _assert_contents)
-
-
-@with_session(SESSION_ID)
-def test_save_with_invalid_file(client: TestClient) -> None:
- filename = get_session_manager(client).workspace.get_unique_file_key()
- assert filename
- path = Path(filename)
- assert path.exists()
-
- header = (
- '"""This is a docstring"""\n\n'
- + 'print("dont do this!")\n'
- + "# Linter ignore\n"
- )
-
- # Prepend a header to the file
- contents = path.read_text()
- contents = header + contents
- path.write_text(contents)
+ layout_file = app.config.layout_file
+ assert layout_file == f"layouts/{path.stem}.grid.json"
+ assert (path.parent / layout_file).exists()
response = client.post(
- "/api/kernel/save",
+ "/api/kernel/save_layout",
headers=HEADERS,
- json={
- "cellIds": ["1"],
- "filename": str(path),
- "codes": ["import marimo as mo"],
- "names": ["my_cell"],
- "configs": [
- {
- "hide_code": True,
- "disabled": False,
- }
- ],
- },
+ json={"layout": None},
)
-
assert response.status_code == 200, response.text
- assert "import marimo" in response.text
-
- def _assert_contents():
- file_contents = path.read_text()
- assert "@app.cell(hide_code=True)" in file_contents
- assert "my_cell" in file_contents
-
- # Race condition with uv (seen in python 3.10)
- if file_contents.startswith("# ///"):
- file_contents = file_contents.split("# ///")[2].lstrip()
- assert file_contents.startswith("import marimo"), (
- "Header was not removed"
- )
-
- try_assert_n_times(5, _assert_contents)
-
-
-@with_session(SESSION_ID)
-def test_save_file_cannot_rename(client: TestClient) -> None:
- response = client.post(
- "/api/kernel/save",
- headers=HEADERS,
- json={
- "cellIds": ["1"],
- "filename": "random_filename.py",
- "codes": ["import marimo as mo"],
- "names": ["my_cell"],
- "configs": [
- {
- "hide_code": True,
- "disabled": False,
- }
- ],
- },
- )
- assert response.status_code == 400
- body = response.json()
- assert body["detail"]
- assert "cannot rename" in body["detail"]
+ assert app.config.layout_file is None
@pytest.mark.flaky(reruns=5)
@@ -454,36 +306,6 @@ def test_copy_file_with_relative_paths(client: TestClient) -> None:
try_assert_n_times(5, _assert_contents)
-@with_session(SESSION_ID)
-def test_path_traversal_save_blocked(client: TestClient) -> None:
- """Save endpoint must not write outside the workspace's directory."""
- filename = get_session_manager(client).workspace.get_unique_file_key()
- assert filename
- path = Path(filename)
- directory = str(path.parent)
- workspace = get_session_manager(client).workspace
-
- with patch.object(
- type(workspace),
- "directory",
- new_callable=lambda: property(lambda _: directory),
- ):
- # Attempt to save outside the directory via path traversal
- traversal_path = str(path.parent.parent / "escaped.py")
- response = client.post(
- "/api/kernel/save",
- headers=HEADERS,
- json={
- "cellIds": ["1"],
- "codes": ["import marimo as mo"],
- "names": ["cell"],
- "configs": [{}],
- "filename": traversal_path,
- },
- )
- assert response.status_code == 403, response.text
-
-
@with_session(SESSION_ID)
def test_path_traversal_rename_blocked(client: TestClient) -> None:
"""Rename endpoint must not move files outside the workspace's directory."""
@@ -623,55 +445,6 @@ def test_read_code_without_saved_file(client: TestClient) -> None:
)
-@with_session(SESSION_ID)
-def test_save_with_unicode_content(client: TestClient) -> None:
- """Test save endpoint with unicode and special characters."""
- filename = get_session_manager(client).workspace.get_unique_file_key()
- assert filename
- path = Path(filename)
-
- unicode_code = """# Unicode test: 你好世界 🌍 ñáéíóú
-def test():
- return "Hello 世界" """
-
- response = client.post(
- "/api/kernel/save",
- headers=HEADERS,
- json={
- "cellIds": ["1"],
- "filename": str(path),
- "codes": [unicode_code],
- "names": ["unicode_cell"],
- "configs": [{}],
- },
- )
- assert response.status_code == 200
-
- def _assert_contents():
- file_contents = path.read_text(encoding="utf-8")
- assert "你好世界" in file_contents
- assert "🌍" in file_contents
-
- try_assert_n_times(5, _assert_contents)
-
-
-@with_session(SESSION_ID)
-def test_save_with_missing_required_fields(client: TestClient) -> None:
- """Test save endpoint with missing required fields."""
- # Missing codes field
- with pytest.raises(msgspec.ValidationError):
- client.post(
- "/api/kernel/save",
- headers=HEADERS,
- json={
- "cellIds": ["1"],
- "filename": "test.py",
- "names": ["my_cell"],
- "configs": [{}],
- },
- )
-
-
def test_endpoints_without_authentication(client: TestClient) -> None:
"""Test endpoints without proper authentication headers."""
endpoints_and_methods = [
diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.py
index 551753b6a0..31658c7531 100644
--- a/tests/_server/api/endpoints/test_kiosk.py
+++ b/tests/_server/api/endpoints/test_kiosk.py
@@ -46,7 +46,6 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:
) as websocket:
snapshot = socket_snapshot(websocket)
notebook_id = notebook_id_of(snapshot)
- cells = [e["data"]["cell"] for e in snapshot if e["event"] == "cell"]
editor_ready = receive_notification(websocket)
assert_kernel_ready_response(editor_ready)
@@ -87,36 +86,6 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:
data = receive_notification(other_websocket)
assert data["op"] == "notebook-document-transaction"
- # A full save replaces the canonical document. Viewers receive
- # the applied diff even when it includes edits that bypassed the
- # incremental document endpoint during recovery.
- filename = client.app.state.session_manager.workspace.get_unique_file_key()
- assert filename
- replacement_code = cells[0]["code"] + "\n# saved"
- response = client.post(
- "/api/kernel/save",
- headers=HEADERS,
- json={
- "cellIds": [cell["id"] for cell in cells],
- "filename": filename,
- "codes": [
- replacement_code,
- *(cell["code"] for cell in cells[1:]),
- ],
- "names": [cell["name"] for cell in cells],
- "configs": [cell["config"] for cell in cells],
- },
- )
- assert response.status_code == 200, response.text
- data = receive_until(
- "notebook-document-transaction", other_websocket
- )
- assert any(
- change["type"] == "set-code"
- and change["code"] == replacement_code
- for change in data["data"]["transaction"]["changes"]
- )
-
# Send run single cell
response = client.post(
"/api/kernel/run",
diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.py
index 2a4c96ebf2..2481156856 100644
--- a/tests/_server/api/endpoints/test_resume_session.py
+++ b/tests/_server/api/endpoints/test_resume_session.py
@@ -33,6 +33,7 @@ from tests._server.api.endpoints.ws_helpers import (
headers,
receive_notification,
)
+from tests._server.host.drive import socket_snapshot
from tests._server.mocks import get_session_manager, workspace_scope
if TYPE_CHECKING:
@@ -170,39 +171,54 @@ def test_refresh_resumes_directory_workspace_session(
session_manager.close_session(SessionId("dir2"))
-def test_save_session(client: TestClient) -> None:
- filename = (
- get_session_manager(client)
- .workspace.get_single_app_file_manager()
- .filename
- )
+def test_edited_document_survives_resume(client: TestClient) -> None:
with client.websocket_connect(_create_ws_url("123")) as websocket:
+ snapshot = socket_snapshot(websocket)
+ notebook_id = next(
+ e["data"]["notebook"]["id"]
+ for e in snapshot
+ if e["event"] == "notebook"
+ )
data = receive_notification(websocket)
assert_kernel_ready_response(data, create_response({}))
- # Send save request
- client.post(
- "/api/kernel/save",
- headers=headers("123"),
+ # Replace the notebook's cells through the host.
+ session = get_session(client, SessionId("123"))
+ assert session is not None
+ response = client.post(
+ f"/api/marimo/v1/notebooks/{notebook_id}/edits",
+ headers={**headers("123"), "Idempotency-Key": "edit-1"},
json={
- "cellIds": ["2", "1"],
- "filename": filename,
- "codes": [
- "slider = mo.ui.slider(0, 100)",
- "import marimo as mo",
- ],
- "names": ["cell_0", "cell_1"],
- "configs": [
+ "changes": [
+ *(
+ {
+ "kind": "delete_cell",
+ "id": cell_id,
+ "base_etag": "*",
+ }
+ for cell_id in session.document.cell_ids
+ ),
{
- "hideCode": True,
- "disabled": True,
+ "kind": "put_cell",
+ "base_etag": None,
+ "cell": {
+ "id": "2",
+ "code": "slider = mo.ui.slider(0, 100)",
+ "name": "cell_0",
+ },
},
{
- "hideCode": False,
- "disabled": False,
+ "kind": "put_cell",
+ "base_etag": None,
+ "cell": {
+ "id": "1",
+ "code": "import marimo as mo",
+ "name": "cell_1",
+ },
},
- ],
+ ]
},
)
+ assert response.status_code == 200, response.text
# Check the session still exists after closing the websocket
assert get_session(client, "123")
@@ -219,7 +235,7 @@ def test_save_session(client: TestClient) -> None:
data,
create_response({"resumed": True}),
)
- # The saved cells are the resumed session's document
+ # The edited cells are the resumed session's document
session = get_session(client, SessionId("456"))
assert session is not None
assert list(session.document.cell_ids) == ["2", "1"]
diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.py
index e36133da00..18894114b7 100644
--- a/tests/_server/test_file_manager.py
+++ b/tests/_server/test_file_manager.py
@@ -10,8 +10,8 @@ from marimo import __version__
from marimo._ast.app import App, InternalApp
from marimo._ast.cell import CellConfig
from marimo._config.settings import GLOBAL_SETTINGS
+from marimo._messaging.notebook.document import NotebookCell
from marimo._server.app_defaults import AppDefaults
-from marimo._server.models.models import SaveNotebookRequest
from marimo._session.notebook import AppFileManager
from marimo._types.ids import CellId_t
from marimo._utils.cell_matching import similarity_score
@@ -21,14 +21,6 @@ if TYPE_CHECKING:
from collections.abc import Generator
from pathlib import Path
-save_request = SaveNotebookRequest(
- cell_ids=["1"],
- filename="save_existing.py",
- codes=["import marimo as mo"],
- names=["my_cell"],
- configs=[CellConfig(hide_code=True)],
-)
-
@pytest.fixture
def app_file_manager(tmp_path: Path) -> Generator[AppFileManager, None, None]:
@@ -200,15 +192,16 @@ def test_save_mystmd_preserves_frontmatter_and_marimo_config(
assert 'dependencies = ["polars"]' in manager.app.to_ir().header.value
cells = list(manager.app.cell_manager.cell_data())
- manager.save(
- SaveNotebookRequest(
- cell_ids=[cell.cell_id for cell in cells],
- filename=str(temp_file),
- codes=[cell.code for cell in cells],
- names=[cell.name for cell in cells],
- configs=[cell.config for cell in cells],
- persist=True,
- )
+ manager.save_from_cells(
+ [
+ NotebookCell(
+ id=cell.cell_id,
+ code=cell.code,
+ name=cell.name,
+ config=cell.config,
+ )
+ for cell in cells
+ ]
)
contents = temp_file.read_text(encoding="utf-8")
@@ -249,51 +242,10 @@ def test_save_app_config_exception(app_file_manager: AppFileManager) -> None:
assert e.value.status_code == HTTPStatus.SERVER_ERROR
-def test_save_filename_change_not_allowed(
- app_file_manager: AppFileManager,
-) -> None:
- app_file_manager.filename = "original.py"
- save_request.filename = "new.py"
- with pytest.raises(HTTPException) as e:
- app_file_manager.save(save_request)
- assert e.value.status_code == HTTPStatus.BAD_REQUEST
-
-
-def test_save_existing_filename(app_file_manager: AppFileManager) -> None:
- existing_filename = "existing_file.py"
- with open(existing_filename, "w") as f:
- f.write("This is a test file.")
- save_request.filename = existing_filename
- try:
- with pytest.raises(HTTPException) as e:
- app_file_manager.save(save_request)
- assert e.value.status_code == HTTPStatus.BAD_REQUEST
- finally:
- os.remove(existing_filename)
-
-
-def test_save_successful(app_file_manager: AppFileManager) -> None:
- save_request.filename = app_file_manager.filename or ""
- try:
- app_file_manager.save(save_request)
- assert os.path.exists(save_request.filename)
- finally:
- os.remove(save_request.filename)
-
-
-def test_save_cannot_rename(app_file_manager: AppFileManager) -> None:
- save_request.filename = "/invalid/path/save_exception.py"
- with pytest.raises(HTTPException) as e:
- app_file_manager.save(save_request)
- assert e.value.status_code == HTTPStatus.BAD_REQUEST
-
-
def test_save_from_cells_persists_cells(
app_file_manager: AppFileManager,
) -> None:
"""`save_from_cells` should round-trip cells through the serializer."""
- from marimo._messaging.notebook.document import NotebookCell
-
app_file_manager.save_from_cells(
[
NotebookCell(
@@ -319,8 +271,6 @@ def test_save_from_cells_leaves_the_document_alone(
An autosave runs on a worker thread with a copy of the cells. An
edit that lands meanwhile must not be replaced by the older copy.
"""
- from marimo._messaging.notebook.document import NotebookCell
-
document = app_file_manager.app.cell_manager.document
(cell,) = document.cells
version = document.version
@@ -375,8 +325,6 @@ def test_save_from_cells_empty_name_normalizes(
) -> None:
"""Empty cell names must serialize as the default `_` rather than
falling back to the unparsable-cell path."""
- from marimo._messaging.notebook.document import NotebookCell
-
app_file_manager.save_from_cells(
[
NotebookCell(
@@ -408,8 +356,6 @@ def test_save_from_cells_preserves_layout_file(
app_file_manager: AppFileManager,
) -> None:
"""`save_from_cells` must keep `layout_file` in app config."""
- from marimo._messaging.notebook.document import NotebookCell
-
app_file_manager.app.update_config({"layout_file": "layouts/x.grid.json"})
app_file_manager.save_from_cells(
[
@@ -424,71 +370,6 @@ def test_save_from_cells_preserves_layout_file(
assert app_file_manager.app.config.layout_file == "layouts/x.grid.json"
-def test_save_and_save_from_cells_serialize_under_lock(
- app_file_manager: AppFileManager,
-) -> None:
- """Concurrent `save` + `save_from_cells` on the same manager must
- produce a valid (non-torn) file. Also regression-tests that the
- reentrant lock covers both entry points."""
- import threading
-
- from marimo._messaging.notebook.document import NotebookCell
-
- assert app_file_manager.filename is not None
- save_request.filename = app_file_manager.filename
- errors: list[Exception] = []
-
- def _frontend_save() -> None:
- try:
- for _ in range(20):
- app_file_manager.save(save_request)
- except Exception as e: # pragma: no cover — should never happen
- errors.append(e)
-
- def _autosave() -> None:
- cells = [
- NotebookCell(
- id=CellId_t("auto"),
- code="auto = 1",
- name="",
- config=CellConfig(),
- )
- ]
- try:
- for _ in range(20):
- app_file_manager.save_from_cells(cells)
- except Exception as e: # pragma: no cover
- errors.append(e)
-
- try:
- t1 = threading.Thread(target=_frontend_save)
- t2 = threading.Thread(target=_autosave)
- t1.start()
- t2.start()
- t1.join(timeout=10)
- t2.join(timeout=10)
-
- assert not t1.is_alive(), (
- "frontend save thread did not terminate within 10s "
- "(likely deadlock in AppFileManager write lock)"
- )
- assert not t2.is_alive(), (
- "autosave thread did not terminate within 10s "
- "(likely deadlock in AppFileManager write lock)"
- )
- assert not errors, f"unexpected errors: {errors}"
- # File ends in a parseable state — the serializer's codegen would
- # raise on a torn write, and the final content must be one of the
- # two write paths, never a mix.
- with open(save_request.filename, encoding="utf-8") as f:
- contents = f.read()
- assert "import marimo" in contents
- assert "app = marimo.App" in contents
- finally:
- if os.path.exists(save_request.filename):
- os.remove(save_request.filename)
-
-
def test_save_with_header(
app_file_manager: AppFileManager, tmp_path: Path
) -> None:
@@ -506,14 +387,15 @@ def _():
""")
app_file_manager.filename = str(file)
assert app_file_manager.path is not None
- app_file_manager.save(
- SaveNotebookRequest(
- cell_ids=[CellId_t("1")],
- filename=str(file),
- codes=["print(2)"],
- names=["_"],
- configs=[CellConfig(hide_code=True)],
- )
+ app_file_manager.save_from_cells(
+ [
+ NotebookCell(
+ id=CellId_t("1"),
+ code="print(2)",
+ name="_",
+ config=CellConfig(hide_code=True),
+ )
+ ]
)
new_contents = file.read_text()
assert "# This is a header" in new_contents
@@ -1137,15 +1019,15 @@ if __name__ == "__main__":
assert manager.file_content_matches_last_save() is False
# Save the file
- manager.save(
- SaveNotebookRequest(
- cell_ids=[CellId_t("1")],
- filename=str(temp_file),
- codes=["x = 1"],
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ manager.save_from_cells(
+ [
+ NotebookCell(
+ id=CellId_t("1"),
+ code="x = 1",
+ name="cell1",
+ config=CellConfig(),
+ )
+ ]
)
# Now the file should match the last save
@@ -1228,15 +1110,15 @@ if __name__ == "__main__":
manager = AppFileManager(filename=str(temp_file))
# Save the file
- manager.save(
- SaveNotebookRequest(
- cell_ids=[CellId_t("1")],
- filename=str(temp_file),
- codes=["x = 1"],
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ manager.save_from_cells(
+ [
+ NotebookCell(
+ id=CellId_t("1"),
+ code="x = 1",
+ name="cell1",
+ config=CellConfig(),
+ )
+ ]
)
# Verify it matches
@@ -1272,15 +1154,15 @@ if __name__ == "__main__":
manager = AppFileManager(filename=str(temp_file))
# Save the file
- manager.save(
- SaveNotebookRequest(
- cell_ids=[CellId_t("1")],
- filename=str(temp_file),
- codes=["x = 1"],
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ manager.save_from_cells(
+ [
+ NotebookCell(
+ id=CellId_t("1"),
+ code="x = 1",
+ name="cell1",
+ config=CellConfig(),
+ )
+ ]
)
# Should match (content is the same)
@@ -1321,15 +1203,15 @@ if __name__ == "__main__":
)
manager = AppFileManager(filename=str(temp_file))
- manager.save(
- SaveNotebookRequest(
- cell_ids=[CellId_t("1")],
- filename=str(temp_file),
- codes=["x = 1"],
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ manager.save_from_cells(
+ [
+ NotebookCell(
+ id=CellId_t("1"),
+ code="x = 1",
+ name="cell1",
+ config=CellConfig(),
+ )
+ ]
)
temp_file.write_text(
@@ -1363,29 +1245,29 @@ if __name__ == "__main__":
manager = AppFileManager(filename=str(temp_file))
# First save
- manager.save(
- SaveNotebookRequest(
- cell_ids=[CellId_t("1")],
- filename=str(temp_file),
- codes=["x = 1"],
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ manager.save_from_cells(
+ [
+ NotebookCell(
+ id=CellId_t("1"),
+ code="x = 1",
+ name="cell1",
+ config=CellConfig(),
+ )
+ ]
)
assert manager.file_content_matches_last_save() is True
# Second save with different content
- manager.save(
- SaveNotebookRequest(
- cell_ids=[CellId_t("1")],
- filename=str(temp_file),
- codes=["x = 2"],
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ manager.save_from_cells(
+ [
+ NotebookCell(
+ id=CellId_t("1"),
+ code="x = 2",
+ name="cell1",
+ config=CellConfig(),
+ )
+ ]
)
# Should still match after second save
diff --git a/tests/_session/extensions/test_notification_listener_autosave.py b/tests/_session/extensions/test_notification_listener_autosave.py
index 6ecfee3f4f..4fef297502 100644
--- a/tests/_session/extensions/test_notification_listener_autosave.py
+++ b/tests/_session/extensions/test_notification_listener_autosave.py
@@ -27,7 +27,6 @@ from marimo._messaging.notification import (
)
from marimo._messaging.serde import serialize_kernel_message
from marimo._messaging.types import KernelMessage
-from marimo._server.models.models import SaveNotebookRequest
from marimo._session.extensions.extensions import (
NotificationListenerExtension,
)
@@ -555,14 +554,15 @@ class TestAutosaveOrdering:
renamed_path = notebook_path.with_name("renamed_after_autosave.py")
app_file_manager.rename(str(renamed_path))
- app_file_manager.save(
- SaveNotebookRequest(
- cell_ids=[existing_cell_id],
- filename=str(renamed_path),
- codes=["new = 2"],
- names=[""],
- configs=[CellConfig()],
- )
+ app_file_manager.save_from_cells(
+ [
+ NotebookCell(
+ id=existing_cell_id,
+ code="new = 2",
+ name="",
+ config=CellConfig(),
+ )
+ ]
)
work, _on_error = queued_work.pop()
diff --git a/tests/_session/notebook/test_app_file_manager.py b/tests/_session/notebook/test_app_file_manager.py
index 590aae0797..927bf438b5 100644
--- a/tests/_session/notebook/test_app_file_manager.py
+++ b/tests/_session/notebook/test_app_file_manager.py
@@ -10,14 +10,16 @@ from unittest.mock import patch
import pytest
+from marimo._ast.cell import CellConfig
from marimo._ast.type_inference import Inferred
-from marimo._server.models.models import SaveNotebookRequest
+from marimo._messaging.notebook.document import NotebookCell
from marimo._session.notebook import (
AppFileManager,
load_notebook,
new_notebook,
read_css_file,
)
+from marimo._utils.http import HTTPException
if TYPE_CHECKING:
from pathlib import Path
@@ -125,7 +127,6 @@ def test_manifest_and_cell_saves_preserve_each_other(
first_writer: str,
) -> None:
from marimo._environments import script_metadata
- from marimo._server.models.models import SaveNotebookRequest
from marimo._session.notebook.serializer import get_notebook_serializer
path = tmp_path / f"notebook{suffix}"
@@ -167,16 +168,13 @@ def test_manifest_and_cell_saves_preserve_each_other(
)
def save_cells():
- return manager.save(
- SaveNotebookRequest(
- cell_ids=list(manager.app.cell_manager.cell_ids()),
- codes=["x = 2"],
- names=["__"],
- configs=[{}],
- filename=str(path),
- layout=None,
- persist=True,
- )
+ return manager.save_from_cells(
+ [
+ NotebookCell(
+ id=cell_id, code="x = 2", name="__", config=CellConfig()
+ )
+ for cell_id in manager.app.cell_manager.cell_ids()
+ ]
)
first, second = (
@@ -268,15 +266,13 @@ class _FakeBackend:
return [None] * len(expressions)
-def _save_request(fm: AppFileManager, nb: Path) -> SaveNotebookRequest:
- cell_manager = fm.app.cell_manager
- return SaveNotebookRequest(
- cell_ids=list(cell_manager.cell_ids()),
- codes=list(cell_manager.codes()),
- names=list(cell_manager.names()),
- configs=list(cell_manager.configs()),
- filename=str(nb),
- )
+def _cells_to_save(fm: AppFileManager) -> list[NotebookCell]:
+ return [
+ NotebookCell(
+ id=data.cell_id, code=data.code, name=data.name, config=data.config
+ )
+ for data in fm.app.cell_manager.cell_data()
+ ]
def test_infer_types_defaults_off_without_config(tmp_path: Path) -> None:
@@ -306,7 +302,7 @@ def test_save_writes_inferred_types_to_disk_when_enabled(
"marimo._ast.type_inference.JediBackend", lambda: backend
)
- fm.save(_save_request(fm, nb))
+ fm.save_from_cells(_cells_to_save(fm))
assert "def _(x: int):" in nb.read_text()
assert backend.search_paths == [tmp_path]
@@ -319,10 +315,15 @@ def test_save_normalizes_nonbreaking_spaces_with_inference(
nb.write_text(_NOTEBOOK_WITH_PARAMETER)
fm = load_notebook(nb)
fm.config_reader = _ConfigReader(infer_types="jedi") # type: ignore[assignment]
- request = _save_request(fm, nb)
- request.codes[0] = "x\u00a0=\u00a02"
+ cells = _cells_to_save(fm)
+ cells[0] = NotebookCell(
+ id=cells[0].id,
+ code="x\u00a0=\u00a02",
+ name=cells[0].name,
+ config=cells[0].config,
+ )
- fm.save(request)
+ fm.save_from_cells(cells)
assert "def _(x: int):" in nb.read_text()
_, values = runpy.run_path(str(nb))["app"].run()
@@ -358,7 +359,6 @@ def test_line_length_follows_config_and_defaults_to_79(tmp_path: Path) -> None:
def test_on_persisted_reports_the_cells_and_config_written(
tmp_path: Path,
) -> None:
- from marimo._ast.cell import CellConfig
from marimo._messaging.notebook.document import NotebookCell
from marimo._types.ids import CellId_t
@@ -392,3 +392,30 @@ def test_on_config_changed_fires_only_when_the_config_changes(
fm.save_app_config({"width": "full"})
assert len(changes) == 1
+
+
+def test_save_layout_writes_the_sidecar_and_points_the_config_at_it(
+ tmp_path: Path,
+) -> None:
+ path = tmp_path / "nb.py"
+ path.write_text("import marimo\napp = marimo.App()\n")
+ manager = AppFileManager(str(path))
+ changes: list[None] = []
+ manager.on_config_changed = lambda: changes.append(None)
+
+ manager.save_layout({"type": "grid", "data": {"columns": 24, "cells": []}})
+
+ assert manager.app.config.layout_file == "layouts/nb.grid.json"
+ assert (tmp_path / "layouts" / "nb.grid.json").exists()
+ assert len(changes) == 1
+
+ manager.save_layout(None)
+
+ assert manager.app.config.layout_file is None
+ assert len(changes) == 2
+
+
+def test_save_layout_needs_a_named_notebook() -> None:
+ manager = AppFileManager(None)
+ with pytest.raises(HTTPException):
+ manager.save_layout({"type": "grid", "data": {}})
diff --git a/tests/_session/test_file_change_handler.py b/tests/_session/test_file_change_handler.py
index 7645cb614e..a3d390b3c9 100644
--- a/tests/_session/test_file_change_handler.py
+++ b/tests/_session/test_file_change_handler.py
@@ -28,7 +28,6 @@ from marimo._messaging.notification import (
ReloadNotification,
)
from marimo._runtime.commands import SyncGraphCommand
-from marimo._server.models.models import SaveNotebookRequest
from marimo._session.file_change_handler import (
EditModeReloadStrategy,
FileChangeCoordinator,
@@ -671,15 +670,11 @@ async def test_file_change_coordinator_skips_own_writes(
cell_ids = list(afm.app.cell_manager.cell_ids())
codes = list(afm.app.cell_manager.codes())
- afm.save(
- SaveNotebookRequest(
- cell_ids=cell_ids,
- filename=str(temp_file),
- codes=codes,
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ afm.save_from_cells(
+ [
+ NotebookCell(id=i, code=c, name=n, config=CellConfig())
+ for i, c, n in zip(cell_ids, codes, ["cell1"], strict=True)
+ ]
)
strategy = MagicMock()
@@ -707,29 +702,23 @@ async def test_file_change_coordinator_keeps_reloaded_generated_with(
afm = AppFileManager(filename=str(temp_file))
mock_session.app_file_manager = afm
- request = SaveNotebookRequest(
- cell_ids=[CellId_t("1")],
- filename=str(temp_file),
- codes=["x = 1"],
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
- afm.save(request)
+ request = [
+ NotebookCell(id=i, code=c, name=n, config=CellConfig())
+ for i, c, n in zip([CellId_t("1")], ["x = 1"], ["cell1"], strict=True)
+ ]
+ afm.save_from_cells(request)
old_content = temp_file.read_text().replace(
f'__generated_with = "{__version__}"',
'__generated_with = "0.0.0"',
)
- afm.save(
- SaveNotebookRequest(
- cell_ids=[CellId_t("1")],
- filename=str(temp_file),
- codes=["x = 2"],
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ afm.save_from_cells(
+ [
+ NotebookCell(id=i, code=c, name=n, config=CellConfig())
+ for i, c, n in zip(
+ [CellId_t("1")], ["x = 2"], ["cell1"], strict=True
+ )
+ ]
)
temp_file.write_text(old_content)
@@ -738,15 +727,16 @@ async def test_file_change_coordinator_keeps_reloaded_generated_with(
)
assert result.handled
- afm.save(
- SaveNotebookRequest(
- cell_ids=list(afm.app.cell_manager.cell_ids()),
- filename=str(temp_file),
- codes=list(afm.app.cell_manager.codes()),
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ afm.save_from_cells(
+ [
+ NotebookCell(id=i, code=c, name=n, config=CellConfig())
+ for i, c, n in zip(
+ list(afm.app.cell_manager.cell_ids()),
+ list(afm.app.cell_manager.codes()),
+ ["cell1"],
+ strict=True,
+ )
+ ]
)
assert '__generated_with = "0.0.0"' in temp_file.read_text()