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: preview and edit TOML files with syntax highlighting (#10599)
Shahmir Varqha0b96055b807e
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.tsindex aed00874f1..b84bf336ec 100644--- 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.ts@@ -8,7 +8,10 @@ describe("getFileRenderMode", () => {["text/plain", false, "text"],["text/x-rust", false, "text"],["application/json", false, "text"],+ ["application/toml", false, "text"],+ ["application/x-toml", false, "text"],["application/xml", false, "text"],+ ["text/x-toml", false, "text"],["text/csv", false, "csv"],["image/png", true, "media"],["video/mp4", true, "media"],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.tsxindex 13a5f3df7a..42d8a795c6 100644--- a/frontend/src/components/editor/file-tree/__tests__/file-viewer.test.tsx+++ b/frontend/src/components/editor/file-tree/__tests__/file-viewer.test.tsx@@ -15,13 +15,19 @@ vi.mock("@/plugins/impl/code/LazyAnyLanguageCodeMirror", () => ({LazyAnyLanguageCodeMirror: ({value,onChange,+ language,+ readOnly,}: {value?: string;onChange?: (value: string) => void;+ language?: string;+ readOnly?: boolean;}) => (<textareadata-testid="code-editor"+ data-language={language}value={value ?? ""}+ readOnly={readOnly}onChange={(evt) => onChange?.(evt.target.value)}/>),@@ -106,6 +112,21 @@ describe("FileViewer bounded previews", () => {expect(screen.queryByText(/too large to preview/i)).not.toBeInTheDocument();});+ it("renders TOML files as editable TOML", async () => {+ renderViewer({+ file: { ...file, name: "pyproject.toml", size: 20 },+ contents: '[project]\nname = "demo"',+ mimeType: "application/toml",+ isBase64: false,+ isTooLarge: false,+ });++ const editor =+ await screen.findByTestId<HTMLTextAreaElement>("code-editor");+ expect(editor).toHaveAttribute("data-language", "toml");+ expect(editor).not.toHaveAttribute("readonly");+ });+it("preserves edits to an initially empty text file across remount", async () => {const emptyFile: FileInfo = {id: "/workspace/empty.txt",diff --git a/frontend/src/components/editor/file-tree/__tests__/renderers.test.ts b/frontend/src/components/editor/file-tree/__tests__/renderers.test.tsdeleted file mode 100644index 9315d94e49..0000000000--- a/frontend/src/components/editor/file-tree/__tests__/renderers.test.ts+++ /dev/null@@ -1,31 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */-import { describe, expect, it } from "vitest";-import { buildMediaSource } from "../renderers";--describe("buildMediaSource", () => {- it("returns base64 source for binary media", () => {- expect(- buildMediaSource({- contents: "aGVsbG8=",- mimeType: "image/png",- isBase64: true,- }),- ).toEqual({- base64: "aGVsbG8=",- mime: "image/png",- });- });-- it("returns UTF-8 data URL for text-based media", () => {- const svg = '<svg xmlns="http://www.w3.org/2000/svg"></svg>';- expect(- buildMediaSource({- contents: svg,- mimeType: "image/svg+xml",- isBase64: false,- }),- ).toEqual({- url: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`,- });- });-});diff --git a/frontend/src/components/editor/file-tree/__tests__/renderers.test.tsx b/frontend/src/components/editor/file-tree/__tests__/renderers.test.tsxnew file mode 100644index 0000000000..a61b6af8c2--- /dev/null+++ b/frontend/src/components/editor/file-tree/__tests__/renderers.test.tsx@@ -0,0 +1,129 @@+/* Copyright 2026 Marimo. All rights reserved. */+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { buildMediaSource, FileContentRenderer } from "../renderers";++vi.mock("@/plugins/impl/code/LazyAnyLanguageCodeMirror", () => ({+ LazyAnyLanguageCodeMirror: ({+ value,+ language,+ readOnly,+ onChange,+ }: {+ value?: string;+ language?: string;+ readOnly?: boolean;+ onChange?: (value: string) => void;+ }) => (+ <textarea+ data-testid="code-editor"+ data-language={language}+ value={value}+ readOnly={readOnly}+ onChange={(event) => onChange?.(event.target.value)}+ />+ ),+}));++vi.mock("@/theme/useTheme", () => ({+ useTheme: () => ({ theme: "light" }),+}));++describe("buildMediaSource", () => {+ it("returns base64 source for binary media", () => {+ expect(+ buildMediaSource({+ contents: "aGVsbG8=",+ mimeType: "image/png",+ isBase64: true,+ }),+ ).toEqual({+ base64: "aGVsbG8=",+ mime: "image/png",+ });+ });++ it("returns UTF-8 data URL for text-based media", () => {+ const svg = '<svg xmlns="http://www.w3.org/2000/svg"></svg>';+ expect(+ buildMediaSource({+ contents: svg,+ mimeType: "image/svg+xml",+ isBase64: false,+ }),+ ).toEqual({+ url: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`,+ });+ });+});++describe("FileContentRenderer", () => {+ it("renders editable TOML with syntax highlighting", () => {+ const onChange = vi.fn();+ render(+ <FileContentRenderer+ mimeType="application/toml"+ contents={'name = "demo"'}+ readOnly={false}+ onChange={onChange}+ />,+ );++ const editor = screen.getByTestId<HTMLTextAreaElement>("code-editor");+ expect(editor).toHaveAttribute("data-language", "toml");+ expect(editor).not.toHaveAttribute("readonly");++ fireEvent.change(editor, { target: { value: 'name = "updated"' } });+ expect(onChange).toHaveBeenCalledWith('name = "updated"');+ });++ it.each(["application/toml", "application/x-toml", "text/x-toml"])(+ "renders %s as read-only TOML by default",+ (mimeType) => {+ render(+ <FileContentRenderer mimeType={mimeType} contents={'name = "demo"'} />,+ );++ const editor = screen.getByTestId<HTMLTextAreaElement>("code-editor");+ expect(editor).toHaveAttribute("data-language", "toml");+ expect(editor).toHaveAttribute("readonly");+ },+ );++ it.each([+ "application/octet-stream",+ "text/plain",+ "text/plain; charset=utf-8",+ ])("uses the filename when a provider returns %s", (mimeType) => {+ render(+ <FileContentRenderer+ mimeType={mimeType}+ filename="pyproject.TOML"+ contents={'name = "demo"'}+ />,+ );++ expect(screen.getByTestId("code-editor")).toHaveAttribute(+ "data-language",+ "toml",+ );+ });++ it.each(["file.constructor", "file.__proto__"])(+ "ignores inherited extension-map property in %s",+ (filename) => {+ render(+ <FileContentRenderer+ mimeType="text/plain"+ filename={filename}+ contents="text"+ />,+ );++ expect(screen.getByTestId("code-editor")).toHaveAttribute(+ "data-language",+ "markdown",+ );+ },+ );+});diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsxindex 63b11b5e7c..ee8a382bbe 100644--- a/frontend/src/components/editor/file-tree/file-viewer.tsx+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx@@ -240,6 +240,7 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {{warningBanner}<FileContentRenderermimeType={mimeType}+ filename={data.file.name}contents={isText? internalValuediff --git a/frontend/src/components/editor/file-tree/renderers.tsx b/frontend/src/components/editor/file-tree/renderers.tsxindex 000f9ac3b5..f247b4f860 100644--- a/frontend/src/components/editor/file-tree/renderers.tsx+++ b/frontend/src/components/editor/file-tree/renderers.tsx@@ -16,6 +16,7 @@ import { useTheme } from "@/theme/useTheme";import { Arrays } from "@/utils/arrays";import { type Base64String, base64ToDataURL } from "@/utils/json/base64";import { Objects } from "@/utils/objects";+import { Paths } from "@/utils/paths";const PAGE_SIZE = 25;@@ -38,13 +39,36 @@ export const MIME_TO_LANGUAGE: Record<string, string> = {"text/css": "css","text/x-python": "python","application/json": "json",+ "application/toml": "toml",+ "application/x-toml": "toml","application/xml": "xml",+ "text/x-toml": "toml","text/x-yaml": "yaml","text/csv": "markdown","text/plain": "markdown",default: "markdown",};+const EXTENSION_TO_LANGUAGE: Record<string, string> = {+ toml: "toml",+};++const GENERIC_MIME_TYPES = new Set(["application/octet-stream", "text/plain"]);++function resolveLanguage(mimeType: string, filename?: string): string {+ const normalizedMimeType = mimeType.split(";", 1)[0].trim().toLowerCase();+ if (GENERIC_MIME_TYPES.has(normalizedMimeType) && filename) {+ const extension = Paths.extension(filename).toLowerCase();+ const language = Object.hasOwn(EXTENSION_TO_LANGUAGE, extension)+ ? EXTENSION_TO_LANGUAGE[extension]+ : undefined;+ if (language) {+ return language;+ }+ }+ return MIME_TO_LANGUAGE[normalizedMimeType] || MIME_TO_LANGUAGE.default;+}+/*** Media viewer props: provide either a direct `url` or `base64` + `mime`.* When `url` is set it takes precedence.@@ -167,6 +191,7 @@ export const MediaRenderer: React.FC<MediaSource & { mimeType: string }> = ({*/export const FileContentRenderer: React.FC<{mimeType: string;+ filename?: string;/** Text content for text/CSV files. */contents?: string;/** Media source for image/audio/video/PDF files. */@@ -177,6 +202,7 @@ export const FileContentRenderer: React.FC<{extensions?: Extension[];}> = ({mimeType,+ filename,contents,mediaSource,readOnly = true,@@ -202,7 +228,7 @@ export const FileContentRenderer: React.FC<{}if (contents != null) {- const language = MIME_TO_LANGUAGE[mimeType] || MIME_TO_LANGUAGE.default;+ const language = resolveLanguage(mimeType, filename);return (<div className="flex-1 overflow-auto"><Suspense>diff --git a/frontend/src/components/storage/__tests__/storage-file-viewer.test.tsx b/frontend/src/components/storage/__tests__/storage-file-viewer.test.tsxnew file mode 100644index 0000000000..296a481616--- /dev/null+++ b/frontend/src/components/storage/__tests__/storage-file-viewer.test.tsx@@ -0,0 +1,84 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { TooltipProvider } from "@/components/ui/tooltip";+import { DownloadStorage } from "@/core/storage/request-registry";+import { StorageFileViewer } from "../storage-file-viewer";++vi.mock("@/components/editor/cell/useAddCell", () => ({+ useAddCodeToNewCell: () => vi.fn(),+}));++vi.mock("@/plugins/impl/code/LazyAnyLanguageCodeMirror", () => ({+ LazyAnyLanguageCodeMirror: ({+ value,+ language,+ readOnly,+ }: {+ value?: string;+ language?: string;+ readOnly?: boolean;+ }) => (+ <textarea+ data-testid="code-editor"+ data-language={language}+ value={value}+ readOnly={readOnly}+ />+ ),+}));++vi.mock("@/theme/useTheme", () => ({+ useTheme: () => ({ theme: "light" }),+}));++describe("StorageFileViewer", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it("renders TOML from generic storage metadata as read-only TOML", async () => {+ const request = vi.spyOn(DownloadStorage, "request").mockResolvedValue({+ request_id: "request-id",+ url: "https://example.com/pyproject.toml?signature=secret",+ });+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ text: async () => '[project]\nname = "demo"',+ }),+ );++ render(+ <TooltipProvider>+ <StorageFileViewer+ entry={{+ path: "config/pyproject.toml",+ kind: "file",+ size: 24,+ lastModified: null,+ mimeType: null,+ }}+ namespace="files"+ protocol="s3"+ backendType="fsspec"+ onBack={vi.fn()}+ />+ </TooltipProvider>,+ );++ const editor =+ await screen.findByTestId<HTMLTextAreaElement>("code-editor");+ expect(editor).toHaveAttribute("data-language", "toml");+ expect(editor).toHaveAttribute("readonly");+ expect(editor).toHaveValue('[project]\nname = "demo"');+ expect(request).toHaveBeenCalledWith({+ namespace: "files",+ path: "config/pyproject.toml",+ preview: true,+ });+ });+});diff --git a/frontend/src/components/storage/storage-file-viewer.tsx b/frontend/src/components/storage/storage-file-viewer.tsxindex 0eb587cf6d..cb2e00afcf 100644--- a/frontend/src/components/storage/storage-file-viewer.tsx+++ b/frontend/src/components/storage/storage-file-viewer.tsx@@ -237,6 +237,7 @@ export const StorageFileViewer: React.FC<Props> = ({{renderMetadata({})}<FileContentRenderermimeType={mime}+ filename={name}contents={preview.type === "text" ? preview.content : undefined}mediaSource={preview.type === "media" ? { url: preview.url } : undefineddiff --git a/marimo/_ai/_types.py b/marimo/_ai/_types.pyindex 56fa50c560..e06d0a9f31 100644--- a/marimo/_ai/_types.py+++ b/marimo/_ai/_types.py@@ -2,7 +2,6 @@from __future__ import annotationsimport abc-import mimetypesfrom dataclasses import asdict, dataclass, is_dataclassfrom typing import TYPE_CHECKING, Any, Literal, TypedDict, cast@@ -10,6 +9,7 @@ import msgspecfrom marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager+from marimo._utils.mime import guess_mime_typefrom marimo._utils.parse_dataclass import parse_rawLOGGER = _loggers.marimo_logger()@@ -95,7 +95,7 @@ class ChatAttachment:def __post_init__(self) -> None:if self.content_type is None:- self.content_type = mimetypes.guess_type(self.url)[0]+ self.content_type = guess_mime_type(self.url)# AI SDK part type definitions (based on actual frontend structure)diff --git a/marimo/_convert/common/dom_traversal.py b/marimo/_convert/common/dom_traversal.pyindex 0779b2b5d7..2d114dbdb4 100644--- a/marimo/_convert/common/dom_traversal.py+++ b/marimo/_convert/common/dom_traversal.py@@ -2,7 +2,6 @@from __future__ import annotationsimport base64-import mimetypesimport refrom html.parser import HTMLParserfrom typing import TYPE_CHECKING, cast@@ -11,6 +10,7 @@ from marimo import _loggersfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._runtime.virtual_file import read_virtual_filefrom marimo._utils.data_uri import build_data_url+from marimo._utils.mime import guess_mime_typeif TYPE_CHECKING:from collections.abc import Callable@@ -256,7 +256,7 @@ def _virtual_file_to_data_uri(virtual_file_url: str) -> str | None:byte_length, filename = parsedtry:buffer_contents = read_virtual_file(filename, byte_length)- mime_type = mimetypes.guess_type(filename)[0] or "text/plain"+ mime_type = guess_mime_type(filename) or "text/plain"return build_data_url(cast(KnownMimeType, mime_type),base64.b64encode(buffer_contents),@@ -453,7 +453,7 @@ def replace_public_files_with_data_uris("Failed to read public file %s during export: %s", value, e)return None- mime_type = mimetypes.guess_type(resolved.name)[0] or "text/plain"+ mime_type = guess_mime_type(resolved.name) or "text/plain"replaced.add(value)return build_data_url(cast(KnownMimeType, mime_type),diff --git a/marimo/_data/_external_storage/huggingface.py b/marimo/_data/_external_storage/huggingface.pyindex ab0d8fa693..b800f79cd6 100644--- a/marimo/_data/_external_storage/huggingface.py+++ b/marimo/_data/_external_storage/huggingface.py@@ -2,7 +2,6 @@from __future__ import annotationsimport asyncio-import mimetypesimport osimport tempfilefrom dataclasses import dataclass@@ -24,6 +23,7 @@ from marimo._data._external_storage.utils import ()from marimo._dependencies.dependencies import DependencyManagerfrom marimo._utils.assert_never import log_never+from marimo._utils.mime import guess_mime_typefrom marimo._utils.typing import overrideif TYPE_CHECKING:@@ -233,7 +233,7 @@ class HuggingfaceApi(StorageBackend["HfApi"]):last_modified=_last_modified_from_commit(item.last_commit),- mime_type=mimetypes.guess_type(full_path)[0],+ mime_type=guess_mime_type(full_path),))elif isinstance(item, RepoFolder):@@ -286,7 +286,7 @@ class HuggingfaceApi(StorageBackend["HfApi"]):last_modified=_last_modified_from_bucket_item(item.uploaded_at),- mime_type=mimetypes.guess_type(full_path)[0],+ mime_type=guess_mime_type(full_path),))elif isinstance(item, BucketFolder):@@ -351,7 +351,7 @@ class HuggingfaceApi(StorageBackend["HfApi"]):kind="file",size=item.size or 0,last_modified=_last_modified_from_commit(item.last_commit),- mime_type=mimetypes.guess_type(full_path)[0],+ mime_type=guess_mime_type(full_path),)elif isinstance(item, RepoFolder):folder_path = item.path.rstrip("/")@@ -397,7 +397,7 @@ class HuggingfaceApi(StorageBackend["HfApi"]):last_modified=_last_modified_from_bucket_item(item.uploaded_at),- mime_type=mimetypes.guess_type(full_path)[0],+ mime_type=guess_mime_type(full_path),)# get_bucket_paths_info only resolves files (nonexistent paths arediff --git a/marimo/_data/_external_storage/storage.py b/marimo/_data/_external_storage/storage.pyindex 67dc9f8b73..bbe706d9bf 100644--- a/marimo/_data/_external_storage/storage.py+++ b/marimo/_data/_external_storage/storage.py@@ -2,7 +2,6 @@from __future__ import annotationsimport asyncio-import mimetypesimport refrom datetime import timedeltafrom functools import cached_property@@ -26,6 +25,7 @@ from marimo._data._external_storage.utils import (from marimo._dependencies.dependencies import DependencyManagerfrom marimo._utils.assert_never import log_neverfrom marimo._utils.dicts import remove_none_values+from marimo._utils.mime import guess_mime_typeif TYPE_CHECKING:from fsspec import ( # type: ignore[import-untyped]@@ -109,7 +109,7 @@ class Obstore(StorageBackend["ObjectStore"]):last_modified=last_modified.timestamp() if last_modified else None,kind="object",metadata=entry_meta,- mime_type=mimetypes.guess_type(path or "")[0],+ mime_type=guess_mime_type(path or ""),)async def download(self, path: str) -> bytes:@@ -403,7 +403,7 @@ class FsspecFilesystem(StorageBackend["AbstractFileSystem"]):last_modified=file.get("mtime"),kind=resolved_kind,metadata=entry_meta,- mime_type=mimetypes.guess_type(resolved_path)[0]+ mime_type=guess_mime_type(resolved_path)if resolved_kind != "directory"else None,)diff --git a/marimo/_export/exporter.py b/marimo/_export/exporter.pyindex 66e5018415..b2c191b877 100644--- a/marimo/_export/exporter.py+++ b/marimo/_export/exporter.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport asyncioimport base64-import mimetypesimport sysfrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Path@@ -63,6 +62,7 @@ from marimo._utils import async_pathfrom marimo._utils.code import hash_codefrom marimo._utils.data_uri import build_data_urlfrom marimo._utils.marimo_path import MarimoPath+from marimo._utils.mime import guess_mime_typefrom marimo._utils.paths import marimo_package_path, notebook_output_dirfrom marimo._version import __version__@@ -494,7 +494,7 @@ class Exporter:)return None- mime_type = mimetypes.guess_type(basename)[0] or "text/plain"+ mime_type = guess_mime_type(basename) or "text/plain"return build_data_url(cast(KnownMimeType, mime_type),base64.b64encode(buffer_contents),diff --git a/marimo/_plugins/core/media.py b/marimo/_plugins/core/media.pyindex 0210e2b5a2..278f999986 100644--- a/marimo/_plugins/core/media.py+++ b/marimo/_plugins/core/media.py@@ -11,6 +11,7 @@ from urllib.parse import urlparseimport narwhals.stable.v2 as nwfrom marimo._dependencies.dependencies import DependencyManager+from marimo._utils.mime import guess_mime_type as guess_mime_type_from_pathfrom marimo._utils.narwhals_utils import can_narwhalifyif TYPE_CHECKING:@@ -30,13 +31,13 @@ def guess_mime_type(return src.split(";")[0].split(":")[1]if isinstance(src, str):- return mimetypes.guess_type(src)[0]+ return guess_mime_type_from_path(src)if isinstance(src, io.FileIO):- return mimetypes.guess_type(src.name)[0]+ return guess_mime_type_from_path(src.name)if isinstance(src, io.BufferedReader):- return mimetypes.guess_type(src.name)[0]+ return guess_mime_type_from_path(src.name)return Nonediff --git a/marimo/_runtime/virtual_file/virtual_file.py b/marimo/_runtime/virtual_file/virtual_file.pyindex d713b6467b..d9f83428df 100644--- a/marimo/_runtime/virtual_file/virtual_file.py+++ b/marimo/_runtime/virtual_file/virtual_file.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport base64import dataclasses-import mimetypesimport randomimport stringimport threading@@ -22,6 +21,7 @@ from marimo._runtime.virtual_file.storage import ()from marimo._utils.data_uri import build_data_urlfrom marimo._utils.http import HTTPException, HTTPStatus+from marimo._utils.mime import guess_mime_typeif TYPE_CHECKING:from collections.abc import Iterable@@ -68,7 +68,7 @@ class VirtualFile:if not as_data_url:self.url = url or f"./@file/{len(buffer)}-{filename}"else:- mimetype = mimetypes.guess_type(self.filename)[0] or "text/plain"+ mimetype = guess_mime_type(self.filename) or "text/plain"self.url = url or build_data_url(mimetype=cast(KnownMimeType, mimetype),data=base64.b64encode(buffer),diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex 44e30da009..448c1f89a0 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -2,7 +2,6 @@from __future__ import annotationsimport hashlib-import mimetypesimport refrom pathlib import Pathfrom typing import TYPE_CHECKING, TypedDict@@ -41,6 +40,7 @@ from marimo._templates import (notebook_page_template,)from marimo._utils.async_path import AsyncPath+from marimo._utils.mime import guess_mime_typefrom marimo._utils.paths import (MARIMO_DIR_NAME,marimo_package_path,@@ -592,7 +592,7 @@ def virtual_file()total_size = int(byte_length_str)- mimetype, _ = mimetypes.guess_type(filename)+ mimetype = guess_mime_type(filename)headers = {"Cache-Control": "max-age=86400",# Advertise range support so Safari (which requires it for mediadiff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.pyindex ba01504efe..5b8ca31699 100644--- a/marimo/_server/api/endpoints/file_explorer.py+++ b/marimo/_server/api/endpoints/file_explorer.py@@ -1,7 +1,6 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import mimetypesfrom pathlib import Pathfrom typing import TYPE_CHECKING@@ -43,6 +42,7 @@ from marimo._server.models.models import ()from marimo._server.router import APIRouterfrom marimo._utils.http import HTTPException as MarimoHTTPException+from marimo._utils.mime import guess_mime_typeif TYPE_CHECKING:from starlette.requests import Request@@ -189,9 +189,7 @@ def download_file(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"- )+ media_type = guess_mime_type(file_path.name) or "application/octet-stream"return FileResponse(file_path,media_type=media_type,diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex 9ead16fed1..a3d9a70b7b 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -2,7 +2,6 @@from __future__ import annotationsimport base64-import mimetypesimport osimport platformimport re@@ -18,6 +17,7 @@ from marimo._server.files.file_system import FileSystemfrom marimo._server.models.files import FileDetailsResponse, FileInfofrom marimo._session.notebook.file_manager import AppFileManagerfrom marimo._utils.files import natural_sort+from marimo._utils.mime import guess_mime_typeLOGGER = _loggers.marimo_logger()@@ -130,7 +130,7 @@ class OSFileSystem(FileSystem):raise ValueError("max_bytes must be non-negative")file_info = self.get_info(path)- mime_type = mimetypes.guess_type(path)[0]+ mime_type = guess_mime_type(path)is_base64 = Falseis_too_large = Falseactual_contents: str | Nonediff --git a/marimo/_utils/mime.py b/marimo/_utils/mime.pynew file mode 100644index 0000000000..d0b2c32958--- /dev/null+++ b/marimo/_utils/mime.py@@ -0,0 +1,31 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import mimetypes+import os+from pathlib import PurePath+from typing import Final+from urllib.parse import urlparse++_CUSTOM_MIME_TYPES: Final[dict[str, str]] = {+ ".toml": "application/toml",+}+++def guess_mime_type(path: str | os.PathLike[str]) -> str | None:+ """Guess a file's MIME type consistently across platforms and processes.++ `mimetypes` uses platform-specific databases, so custom mappings provide+ deterministic results.+ """+ path_string = os.fspath(path)+ parsed = urlparse(path_string)+ if parsed.scheme == "data":+ return mimetypes.guess_type(path_string)[0]+ # A single-letter scheme is a Windows drive, not a URL.+ is_url = len(parsed.scheme) > 1 or (+ not parsed.scheme and bool(parsed.netloc)+ )+ mime_path = parsed.path if is_url else path_string+ suffix = PurePath(mime_path).suffix.lower()+ return _CUSTOM_MIME_TYPES.get(suffix) or mimetypes.guess_type(mime_path)[0]diff --git a/tests/_ai/test_ai_types.py b/tests/_ai/test_ai_types.pyindex 4724750610..ef791a9220 100644--- a/tests/_ai/test_ai_types.py+++ b/tests/_ai/test_ai_types.py@@ -526,6 +526,11 @@ class TestChatMessagePostInit:class TestChatMessageDict:"""Tests for ChatMessage serialization via dict()."""+ def test_attachment_infers_content_type_from_data_url(self):+ attachment = ChatAttachment(url="data:image/png;base64,AAAA")++ assert attachment.content_type == "image/png"+def test_parts_and_attachments_serialized_to_dict(self):"""Parts and attachments are converted to dicts via asdict."""message = ChatMessage(diff --git a/tests/_data/_external_storage/test_storage_models.py b/tests/_data/_external_storage/test_storage_models.pyindex 2a93236d1a..95d37f56cd 100644--- a/tests/_data/_external_storage/test_storage_models.py+++ b/tests/_data/_external_storage/test_storage_models.py@@ -252,6 +252,21 @@ class TestObstore:))+ def test_create_storage_entry_with_toml(self) -> None:+ backend = self._make_backend(MagicMock())++ entry = backend._create_storage_entry(+ {+ "path": "pyproject.toml",+ "size": 100,+ "last_modified": None,+ "e_tag": None,+ "version": None,+ }+ )++ assert entry.mime_type == "application/toml"+async def test_get_entry(self) -> None:now = datetime(2025, 6, 15, 12, 0, 0, tzinfo=timezone.utc)mock_store = MagicMock()@@ -1023,6 +1038,19 @@ class TestFsspecFilesystem:))+ def test_create_storage_entry_with_toml(self) -> None:+ backend = self._make_backend(MagicMock())++ entry = backend._create_storage_entry(+ {+ "name": "pyproject.toml",+ "size": 100,+ "type": "file",+ }+ )++ assert entry.mime_type == "application/toml"+def test_create_storage_entry_includes_id(self) -> None:# Backends such as Google Drive allow duplicate paths, so the stable# id must flow through to disambiguate entries on the client.diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.pyindex af370187fa..f11a50b427 100644--- a/tests/_pyodide/test_pyodide_session.py+++ b/tests/_pyodide/test_pyodide_session.py@@ -910,6 +910,19 @@ def test_pyodide_bridge_file_details(assert response["file"]["path"] == str(test_file)+def test_pyodide_bridge_toml_file_details(+ pyodide_bridge: PyodideBridge,+ tmp_path: Path,+) -> None:+ test_file = tmp_path / "pyproject.toml"+ test_file.write_text('[project]\nname = "demo"')++ request_json = json.dumps({"path": str(test_file)})+ response = json.loads(pyodide_bridge.file_details(request_json))++ assert response["mimeType"] == "application/toml"++def test_pyodide_bridge_file_details_honors_limit(pyodide_bridge: PyodideBridge,tmp_path: Path,diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.pyindex 32020a03dc..e079534cfa 100644--- a/tests/_server/files/test_os_file_system.py+++ b/tests/_server/files/test_os_file_system.py@@ -370,6 +370,16 @@ def test_get_details(test_dir: Path, fs: OSFileSystem) -> None:assert file_info2.contents == "direct content"+def test_get_toml_details(test_dir: Path, fs: OSFileSystem) -> None:+ file_path = test_dir / "pyproject.toml"+ file_path.write_text('[project]\nname = "demo"')++ result = fs.get_details(str(file_path))++ assert result.mime_type == "application/toml"+ assert result.contents == '[project]\nname = "demo"'++def test_get_details_at_limit(test_dir: Path, fs: OSFileSystem) -> None:file_path = test_dir / "exact.txt"file_path.write_bytes(b"1234")diff --git a/tests/_utils/test_mime.py b/tests/_utils/test_mime.pynew file mode 100644index 0000000000..5e43ca5cdd--- /dev/null+++ b/tests/_utils/test_mime.py@@ -0,0 +1,56 @@+# Copyright 2026 Marimo. All rights reserved.+from pathlib import Path++import pytest++from marimo._utils.mime import guess_mime_type+++def test_guess_mime_type() -> None:+ assert guess_mime_type("notes.txt") == "text/plain"+ assert guess_mime_type("file-without-extension") is None+++def test_guess_custom_mime_type() -> None:+ assert guess_mime_type("pyproject.toml") == "application/toml"+ assert guess_mime_type("CONFIG.TOML") == "application/toml"+ assert (+ guess_mime_type("s3://bucket/pyproject.toml?version=1")+ == "application/toml"+ )+ assert guess_mime_type(Path("pyproject.toml")) == "application/toml"+++def test_custom_mime_type_does_not_depend_on_system(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ "marimo._utils.mime.mimetypes.guess_type",+ lambda _path: (None, None),+ )++ assert guess_mime_type("pyproject.toml") == "application/toml"+++def test_guess_mime_type_from_url_path() -> None:+ assert (+ guess_mime_type("https://example.com/report.pdf?signature=secret")+ == "application/pdf"+ )+ assert (+ guess_mime_type("s3://bucket/data.json?version=1#preview")+ == "application/json"+ )+ assert guess_mime_type("//cdn.example.com/app.js?v=1") in {+ "application/javascript",+ "text/javascript",+ }+++def test_windows_drive_is_not_treated_as_url_scheme() -> None:+ assert guess_mime_type(r"C:\project\pyproject.toml") == "application/toml"+++def test_guess_mime_type_from_data_url() -> None:+ assert guess_mime_type("data:image/png;base64,AAAA") == "image/png"+ assert guess_mime_type("data:text/plain;base64,SGVsbG8=") == "text/plain"