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: enables sandboxing for markdown files (#4685)
Dylan Madisetti81c8667b30aa
diff --git a/marimo/_ast/app_config.py b/marimo/_ast/app_config.pyindex 4c4ba8a3a7..b08442be13 100644--- a/marimo/_ast/app_config.py+++ b/marimo/_ast/app_config.py@@ -38,7 +38,9 @@ class _AppConfig:sql_output: SqlOutputType = "auto"@staticmethod- def from_untrusted_dict(updates: dict[str, Any]) -> "_AppConfig":+ def from_untrusted_dict(+ updates: dict[str, Any], silent: bool = False+ ) -> "_AppConfig":# Certain flags are useful to pass to App for construction, but# shouldn't make it into the config. (e.g. the _filename flag is# internal)@@ -48,9 +50,10 @@ class _AppConfig:if hasattr(config, key):config.__setattr__(key, updates[key])elif key not in other_allowed:- LOGGER.warning(- f"Unrecognized key '{key}' in app config. Ignoring."- )+ if not silent:+ LOGGER.warning(+ f"Unrecognized key '{key}' in app config. Ignoring."+ )return configdef asdict(self) -> dict[str, Any]:diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex 7996f6a30c..6f8a1e95fe 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -7,7 +7,7 @@ import osimport reimport sysimport textwrap-from typing import Any, Literal, Optional, cast+from typing import TYPE_CHECKING, Any, Literal, Optional, castfrom marimo import __version__from marimo._ast.app_config import _AppConfig@@ -19,6 +19,9 @@ from marimo._ast.variables import BUILTINSfrom marimo._ast.visitor import Namefrom marimo._types.ids import CellId_t+if TYPE_CHECKING:+ from pathlib import Path+if sys.version_info < (3, 10):from typing_extensions import TypeAliaselse:@@ -380,7 +383,7 @@ def is_multiline_comment(node: ast.stmt) -> bool:return False-def get_header_comments(filename: str) -> Optional[str]:+def get_header_comments(filename: str | Path) -> Optional[str]:"""Gets the header comments from a file. ReturnsNone if the file does not exist or the header isinvalid, which is determined by:diff --git a/marimo/_ast/load.py b/marimo/_ast/load.pyindex 3593a16f51..9ea9904709 100644--- a/marimo/_ast/load.py+++ b/marimo/_ast/load.py@@ -93,7 +93,7 @@ def load_app(filename: Optional[str]) -> Optional[App]:if filename is None:return None- if filename.endswith(".md"):+ if filename.endswith(".md") or filename.endswith(".qmd"):contents = _maybe_contents(filename)if not contents:return Nonediff --git a/marimo/_cli/convert/markdown.py b/marimo/_cli/convert/markdown.pyindex f5851d783a..a0e8817119 100644--- a/marimo/_cli/convert/markdown.py+++ b/marimo/_cli/convert/markdown.py@@ -39,16 +39,6 @@ MARIMO_CODE = "marimo-code"ConvertKeys = Union[Literal["marimo"], Literal["marimo-app"]]-# Regex captures loose yaml for frontmatter-# Should match the following:-# ----# title: "Title"-# whatever-# ----YAML_FRONT_MATTER_REGEX = re.compile(- r"^---\s*\n(.*?\n?)(?:---)\s*\n", re.UNICODE | re.DOTALL-)-def backwards_compatible_sanitization(line: str) -> str:return line@@ -132,7 +122,7 @@ def app_config_from_root(root: Element) -> _AppConfig:# Remove values particular to markdown saves.config.pop("marimo-version", None)- return _AppConfig.from_untrusted_dict(config)+ return _AppConfig.from_untrusted_dict(config, silent=True)def get_source_from_tag(tag: Element) -> str:@@ -232,11 +222,16 @@ def _tree_to_app(root: Element) -> str:)sources.append(get_source_from_tag(child))+ header = root.get("header", None)+ pyproject = root.get("pyproject", None)+ if pyproject and not header:+ header = "\n# ".join(["# ///script", *pyproject.splitlines(), "///"])return codegen.generate_filecontents(sources,names,cell_config,config=app_config,+ header_comments=header,)@@ -289,6 +284,7 @@ class MarimoParser(IdentityParser):def __init__(self, *args: Any, **kwargs: Any) -> None:super().__init__(*args, **kwargs)+ self.meta = {}# Build here opposed to the parent class since there is intermediate# logic after the parser is built, and it is more clear here what is# registered.@@ -349,34 +345,18 @@ class FrontMatterPreprocessor(Preprocessor):def __init__(self, md: MarimoParser):super().__init__(md)- self.md = md- self.md.meta = {}+ self.md: MarimoParser = mddef run(self, lines: list[str]) -> list[str]:- import yaml-- # CSafeLoader is faster than SafeLoader.- try:- from yaml import CSafeLoader as SafeLoader- except ImportError:- from yaml import SafeLoader # type: ignore[assignment]-if not lines:return linesdoc = "\n".join(lines)- result = YAML_FRONT_MATTER_REGEX.match(doc)-- if result:- yaml_content = result.group(1)- try:- meta = yaml.load(yaml_content, SafeLoader)- if isinstance(meta, dict):- self.md.meta = meta # type: ignore[attr-defined]- doc = doc[result.end() :].lstrip("\n")- # If there's an error in parsing YAML, ignore the meta and proceed.- except yaml.YAMLError as e:- raise e++ meta, doc = extract_frontmatter(doc)+ if isinstance(meta, dict):+ self.md.meta.update(meta)+return doc.split("\n")@@ -439,7 +419,8 @@ class ExpandAndClassifyProcessor(BlockProcessor):def run(self, parent: Element, blocks: list[str]) -> None:# Copy app metadata to the parent element.- for key, value in self.parser.md.meta.items(): # type: ignore[attr-defined]+ assert isinstance(self.parser.md, MarimoParser)+ for key, value in self.parser.md.meta.items():if isinstance(value, str):parent.set(key, value)@@ -508,11 +489,30 @@ def convert_from_md_to_app(text: str) -> App:def convert_from_md(text: str) -> str:- return MarimoParser(output_format="marimo").convert(text) # type: ignore[arg-type]+ return MarimoParser(output_format="marimo").convert(text)+++def extract_frontmatter(text: str) -> tuple[dict[str, str], str]:+ from marimo._utils import yaml++ result = yaml.YAML_FRONT_MATTER_REGEX.match(text)++ if result:+ yaml_content = result.group(1)+ body = text[result.end() :].lstrip("\n")+ try:+ return yaml.load(yaml_content), body+ # If there's an error in parsing YAML, ignore the meta and proceed.+ except yaml.YAMLError:+ LOGGER.warning(+ "Error parsing frontmatter YAML. Ignoring frontmatter."+ )+ return {}, body+ return {}, textdef sanitize_markdown(text: str) -> str:- return SanitizeParser(output_format="identity").convert(text) # type: ignore[arg-type]+ return SanitizeParser(output_format="identity").convert(text)def is_sanitized_markdown(text: str) -> bool:diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex 25afb999f2..6df45b8e94 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -331,7 +331,7 @@ def md(returndef export_callback(file_path: MarimoPath) -> ExportResult:- return export_as_md(file_path)+ return export_as_md(file_path, new_filename=output)return watch_and_export(MarimoPath(name), output, watch, export_callback)diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex 788c1f01ea..7162a91444 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -85,6 +85,29 @@ class PyProjectReader:return []+def get_headers_from_markdown(contents: str) -> dict[str, str]:+ from marimo._cli.convert.markdown import extract_frontmatter++ frontmatter, _ = extract_frontmatter(contents)+ return get_headers_from_frontmatter(frontmatter)+++def get_headers_from_frontmatter(+ frontmatter: dict[str, Any],+) -> dict[str, str]:+ headers = {"pyproject": "", "header": ""}++ pyproject = frontmatter.get("pyproject", "")+ if pyproject:+ if not pyproject.startswith("#"):+ pyproject = "\n# ".join(+ [r"# /// script", *pyproject.splitlines(), r"///"]+ )+ headers["pyproject"] = pyproject+ headers["header"] = frontmatter.get("header", "")+ return headers++def _pyproject_toml_to_requirements_txt(pyproject: dict[str, Any],) -> list[str]:@@ -158,7 +181,26 @@ def _pyproject_toml_to_requirements_txt(def _get_pyproject_from_filename(name: str) -> dict[str, Any] | None:try:contents, _ = FileContentReader().read_file(name)- return read_pyproject_from_script(contents)+ if name.endswith(".py"):+ return read_pyproject_from_script(contents)++ if not (name.endswith(".md") or name.endswith(".qmd")):+ raise ValueError(+ f"Unsupported file type: {name}. Only .py and .md files are supported."+ )++ headers = get_headers_from_markdown(contents)+ header = headers["pyproject"]+ if not header:+ header = headers["header"]+ elif headers["header"]:+ pyproject = PyProjectReader.from_script(headers["header"])+ if pyproject.dependencies or pyproject.python_version:+ LOGGER.warning(+ "Both header and pyproject provide dependencies. "+ "Preferring pyproject."+ )+ return read_pyproject_from_script(header)except FileNotFoundError:return Noneexcept Exception:diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.pyindex 3de192713f..95b9839776 100644--- a/marimo/_runtime/packages/pypi_package_manager.py+++ b/marimo/_runtime/packages/pypi_package_manager.py@@ -2,8 +2,10 @@from __future__ import annotationsimport json+import osimport subprocessimport sys+import tempfilefrom typing import Optionalfrom marimo._runtime.packages.module_name_to_pypi_name import (@@ -186,6 +188,79 @@ class UvPackageManager(PypiPackageManager):if _is_installed(im)]+ if filepath.endswith(".md") or filepath.endswith(".qmd"):+ # md and qmd require writing to a faux python file first.+ return self._process_md_changes(+ filepath, packages_to_add, packages_to_remove+ )+ return self._process_changes(+ filepath, packages_to_add, packages_to_remove+ )++ def _process_md_changes(+ self,+ filepath: str,+ packages_to_add: list[str],+ packages_to_remove: list[str],+ ) -> None:+ from marimo._cli.convert.markdown import extract_frontmatter+ from marimo._cli.sandbox import get_headers_from_frontmatter+ from marimo._utils import yaml++ # Get script metadata+ with open(filepath) as f:+ frontmatter, body = extract_frontmatter(f.read())+ headers = get_headers_from_frontmatter(frontmatter)+ pyproject = bool(headers.get("pyproject", ""))+ header = (+ headers.get("pyproject", "")+ if pyproject+ else headers.get("header", "")+ )+ pyproject = pyproject or not bool(header)++ # Write out and process the header+ with tempfile.NamedTemporaryFile(+ mode="w", delete=False, suffix=".py"+ ) as temp_file:+ temp_file.write(header)+ temp_file.flush()+ # Have UV modify it+ self._process_changes(+ temp_file.name,+ packages_to_add,+ packages_to_remove,+ )+ with open(temp_file.name) as f:+ header = f.read()+ # Clean up the temporary file+ os.unlink(temp_file.name)++ # Write back the changes to the original file+ if pyproject:+ # Strip '# '+ # and leading/trailing ///+ header = "\n".join(+ [line[2:] for line in header.strip().splitlines()[1:-1]]+ )+ frontmatter["pyproject"] = header+ else:+ frontmatter["header"] = header++ header = yaml.marimo_compat_dump(+ frontmatter,+ sort_keys=False,+ )+ document = ["---", header.strip(), "---", body]+ with open(filepath, "w") as f:+ f.write("\n".join(document))++ def _process_changes(+ self,+ filepath: str,+ packages_to_add: list[str],+ packages_to_remove: list[str],+ ) -> None:if packages_to_add:self.run(["uv", "--quiet", "add", "--script", filepath]diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex a66cdea71c..4b9027762a 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -5,7 +5,7 @@ import asyncioimport osimport sysfrom dataclasses import dataclass-from typing import Any, Callable, Literal, Optional, Union, cast+from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union, castfrom marimo._cli.print import echofrom marimo._config.config import RuntimeConfig@@ -29,6 +29,9 @@ from marimo._types.ids import ConsumerIdfrom marimo._utils.marimo_path import MarimoPathfrom marimo._utils.parse_dataclass import parse_raw+if TYPE_CHECKING:+ from pathlib import Path+@dataclassclass ExportResult:@@ -55,13 +58,17 @@ def export_as_script(def export_as_md(path: MarimoPath,+ new_filename: Optional[Path] = None,) -> ExportResult:file_router = AppFileRouter.from_filename(path)file_key = file_router.get_unique_file_key()assert file_key is not Nonefile_manager = file_router.get_file_manager(file_key)- result = Exporter().export_as_md(file_manager)+ # py -> md+ if new_filename:+ file_manager.filename = str(new_filename)+ result = Exporter().export_as_md(file_manager, previous=path.path)return ExportResult(contents=result[0],download_filename=result[1],diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 82abf734eb..3f494b407b 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -223,45 +223,71 @@ class Exporter:download_filename = get_download_filename(file_manager, "ipynb")return stream.read(), download_filename- def export_as_md(self, file_manager: AppFileManager) -> tuple[str, str]:- import yaml-+ def export_as_md(+ self, file_manager: AppFileManager, previous: Path | None = None+ ) -> tuple[str, str]:+ from marimo._ast import codegenfrom marimo._ast.app_config import _AppConfigfrom marimo._ast.cell import Cellfrom marimo._ast.compiler import compile_cellfrom marimo._cli.convert.markdown import (+ extract_frontmatter,formatted_code_block,is_sanitized_markdown,)+ from marimo._utils import yaml- # TODO: Provide filter or kernel in yaml header such that markdown- # documents are executable.+ filename = get_filename(file_manager)+ metadata: dict[str, str | list[str]] = {}+ metadata.update(+ {+ "title": get_app_title(file_manager),+ "marimo-version": __version__,+ }+ )- # Put data from AppFileManager into the yaml header.+ # Put data from AppFileManager into the yaml header.ignored_keys = {"app_title"}- metadata: dict[str, str | list[str]] = {- "title": get_app_title(file_manager),- "marimo-version": __version__,- }-- def _format_value(v: Optional[str | list[str]]) -> str | list[str]:- if isinstance(v, list):- return v- return str(v)-default_config = _AppConfig().asdict()# Get values defined in _AppConfig without explicitly extracting keys,# as long as it isn't the default.metadata.update({- k: _format_value(v)+ k: vfor k, v in file_manager.app.config.asdict().items()if k not in ignored_keys and v != default_config.get(k)})+ # If previously a markdown file, extract frontmatter.+ # otherwise if it was a python file, extract header.+ if previous and previous.suffix == ".py":+ header = codegen.get_header_comments(previous)+ if header:+ metadata["header"] = header.strip()+ else:+ header_file = previous if previous else file_manager.filename+ if header_file:+ with open(header_file, encoding="utf-8") as f:+ _metadata, _ = extract_frontmatter(f.read())+ metadata.update(_metadata)++ # Add the expected qmd filter to the metadata.+ if filename.endswith(".qmd"):+ if "filters" not in metadata:+ metadata["filters"] = []+ if "marimo" not in str(metadata["filters"]):+ if isinstance(metadata["filters"], str):+ metadata["filters"] = metadata["filters"].split(",")+ if isinstance(metadata["filters"], list):+ metadata["filters"].append("marimo-team/marimo")+ else:+ LOGGER.warning(+ "Unexpected type for filters: %s",+ type(metadata["filters"]),+ )- header = yaml.dump(+ header = yaml.marimo_compat_dump({k: vfor k, v in metadata.items()diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex c1136c8f1f..6060a4f4f6 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -129,19 +129,38 @@ class AppFileManager:app_config: _AppConfig,# Whether or not to persist the app to the file systempersist: bool,+ # Whether save was triggered by a rename+ previous_filename: Optional[str] = None,) -> str:LOGGER.debug("Saving app to %s", filename)- if filename.endswith(".md"):- # TODO: Remember just proof of concept, potentially needs- # restructuring.++ type_changed = (+ previous_filename and filename[-2:] != previous_filename[-2:]+ )+ if filename.endswith(".md") or filename.endswith(".qmd"):+ # TODO: Potentially restructure, such that code compilation doesn't+ # have to occur multiple times.from marimo._server.export.exporter import Exporter- contents, _ = Exporter().export_as_md(self)+ previous = None+ if previous_filename:+ previous = Path(previous_filename)+ contents, _ = Exporter().export_as_md(self, previous)else:# Header might be better kept on the AppConfig side, opposed to# reparsing it. Also would allow for md equivalent in a field like# `description`.- header_comments = codegen.get_header_comments(filename)+ if type_changed:+ from marimo._cli.sandbox import get_headers_from_markdown++ with open(filename, encoding="utf-8") as f:+ markdown = f.read()+ headers = get_headers_from_markdown(markdown)+ header_comments = headers.get("header", None) or headers.get(+ "pyproject", None+ )+ else:+ header_comments = codegen.get_header_comments(filename)# try to save the app under the name `filename`contents = codegen.generate_filecontents(codes,@@ -190,19 +209,20 @@ class AppFileManager:self._assert_path_does_not_exist(new_filename)- need_save = False+ needs_save = False# Check if filename is not None to satisfy mypy's type checking.# This ensures that filename is treated as a non-optional str,# preventing potential type errors in subsequent code.if self.is_notebook_named and self.filename is not None:# Force a save after rename in case filetype changed.- need_save = self.filename[-3:] != new_filename[-3:]+ needs_save = self.filename[-3:] != new_filename[-3:]self._rename_file(new_filename)else:self._create_file(new_filename)+ previous_filename = self.filenameself.filename = new_filename- if need_save:+ if needs_save:self._save_file(self.filename,list(self.app.cell_manager.codes()),@@ -210,6 +230,7 @@ class AppFileManager:list(self.app.cell_manager.configs()),self.app.config,persist=True,+ previous_filename=previous_filename,)def read_layout_config(self) -> Optional[LayoutConfig]:diff --git a/marimo/_tutorials/markdown_format.md b/marimo/_tutorials/markdown_format.mdindex 4849160635..bef431a04c 100644--- a/marimo/_tutorials/markdown_format.md+++ b/marimo/_tutorials/markdown_format.md@@ -1,6 +1,19 @@---title: Markdown-marimo-version: 0.10.19+marimo-version: 0.13.2+author: Marimo Team+description: >-+ Markdown is a lightweight markup language with plain text formatting syntax. `marimo`+ notebooks can be stored as markdown files, allowing you to work on prose-heavy notebooks+ in your editor of choice.+pyproject: |-+ requires-python = ">=3.12"+ dependencies = [+ "marimo",+ "duckdb==1.2.2",+ "matplotlib==3.10.1",+ "sqlglot==26.16.2",+ ]---# Markdown file formatdiff --git a/marimo/_utils/yaml.py b/marimo/_utils/yaml.pynew file mode 100644index 0000000000..885900dcbf--- /dev/null+++ b/marimo/_utils/yaml.py@@ -0,0 +1,85 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++import re+import sys+from typing import Any, Callable++import yaml+from yaml.representer import SafeRepresenter, ScalarNode++if sys.version_info < (3, 10):+ from typing_extensions import TypeAlias+else:+ from typing import TypeAlias+++# Regex captures loose yaml for frontmatter+# Should match the following:+# ---+# title: "Title"+# whatever+# ---+YAML_FRONT_MATTER_REGEX = re.compile(+ r"^---\s*\n(.*?\n?)(?:---)\s*\n", re.UNICODE | re.DOTALL+)++Repr: TypeAlias = Callable[[SafeRepresenter, str], ScalarNode]+++# represent_str does handle some corner cases, so use that+# instead of calling represent_scalar directly+class folded_str(str):+ pass+++class literal_str(str):+ pass+++def _format_header_value(k: str, v: Any) -> Any:+ if not isinstance(v, str):+ return v+ if k in ("pyproject", "header") or "\n" in v:+ return literal_str(v)+ if k == "description":+ return folded_str(v)+ return v+++def dump(data: dict[str, Any], **kwargs: Any) -> str:+ def _change_style(style: str, representer: Repr) -> Repr:+ def new_representer(dumper: SafeRepresenter, data: str) -> ScalarNode:+ scalar = representer(dumper, data)+ scalar.style = style+ return scalar++ return new_representer++ represent_folded_str = _change_style(">", SafeRepresenter.represent_str)+ represent_literal_str = _change_style("|", SafeRepresenter.represent_str)+ yaml.add_representer(folded_str, represent_folded_str)+ yaml.add_representer(literal_str, represent_literal_str)++ response = yaml.dump(data, **kwargs)+ assert isinstance(response, str), f"Expected str, got {type(response)}"+ return response+++def marimo_compat_dump(data: dict[str, Any], **kwargs: Any) -> str:+ safe_data = {k: _format_header_value(k, v) for k, v in data.items()}+ return dump(safe_data, **kwargs)+++def load(yaml_content: str) -> dict[str, Any]:+ # CSafeLoader is faster than SafeLoader.+ try:+ from yaml import CSafeLoader as SafeLoader+ except ImportError:+ from yaml import SafeLoader # type: ignore[assignment]+ response = yaml.load(yaml_content, SafeLoader)+ assert isinstance(response, dict), f"Expected dict, got {type(response)}"+ return response+++YAMLError = yaml.YAMLErrordiff --git a/tests/_cli/snapshots/dataflow.md.txt b/tests/_cli/snapshots/dataflow.md.txtindex 02ec27b161..0db25c19c5 100644--- a/tests/_cli/snapshots/dataflow.md.txt+++ b/tests/_cli/snapshots/dataflow.md.txt@@ -1,6 +1,16 @@---title: Dataflowmarimo-version: 0.0.0+header: |-+ # Copyright 2025 Marimo. All rights reserved.+ # /// script+ # requires-python = ">=3.12"+ # dependencies = [+ # "marimo",+ # "matplotlib==3.10.1",+ # "numpy==2.2.4",+ # ]+ # ///---# How marimo notebooks rundiff --git a/tests/_cli/snapshots/frontmatter-test.py.txt b/tests/_cli/snapshots/frontmatter-test.py.txtindex 8f9d6c934b..201e5bc2a1 100644--- a/tests/_cli/snapshots/frontmatter-test.py.txt+++ b/tests/_cli/snapshots/frontmatter-test.py.txt@@ -1,3 +1,6 @@+#!/usr/bin/env python+# and some other random stuff+import marimo__generated_with = "0.0.0"diff --git a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txtindex d51edef127..fa2cda7a3a 100644--- a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt+++ b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt@@ -1,6 +1,8 @@---title: marimo for Jupyter usersmarimo-version: 0.0.0+header: |-+ # Copyright 2024 Marimo. All rights reserved.---# marimo for Jupyter usersdiff --git a/tests/_cli/snapshots/sql.md.txt b/tests/_cli/snapshots/sql.md.txtindex 142a5cce77..c24a890251 100644--- a/tests/_cli/snapshots/sql.md.txt+++ b/tests/_cli/snapshots/sql.md.txt@@ -2,6 +2,19 @@title: Sqlmarimo-version: 0.0.0width: medium+header: |-+ # Copyright 2025 Marimo. All rights reserved.+ # /// script+ # requires-python = ">=3.12"+ # dependencies = [+ # "duckdb==1.2.2",+ # "marimo",+ # "pandas==2.2.3",+ # "polars==1.27.1",+ # "pyarrow==19.0.1",+ # "sqlglot==26.13.0",+ # ]+ # ///---# Hello, SQL!diff --git a/tests/_cli/test_markdown_conversion.py b/tests/_cli/test_markdown_conversion.pyindex 8ccb31757b..0d3cf2163f 100644--- a/tests/_cli/test_markdown_conversion.py+++ b/tests/_cli/test_markdown_conversion.py@@ -95,6 +95,9 @@ def test_markdown_frontmatter() -> None:filters:- name: "filter1"- name: "filter2"+ header: |+ #!/usr/bin/env python+ # and some other random stuff---# Notebook@@ -109,6 +112,7 @@ def test_markdown_frontmatter() -> None:# As python fileoutput = sanitized_version(convert_from_md(script))assert 'app_title="My Title"' in output+ assert output.startswith("#!/usr/bin/env python")snapshot("frontmatter-test.py.txt", output)# As python object@@ -239,6 +243,22 @@ def test_markdown_empty() -> None:assert app.cell_manager.cell_data_at(ids[0]).code == ""+def test_python_to_md_header() -> None:+ script = dedent(+ remove_empty_lines(+ """+ #!/usr/bin/env python+ import marimo+ __generated_with = "0.0.0"+ app = marimo.App()+ """+ )+ )+ md = convert_from_py(script)+ assert "#!/usr/bin/env python" in md+ snapshot("has-header.md.txt", md)++def test_python_to_md_code_injection() -> None:unsafe_app = dedent(remove_empty_lines(diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.pyindex a4719c3a24..7af6d2ae70 100644--- a/tests/_cli/test_sandbox.py+++ b/tests/_cli/test_sandbox.py@@ -564,3 +564,109 @@ def test_construct_uv_cmd_with_additional_deps() -> None:requirements = f.read()assert "numpy>=1.20.0" in requirementsassert "pandas" in requirements+++def test_markdown_sandbox(tmp_path: Path) -> None:+ # Test Python version requirement is passed through+ script_path = tmp_path / "test.md"+ script_path.write_text(+ """---+title: Test+pyproject: |+ requires-python = ">=3.11"+ dependencies = ["numpy"]+---++Hello world!"""+ )+ uv_cmd = construct_uv_command(+ ["edit", str(script_path), "--sandbox"],+ str(script_path),+ additional_features=[],+ additional_deps=[],+ )+ assert "--python" in uv_cmd+ assert ">=3.11" in uv_cmd+ assert "--isolated" in uv_cmd+ assert "--no-project" in uv_cmd+ assert "--compile-bytecode" in uv_cmd+ assert "--sandbox" not in uv_cmd++ req_file_index = uv_cmd.index("--with-requirements") + 1+ req_file_path = uv_cmd[req_file_index]+ with open(req_file_path) as f:+ requirements = f.read()+ assert "numpy" in requirements+++def test_markdown_header(tmp_path: Path) -> None:+ # Test Python version requirement is passed through+ script_path = tmp_path / "test.md"+ script_path.write_text(+ """---+title: Test+pyproject: |+header: |+ #! /usr/bin/env python+ # /// script+ # requires-python = ">=3.11"+ # dependencies = ["numpy"]+ # ///+ "Other metadata"+---+import marimo+ """+ )+ uv_cmd = construct_uv_command(+ ["edit", str(script_path), "--sandbox"],+ str(script_path),+ additional_features=[],+ additional_deps=[],+ )+ assert "--python" in uv_cmd+ assert ">=3.11" in uv_cmd+ assert "--isolated" in uv_cmd+ assert "--no-project" in uv_cmd+ assert "--compile-bytecode" in uv_cmd+ assert "--sandbox" not in uv_cmd++ req_file_index = uv_cmd.index("--with-requirements") + 1+ req_file_path = uv_cmd[req_file_index]+ with open(req_file_path) as f:+ requirements = f.read()+ assert "numpy" in requirements+++def test_markdown_sandbox_and_header(tmp_path: Path) -> None:+ # Test Python version requirement is passed through+ script_path = tmp_path / "test.md"+ script_path.write_text(+ """---+title: Test+pyproject: |+ requires-python = ">=3.11"+ dependencies = ["numpy"]+header: |+ #! /usr/bin/env python+---+import marimo+ """+ )+ uv_cmd = construct_uv_command(+ ["edit", str(script_path), "--sandbox"],+ str(script_path),+ additional_features=[],+ additional_deps=[],+ )+ assert "--python" in uv_cmd+ assert ">=3.11" in uv_cmd+ assert "--isolated" in uv_cmd+ assert "--no-project" in uv_cmd+ assert "--compile-bytecode" in uv_cmd+ assert "--sandbox" not in uv_cmd++ req_file_index = uv_cmd.index("--with-requirements") + 1+ req_file_path = uv_cmd[req_file_index]+ with open(req_file_path) as f:+ requirements = f.read()+ assert "numpy" in requirementsdiff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.pyindex ad63161718..076a3df263 100644--- a/tests/_server/test_file_manager.py+++ b/tests/_server/test_file_manager.py@@ -148,6 +148,27 @@ def test_rename_different_filetype(app_file_manager: AppFileManager) -> None:assert "app = marimo.App()" not in contents+def test_rename_to_qmd(app_file_manager: AppFileManager) -> None:+ initial_filename = app_file_manager.filename+ assert initial_filename+ assert initial_filename.endswith(".py")+ with open(initial_filename) as f:+ contents = f.read()+ assert "app = marimo.App()" in contents+ assert "marimo-team/marimo" not in contents+ assert "marimo-version" not in contents+ app_file_manager.rename(initial_filename[:-3] + ".qmd")+ next_filename = app_file_manager.filename+ assert next_filename+ assert next_filename.endswith(".qmd")+ with open(next_filename) as f:+ contents = f.read()+ assert "marimo-version" in contents+ assert "filters:" in contents+ assert "marimo-team/marimo" in contents+ assert "app = marimo.App()" not in contents++def test_save_app_config_valid(app_file_manager: AppFileManager) -> None:app_file_manager.filename = "app_config.py"try: