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: respect include_code setting for code downloads in run mode, and show "Download as .py" (#7642)
Myles Scolnick31707b3d52ba
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex 1d699aebce..3542fea22a 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -4,6 +4,7 @@ import { useAtomValue } from "jotai";import {Check,Code2Icon,+ CodeIcon,FolderDownIcon,ImageIcon,MoreHorizontalIcon,@@ -34,12 +35,14 @@ import type { OutputMessage } from "@/core/kernel/messages";import { showCodeInRunModeAtom } from "@/core/meta/state";import { isErrorMime } from "@/core/mime";import { type AppMode, kioskModeAtom } from "@/core/mode";+import { useRequestClient } from "@/core/network/requests";import type { CellConfig } from "@/core/network/types";import { downloadAsHTML } from "@/core/static/download-html";import { isStaticNotebook } from "@/core/static/static-state";import { isWasm } from "@/core/wasm/utils";import { cn } from "@/utils/cn";-import { downloadHTMLAsImage } from "@/utils/download";+import { downloadBlob, downloadHTMLAsImage } from "@/utils/download";+import { Filenames } from "@/utils/filenames";import { FloatingOutline } from "../../chrome/panels/outline/floating-outline";import { cellDomProps } from "../../common";import type { ICellRendererPlugin, ICellRendererProps } from "../types";@@ -175,6 +178,8 @@ const ActionButtons: React.FC<{showCode: boolean;onToggleShowCode: () => void;}> = ({ canShowCode, showCode, onToggleShowCode }) => {+ const { readCode } = useRequestClient();+const handleDownloadAsPNG = async () => {const app = document.getElementById("App");if (!app) {@@ -191,6 +196,14 @@ const ActionButtons: React.FC<{await downloadAsHTML({ filename: document.title, includeCode: true });};+ const handleDownloadAsPython = async () => {+ const code = await readCode();+ downloadBlob(+ new Blob([code.contents], { type: "text/plain" }),+ Filenames.toPY(document.title),+ );+ };+const isStatic = isStaticNotebook();const actions: React.ReactNode[] = [];@@ -219,7 +232,24 @@ const ActionButtons: React.FC<{<FolderDownIcon className="mr-2" size={14} strokeWidth={1.5} />Download as HTML</DropdownMenuItem>,- <DropdownMenuSeparator key="download-html-separator" />,+ );++ // Only show download as Python if code is available+ if (canShowCode) {+ actions.push(+ <DropdownMenuItem+ onSelect={handleDownloadAsPython}+ data-testid="notebook-action-download-python"+ key="download-python"+ >+ <CodeIcon className="mr-2" size={14} strokeWidth={1.5} />+ Download as .py+ </DropdownMenuItem>,+ );+ }++ actions.push(+ <DropdownMenuSeparator key="download-separator" />,<DropdownMenuItemonSelect={handleDownloadAsPNG}data-testid="notebook-action-download-png"diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex faede0e381..edf549e6f1 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -24,7 +24,6 @@ from marimo._server.models.export import ()from marimo._server.models.models import SuccessResponsefrom marimo._server.router import APIRouter-from marimo._session.model import SessionModefrom marimo._utils.http import HTTPStatusif TYPE_CHECKING:@@ -71,8 +70,8 @@ async def export_as_html(detail="File must have a name before exporting",)- # Only include the code and console if we are in edit mode- if app_state.mode != SessionMode.EDIT:+ # Only include the code if allowed (edit mode or include_code=True)+ if not app_state.session_manager.should_send_code_to_frontend():body.include_code = Falsehtml, filename = Exporter().export_as_html(diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.pyindex 412abd55cf..335c5f7275 100644--- a/marimo/_server/api/endpoints/files.py+++ b/marimo/_server/api/endpoints/files.py@@ -35,7 +35,7 @@ router = APIRouter()@router.post("/read_code")-@requires("edit")+@requires("read")async def read_code(*,request: Request,@@ -50,8 +50,18 @@ async def read_code($ref: "#/components/schemas/ReadCodeResponse"400:description: File must be saved before downloading+ 403:+ description: Code is not available in run mode"""app_state = AppState(request)++ # Check if code should be visible (edit mode or include_code=True)+ if not app_state.session_manager.should_send_code_to_frontend():+ raise HTTPException(+ status_code=HTTPStatus.FORBIDDEN,+ detail="Code is not available",+ )+session = app_state.require_current_session()if not session.app_file_manager.path:diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 22e7edeef3..3754bde4fe 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -4985,6 +4985,8 @@ paths:description: Read the code from the server400:description: File must be saved before downloading+ 403:+ description: Code is not available in run mode/api/kernel/rename:post:requestBody:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex c02eeb15fd..e7b91a78d9 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -1696,6 +1696,13 @@ export interface paths {};content?: never;};+ /** @description Code is not available in run mode */+ 403: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };};};delete?: never;diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex 9ba21d585a..929af8b31b 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -116,12 +116,38 @@ def test_export_html_file_not_found(client: TestClient) -> None:assert "<marimo-code hidden=" in response.text-# Read session forces empty code-@with_read_session(SESSION_ID)+# Read session with include_code=True allows code to be included+@with_read_session(SESSION_ID, include_code=True)+def test_export_html_with_code_in_read_with_include_code(+ client: TestClient,+) -> None:+ """Test that HTML export includes code in run mode when include_code=True."""+ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.filename = "test.py"+ response = client.post(+ "/api/export/html",+ headers=HEADERS,+ json={+ "download": False,+ "files": [],+ "includeCode": True,+ },+ )+ body = response.text+ # Code should be included when include_code=True+ assert '<marimo-code hidden=""></marimo-code>' not in body+ assert CODE in body+++# Read session without include_code forces empty code+@with_read_session(SESSION_ID, include_code=False)def test_export_html_no_code_in_read(client: TestClient) -> None:+ """Test that HTML export excludes code in run mode when include_code=False."""session = get_session_manager(client).get_session(SESSION_ID)assert sessionsession.app_file_manager.filename = "test.py"+ # Even if request asks for code, it should be deniedresponse = client.post("/api/export/html",headers=HEADERS,diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex 56d3499918..0db75ce036 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -16,6 +16,7 @@ from marimo._utils.platform import is_windowsfrom tests._server.conftest import get_session_managerfrom tests._server.mocks import (token_header,+ with_read_session,with_session,with_websocket_session,)@@ -73,6 +74,32 @@ def test_read_code(client: TestClient) -> None:assert "import marimo" in response.json()["contents"]+@with_read_session(SESSION_ID, include_code=True)+def test_read_code_in_run_mode_with_include_code(client: TestClient) -> None:+ """Test read_code works in run mode when include_code=True."""+ response = client.post(+ "/api/kernel/read_code",+ headers=HEADERS,+ json={},+ )+ assert response.status_code == 200, response.text+ assert "import marimo" in response.json()["contents"]+++@with_read_session(SESSION_ID, include_code=False)+def test_read_code_in_run_mode_without_include_code(+ client: TestClient,+) -> None:+ """Test read_code is not accessible in run mode when include_code=False."""+ response = client.post(+ "/api/kernel/read_code",+ headers=HEADERS,+ json={},+ )+ # Should be denied 403 (forbidden)+ assert response.status_code == 403++@pytest.mark.flaky(reruns=5)@with_session(SESSION_ID)def test_save_file(client: TestClient) -> None:diff --git a/tests/_server/mocks.py b/tests/_server/mocks.pyindex 9b362e5dda..39bcbcc890 100644--- a/tests/_server/mocks.py+++ b/tests/_server/mocks.py@@ -188,8 +188,14 @@ def with_websocket_session(def with_read_session(session_id: str,+ include_code: bool = True,) -> Callable[[Callable[..., None]], Callable[..., None]]:- """Decorator to create a session and close it after the test"""+ """Decorator to create a read session and close it after the test.++ Args:+ session_id: The session ID to use+ include_code: Whether code should be visible in run mode (default True)+ """def decorator(func: Callable[..., None]) -> Callable[..., None]:def wrapper(client: TestClient) -> None:@@ -204,9 +210,13 @@ def with_read_session(assert data# Just change the mode here, otherwise our tests will run,# in threads+ original_mode = session_manager.mode+ original_include_code = session_manager.include_codesession_manager.mode = SessionMode.RUN+ session_manager.include_code = include_codefunc(client)- session_manager.mode = SessionMode.EDIT+ session_manager.mode = original_mode+ session_manager.include_code = original_include_codefinally:# Always shutdown, even if there's an errorclient.post(