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
feat(export): support IPYNB sort order and output selection (#10374)
Péter Gyarmatifbbc363ac419
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex e5f5c5a1e4..a95404b338 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -17,6 +17,7 @@ export type CellConfig = schemas["CellConfig"];export type RuntimeState = schemas["CellNotification"]["status"];export type CodeCompletionRequest = schemas["CodeCompletionRequest"];export type DeleteCellRequest = schemas["DeleteCellRequest"];+export type AutoExportAsIPYNBRequest = schemas["AutoExportAsIPYNBRequest"];export type AutoExportAsMarkdownRequest =schemas["AutoExportAsMarkdownRequest"];export type ExportAsHTMLRequest = schemas["ExportAsHTMLRequest"];@@ -226,7 +227,7 @@ export interface EditRequests {exportAsPDF: (request: ExportAsPDFRequest) => Promise<ExportedFile<Blob>>;autoExportAsHTML: (request: ExportAsHTMLRequest) => Promise<null>;autoExportAsMarkdown: (request: AutoExportAsMarkdownRequest) => Promise<null>;- autoExportAsIPYNB: (request: ExportAsIPYNBRequest) => Promise<null>;+ autoExportAsIPYNB: (request: AutoExportAsIPYNBRequest) => Promise<null>;updateCellOutputs: (request: UpdateCellOutputsRequest) => Promise<null>;// Package requestsgetPackageList: () => Promise<ListPackagesResponse>;diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex b4a3ae0249..7f0de39184 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -352,6 +352,7 @@ def _generate_server_api_schema() -> dict[str, Any]:completion.AiCompletionRequest,completion.AiInlineCompletionRequest,completion.ChatRequest,+ export.AutoExportAsIPYNBRequest,export.AutoExportAsMarkdownRequest,export.ExportAsHTMLRequest,export.ExportAsMarkdownRequest,diff --git a/marimo/_schemas/export.py b/marimo/_schemas/export.pyindex 327ab9072e..e0dd6b5dea 100644--- a/marimo/_schemas/export.py+++ b/marimo/_schemas/export.py@@ -10,6 +10,8 @@ from marimo._messaging.mimetypes import MimeBundleTuplefrom marimo._schemas.export_options import (ExportPDFPreset,HTMLExportOptions,+ IPYNBExportOptions,+ IPYNBSortMode,MarkdownExportOptions,PDFRasterServer,ServerExportFormat,@@ -40,6 +42,18 @@ class ExportAsScriptRequest(msgspec.Struct, rename="camel"):class ExportAsIPYNBRequest(msgspec.Struct, rename="camel"):download: bool+ sort_mode: IPYNBSortMode = "top-down"+ include_outputs: bool = True+++class AutoExportAsIPYNBRequest(msgspec.Struct, rename="camel"):+ download: bool+++def to_ipynb_export_options(+ request: ExportAsIPYNBRequest,+) -> IPYNBExportOptions:+ return IPYNBExportOptions(sort_mode=request.sort_mode)class ExportAsMarkdownRequest(msgspec.Struct, rename="camel"):diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex 7972031c9d..61bf121033 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -46,6 +46,7 @@ from marimo._schemas.export import (ExportFormatAvailability,UpdateCellOutputsRequest,to_html_export_options,+ to_ipynb_export_options,to_markdown_export_options,)from marimo._schemas.export_options import (@@ -409,8 +410,10 @@ async def export_as_ipynb(ipynb = Exporter().export_as_ipynb(IPYNBExportRequest(app=session.app_file_manager.app,- options=IPYNBExportOptions(sort_mode="top-down"),- session_view=session.session_view,+ options=to_ipynb_export_options(body),+ session_view=session.session_view+ if body.include_outputs+ else None,))@@ -509,7 +512,7 @@ async def auto_export_as_ipynb(content:application/json:schema:- $ref: "#/components/schemas/ExportAsIPYNBRequest"+ $ref: "#/components/schemas/AutoExportAsIPYNBRequest"responses:200:description: Export the notebook as IPYNBdiff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex d0ecf35fda..8a19c255aa 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -255,6 +255,14 @@ components:required: []title: AnthropicConfigtype: object+ AutoExportAsIPYNBRequest:+ properties:+ download:+ type: boolean+ required:+ - download+ title: AutoExportAsIPYNBRequest+ type: objectAutoExportAsMarkdownRequest:properties:download:@@ -1743,6 +1751,14 @@ components:properties:download:type: boolean+ includeOutputs:+ default: true+ type: boolean+ sortMode:+ default: top-down+ enum:+ - top-down+ - topologicalrequired:- downloadtitle: ExportAsIPYNBRequest@@ -6387,7 +6403,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/ExportAsIPYNBRequest'+ $ref: '#/components/schemas/AutoExportAsIPYNBRequest'responses:200:content:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 2c0c3b200f..d8ab6fc50e 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -773,7 +773,7 @@ export interface paths {};requestBody?: {content: {- "application/json": components["schemas"]["ExportAsIPYNBRequest"];+ "application/json": components["schemas"]["AutoExportAsIPYNBRequest"];};};responses: {@@ -3740,6 +3740,10 @@ export interface components {AnthropicConfig: {api_key?: string;};+ /** AutoExportAsIPYNBRequest */+ AutoExportAsIPYNBRequest: {+ download: boolean;+ };/** AutoExportAsMarkdownRequest */AutoExportAsMarkdownRequest: {download: boolean;@@ -4667,6 +4671,13 @@ export interface components {/** ExportAsIPYNBRequest */ExportAsIPYNBRequest: {download: boolean;+ /** @default true */+ includeOutputs?: boolean;+ /**+ * @default top-down+ * @enum {unknown}+ */+ sortMode?: "top-down" | "topological";};/** ExportAsMarkdownRequest */ExportAsMarkdownRequest: {diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex 9aebfcd7c8..dcd7f43765 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -12,7 +12,8 @@ from unittest.mock import patchimport pytest-from marimo import __version__+from marimo import App, __version__+from marimo._ast.app import InternalAppfrom marimo._convert.markdown.flavor.base import MarkdownFlavorNamefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._export.requests import PDFExportRequest, PDFRasterizationRequest@@ -44,6 +45,27 @@ HEADERS = {CODE = uri_encode_component("import marimo as mo")+def _ipynb_export_app() -> InternalApp:+ app = App()++ @app.cell()+ def result(x, y):+ z = x + y+ return (z,)++ @app.cell()+ def __():+ x = 1+ return (x,)++ @app.cell()+ def __():+ y = 1+ return (y,)++ return InternalApp(app)++class _CollectorNotWired(Exception):pass@@ -360,6 +382,91 @@ def test_export_ipynb(client: TestClient) -> None:assert response.headers["content-type"] == "text/plain; charset=utf-8"+ not DependencyManager.nbformat.has(), reason="nbformat not installed"+)+@with_session(SESSION_ID)+def test_export_ipynb_uses_requested_sort_mode(client: TestClient) -> None:+ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.app = _ipynb_export_app()++ top_down = ["z = x + y", "x = 1", "y = 1"]+ topological = ["x = 1", "y = 1", "z = x + y"]+ cases = [+ ({"download": False}, top_down),+ ({"download": False, "sortMode": "top-down"}, top_down),+ ({"download": False, "sortMode": "topological"}, topological),+ ]++ for request_body, expected_sources in cases:+ response = client.post(+ "/api/export/ipynb",+ headers=HEADERS,+ json=request_body,+ )++ assert response.status_code == 200+ cells = json.loads(response.text)["cells"]+ assert ["".join(cell["source"]) for cell in cells] == expected_sources+++ not DependencyManager.nbformat.has(), reason="nbformat not installed"+)+@with_session(SESSION_ID)+def test_export_ipynb_selects_current_session_outputs(+ client: TestClient,+) -> None:+ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ app = _ipynb_export_app()+ session.app_file_manager.app = app++ output_cell_id = next(+ cell_data.cell_id+ for cell_data in app.cell_manager.cell_data()+ if cell_data.code == "x = 1"+ )+ session.session_view.add_notification(+ CellNotification(+ cell_id=output_cell_id,+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="current output",+ ),+ )+ )++ current_output = [+ {+ "data": {"text/plain": ["current output"]},+ "metadata": {},+ "output_type": "display_data",+ }+ ]+ cases = [+ ({"download": False}, current_output),+ ({"download": False, "includeOutputs": True}, current_output),+ ({"download": False, "includeOutputs": False}, []),+ ]++ for request_body, expected_outputs in cases:+ response = client.post(+ "/api/export/ipynb",+ headers=HEADERS,+ json=request_body,+ )++ assert response.status_code == 200+ cells = json.loads(response.text)["cells"]+ output_cell = next(+ cell for cell in cells if "".join(cell["source"]) == "x = 1"+ )+ assert output_cell["outputs"] == expected_outputs++@with_read_session(SESSION_ID)def test_other_exports_dont_work_in_read(client: TestClient) -> None:response = client.post(