A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: notebook schema serialization (#5131)
Myles Scolnick2422d9b162c4
diff --git a/.github/workflows/test_schemas.yaml b/.github/workflows/test_schemas.yamlindex e037597230..79c512d7b1 100644--- a/.github/workflows/test_schemas.yaml+++ b/.github/workflows/test_schemas.yaml@@ -3,7 +3,8 @@ name: Schema Breaking Changes Checkon:pull_request:paths:- - '**/*.yaml'+ - 'marimo/_schemas/**/*.yaml'+ - 'openapi/api.yaml'jobs:changes:@@ -11,6 +12,7 @@ jobs:outputs:openapi: ${{ steps.filter.outputs.openapi }}session: ${{ steps.filter.outputs.session }}+ notebook: ${{ steps.filter.outputs.notebook }}steps:- uses: actions/checkout@v4- uses: dorny/paths-filter@v3@@ -21,35 +23,55 @@ jobs:- 'openapi/api.yaml'session:- 'marimo/_schemas/generated/session.yaml'+ notebook:+ - 'marimo/_schemas/generated/notebook.yaml'- check-openapi:+ check-schemas:needs: changes- if: ${{ needs.changes.outputs.openapi == 'true' }}runs-on: ubuntu-latest- env:- SCHEMA_PATH: openapi/api.yaml+ strategy:+ matrix:+ schema:+ - name: openapi+ path: openapi/api.yaml+ display_name: OpenAPI specification+ condition: ${{ needs.changes.outputs.openapi == 'true' }}+ - name: session+ path: marimo/_schemas/generated/session.yaml+ display_name: Session Schema+ condition: ${{ needs.changes.outputs.session == 'true' }}+ - name: notebook+ path: marimo/_schemas/generated/notebook.yaml+ display_name: Notebook Schema+ condition: ${{ needs.changes.outputs.notebook == 'true' }}steps:- name: Checkout current branch+ if: ${{ matrix.schema.condition }}uses: actions/checkout@v4with:path: current- name: Checkout main branch+ if: ${{ matrix.schema.condition }}uses: actions/checkout@v4with:ref: mainpath: main- name: Install oasdiff+ if: ${{ matrix.schema.condition }}run: |curl -sSL https://raw.githubusercontent.com/tufin/oasdiff/master/install.sh | sh- - name: Compare OpenAPI specs+ - name: Compare ${{ matrix.schema.display_name }}+ if: ${{ matrix.schema.condition }}id: comparerun: |- BREAKING_CHANGES=$(oasdiff breaking main/${{ env.SCHEMA_PATH }} current/${{ env.SCHEMA_PATH }})+ BREAKING_CHANGES=$(oasdiff breaking main/${{ matrix.schema.path }} current/${{ matrix.schema.path }})if [ -n "$BREAKING_CHANGES" ]; then- echo "breaking_changes=$BREAKING_CHANGES" >> $GITHUB_OUTPUT+ echo "breaking_changes<<EOF" >> $GITHUB_OUTPUT+ echo "$BREAKING_CHANGES" >> $GITHUB_OUTPUT+ echo "EOF" >> $GITHUB_OUTPUTecho "Breaking changes detected:"echo "$BREAKING_CHANGES"exit 1@@ -58,11 +80,11 @@ jobs:fi- name: Comment on PR- if: failure()+ if: ${{ failure() && matrix.schema.condition }}uses: actions/github-script@v7with:script: |- const output = `Breaking changes detected in the OpenAPI specification!+ const output = `Breaking changes detected in the ${{ matrix.schema.display_name }}!${{ steps.compare.outputs.breaking_changes }}`@@ -72,53 +94,3 @@ jobs:repo: context.repo.repo,body: output})-- check-session:- needs: changes- if: ${{ needs.changes.outputs.session == 'true' }}- runs-on: ubuntu-latest- env:- SCHEMA_PATH: marimo/_schemas/generated/session.yaml- steps:- - name: Checkout current branch- uses: actions/checkout@v4- with:- path: current-- - name: Checkout main branch- uses: actions/checkout@v4- with:- ref: main- path: main-- - name: Install oasdiff- run: |- curl -sSL https://raw.githubusercontent.com/tufin/oasdiff/master/install.sh | sh-- - name: Compare Session Schema- id: compare- run: |- BREAKING_CHANGES=$(oasdiff breaking main/${{ env.SCHEMA_PATH }} current/${{ env.SCHEMA_PATH }})- if [ -n "$BREAKING_CHANGES" ]; then- echo "Breaking changes detected:"- echo "$BREAKING_CHANGES"- exit 1- else- echo "No breaking changes detected"- fi-- - name: Comment on PR- if: failure()- uses: actions/github-script@v7- with:- script: |- const output = `Breaking changes detected in the Session Schema!-- ${process.env.BREAKING_CHANGES}`-- github.rest.issues.createComment({- issue_number: context.issue.number,- owner: context.repo.owner,- repo: context.repo.repo,- body: output- })diff --git a/frontend/index.html b/frontend/index.htmlindex 42fd362058..e3255c9f77 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -57,7 +57,7 @@</head><body><div id="root"></div>- <script>+ <script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = '{{ mount_config }}';</script><script type="module" src="/src/main.tsx"></script>diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex 5ccfcda245..ace83ef0c8 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -173,6 +173,50 @@ const ActionButtons: React.FC<{await downloadAsHTML({ filename: document.title, includeCode: true });};+ const isStatic = isStaticNotebook();+ const actions: React.ReactNode[] = [];++ if (canShowCode) {+ actions.push(+ <DropdownMenuItem+ onSelect={onToggleShowCode}+ id="notebook-action-show-code"+ key="show-code"+ >+ <Code2Icon className="mr-2" size={14} strokeWidth={1.5} />+ <span className="flex-1">Show code</span>+ {showCode && <Check className="h-4 w-4" />}+ </DropdownMenuItem>,+ <DropdownMenuSeparator key="show-code-separator" />,+ );+ }++ if (!isStatic) {+ actions.push(+ <DropdownMenuItem+ onSelect={handleDownloadAsHTML}+ id="notebook-action-download-html"+ key="download-html"+ >+ <FolderDownIcon className="mr-2" size={14} strokeWidth={1.5} />+ Download as HTML+ </DropdownMenuItem>,+ <DropdownMenuSeparator key="download-html-separator" />,+ <DropdownMenuItem+ onSelect={handleDownloadAsPNG}+ id="notebook-action-download-png"+ key="download-png"+ >+ <ImageIcon className="mr-2" size={14} strokeWidth={1.5} />+ Download as PNG+ </DropdownMenuItem>,+ );+ }++ if (actions.length === 0) {+ return null;+ }+// Don't change the id of this element// as this may be used in custom css to hide/show the actions dropdownreturn (@@ -193,33 +237,7 @@ const ActionButtons: React.FC<{</Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="no-print w-[220px]">- {canShowCode && (- <>- <DropdownMenuItem- onSelect={onToggleShowCode}- id="notebook-action-show-code"- >- <Code2Icon className="mr-2" size={14} strokeWidth={1.5} />- <span className="flex-1">Show code</span>- {showCode && <Check className="h-4 w-4" />}- </DropdownMenuItem>- <DropdownMenuSeparator />- </>- )}- <DropdownMenuItem- onSelect={handleDownloadAsHTML}- id="notebook-action-download-html"- >- <FolderDownIcon className="mr-2" size={14} strokeWidth={1.5} />- Download as HTML- </DropdownMenuItem>- <DropdownMenuItem- onSelect={handleDownloadAsPNG}- id="notebook-action-download-png"- >- <ImageIcon className="mr-2" size={14} strokeWidth={1.5} />- Download as PNG- </DropdownMenuItem>+ {actions}</DropdownMenuContent></DropdownMenu></div>diff --git a/frontend/src/core/cells/__tests__/session.test.ts b/frontend/src/core/cells/__tests__/session.test.tsnew file mode 100644index 0000000000..045c432338--- /dev/null+++ b/frontend/src/core/cells/__tests__/session.test.ts@@ -0,0 +1,560 @@+/* Copyright 2024 Marimo. All rights reserved. */++/* eslint-disable @typescript-eslint/no-explicit-any */+import { describe, expect, it, vi, beforeEach } from "vitest";+import { notebookStateFromSession } from "../session";+import { Logger } from "@/utils/Logger";+import { parseOutline } from "@/core/dom/outline";+import { MultiColumn } from "@/utils/id-tree";+import type * as api from "@marimo-team/marimo-api";+import { invariant } from "@/utils/invariant";+import type { CellId } from "../ids";+import { visibleForTesting } from "@/utils/id-tree";++// Mock dependencies+vi.mock("@/utils/Logger", () => ({+ Logger: {+ error: vi.fn(),+ warn: vi.fn(),+ debug: vi.fn(),+ },+}));++vi.mock("@/core/dom/outline", () => ({+ parseOutline: vi.fn(),+}));++type SessionCell = api.Session["NotebookSessionV1"]["cells"][0];+type NotebookCell = api.Notebook["NotebookV1"]["cells"][0];++// Test constants+const CELL_1 = "cell-1" as CellId;++describe("notebookStateFromSession", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ visibleForTesting.reset();+ });++ // Test data factories+ const createSessionCell = (+ id: string,+ outputs: SessionCell["outputs"] = [],+ console: SessionCell["console"] = [],+ ): SessionCell => ({+ id,+ code_hash: null,+ outputs,+ console,+ });++ const createNotebookCell = (+ id: string,+ code: string | null = null,+ name: string | null = null,+ config: NotebookCell["config"] | null = null,+ ): NotebookCell => ({+ id,+ code,+ name,+ config: {+ column: config?.column ?? null,+ disabled: config?.disabled ?? null,+ hide_code: config?.hide_code ?? null,+ },+ });++ const createSession = (+ cells: SessionCell[],+ ): api.Session["NotebookSessionV1"] => ({+ version: "1",+ metadata: { marimo_version: "1" },+ cells,+ });++ const createNotebook = (+ cells: NotebookCell[],+ ): api.Notebook["NotebookV1"] => ({+ version: "1",+ metadata: { marimo_version: "1" },+ cells,+ });++ describe("validation", () => {+ it("logs error for both session and notebook null/undefined", () => {+ const result = notebookStateFromSession(null, null);+ expect(Logger.error).toHaveBeenCalledWith(+ "Both session and notebook are null/undefined",+ );+ expect(result).toBeNull();+ });++ it("logs error when session and notebook have different cells", () => {+ const session = createSession([createSessionCell("cell-1")]);+ const notebook = createNotebook([createNotebookCell("cell-2")]);++ const result = notebookStateFromSession(session, notebook);++ expect(Logger.error).toHaveBeenCalledWith(+ "Session and notebook must have the same cells if both are provided",+ );+ expect(result).toBeNull();+ });+ });++ describe("null/undefined inputs", () => {+ it("returns null when both session and notebook are null", () => {+ const result = notebookStateFromSession(null, null);+ expect(result).toBeNull();+ });++ it("returns null when both session and notebook are undefined", () => {+ const result = notebookStateFromSession(undefined, undefined);+ expect(result).toBeNull();+ });++ it("returns null when session is null and notebook is undefined", () => {+ const result = notebookStateFromSession(null, undefined);+ expect(result).toBeNull();+ });+ });++ describe("session only scenarios", () => {+ it("creates state from session with single cell", () => {+ const session = createSession([createSessionCell("cell-1")]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellIds.inOrderIds).toEqual(+ MultiColumn.from([[CELL_1]]).inOrderIds,+ );+ expect(result.cellData[CELL_1]).toBeUndefined();+ expect(result.cellRuntime[CELL_1]).toBeDefined();+ });++ it("creates state from session with multiple cells", () => {+ const session = createSession([+ createSessionCell("cell-1"),+ createSessionCell("cell-2"),+ ]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellIds.inOrderIds).toEqual(+ MultiColumn.from([["cell-1", "cell-2"]]).inOrderIds,+ );+ expect(Object.keys((result as any).cellData)).toEqual([]);+ expect(Object.keys((result as any).cellRuntime)).toEqual([+ "cell-1",+ "cell-2",+ ]);+ });++ it("handles error output in session cell", () => {+ const errorOutput = {+ type: "error" as const,+ ename: "ValueError",+ evalue: "Something went wrong",+ traceback: ["Traceback line 1"],+ };+ const session = createSession([+ createSessionCell("cell-1", [errorOutput]),+ ]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].output).toEqual({+ channel: "marimo-error",+ data: [+ {+ type: "unknown",+ msg: "Something went wrong",+ },+ ],+ mimetype: "application/vnd.marimo+error",+ timestamp: 0,+ });+ });++ it("handles data output in session cell", () => {+ const dataOutput = {+ type: "data" as const,+ data: {+ "text/plain": "Hello World",+ },+ };+ const session = createSession([+ createSessionCell("cell-1", [dataOutput]),+ ]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].output).toEqual({+ channel: "output",+ data: "Hello World",+ mimetype: "text/plain",+ timestamp: 0,+ });+ });++ it("handles console outputs in session cell", () => {+ const consoleOutputs = [+ { type: "stream", name: "stdout", text: "Hello stdout" } as const,+ { type: "stream", name: "stderr", text: "Hello stderr" } as const,+ ];+ const session = createSession([+ createSessionCell("cell-1", [], consoleOutputs),+ ]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].consoleOutputs).toEqual([+ {+ channel: "stdout",+ data: "Hello stdout",+ mimetype: "text/plain",+ timestamp: 0,+ },+ {+ channel: "stderr",+ data: "Hello stderr",+ mimetype: "text/plain",+ timestamp: 0,+ },+ ]);+ });++ it("calls parseOutline when output exists", () => {+ const mockOutline = { items: [] };+ vi.mocked(parseOutline).mockReturnValue(mockOutline);++ const dataOutput = {+ type: "data" as const,+ data: { "text/html": "<h1>Title</h1>" },+ };+ const session = createSession([+ createSessionCell("cell-1", [dataOutput]),+ ]);+ const result = notebookStateFromSession(session, null);++ expect(parseOutline).toHaveBeenCalledWith({+ channel: "output",+ data: "<h1>Title</h1>",+ mimetype: "text/html",+ timestamp: 0,+ });+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].outline).toBe(mockOutline);+ });++ it("sets outline to null when no output exists", () => {+ const session = createSession([createSessionCell("cell-1")]);+ const result = notebookStateFromSession(session, null);++ expect(parseOutline).not.toHaveBeenCalled();+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].outline).toBeNull();+ });+ });++ describe("notebook only scenarios", () => {+ it("creates state from notebook with single cell", () => {+ const notebook = createNotebook([+ createNotebookCell("cell-1", "print('hello')", "my_cell"),+ ]);+ const result = notebookStateFromSession(null, notebook);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellIds.inOrderIds).toEqual(+ MultiColumn.from([[CELL_1]]).inOrderIds,+ );+ expect(result.cellData[CELL_1]).toEqual({+ id: "cell-1",+ name: "my_cell",+ code: "print('hello')",+ edited: false,+ lastCodeRun: null,+ lastExecutionTime: null,+ config: {+ hide_code: false,+ disabled: false,+ column: null,+ },+ serializedEditorState: null,+ });+ });++ it("creates state from notebook with custom config", () => {+ const notebook = createNotebook([+ createNotebookCell("cell-1", "code", "name", {+ hide_code: true,+ disabled: true,+ column: 1,+ }),+ ]);+ const result = notebookStateFromSession(null, notebook);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellData[CELL_1].config).toEqual({+ hide_code: true,+ disabled: true,+ column: 1,+ });+ });++ it("handles null/undefined fields in notebook cell", () => {+ const notebookCell = {+ id: "cell-1",+ code: null,+ name: null,+ config: {+ hide_code: null,+ disabled: null,+ column: null,+ },+ };+ const notebook = createNotebook([notebookCell]);+ const result = notebookStateFromSession(null, notebook);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellData[CELL_1]).toEqual({+ id: "cell-1",+ name: "",+ code: "",+ edited: false,+ lastCodeRun: null,+ lastExecutionTime: null,+ config: {+ hide_code: false,+ disabled: false,+ column: null,+ },+ serializedEditorState: null,+ });+ });+ });++ describe("both session and notebook scenarios", () => {+ it("creates state when session and notebook have matching cells", () => {+ const session = createSession([+ createSessionCell(+ "cell-1",+ [],+ [{ type: "stream", name: "stdout", text: "output" }],+ ),+ ]);+ const notebook = createNotebook([+ createNotebookCell("cell-1", "print('hello')", "my_cell"),+ ]);+ const result = notebookStateFromSession(session, notebook);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellData[CELL_1]).toEqual({+ id: "cell-1",+ name: "my_cell",+ code: "print('hello')",+ edited: false,+ lastCodeRun: null,+ lastExecutionTime: null,+ config: {+ hide_code: false,+ disabled: false,+ column: null,+ },+ serializedEditorState: null,+ });+ expect(result.cellRuntime[CELL_1].consoleOutputs).toEqual([+ {+ channel: "stdout",+ data: "output",+ mimetype: "text/plain",+ timestamp: 0,+ },+ ]);+ });++ it("creates state when cell order differs but same cells", () => {+ const session = createSession([+ createSessionCell("cell-1"),+ createSessionCell("cell-2"),+ ]);+ const notebook = createNotebook([+ createNotebookCell("cell-2"),+ createNotebookCell("cell-1"),+ ]);++ const result = notebookStateFromSession(session, notebook);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellIds.inOrderIds).toEqual(+ MultiColumn.from([["cell-2", "cell-1"]]).inOrderIds,+ );+ });++ it("creates state when session and notebook have identical cell arrays", () => {+ const session = createSession([+ createSessionCell("cell-1"),+ createSessionCell("cell-2"),+ ]);+ const notebook = createNotebook([+ createNotebookCell("cell-1"),+ createNotebookCell("cell-2"),+ ]);++ const result = notebookStateFromSession(session, notebook);++ expect(Logger.error).not.toHaveBeenCalled();+ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellIds.inOrderIds).toEqual(+ MultiColumn.from([["cell-1", "cell-2"]]).inOrderIds,+ );+ });+ });++ describe("empty cells scenarios", () => {+ it("warns and returns null when session has empty cells array", () => {+ const session = createSession([]);+ const result = notebookStateFromSession(session, null);++ expect(Logger.warn).toHaveBeenCalledWith(+ "Session and notebook must have at least one cell",+ );+ expect(result).toBeNull();+ });++ it("warns and returns null when notebook has empty cells array", () => {+ const notebook = createNotebook([]);+ const result = notebookStateFromSession(null, notebook);++ expect(Logger.warn).toHaveBeenCalledWith(+ "Session and notebook must have at least one cell",+ );+ expect(result).toBeNull();+ });++ it("warns and returns null when both have empty cells arrays", () => {+ const session = createSession([]);+ const notebook = createNotebook([]);+ const result = notebookStateFromSession(session, notebook);++ expect(Logger.warn).toHaveBeenCalledWith(+ "Session and notebook must have at least one cell",+ );+ expect(result).toBeNull();+ });+ });++ describe("edge cases", () => {+ it("handles session cell with no outputs", () => {+ const session = createSession([createSessionCell("cell-1", [])]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].output).toBeNull();+ expect(result.cellRuntime[CELL_1].consoleOutputs).toEqual([]);+ expect(result.cellRuntime[CELL_1].outline).toBeNull();+ });++ it("handles session cell with empty console array", () => {+ const session = createSession([createSessionCell("cell-1", [], [])]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].consoleOutputs).toEqual([]);+ });++ it("handles session cell with multiple outputs (uses first one)", () => {+ const outputs = [+ { type: "data" as const, data: { "text/plain": "First" } },+ { type: "data" as const, data: { "text/plain": "Second" } },+ ];+ const session = createSession([createSessionCell("cell-1", outputs)]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].output).toEqual({+ channel: "output",+ data: "First",+ mimetype: "text/plain",+ timestamp: 0,+ });+ });++ it("handles data output with multiple mimetypes (uses first one)", () => {+ const dataOutput = {+ type: "data" as const,+ data: {+ "text/plain": "Plain text",+ "text/html": "<p>HTML</p>",+ },+ };+ const session = createSession([+ createSessionCell("cell-1", [dataOutput]),+ ]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].output).toEqual({+ channel: "output",+ data: "Plain text",+ mimetype: "text/plain",+ timestamp: 0,+ });+ });++ it("handles data output with empty data object", () => {+ const dataOutput = {+ type: "data" as const,+ data: {},+ };+ const session = createSession([+ createSessionCell("cell-1", [dataOutput]),+ ]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result.cellRuntime[CELL_1].output).toEqual({+ channel: "output",+ data: undefined,+ mimetype: undefined,+ timestamp: 0,+ });+ });++ it("returns correct structure with all expected properties", () => {+ const session = createSession([createSessionCell("cell-1")]);+ const result = notebookStateFromSession(session, null);++ expect(result).not.toBeNull();+ invariant(result, "result is null");+ expect(result).toHaveProperty("cellIds");+ expect(result).toHaveProperty("cellData");+ expect(result).toHaveProperty("cellRuntime");+ expect(result).toHaveProperty("cellHandles");+ expect(result).toHaveProperty("history");+ expect(result).toHaveProperty("scrollKey");+ expect(result).toHaveProperty("cellLogs");++ expect(result.cellHandles).toEqual({});+ expect(result.history).toEqual([]);+ expect(result.scrollKey).toBeNull();+ expect(result.cellLogs).toEqual([]);+ });+ });+});diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex e73bd69b44..e5a8a5b3ed 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -18,14 +18,12 @@ import { prepareCellForExecution, transitionCell } from "./cell";import { createDeepEqualAtom, store } from "../state/jotai";import { createReducerAndAtoms } from "../../utils/createReducer";import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";-import { findCollapseRange, mergeOutlines, parseOutline } from "../dom/outline";+import { findCollapseRange, mergeOutlines } from "../dom/outline";import type { CellHandle } from "@/components/editor/Cell";import { Logger } from "@/utils/Logger";import { Objects } from "@/utils/objects";import { splitAtom, selectAtom } from "jotai/utils";-import { isStaticNotebook, parseStaticState } from "../static/static-state";import { type CellLog, getCellLogsForMessage } from "./logs";-import { deserializeBase64, deserializeJson } from "@/utils/json/base64";import { historyField } from "@codemirror/commands";import { clamp } from "@/utils/math";import {@@ -127,57 +125,6 @@ function withScratchCell(notebookState: NotebookState): NotebookState {* Initial state of the notebook.*/function initialNotebookState(): NotebookState {- if (isStaticNotebook()) {- const {- cellCodes,- cellConfigs,- cellConsoleOutputs,- cellIds,- cellNames,- cellOutputs,- } = parseStaticState();- const cellData: Record<CellId, CellData> = {};- const cellRuntime: Record<CellId, CellRuntimeState> = {};- for (const [i, cellId] of cellIds.entries()) {- const name = cellNames[i];- const code = cellCodes[i];- const config = cellConfigs[i];- const outputs = cellConsoleOutputs[cellId] || [];- const output = cellOutputs[cellId];- cellData[cellId] = {- id: cellId,- name: deserializeBase64(name),- code: deserializeBase64(code),- edited: false,- lastCodeRun: null,- lastExecutionTime: null,- config: deserializeJson(deserializeBase64(config)),- serializedEditorState: null,- };- const outputMessage = output- ? deserializeJson(deserializeBase64(output))- : null;- cellRuntime[cellId] = {- ...createCellRuntimeState(),- output: outputMessage,- outline: parseOutline(outputMessage),- consoleOutputs: outputs.map((output) =>- deserializeJson(deserializeBase64(output)),- ),- };- }-- return {- cellIds: MultiColumn.from([cellIds]),- cellData: cellData,- cellRuntime: cellRuntime,- cellHandles: {},- history: [],- scrollKey: null,- cellLogs: [],- };- }-return withScratchCell({cellIds: MultiColumn.from([]),cellData: {},diff --git a/frontend/src/core/cells/session.ts b/frontend/src/core/cells/session.tsnew file mode 100644index 0000000000..d89cb850c9--- /dev/null+++ b/frontend/src/core/cells/session.ts@@ -0,0 +1,202 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { MultiColumn } from "@/utils/id-tree";+import type * as api from "@marimo-team/marimo-api";+import { parseOutline } from "../dom/outline";+import type { CellId } from "./ids";+import {+ type CellData,+ type CellRuntimeState,+ createCellRuntimeState,+} from "./types";+import { Logger } from "@/utils/Logger";+import { Maps } from "@/utils/maps";+import { Sets } from "@/utils/sets";++// Constants+const DEFAULT_TIMESTAMP = 0;+const EMPTY_STRING = "";++type SessionCell = api.Session["NotebookSessionV1"]["cells"][0];+type NotebookCell = api.Notebook["NotebookV1"]["cells"][0];++interface ValidationResult {+ isValid: boolean;+ error?: string;+}++function validateSessionNotebookCompatibility(+ session: api.Session["NotebookSessionV1"] | null | undefined,+ notebook: api.Notebook["NotebookV1"] | null | undefined,+): ValidationResult {+ if (!session && !notebook) {+ return {+ isValid: false,+ error: "Both session and notebook are null/undefined",+ };+ }++ if (!session || !notebook) {+ return { isValid: true }; // One is null, which is fine+ }++ const sessionCellIds = new Set(session.cells.map((cell) => cell.id));+ const notebookCellIds = new Set(notebook.cells.map((cell) => cell.id));++ // Only check they are equal if both are provided+ if (+ sessionCellIds.size > 0 &&+ notebookCellIds.size > 0 &&+ !Sets.equals(sessionCellIds, notebookCellIds)+ ) {+ return {+ isValid: false,+ error:+ "Session and notebook must have the same cells if both are provided",+ };+ }++ return { isValid: true };+}++function getCellIds(+ session: api.Session["NotebookSessionV1"] | null | undefined,+ notebook: api.Notebook["NotebookV1"] | null | undefined,+): CellId[] {+ // Prefer notebook cells (for ordering) over session cells if both are provided+ return (notebook?.cells.map((cell) => cell.id) ??+ session?.cells.map((cell) => cell.id) ??+ []) as CellId[];+}++function createCellDataFromNotebook(+ cellId: CellId,+ notebookCell: NotebookCell,+): CellData {+ return {+ id: cellId,+ name: notebookCell.name ?? EMPTY_STRING,+ code: notebookCell.code ?? EMPTY_STRING,+ edited: false,+ lastCodeRun: null,+ lastExecutionTime: null,+ config: {+ column: notebookCell.config?.column ?? null,+ disabled: notebookCell.config?.disabled ?? false,+ hide_code: notebookCell.config?.hide_code ?? false,+ },+ serializedEditorState: null,+ };+}++function createCellRuntimeFromSession(+ sessionCell: SessionCell | null | undefined,+): CellRuntimeState {+ const runtimeState = createCellRuntimeState();++ if (!sessionCell) {+ return runtimeState;+ }++ // Handle outputs - prioritize by type and use first available+ const outputs = sessionCell.outputs || [];+ const primaryOutput =+ outputs.find((output) => output.type === "data") ||+ outputs.find((output) => output.type === "error") ||+ outputs[0];++ if (primaryOutput) {+ if (primaryOutput.type === "error") {+ runtimeState.output = {+ channel: "marimo-error",+ data: [+ {+ type: "unknown",+ msg: primaryOutput.evalue,+ },+ ],+ mimetype: "application/vnd.marimo+error",+ timestamp: DEFAULT_TIMESTAMP,+ };+ } else if (primaryOutput.type === "data") {+ const mimeType = Object.keys(primaryOutput.data)[0];+ const data = Object.values(primaryOutput.data)[0];+ runtimeState.output = {+ channel: "output",+ data: data as {},+ mimetype: mimeType as "application/json",+ timestamp: DEFAULT_TIMESTAMP,+ };+ }+ }++ const consoleOutputs = sessionCell.console || [];++ return {+ ...runtimeState,+ outline: runtimeState.output ? parseOutline(runtimeState.output) : null,+ consoleOutputs: consoleOutputs.map((consoleOutput) => ({+ channel: consoleOutput.name === "stderr" ? "stderr" : "stdout",+ data: consoleOutput.text,+ mimetype: "text/plain",+ timestamp: DEFAULT_TIMESTAMP,+ })),+ };+}++export function notebookStateFromSession(+ session: api.Session["NotebookSessionV1"] | null | undefined,+ notebook: api.Notebook["NotebookV1"] | null | undefined,+) {+ // Validate compatibility+ const validation = validateSessionNotebookCompatibility(session, notebook);+ if (!validation.isValid) {+ if (validation.error) {+ Logger.error(validation.error);+ }+ return null;+ }++ // Get cell IDs+ const cellIds = getCellIds(session, notebook);+ if (cellIds.length === 0) {+ Logger.warn("Session and notebook must have at least one cell");+ return null;+ }++ // Create lookup maps for efficient access+ const sessionCellData = session?.cells+ ? Maps.keyBy(session.cells, (cell) => cell.id)+ : new Map();+ const notebookCellData = notebook?.cells+ ? Maps.keyBy(notebook.cells, (cell) => cell.id)+ : new Map();++ const cellData: Record<CellId, CellData> = {};+ const cellRuntime: Record<CellId, CellRuntimeState> = {};++ // Process each cell+ for (const cellId of cellIds) {+ const sessionCell = sessionCellData.get(cellId);+ const notebookCell = notebookCellData.get(cellId);++ // Create cell data from notebook if available+ if (notebookCell) {+ cellData[cellId] = createCellDataFromNotebook(cellId, notebookCell);+ }++ // Create cell runtime+ // This needs always be created even if there is no session cell+ // in order to display the cell in the correct state+ cellRuntime[cellId] = createCellRuntimeFromSession(sessionCell);+ }++ return {+ cellIds: MultiColumn.from([cellIds]),+ cellData: cellData,+ cellRuntime: cellRuntime,+ cellHandles: {},+ history: [],+ scrollKey: null,+ cellLogs: [],+ };+}diff --git a/frontend/src/core/static/static-state.ts b/frontend/src/core/static/static-state.tsindex 233b4ac1fb..913eccbcdf 100644--- a/frontend/src/core/static/static-state.ts+++ b/frontend/src/core/static/static-state.ts@@ -1,10 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { invariant } from "@/utils/invariant";-import type {- MarimoStaticState,- StaticNotebookState,- StaticVirtualFiles,-} from "./types";+import type { MarimoStaticState, StaticVirtualFiles } from "./types";declare global {interface Window {@@ -12,12 +8,6 @@ declare global {}}-export function parseStaticState(): StaticNotebookState {- invariant(window.__MARIMO_STATIC__ !== undefined, "Not a static notebook");-- return window.__MARIMO_STATIC__.notebookState;-}-export function isStaticNotebook(): boolean {return window?.__MARIMO_STATIC__ !== undefined;}diff --git a/frontend/src/core/static/types.ts b/frontend/src/core/static/types.tsindex f0274cdaba..3d3a4e3b58 100644--- a/frontend/src/core/static/types.ts+++ b/frontend/src/core/static/types.ts@@ -1,43 +1,8 @@/* Copyright 2024 Marimo. All rights reserved. */-import type {- Base64String,- DataURLString,- JsonString,-} from "@/utils/json/base64";-import type { CellId } from "../cells/ids";-import type { OutputMessage } from "../kernel/messages";-import type { CellConfig } from "../network/types";--export interface StaticNotebookState {- cellIds: CellId[];- cellNames: Array<Base64String<string>>;- cellCodes: Array<Base64String<string>>;- cellConfigs: Array<Base64String<JsonString<CellConfig>>>;- /**- * The runtime output of each cell.- * {- * "cell-1": "base64 json string",- * }- */- cellOutputs: Record<- CellId,- Base64String<JsonString<OutputMessage>> | undefined- >;- /**- * The data of each cell.- *- */- cellConsoleOutputs: Record<- CellId,- Array<Base64String<JsonString<OutputMessage>>> | undefined- >;-}+import type { DataURLString } from "@/utils/json/base64";export type StaticVirtualFiles = Record<string, DataURLString>;export interface MarimoStaticState {- version: string;- notebookState: StaticNotebookState;- assetUrl: string;files: StaticVirtualFiles;}diff --git a/frontend/src/css/table.css b/frontend/src/css/table.cssindex 1d4c5eae34..666b8df914 100644--- a/frontend/src/css/table.css+++ b/frontend/src/css/table.css@@ -3,7 +3,6 @@ table.dataframe {display: block;max-width: 100%;overflow: auto;-scrollbar-width: thin;}diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsxindex 261fe3730b..1894f4abba 100644--- a/frontend/src/mount.tsx+++ b/frontend/src/mount.tsx@@ -30,6 +30,9 @@ import {import { appConfigAtom, userConfigAtom } from "@/core/config/config";import { configOverridesAtom } from "@/core/config/config";import { getMarimoCode } from "@/core/meta/globals";+import type * as api from "@marimo-team/marimo-api";+import { notebookAtom } from "./core/cells/cells";+import { notebookStateFromSession } from "./core/cells/session";let hasMounted = false;@@ -173,6 +176,38 @@ const mountOptionsSchema = z.object({.string().nullish().transform((val) => val ?? ""),++ /**+ * Serialized Session["NotebookSessionV1"] snapshot+ */+ session: z.union([+ z.null().optional(),+ z+ .object({+ // Rough shape, we don't need to validate the full schema+ version: z.literal("1"),+ metadata: z.any(),+ cells: z.array(z.any()),+ })+ .passthrough()+ .transform((val) => val as api.Session["NotebookSessionV1"]),+ ]),++ /**+ * Serialized Notebook["NotebookV1"] snapshot+ */+ notebook: z.union([+ z.null().optional(),+ z+ .object({+ // Rough shape, we don't need to validate the full schema+ version: z.literal("1"),+ metadata: z.any(),+ cells: z.array(z.any()),+ })+ .passthrough()+ .transform((val) => val as api.Notebook["NotebookV1"]),+ ]),});function initStore(options: unknown) {@@ -202,6 +237,15 @@ function initStore(options: unknown) {);store.set(userConfigAtom, parseUserConfig(parsedOptions.data.config));store.set(appConfigAtom, parseAppConfig(parsedOptions.data.appConfig));++ // Session/notebook+ const notebook = notebookStateFromSession(+ parsedOptions.data.session,+ parsedOptions.data.notebook,+ );+ if (notebook) {+ store.set(notebookAtom, notebook);+ }}export const visibleForTesting = {diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsxindex 1905aa9768..7804ce88e8 100644--- a/frontend/src/utils/id-tree.tsx+++ b/frontend/src/utils/id-tree.tsx@@ -994,3 +994,9 @@ export class MultiColumn<T> {return new MultiColumn(newColumns);}}++export const visibleForTesting = {+ reset: () => {+ uniqueId = 0;+ },+};diff --git a/frontend/src/utils/sets.ts b/frontend/src/utils/sets.tsindex dd6c0a2dc0..16d3a4123d 100644--- a/frontend/src/utils/sets.ts+++ b/frontend/src/utils/sets.ts@@ -1,6 +1,9 @@/* Copyright 2024 Marimo. All rights reserved. */export const Sets = {- merge<T>(...sets: Array<Set<T>>): Set<T> {+ /**+ * Merge multiple iterables into a single set.+ */+ merge<T>(...sets: Array<Iterable<T>>): Set<T> {const result = new Set<T>();for (const set of sets) {for (const item of set) {@@ -9,4 +12,19 @@ export const Sets = {}return result;},++ /**+ * Check if two sets are equal (contain the same elements).+ */+ equals<T>(set1: Set<T>, set2: Set<T>): boolean {+ if (set1.size !== set2.size) {+ return false;+ }+ for (const item of set1) {+ if (!set2.has(item)) {+ return false;+ }+ }+ return true;+ },};diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex c1cfbd3af2..d59572cc26 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -17,6 +17,7 @@ if sys.version_info < (3, 10):else:from typing import ParamSpec, TypeAlias+from marimo import _loggersfrom marimo._ast.cell import Cell, CellConfigfrom marimo._ast.compiler import (cell_factory,@@ -45,6 +46,8 @@ Fn: TypeAlias = Callable[P, R]Cls: TypeAlias = typeObj: TypeAlias = "Cls | Fn[P, R]"+LOGGER = _loggers.marimo_logger()+class CellManager:"""A manager for cells in a marimo notebook.@@ -401,10 +404,32 @@ class CellManager:return self._cell_data[cell_id]def get_cell_code(self, cell_id: CellId_t) -> Optional[str]:+ """Get the code for a cell by its ID.++ Args:+ cell_id: The ID of the cell++ Returns:+ Optional[str]: The cell's code, or None if the cell doesn't exist+ """if cell_id not in self._cell_data:return Nonereturn self._cell_data[cell_id].code+ def get_cell_data(self, cell_id: CellId_t) -> Optional[CellData]:+ """Get the cell data for a specific cell ID.++ Args:+ cell_id: The ID of the cell to get data for++ Returns:+ Optional[CellData]: The cell's data, or None if the cell doesn't exist+ """+ if cell_id not in self._cell_data:+ LOGGER.debug(f"Cell with ID '{cell_id}' not found in cell manager")+ return None+ return self._cell_data[cell_id]+def get_cell_id_by_code(self, code: str) -> Optional[CellId_t]:"""Find a cell ID by its code content.diff --git a/marimo/_schemas/README.md b/marimo/_schemas/README.mdnew file mode 100644index 0000000000..781c0dfed0--- /dev/null+++ b/marimo/_schemas/README.md@@ -0,0 +1,21 @@+# Schemas++This directory contains the schemas for the notebook and session.++## How to update the schemas++1. Run `python scripts/generate_schemas.py` to generate the OpenAPI schema.+2. Run `make fe-codegen` to generate the frontend types.++## Schema backwards compatibility++We check for backwards compatibility using a GitHub action: `.github/workflows/test_schemas.yaml`++This will check that the OpenAPI schema is backwards compatible.++## Adding a new schema++1. Add the new schema to the `marimo/_schemas` directory.+2. Run `marimo edit scripts/generate_schemas.py` and add the schema (should be analogous to others).+3. Run `make fe-codegen` to generate the frontend types.+4. Add the new schema GitHub action to `.github/workflows/test_schemas.yaml`diff --git a/marimo/_schemas/common.py b/marimo/_schemas/common.pynew file mode 100644index 0000000000..05ededc41a--- /dev/null+++ b/marimo/_schemas/common.py@@ -0,0 +1,11 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++from typing import TypedDict+++# Base types for extensibility+class BaseDict(TypedDict, total=False):+ """Base dictionary allowing additional fields"""++ passdiff --git a/marimo/_schemas/generated/notebook.yaml b/marimo/_schemas/generated/notebook.yamlnew file mode 100644index 0000000000..905dc2a2d0--- /dev/null+++ b/marimo/_schemas/generated/notebook.yaml@@ -0,0 +1,77 @@+# This file is generated by scripts/generate_schemas.py+components:+ schemas:+ NotebookCell:+ properties:+ code:+ nullable: true+ type: string+ config:+ properties:+ column:+ nullable: true+ type: integer+ disabled:+ nullable: true+ type: boolean+ hide_code:+ nullable: true+ type: boolean+ required:+ - column+ - disabled+ - hide_code+ type: object+ id:+ type: string+ name:+ nullable: true+ type: string+ required:+ - id+ - code+ - name+ - config+ type: object+ NotebookCellConfig:+ properties:+ column:+ nullable: true+ type: integer+ disabled:+ nullable: true+ type: boolean+ hide_code:+ nullable: true+ type: boolean+ required:+ - column+ - disabled+ - hide_code+ type: object+ NotebookMetadata:+ properties:+ marimo_version:+ nullable: true+ type: string+ required:+ - marimo_version+ type: object+ NotebookV1:+ properties:+ cells:+ items:+ $ref: '#/components/schemas/NotebookCell'+ type: array+ metadata:+ $ref: '#/components/schemas/NotebookMetadata'+ version:+ type: string+ required:+ - version+ - metadata+ - cells+ type: object+info:+ title: marimo_session+openapi: 3.0.0diff --git a/marimo/_schemas/generated/session.yaml b/marimo/_schemas/generated/session.yamlindex 9e3e0a969d..f78c7d0a2c 100644--- a/marimo/_schemas/generated/session.yaml+++ b/marimo/_schemas/generated/session.yaml@@ -57,7 +57,7 @@ components:- evalue- tracebacktype: object- NotebookMetadata:+ NotebookSessionMetadata:properties:marimo_version:nullable: true@@ -72,7 +72,7 @@ components:$ref: '#/components/schemas/Cell'type: arraymetadata:- $ref: '#/components/schemas/NotebookMetadata'+ $ref: '#/components/schemas/NotebookSessionMetadata'version:type: stringrequired:diff --git a/marimo/_schemas/notebook.py b/marimo/_schemas/notebook.pynew file mode 100644index 0000000000..f3603b014e--- /dev/null+++ b/marimo/_schemas/notebook.py@@ -0,0 +1,49 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++from typing import Optional++from marimo._schemas.common import BaseDict++# This file contains the schema for the notebook.+# It may be externally used and must be kept backwards compatible.+#+# We generate the OpenAPI schema using a marimo notebook: `python scripts/generate_schemas.py`+# We generate frontend types using `make fe-codegen`+# We check for backwards compatibility using a GitHub action: `.github/workflows/test_schemas.yaml`+++class NotebookCellConfig(BaseDict):+ """Configuration for a notebook cell"""++ column: Optional[int]+ disabled: Optional[bool]+ hide_code: Optional[bool]+++class NotebookCell(BaseDict):+ """Code cell specific structure"""++ id: str+ code: Optional[str]+ name: Optional[str]+ config: NotebookCellConfig+++# Notebook metadata+class NotebookMetadata(BaseDict):+ """Metadata about the notebook"""++ marimo_version: Optional[str]+++# Main notebook structure+class NotebookV1(BaseDict):+ """Main notebook structure"""++ # The notebook format version+ version: str+ # Metadata about the notebook+ metadata: NotebookMetadata+ # The cells in the notebook+ cells: list[NotebookCell]diff --git a/marimo/_schemas/session.py b/marimo/_schemas/session.pyindex 1c495063b5..033abdc20c 100644--- a/marimo/_schemas/session.py+++ b/marimo/_schemas/session.py@@ -1,14 +1,16 @@# Copyright 2025 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Literal, Optional, TypedDict, Union+from typing import Any, Literal, Optional, Union+from marimo._schemas.common import BaseDict-# Base types for extensibility-class BaseDict(TypedDict, total=False):- """Base dictionary allowing additional fields"""-- pass+# This file contains the schema for the notebook session.+# It may be externally used and must be kept backwards compatible.+#+# We generate the OpenAPI schema using a marimo notebook: `python scripts/generate_schemas.py`+# We generate frontend types using `make fe-codegen`+# We check for backwards compatibility using a GitHub action: `.github/workflows/test_schemas.yaml`# Metadata types@@ -57,8 +59,8 @@ class Cell(BaseDict):# since that exists in the notebook.py itself-# Notebook metadata-class NotebookMetadata(BaseDict):+# Notebook session metadata+class NotebookSessionMetadata(BaseDict):"""Metadata about the notebook"""marimo_version: Optional[str]@@ -74,7 +76,7 @@ class NotebookSessionV1(BaseDict):# The notebook format versionversion: str# Metadata about the notebook- metadata: NotebookMetadata+ metadata: NotebookSessionMetadata# The cells in the notebookcells: list[Cell]diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 3f494b407b..1de6b83b76 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -14,7 +14,7 @@ from typing import ()from marimo import __version__, _loggers-from marimo._ast.cell import Cell, CellConfig, CellImpl+from marimo._ast.cell import Cell, CellImplfrom marimo._ast.names import DEFAULT_CELL_NAME, is_internal_cell_namefrom marimo._config.config import (DEFAULT_CONFIG,@@ -37,6 +37,10 @@ from marimo._server.export.utils import ()from marimo._server.file_manager import AppFileManagerfrom marimo._server.models.export import ExportAsHTMLRequest+from marimo._server.session.serialize import (+ serialize_notebook,+ serialize_session_view,+)from marimo._server.session.session_view import SessionViewfrom marimo._server.templates.templates import (static_notebook_template,@@ -67,7 +71,6 @@ class Exporter:) -> tuple[str, str]:index_html = get_html_contents()- cell_ids = list(file_manager.app.cell_manager.cell_ids())filename = get_filename(file_manager)files: dict[str, str] = {}@@ -97,18 +100,20 @@ class Exporter:config = deep_copy(DEFAULT_CONFIG)config["display"] = display_config- # code and console outputs are grouped together, but- # we can split them up in the future if desired.- if request.include_code:- code = file_manager.to_code()- codes = file_manager.app.cell_manager.codes()- configs = file_manager.app.cell_manager.configs()- console_outputs = session_view.get_cell_console_outputs(cell_ids)- else:+ session_snapshot = serialize_session_view(session_view)+ notebook_snapshot = serialize_notebook(+ session_view, file_manager.app.cell_manager+ )+ if not request.include_code:code = ""- codes = ["" for _ in cell_ids]- configs = [CellConfig() for _ in cell_ids]- console_outputs = {}+ # Clear code and console outputs+ for cell in notebook_snapshot["cells"]:+ cell["code"] = ""+ cell["name"] = ""+ for output in session_snapshot["cells"]:+ output["console"] = []+ else:+ code = file_manager.to_code()# We include the code hash regardless of whether we include the codecode_hash = hash_code(file_manager.to_code())@@ -122,12 +127,8 @@ class Exporter:filepath=file_manager.filename,code=code,code_hash=code_hash,- cell_ids=cell_ids,- cell_names=list(file_manager.app.cell_manager.names()),- cell_codes=list(codes),- cell_configs=list(configs),- cell_outputs=session_view.get_cell_outputs(cell_ids),- cell_console_outputs=console_outputs,+ session_snapshot=session_snapshot,+ notebook_snapshot=notebook_snapshot,files=files,asset_url=request.asset_url,)diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.pyindex 18b66cabf1..8ec7d981ae 100644--- a/marimo/_server/session/serialize.py+++ b/marimo/_server/session/serialize.py@@ -9,6 +9,7 @@ from pathlib import Pathfrom typing import Any, Optional, Union, castfrom marimo import __version__, _loggers+from marimo._ast.cell_manager import CellManagerfrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.errors import (Error as MarimoError,@@ -16,12 +17,18 @@ from marimo._messaging.errors import ()from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.ops import CellOp+from marimo._schemas.notebook import (+ NotebookCell,+ NotebookCellConfig,+ NotebookMetadata,+ NotebookV1,+)from marimo._schemas.session import (VERSION,Cell,DataOutput,ErrorOutput,- NotebookMetadata,+ NotebookSessionMetadata,NotebookSessionV1,OutputType,StreamOutput,@@ -34,6 +41,24 @@ from marimo._utils.lists import as_listLOGGER = _loggers.marimo_logger()+def _normalize_error(error: Union[MarimoError, dict[str, Any]]) -> ErrorOutput:+ """Normalize error to consistent format."""+ if isinstance(error, dict):+ return ErrorOutput(+ type="error",+ ename=error.get("type", "UnknownError"),+ evalue=error.get("msg", ""),+ traceback=error.get("traceback", []),+ )+ else:+ return ErrorOutput(+ type="error",+ ename=error.type,+ evalue=error.describe(),+ traceback=getattr(error, "traceback", []),+ )++def serialize_session_view(view: SessionView) -> NotebookSessionV1:"""Convert a SessionView to a NotebookSession schema."""cells: list[Cell] = []@@ -49,26 +74,7 @@ def serialize_session_view(view: SessionView) -> NotebookSessionV1:list[Union[MarimoError, dict[str, Any]]],cell_op.output.data,):- # Handle both dictionary and object errors- # Errors can be a dictionary if they are serialized- error_type = (- error.get("type", "Unknown")- if isinstance(error, dict)- else error.type- )- error_value = (- error.get("msg", "")- if isinstance(error, dict)- else error.describe()- )- outputs.append(- ErrorOutput(- type="error",- ename=error_type,- evalue=error_value,- traceback=[],- )- )+ outputs.append(_normalize_error(error))else:outputs.append(DataOutput(@@ -106,7 +112,7 @@ def serialize_session_view(view: SessionView) -> NotebookSessionV1:return NotebookSessionV1(version=VERSION,- metadata=NotebookMetadata(marimo_version=__version__),+ metadata=NotebookSessionMetadata(marimo_version=__version__),cells=cells,)@@ -187,6 +193,48 @@ def deserialize_session(session: NotebookSessionV1) -> SessionView:return view+def serialize_notebook(+ view: SessionView, cell_manager: CellManager+) -> NotebookV1:+ """Convert a SessionView to a Notebook schema."""+ cells: list[NotebookCell] = []++ for cell_id in view.cell_operations.keys():+ # Get the code from last_executed_code, fallback to empty string+ code = view.last_executed_code.get(cell_id, "")+ cell_data = cell_manager.get_cell_data(cell_id)+ if cell_data is None:+ LOGGER.warning(f"Cell data not found for cell {cell_id}")+ name = None+ config = NotebookCellConfig(+ column=None,+ disabled=None,+ hide_code=None,+ )+ else:+ name = cell_data.name+ config = NotebookCellConfig(+ column=cell_data.config.column,+ disabled=cell_data.config.disabled,+ hide_code=cell_data.config.hide_code,+ )++ cells.append(+ NotebookCell(+ id=cell_id,+ code=code,+ name=name,+ config=config,+ )+ )++ return NotebookV1(+ version=VERSION,+ metadata=NotebookMetadata(marimo_version=__version__),+ cells=cells,+ )++def get_session_cache_file(path: Path) -> Path:"""Get the cache file for a given path.diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 9f253a0b81..594a5b7304 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import base64+import htmlimport jsonimport osfrom textwrap import dedent@@ -9,20 +9,24 @@ from typing import Any, Literal, Optional, Union, castfrom marimo import __version__from marimo._ast.app_config import _AppConfig-from marimo._ast.cell import CellConfigfrom marimo._config.config import MarimoConfig, PartialMarimoConfig-from marimo._messaging.cell_output import CellOutputfrom marimo._output.utils import uri_encode_component+from marimo._schemas.notebook import NotebookV1+from marimo._schemas.session import NotebookSessionV1from marimo._server.api.utils import parse_titlefrom marimo._server.file_manager import read_css_file, read_html_head_filefrom marimo._server.model import SessionModefrom marimo._server.tokens import SkewProtectionToken-from marimo._types.ids import CellId_tfrom marimo._utils.versions import is_editableMOUNT_CONFIG_TEMPLATE = "'{{ mount_config }}'"+def _html_escape(text: str) -> str:+ """Escape HTML special characters."""+ return html.escape(text, quote=True)++def _get_mount_config(*,filename: Optional[str],@@ -33,13 +37,15 @@ def _get_mount_config(app_config: Optional[_AppConfig],version: Optional[str] = None,show_app_code: bool = True,+ session_snapshot: Optional[NotebookSessionV1] = None,+ notebook_snapshot: Optional[NotebookV1] = None,) -> str:"""Return a JSON string with custom indentation and sorting."""options: dict[str, Any] = {- "filename": filename,+ "filename": filename or "","mode": mode,"version": version or get_version(),"server_token": str(server_token),@@ -47,10 +53,12 @@ def _get_mount_config("config_overrides": config_overrides,"app_config": _del_none_or_empty(app_config.asdict())if app_config- else None,+ else {},"view": {"showAppCode": show_app_code,},+ "notebook": notebook_snapshot,+ "session": session_snapshot,}return """{{@@ -62,6 +70,8 @@ def _get_mount_config("configOverrides": {config_overrides},"appConfig": {app_config},"view": {view},+ "notebook": {notebook},+ "session": {session},}}""".format(**{k: json.dumps(v, sort_keys=True) for k, v in options.items()}@@ -109,7 +119,7 @@ def notebook_page_template() -> str:html = html.replace("{{ base_url }}", base_url)- html = html.replace("{{ filename }}", filename or "")+ html = html.replace("{{ filename }}", _html_escape(filename or ""))html = html.replace(MOUNT_CONFIG_TEMPLATE,_get_mount_config(@@ -124,7 +134,7 @@ def notebook_page_template(html = html.replace("{{ title }}",- (+ _html_escape(parse_title(filename)if app_config.app_title is Noneelse app_config.app_title@@ -164,12 +174,8 @@ def static_notebook_template(filepath: Optional[str],code: str,code_hash: str,- cell_ids: list[CellId_t],- cell_names: list[str],- cell_codes: list[str],- cell_configs: list[CellConfig],- cell_outputs: dict[CellId_t, CellOutput],- cell_console_outputs: dict[CellId_t, list[CellOutput]],+ session_snapshot: NotebookSessionV1,+ notebook_snapshot: NotebookV1,files: dict[str, str],asset_url: Optional[str] = None,) -> str:@@ -178,7 +184,7 @@ def static_notebook_template(html = html.replace("{{ base_url }}", "")filename = os.path.basename(filepath or "")- html = html.replace("{{ filename }}", filename or "")+ html = html.replace("{{ filename }}", _html_escape(filename))# We don't need all this user config when we export the notebook,# but we do need some:@@ -193,51 +199,24 @@ def static_notebook_template(user_config=user_config,config_overrides=config_overrides,app_config=app_config,+ session_snapshot=session_snapshot,+ notebook_snapshot=notebook_snapshot,),)html = html.replace("{{ title }}",- (+ _html_escape(parse_title(filepath)if app_config.app_title is Noneelse app_config.app_title),)- serialized_cell_outputs = {- cell_id: _serialize_to_base64(json.dumps(output.asdict()))- for cell_id, output in cell_outputs.items()- }- serialized_cell_console_outputs = {- cell_id: [_serialize_to_base64(json.dumps(o.asdict())) for o in output]- for cell_id, output in cell_console_outputs.items()- if output- }-static_block = dedent(f"""<script data-marimo="true">window.__MARIMO_STATIC__ = {{}};- window.__MARIMO_STATIC__.version = "{__version__}";- window.__MARIMO_STATIC__.notebookState = {- json.dumps(- {- "cellIds": cell_ids,- "cellNames": _serialize_list_to_base64(cell_names),- "cellCodes": _serialize_list_to_base64(cell_codes),- "cellConfigs": _serialize_list_to_base64(- [- json.dumps(config.asdict())- for config in cell_configs- ]- ),- "cellOutputs": serialized_cell_outputs,- "cellConsoleOutputs": serialized_cell_console_outputs,- }- )- };- window.__MARIMO_STATIC__.assetUrl = "{asset_url}";window.__MARIMO_STATIC__.files = {json.dumps(files)};</script>"""@@ -326,12 +305,14 @@ def wasm_notebook_template(body = body.replace("{{ base_url }}", "")body = body.replace("{{ title }}",- parse_title(filename)- if app_config.app_title is None- else app_config.app_title,+ _html_escape(+ parse_title(filename)+ if app_config.app_title is None+ else app_config.app_title+ ),)- body = body.replace("{{ filename }}", "notebook.py")+ body = body.replace("{{ filename }}", _html_escape("notebook.py"))body = body.replace(MOUNT_CONFIG_TEMPLATE,_get_mount_config(@@ -408,18 +389,6 @@ def inject_script(html: str, script: str) -> str:return html.replace("</body>", f"{script_tag}</body>")-def _serialize_to_base64(value: str) -> str:- # Encode the JSON string to URL-encoded format- url_encoded = uri_encode_component(value)- # Encode the URL-encoded string to Base64- base64_encoded = base64.b64encode(url_encoded.encode()).decode()- return base64_encoded---def _serialize_list_to_base64(value: list[str]) -> list[str]:- return [_serialize_to_base64(v) for v in value]--def _del_none_or_empty(d: Any) -> Any:return {key: (diff --git a/openapi/api.yaml b/openapi/api.yamlindex d4f2991b85..94003ac3b2 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -8,7 +8,7 @@ components:nullable: truetype: booleanrequired:- - package+ - packagetype: objectAiCompletionContext:properties:@@ -19,12 +19,12 @@ components:variables:items:oneOf:- - $ref: '#/components/schemas/VariableContext'- - type: string+ - $ref: '#/components/schemas/VariableContext'+ - type: stringtype: arrayrequired:- - schema- - variables+ - schema+ - variablestype: objectAiCompletionRequest:properties:@@ -37,9 +37,9 @@ components:type: stringlanguage:enum:- - python- - markdown- - sql+ - python+ - markdown+ - sqltype: stringprompt:type: string@@ -47,27 +47,27 @@ components:nullable: truetype: stringrequired:- - prompt- - includeOtherCode- - code- - language+ - prompt+ - includeOtherCode+ - code+ - languagetype: objectAiInlineCompletionRequest:properties:language:enum:- - python- - markdown- - sql+ - python+ - markdown+ - sqltype: stringprefix:type: stringsuffix:type: stringrequired:- - prefix- - suffix- - language+ - prefix+ - suffix+ - languagetype: objectAlert:properties:@@ -75,61 +75,61 @@ components:type: stringname:enum:- - alert+ - alerttype: stringtitle:type: stringvariant:enum:- - danger+ - dangernullable: truetype: stringrequired:- - title- - description- - name+ - title+ - description+ - nametype: objectBanner:properties:action:enum:- - restart+ - restartnullable: truetype: stringdescription:type: stringname:enum:- - banner+ - bannertype: stringtitle:type: stringvariant:enum:- - danger+ - dangernullable: truetype: stringrequired:- - title- - description- - name+ - title+ - description+ - nametype: objectBaseResponse:properties:success:type: booleanrequired:- - success+ - successtype: objectCellChannel:enum:- - stdout- - stderr- - stdin- - pdb- - output- - marimo-error- - media+ - stdout+ - stderr+ - stdin+ - pdb+ - output+ - marimo-error+ - mediatype: stringCellConfig:properties:@@ -141,8 +141,8 @@ components:hide_code:type: booleanrequired:- - disabled- - hide_code+ - disabled+ - hide_codetype: objectCellOp:properties:@@ -151,13 +151,13 @@ components:console:nullable: trueoneOf:- - $ref: '#/components/schemas/CellOutput'- - items:- $ref: '#/components/schemas/CellOutput'- type: array+ - $ref: '#/components/schemas/CellOutput'+ - items:+ $ref: '#/components/schemas/CellOutput'+ type: arrayname:enum:- - cell-op+ - cell-optype: stringoutput:$ref: '#/components/schemas/CellOutput'@@ -177,9 +177,9 @@ components:timestamp:type: numberrequired:- - cell_id- - timestamp- - name+ - cell_id+ - timestamp+ - nametype: objectCellOutput:properties:@@ -187,21 +187,21 @@ components:$ref: '#/components/schemas/CellChannel'data:oneOf:- - type: string- - items:- $ref: '#/components/schemas/Error'- type: array- - additionalProperties: {}- type: object+ - type: string+ - items:+ $ref: '#/components/schemas/Error'+ type: array+ - additionalProperties: {}+ type: objectmimetype:$ref: '#/components/schemas/MimeType'timestamp:type: numberrequired:- - channel- - mimetype- - data- - timestamp+ - channel+ - mimetype+ - data+ - timestamptype: objectChatRequest:properties:@@ -223,8 +223,8 @@ components:url:type: stringrequired:- - url- - name+ - url+ - nametype: objectnullable: truetype: array@@ -233,13 +233,13 @@ components:type: objectrole:enum:- - user- - assistant- - system+ - user+ - assistant+ - systemtype: stringrequired:- - role- - content+ - role+ - contenttype: objecttype: arraymodel:@@ -248,14 +248,14 @@ components:variables:items:oneOf:- - $ref: '#/components/schemas/VariableContext'- - type: string+ - $ref: '#/components/schemas/VariableContext'+ - type: stringnullable: truetype: arrayrequired:- - context- - includeOtherCode- - messages+ - context+ - includeOtherCode+ - messagestype: objectCodeCompletionRequest:properties:@@ -266,9 +266,9 @@ components:id:type: stringrequired:- - id- - document- - cellId+ - id+ - document+ - cellIdtype: objectColumnStats:properties:@@ -319,10 +319,10 @@ components:properties:name:enum:- - completed-run+ - completed-runtype: stringrequired:- - name+ - nametype: objectCompletionResult:properties:@@ -330,7 +330,7 @@ components:type: stringname:enum:- - completion-result+ - completion-resulttype: stringoptions:items:@@ -343,17 +343,17 @@ components:type:type: stringrequired:- - name- - type+ - name+ - typetype: objecttype: arrayprefix_length:type: integerrequired:- - completion_id- - prefix_length- - options- - name+ - completion_id+ - prefix_length+ - options+ - nametype: objectCopyNotebookRequest:properties:@@ -362,8 +362,8 @@ components:source:type: stringrequired:- - source- - destination+ - source+ - destinationtype: objectCreateSecretRequest:properties:@@ -373,36 +373,36 @@ components:type: stringprovider:enum:- - env- - dotenv+ - env+ - dotenvtype: stringvalue:type: stringrequired:- - key- - value- - provider- - name+ - key+ - value+ - provider+ - nametype: objectCycleError:properties:edges_with_vars:items:prefixItems:- - type: string- - items:- type: string- type: array- - type: string+ - type: string+ - items:+ type: string+ type: array+ - type: stringtype: arraytype: arraytype:enum:- - cycle+ - cycletype: stringrequired:- - edges_with_vars- - type+ - edges_with_vars+ - typetype: objectDataColumnPreview:properties:@@ -426,7 +426,7 @@ components:type: arrayname:enum:- - data-column-preview+ - data-column-previewtype: stringstats:$ref: '#/components/schemas/ColumnStats'@@ -434,10 +434,10 @@ components:table_name:type: stringrequired:- - chart_max_rows_errors- - table_name- - column_name- - name+ - chart_max_rows_errors+ - table_name+ - column_name+ - nametype: objectDataSourceConnection:properties:@@ -461,14 +461,14 @@ components:$ref: '#/components/schemas/DataTable'type: arrayrequired:- - name- - tables+ - name+ - tablestype: objecttype: arrayrequired:- - name- - dialect- - schemas+ - name+ - dialect+ - schemastype: objecttype: arraydefault_database:@@ -486,11 +486,11 @@ components:source:type: stringrequired:- - source- - dialect- - name- - display_name- - databases+ - source+ - dialect+ - name+ - display_name+ - databasestype: objectDataSourceConnections:properties:@@ -500,11 +500,11 @@ components:type: arrayname:enum:- - data-source-connections+ - data-source-connectionstype: stringrequired:- - connections- - name+ - connections+ - nametype: objectDataTable:properties:@@ -537,25 +537,25 @@ components:type: stringsource_type:enum:- - local- - duckdb- - connection- - catalog+ - local+ - duckdb+ - connection+ - catalogtype: stringtype:enum:- - table- - view+ - table+ - viewtype: stringvariable_name:nullable: truetype: stringrequired:- - source_type- - source- - name- - columns- - type+ - source_type+ - source+ - name+ - columns+ - typetype: objectDataTableColumn:properties:@@ -569,21 +569,21 @@ components:type:$ref: '#/components/schemas/DataType'required:- - name- - type- - external_type- - sample_values+ - name+ - type+ - external_type+ - sample_valuestype: objectDataType:enum:- - string- - boolean- - integer- - number- - date- - datetime- - time- - unknown+ - string+ - boolean+ - integer+ - number+ - date+ - datetime+ - time+ - unknowntype: stringDatabase:properties:@@ -599,38 +599,38 @@ components:$ref: '#/components/schemas/Schema'type: arrayrequired:- - name- - dialect- - schemas+ - name+ - dialect+ - schemastype: objectDatasets:properties:clear_channel:enum:- - local- - duckdb- - connection- - catalog+ - local+ - duckdb+ - connection+ - catalognullable: truetype: stringname:enum:- - datasets+ - datasetstype: stringtables:items:$ref: '#/components/schemas/DataTable'type: arrayrequired:- - tables- - name+ - tables+ - nametype: objectDeleteCellRequest:properties:cellId:type: stringrequired:- - cellId+ - cellIdtype: objectDeleteNonlocalError:properties:@@ -642,35 +642,35 @@ components:type: stringtype:enum:- - delete-nonlocal+ - delete-nonlocaltype: stringrequired:- - name- - cells- - type+ - name+ - cells+ - typetype: objectDeleteSecretRequest:properties:key:type: stringrequired:- - key+ - keytype: objectError:oneOf:- - $ref: '#/components/schemas/SetupRootError'- - $ref: '#/components/schemas/CycleError'- - $ref: '#/components/schemas/MultipleDefinitionError'- - $ref: '#/components/schemas/ImportStarError'- - $ref: '#/components/schemas/DeleteNonlocalError'- - $ref: '#/components/schemas/MarimoAncestorStoppedError'- - $ref: '#/components/schemas/MarimoAncestorPreventedError'- - $ref: '#/components/schemas/MarimoExceptionRaisedError'- - $ref: '#/components/schemas/MarimoStrictExecutionError'- - $ref: '#/components/schemas/MarimoInterruptionError'- - $ref: '#/components/schemas/MarimoSyntaxError'- - $ref: '#/components/schemas/MarimoInternalError'- - $ref: '#/components/schemas/UnknownError'+ - $ref: '#/components/schemas/SetupRootError'+ - $ref: '#/components/schemas/CycleError'+ - $ref: '#/components/schemas/MultipleDefinitionError'+ - $ref: '#/components/schemas/ImportStarError'+ - $ref: '#/components/schemas/DeleteNonlocalError'+ - $ref: '#/components/schemas/MarimoAncestorStoppedError'+ - $ref: '#/components/schemas/MarimoAncestorPreventedError'+ - $ref: '#/components/schemas/MarimoExceptionRaisedError'+ - $ref: '#/components/schemas/MarimoStrictExecutionError'+ - $ref: '#/components/schemas/MarimoInterruptionError'+ - $ref: '#/components/schemas/MarimoSyntaxError'+ - $ref: '#/components/schemas/MarimoInternalError'+ - $ref: '#/components/schemas/UnknownError'ExecuteMultipleRequest:properties:cellIds:@@ -687,9 +687,9 @@ components:timestamp:type: numberrequired:- - cellIds- - codes- - timestamp+ - cellIds+ - codes+ - timestamptype: objectExecuteScratchpadRequest:properties:@@ -699,7 +699,7 @@ components:$ref: '#/components/schemas/HTTPRequest'nullable: truerequired:- - code+ - codetype: objectExecuteStaleRequest:properties:@@ -719,9 +719,9 @@ components:timestamp:type: numberrequired:- - cellId- - code- - timestamp+ - cellId+ - code+ - timestamptype: objectExportAsHTMLRequest:properties:@@ -737,30 +737,30 @@ components:includeCode:type: booleanrequired:- - download- - files- - includeCode+ - download+ - files+ - includeCodetype: objectExportAsIPYNBRequest:properties:download:type: booleanrequired:- - download+ - downloadtype: objectExportAsMarkdownRequest:properties:download:type: booleanrequired:- - download+ - downloadtype: objectExportAsScriptRequest:properties:download:type: booleanrequired:- - download+ - downloadtype: objectFileCreateRequest:properties:@@ -773,13 +773,13 @@ components:type: stringtype:enum:- - file- - directory+ - file+ - directorytype: stringrequired:- - path- - type- - name+ - path+ - type+ - nametype: objectFileCreateResponse:properties:@@ -792,14 +792,14 @@ components:success:type: booleanrequired:- - success+ - successtype: objectFileDeleteRequest:properties:path:type: stringrequired:- - path+ - pathtype: objectFileDeleteResponse:properties:@@ -809,14 +809,14 @@ components:success:type: booleanrequired:- - success+ - successtype: objectFileDetailsRequest:properties:path:type: stringrequired:- - path+ - pathtype: objectFileDetailsResponse:properties:@@ -829,7 +829,7 @@ components:nullable: truetype: stringrequired:- - file+ - filetype: objectFileInfo:properties:@@ -851,12 +851,12 @@ components:path:type: stringrequired:- - id- - path- - name- - isDirectory- - isMarimoFile- - children+ - id+ - path+ - name+ - isDirectory+ - isMarimoFile+ - childrentype: objectFileListRequest:properties:@@ -873,8 +873,8 @@ components:root:type: stringrequired:- - files- - root+ - files+ - roottype: objectFileMoveRequest:properties:@@ -883,8 +883,8 @@ components:path:type: stringrequired:- - path- - newPath+ - path+ - newPathtype: objectFileMoveResponse:properties:@@ -897,14 +897,14 @@ components:success:type: booleanrequired:- - success+ - successtype: objectFileOpenRequest:properties:path:type: stringrequired:- - path+ - pathtype: objectFileUpdateRequest:properties:@@ -913,8 +913,8 @@ components:path:type: stringrequired:- - path- - contents+ - path+ - contentstype: objectFileUpdateResponse:properties:@@ -927,7 +927,7 @@ components:success:type: booleanrequired:- - success+ - successtype: objectFocusCell:properties:@@ -935,11 +935,11 @@ components:type: stringname:enum:- - focus-cell+ - focus-celltype: stringrequired:- - cell_id- - name+ - cell_id+ - nametype: objectFormatRequest:properties:@@ -950,8 +950,8 @@ components:lineLength:type: integerrequired:- - codes- - lineLength+ - codes+ - lineLengthtype: objectFormatResponse:properties:@@ -960,7 +960,7 @@ components:type: stringtype: objectrequired:- - codes+ - codestype: objectFunctionCallRequest:properties:@@ -974,10 +974,10 @@ components:namespace:type: stringrequired:- - functionCallId- - namespace- - functionName- - args+ - functionCallId+ - namespace+ - functionName+ - argstype: objectFunctionCallResult:properties:@@ -985,30 +985,30 @@ components:type: stringname:enum:- - function-call-result+ - function-call-resulttype: stringreturn_value:nullable: trueoneOf:- - additionalProperties:- $ref: '#/components/schemas/JSONType'- type: object- - items:- $ref: '#/components/schemas/JSONType'- type: array- - type: string- - type: integer- - type: number- - type: boolean- - additionalProperties: true- type: object- - $ref: '#/components/schemas/MIME'+ - additionalProperties:+ $ref: '#/components/schemas/JSONType'+ type: object+ - items:+ $ref: '#/components/schemas/JSONType'+ type: array+ - type: string+ - type: integer+ - type: number+ - type: boolean+ - additionalProperties: true+ type: object+ - $ref: '#/components/schemas/MIME'status:$ref: '#/components/schemas/HumanReadableStatus'required:- - function_call_id- - status- - name+ - function_call_id+ - status+ - nametype: objectHTTPRequest:type: 'null'@@ -1016,8 +1016,8 @@ components:properties:code:enum:- - ok- - error+ - ok+ - errortype: stringmessage:nullable: true@@ -1026,7 +1026,7 @@ components:nullable: truetype: stringrequired:- - code+ - codetype: objectImportStarError:properties:@@ -1034,11 +1034,11 @@ components:type: stringtype:enum:- - import-star+ - import-startype: stringrequired:- - msg- - type+ - msg+ - typetype: objectInstallMissingPackagesRequest:properties:@@ -1049,27 +1049,27 @@ components:type: stringtype: objectrequired:- - manager- - versions+ - manager+ - versionstype: objectInstallingPackageAlert:properties:name:enum:- - installing-package-alert+ - installing-package-alerttype: stringpackages:additionalProperties:enum:- - queued- - installing- - installed- - failed+ - queued+ - installing+ - installed+ - failedtype: stringtype: objectrequired:- - packages- - name+ - packages+ - nametype: objectInstantiateRequest:properties:@@ -1083,27 +1083,27 @@ components:items: {}type: arrayrequired:- - objectIds- - values- - autoRun+ - objectIds+ - values+ - autoRuntype: objectInterrupted:properties:name:enum:- - interrupted+ - interruptedtype: stringrequired:- - name+ - nametype: objectJSONType:oneOf:- - type: string- - type: number- - type: object- - type: array- - type: boolean- - type: 'null'+ - type: string+ - type: number+ - type: object+ - type: array+ - type: boolean+ - type: 'null'KernelReady:properties:app_config:@@ -1114,8 +1114,8 @@ components:auto_download:items:enum:- - html- - markdown+ - html+ - markdowntype: stringtype: arraycss_file:@@ -1129,24 +1129,24 @@ components:type: stringsql_output:enum:- - polars- - lazy-polars- - pandas- - native- - auto+ - polars+ - lazy-polars+ - pandas+ - native+ - autotype: stringwidth:enum:- - normal- - compact- - medium- - full- - columns+ - normal+ - compact+ - medium+ - full+ - columnstype: stringrequired:- - width- - auto_download- - sql_output+ - width+ - auto_download+ - sql_outputtype: objectcapabilities:properties:@@ -1155,8 +1155,8 @@ components:terminal:type: booleanrequired:- - terminal- - pylsp+ - terminal+ - pylsptype: objectcell_ids:items:@@ -1191,12 +1191,12 @@ components:type:type: stringrequired:- - type- - data+ - type+ - datatype: objectname:enum:- - kernel-ready+ - kernel-readytype: stringnames:items:@@ -1208,59 +1208,59 @@ components:additionalProperties:nullable: trueoneOf:- - additionalProperties:- nullable: true- oneOf:- - additionalProperties:- $ref: '#/components/schemas/JSONType'- type: object- - items:- $ref: '#/components/schemas/JSONType'- type: array- - type: string- - type: integer- - type: number- - type: boolean- - additionalProperties: true- type: object- - $ref: '#/components/schemas/MIME'- type: object- - items:- nullable: true- oneOf:- - additionalProperties:- $ref: '#/components/schemas/JSONType'- type: object- - items:- $ref: '#/components/schemas/JSONType'- type: array- - type: string- - type: integer- - type: number- - type: boolean- - additionalProperties: true- type: object- - $ref: '#/components/schemas/MIME'- type: array- - type: string- - type: integer- - type: number- - type: boolean- - additionalProperties: true- type: object- - $ref: '#/components/schemas/MIME'+ - additionalProperties:+ nullable: true+ oneOf:+ - additionalProperties:+ $ref: '#/components/schemas/JSONType'+ type: object+ - items:+ $ref: '#/components/schemas/JSONType'+ type: array+ - type: string+ - type: integer+ - type: number+ - type: boolean+ - additionalProperties: true+ type: object+ - $ref: '#/components/schemas/MIME'+ type: object+ - items:+ nullable: true+ oneOf:+ - additionalProperties:+ $ref: '#/components/schemas/JSONType'+ type: object+ - items:+ $ref: '#/components/schemas/JSONType'+ type: array+ - type: string+ - type: integer+ - type: number+ - type: boolean+ - additionalProperties: true+ type: object+ - $ref: '#/components/schemas/MIME'+ type: array+ - type: string+ - type: integer+ - type: number+ - type: boolean+ - additionalProperties: true+ type: object+ - $ref: '#/components/schemas/MIME'nullable: truetype: objectrequired:- - cell_ids- - codes- - names- - configs- - resumed- - app_config- - kiosk- - capabilities- - name+ - cell_ids+ - codes+ - names+ - configs+ - resumed+ - app_config+ - kiosk+ - capabilities+ - nametype: objectListPackagesResponse:properties:@@ -1269,14 +1269,14 @@ components:$ref: '#/components/schemas/PackageDescription'type: arrayrequired:- - packages+ - packagestype: objectListSecretKeysRequest:properties:requestId:type: stringrequired:- - requestId+ - requestIdtype: objectListSecretKeysResponse:properties:@@ -1285,7 +1285,7 @@ components:$ref: '#/components/schemas/SecretKeysWithProvider'type: arrayrequired:- - keys+ - keystype: objectMIME:properties: {}@@ -1301,12 +1301,12 @@ components:type: stringtype:enum:- - ancestor-prevented+ - ancestor-preventedtype: stringrequired:- - msg- - raising_cell- - type+ - msg+ - raising_cell+ - typetype: objectMarimoAncestorStoppedError:properties:@@ -1316,12 +1316,12 @@ components:type: stringtype:enum:- - ancestor-stopped+ - ancestor-stoppedtype: stringrequired:- - msg- - raising_cell- - type+ - msg+ - raising_cell+ - typetype: objectMarimoConfig:properties:@@ -1383,39 +1383,39 @@ components:type: stringcopilot:oneOf:- - type: boolean- - enum:- - github- - codeium- - custom- type: string+ - type: boolean+ - enum:+ - github+ - codeium+ - custom+ type: stringmodel:nullable: truetype: stringrequired:- - activate_on_typing- - copilot+ - activate_on_typing+ - copilottype: objectdatasources:properties:auto_discover_columns:oneOf:- - type: boolean- - enum:- - auto- type: string+ - type: boolean+ - enum:+ - auto+ type: stringauto_discover_schemas:oneOf:- - type: boolean- - enum:- - auto- type: string+ - type: boolean+ - enum:+ - auto+ type: stringauto_discover_tables:oneOf:- - type: boolean- - enum:- - auto- type: string+ - type: boolean+ - enum:+ - auto+ type: stringtype: objectdiagnostics:properties:@@ -1426,8 +1426,8 @@ components:properties:cell_output:enum:- - above- - below+ - above+ - belowtype: stringcode_editor_font_size:type: integer@@ -1437,32 +1437,32 @@ components:type: arraydataframes:enum:- - rich- - plain+ - rich+ - plaintype: stringdefault_table_page_size:type: integerdefault_width:enum:- - normal- - compact- - medium- - full- - columns+ - normal+ - compact+ - medium+ - full+ - columnstype: stringtheme:enum:- - light- - dark- - system+ - light+ - dark+ - systemtype: stringrequired:- - theme- - code_editor_font_size- - cell_output- - default_width- - dataframes- - default_table_page_size+ - theme+ - code_editor_font_size+ - cell_output+ - default_width+ - dataframes+ - default_table_page_sizetype: objectexperimental:additionalProperties: {}@@ -1472,7 +1472,7 @@ components:line_length:type: integerrequired:- - line_length+ - line_lengthtype: objectkeymap:properties:@@ -1482,14 +1482,14 @@ components:type: objectpreset:enum:- - default- - vim+ - default+ - vimtype: stringvimrc:nullable: truetype: stringrequired:- - preset+ - presettype: objectlanguage_servers:properties:@@ -1515,14 +1515,14 @@ components:properties:manager:enum:- - pip- - rye- - uv- - poetry- - pixi+ - pip+ - rye+ - uv+ - poetry+ - pixitype: stringrequired:- - manager+ - managertype: objectruntime:properties:@@ -1530,17 +1530,17 @@ components:type: booleanauto_reload:enum:- - 'off'- - lazy- - autorun+ - 'off'+ - lazy+ - autoruntype: stringdefault_sql_output:enum:- - polars- - lazy-polars- - pandas- - native- - auto+ - polars+ - lazy-polars+ - pandas+ - native+ - autotype: stringdotenv:items:@@ -1548,8 +1548,8 @@ components:type: arrayon_cell_change:enum:- - lazy- - autorun+ - lazy+ - autoruntype: stringoutput_max_bytes:type: integer@@ -1563,48 +1563,48 @@ components:type: integerwatcher_on_save:enum:- - lazy- - autorun+ - lazy+ - autoruntype: stringrequired:- - auto_instantiate- - auto_reload- - reactive_tests- - on_cell_change- - watcher_on_save- - output_max_bytes- - std_stream_max_bytes- - default_sql_output+ - auto_instantiate+ - auto_reload+ - reactive_tests+ - on_cell_change+ - watcher_on_save+ - output_max_bytes+ - std_stream_max_bytes+ - default_sql_outputtype: objectsave:properties:autosave:enum:- - 'off'- - after_delay+ - 'off'+ - after_delaytype: stringautosave_delay:type: integerformat_on_save:type: booleanrequired:- - autosave- - autosave_delay- - format_on_save+ - autosave+ - autosave_delay+ - format_on_savetype: objectserver:properties:browser:oneOf:- - enum:- - default- type: string- - type: string+ - enum:+ - default+ type: string+ - type: stringfollow_symlink:type: booleanrequired:- - browser- - follow_symlink+ - browser+ - follow_symlinktype: objectsnippets:properties:@@ -1616,14 +1616,14 @@ components:type: booleantype: objectrequired:- - completion- - display- - formatting- - keymap- - runtime- - save- - server- - package_management+ - completion+ - display+ - formatting+ - keymap+ - runtime+ - save+ - server+ - package_managementtype: objectMarimoExceptionRaisedError:properties:@@ -1636,12 +1636,12 @@ components:type: stringtype:enum:- - exception+ - exceptiontype: stringrequired:- - msg- - exception_type- - type+ - msg+ - exception_type+ - typetype: objectMarimoFile:properties:@@ -1659,8 +1659,8 @@ components:nullable: truetype: stringrequired:- - name- - path+ - name+ - pathtype: objectMarimoInternalError:properties:@@ -1670,21 +1670,21 @@ components:type: stringtype:enum:- - internal+ - internaltype: stringrequired:- - error_id- - type- - msg+ - error_id+ - type+ - msgtype: objectMarimoInterruptionError:properties:type:enum:- - interruption+ - interruptiontype: stringrequired:- - type+ - typetype: objectMarimoStrictExecutionError:properties:@@ -1697,12 +1697,12 @@ components:type: stringtype:enum:- - strict-exception+ - strict-exceptiontype: stringrequired:- - msg- - ref- - type+ - msg+ - ref+ - typetype: objectMarimoSyntaxError:properties:@@ -1710,65 +1710,65 @@ components:type: stringtype:enum:- - syntax+ - syntaxtype: stringrequired:- - msg- - type+ - msg+ - typetype: objectMessageOperation:oneOf:- - $ref: '#/components/schemas/CellOp'- - $ref: '#/components/schemas/FunctionCallResult'- - $ref: '#/components/schemas/SendUIElementMessage'- - $ref: '#/components/schemas/RemoveUIElements'- - $ref: '#/components/schemas/Reload'- - $ref: '#/components/schemas/Reconnected'- - $ref: '#/components/schemas/Interrupted'- - $ref: '#/components/schemas/CompletedRun'- - $ref: '#/components/schemas/KernelReady'- - $ref: '#/components/schemas/CompletionResult'- - $ref: '#/components/schemas/Alert'- - $ref: '#/components/schemas/Banner'- - $ref: '#/components/schemas/MissingPackageAlert'- - $ref: '#/components/schemas/InstallingPackageAlert'- - $ref: '#/components/schemas/Variables'- - $ref: '#/components/schemas/VariableValues'- - $ref: '#/components/schemas/QueryParamsSet'- - $ref: '#/components/schemas/QueryParamsAppend'- - $ref: '#/components/schemas/QueryParamsDelete'- - $ref: '#/components/schemas/QueryParamsClear'- - $ref: '#/components/schemas/Datasets'- - $ref: '#/components/schemas/DataColumnPreview'- - $ref: '#/components/schemas/SQLTablePreview'- - $ref: '#/components/schemas/SQLTableListPreview'- - $ref: '#/components/schemas/DataSourceConnections'- - $ref: '#/components/schemas/SecretKeysResult'- - $ref: '#/components/schemas/FocusCell'- - $ref: '#/components/schemas/UpdateCellCodes'- - $ref: '#/components/schemas/UpdateCellIdsRequest'+ - $ref: '#/components/schemas/CellOp'+ - $ref: '#/components/schemas/FunctionCallResult'+ - $ref: '#/components/schemas/SendUIElementMessage'+ - $ref: '#/components/schemas/RemoveUIElements'+ - $ref: '#/components/schemas/Reload'+ - $ref: '#/components/schemas/Reconnected'+ - $ref: '#/components/schemas/Interrupted'+ - $ref: '#/components/schemas/CompletedRun'+ - $ref: '#/components/schemas/KernelReady'+ - $ref: '#/components/schemas/CompletionResult'+ - $ref: '#/components/schemas/Alert'+ - $ref: '#/components/schemas/Banner'+ - $ref: '#/components/schemas/MissingPackageAlert'+ - $ref: '#/components/schemas/InstallingPackageAlert'+ - $ref: '#/components/schemas/Variables'+ - $ref: '#/components/schemas/VariableValues'+ - $ref: '#/components/schemas/QueryParamsSet'+ - $ref: '#/components/schemas/QueryParamsAppend'+ - $ref: '#/components/schemas/QueryParamsDelete'+ - $ref: '#/components/schemas/QueryParamsClear'+ - $ref: '#/components/schemas/Datasets'+ - $ref: '#/components/schemas/DataColumnPreview'+ - $ref: '#/components/schemas/SQLTablePreview'+ - $ref: '#/components/schemas/SQLTableListPreview'+ - $ref: '#/components/schemas/DataSourceConnections'+ - $ref: '#/components/schemas/SecretKeysResult'+ - $ref: '#/components/schemas/FocusCell'+ - $ref: '#/components/schemas/UpdateCellCodes'+ - $ref: '#/components/schemas/UpdateCellIdsRequest'MimeType:enum:- - application/json- - application/vnd.marimo+error- - application/vnd.marimo+traceback- - application/vnd.marimo+mimebundle- - application/vnd.vega.v5+json- - application/vnd.vegalite.v5+json- - image/png- - image/svg+xml- - image/tiff- - image/avif- - image/bmp- - image/gif- - image/jpeg- - video/mp4- - video/mpeg- - text/html- - text/plain- - text/markdown- - text/latex- - text/csv+ - application/json+ - application/vnd.marimo+error+ - application/vnd.marimo+traceback+ - application/vnd.marimo+mimebundle+ - application/vnd.vega.v5+json+ - application/vnd.vegalite.v5+json+ - image/png+ - image/svg+xml+ - image/tiff+ - image/avif+ - image/bmp+ - image/gif+ - image/jpeg+ - video/mp4+ - video/mpeg+ - text/html+ - text/plain+ - text/markdown+ - text/latex+ - text/csvtype: stringMissingPackageAlert:properties:@@ -1776,16 +1776,16 @@ components:type: booleanname:enum:- - missing-package-alert+ - missing-package-alerttype: stringpackages:items:type: stringtype: arrayrequired:- - packages- - isolated- - name+ - packages+ - isolated+ - nametype: objectMultipleDefinitionError:properties:@@ -1797,49 +1797,49 @@ components:type: stringtype:enum:- - multiple-defs+ - multiple-defstype: stringrequired:- - name- - cells- - type+ - name+ - cells+ - typetype: objectNonNestedLiteral:oneOf:- - type: integer- - type: number- - format: date- type: string- - format: time- type: string- - format: date-time- type: string- - format: duration- type: string- - type: string- - type: boolean- - format: byte- type: string+ - type: integer+ - type: number+ - format: date+ type: string+ - format: time+ type: string+ - format: date-time+ type: string+ - format: duration+ type: string+ - type: string+ - type: boolean+ - format: byte+ type: stringOpenTutorialRequest:properties:tutorialId:oneOf:- - enum:- - intro- - dataflow- - ui- - markdown- - plots- - sql- - layout- - fileformat- - for-jupyter-users- type: string- - enum:- - markdown-format- type: string+ - enum:+ - intro+ - dataflow+ - ui+ - markdown+ - plots+ - sql+ - layout+ - fileformat+ - for-jupyter-users+ type: string+ - enum:+ - markdown-format+ type: stringrequired:- - tutorialId+ - tutorialIdtype: objectPackageDescription:properties:@@ -1848,8 +1848,8 @@ components:version:type: stringrequired:- - name- - version+ - name+ - versiontype: objectPackageOperationResponse:properties:@@ -1859,7 +1859,7 @@ components:success:type: booleanrequired:- - success+ - successtype: objectPdbRequest:properties:@@ -1869,14 +1869,14 @@ components:$ref: '#/components/schemas/HTTPRequest'nullable: truerequired:- - cellId+ - cellIdtype: objectPreviewDataSourceConnectionRequest:properties:engine:type: stringrequired:- - engine+ - enginetype: objectPreviewDatasetColumnRequest:properties:@@ -1889,18 +1889,18 @@ components:type: stringsourceType:enum:- - local- - duckdb- - connection- - catalog+ - local+ - duckdb+ - connection+ - catalogtype: stringtableName:type: stringrequired:- - sourceType- - source- - tableName- - columnName+ - sourceType+ - source+ - tableName+ - columnNametype: objectPreviewSQLTableListRequest:properties:@@ -1913,10 +1913,10 @@ components:schema:type: stringrequired:- - requestId- - engine- - database- - schema+ - requestId+ - engine+ - database+ - schematype: objectPreviewSQLTableRequest:properties:@@ -1931,11 +1931,11 @@ components:tableName:type: stringrequired:- - requestId- - engine- - database- - schema- - tableName+ - requestId+ - engine+ - database+ - schema+ - tableNametype: objectQueryParamsAppend:properties:@@ -1943,23 +1943,23 @@ components:type: stringname:enum:- - query-params-append+ - query-params-appendtype: stringvalue:type: stringrequired:- - key- - value- - name+ - key+ - value+ - nametype: objectQueryParamsClear:properties:name:enum:- - query-params-clear+ - query-params-cleartype: stringrequired:- - name+ - nametype: objectQueryParamsDelete:properties:@@ -1967,14 +1967,14 @@ components:type: stringname:enum:- - query-params-delete+ - query-params-deletetype: stringvalue:nullable: truetype: stringrequired:- - key- - name+ - key+ - nametype: objectQueryParamsSet:properties:@@ -1982,25 +1982,25 @@ components:type: stringname:enum:- - query-params-set+ - query-params-settype: stringvalue:oneOf:- - type: string- - items:- type: string- type: array+ - type: string+ - items:+ type: string+ type: arrayrequired:- - key- - value- - name+ - key+ - value+ - nametype: objectReadCodeResponse:properties:contents:type: stringrequired:- - contents+ - contentstype: objectRecentFilesResponse:properties:@@ -2009,32 +2009,32 @@ components:$ref: '#/components/schemas/MarimoFile'type: arrayrequired:- - files+ - filestype: objectReconnected:properties:name:enum:- - reconnected+ - reconnectedtype: stringrequired:- - name+ - nametype: objectReload:properties:name:enum:- - reload+ - reloadtype: stringrequired:- - name+ - nametype: objectRemovePackageRequest:properties:package:type: stringrequired:- - package+ - packagetype: objectRemoveUIElements:properties:@@ -2042,25 +2042,25 @@ components:type: stringname:enum:- - remove-ui-elements+ - remove-ui-elementstype: stringrequired:- - cell_id- - name+ - cell_id+ - nametype: objectRenameFileRequest:properties:filename:type: stringrequired:- - filename+ - filenametype: objectRenameRequest:properties:filename:type: stringrequired:- - filename+ - filenametype: objectRunRequest:properties:@@ -2076,8 +2076,8 @@ components:$ref: '#/components/schemas/HTTPRequest'nullable: truerequired:- - cellIds- - codes+ - cellIds+ - codestype: objectRunningNotebooksResponse:properties:@@ -2086,14 +2086,14 @@ components:$ref: '#/components/schemas/MarimoFile'type: arrayrequired:- - files+ - filestype: objectRuntimeState:enum:- - idle- - queued- - running- - disabled-transitively+ - idle+ - queued+ - running+ - disabled-transitivelytype: stringSQLTableListPreview:properties:@@ -2102,7 +2102,7 @@ components:type: stringname:enum:- - sql-table-list-preview+ - sql-table-list-previewtype: stringrequest_id:type: string@@ -2111,9 +2111,9 @@ components:$ref: '#/components/schemas/DataTable'type: arrayrequired:- - request_id- - tables- - name+ - request_id+ - tables+ - nametype: objectSQLTablePreview:properties:@@ -2122,7 +2122,7 @@ components:type: stringname:enum:- - sql-table-preview+ - sql-table-previewtype: stringrequest_id:type: string@@ -2130,8 +2130,8 @@ components:$ref: '#/components/schemas/DataTable'nullable: truerequired:- - request_id- - name+ - request_id+ - nametype: objectSaveAppConfigurationRequest:properties:@@ -2139,7 +2139,7 @@ components:additionalProperties: {}type: objectrequired:- - config+ - configtype: objectSaveNotebookRequest:properties:@@ -2168,19 +2168,19 @@ components:persist:type: booleanrequired:- - cellIds- - codes- - names- - configs- - filename- - persist+ - cellIds+ - codes+ - names+ - configs+ - filename+ - persisttype: objectSaveUserConfigurationRequest:properties:config:$ref: '#/components/schemas/MarimoConfig'required:- - config+ - configtype: objectSchema:properties:@@ -2191,8 +2191,8 @@ components:$ref: '#/components/schemas/DataTable'type: arrayrequired:- - name- - tables+ - name+ - tablestype: objectSchemaColumn:properties:@@ -2204,9 +2204,9 @@ components:type:type: stringrequired:- - name- - type- - sampleValues+ - name+ - type+ - sampleValuestype: objectSchemaTable:properties:@@ -2217,14 +2217,14 @@ components:name:type: stringrequired:- - name- - columns+ - name+ - columnstype: objectSecretKeysResult:properties:name:enum:- - secret-keys-result+ - secret-keys-resulttype: stringrequest_id:type: string@@ -2233,9 +2233,9 @@ components:$ref: '#/components/schemas/SecretKeysWithProvider'type: arrayrequired:- - request_id- - secrets- - name+ - request_id+ - secrets+ - nametype: objectSecretKeysWithProvider:properties:@@ -2247,13 +2247,13 @@ components:type: stringprovider:enum:- - env- - dotenv+ - env+ - dotenvtype: stringrequired:- - provider- - name- - keys+ - provider+ - name+ - keystype: objectSendUIElementMessage:properties:@@ -2270,14 +2270,14 @@ components:type: stringname:enum:- - send-ui-element-message+ - send-ui-element-messagetype: stringui_element:nullable: truetype: stringrequired:- - message- - name+ - message+ - nametype: objectSetCellConfigRequest:properties:@@ -2287,7 +2287,7 @@ components:type: objecttype: objectrequired:- - configs+ - configstype: objectSetModelMessageRequest:properties:@@ -2302,22 +2302,22 @@ components:items:items:oneOf:- - type: string- - type: integer+ - type: string+ - type: integertype: arraytype: arraystate:additionalProperties: {}type: objectrequired:- - state- - bufferPaths+ - state+ - bufferPathstype: objectmodelId:type: stringrequired:- - modelId- - message+ - modelId+ - messagetype: objectSetUIElementValueRequest:properties:@@ -2334,43 +2334,43 @@ components:items: {}type: arrayrequired:- - objectIds- - values- - token+ - objectIds+ - values+ - tokentype: objectSetUserConfigRequest:properties:config:$ref: '#/components/schemas/MarimoConfig'required:- - config+ - configtype: objectSetupRootError:properties:edges_with_vars:items:prefixItems:- - type: string- - items:- type: string- type: array- - type: string+ - type: string+ - items:+ type: string+ type: array+ - type: stringtype: arraytype: arraytype:enum:- - setup-refs+ - setup-refstype: stringrequired:- - edges_with_vars- - type+ - edges_with_vars+ - typetype: objectShutdownSessionRequest:properties:sessionId:type: stringrequired:- - sessionId+ - sessionIdtype: objectSnippet:properties:@@ -2381,8 +2381,8 @@ components:title:type: stringrequired:- - title- - sections+ - title+ - sectionstype: objectSnippetSection:properties:@@ -2395,7 +2395,7 @@ components:id:type: stringrequired:- - id+ - idtype: objectSnippets:properties:@@ -2404,14 +2404,14 @@ components:$ref: '#/components/schemas/Snippet'type: arrayrequired:- - snippets+ - snippetstype: objectStdinRequest:properties:text:type: stringrequired:- - text+ - texttype: objectStopRequest:properties: {}@@ -2421,7 +2421,7 @@ components:success:type: booleanrequired:- - success+ - successtype: objectUnknownError:properties:@@ -2429,11 +2429,11 @@ components:type: stringtype:enum:- - unknown+ - unknowntype: stringrequired:- - msg- - type+ - msg+ - typetype: objectUpdateCellCodes:properties:@@ -2449,13 +2449,13 @@ components:type: arrayname:enum:- - update-cell-codes+ - update-cell-codestype: stringrequired:- - cell_ids- - codes- - code_is_stale- - name+ - cell_ids+ - codes+ - code_is_stale+ - nametype: objectUpdateCellIdsRequest:properties:@@ -2465,11 +2465,11 @@ components:type: arrayname:enum:- - update-cell-ids+ - update-cell-idstype: stringrequired:- - cell_ids- - name+ - cell_ids+ - nametype: objectUpdateComponentValuesRequest:properties:@@ -2481,8 +2481,8 @@ components:items: {}type: arrayrequired:- - objectIds- - values+ - objectIds+ - valuestype: objectVariableContext:properties:@@ -2492,9 +2492,9 @@ components:valueType:type: stringrequired:- - name- - valueType- - previewValue+ - name+ - valueType+ - previewValuetype: objectVariableDeclaration:properties:@@ -2509,9 +2509,9 @@ components:type: stringtype: arrayrequired:- - name- - declared_by- - used_by+ - name+ - declared_by+ - used_bytype: objectVariableValue:properties:@@ -2524,42 +2524,42 @@ components:nullable: truetype: stringrequired:- - name+ - nametype: objectVariableValues:properties:name:enum:- - variable-values+ - variable-valuestype: stringvariables:items:$ref: '#/components/schemas/VariableValue'type: arrayrequired:- - variables- - name+ - variables+ - nametype: objectVariables:properties:name:enum:- - variables+ - variablestype: stringvariables:items:$ref: '#/components/schemas/VariableDeclaration'type: arrayrequired:- - variables- - name+ - variables+ - nametype: objectWorkspaceFilesRequest:properties:includeMarkdown:type: booleanrequired:- - includeMarkdown+ - includeMarkdowntype: objectWorkspaceFilesResponse:properties:@@ -2570,23 +2570,23 @@ components:root:type: stringrequired:- - root- - files+ - root+ - filestype: objectinfo:title: marimo API- version: 0.13.12+ version: 0.13.15openapi: 3.1.0paths:/@file/{filename_and_length}:get:parameters:- - description: The filename and byte length of the virtual file- in: path- name: filename_and_length- required: true- schema:- type: string+ - description: The filename and byte length of the virtual file+ in: path+ name: filename_and_length+ required: true+ schema:+ type: stringresponses:200:content:@@ -3406,7 +3406,7 @@ paths:percent:type: numberrequired:- - percent+ - percenttype: objectgpu:items:@@ -3424,17 +3424,17 @@ paths:used:type: integerrequired:- - total- - used- - free- - percent+ - total+ - used+ - free+ - percenttype: objectname:type: stringrequired:- - index- - memory- - name+ - index+ - memory+ - nametype: objecttype: arraykernel:@@ -3455,22 +3455,22 @@ paths:used:type: integerrequired:- - total- - available- - percent- - used- - free+ - total+ - available+ - percent+ - used+ - freetype: objectserver:properties:memory:type: integerrequired:- - memory+ - memorytype: objectrequired:- - memory- - cpu+ - memory+ - cputype: objectdescription: Get the current memory and CPU usage of the application/api/version:@@ -3508,4 +3508,5 @@ paths:type: stringsummary: Submit login formtags:- - auth+ - auth+diff --git a/openapi/package.json b/openapi/package.jsonindex e6809d7b74..c30cf4a326 100644--- a/openapi/package.json+++ b/openapi/package.json@@ -10,7 +10,10 @@"src"],"scripts": {- "codegen": "npx openapi-typescript ./api.yaml -o ./src/api.ts"+ "codegen": "pnpm run \"/^codegen:.*/\"",+ "codegen:api": "npx openapi-typescript ./api.yaml -o ./src/api.ts",+ "codegen:session": "npx openapi-typescript ../marimo/_schemas/generated/session.yaml -o ./src/session.ts",+ "codegen:notebook": "npx openapi-typescript ../marimo/_schemas/generated/notebook.yaml -o ./src/notebook.ts"},"devDependencies": {"openapi-typescript": "^7.3.0",diff --git a/openapi/src/index.ts b/openapi/src/index.tsindex 9d04d55d57..dad853e52f 100644--- a/openapi/src/index.ts+++ b/openapi/src/index.ts@@ -1,8 +1,13 @@export type * from "./api";+import type { components as session } from "./session";+import type { components as notebook } from "./notebook";import createClient, { type ClientOptions } from "openapi-fetch";import type { paths } from "./api";+export type Session = session["schemas"];+export type Notebook = notebook["schemas"];+export function createMarimoClient(opts: ClientOptions) {return createClient<paths>(opts);}diff --git a/openapi/src/notebook.ts b/openapi/src/notebook.tsnew file mode 100644index 0000000000..3af874562a--- /dev/null+++ b/openapi/src/notebook.ts@@ -0,0 +1,41 @@+/**+ * This file was auto-generated by openapi-typescript.+ * Do not make direct changes to the file.+ */++export type paths = Record<string, never>;+export type webhooks = Record<string, never>;+export interface components {+ schemas: {+ NotebookCell: {+ code: string | null;+ config: {+ column: number | null;+ disabled: boolean | null;+ hide_code: boolean | null;+ };+ id: string;+ name: string | null;+ };+ NotebookCellConfig: {+ column: number | null;+ disabled: boolean | null;+ hide_code: boolean | null;+ };+ NotebookMetadata: {+ marimo_version: string | null;+ };+ NotebookV1: {+ cells: components["schemas"]["NotebookCell"][];+ metadata: components["schemas"]["NotebookMetadata"];+ version: string;+ };+ };+ responses: never;+ parameters: never;+ requestBodies: never;+ headers: never;+ pathItems: never;+}+export type $defs = Record<string, never>;+export type operations = Record<string, never>;diff --git a/openapi/src/session.ts b/openapi/src/session.tsnew file mode 100644index 0000000000..9f2b585353--- /dev/null+++ b/openapi/src/session.ts@@ -0,0 +1,61 @@+/**+ * This file was auto-generated by openapi-typescript.+ * Do not make direct changes to the file.+ */++export type paths = Record<string, never>;+export type webhooks = Record<string, never>;+export interface components {+ schemas: {+ Cell: {+ code_hash: string | null;+ console: components["schemas"]["StreamOutput"][];+ id: string;+ outputs: (+ | components["schemas"]["ErrorOutput"]+ | components["schemas"]["DataOutput"]+ )[];+ };+ DataOutput: {+ data: {+ [key: string]: unknown;+ };+ /** @enum {string} */+ type: "data";+ };+ ErrorOutput: {+ ename: string;+ evalue: string;+ traceback: string[];+ /** @enum {string} */+ type: "error";+ };+ NotebookSessionMetadata: {+ marimo_version: string | null;+ };+ NotebookSessionV1: {+ cells: components["schemas"]["Cell"][];+ metadata: components["schemas"]["NotebookSessionMetadata"];+ version: string;+ };+ StreamOutput: {+ /** @enum {string} */+ name: "stdout" | "stderr";+ text: string;+ /** @enum {string} */+ type: "stream";+ };+ TimeMetadata: {+ completed: string | null;+ duration: number | null;+ started: string | null;+ };+ };+ responses: never;+ parameters: never;+ requestBodies: never;+ headers: never;+ pathItems: never;+}+export type $defs = Record<string, never>;+export type operations = Record<string, never>;diff --git a/scripts/generate.py b/scripts/generate.pyindex dc68acf6f2..28959d1323 100644--- a/scripts/generate.py+++ b/scripts/generate.py@@ -19,7 +19,7 @@ def _():ErrorOutput,DataOutput,Cell,- NotebookMetadata,+ NotebookSessionMetadata,NotebookSessionV1,)@@ -29,7 +29,7 @@ def _():ErrorOutput,DataOutput,Cell,- NotebookMetadata,+ NotebookSessionMetadata,NotebookSessionV1,]return (@@ -37,7 +37,7 @@ def _():DataOutput,ErrorOutput,MESSAGES,- NotebookMetadata,+ NotebookSessionMetadata,NotebookSessionV1,StreamOutput,TimeMetadata,diff --git a/scripts/generate_schemas.py b/scripts/generate_schemas.pyindex 92d490baa8..bb25311f93 100755--- a/scripts/generate_schemas.py+++ b/scripts/generate_schemas.py@@ -2,123 +2,116 @@import marimo-__generated_with = "0.11.5"+__generated_with = "0.13.15"app = marimo.App(width="medium")+with app.setup:+ import marimo as mo+ import marimo._schemas.session as s++ import marimo._schemas.notebook as n+ import typing as t++ SESSION_MESSAGES = [+ # Session+ s.TimeMetadata,+ s.StreamOutput,+ s.ErrorOutput,+ s.DataOutput,+ s.Cell,+ s.NotebookSessionMetadata,+ s.NotebookSessionV1,+ ]+ NOTEBOOK_MESSAGES = [+ # Notebook+ n.NotebookCell,+ n.NotebookCellConfig,+ n.NotebookMetadata,+ n.NotebookV1,+ ]+@app.cell(hide_code=True)-def _(mo):- mo.md(r"""This marimo notebook generates the OpenAPI schema for the `TypeDict`s defined in `marimo._schemas.session`""")+def _():+ mo.md(+ r"""This marimo notebook generates the OpenAPI schema for the `TypeDict`s defined in `marimo._schemas`"""+ )return[email protected](hide_code=True)def _():- return+ generate_schema_button = mo.ui.run_button(label="Write schema")+ generate_schema_button+ return (generate_schema_button,)-def _():- from marimo._schemas.session import (- TimeMetadata,- StreamOutput,- ErrorOutput,- DataOutput,- Cell,- NotebookMetadata,- NotebookSessionV1,- )+def generate_schema(name: str):+ import yaml- MESSAGES = [- TimeMetadata,- StreamOutput,- ErrorOutput,- DataOutput,- Cell,- NotebookMetadata,- NotebookSessionV1,- ]- return (- Cell,- DataOutput,- ErrorOutput,- MESSAGES,- NotebookMetadata,- NotebookSessionV1,- StreamOutput,- TimeMetadata,+ assert name == "session" or name == "notebook", (+ "Invalid schema name must be 'session' or 'notebook'")+ header = f"# This file is generated by scripts/generate_schemas.py\n"[email protected](hide_code=True)-def _(mo):- generate_schema = mo.ui.run_button(label="Write schema")- generate_schema- return (generate_schema,)-+ print(f"Writing schema to marimo/_schemas/generated/{name}.yaml")+ messages = SESSION_MESSAGES if name == "session" else NOTEBOOK_MESSAGES+ return header + yaml.dump(build_openapi_schema(messages))-def _(build_openapi_schema, generate_schema, mo):- import yaml- header = f"# This file is generated by scripts/generate_schemas.py\n"+def write_schema(name: str):+ output = (+ mo.notebook_dir().parent+ / "marimo"+ / "_schemas"+ / "generated"+ / f"{name}.yaml"+ )+ output.write_text(generate_schema(name), encoding="utf-8")- if generate_schema.value:- print("Writing schema to marimo/_schemas/generated/session.yaml")- output = (- mo.notebook_dir().parent- / "marimo"- / "_schemas"- / "generated"- / "session.yaml"- )- output.write_text(header + yaml.dump(build_openapi_schema()))- if mo.app_meta().mode == "script":- print(header + yaml.dump(build_openapi_schema()))- return header, output, yaml+def _(generate_schema_button):+ if mo.app_meta().mode == "script" or generate_schema_button.value:+ write_schema("session")+ write_schema("notebook")+ return[email protected](hide_code=True)-def _(Any, Dict, MESSAGES):[email protected](hide_code=True)+def build_openapi_schema(messages):from marimo._server.api.router import build_routesfrom marimo._utils.dataclass_to_openapi import (PythonTypeToOpenAPI,)+ processed_classes: dict[t.Any, str] = {}+ component_schemas: dict[str, t.Any] = {}+ name_overrides: dict[t.Any, str] = {}- def build_openapi_schema():- processed_classes: Dict[Any, str] = {}- component_schemas: Dict[str, Any] = {}- name_overrides: Dict[Any, str] = {}-- converter = PythonTypeToOpenAPI(- camel_case=False, name_overrides=name_overrides- )- for cls in MESSAGES:- if cls in processed_classes:- del processed_classes[cls]- name = name_overrides.get(cls, cls.__name__) # type: ignore[attr-defined]- component_schemas[name] = converter.convert(cls, processed_classes)- processed_classes[cls] = name-- schemas = {- "openapi": "3.0.0",- "info": {"title": "marimo_session"},- "components": {- "schemas": {- **component_schemas,- }- },- }- return schemas- return PythonTypeToOpenAPI, build_openapi_schema, build_routes---def _():- import marimo as mo- return (mo,)+ converter = PythonTypeToOpenAPI(+ camel_case=False, name_overrides=name_overrides+ )+ for cls in messages:+ if cls in processed_classes:+ del processed_classes[cls]+ name = name_overrides.get(cls, cls.__name__) # type: ignore[attr-defined]+ component_schemas[name] = converter.convert(cls, processed_classes)+ processed_classes[cls] = name++ schemas = {+ "openapi": "3.0.0",+ "info": {"title": "marimo_session"},+ "components": {+ "schemas": {+ **component_schemas,+ }+ },+ }+ return schemasif __name__ == "__main__":diff --git a/tests/_ast/test_cell_manager.py b/tests/_ast/test_cell_manager.pyindex bca85742d7..08c57e62f9 100644--- a/tests/_ast/test_cell_manager.py+++ b/tests/_ast/test_cell_manager.py@@ -6,6 +6,23 @@ from marimo._ast.cell import Cell, CellConfigfrom marimo._ast.cell_manager import CellManager, _match_cell_ids_by_similarityfrom marimo._ast.compiler import compile_cellfrom marimo._ast.names import DEFAULT_CELL_NAME+from marimo._types.ids import CellId_t++# Test cell ID constants+CELL_A = CellId_t("a")+CELL_B = CellId_t("b")+CELL_C = CellId_t("c")+CELL_X = CellId_t("x")+CELL_Y = CellId_t("y")+CELL_Z = CellId_t("z")+CELL_P = CellId_t("p")+CELL_Q = CellId_t("q")+CELL_R = CellId_t("r")+TEST_CELL1 = CellId_t("test_cell1")+TEST_CELL2 = CellId_t("test_cell2")+UNUSED_A = CellId_t("unused_a")+UNUSED_B = CellId_t("unused_b")+UNUSED_C = CellId_t("unused_c")@pytest.fixture@@ -24,7 +41,7 @@ def test_create_cell_id(cell_manager: CellManager) -> None:def test_register_cell(cell_manager: CellManager) -> None:- cell_id = "test_cell"+ cell_id = CellId_t("test_cell")code = "print('hello')"config = CellConfig()@@ -69,37 +86,57 @@ def test_ensure_one_cell(cell_manager: CellManager) -> None:def test_cell_queries(cell_manager: CellManager) -> None:- cell_id1 = "test_cell1"- cell_id2 = "test_cell2"code1 = "print('hello')"code2 = "print('world')"config1 = CellConfig(column=1)config2 = CellConfig(disabled=True)- cell_manager.register_cell(cell_id1, code1, config1, name="cell1")- cell_manager.register_cell(cell_id2, code2, config2, name="cell2")+ cell_manager.register_cell(TEST_CELL1, code1, config1, name="cell1")+ cell_manager.register_cell(TEST_CELL2, code2, config2, name="cell2")assert list(cell_manager.names()) == ["cell1", "cell2"]assert list(cell_manager.codes()) == [code1, code2]assert list(cell_manager.configs()) == [config1, config2]- assert list(cell_manager.cell_ids()) == [cell_id1, cell_id2]- assert cell_manager.config_map() == {cell_id1: config1, cell_id2: config2}+ assert list(cell_manager.cell_ids()) == [TEST_CELL1, TEST_CELL2]+ assert cell_manager.config_map() == {+ TEST_CELL1: config1,+ TEST_CELL2: config2,+ }def test_get_cell_id_by_code(cell_manager: CellManager) -> None:code = "print('unique')"- cell_manager.register_cell("test_cell1", code, CellConfig())- cell_manager.register_cell("test_cell2", "different_code", CellConfig())+ cell_manager.register_cell(TEST_CELL1, code, CellConfig())+ cell_manager.register_cell(TEST_CELL2, "different_code", CellConfig())- assert cell_manager.get_cell_id_by_code(code) == "test_cell1"+ assert cell_manager.get_cell_id_by_code(code) == TEST_CELL1assert cell_manager.get_cell_id_by_code("nonexistent") is Nonedef test_get_cell_code(cell_manager: CellManager) -> None:code = "print('hello')"- cell_manager.register_cell("test_cell1", code, CellConfig())- assert cell_manager.get_cell_code("test_cell1") == code- assert cell_manager.get_cell_code("nonexistent") is None+ cell_manager.register_cell(TEST_CELL1, code, CellConfig())+ assert cell_manager.get_cell_code(TEST_CELL1) == code+ assert cell_manager.get_cell_code(CellId_t("nonexistent")) is None+++def test_get_cell_data(cell_manager: CellManager) -> None:+ code = "print('hello')"+ config = CellConfig(column=1, disabled=True)+ name = "test_cell"++ cell_manager.register_cell(TEST_CELL1, code, config, name=name)++ # Test getting existing cell data+ cell_data = cell_manager.get_cell_data(TEST_CELL1)+ assert cell_data is not None+ assert cell_data.cell_id == TEST_CELL1+ assert cell_data.code == code+ assert cell_data.config == config+ assert cell_data.name == name++ # Test getting non-existent cell data+ assert cell_manager.get_cell_data(CellId_t("nonexistent")) is Nonedef test_register_unparsable_cell(cell_manager: CellManager) -> None:@@ -123,73 +160,73 @@ def test_register_unparsable_cell(cell_manager: CellManager) -> None:def test_valid_cells(cell_manager: CellManager) -> None:# Register a mix of valid and invalid cells- cell1 = Cell(_name="_", _cell=compile_cell("print('valid')", "test_cell1"))+ cell1 = Cell(_name="_", _cell=compile_cell("print('valid')", TEST_CELL1))cell_manager.register_cell(- "test_cell1", "print('valid')", CellConfig(), cell=cell1+ TEST_CELL1, "print('valid')", CellConfig(), cell=cell1)cell_manager.register_cell(- "test_cell2", "print('invalid')", CellConfig(), cell=None+ TEST_CELL2, "print('invalid')", CellConfig(), cell=None)valid_cells = list(cell_manager.valid_cells())assert len(valid_cells) == 1- assert valid_cells[0][0] == "test_cell1"+ assert valid_cells[0][0] == TEST_CELL1assert valid_cells[0][1] == cell1valid_ids = list(cell_manager.valid_cell_ids())- assert valid_ids == ["test_cell1"]+ assert valid_ids == [TEST_CELL1]def test_match_cell_ids_by_similarity():# Test exact matchesassert _match_cell_ids_by_similarity(- prev_ids=["a", "b", "c"],+ prev_ids=[CELL_A, CELL_B, CELL_C],prev_codes=["abc", "def", "ghi"],- next_ids=["unused_a", "unused_b", "unused_c"],+ next_ids=[UNUSED_A, UNUSED_B, UNUSED_C],next_codes=["abc", "def", "ghi"],- ) == ["a", "b", "c"]+ ) == [CELL_A, CELL_B, CELL_C]# Test with reordered codesassert _match_cell_ids_by_similarity(- prev_ids=["a", "b", "c"],+ prev_ids=[CELL_A, CELL_B, CELL_C],prev_codes=["abc", "def", "ghi"],- next_ids=["unused_a", "unused_b", "unused_c"],+ next_ids=[UNUSED_A, UNUSED_B, UNUSED_C],next_codes=["def", "ghi", "abc"],- ) == ["b", "c", "a"]+ ) == [CELL_B, CELL_C, CELL_A]# Test with similar but not exact matchesassert _match_cell_ids_by_similarity(- prev_ids=["a", "b", "c"],+ prev_ids=[CELL_A, CELL_B, CELL_C],prev_codes=["abc", "def", "ghi"],- next_ids=["unused_a", "unused_b", "unused_c"],+ next_ids=[UNUSED_A, UNUSED_B, UNUSED_C],next_codes=["ghij", "abcd", "defg"],- ) == ["c", "a", "b"]+ ) == [CELL_C, CELL_A, CELL_B]# Test with fewer next cellsresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b", "c"],+ prev_ids=[CELL_A, CELL_B, CELL_C],prev_codes=["abc", "def", "ghi"],- next_ids=["unused_a", "unused_b"],+ next_ids=[UNUSED_A, UNUSED_B],next_codes=["abc", "ghi"],)assert len(result) == 2- assert result == ["a", "c"]+ assert result == [CELL_A, CELL_C]# Test with more next cellsresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=["abc", "def"],- next_ids=["a", "b", "c"],+ next_ids=[CELL_A, CELL_B, CELL_C],next_codes=["def", "ghi", "abc"],)assert len(result) == 3- assert result == ["b", "c", "a"]+ assert result == [CELL_B, CELL_C, CELL_A]# Test with completely different codesresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=["abc", "def"],- next_ids=["unused_a", "unused_b"],+ next_ids=[UNUSED_A, UNUSED_B],next_codes=["xyz", "123"],)assert len(result) == 2@@ -199,211 +236,215 @@ def test_match_cell_ids_by_similarity():# Test with empty stringsassert _match_cell_ids_by_similarity(- prev_ids=["a"],+ prev_ids=[CELL_A],prev_codes=[""],- next_ids=["unused_a"],+ next_ids=[UNUSED_A],next_codes=[""],- ) == ["a"]+ ) == [CELL_A]def test_match_cell_ids_by_similarity_edge_cases():# Test with multiple identical codes in prevresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b", "c"],+ prev_ids=[CELL_A, CELL_B, CELL_C],prev_codes=["same", "same", "diff"],- next_ids=["x", "y"],+ next_ids=[CELL_X, CELL_Y],next_codes=["same", "diff"],)assert len(result) == 2- assert result[0] in ["a", "b"]- assert result[1] == "c"+ assert result[0] in [CELL_A, CELL_B]+ assert result[1] == CELL_C# Test with multiple identical codes in nextresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=["code1", "code2"],- next_ids=["x", "y", "z"],+ next_ids=[CELL_X, CELL_Y, CELL_Z],next_codes=["code1", "code1", "code2"],)assert len(result) == 3- assert result == ["a", "x", "b"]+ assert result == [CELL_A, CELL_X, CELL_B]# Test with very long common prefixes/suffixeslong_prefix = "x" * 1000result = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=[long_prefix + "1", long_prefix + "2"],- next_ids=["x", "y"],+ next_ids=[CELL_X, CELL_Y],next_codes=[long_prefix + "2", long_prefix + "1"],)- assert result == ["b", "a"]+ assert result == [CELL_B, CELL_A]# Test with Unicode and special charactersresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b", "c"],+ prev_ids=[CELL_A, CELL_B, CELL_C],prev_codes=["🔥", "∑∫", "\n\t\r"],- next_ids=["x", "y", "z"],+ next_ids=[CELL_X, CELL_Y, CELL_Z],next_codes=["∑∫", "🔥", "\n\t\r"],)- assert result == ["b", "a", "c"]+ assert result == [CELL_B, CELL_A, CELL_C]# Test with mixed case sensitivityresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=["ABC", "def"],- next_ids=["x", "y"],+ next_ids=[CELL_X, CELL_Y],next_codes=["abc", "DEF"],)assert len(result) == 2# Test with whitespace variationsresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=["x y", "a\nb"],- next_ids=["x", "y"],+ next_ids=[CELL_X, CELL_Y],next_codes=["x y", "a b"],)- assert result == ["a", "b"]+ assert result == [CELL_A, CELL_B]# Test with all codes being substrings of each otherresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b", "c"],+ prev_ids=[CELL_A, CELL_B, CELL_C],prev_codes=["x", "xy", "xyz"],- next_ids=["p", "q", "r"],+ next_ids=[CELL_P, CELL_Q, CELL_R],next_codes=["xyz", "xy", "x"],)- assert result == ["c", "b", "a"]+ assert result == [CELL_C, CELL_B, CELL_A]# Test with maximum length differencesresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=["x", "x" * 10000],- next_ids=["y", "z"],+ next_ids=[CELL_Y, CELL_Z],next_codes=["x" * 10000, "x"],)- assert result == ["b", "a"]+ assert result == [CELL_B, CELL_A]# Test with empty stringsresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=["", "x"],- next_ids=["y", "z"],+ next_ids=[CELL_Y, CELL_Z],next_codes=["x", ""],)- assert result == ["b", "a"]+ assert result == [CELL_B, CELL_A]# Test with identical codesresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b", "c"],+ prev_ids=[CELL_A, CELL_B, CELL_C],prev_codes=["same", "same", "same"],- next_ids=["x", "y", "z"],+ next_ids=[CELL_X, CELL_Y, CELL_Z],next_codes=["same", "same", "same"],)assert len(result) == 3- assert set(result) == {"a", "b", "c"}+ assert set(result) == {CELL_A, CELL_B, CELL_C}# Test with completely different codesresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=["abc", "def"],- next_ids=["x", "y"],+ next_ids=[CELL_X, CELL_Y],next_codes=["123", "456"],)assert len(result) == 2# This is probably ok since they are completely different.# Not sure what the best behavior is.- assert result == ["b", "x"]+ assert result == [CELL_B, CELL_X]# Test with special Python syntaxresult = _match_cell_ids_by_similarity(- prev_ids=["a", "b"],+ prev_ids=[CELL_A, CELL_B],prev_codes=["def foo():", "class Bar:"],- next_ids=["x", "y"],+ next_ids=[CELL_X, CELL_Y],next_codes=["class Bar:", "def foo():"],)- assert result == ["b", "a"]+ assert result == [CELL_B, CELL_A]def test_sort_cell_ids_by_similarity_reorder():# Test simple reorderprev_manager = CellManager()- prev_manager.register_cell("a", "code1", CellConfig())- prev_manager.register_cell("b", "code2", CellConfig())+ prev_manager.register_cell(CELL_A, "code1", CellConfig())+ prev_manager.register_cell(CELL_B, "code2", CellConfig())curr_manager = CellManager()- curr_manager.register_cell("x", "code2", CellConfig())- curr_manager.register_cell("y", "code1", CellConfig())+ curr_manager.register_cell(CELL_X, "code2", CellConfig())+ curr_manager.register_cell(CELL_Y, "code1", CellConfig())# Save original seen_idsoriginal_seen_ids = curr_manager.seen_ids.copy()curr_manager.sort_cell_ids_by_similarity(prev_manager)- assert list(curr_manager.cell_ids()) == ["b", "a"]- assert curr_manager.cell_data_at("b").code == "code2"- assert curr_manager.cell_data_at("a").code == "code1"+ assert list(curr_manager.cell_ids()) == [CELL_B, CELL_A]+ assert curr_manager.cell_data_at(CELL_B).code == "code2"+ assert curr_manager.cell_data_at(CELL_A).code == "code1"# Check seen_ids were updated- assert curr_manager.seen_ids == original_seen_ids | {"a", "b"}+ assert curr_manager.seen_ids == original_seen_ids | {CELL_A, CELL_B}def test_sort_cell_ids_by_similarity_reorder_same_ids():# Test simple reorderprev_manager = CellManager()- prev_manager.register_cell("a", "code1", CellConfig())- prev_manager.register_cell("b", "code2", CellConfig())+ prev_manager.register_cell(CELL_A, "code1", CellConfig())+ prev_manager.register_cell(CELL_B, "code2", CellConfig())curr_manager = CellManager()- curr_manager.register_cell("a", "code2", CellConfig())- curr_manager.register_cell("b", "code1", CellConfig())+ curr_manager.register_cell(CELL_A, "code2", CellConfig())+ curr_manager.register_cell(CELL_B, "code1", CellConfig())# Save original seen_idsoriginal_seen_ids = curr_manager.seen_ids.copy()curr_manager.sort_cell_ids_by_similarity(prev_manager)- assert list(curr_manager.cell_ids()) == ["b", "a"]- assert curr_manager.cell_data_at("b").code == "code2"- assert curr_manager.cell_data_at("a").code == "code1"+ assert list(curr_manager.cell_ids()) == [CELL_B, CELL_A]+ assert curr_manager.cell_data_at(CELL_B).code == "code2"+ assert curr_manager.cell_data_at(CELL_A).code == "code1"# Check seen_ids were updated- assert curr_manager.seen_ids == original_seen_ids | {"a", "b"}+ assert curr_manager.seen_ids == original_seen_ids | {CELL_A, CELL_B}def test_sort_cell_ids_by_similarity_less_cells():# Test less cells than beforeprev_manager = CellManager()- prev_manager.register_cell("a", "code1", CellConfig())- prev_manager.register_cell("b", "code2", CellConfig())- prev_manager.register_cell("c", "code3", CellConfig())+ prev_manager.register_cell(CELL_A, "code1", CellConfig())+ prev_manager.register_cell(CELL_B, "code2", CellConfig())+ prev_manager.register_cell(CELL_C, "code3", CellConfig())curr_manager = CellManager()- curr_manager.register_cell("x", "code2", CellConfig())- curr_manager.register_cell("y", "code1", CellConfig())+ curr_manager.register_cell(CELL_X, "code2", CellConfig())+ curr_manager.register_cell(CELL_Y, "code1", CellConfig())original_seen_ids = curr_manager.seen_ids.copy()curr_manager.sort_cell_ids_by_similarity(prev_manager)- assert list(curr_manager.cell_ids()) == ["b", "a"]- assert curr_manager.seen_ids == original_seen_ids | {"a", "b"}- assert curr_manager.cell_data_at("b").code == "code2"- assert curr_manager.cell_data_at("a").code == "code1"+ assert list(curr_manager.cell_ids()) == [CELL_B, CELL_A]+ assert curr_manager.seen_ids == original_seen_ids | {CELL_A, CELL_B}+ assert curr_manager.cell_data_at(CELL_B).code == "code2"+ assert curr_manager.cell_data_at(CELL_A).code == "code1"def test_sort_cell_ids_by_similarity_more_cells():# Test more cells than beforeprev_manager = CellManager()- prev_manager.register_cell("a", "code1", CellConfig())- prev_manager.register_cell("b", "code2", CellConfig())+ prev_manager.register_cell(CELL_A, "code1", CellConfig())+ prev_manager.register_cell(CELL_B, "code2", CellConfig())curr_manager = CellManager()- curr_manager.register_cell("x", "code2", CellConfig())- curr_manager.register_cell("y", "code1", CellConfig())- curr_manager.register_cell("z", "code3", CellConfig())+ curr_manager.register_cell(CELL_X, "code2", CellConfig())+ curr_manager.register_cell(CELL_Y, "code1", CellConfig())+ curr_manager.register_cell(CELL_Z, "code3", CellConfig())original_seen_ids = curr_manager.seen_ids.copy()curr_manager.sort_cell_ids_by_similarity(prev_manager)- assert list(curr_manager.cell_ids()) == ["b", "a", "x"]- assert curr_manager.seen_ids == original_seen_ids | {"a", "b", "x"}- assert curr_manager.cell_data_at("b").code == "code2"- assert curr_manager.cell_data_at("a").code == "code1"- assert curr_manager.cell_data_at("x").code == "code3"+ assert list(curr_manager.cell_ids()) == [CELL_B, CELL_A, CELL_X]+ assert curr_manager.seen_ids == original_seen_ids | {+ CELL_A,+ CELL_B,+ CELL_X,+ }+ assert curr_manager.cell_data_at(CELL_B).code == "code2"+ assert curr_manager.cell_data_at(CELL_A).code == "code1"+ assert curr_manager.cell_data_at(CELL_X).code == "code3"diff --git a/tests/_schemas/test_schema.py b/tests/_schemas/test_schema.pyindex ae12ee2293..4e2a057fd3 100644--- a/tests/_schemas/test_schema.py+++ b/tests/_schemas/test_schema.py@@ -1,6 +1,5 @@from __future__ import annotations-import subprocessimport sysfrom pathlib import Path@@ -13,16 +12,25 @@ import yamlreason="This test is flaky on Windows",)def test_session_schema_up_to_date() -> None:- with open("marimo/_schemas/generated/session.yaml") as f:- current_content = yaml.safe_load(f)-- script_path = (- Path(__file__).parent.parent.parent / "scripts" / "generate_schemas.py"+ current_session_schema = yaml.safe_load(+ Path("marimo/_schemas/generated/session.yaml").read_text()+ )+ current_notebook_schema = yaml.safe_load(+ Path("marimo/_schemas/generated/notebook.yaml").read_text())- result = subprocess.run([script_path], capture_output=True, text=True)- generated_content = yaml.safe_load(result.stdout)- cmd = "marimo edit scripts/generate_schemas.py"- assert current_content == generated_content, (+ import sys++ sys.path.append(str(Path(__file__).parent.parent.parent))+ from scripts.generate_schemas import generate_schema++ generated_session_schema = yaml.safe_load(generate_schema("session"))+ generated_notebook_schema = yaml.safe_load(generate_schema("notebook"))+ cmd = "python scripts/generate_schemas.py"++ assert current_session_schema == generated_session_schema, (f"session.yaml is not up to date. Run '{cmd}' and press 'Write schema' to update.")+ assert current_notebook_schema == generated_notebook_schema, (+ f"notebook.yaml is not up to date. Run '{cmd}' and press 'Write schema' to update."+ )diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex 0f8cda8194..ac7f13918f 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -47,7 +47,6 @@ def test_rename(client: TestClient) -> None:assert response.json() == {"success": True}assert new_path.exists()- assert not current_path.exists()@with_session(SESSION_ID)diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.pyindex 55947f1cf8..7c71c3b849 100644--- a/tests/_server/export/test_exporter.py+++ b/tests/_server/export/test_exporter.py@@ -10,6 +10,7 @@ import pytestfrom marimo._ast.app import App, InternalAppfrom marimo._config.config import DEFAULT_CONFIGfrom marimo._dependencies.dependencies import DependencyManager+from marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.ops import CellOpfrom marimo._plugins.core.json_encoder import WebComponentEncoderfrom marimo._server.export import (@@ -19,6 +20,8 @@ from marimo._server.export import ()from marimo._server.export.exporter import Exporterfrom marimo._server.file_manager import AppFileManager+from marimo._server.models.export import ExportAsHTMLRequest+from marimo._server.session.session_view import SessionViewfrom marimo._utils.marimo_path import MarimoPathfrom tests.mocks import snapshotter@@ -465,3 +468,428 @@ async def test_run_until_completion_with_console_output(mock_echo: MagicMock):"run_until_completion_with_console_output.txt",_print_messages(cell_ops),)+++def test_export_as_html_with_serialization():+ """Test HTML export uses new serialization approach correctly."""+ app = App()++ @app.cell()+ def cell_1():+ print("Hello World")+ return 10++ @app.cell()+ def cell_2():+ import marimo as mo++ mo.md("# Markdown Cell")+ return (mo,)++ file_manager = AppFileManager.from_app(InternalApp(app))+ session_view = SessionView()++ # Add some test data to session view+ cell_ids = list(file_manager.app.cell_manager.cell_ids())+ session_view.cell_operations[cell_ids[0]] = CellOp(+ cell_id=cell_ids[0],+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="10",+ ),+ console=[+ CellOutput(+ channel=CellChannel.STDOUT,+ mimetype="text/plain",+ data="Hello World",+ )+ ],+ timestamp=0,+ )+ session_view.last_executed_code[cell_ids[0]] = (+ "print('Hello World')\nreturn 10"+ )++ session_view.cell_operations[cell_ids[1]] = CellOp(+ cell_id=cell_ids[1],+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/html",+ data="<h1>Markdown Cell</h1>",+ ),+ console=[],+ timestamp=0,+ )+ session_view.last_executed_code[cell_ids[1]] = (+ "import marimo as mo\nmo.md('# Markdown Cell')\nreturn (mo,)"+ )++ exporter = Exporter()++ request = ExportAsHTMLRequest(+ download=True,+ files=[],+ include_code=True,+ )++ html, filename = exporter.export_as_html(+ file_manager=file_manager,+ session_view=session_view,+ display_config=DEFAULT_CONFIG["display"],+ request=request,+ )++ assert filename == "notebook.html"+ assert "Hello World" in html+ assert "Markdown Cell" in html+ assert 'data-marimo="true"' in html+++def test_export_as_html_without_code():+ """Test HTML export clears code when include_code=False."""+ app = App()++ @app.cell()+ def test_cell():+ secret_value = "should_not_appear"+ print("visible output")+ return secret_value++ file_manager = AppFileManager.from_app(InternalApp(app))+ session_view = SessionView()++ cell_ids = list(file_manager.app.cell_manager.cell_ids())+ session_view.cell_operations[cell_ids[0]] = CellOp(+ cell_id=cell_ids[0],+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="visible output",+ ),+ console=[+ CellOutput(+ channel=CellChannel.STDOUT,+ mimetype="text/plain",+ data="console message",+ )+ ],+ timestamp=0,+ )+ session_view.last_executed_code[cell_ids[0]] = (+ "secret_value = 'should_not_appear'\nprint('visible output')\nreturn secret_value"+ )++ exporter = Exporter()++ request = ExportAsHTMLRequest(+ download=False,+ files=[],+ include_code=False,+ )++ html, filename = exporter.export_as_html(+ file_manager=file_manager,+ session_view=session_view,+ display_config=DEFAULT_CONFIG["display"],+ request=request,+ )++ # Code should not appear in the HTML+ assert "secret_value" not in html+ assert "should_not_appear" not in html++ # But outputs should still be visible+ assert "visible output" in html++ # Console outputs should be cleared (no console message in HTML)+ # The exact format depends on template implementation+++def test_export_as_html_with_files():+ """Test HTML export includes virtual files."""+ app = App()++ @app.cell()+ def test_cell():+ return "test"++ file_manager = AppFileManager.from_app(InternalApp(app))+ session_view = SessionView()++ cell_ids = list(file_manager.app.cell_manager.cell_ids())+ session_view.cell_operations[cell_ids[0]] = CellOp(+ cell_id=cell_ids[0],+ status="idle",+ output=None,+ console=[],+ timestamp=0,+ )+ session_view.last_executed_code[cell_ids[0]] = "return 'test'"++ exporter = Exporter()++ request = ExportAsHTMLRequest(+ download=True,+ files=["/@file/10-test.txt"], # Mock file reference+ include_code=True,+ )++ # Mock the read_virtual_file function to avoid file system dependencies+ with patch(+ "marimo._server.export.exporter.read_virtual_file"+ ) as mock_read:+ mock_read.return_value = b"test file content"++ html, filename = exporter.export_as_html(+ file_manager=file_manager,+ session_view=session_view,+ display_config=DEFAULT_CONFIG["display"],+ request=request,+ )++ assert filename == "notebook.html"+ # Files should be embedded as data URLs+ assert "data:" in html+++def test_export_as_html_with_cell_configs():+ """Test HTML export preserves cell configurations through serialization."""+ app = App()++ @app.cell(hide_code=True, disabled=True, column=1)+ def configured_cell():+ return "configured"++ file_manager = AppFileManager.from_app(InternalApp(app))+ session_view = SessionView()++ cell_ids = list(file_manager.app.cell_manager.cell_ids())+ session_view.cell_operations[cell_ids[0]] = CellOp(+ cell_id=cell_ids[0],+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="configured",+ ),+ console=[],+ timestamp=0,+ )+ session_view.last_executed_code[cell_ids[0]] = "return 'configured'"++ exporter = Exporter()++ request = ExportAsHTMLRequest(+ download=True,+ files=[],+ include_code=True,+ )++ html, filename = exporter.export_as_html(+ file_manager=file_manager,+ session_view=session_view,+ display_config=DEFAULT_CONFIG["display"],+ request=request,+ )++ assert filename == "notebook.html"+ # Verify that the serialized notebook data contains configuration+ assert (+ "hide_code" in html or "hideCode" in html+ ) # depends on serialization format+ assert "configured" in html+++def test_export_as_html_preserves_output_order():+ """Test HTML export preserves cell execution order in session snapshot."""+ app = App()++ @app.cell()+ def cell_first():+ return "first"++ @app.cell()+ def cell_second():+ return "second"++ @app.cell()+ def cell_third():+ return "third"++ file_manager = AppFileManager.from_app(InternalApp(app))+ session_view = SessionView()++ cell_ids = list(file_manager.app.cell_manager.cell_ids())++ # Add cells in different order than execution+ for i, cell_id in enumerate(cell_ids):+ session_view.cell_operations[cell_id] = CellOp(+ cell_id=cell_id,+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data=f"output_{i}",+ ),+ console=[],+ timestamp=i,+ )+ session_view.last_executed_code[cell_id] = f"return 'output_{i}'"++ exporter = Exporter()++ request = ExportAsHTMLRequest(+ download=True,+ files=[],+ include_code=True,+ )++ html, filename = exporter.export_as_html(+ file_manager=file_manager,+ session_view=session_view,+ display_config=DEFAULT_CONFIG["display"],+ request=request,+ )++ assert filename == "notebook.html"+ # All outputs should be present+ assert "output_0" in html+ assert "output_1" in html+ assert "output_2" in html+++def test_export_as_html_with_error_outputs():+ """Test HTML export handles error outputs correctly."""+ app = App()++ @app.cell()+ def error_cell():+ raise ValueError("Test error")++ file_manager = AppFileManager.from_app(InternalApp(app))+ session_view = SessionView()++ cell_ids = list(file_manager.app.cell_manager.cell_ids())++ # Mock an error output+ from marimo._messaging.errors import MarimoExceptionRaisedError++ error = MarimoExceptionRaisedError(+ type="exception",+ exception_type="ValueError",+ msg="Test error",+ raising_cell=cell_ids[0],+ )++ session_view.cell_operations[cell_ids[0]] = CellOp(+ cell_id=cell_ids[0],+ status="idle",+ output=CellOutput.errors([error]),+ console=[],+ timestamp=0,+ )+ session_view.last_executed_code[cell_ids[0]] = (+ "raise ValueError('Test error')"+ )++ exporter = Exporter()++ request = ExportAsHTMLRequest(+ download=True,+ files=[],+ include_code=True,+ )++ html, filename = exporter.export_as_html(+ file_manager=file_manager,+ session_view=session_view,+ display_config=DEFAULT_CONFIG["display"],+ request=request,+ )++ assert filename == "notebook.html"+ # Error should be serialized in the session snapshot+ assert "Test error" in html or "ValueError" in html+++def test_export_as_html_code_hash_consistency():+ """Test HTML export includes correct code hash regardless of include_code setting."""+ app = App()++ @app.cell()+ def test_cell():+ return "test"++ file_manager = AppFileManager.from_app(InternalApp(app))+ session_view = SessionView()++ cell_ids = list(file_manager.app.cell_manager.cell_ids())+ session_view.cell_operations[cell_ids[0]] = CellOp(+ cell_id=cell_ids[0],+ status="idle",+ output=None,+ console=[],+ timestamp=0,+ )+ session_view.last_executed_code[cell_ids[0]] = "return 'test'"++ exporter = Exporter()++ # Test with include_code=True+ request_with_code = ExportAsHTMLRequest(+ download=True,+ files=[],+ include_code=True,+ )++ html_with_code, _ = exporter.export_as_html(+ file_manager=file_manager,+ session_view=session_view,+ display_config=DEFAULT_CONFIG["display"],+ request=request_with_code,+ )++ # Test with include_code=False+ request_without_code = ExportAsHTMLRequest(+ download=True,+ files=[],+ include_code=False,+ )++ html_without_code, _ = exporter.export_as_html(+ file_manager=file_manager,+ session_view=session_view,+ display_config=DEFAULT_CONFIG["display"],+ request=request_without_code,+ )++ # Both should contain the same code hash+ # The code hash should be in both because it's computed from the actual file code+ import re++ # Extract code hash from both HTML outputs+ hash_pattern = r"<marimo-code-hash[^>]*>([a-f0-9]+)</marimo-code-hash>"++ hash_with_code = re.search(hash_pattern, html_with_code)+ hash_without_code = re.search(hash_pattern, html_without_code)++ assert hash_with_code is not None, "Code hash not found in HTML with code"+ assert hash_without_code is not None, (+ "Code hash not found in HTML without code"+ )+ assert hash_with_code.group(1) == hash_without_code.group(1), (+ "Code hashes should be identical"+ )++ # Verify that when include_code=False, the notebook cells have empty code+ assert '"code": ""' in html_without_code, (+ "Cell code should be empty when include_code=False"+ )+ # But when include_code=True, the notebook cells should have code+ assert '"code": "return' in html_with_code, (+ "Cell code should be present when include_code=True"+ )diff --git a/tests/_server/session/snapshots/mixed_error_session.json b/tests/_server/session/snapshots/mixed_error_session.jsonnew file mode 100644index 0000000000..29ab6b621e--- /dev/null+++ b/tests/_server/session/snapshots/mixed_error_session.json@@ -0,0 +1,33 @@+{+ "version": "1",+ "metadata": {+ "marimo_version": "0.0.0"+ },+ "cells": [+ {+ "id": "cell1",+ "code_hash": "c15059b59342088fa950e0f01cb6b59a",+ "outputs": [+ {+ "type": "error",+ "ename": "ValueError",+ "evalue": "Invalid value",+ "traceback": ["line 1", "line 2"]+ },+ {+ "type": "error",+ "ename": "RuntimeError",+ "evalue": "Runtime error occurred",+ "traceback": []+ },+ {+ "type": "error",+ "ename": "TypeError",+ "evalue": "Type mismatch",+ "traceback": []+ }+ ],+ "console": []+ }+ ]+}diff --git a/tests/_server/session/test_serialize_session.py b/tests/_server/session/test_serialize_session.pyindex 628d1d5cfa..d033bfde12 100644--- a/tests/_server/session/test_serialize_session.py+++ b/tests/_server/session/test_serialize_session.py@@ -7,6 +7,8 @@ import tempfilefrom pathlib import Pathfrom marimo import __version__+from marimo._ast.cell import CellConfig+from marimo._ast.cell_manager import CellManagerfrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.errors import MarimoExceptionRaisedError, UnknownErrorfrom marimo._messaging.ops import CellOp@@ -19,9 +21,11 @@ from marimo._server.session.serialize import (_hash_code,deserialize_session,get_session_cache_file,+ serialize_notebook,serialize_session_view,)from marimo._server.session.session_view import SessionView+from marimo._types.ids import CellId_tfrom tests.mocks import snapshottersnapshot = snapshotter(__file__)@@ -30,8 +34,8 @@ snapshot = snapshotter(__file__)def test_serialize_basic_session():"""Test serialization of a basic session with a single cell with data output"""view = SessionView()- view.cell_operations["cell1"] = CellOp(- cell_id="cell1",+ view.cell_operations[CellId_t("cell1")] = CellOp(+ cell_id=CellId_t("cell1"),status="idle",output=CellOutput(channel=CellChannel.OUTPUT,@@ -41,7 +45,7 @@ def test_serialize_basic_session():console=[],timestamp=0,)- view.last_executed_code["cell1"] = "print('Hello, world!')"+ view.last_executed_code[CellId_t("cell1")] = "print('Hello, world!')"result = serialize_session_view(view)snapshot("basic_session.json", json.dumps(result, indent=2))@@ -50,8 +54,8 @@ def test_serialize_basic_session():def test_serialize_session_with_error():"""Test serialization of a session with an error output"""view = SessionView()- view.cell_operations["cell1"] = CellOp(- cell_id="cell1",+ view.cell_operations[CellId_t("cell1")] = CellOp(+ cell_id=CellId_t("cell1"),status="idle",output=CellOutput(channel=CellChannel.MARIMO_ERROR,@@ -61,7 +65,7 @@ def test_serialize_session_with_error():console=[],timestamp=0,)- view.last_executed_code["cell1"] = (+ view.last_executed_code[CellId_t("cell1")] = ("raise RuntimeError('Something went wrong')")@@ -119,10 +123,201 @@ def test_serialize_session_with_mime_bundle():snapshot("mime_bundle_session.json", json.dumps(result, indent=2))+def test_serialize_notebook_basic():+ """Test serialization of a SessionView to a Notebook with basic cell"""+ view = SessionView()+ cell_manager = CellManager()++ # Register cell with cell manager+ cell_id = CellId_t("cell1")+ cell_manager.register_cell(+ cell_id=cell_id,+ code="print('Hello, world!')",+ name="my_cell",+ config=CellConfig(column=1, disabled=False, hide_code=True),+ )++ # Add to session view+ view.cell_operations[cell_id] = CellOp(+ cell_id=cell_id,+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="Hello, world!",+ ),+ console=[],+ timestamp=0,+ )+ view.last_executed_code[cell_id] = "print('Hello, world!')"++ result = serialize_notebook(view, cell_manager)++ assert result["version"] == "1"+ assert result["metadata"]["marimo_version"] == __version__+ assert len(result["cells"]) == 1++ cell = result["cells"][0]+ assert cell["id"] == "cell1"+ assert cell["code"] == "print('Hello, world!')"+ assert cell["name"] == "my_cell"+ assert cell["config"]["column"] == 1+ assert cell["config"]["disabled"] is False+ assert cell["config"]["hide_code"] is True+++def test_serialize_notebook_multiple_cells():+ """Test serialization of a SessionView to a Notebook with multiple cells"""+ view = SessionView()+ cell_manager = CellManager()++ # Register first cell+ cell_id1 = CellId_t("cell1")+ cell_manager.register_cell(+ cell_id=cell_id1,+ code="x = 1",+ name="setup",+ config=CellConfig(column=0, disabled=False),+ )++ # Register second cell+ cell_id2 = CellId_t("cell2")+ cell_manager.register_cell(+ cell_id=cell_id2,+ code="print(x + 1)",+ name="output",+ config=CellConfig(column=1, hide_code=True),+ )++ # Add first cell to session view+ view.cell_operations[cell_id1] = CellOp(+ cell_id=cell_id1,+ status="idle",+ output=None,+ console=[],+ timestamp=0,+ )+ view.last_executed_code[cell_id1] = "x = 1"++ # Add second cell to session view+ view.cell_operations[cell_id2] = CellOp(+ cell_id=cell_id2,+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="2",+ ),+ console=[],+ timestamp=0,+ )+ view.last_executed_code[cell_id2] = "print(x + 1)"++ result = serialize_notebook(view, cell_manager)++ assert len(result["cells"]) == 2++ cell1 = result["cells"][0]+ assert cell1["id"] == "cell1"+ assert cell1["code"] == "x = 1"+ assert cell1["name"] == "setup"+ assert cell1["config"]["column"] == 0+ assert cell1["config"]["disabled"] is False++ cell2 = result["cells"][1]+ assert cell2["id"] == "cell2"+ assert cell2["code"] == "print(x + 1)"+ assert cell2["name"] == "output"+ assert cell2["config"]["column"] == 1+ assert cell2["config"]["hide_code"] is True+++def test_serialize_notebook_empty_code():+ """Test serialization when cells have no executed code"""+ view = SessionView()+ cell_manager = CellManager()++ # Register cell with cell manager but with different code+ cell_id = CellId_t("cell1")+ cell_manager.register_cell(+ cell_id=cell_id,+ code="# Original code",+ name="empty_cell",+ config=CellConfig(),+ )++ # Add to session view but without executed code+ view.cell_operations[cell_id] = CellOp(+ cell_id=cell_id,+ status="idle",+ output=None,+ console=[],+ timestamp=0,+ )+ # No entry in last_executed_code++ result = serialize_notebook(view, cell_manager)++ assert len(result["cells"]) == 1+ cell = result["cells"][0]+ assert cell["id"] == "cell1"+ assert (+ cell["code"] == ""+ ) # Should default to empty string from last_executed_code+ assert cell["name"] == "empty_cell"+ assert cell["config"]["column"] is None+ assert cell["config"]["disabled"] is False # Default value+ assert cell["config"]["hide_code"] is False # Default value+++def test_serialize_notebook_no_cells():+ """Test serialization of an empty SessionView"""+ view = SessionView()+ cell_manager = CellManager()++ result = serialize_notebook(view, cell_manager)++ assert result["version"] == "1"+ assert result["metadata"]["marimo_version"] == __version__+ assert len(result["cells"]) == 0+++def test_serialize_notebook_missing_cell_data():+ """Test serialization when cell exists in SessionView but not in CellManager"""+ view = SessionView()+ cell_manager = CellManager()++ # Add cell to session view but don't register it with cell manager+ cell_id = CellId_t("orphan_cell")+ view.cell_operations[cell_id] = CellOp(+ cell_id=cell_id,+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="orphan output",+ ),+ console=[],+ timestamp=0,+ )+ view.last_executed_code[cell_id] = "print('orphan')"++ result = serialize_notebook(view, cell_manager)++ assert len(result["cells"]) == 1+ cell = result["cells"][0]+ assert cell["id"] == "orphan_cell"+ assert cell["code"] == "print('orphan')"+ assert cell["name"] is None # Should be None due to missing cell data+ assert cell["config"]["column"] is None+ assert cell["config"]["disabled"] is None+ assert cell["config"]["hide_code"] is None++def test_deserialize_basic_session():"""Test deserialization of a basic session"""session = NotebookSessionV1(- version=1,+ version="1",metadata={"marimo_version": "1.0.0"},cells=[{@@ -140,8 +335,8 @@ def test_deserialize_basic_session():)view = deserialize_session(session)- assert "cell1" in view.cell_operations- cell = view.cell_operations["cell1"]+ assert CellId_t("cell1") in view.cell_operations+ cell = view.cell_operations[CellId_t("cell1")]assert cell.output is not Noneassert cell.output.channel == CellChannel.OUTPUTassert cell.output.mimetype == "text/plain"@@ -380,6 +575,72 @@ def test_serialize_session_with_dict_error():assert result["cells"][0]["outputs"][0]["evalue"] == "Something went wrong"+def test_serialize_session_with_mixed_error_formats():+ """Test serialization of a session with mixed error formats (dict and object)"""+ view = SessionView()++ # Test with both dictionary and object error formats+ mixed_errors = [+ # Dictionary format error+ {+ "type": "ValueError",+ "msg": "Invalid value",+ "traceback": ["line 1", "line 2"],+ },+ # Object format error+ UnknownError(type="RuntimeError", msg="Runtime error occurred"),+ # Dictionary without traceback+ {"type": "TypeError", "msg": "Type mismatch"},+ ]++ view.cell_operations[CellId_t("cell1")] = CellOp(+ cell_id=CellId_t("cell1"),+ status="idle",+ output=CellOutput(+ channel=CellChannel.MARIMO_ERROR,+ mimetype="application/vnd.marimo+error",+ data=mixed_errors,+ ),+ console=[],+ timestamp=0,+ )+ view.last_executed_code[CellId_t("cell1")] = (+ "# code that causes mixed errors"+ )++ result = serialize_session_view(view)++ # Verify the error normalization worked correctly+ assert len(result["cells"]) == 1+ cell = result["cells"][0]+ assert len(cell["outputs"]) == 3++ # Check first error (dictionary with traceback)+ error1 = cell["outputs"][0]+ assert error1["type"] == "error"+ assert error1["ename"] == "ValueError"+ assert error1["evalue"] == "Invalid value"+ assert error1["traceback"] == ["line 1", "line 2"]++ # Check second error (object format)+ error2 = cell["outputs"][1]+ assert error2["type"] == "error"+ assert error2["ename"] == "RuntimeError"+ assert error2["evalue"] == "Runtime error occurred"+ assert (+ error2["traceback"] == []+ ) # UnknownError doesn't have traceback by default++ # Check third error (dictionary without traceback)+ error3 = cell["outputs"][2]+ assert error3["type"] == "error"+ assert error3["ename"] == "TypeError"+ assert error3["evalue"] == "Type mismatch"+ assert error3["traceback"] == []++ snapshot("mixed_error_session.json", json.dumps(result, indent=2))++class TestSessionCacheManager:"""Test SessionCacheManager functionality"""diff --git a/tests/_server/session/test_serialize_session_missing_type.py b/tests/_server/session/test_serialize_session_missing_type.pyindex 164b253765..9bc72f41fc 100644--- a/tests/_server/session/test_serialize_session_missing_type.py+++ b/tests/_server/session/test_serialize_session_missing_type.py@@ -28,5 +28,5 @@ def test_serialize_session_with_dict_error_missing_type():assert len(result["cells"]) == 1assert len(result["cells"][0]["outputs"]) == 1assert result["cells"][0]["outputs"][0]["type"] == "error"- assert result["cells"][0]["outputs"][0]["ename"] == "Unknown"+ assert result["cells"][0]["outputs"][0]["ename"] == "UnknownError"assert result["cells"][0]["outputs"][0]["evalue"] == "Something went wrong"diff --git a/tests/_server/templates/data/index.html b/tests/_server/templates/data/index.htmlindex a333f30e40..8048631688 100644--- a/tests/_server/templates/data/index.html+++ b/tests/_server/templates/data/index.html@@ -53,7 +53,7 @@}</script><marimo-filename hidden>{{ filename }}</marimo-filename>- <script>+ <script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = '{{ mount_config }}';</script><title>{{ title }}</title>diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txtindex 5fc06173c9..5f352d0bed 100644--- a/tests/_server/templates/snapshots/export1.txt+++ b/tests/_server/templates/snapshots/export1.txt@@ -53,7 +53,7 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <script>+ <script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py","mode": "read",@@ -63,6 +63,8 @@"configOverrides": {"formatting": {"line_length": 100}},"appConfig": {"sql_output": "auto", "width": "compact"},"view": {"showAppCode": true},+ "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},};</script><title>notebook</title>@@ -71,9 +73,6 @@<script data-marimo="true">window.__MARIMO_STATIC__ = {};- window.__MARIMO_STATIC__.version = "0.0.0";- window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDEnKQ==", "cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDInKQ=="], "cellConfigs": ["JTdCJTIyY29sdW1uJTIyJTNBJTIwbnVsbCUyQyUyMCUyMmRpc2FibGVkJTIyJTNBJTIwZmFsc2UlMkMlMjAlMjJoaWRlX2NvZGUlMjIlM0ElMjBmYWxzZSU3RA==", "JTdCJTIyY29sdW1uJTIyJTNBJTIwbnVsbCUyQyUyMCUyMmRpc2FibGVkJTIyJTNBJTIwZmFsc2UlMkMlMjAlMjJoaWRlX2NvZGUlMjIlM0ElMjBmYWxzZSU3RA=="], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkVycm9yJTIwaW4lMjBDZWxsJTIwMSUyMiUyQyUyMCUyMnRpbWVzdGFtcCUyMiUzQSUyMDAlN0Q="]}};- window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};</script></head>diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txtindex 05eda50f61..8510c208ad 100644--- a/tests/_server/templates/snapshots/export2.txt+++ b/tests/_server/templates/snapshots/export2.txt@@ -53,7 +53,7 @@}</script><marimo-filename hidden></marimo-filename>- <script>+ <script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "","mode": "read",@@ -63,6 +63,8 @@"configOverrides": {"formatting": {"line_length": 100}},"appConfig": {"sql_output": "auto", "width": "compact"},"view": {"showAppCode": true},+ "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},};</script><title>marimo</title>@@ -71,9 +73,6 @@<script data-marimo="true">window.__MARIMO_STATIC__ = {};- window.__MARIMO_STATIC__.version = "0.0.0";- window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDEnKQ==", "cHJpbnQoJ0hlbGxvJTJDJTIwQ2VsbCUyMDInKQ=="], "cellConfigs": ["JTdCJTIyY29sdW1uJTIyJTNBJTIwbnVsbCUyQyUyMCUyMmRpc2FibGVkJTIyJTNBJTIwZmFsc2UlMkMlMjAlMjJoaWRlX2NvZGUlMjIlM0ElMjBmYWxzZSU3RA==", "JTdCJTIyY29sdW1uJTIyJTNBJTIwbnVsbCUyQyUyMCUyMmRpc2FibGVkJTIyJTNBJTIwZmFsc2UlMkMlMjAlMjJoaWRlX2NvZGUlMjIlM0ElMjBmYWxzZSU3RA=="], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkhlbGxvJTJDJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dCUyRnBsYWluJTIyJTJDJTIwJTIyZGF0YSUyMiUzQSUyMCUyMkVycm9yJTIwaW4lMjBDZWxsJTIwMSUyMiUyQyUyMCUyMnRpbWVzdGFtcCUyMiUzQSUyMDAlN0Q="]}};- window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};</script></head>diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txtindex e45ea3245c..37f02631a3 100644--- a/tests/_server/templates/snapshots/export3.txt+++ b/tests/_server/templates/snapshots/export3.txt@@ -53,7 +53,7 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <script>+ <script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py","mode": "read",@@ -63,6 +63,8 @@"configOverrides": {"formatting": {"line_length": 100}},"appConfig": {"sql_output": "auto", "width": "compact"},"view": {"showAppCode": true},+ "notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},};</script><title>notebook</title>@@ -71,9 +73,6 @@<script data-marimo="true">window.__MARIMO_STATIC__ = {};- window.__MARIMO_STATIC__.version = "0.0.0";- window.__MARIMO_STATIC__.notebookState = {"cellIds": [], "cellNames": [], "cellCodes": [], "cellConfigs": [], "cellOutputs": {}, "cellConsoleOutputs": {}};- window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";window.__MARIMO_STATIC__.files = {};</script></head>diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txtindex 5c8812b001..8bf5ea6f2a 100644--- a/tests/_server/templates/snapshots/export4.txt+++ b/tests/_server/templates/snapshots/export4.txt@@ -53,7 +53,7 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <script>+ <script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py","mode": "read",@@ -63,6 +63,8 @@"configOverrides": {"formatting": {"line_length": 100}},"appConfig": {"css_file": "custom.css", "sql_output": "auto", "width": "compact"},"view": {"showAppCode": true},+ "notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},};</script><title>notebook</title>@@ -71,9 +73,6 @@<script data-marimo="true">window.__MARIMO_STATIC__ = {};- window.__MARIMO_STATIC__.version = "0.0.0";- window.__MARIMO_STATIC__.notebookState = {"cellIds": [], "cellNames": [], "cellCodes": [], "cellConfigs": [], "cellOutputs": {}, "cellConsoleOutputs": {}};- window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";window.__MARIMO_STATIC__.files = {};</script><style title='marimo-custom'>/* custom css */</style></head>diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txtindex df83cc97fb..edd17ebe72 100644--- a/tests/_server/templates/snapshots/export5.txt+++ b/tests/_server/templates/snapshots/export5.txt@@ -53,7 +53,7 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <script>+ <script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py","mode": "read",@@ -63,6 +63,8 @@"configOverrides": {"formatting": {"line_length": 100}},"appConfig": {"app_title": "My App", "html_head_file": "head.html", "sql_output": "auto", "width": "compact"},"view": {"showAppCode": true},+ "notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},};</script><title>My App</title>@@ -71,9 +73,6 @@<script data-marimo="true">window.__MARIMO_STATIC__ = {};- window.__MARIMO_STATIC__.version = "0.0.0";- window.__MARIMO_STATIC__.notebookState = {"cellIds": [], "cellNames": [], "cellCodes": [], "cellConfigs": [], "cellOutputs": {}, "cellConsoleOutputs": {}};- window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";window.__MARIMO_STATIC__.files = {};</script>diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txtindex 3d5fdf19d4..59efc653c2 100644--- a/tests/_server/templates/snapshots/export6.txt+++ b/tests/_server/templates/snapshots/export6.txt@@ -53,7 +53,7 @@}</script><marimo-filename hidden>notebook.py</marimo-filename>- <script>+ <script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = {"filename": "notebook.py","mode": "read",@@ -63,6 +63,8 @@"configOverrides": {"formatting": {"line_length": 100}},"appConfig": {"sql_output": "auto", "width": "compact"},"view": {"showAppCode": true},+ "notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},};</script><title>notebook</title>@@ -71,9 +73,6 @@<script data-marimo="true">window.__MARIMO_STATIC__ = {};- window.__MARIMO_STATIC__.version = "0.0.0";- window.__MARIMO_STATIC__.notebookState = {"cellIds": [], "cellNames": [], "cellCodes": [], "cellConfigs": [], "cellOutputs": {}, "cellConsoleOutputs": {}};- window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";window.__MARIMO_STATIC__.files = {};</script><style title='marimo-custom'>/* custom css 1 */</style>diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex 88b1d5488c..06f38f1460 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -8,13 +8,25 @@ from pathlib import Pathfrom typing import Literalfrom marimo._ast.app_config import _AppConfig-from marimo._ast.cell import CellConfigfrom marimo._config.config import (MarimoConfig,PartialMarimoConfig,merge_default_config,)-from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._schemas.notebook import (+ NotebookCell,+ NotebookCellConfig,+ NotebookMetadata,+ NotebookV1,+)+from marimo._schemas.session import (+ VERSION,+ Cell,+ DataOutput,+ NotebookSessionMetadata,+ NotebookSessionV1,+ StreamOutput,+)from marimo._server.export.exporter import hash_codefrom marimo._server.model import SessionModefrom marimo._server.templates import templates@@ -312,35 +324,64 @@ class TestStaticNotebookTemplate(unittest.TestCase):self.filename = tmp_path / "notebook.py"self.filepath = "path/to/notebook.py"self.code = "print('Hello, World!')"- self.cell_ids = ["cell1", "cell2"]- self.cell_names = ["Cell 1", "Cell 2"]- self.cell_codes = ["print('Hello, Cell 1')", "print('Hello, Cell 2')"]- self.cell_configs = [CellConfig(), CellConfig()]- self.cell_outputs = {- "cell1": CellOutput(- channel=CellChannel.OUTPUT,- data="Hello, Cell 1",- mimetype="text/plain",- timestamp=0,- )- }- self.cell_console_outputs = {- "cell1": [- CellOutput(- channel=CellChannel.STDOUT,- data="Hello, Cell 1",- mimetype="text/plain",- timestamp=0,++ # Create session and notebook snapshots+ self.session_snapshot = NotebookSessionV1(+ version=VERSION,+ metadata=NotebookSessionMetadata(marimo_version="0.1.0"),+ cells=[+ Cell(+ id="cell1",+ code_hash="abc123",+ outputs=[+ DataOutput(+ type="data",+ data={+ "text/plain": "Hello, Cell 1",+ },+ )+ ],+ console=[+ StreamOutput(+ type="stream",+ name="stdout",+ text="Hello, Cell 1",+ ),+ StreamOutput(+ type="stream",+ name="stderr",+ text="Error in Cell 1",+ ),+ ],),- CellOutput(- channel=CellChannel.STDERR,- data="Error in Cell 1",- mimetype="text/plain",- timestamp=0,+ Cell(+ id="cell2",+ code_hash="def456",+ outputs=[],+ console=[],),],- "cell2": [],- }+ )++ self.notebook_snapshot = NotebookV1(+ version=VERSION,+ metadata=NotebookMetadata(marimo_version="0.1.0"),+ cells=[+ NotebookCell(+ id="cell1",+ code="print('Hello, Cell 1')",+ name="Cell 1",+ config=NotebookCellConfig(),+ ),+ NotebookCell(+ id="cell2",+ code="print('Hello, Cell 2')",+ name="Cell 2",+ config=NotebookCellConfig(),+ ),+ ],+ )+self.files = {"file1": "File 1 content", "file2": "File 2 content"}def tearDown(self) -> None:@@ -356,12 +397,8 @@ class TestStaticNotebookTemplate(unittest.TestCase):self.filepath,self.code,hash_code(self.code),- self.cell_ids,- self.cell_names,- self.cell_codes,- self.cell_configs,- self.cell_outputs,- self.cell_console_outputs,+ self.session_snapshot,+ self.notebook_snapshot,self.files,)@@ -378,12 +415,8 @@ class TestStaticNotebookTemplate(unittest.TestCase):None,self.code,hash_code(self.code),- self.cell_ids,- self.cell_names,- self.cell_codes,- self.cell_configs,- self.cell_outputs,- self.cell_console_outputs,+ self.session_snapshot,+ self.notebook_snapshot,files=self.files,)@@ -391,6 +424,18 @@ class TestStaticNotebookTemplate(unittest.TestCase):_assert_no_leftover_replacements(result)def test_static_notebook_template_no_code(self) -> None:+ # Create empty snapshots for no-code case+ empty_session = NotebookSessionV1(+ version=VERSION,+ metadata=NotebookSessionMetadata(marimo_version="0.1.0"),+ cells=[],+ )+ empty_notebook = NotebookV1(+ version=VERSION,+ metadata=NotebookMetadata(marimo_version="0.1.0"),+ cells=[],+ )+result = templates.static_notebook_template(self.html,self.user_config,@@ -400,12 +445,8 @@ class TestStaticNotebookTemplate(unittest.TestCase):self.filepath,"",hash_code(self.code),- [],- [],- [],- [],- {},- {},+ empty_session,+ empty_notebook,{},)@@ -419,6 +460,18 @@ class TestStaticNotebookTemplate(unittest.TestCase):css_file = self.filename.parent / "custom.css"css_file.write_text(css)+ # Create empty snapshots+ empty_session = NotebookSessionV1(+ version=VERSION,+ metadata=NotebookSessionMetadata(marimo_version="0.1.0"),+ cells=[],+ )+ empty_notebook = NotebookV1(+ version=VERSION,+ metadata=NotebookMetadata(marimo_version="0.1.0"),+ cells=[],+ )+result = templates.static_notebook_template(self.html,self.user_config,@@ -428,12 +481,8 @@ class TestStaticNotebookTemplate(unittest.TestCase):str(self.filename),"",hash_code(self.code),- [],- [],- [],- [],- {},- {},+ empty_session,+ empty_notebook,{},)@@ -457,6 +506,18 @@ class TestStaticNotebookTemplate(unittest.TestCase):head_file = self.filename.parent / "head.html"head_file.write_text(head)+ # Create empty snapshots+ empty_session = NotebookSessionV1(+ version=VERSION,+ metadata=NotebookSessionMetadata(marimo_version="0.1.0"),+ cells=[],+ )+ empty_notebook = NotebookV1(+ version=VERSION,+ metadata=NotebookMetadata(marimo_version="0.1.0"),+ cells=[],+ )+result = templates.static_notebook_template(self.html,self.user_config,@@ -466,12 +527,8 @@ class TestStaticNotebookTemplate(unittest.TestCase):str(self.filename),"",hash_code(self.code),- [],- [],- [],- [],- {},- {},+ empty_session,+ empty_notebook,{},)@@ -492,6 +549,18 @@ class TestStaticNotebookTemplate(unittest.TestCase):config = merge_default_config(self.user_config)config["display"]["custom_css"] = ["custom1.css", "custom2.css"]+ # Create empty snapshots+ empty_session = NotebookSessionV1(+ version=VERSION,+ metadata=NotebookSessionMetadata(marimo_version="0.1.0"),+ cells=[],+ )+ empty_notebook = NotebookV1(+ version=VERSION,+ metadata=NotebookMetadata(marimo_version="0.1.0"),+ cells=[],+ )+result = templates.static_notebook_template(self.html,config,@@ -501,12 +570,8 @@ class TestStaticNotebookTemplate(unittest.TestCase):str(self.filename),"",hash_code(self.code),- [],- [],- [],- [],- {},- {},+ empty_session,+ empty_notebook,{},)@@ -526,6 +591,18 @@ class TestStaticNotebookTemplate(unittest.TestCase):config = merge_default_config(self.user_config)config["display"]["custom_css"] = [str(css_file)]+ # Create empty snapshots+ empty_session = NotebookSessionV1(+ version=VERSION,+ metadata=NotebookSessionMetadata(marimo_version="0.1.0"),+ cells=[],+ )+ empty_notebook = NotebookV1(+ version=VERSION,+ metadata=NotebookMetadata(marimo_version="0.1.0"),+ cells=[],+ )+result = templates.static_notebook_template(self.html,config,@@ -535,12 +612,8 @@ class TestStaticNotebookTemplate(unittest.TestCase):str(self.filename),"",hash_code(self.code),- [],- [],- [],- [],- {},- {},+ empty_session,+ empty_notebook,{},)@@ -555,6 +628,18 @@ class TestStaticNotebookTemplate(unittest.TestCase):config = merge_default_config(self.user_config)config["display"]["custom_css"] = ["nonexistent.css"]+ # Create empty snapshots+ empty_session = NotebookSessionV1(+ version=VERSION,+ metadata=NotebookSessionMetadata(marimo_version="0.1.0"),+ cells=[],+ )+ empty_notebook = NotebookV1(+ version=VERSION,+ metadata=NotebookMetadata(marimo_version="0.1.0"),+ cells=[],+ )+result = templates.static_notebook_template(self.html,config,@@ -564,12 +649,8 @@ class TestStaticNotebookTemplate(unittest.TestCase):str(self.filename),"",hash_code(self.code),- [],- [],- [],- [],- {},- {},+ empty_session,+ empty_notebook,{},)