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
Bound file previews and offer download for unpreviewable files (#10277)
Kiran Gadhavedc57e9ff3a79
diff --git a/frontend/src/components/editor/file-tree/__tests__/file-render-mode.test.ts b/frontend/src/components/editor/file-tree/__tests__/file-render-mode.test.tsnew file mode 100644index 0000000000..aed00874f1--- /dev/null+++ b/frontend/src/components/editor/file-tree/__tests__/file-render-mode.test.ts@@ -0,0 +1,27 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import { getFileRenderMode } from "../file-render-mode";++describe("getFileRenderMode", () => {+ it.each([+ ["text/plain", false, "text"],+ ["text/x-rust", false, "text"],+ ["application/json", false, "text"],+ ["application/xml", false, "text"],+ ["text/csv", false, "csv"],+ ["image/png", true, "media"],+ ["video/mp4", true, "media"],+ ["application/pdf", true, "media"],+ ["application/x-apple-diskimage", true, "unsupported"],+ ["application/zip", true, "unsupported"],+ ["application/octet-stream", false, "unsupported"],+ [null, false, "text"],+ [null, true, "unsupported"],+ ] as const)(+ "maps %s with isBase64=%s to %s",+ (mimeType, isBase64, expected) => {+ expect(getFileRenderMode(mimeType, isBase64)).toBe(expected);+ },+ );+});diff --git a/frontend/src/components/editor/file-tree/__tests__/file-viewer.test.tsx b/frontend/src/components/editor/file-tree/__tests__/file-viewer.test.tsxnew file mode 100644index 0000000000..13a5f3df7a--- /dev/null+++ b/frontend/src/components/editor/file-tree/__tests__/file-viewer.test.tsx@@ -0,0 +1,150 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { Provider } from "jotai";+import type React from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { MockRequestClient } from "@/__mocks__/requests";+import { TooltipProvider } from "@/components/ui/tooltip";+import { requestClientAtom } from "@/core/network/requests";+import type { FileDetailsResponse, FileInfo } from "@/core/network/types";+import { store } from "@/core/state/jotai";+import { FileViewer, MAX_FILE_PREVIEW_BYTES } from "../file-viewer";++vi.mock("@/plugins/impl/code/LazyAnyLanguageCodeMirror", () => ({+ LazyAnyLanguageCodeMirror: ({+ value,+ onChange,+ }: {+ value?: string;+ onChange?: (value: string) => void;+ }) => (+ <textarea+ data-testid="code-editor"+ value={value ?? ""}+ onChange={(evt) => onChange?.(evt.target.value)}+ />+ ),+}));++vi.mock("@/core/wasm/utils", () => ({ isWasm: () => false }));++const wrapper = ({ children }: { children: React.ReactNode }) => (+ <Provider store={store}>+ <TooltipProvider>{children}</TooltipProvider>+ </Provider>+);++const file: FileInfo = {+ id: "/workspace/installer.dmg",+ path: "/workspace/installer.dmg",+ name: "installer.dmg",+ isDirectory: false,+ isMarimoFile: false,+ size: 20 * 1024 * 1024,+};++function renderViewer(response: FileDetailsResponse) {+ const client = MockRequestClient.create({+ sendFileDetails: vi.fn().mockResolvedValue(response),+ });+ store.set(requestClientAtom, client);+ render(<FileViewer file={file} onOpenNotebook={vi.fn()} />, { wrapper });+ return client;+}++describe("FileViewer bounded previews", () => {+ beforeEach(() => {+ store.set(requestClientAtom, null);+ });++ it("requests a bounded preview and shows oversized metadata", async () => {+ const client = renderViewer({+ file,+ contents: null,+ mimeType: "application/x-apple-diskimage",+ isBase64: false,+ isTooLarge: true,+ });++ expect(await screen.findByText(/too large to preview/i)).toBeVisible();+ expect(screen.getByText("20 MB")).toBeVisible();+ expect(screen.getByRole("button", { name: /download/i })).toBeVisible();+ expect(screen.queryByTestId("code-editor")).not.toBeInTheDocument();+ expect(client.sendFileDetails).toHaveBeenCalledWith({+ path: file.path,+ maxBytes: MAX_FILE_PREVIEW_BYTES,+ });+ });++ it("shows unsupported metadata with a download action, not base64 text", async () => {+ renderViewer({+ file: { ...file, size: 4 },+ contents: "AAEC",+ mimeType: "application/x-apple-diskimage",+ isBase64: true,+ isTooLarge: false,+ });++ expect(await screen.findByText(/cannot be previewed/i)).toBeVisible();+ expect(screen.getByRole("button", { name: /download/i })).toBeVisible();+ expect(screen.queryByTestId("code-editor")).not.toBeInTheDocument();+ });++ it("continues to render small text files", async () => {+ renderViewer({+ file: { ...file, name: "notes.txt", size: 5 },+ contents: "hello",+ mimeType: "text/plain",+ isBase64: false,+ isTooLarge: false,+ });++ await waitFor(() => {+ expect(screen.getByTestId("code-editor")).toBeInTheDocument();+ });+ expect(screen.queryByText(/too large to preview/i)).not.toBeInTheDocument();+ });++ it("preserves edits to an initially empty text file across remount", async () => {+ const emptyFile: FileInfo = {+ id: "/workspace/empty.txt",+ path: "/workspace/empty.txt",+ name: "empty.txt",+ isDirectory: false,+ isMarimoFile: false,+ size: 0,+ };+ const response: FileDetailsResponse = {+ file: emptyFile,+ contents: "",+ mimeType: "text/plain",+ isBase64: false,+ isTooLarge: false,+ };+ const client = MockRequestClient.create({+ sendFileDetails: vi.fn().mockResolvedValue(response),+ });+ store.set(requestClientAtom, client);++ const { unmount } = render(+ <FileViewer file={emptyFile} onOpenNotebook={vi.fn()} />,+ { wrapper },+ );++ const editor =+ await screen.findByTestId<HTMLTextAreaElement>("code-editor");+ fireEvent.change(editor, { target: { value: "draft" } });+ unmount();++ render(<FileViewer file={emptyFile} onOpenNotebook={vi.fn()} />, {+ wrapper,+ });++ const reopened =+ await screen.findByTestId<HTMLTextAreaElement>("code-editor");+ await waitFor(() => {+ expect(reopened.value).toBe("draft");+ });+ });+});diff --git a/frontend/src/components/editor/file-tree/file-preview-metadata.tsx b/frontend/src/components/editor/file-tree/file-preview-metadata.tsxnew file mode 100644index 0000000000..7f43fcb004--- /dev/null+++ b/frontend/src/components/editor/file-tree/file-preview-metadata.tsx@@ -0,0 +1,51 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { DownloadIcon } from "lucide-react";+import { useLocale } from "react-aria";+import { Button } from "@/components/ui/button";+import type { FileInfo } from "@/core/network/types";+import { formatBytes } from "@/utils/formatting";++interface Props {+ file: FileInfo;+ mimeType: string;+ message: string;+ onDownload?: () => void;+}++export const FilePreviewMetadata = ({+ file,+ mimeType,+ message,+ onDownload,+}: Props) => {+ const { locale } = useLocale();+ return (+ <div className="p-4 text-sm">+ <div className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2">+ <span className="text-muted-foreground font-medium">Path</span>+ <span className="font-mono text-xs break-all">{file.path}</span>+ <span className="text-muted-foreground font-medium">Type</span>+ <span>{mimeType}</span>+ {file.size != null && (+ <>+ <span className="text-muted-foreground font-medium">Size</span>+ <span>{formatBytes(file.size, locale)}</span>+ </>+ )}+ </div>+ <div className="mt-4 text-muted-foreground italic">{message}</div>+ {onDownload && (+ <Button+ variant="outline"+ size="sm"+ className="mt-4"+ onClick={onDownload}+ >+ <DownloadIcon className="h-3.5 w-3.5 mr-2" />+ Download+ </Button>+ )}+ </div>+ );+};diff --git a/frontend/src/components/editor/file-tree/file-render-mode.ts b/frontend/src/components/editor/file-tree/file-render-mode.tsnew file mode 100644index 0000000000..8ccd50a845--- /dev/null+++ b/frontend/src/components/editor/file-tree/file-render-mode.ts@@ -0,0 +1,32 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { isMediaMime, MIME_TO_LANGUAGE } from "./renderers";++export type FileRenderMode = "text" | "csv" | "media" | "unsupported";++export function getFileRenderMode(+ mimeType: string | null | undefined,+ isBase64: boolean | undefined,+): FileRenderMode {+ const mime = mimeType || "text/plain";++ if (isMediaMime(mime)) {+ return "media";+ }+ if (isBase64) {+ return "unsupported";+ }+ if (mime === "text/csv") {+ return "csv";+ }+ if (+ mime.startsWith("text/") ||+ (mime !== "default" && mime in MIME_TO_LANGUAGE)+ ) {+ return "text";+ }+ if (mimeType == null) {+ return "text";+ }+ return "unsupported";+}diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsxindex 9b4015fc72..f0ad01e051 100644--- a/frontend/src/components/editor/file-tree/file-viewer.tsx+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx@@ -25,11 +25,11 @@ import { copyToClipboard } from "@/utils/copy";import type { Base64String } from "@/utils/json/base64";import { downloadFile } from "./download";import { FilePreviewHeader } from "./file-header";-import {- FileContentRenderer,- isMediaMime,- MIME_TO_LANGUAGE,-} from "./renderers";+import { FilePreviewMetadata } from "./file-preview-metadata";+import { getFileRenderMode } from "./file-render-mode";+import { FileContentRenderer } from "./renderers";++export const MAX_FILE_PREVIEW_BYTES = 10 * 1024 * 1024;interface Props {file: FileInfo;@@ -50,9 +50,15 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {const { data, isPending, error, setData, refetch } =useAsyncData(async () => {- const details = await sendFileDetails({ path: file.path });- const contents = details.contents || "";- setInternalValue(unsavedContentsForFile.get(file.path) || contents);+ const details = await sendFileDetails({+ path: file.path,+ maxBytes: MAX_FILE_PREVIEW_BYTES,+ });+ const mode = getFileRenderMode(details.mimeType, details.isBase64);+ if (!details.isTooLarge && mode === "text") {+ const contents = details.contents || "";+ setInternalValue(unsavedContentsForFile.get(file.path) ?? contents);+ }return details;}, [file.path]);@@ -72,13 +78,19 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {);};- // On file change or unmount, save the unsaved contents+ // On file change or unmount, save the unsaved contents. Only editable text+ // previews participate in editor state; oversized and non-text responses+ // carry no draft to preserve.// We use a ref for internalValue so we don't call this effect on each keystrokeconst internalValueRef = useRef<string>(internalValue);internalValueRef.current = internalValue;useEffect(() => {return () => {- if (!data?.contents) {+ if (+ data?.contents == null ||+ data.isTooLarge ||+ getFileRenderMode(data.mimeType, data.isBase64) !== "text"+ ) {return;}const draft = internalValueRef.current;@@ -88,7 +100,13 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {unsavedContentsForFile.set(file.path, draft);}};- }, [file.path, data?.contents]);+ }, [+ file.path,+ data?.contents,+ data?.isTooLarge,+ data?.mimeType,+ data?.isBase64,+ ]);if (error) {return <ErrorBanner error={error} />;@@ -99,7 +117,10 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {}const mimeType = data.mimeType || "text/plain";- const isEditable = mimeType in MIME_TO_LANGUAGE;+ const renderMode = getFileRenderMode(data.mimeType, data.isBase64);+ const isText = renderMode === "text";+ const isCsv = renderMode === "csv";+ const isMedia = renderMode === "media";const isActiveNotebook =currentNotebookFilename &&data.file.isMarimoFile &&@@ -108,22 +129,27 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {// but this is an okay heuristic for now.file.path.endsWith(`/${currentNotebookFilename}`));- if (!data.contents && !isEditable) {- // Show details instead of contents- return (- <div className="grid grid-cols-2 gap-2 p-6">- <div className="font-bold text-muted-foreground">Name</div>- <div>{data.file.name}</div>- <div className="font-bold text-muted-foreground">Type</div>- <div>{mimeType}</div>- </div>- );- }-const handleDownload = async () => {await downloadFile(file.path, data.file.name);};+ const saveKeymapExtension = keymap.of([+ {+ key: hotkeys.getHotkey("global.save").key,+ stopPropagation: true,+ run: () => {+ if (internalValue !== data.contents) {+ void handleSaveFile();+ return true;+ }+ return false;+ },+ },+ ]);++ // Defined before the metadata-only returns so refresh, download, and+ // open-notebook stay available while edit-only copy/save are withheld from+ // non-text previews.const header = (<FilePreviewHeaderfilename={data.file.name}@@ -142,7 +168,7 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {</Button></Tooltip>)}- {!isMediaMime(mimeType) && (+ {isText && (<><Tooltip content="Copy contents to clipboard"><Button@@ -172,8 +198,23 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {/>);- const isMedia = isMediaMime(mimeType);- const isText = !isMedia && mimeType !== "text/csv";+ if (data.isTooLarge || renderMode === "unsupported") {+ return (+ <>+ {header}+ <FilePreviewMetadata+ file={data.file}+ mimeType={mimeType}+ message={+ data.isTooLarge+ ? "File is too large to preview."+ : "This file type cannot be previewed."+ }+ onDownload={disableFileDownloads ? undefined : handleDownload}+ />+ </>+ );+ }const warningBanner = isText && isActiveNotebook && (<Alert variant="warning" className="rounded-none">@@ -192,35 +233,20 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {<FileContentRenderermimeType={mimeType}contents={- isMedia- ? undefined- : isText- ? internalValue- : (data.contents ?? undefined)+ isText+ ? internalValue+ : isCsv+ ? (data.contents ?? undefined)+ : undefined}mediaSource={- isMedia+ isMedia && data.contents? { base64: data.contents as Base64String, mime: mimeType }: undefined}readOnly={!isText}- onChange={setInternalValue}- extensions={[- // Command S for save- keymap.of([- {- key: hotkeys.getHotkey("global.save").key,- stopPropagation: true,- run: () => {- if (internalValue !== data.contents) {- handleSaveFile();- return true;- }- return false;- },- },- ]),- ]}+ onChange={isText ? setInternalValue : undefined}+ extensions={isText ? [saveKeymapExtension] : []}/></>);diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex d208eb38bc..feb4f5c7eb 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -191,7 +191,9 @@ export interface EditRequests {request: FileMoveRequest,) => Promise<FileMoveResponse>;sendUpdateFile: (request: FileUpdateRequest) => Promise<FileUpdateResponse>;- sendFileDetails: (request: { path: string }) => Promise<FileDetailsResponse>;+ sendFileDetails: (+ request: FileDetailsRequest,+ ) => Promise<FileDetailsResponse>;// Homepage requestsopenTutorial: (request: OpenTutorialRequest) => Promise<MarimoFile>;getRecentFiles: () => Promise<RecentFilesResponse>;diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 9818c4a66e..d0617a002c 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -308,7 +308,10 @@ class PyodideBridge:request: str,) -> str:body = self._parse(request, FileDetailsRequest)- response = self.file_system.get_details(body.path)+ response = self.file_system.get_details(+ body.path,+ max_bytes=body.max_bytes,+ )return self._dump(response)def create_file_or_directory(diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.pyindex 673cf86f1b..29f20b9d31 100644--- a/marimo/_server/api/endpoints/file_explorer.py+++ b/marimo/_server/api/endpoints/file_explorer.py@@ -105,7 +105,14 @@ async def file_details($ref: "#/components/schemas/FileDetailsResponse""""body = await parse_request(request, cls=FileDetailsRequest)- return file_system.get_details(body.path)+ if body.max_bytes is not None and body.max_bytes < 0:+ raise HTTPException(+ status_code=400,+ detail="maxBytes must be non-negative",+ )+ # Only bound the read when the caller asks for it. The file preview is+ # the sole caller that sets a limit; other consumers read in full.+ return file_system.get_details(body.path, max_bytes=body.max_bytes)@router.get("/download")@@ -239,8 +246,7 @@ async def delete_file_or_directory("""body = await parse_request(request, cls=FileDeleteRequest)try:- # TODO: Refactor this side-effect based validation to a dedicated validation.- file_system.get_details(body.path)+ file_system.get_info(body.path)success = file_system.delete_file_or_directory(body.path)return FileDeleteResponse(success=success)except Exception as e:@@ -270,8 +276,7 @@ async def copy_file_or_directory("""body = await parse_request(request, cls=FileCopyRequest)try:- # TODO: Refactor this side-effect based validation to a dedicated validation.- file_system.get_details(body.path)+ file_system.get_info(body.path)info = file_system.copy_file_or_directory(body.path, body.new_path)return FileCopyResponse(success=True, info=info)except Exception as e:@@ -301,8 +306,7 @@ async def move_file_or_directory("""body = await parse_request(request, cls=FileMoveRequest)try:- # TODO: Refactor this side-effect based validation to a dedicated validation.- file_system.get_details(body.path)+ file_system.get_info(body.path)info = file_system.move_file_or_directory(body.path, body.new_path)return FileMoveResponse(success=True, info=info)except Exception as e:@@ -333,8 +337,7 @@ async def update_file(app_state = AppState(request)body = await parse_request(request, cls=FileUpdateRequest)try:- # TODO: Refactor this side-effect based validation to a dedicated validation.- file_system.get_details(body.path)+ file_system.get_info(body.path)info = file_system.update_file(body.path, body.contents)# Handle marimo notebook reload if there's an active session@@ -369,8 +372,7 @@ async def open_file("""body = await parse_request(request, cls=FileOpenRequest)try:- # TODO: Refactor this side-effect based validation to a dedicated validation.- file_system.get_details(body.path)+ file_system.get_info(body.path)success = file_system.open_in_editor(body.path, body.line_number)return SuccessResponse(success=success)except Exception as e:diff --git a/marimo/_server/files/file_system.py b/marimo/_server/files/file_system.pyindex 61e5dca771..e861caedd1 100644--- a/marimo/_server/files/file_system.py+++ b/marimo/_server/files/file_system.py@@ -16,14 +16,24 @@ class FileSystem(ABC):def list_files(self, path: str) -> list[FileInfo]:"""List files and directories in a given path."""+ @abstractmethod+ def get_info(self, path: str) -> FileInfo:+ """Get metadata without materializing file contents for a response."""+@abstractmethoddef get_details(self,path: str,encoding: str | None = None,contents: str | None = None,+ max_bytes: int | None = None,) -> FileDetailsResponse:- """Get details of a specific file or directory. If contents is provided, use it instead of reading from disk."""+ """Get file details and optionally bound content reads.++ If `contents` is provided, use it instead of reading from disk. If+ `max_bytes` is provided and disk content exceeds it, return metadata+ with `is_too_large=True` and no contents.+ """@abstractmethoddef open_file(self, path: str, encoding: str | None = None) -> str | bytes:diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex 8d121d375c..9ead16fed1 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -93,6 +93,7 @@ class OSFileSystem(FileSystem):is_marimo_file=not is_directoryand self._is_marimo_file(entry.path),last_modified=entry_stat.st_mtime,+ size=None if is_directory else entry_stat.st_size,)if is_directory:folders.append(info)@@ -105,7 +106,7 @@ class OSFileSystem(FileSystem):files, key=natural_sort_file)- def _get_file_info(self, path: str) -> FileInfo:+ def get_info(self, path: str) -> FileInfo:stat = os.stat(path)is_directory = os.path.isdir(path)return FileInfo(@@ -115,6 +116,7 @@ class OSFileSystem(FileSystem):is_directory=is_directory,is_marimo_file=not is_directory and self._is_marimo_file(path),last_modified=stat.st_mtime,+ size=None if is_directory else stat.st_size,)def get_details(@@ -122,27 +124,54 @@ class OSFileSystem(FileSystem):path: str,encoding: str | None = None,contents: str | None = None,+ max_bytes: int | None = None,) -> FileDetailsResponse:- file_info = self._get_file_info(path)+ if max_bytes is not None and max_bytes < 0:+ raise ValueError("max_bytes must be non-negative")++ file_info = self.get_info(path)+ mime_type = mimetypes.guess_type(path)[0]is_base64 = False- actual_contents: str | bytes | None+ is_too_large = False+ actual_contents: str | Noneif file_info.is_directory:actual_contents = Noneelif contents is not None:actual_contents = contents- else:- actual_contents = self.open_file(path, encoding=encoding)- if isinstance(actual_contents, bytes):- actual_contents = base64.b64encode(actual_contents).decode(- "utf-8"- )+ elif (+ max_bytes is not None+ and file_info.size is not None+ and file_info.size > max_bytes+ ):+ actual_contents = None+ is_too_large = True+ elif max_bytes is None:+ opened = self.open_file(path, encoding=encoding)+ if isinstance(opened, bytes):+ actual_contents = base64.b64encode(opened).decode("utf-8")is_base64 = True- mime_type = mimetypes.guess_type(path)[0]+ else:+ actual_contents = opened+ else:+ file_path = Path(path)+ with file_path.open("rb") as file:+ raw = file.read(max_bytes + 1)+ if len(raw) > max_bytes:+ actual_contents = None+ is_too_large = True+ else:+ try:+ actual_contents = raw.decode(encoding or "utf-8")+ except UnicodeDecodeError:+ actual_contents = base64.b64encode(raw).decode("utf-8")+ is_base64 = True+return FileDetailsResponse(file=file_info,contents=actual_contents,mime_type=mime_type,is_base64=is_base64,+ is_too_large=is_too_large,)def _is_marimo_file(self, path: str) -> bool:@@ -205,19 +234,10 @@ class OSFileSystem(FileSystem):else:notebook_code = converter.to_py()full_path.write_text(notebook_code, encoding="utf-8")- contents = notebook_code.encode("utf-8")else:full_path.parent.mkdir(parents=True, exist_ok=True)full_path.write_bytes(contents or b"")- # encoding latin-1 to get an invertible representation of the- # bytes as a string ...- return self.get_details(- str(full_path),- encoding="latin-1",- contents=(- contents.decode("latin-1") if contents is not None else None- ),- ).file+ return self.get_info(str(full_path))async def stream_create_file(self,@@ -272,9 +292,7 @@ class OSFileSystem(FileSystem):passraise- # `get_details` would re-read the file (and base64-encode binary),- # defeating the streaming win.- return self._get_file_info(str(full_path))+ return self.get_info(str(full_path))def delete_file_or_directory(self, path: str) -> bool:if os.path.isdir(path):@@ -291,7 +309,7 @@ class OSFileSystem(FileSystem):shutil.copytree(path, new_path)else:shutil.copy2(path, new_path)- return self.get_details(new_path).file+ return self.get_info(new_path)def move_file_or_directory(self, path: str, new_path: str) -> FileInfo:if not _is_allowed_paths(path, new_path):@@ -300,12 +318,12 @@ class OSFileSystem(FileSystem):if os.path.exists(new_path):raise ValueError(f"Destination path {new_path} already exists")safe_move(path, new_path)- return self.get_details(new_path).file+ return self.get_info(new_path)def update_file(self, path: str, contents: str) -> FileInfo:file_path = Path(path)file_path.write_text(contents, encoding="utf-8")- return self.get_details(path, contents=contents).file+ return self.get_info(path)def search(self,@@ -405,6 +423,9 @@ class OSFileSystem(FileSystem):# This can be expensive, so we don't do it on searchis_marimo_file=False,last_modified=entry_stat.st_mtime,+ size=None+ if is_directory+ else entry_stat.st_size,)results.append(file_info)diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.pyindex c0dfd5ed9d..1397dfe985 100644--- a/marimo/_server/models/files.py+++ b/marimo/_server/models/files.py@@ -18,6 +18,7 @@ class FileInfo(msgspec.Struct, rename="camel"):is_directory: boolis_marimo_file: boollast_modified: float | None = None+ size: int | None = Nonechildren: list[FileInfo] = msgspec.field(default_factory=list)opengraph: OpenGraphMetadata | None = None@@ -31,6 +32,8 @@ class FileListRequest(msgspec.Struct, rename="camel"):class FileDetailsRequest(msgspec.Struct, rename="camel"):# The path of the file or directorypath: str+ # Optional cap on bytes read from disk; unbounded when omitted.+ max_bytes: int | None = Noneclass FileOpenRequest(msgspec.Struct, rename="camel"):@@ -130,6 +133,7 @@ class FileDetailsResponse(msgspec.Struct, rename="camel"):contents: str | None = Nonemime_type: str | None = Noneis_base64: bool = False+ is_too_large: bool = Falseclass FileCreateResponse(BaseResponse):diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 0ae3365280..5ac5051665 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -1902,6 +1902,11 @@ components:type: objectFileDetailsRequest:properties:+ maxBytes:+ anyOf:+ - type: integer+ - type: 'null'+ default: nullpath:type: stringrequired:@@ -1920,6 +1925,9 @@ components:isBase64:default: falsetype: boolean+ isTooLarge:+ default: false+ type: booleanmimeType:anyOf:- type: string@@ -1956,6 +1964,11 @@ components:default: nullpath:type: string+ size:+ anyOf:+ - type: integer+ - type: 'null'+ default: nullrequired:- id- pathdiff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 638715dd74..4cf2cd2e22 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -4719,6 +4719,8 @@ export interface components {};/** FileDetailsRequest */FileDetailsRequest: {+ /** @default null */+ maxBytes?: number | null;path: string;};/** FileDetailsResponse */@@ -4728,6 +4730,8 @@ export interface components {file: components["schemas"]["FileInfo"];/** @default false */isBase64?: boolean;+ /** @default false */+ isTooLarge?: boolean;/** @default null */mimeType?: string | null;};@@ -4744,6 +4748,8 @@ export interface components {/** @default null */opengraph?: null | components["schemas"]["OpenGraphMetadata"];path: string;+ /** @default null */+ size?: number | null;};/** FileListRequest */FileListRequest: {diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.pyindex 5154e10339..f3b06b9b24 100644--- a/tests/_pyodide/test_pyodide_session.py+++ b/tests/_pyodide/test_pyodide_session.py@@ -879,6 +879,34 @@ def test_pyodide_bridge_file_details(assert response["file"]["path"] == str(test_file)+def test_pyodide_bridge_file_details_honors_limit(+ pyodide_bridge: PyodideBridge,+ tmp_path: Path,+) -> None:+ test_file = tmp_path / "large.txt"+ test_file.write_bytes(b"12345")++ request_json = json.dumps({"path": str(test_file), "maxBytes": 4})+ response = json.loads(pyodide_bridge.file_details(request_json))++ assert response["contents"] is None+ assert response["isTooLarge"] is True+++def test_pyodide_bridge_file_details_without_limit_is_unrestricted(+ pyodide_bridge: PyodideBridge,+ tmp_path: Path,+) -> None:+ test_file = tmp_path / "download.bin"+ test_file.write_bytes(b"12345")++ request_json = json.dumps({"path": str(test_file)})+ response = json.loads(pyodide_bridge.file_details(request_json))++ assert response["contents"] == "12345"+ assert response["isTooLarge"] is False++def test_pyodide_bridge_create_file(pyodide_bridge: PyodideBridge,tmp_path: Path,diff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.pyindex a78e457103..19ba921cdb 100644--- a/tests/_server/api/endpoints/test_file_explorer.py+++ b/tests/_server/api/endpoints/test_file_explorer.py@@ -73,6 +73,62 @@ def test_file_details_binary(client: TestClient) -> None:os.remove(bin_path)+def test_file_details_caps_oversized_file_when_limited(+ client: TestClient,+ tmp_path: Path,+) -> None:+ path = tmp_path / "large.txt"+ path.write_bytes(b"12345")++ response = client.post(+ "/api/files/file_details",+ headers=HEADERS,+ json={"path": str(path), "maxBytes": 4},+ )++ assert response.status_code == 200, response.text+ data = response.json()+ assert data["contents"] is None+ assert data["isBase64"] is False+ assert data["isTooLarge"] is True+ assert data["file"]["size"] == 5+++def test_file_details_is_unbounded_without_limit(+ client: TestClient,+ tmp_path: Path,+) -> None:+ path = tmp_path / "large.txt"+ path.write_bytes(b"12345")++ response = client.post(+ "/api/files/file_details",+ headers=HEADERS,+ json={"path": str(path)},+ )++ assert response.status_code == 200, response.text+ data = response.json()+ assert data["contents"] == "12345"+ assert data["isTooLarge"] is False+++def test_file_details_rejects_negative_limit(+ client: TestClient, tmp_path: Path+) -> None:+ path = tmp_path / "small.txt"+ path.write_text("ok", encoding="utf-8")++ response = client.post(+ "/api/files/file_details",+ headers=HEADERS,+ json={"path": str(path), "maxBytes": -1},+ )++ assert response.status_code == 400, response.text+ assert response.json()["detail"] == "maxBytes must be non-negative"++def test_create_and_delete_file_or_directory(client: TestClient) -> None:# Create a file with no contents (empty file)response = client.post(diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.pyindex 2965084261..32020a03dc 100644--- a/tests/_server/files/test_os_file_system.py+++ b/tests/_server/files/test_os_file_system.py@@ -13,7 +13,7 @@ from marimo._server.files.os_file_system import (_generate_unique_path,_is_allowed_paths,)-from marimo._server.models.files import FileDetailsResponse+from marimo._server.models.files import FileDetailsResponse, FileInfofrom marimo._utils.files import natural_sort@@ -292,6 +292,57 @@ def test_list_files(test_dir: Path, fs: OSFileSystem) -> None:assert len(files) == 2 # Expecting 1 file and 1 directory+def test_get_info_reports_file_size(test_dir: Path, fs: OSFileSystem) -> None:+ file_path = test_dir / "sized.txt"+ file_path.write_bytes(b"12345")++ info = fs.get_info(str(file_path))++ assert info.size == 5+ assert info.is_directory is False+++def test_get_info_directory_has_no_size(+ test_dir: Path, fs: OSFileSystem+) -> None:+ directory = test_dir / "folder"+ directory.mkdir()++ info = fs.get_info(str(directory))++ assert info.size is None+ assert info.is_directory is True+++def test_metadata_operations_do_not_call_get_details(+ test_dir: Path,+ fs: OSFileSystem,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ source = test_dir / "source.txt"+ source.write_text("source", encoding="utf-8")++ def fail_get_details(*args: object, **kwargs: object) -> None:+ del args, kwargs+ raise AssertionError("metadata operation read file contents")++ monkeypatch.setattr(fs, "get_details", fail_get_details)++ created = fs.create_file_or_directory(+ str(test_dir), "file", "created.txt", b"created"+ )+ copied = fs.copy_file_or_directory(+ str(source), str(test_dir / "copied.txt")+ )+ moved = fs.move_file_or_directory(copied.path, str(test_dir / "moved.txt"))+ updated = fs.update_file(moved.path, "updated")++ assert created.size == len("created")+ assert copied.size == len("source")+ assert moved.size == len("source")+ assert updated.size == len("updated")++def test_list_files_with_broken_directory_symlink(test_dir: Path, fs: OSFileSystem) -> None:@@ -319,6 +370,61 @@ def test_get_details(test_dir: Path, fs: OSFileSystem) -> None:assert file_info2.contents == "direct content"+def test_get_details_at_limit(test_dir: Path, fs: OSFileSystem) -> None:+ file_path = test_dir / "exact.txt"+ file_path.write_bytes(b"1234")++ result = fs.get_details(str(file_path), max_bytes=4)++ assert result.contents == "1234"+ assert result.is_too_large is False+++def test_get_details_over_limit_does_not_open_file(+ test_dir: Path,+ fs: OSFileSystem,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ file_path = test_dir / "large.bin"+ file_path.write_bytes(b"12345")++ def fail_open(*args: object, **kwargs: object) -> None:+ del args, kwargs+ raise AssertionError("oversized file was opened")++ monkeypatch.setattr(Path, "open", fail_open)++ result = fs.get_details(str(file_path), max_bytes=4)++ assert result.contents is None+ assert result.is_base64 is False+ assert result.is_too_large is True+ assert result.file.size == 5+++def test_get_details_detects_file_growth_after_stat(+ test_dir: Path,+ fs: OSFileSystem,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ file_path = test_dir / "growing.txt"+ file_path.write_bytes(b"12345")+ stale_info = FileInfo(+ id=str(file_path),+ path=str(file_path),+ name=file_path.name,+ is_directory=False,+ is_marimo_file=False,+ size=4,+ )+ monkeypatch.setattr(fs, "get_info", lambda _path: stale_info)++ result = fs.get_details(str(file_path), max_bytes=4)++ assert result.contents is None+ assert result.is_too_large is True++@pytest.mark.parametrize("encoding", ["utf-8", "iso-8859-1"])def test_get_details_marimo_file(test_dir: Path, fs: OSFileSystem, encoding: str