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: stream file-browser downloads from disk (#10247)
Kiran Gadhaved08b1c1256c8
diff --git a/frontend/src/components/editor/file-tree/download.ts b/frontend/src/components/editor/file-tree/download.tsnew file mode 100644index 0000000000..b926a82cf7--- /dev/null+++ b/frontend/src/components/editor/file-tree/download.ts@@ -0,0 +1,46 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { getRequestClient } from "@/core/network/requests";+import { getRuntimeManager } from "@/core/runtime/config";+import { isWasm } from "@/core/wasm/utils";+import { deserializeBlob } from "@/utils/blob";+import { downloadBlob, downloadByURL } from "@/utils/download";+import { type Base64String, base64ToDataURL } from "@/utils/json/base64";++/**+ * Download a workspace file by path.+ *+ * Over HTTP this navigates to a streaming download endpoint, so the+ * browser's download manager handles the transfer and no file contents+ * are buffered in memory. In WASM there is no HTTP server to stream+ * from; contents come over the pyodide bridge as base64 and are saved+ * via a Blob.+ */+export async function downloadFile(path: string, name: string): Promise<void> {+ if (!isWasm()) {+ const url = getRuntimeManager().formatNavigableHttpURL(+ "api/files/download",+ new URLSearchParams({ path }),+ );+ downloadByURL(url.toString(), name);+ return;+ }++ const details = await getRequestClient().sendFileDetails({ path });+ if (details.isBase64 && details.contents) {+ const blob = deserializeBlob(+ base64ToDataURL(+ details.contents as Base64String,+ details.mimeType || "application/octet-stream",+ ),+ );+ downloadBlob(blob, name);+ } else {+ downloadBlob(+ new Blob([details.contents || ""], {+ type: details.mimeType || "application/octet-stream",+ }),+ name,+ );+ }+}diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsxindex 57a4cc7f22..534cd094fb 100644--- a/frontend/src/components/editor/file-tree/file-explorer.tsx+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx@@ -62,16 +62,14 @@ import type { FileInfo } from "@/core/network/types";import { isWasm } from "@/core/wasm/utils";import { useAsyncData } from "@/hooks/useAsyncData";import { ErrorBanner } from "@/plugins/impl/common/error-banner";-import { deserializeBlob } from "@/utils/blob";import { cn } from "@/utils/cn";import { copyToClipboard } from "@/utils/copy";-import { downloadBlob } from "@/utils/download";-import { type Base64String, base64ToDataURL } from "@/utils/json/base64";import { openNotebook } from "@/utils/links";import type { FilePath } from "@/utils/paths";import { makeDuplicateName } from "@/utils/pathUtils";import { jotaiJsonStorage } from "@/utils/storage/jotai";import { useTreeDndManager } from "./dnd-wrapper";+import { downloadFile } from "./download";import { FileViewer } from "./file-viewer";import type { RequestingTree } from "./requesting-tree";import { openStateAtom, treeAtom } from "./state";@@ -393,7 +391,7 @@ const Show = ({};const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {- const { openFile, sendFileDetails } = useRequestClient();+ const { openFile } = useRequestClient();const disableFileDownloads = useAtomValue(disableFileDownloadsAtom);const fileType: FileIconType = node.data.isDirectory@@ -645,23 +643,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {<><DropdownMenuItemonSelect={async () => {- const details = await sendFileDetails({- path: node.data.path,- });- if (details.isBase64 && details.contents) {- const blob = deserializeBlob(- base64ToDataURL(- details.contents as Base64String,- details.mimeType || "application/octet-stream",- ),- );- downloadBlob(blob, node.data.name);- } else {- downloadBlob(- new Blob([details.contents || ""]),- node.data.name,- );- }+ await downloadFile(node.data.path, node.data.name);}}data-testid="file-explorer-download-menu-item">diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsxindex 76d80c10cf..9b4015fc72 100644--- a/frontend/src/components/editor/file-tree/file-viewer.tsx+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx@@ -21,10 +21,9 @@ import { filenameAtom } from "@/core/saving/file-state";import { isWasm } from "@/core/wasm/utils";import { useAsyncData } from "@/hooks/useAsyncData";import { ErrorBanner } from "@/plugins/impl/common/error-banner";-import { deserializeBlob } from "@/utils/blob";import { copyToClipboard } from "@/utils/copy";-import { downloadBlob, downloadByURL } from "@/utils/download";-import { type Base64String, base64ToDataURL } from "@/utils/json/base64";+import type { Base64String } from "@/utils/json/base64";+import { downloadFile } from "./download";import { FilePreviewHeader } from "./file-header";import {FileContentRenderer,@@ -121,30 +120,8 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {);}- const handleDownload = () => {- if (data.isBase64 && data.contents) {- if (isMediaMime(mimeType)) {- const dataURL = base64ToDataURL(- data.contents as Base64String,- mimeType,- );- downloadByURL(dataURL, data.file.name);- } else {- const blob = deserializeBlob(- base64ToDataURL(- data.contents as Base64String,- data.mimeType || "application/octet-stream",- ),- );- downloadBlob(blob, data.file.name);- }- return;- }-- downloadBlob(- new Blob([data.contents || internalValue], { type: mimeType }),- data.file.name,- );+ const handleDownload = async () => {+ await downloadFile(file.path, data.file.name);};const header = (diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.tsindex b9aac6d55b..7710178c8e 100644--- a/frontend/src/core/runtime/__tests__/runtime.test.ts+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts@@ -154,6 +154,70 @@ describe("RuntimeManager", () => {});});+ describe("formatNavigableHttpURL", () => {+ it("adds access_token when cross-origin with authToken", () => {+ const runtime = new RuntimeManager(+ {+ url: "https://sandbox.example.com",+ lazy: true,+ authToken: "my-secret-token",+ },+ true,+ );+ const url = runtime.formatNavigableHttpURL(+ "api/files/download",+ new URLSearchParams({ path: "/tmp/data.csv" }),+ );++ expect(url.pathname).toBe("/api/files/download");+ expect(url.searchParams.get("path")).toBe("/tmp/data.csv");+ expect(url.searchParams.get("access_token")).toBe("my-secret-token");+ });++ it("omits access_token when same-origin", () => {+ const runtime = new RuntimeManager(+ {+ url: window.location.origin,+ lazy: true,+ authToken: "my-secret-token",+ },+ true,+ );+ const url = runtime.formatNavigableHttpURL(+ "api/files/download",+ new URLSearchParams({ path: "/tmp/data.csv" }),+ );++ expect(url.searchParams.get("access_token")).toBeNull();+ expect(url.searchParams.get("path")).toBe("/tmp/data.csv");+ });++ it("omits access_token when no authToken configured", () => {+ const runtime = new RuntimeManager(+ { url: "https://sandbox.example.com", lazy: true },+ true,+ );+ const url = runtime.formatNavigableHttpURL("api/files/download");++ expect(url.searchParams.get("access_token")).toBeNull();+ });++ it("does not forward a page-inherited access_token when same-origin", () => {+ const runtime = new RuntimeManager(+ { url: window.location.origin, lazy: true },+ true,+ );+ const original = window.location.href;+ window.history.replaceState({}, "", "/?access_token=page-token");+ try {+ const url = runtime.formatNavigableHttpURL("api/files/download");+ expect(url.searchParams.get("access_token")).toBeNull();+ } finally {+ window.history.replaceState({}, "", original);+ }+ });+ });+describe("getSseURL", () => {it("should return an http(s) URL with the session ID", () => {const runtime = new RuntimeManager(mockConfig);diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.tsindex 211570f6af..1db04cc6fd 100644--- a/frontend/src/core/runtime/runtime.ts+++ b/frontend/src/core/runtime/runtime.ts@@ -86,6 +86,35 @@ export class RuntimeManager {return baseUrl;}+ /**+ * Channels that cannot send custom headers (WebSockets, and browser+ * navigations such as file downloads) carry the auth token as a query+ * param instead, but only when cross-origin. Same-origin requests+ * authenticate via the session cookie, which keeps the token out of+ * browser history and logs; cross-origin cookies are blocked by browsers,+ * so the access_token query param is the only option there.+ */+ private appendCrossOriginAuth(url: URL): URL {+ if (!this.isSameOrigin && this.config.authToken) {+ url.searchParams.set(KnownQueryParams.accessToken, this.config.authToken);+ }+ return url;+ }++ /**+ * An HTTP URL for requests made by browser navigation (e.g. anchor-click+ * downloads), which cannot attach auth headers.+ */+ formatNavigableHttpURL(path: string, searchParams?: URLSearchParams): URL {+ const url = this.formatHttpURL({ path, searchParams });+ // Drop any token inherited from the current page's query params; re-add it+ // only when cross-origin. Same-origin downloads authenticate via the+ // session cookie, so a token in the URL would needlessly leak into+ // proxy/server logs.+ url.searchParams.delete(KnownQueryParams.accessToken);+ return this.appendCrossOriginAuth(url);+ }+formatWsURL(path: string, searchParams?: URLSearchParams): URL {// We don't restrict to known query parameters, since mo.query_params()// can accept arbitrary parameters.@@ -94,16 +123,7 @@ export class RuntimeManager {searchParams,restrictToKnownQueryParams: false,});-- // For cross-origin runtimes, pass the auth token as a query parameter.- // WebSocket connections cannot send custom headers (no Authorization- // header), and cross-origin cookies are blocked by browsers, so the- // access_token query param is the only way to authenticate.- if (!this.isSameOrigin && this.config.authToken) {- url.searchParams.set(KnownQueryParams.accessToken, this.config.authToken);- }-- return asWsUrl(url.toString());+ return asWsUrl(this.appendCrossOriginAuth(url).toString());}/**diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.pyindex 8b3c24557c..673cf86f1b 100644--- a/marimo/_server/api/endpoints/file_explorer.py+++ b/marimo/_server/api/endpoints/file_explorer.py@@ -1,12 +1,16 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import mimetypes+from pathlib import Pathfrom typing import TYPE_CHECKINGfrom starlette.authentication import requiresfrom starlette.exceptions import HTTPException+from starlette.responses import FileResponsefrom marimo import _loggers+from marimo._convert.common.filename import make_download_headersfrom marimo._server.api.deps import AppStatefrom marimo._server.api.utils import parse_multipart_request, parse_requestfrom marimo._server.files.os_file_system import (@@ -38,6 +42,7 @@ from marimo._server.models.models import (SuccessResponse,)from marimo._server.router import APIRouter+from marimo._utils.http import HTTPException as MarimoHTTPExceptionif TYPE_CHECKING:from starlette.requests import Request@@ -103,6 +108,71 @@ async def file_details(return file_system.get_details(body.path)[email protected]("/download")+@requires("edit")+def download_file(+ *,+ request: Request,+) -> FileResponse:+ """+ parameters:+ - in: query+ name: path+ required: true+ schema:+ type: string+ description: Path of the file to download+ responses:+ 200:+ description: Stream the file as an attachment+ content:+ application/octet-stream:+ schema:+ type: string+ format: binary+ 400:+ description: Path is missing or is a directory+ 403:+ description: File downloads are disabled+ 404:+ description: File not found+ """+ app_state = AppState(request)+ server_config = app_state.config_manager.get_config().get("server", {})+ # This endpoint serves raw file bytes, so its errors raise marimo's+ # HTTPException, whose status code reaches the client unchanged. A Starlette+ # 403 is globally converted to a 401 to prompt re-authentication; a+ # downloads-disabled policy cannot be satisfied by re-auth, so it stays 403.+ if server_config.get("disable_file_downloads", False):+ raise MarimoHTTPException(+ status_code=403, detail="File downloads are disabled"+ )++ path = app_state.query_params("path")+ if not path:+ raise MarimoHTTPException(status_code=400, detail="Missing path")+ file_path = Path(path)+ if file_path.is_dir():+ raise MarimoHTTPException(+ status_code=400, detail="Cannot download a directory"+ )+ if not file_path.is_file():+ raise MarimoHTTPException(status_code=404, detail="File not found")++ media_type = (+ mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"+ )+ return FileResponse(+ file_path,+ media_type=media_type,+ headers={+ **make_download_headers(file_path.name),+ "X-Content-Type-Options": "nosniff",+ "Cache-Control": "no-store",+ },+ )++@router.post("/create")@requires("edit")async def create_file_or_directory(diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex cac0fa362c..d28251ad5c 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -6478,6 +6478,29 @@ paths:schema:$ref: '#/components/schemas/FileDeleteResponse'description: Delete a file or directory+ /api/files/download:+ get:+ parameters:+ - description: Path of the file to download+ in: query+ name: path+ required: true+ schema:+ type: string+ responses:+ 200:+ content:+ application/octet-stream:+ schema:+ format: binary+ type: string+ description: Stream the file as an attachment+ 400:+ description: Path is missing or is a directory+ 403:+ description: File downloads are disabled+ 404:+ description: File not found/api/files/file_details:post:requestBody:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 82659a5519..8633bcced8 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -1205,6 +1205,65 @@ export interface paths {patch?: never;trace?: never;};+ "/api/files/download": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get: {+ parameters: {+ query: {+ /** @description Path of the file to download */+ path: string;+ };+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Stream the file as an attachment */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/octet-stream": string;+ };+ };+ /** @description Path is missing or is a directory */+ 400: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description File downloads are disabled */+ 403: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description File not found */+ 404: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ };+ };+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/files/file_details": {parameters: {query?: never;diff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.pyindex f54869bbca..a78e457103 100644--- a/tests/_server/api/endpoints/test_file_explorer.py+++ b/tests/_server/api/endpoints/test_file_explorer.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport osfrom pathlib import Pathfrom tempfile import TemporaryDirectory-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, castimport pytest@@ -14,6 +14,9 @@ from tests._server.mocks import get_session_manager, token_headerif TYPE_CHECKING:from starlette.testclient import TestClient+ from marimo._config.config import PartialMarimoConfig+ from marimo._config.manager import UserConfigManager+HEADERS = {**token_header("fake-token"),}@@ -449,3 +452,89 @@ def test_search_files_with_directory_and_file_filters(assert response.status_code == 200, response.textdata_no_filter = response.json()assert data_no_filter["totalFound"] == 3+++def test_download_file_text(client: TestClient) -> None:+ path = os.path.join(test_dir, "download_me.txt")+ with open(path, "w") as f:+ f.write("stream me")+ response = client.get(+ "/api/files/download", headers=HEADERS, params={"path": path}+ )+ assert response.status_code == 200, response.text+ assert response.text == "stream me"+ disposition = response.headers["content-disposition"]+ assert disposition.startswith("attachment")+ assert "download_me.txt" in disposition+ assert response.headers["x-content-type-options"] == "nosniff"+ os.remove(path)+++def test_download_file_binary(client: TestClient) -> None:+ raw_bytes = b"\xff\xfe\xfd\x00\x80marimo"+ path = os.path.join(test_dir, "download_me.bin")+ with open(path, "wb") as f:+ f.write(raw_bytes)+ response = client.get(+ "/api/files/download", headers=HEADERS, params={"path": path}+ )+ assert response.status_code == 200, response.text+ assert response.content == raw_bytes+ assert response.headers["content-type"] == "application/octet-stream"+ os.remove(path)+++def test_download_file_unicode_name(client: TestClient) -> None:+ path = os.path.join(test_dir, "émoji 🎉.txt")+ with open(path, "w", encoding="utf-8") as f:+ f.write("unicode")+ response = client.get(+ "/api/files/download", headers=HEADERS, params={"path": path}+ )+ assert response.status_code == 200, response.text+ disposition = response.headers["content-disposition"]+ assert disposition.startswith("attachment")+ assert "filename*=UTF-8''" in disposition+ os.remove(path)+++def test_download_directory_is_rejected(client: TestClient) -> None:+ response = client.get(+ "/api/files/download", headers=HEADERS, params={"path": test_dir}+ )+ assert response.status_code == 400, response.text+++def test_download_missing_file(client: TestClient) -> None:+ response = client.get(+ "/api/files/download",+ headers=HEADERS,+ params={"path": os.path.join(test_dir, "does_not_exist.txt")},+ )+ assert response.status_code == 404, response.text+++def test_download_requires_path_param(client: TestClient) -> None:+ response = client.get("/api/files/download", headers=HEADERS)+ assert response.status_code == 400, response.text+++def test_download_requires_auth(client: TestClient) -> None:+ response = client.get(+ "/api/files/download", params={"path": test_file_path}+ )+ assert response.status_code == 401, response.text+++def test_download_disabled_by_config(+ client: TestClient, user_config_manager: UserConfigManager+) -> None:+ user_config_manager.save_config(+ cast(+ "PartialMarimoConfig", {"server": {"disable_file_downloads": True}}+ )+ )+ response = client.get(+ "/api/files/download", headers=HEADERS, params={"path": test_file_path}+ )+ assert response.status_code == 403, response.text