A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: use script metadata for config and deps in pyodide (#4806)
Myles Scolnick701cce8e7a95
diff --git a/.cursor/rules/python.mdc b/.cursor/rules/python.mdcindex 10d2f708c7..023cfa3467 100644--- a/.cursor/rules/python.mdc+++ b/.cursor/rules/python.mdc@@ -1,6 +1,6 @@----description:-globs:+description:+globs:alwaysApply: true------@@ -34,7 +34,7 @@ Logging Format```pythonfrom marimo import _loggers-+LOGGER = _loggers.marimo_logger()LOGGER.info("Debugging applications with params %s %s", "key1", "key2")@@ -54,12 +54,13 @@ SecurityTesting- Changes or new functionality in the codebase should come with unit tests using pytest.- Tests exist in the tests folder.+ - We use pytest-asyncio globally, so you don't need to add `@pytest.mark.asyncio`- Utilize snapshot testing where appropriate:-+```from tests.mocks import snapshotter- snapshot = snapshotter(__file__)+ snapshot = snapshotter(__file__)snapshot(filename, output)```@@ -71,4 +72,4 @@ Unit tests- demonstrate every use case. The rule of thumb is: if it can happen, it should be covered- To run a test using hatch, you can run the following command:`hatch run +py=3.12 test:test tests/path/to/test.py`- `hatch run +py=3.12 test-optional:test tests/path/to/test.py` (when the test includes an optional dependency)\ No newline at end of file+ `hatch run +py=3.12 test-optional:test tests/path/to/test.py` (when the test includes an optional dependency)diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex 7162a91444..4115ec4641 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -3,22 +3,23 @@ from __future__ import annotationsimport atexitimport os-import reimport signalimport subprocessimport sysimport tempfilefrom pathlib import Path-from typing import Any, Literal, Optional, cast+from typing import Any, Literal, Optionalimport clickfrom marimo import __version__, _loggers-from marimo._cli.file_path import FileContentReaderfrom marimo._cli.print import bold, echo, green, mutedfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._dependencies.dependencies import DependencyManager-from marimo._utils.scripts import read_pyproject_from_script+from marimo._utils.inline_script_metadata import (+ PyProjectReader,+ is_marimo_dependency,+)from marimo._utils.versions import is_editableLOGGER = _loggers.marimo_logger()@@ -26,188 +27,6 @@ LOGGER = _loggers.marimo_logger()DepFeatures = Literal["lsp", "recommended"]-class PyProjectReader:- def __init__(self, project: dict[str, Any]):- self.project = project-- @staticmethod- def from_filename(name: str) -> PyProjectReader:- return PyProjectReader(_get_pyproject_from_filename(name) or {})-- @staticmethod- def from_script(script: str) -> PyProjectReader:- return PyProjectReader(read_pyproject_from_script(script) or {})-- @property- def extra_index_urls(self) -> list[str]:- # See https://docs.astral.sh/uv/reference/settings/#pip_extra-index-url- return ( # type: ignore[no-any-return]- self.project.get("tool", {})- .get("uv", {})- .get("extra-index-url", [])- )-- @property- def index_configs(self) -> list[dict[str, str]]:- # See https://docs.astral.sh/uv/reference/settings/#index- return self.project.get("tool", {}).get("uv", {}).get("index", []) # type: ignore[no-any-return]-- @property- def index_url(self) -> str | None:- # See https://docs.astral.sh/uv/reference/settings/#pip_index-url- return ( # type: ignore[no-any-return]- self.project.get("tool", {}).get("uv", {}).get("index-url", None)- )-- @property- def python_version(self) -> str | None:- try:- version = self.project.get("requires-python")- # Only return string version requirements- if not isinstance(version, str):- return None- return version- except Exception as e:- LOGGER.warning(f"Failed to parse Python version requirement: {e}")- return None-- @property- def dependencies(self) -> list[str]:- return self.project.get("dependencies", []) # type: ignore[no-any-return]-- @property- def requirements_txt_lines(self) -> list[str]:- """Get dependencies from string representation of script."""- try:- return _pyproject_toml_to_requirements_txt(self.project)- except Exception as e:- LOGGER.warning(f"Failed to parse dependencies: {e}")- 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]:- """- Convert a pyproject.toml file to a requirements.txt file.-- If there is a `[tool.uv.sources]` section, we resolve the dependencies- to their corresponding source.-- # dependencies = [- # "python-gcode",- # ]- #- # [tool.uv.sources]- # python-gcode = { git = "https://github.com/fetlab/python_gcode", rev = "new" }- """ # noqa: E501- dependencies = cast(list[str], pyproject.get("dependencies", []))- if not dependencies:- return []-- uv_sources = pyproject.get("tool", {}).get("uv", {}).get("sources", {})-- for dependency, source in uv_sources.items():- # Find the index of the dependency. This may have a version- # attached, so we cannot do .index()- dep_index: int | None = None- for i, dep in enumerate(dependencies):- if (- dep == dependency- or dep.startswith(f"{dependency}==")- or dep.startswith(f"{dependency}<")- or dep.startswith(f"{dependency}>")- or dep.startswith(f"{dependency}~")- ):- dep_index = i- break-- if dep_index is None:- continue-- new_dependency = None-- # Handle git dependencies- if "git" in source:- git_url = f"git+{source['git']}"- ref = (- source.get("rev") or source.get("branch") or source.get("tag")- )- new_dependency = (- f"{dependency} @ {git_url}@{ref}"- if ref- else f"{dependency} @ {git_url}"- )- # Handle local paths- elif "path" in source:- new_dependency = f"{dependency} @ {source['path']}"-- # Handle URLs- elif "url" in source:- new_dependency = f"{dependency} @ {source['url']}"-- if new_dependency:- if source.get("marker"):- new_dependency += f"; {source['marker']}"-- dependencies[dep_index] = new_dependency-- return dependencies---def _get_pyproject_from_filename(name: str) -> dict[str, Any] | None:- try:- contents, _ = FileContentReader().read_file(name)- 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 None- except Exception:- LOGGER.warning(f"Failed to read pyproject.toml from {name}")- return None--def maybe_prompt_run_in_sandbox(name: str | None) -> bool:if GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA:return False@@ -251,13 +70,6 @@ def maybe_prompt_run_in_sandbox(name: str | None) -> bool:return False-def _is_marimo_dependency(dependency: str) -> bool:- # Split on any version specifier- without_version = re.split(r"[=<>~]+", dependency)[0]- # Match marimo and marimo[extras], but not marimo-<something-else>- return without_version == "marimo" or without_version.startswith("marimo[")--def _is_versioned(dependency: str) -> bool:return any(c in dependency for c in ("==", ">=", "<=", ">", "<", "~"))@@ -284,7 +96,7 @@ def _normalize_sandbox_dependencies(return dep.replace("marimo", f"marimo[{','.join(features)}]")# Find all marimo dependencies- marimo_deps = [d for d in dependencies if _is_marimo_dependency(d)]+ marimo_deps = [d for d in dependencies if is_marimo_dependency(d)]if not marimo_deps:if is_editable("marimo"):LOGGER.info("Using editable of marimo for sandbox")@@ -299,7 +111,7 @@ def _normalize_sandbox_dependencies(chosen = bracketed if bracketed else marimo_deps[0]# Remove all marimo deps- filtered = [d for d in dependencies if not _is_marimo_dependency(d)]+ filtered = [d for d in dependencies if not is_marimo_dependency(d)]if is_editable("marimo"):LOGGER.info("Using editable of marimo for sandbox")diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex f897de35f7..f01aae5186 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -457,7 +457,16 @@ def merge_default_config(def merge_config(config: MarimoConfig, new_config: PartialMarimoConfig | MarimoConfig) -> MarimoConfig:- """Merge a user configuration with a new configuration."""+ """Merge a user configuration with a new configuration. The new config+ will take precedence over the default config.++ Args:+ config: The default configuration.+ new_config: The new configuration to merge with the default config.++ Returns:+ A merged configuration.+ """# Remove the keymap overrides from the incoming config,# so that they don't get merged into the new configif new_config.get("keymap", {}).get("overrides") is not None:diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex ba7661fa27..b9e50b512e 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -202,6 +202,7 @@ class DependencyManager:docstring_to_markdown = Dependency("docstring_to_markdown", min_version="0.17.0")+ tomlkit = Dependency("tomlkit")# Version requirements to properly support the new superfences introduced in# pymdown#2470diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.pyindex f13ac84ab9..cac4f99527 100644--- a/marimo/_output/formatters/formatters.py+++ b/marimo/_output/formatters/formatters.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport sysfrom typing import TYPE_CHECKING, Any, Callable+from marimo import _loggersfrom marimo._config.config import Themefrom marimo._output.formatters.ai_formatters import (GoogleAiFormatter,@@ -37,6 +38,8 @@ from marimo._output.formatters.structures import StructuresFormatterfrom marimo._output.formatters.sympy_formatters import SympyFormatterfrom marimo._output.formatters.tqdm_formatters import TqdmFormatter+LOGGER = _loggers.marimo_logger()+if TYPE_CHECKING:from collections.abc import Sequence@@ -149,7 +152,13 @@ def register_formatters(theme: Theme = "light") -> None:original_find_spec=original_find_spec,) -> Any:del self- spec = original_find_spec(fullname, path, target)++ try:+ spec = original_find_spec(fullname, path, target)+ except Exception as e:+ LOGGER.warning(f"Error finding spec for {fullname}: {e}")+ spec = None+if spec is None:return specdiff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.pyindex 8ca98e8429..9166e78a5f 100644--- a/marimo/_pyodide/bootstrap.py+++ b/marimo/_pyodide/bootstrap.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonfrom typing import TYPE_CHECKING, Callable+from marimo._config.config import merge_configfrom marimo._messaging.ops import KernelCapabilities, KernelReady, serializefrom marimo._plugins.core.json_encoder import WebComponentEncoderfrom marimo._runtime.requests import (@@ -83,8 +84,16 @@ def create_session(# Lazy import to decrease startup timefrom marimo._config.config import merge_default_config+ from marimo._config.manager import ScriptConfigManager+ # Add default configuser_config = merge_default_config(user_config)+ script_config = ScriptConfigManager(filename).get_config(+ hide_secrets=False+ )+ # Merge with inline script-metadata config+ user_config = merge_config(user_config, script_config)+app_file_manager = AppFileManager(filename=filename,default_width=user_config["display"]["default_width"],diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex b3102a5f28..c7fecf28a9 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -5,14 +5,16 @@ import asyncioimport base64import dataclassesimport json+import reimport signalfrom pathlib import Path-from typing import Any, Callable, Optional+from typing import Callablefrom marimo import _loggersfrom marimo._ast.cell import CellConfigfrom marimo._config.config import MarimoConfigfrom marimo._messaging.types import KernelMessage+from marimo._pyodide.restartable_task import RestartableTaskfrom marimo._pyodide.streams import (PyodideStderr,PyodideStdin,@@ -66,6 +68,7 @@ from marimo._snippets.snippets import read_snippetsfrom marimo._types.ids import CellId_tfrom marimo._utils.case import deep_to_camel_casefrom marimo._utils.formatter import DefaultFormatter+from marimo._utils.inline_script_metadata import PyProjectReaderfrom marimo._utils.parse_dataclass import parse_rawLOGGER = _loggers.marimo_logger()@@ -158,14 +161,39 @@ class PyodideSession:Find the packages in the code based on the imports,and mapping from module names to package names."""- import pyodide.code # type: ignore- imports: list[str] = pyodide.code.find_imports(code) # type: ignore- if not isinstance(imports, list):- return []+ # Prefer dependencies from script metadata+ try:+ reader = PyProjectReader.from_script(code)+ script_deps = reader.dependencies- package_manager = MicropipPackageManager()- return [package_manager.module_to_package(im) for im in imports]+ def strip_version(dep: str) -> str:+ try:+ return re.split(r"==|>=|<=|~=", dep)[0]+ except Exception:+ return dep++ if len(script_deps) > 0:+ return [strip_version(dep) for dep in script_deps]+ except Exception as e:+ LOGGER.warning("Error parsing script metadata: %s", e)++ try:+ import pyodide.code # type: ignore++ # Get imports from code+ module_names: list[str] = pyodide.code.find_imports(code) # type: ignore+ if not isinstance(module_names, list):+ return []++ # Convert module names to package names+ package_manager = MicropipPackageManager()+ return [+ package_manager.module_to_package(mod) for mod in module_names+ ]+ except Exception as e:+ LOGGER.warning("Error finding packages: %s", e)+ return []class PyodideBridge:@@ -407,34 +435,3 @@ def _launch_pyodide_kernel(await asyncio.gather(listen_messages(), listen_completion())return RestartableTask(listen)---class RestartableTask:- def __init__(self, coro: Callable[[], Any]):- self.coro = coro- self.task: Optional[asyncio.Task[Any]] = None- self.stopped = False-- async def start(self) -> None:- """Create a task that runs the coro."""- while True:- if self.stopped:- break-- try:- self.task = asyncio.create_task(self.coro())- await self.task- except asyncio.CancelledError:- pass-- def stop(self) -> None:- # Stop the task and set the stopped flag- self.stopped = True- assert self.task is not None- self.task.cancel()-- def restart(self) -> None:- # Cancel the current task, which will cause- # the while loop to start a new task- assert self.task is not None- self.task.cancel()diff --git a/marimo/_pyodide/restartable_task.py b/marimo/_pyodide/restartable_task.pynew file mode 100644index 0000000000..54410bcc89--- /dev/null+++ b/marimo/_pyodide/restartable_task.py@@ -0,0 +1,33 @@+import asyncio+from typing import Any, Callable, Optional+++class RestartableTask:+ def __init__(self, coro: Callable[[], Any]):+ self.coro = coro+ self.task: Optional[asyncio.Task[Any]] = None+ self.stopped = False++ async def start(self) -> None:+ """Create a task that runs the coro."""+ while True:+ if self.stopped:+ break++ try:+ self.task = asyncio.create_task(self.coro())+ await self.task+ except asyncio.CancelledError:+ pass++ def stop(self) -> None:+ # Stop the task and set the stopped flag+ self.stopped = True+ assert self.task is not None+ self.task.cancel()++ def restart(self) -> None:+ # Cancel the current task, which will cause+ # the while loop to start a new task+ assert self.task is not None+ self.task.cancel()diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.pyindex 3dd34904d0..dba5dcfd9d 100644--- a/marimo/_pyodide/streams.py+++ b/marimo/_pyodide/streams.py@@ -162,9 +162,11 @@ class PyodideStdin(Stdin):console=CellOutput.stdin(prompt),).broadcast(self.stream)+ return self._get_response()++ def _get_response(self) -> str:loop = asyncio.get_event_loop()- response = loop.run_until_complete(self.stream.input_queue.get())- return response+ return loop.run_until_complete(self.stream.input_queue.get())def readline(self, size: int | None = -1) -> str: # type: ignore[override] # noqa: E501# size only included for compatibility with sys.stdin.readline API;diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.pyindex 95b9839776..362256cb94 100644--- a/marimo/_runtime/packages/pypi_package_manager.py+++ b/marimo/_runtime/packages/pypi_package_manager.py@@ -204,8 +204,10 @@ class UvPackageManager(PypiPackageManager):packages_to_remove: list[str],) -> None:from marimo._cli.convert.markdown import extract_frontmatter- from marimo._cli.sandbox import get_headers_from_frontmatterfrom marimo._utils import yaml+ from marimo._utils.inline_script_metadata import (+ get_headers_from_frontmatter,+ )# Get script metadatawith open(filepath) as f:diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex 6060a4f4f6..afa6e9d884 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -151,7 +151,9 @@ class AppFileManager:# reparsing it. Also would allow for md equivalent in a field like# `description`.if type_changed:- from marimo._cli.sandbox import get_headers_from_markdown+ from marimo._utils.inline_script_metadata import (+ get_headers_from_markdown,+ )with open(filename, encoding="utf-8") as f:markdown = f.read()diff --git a/marimo/_utils/config/config.py b/marimo/_utils/config/config.pyindex 60af4790be..fcb022b4d0 100644--- a/marimo/_utils/config/config.py+++ b/marimo/_utils/config/config.py@@ -7,7 +7,7 @@ from tempfile import TemporaryDirectoryfrom typing import Any, Optional, TypeVarfrom marimo._utils.parse_dataclass import parse_raw-from marimo._utils.toml import read_toml+from marimo._utils.toml import is_toml_error, read_tomlROOT_DIR = ".marimo"@@ -31,13 +31,13 @@ class ConfigReader:return ConfigReader(filepath)def read_toml(self, cls: type[T], *, fallback: T) -> T:- import tomlkit-try:data = read_toml(self.filepath)return parse_raw(data, cls, allow_unknown_keys=True)- except (FileNotFoundError, tomlkit.exceptions.TOMLKitError):- return fallback+ except Exception as e:+ if is_toml_error(e) or isinstance(e, FileNotFoundError):+ return fallback+ raise edef write_toml(self, data: Any) -> None:import tomlkitdiff --git a/marimo/_utils/inline_script_metadata.py b/marimo/_utils/inline_script_metadata.pynew file mode 100644index 0000000000..f979fa5958--- /dev/null+++ b/marimo/_utils/inline_script_metadata.py@@ -0,0 +1,200 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import re+from typing import Any, cast++from marimo import _loggers+from marimo._cli.file_path import FileContentReader+from marimo._utils.scripts import read_pyproject_from_script++LOGGER = _loggers.marimo_logger()+++class PyProjectReader:+ def __init__(self, project: dict[str, Any]):+ self.project = project++ @staticmethod+ def from_filename(name: str) -> PyProjectReader:+ return PyProjectReader(_get_pyproject_from_filename(name) or {})++ @staticmethod+ def from_script(script: str) -> PyProjectReader:+ return PyProjectReader(read_pyproject_from_script(script) or {})++ @property+ def extra_index_urls(self) -> list[str]:+ # See https://docs.astral.sh/uv/reference/settings/#pip_extra-index-url+ return ( # type: ignore[no-any-return]+ self.project.get("tool", {})+ .get("uv", {})+ .get("extra-index-url", [])+ )++ @property+ def index_configs(self) -> list[dict[str, str]]:+ # See https://docs.astral.sh/uv/reference/settings/#index+ return self.project.get("tool", {}).get("uv", {}).get("index", []) # type: ignore[no-any-return]++ @property+ def index_url(self) -> str | None:+ # See https://docs.astral.sh/uv/reference/settings/#pip_index-url+ return ( # type: ignore[no-any-return]+ self.project.get("tool", {}).get("uv", {}).get("index-url", None)+ )++ @property+ def python_version(self) -> str | None:+ try:+ version = self.project.get("requires-python")+ # Only return string version requirements+ if not isinstance(version, str):+ return None+ return version+ except Exception as e:+ LOGGER.warning(f"Failed to parse Python version requirement: {e}")+ return None++ @property+ def dependencies(self) -> list[str]:+ return self.project.get("dependencies", []) # type: ignore[no-any-return]++ @property+ def requirements_txt_lines(self) -> list[str]:+ """Get dependencies from string representation of script."""+ try:+ return _pyproject_toml_to_requirements_txt(self.project)+ except Exception as e:+ LOGGER.warning(f"Failed to parse dependencies: {e}")+ return []+++def _get_pyproject_from_filename(name: str) -> dict[str, Any] | None:+ try:+ contents, _ = FileContentReader().read_file(name)+ 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 None+ except Exception:+ LOGGER.warning(f"Failed to read pyproject.toml from {name}")+ return None+++def _pyproject_toml_to_requirements_txt(+ pyproject: dict[str, Any],+) -> list[str]:+ """+ Convert a pyproject.toml file to a requirements.txt file.++ If there is a `[tool.uv.sources]` section, we resolve the dependencies+ to their corresponding source.++ # dependencies = [+ # "python-gcode",+ # ]+ #+ # [tool.uv.sources]+ # python-gcode = { git = "https://github.com/fetlab/python_gcode", rev = "new" }+ """ # noqa: E501+ dependencies = cast(list[str], pyproject.get("dependencies", []))+ if not dependencies:+ return []++ uv_sources = pyproject.get("tool", {}).get("uv", {}).get("sources", {})++ for dependency, source in uv_sources.items():+ # Find the index of the dependency. This may have a version+ # attached, so we cannot do .index()+ dep_index: int | None = None+ for i, dep in enumerate(dependencies):+ if (+ dep == dependency+ or dep.startswith(f"{dependency}==")+ or dep.startswith(f"{dependency}<")+ or dep.startswith(f"{dependency}>")+ or dep.startswith(f"{dependency}~")+ ):+ dep_index = i+ break++ if dep_index is None:+ continue++ new_dependency = None++ # Handle git dependencies+ if "git" in source:+ git_url = f"git+{source['git']}"+ ref = (+ source.get("rev") or source.get("branch") or source.get("tag")+ )+ new_dependency = (+ f"{dependency} @ {git_url}@{ref}"+ if ref+ else f"{dependency} @ {git_url}"+ )+ # Handle local paths+ elif "path" in source:+ new_dependency = f"{dependency} @ {source['path']}"++ # Handle URLs+ elif "url" in source:+ new_dependency = f"{dependency} @ {source['url']}"++ if new_dependency:+ if source.get("marker"):+ new_dependency += f"; {source['marker']}"++ dependencies[dep_index] = new_dependency++ return dependencies+++def is_marimo_dependency(dependency: str) -> bool:+ # Split on any version specifier+ without_version = re.split(r"[=<>~]+", dependency)[0]+ # Match marimo and marimo[extras], but not marimo-<something-else>+ return without_version == "marimo" or without_version.startswith("marimo[")+++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 headersdiff --git a/marimo/_utils/scripts.py b/marimo/_utils/scripts.pyindex 0b2a4e5745..f1ea4a5145 100644--- a/marimo/_utils/scripts.py+++ b/marimo/_utils/scripts.py@@ -4,6 +4,8 @@ from __future__ import annotationsimport refrom typing import Any+from marimo._utils.toml import read_toml_string+REGEX = (r"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$")@@ -26,10 +28,8 @@ def read_pyproject_from_script(script: str) -> dict[str, Any] | None:line[2:] if line.startswith("# ") else line[1:]for line in matches[0].group("content").splitlines(keepends=True))- import tomlkit-- pyproject = tomlkit.parse(content)+ pyproject = read_toml_string(content)return pyprojectelse:return Nonediff --git a/marimo/_utils/toml.py b/marimo/_utils/toml.pyindex 6d7705e6cc..df68317eb6 100644--- a/marimo/_utils/toml.py+++ b/marimo/_utils/toml.py@@ -3,13 +3,50 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any, Union+from marimo._dependencies.dependencies import DependencyManager+if TYPE_CHECKING:from pathlib import Pathdef read_toml(file_path: Union[str, Path]) -> dict[str, Any]:"""Read and parse a TOML file."""- import tomlkit- with open(file_path, "rb") as file:- return tomlkit.load(file)+ # tomllib is only available in python 3.11++ if DependencyManager.tomlkit.has():+ import tomlkit++ with open(file_path, "rb") as file:+ return tomlkit.load(file)+ else:+ import tomllib++ with open(file_path, "rb") as file:+ return tomllib.load(file)+++def read_toml_string(s: str) -> dict[str, Any]:+ """Read and parse a TOML string."""++ # tomllib is only available in python 3.11++ if DependencyManager.tomlkit.has():+ import tomlkit++ return tomlkit.loads(s)+ else:+ import tomllib++ return tomllib.loads(s)+++def is_toml_error(e: Exception) -> bool:+ """Check if an exception is a TOML error."""++ if DependencyManager.tomlkit.has():+ import tomlkit++ return isinstance(e, tomlkit.exceptions.TOMLKitError)+ else:+ import tomllib++ return isinstance(e, tomllib.TOMLDecodeError)diff --git a/pyproject.toml b/pyproject.tomlindex b4e95a16b0..a44ab52fe5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -473,6 +473,7 @@ minversion = "6.0"addopts = "-ra -q -v --ignore tests/_cli/ipynb_data --ignore tests/_ast/codegen_data --ignore tests/_ast/app_data"testpaths = ["tests"]asyncio_mode = "auto"+asyncio_default_fixture_loop_scope = "function"timeout = 30 # seconds, per test[tool.coverage.run]diff --git a/tests/_cli/snapshots/has-header.md.txt b/tests/_cli/snapshots/has-header.md.txtnew file mode 100644index 0000000000..087e63561e--- /dev/null+++ b/tests/_cli/snapshots/has-header.md.txt@@ -0,0 +1,10 @@+---+title: Test Notebook+marimo-version: 0.0.0+header: |-+ #!/usr/bin/env python+---++```python {.marimo}++```\ No newline at end of filediff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.pyindex 7af6d2ae70..583562ccbe 100644--- a/tests/_cli/test_sandbox.py+++ b/tests/_cli/test_sandbox.py@@ -3,255 +3,16 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyfrom unittest.mock import patch-import pytest-from marimo._cli.sandbox import (- PyProjectReader,- _is_marimo_dependency,_normalize_sandbox_dependencies,- _pyproject_toml_to_requirements_txt,construct_uv_command,)-from marimo._utils.scripts import read_pyproject_from_script+from marimo._utils.inline_script_metadata import PyProjectReaderif TYPE_CHECKING:from pathlib import Path-def test_get_dependencies():- SCRIPT = """-# Copyright 2024 Marimo. All rights reserved.-# /// script-# requires-python = ">=3.11"-# dependencies = [-# "polars",-# "marimo>=0.8.0",-# "quak",-# "vega-datasets",-# ]-# ///--import marimo--__generated_with = "0.8.2"-app = marimo.App(width="medium")-"""- assert PyProjectReader.from_script(SCRIPT).dependencies == [- "polars",- "marimo>=0.8.0",- "quak",- "vega-datasets",- ]---def test_get_dependencies_github():- url = "https://github.com/marimo-team/marimo/blob/a1e1be3190023a86650904249f911b2e6ffb8fac/examples/third_party/leafmap/leafmap_example.py"- assert PyProjectReader.from_filename(url).dependencies == [- "leafmap==0.41.0",- "marimo",- ]---def test_no_dependencies():- SCRIPT = """-import marimo--__generated_with = "0.8.2"-app = marimo.App(width="medium")-"""- assert PyProjectReader.from_script(SCRIPT).dependencies == []---def test_pyproject_toml_to_requirements_txt_git_sources():- pyproject = {- "dependencies": [- "marimo",- "numpy",- "polars",- "altair",- ],- "tool": {- "uv": {- "sources": {- "marimo": {- "git": "https://github.com/marimo-team/marimo.git",- "rev": "main",- },- "numpy": {- "git": "https://github.com/numpy/numpy.git",- "branch": "main",- },- "polars": {- "git": "https://github.com/pola/polars.git",- "branch": "dev",- },- }- }- },- }- assert _pyproject_toml_to_requirements_txt(pyproject) == [- "marimo @ git+https://github.com/marimo-team/marimo.git@main",- "numpy @ git+https://github.com/numpy/numpy.git@main",- "polars @ git+https://github.com/pola/polars.git@dev",- "altair",- ]---def test_pyproject_toml_to_requirements_txt_with_marker():- pyproject = {- "dependencies": [- "marimo",- "polars",- ],- "tool": {- "uv": {- "sources": {- "marimo": {- "git": "https://github.com/marimo-team/marimo.git",- "tag": "0.1.0",- "marker": "python_version >= '3.12'",- }- }- }- },- }- assert _pyproject_toml_to_requirements_txt(pyproject) == [- "marimo @ git+https://github.com/marimo-team/[email protected]; python_version >= '3.12'", # noqa: E501- "polars",- ]---def test_pyproject_toml_to_requirements_txt_with_url_sources():- pyproject = {- "dependencies": [- "marimo",- "polars",- ],- "tool": {- "uv": {- "sources": {- "marimo": {- "url": "https://github.com/marimo-team/marimo/archive/refs/heads/main.zip",- }- }- }- },- }- assert _pyproject_toml_to_requirements_txt(pyproject) == [- "marimo @ https://github.com/marimo-team/marimo/archive/refs/heads/main.zip", # noqa: E501- "polars",- ]---def test_pyproject_toml_to_requirements_txt_with_local_path():- pyproject = {- "dependencies": [- "marimo",- "polars",- ],- "tool": {- "uv": {- "sources": {- "marimo": {- "path": "/Users/me/work/marimo",- }- }- }- },- }- assert _pyproject_toml_to_requirements_txt(pyproject) == [- "marimo @ /Users/me/work/marimo",- "polars",- ]--- "version_spec",- [- "marimo>=0.1.0",- "marimo==0.1.0",- "marimo<=0.1.0",- "marimo>0.1.0",- "marimo<0.1.0",- "marimo~=0.1.0",- ],-)-def test_pyproject_toml_to_requirements_txt_with_versioned_dependencies(- version_spec: str,-):- pyproject = {- "dependencies": [- version_spec,- ],- "tool": {- "uv": {- "sources": {- "marimo": {- "git": "https://github.com/marimo-team/marimo.git",- "rev": "main",- },- }- }- },- }- assert _pyproject_toml_to_requirements_txt(pyproject) == [- "marimo @ git+https://github.com/marimo-team/marimo.git@main",- ]---def test_get_python_version_requirement():- pyproject = {"requires-python": ">=3.11"}- assert PyProjectReader(pyproject).python_version == ">=3.11"-- pyproject = {"dependencies": ["polars"]}- assert PyProjectReader(pyproject).python_version is None-- assert PyProjectReader({}).python_version is None-- pyproject = {"requires-python": {"invalid": "type"}}- assert PyProjectReader(pyproject).python_version is None---def test_get_dependencies_with_python_version():- SCRIPT = """-# /// script-# requires-python = ">=3.11"-# dependencies = ["polars"]-# ///--import marimo-"""- assert PyProjectReader.from_script(SCRIPT).dependencies == ["polars"]-- pyproject = read_pyproject_from_script(SCRIPT)- assert pyproject is not None- assert PyProjectReader(pyproject).python_version == ">=3.11"-- SCRIPT_NO_PYTHON = """-# /// script-# dependencies = ["polars"]-# ///--import marimo-"""- pyproject_no_python = read_pyproject_from_script(SCRIPT_NO_PYTHON)- assert pyproject_no_python is not None- assert PyProjectReader(pyproject_no_python).python_version is None- assert PyProjectReader.from_script(SCRIPT_NO_PYTHON).dependencies == [- "polars"- ]---def test_get_dependencies_with_nonexistent_file():- # Test with a non-existent file- assert (- PyProjectReader.from_filename("nonexistent_file.py").dependencies == []- )-- # Test with empty- assert PyProjectReader.from_filename("").dependencies == []--@patch("marimo._cli.sandbox.is_editable", return_value=False)def test_normalize_marimo_dependencies(mock_is_editable: Any):# Test adding marimo when not present@@ -344,28 +105,6 @@ def test_normalize_marimo_dependencies_editable():assert "marimo" in deps[1]-def test_is_marimo_dependency():- assert _is_marimo_dependency("marimo")- assert _is_marimo_dependency("marimo[extras]")- assert not _is_marimo_dependency("marimo-extras")- assert not _is_marimo_dependency("marimo-ai")-- # With version specifiers- assert _is_marimo_dependency("marimo==0.1.0")- assert _is_marimo_dependency("marimo[extras]>=0.1.0")- assert _is_marimo_dependency("marimo[extras]==0.1.0")- assert _is_marimo_dependency("marimo[extras]~=0.1.0")- assert _is_marimo_dependency("marimo[extras]<=0.1.0")- assert _is_marimo_dependency("marimo[extras]>=0.1.0")- assert _is_marimo_dependency("marimo[extras]<=0.1.0")-- # With other packages- assert not _is_marimo_dependency("numpy")- assert not _is_marimo_dependency("pandas")- assert not _is_marimo_dependency("marimo-ai")- assert not _is_marimo_dependency("marimo-ai==0.1.0")--def test_construct_uv_cmd_marimo_new() -> None:uv_cmd = construct_uv_command(["new"], None, additional_features=[], additional_deps=[]diff --git a/tests/_config/test_reader.py b/tests/_config/test_reader.pyindex b65365e726..f88c7bb144 100644--- a/tests/_config/test_reader.py+++ b/tests/_config/test_reader.py@@ -12,11 +12,11 @@ from marimo._config.reader import (read_marimo_config,read_pyproject_marimo_config,)-from marimo._utils.toml import read_toml+from marimo._utils.toml import is_toml_error, read_tomldef test_read_toml():- toml_content = """+ toml_content = b"""[section]key = "value""""@@ -26,7 +26,7 @@ def test_read_toml():def test_read_marimo_config():- config_content = """+ config_content = b"""[formatting]line_length = 79@@ -132,12 +132,12 @@ def testfind_nearest_pyproject_toml_not_found():def test_read_toml_invalid_content():- invalid_toml = """+ invalid_toml = b"""[invalidkey = value"""- import tomlkit.exceptionswith patch("builtins.open", mock_open(read_data=invalid_toml)):- with pytest.raises(tomlkit.exceptions.UnexpectedCharError):+ with pytest.raises(Exception) as e:read_toml("dummy.toml")+ assert is_toml_error(e.value)diff --git a/tests/_pyodide/test_bootstrap.py b/tests/_pyodide/test_bootstrap.pynew file mode 100644index 0000000000..a979cc1964--- /dev/null+++ b/tests/_pyodide/test_bootstrap.py@@ -0,0 +1,178 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import json+from typing import TYPE_CHECKING, Any, Callable++import pytest++from marimo._config.config import DEFAULT_CONFIG+from marimo._pyodide.bootstrap import create_session, save_file+from marimo._pyodide.pyodide_session import PyodideSession+from marimo._server.model import SessionMode+from marimo._server.models.models import SaveNotebookRequest+from marimo._types.ids import CellId_t++if TYPE_CHECKING:+ from pathlib import Path+++def mock_message_callback() -> Callable[[str], None]:+ def callback(message: str) -> None:+ pass++ return callback+++FILE_CONTENTS = """+import marimo++app = marimo.App()++def _():+ "Hello"+ return+"""+++def mock_app_file(tmp_path: Path) -> Path:+ filename = tmp_path / "test.py"+ filename.write_text(FILE_CONTENTS)+ return filename+++def mock_app_file_with_script_config(tmp_path: Path) -> Path:+ filename = tmp_path / "test.py"+ content = f"""# /// script+# [tool.marimo.runtime]+# auto_instantiate = false+# on_cell_change = "lazy"+# [tool.marimo.display]+# theme = "dark"+# ///++{FILE_CONTENTS}+"""+ filename.write_text(content)+ return filename+++async def test_create_session_with_default_config(+ mock_message_callback: Callable[[str], None],+ mock_app_file: Path,+) -> None:+ session, _ = create_session(+ filename=str(mock_app_file),+ query_params={},+ message_callback=mock_message_callback,+ user_config=DEFAULT_CONFIG,+ )++ assert isinstance(session, PyodideSession)+ assert session.mode == SessionMode.EDIT+++async def test_create_session_with_script_config(+ mock_message_callback: Callable[[str], None],+ mock_app_file_with_script_config: Path,+) -> None:+ session, _ = create_session(+ filename=str(mock_app_file_with_script_config),+ query_params={},+ message_callback=mock_message_callback,+ user_config=DEFAULT_CONFIG,+ )++ # Script config should override default theme+ assert session._initial_user_config["display"]["theme"] == "dark"+++async def test_create_session_with_invalid_script_config(+ mock_message_callback: Callable[[str], None],+ tmp_path: Path,+) -> None:+ # Create a file with invalid config+ filename = tmp_path / "test.py"+ content = """# ---+# marimo:+# invalid: true+# ---++{FILE_CONTENTS}+"""+ filename.write_text(content)++ session, _ = create_session(+ filename=str(filename),+ query_params={},+ message_callback=mock_message_callback,+ user_config=DEFAULT_CONFIG,+ )++ # Invalid config should be ignored and default config should be used+ assert (+ session._initial_user_config["display"]["theme"]+ == DEFAULT_CONFIG["display"]["theme"]+ )+++async def test_instantiate(+ mock_message_callback: Callable[[str], None],+ mock_app_file: Path,+) -> None:+ session, _ = create_session(+ filename=str(mock_app_file),+ query_params={},+ message_callback=mock_message_callback,+ user_config=DEFAULT_CONFIG,+ )++ # Mock the put_control_request method to capture the request+ captured_request = None+ original_put_control_request = session.put_control_request++ def mock_put_control_request(request: Any) -> None:+ nonlocal captured_request+ captured_request = request+ original_put_control_request(request)++ session.put_control_request = mock_put_control_request++ # Call instantiate+ from marimo._pyodide.bootstrap import instantiate++ instantiate(session)++ # Verify the request was created correctly+ assert captured_request is not None+ assert len(captured_request.execution_requests) == 1+ assert captured_request.execution_requests[0].code == '"Hello"'+ assert captured_request.auto_run is True+++def test_save_file(+ mock_app_file: Path,+) -> None:+ # Create a save request+ request = SaveNotebookRequest(+ codes=["print('hello')"],+ names=["cell-1"],+ configs=[{}],+ cell_ids=[CellId_t("cell-1")],+ layout=None,+ filename=str(mock_app_file),+ )++ # Save the file+ save_file(+ request=json.dumps(request.__dict__),+ filename=str(mock_app_file),+ )++ # Verify the file was saved correctly+ saved_content = mock_app_file.read_text()+ assert "print('hello')" in saved_contentdiff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.pynew file mode 100644index 0000000000..5ede017e8d--- /dev/null+++ b/tests/_pyodide/test_pyodide_session.py@@ -0,0 +1,217 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+from textwrap import dedent+from typing import TYPE_CHECKING+from unittest.mock import MagicMock++import pytest++from marimo._ast.app_config import _AppConfig+from marimo._config.config import DEFAULT_CONFIG+from marimo._messaging.types import KernelMessage+from marimo._pyodide.pyodide_session import AsyncQueueManager, PyodideSession+from marimo._runtime.context.types import teardown_context+from marimo._runtime.requests import (+ AppMetadata,+ ExecuteMultipleRequest,+ SetUIElementValueRequest,+ StopRequest,+)+from marimo._server.file_manager import AppFileManager+from marimo._server.model import SessionMode+from marimo._types.ids import CellId_t, UIElementId++if TYPE_CHECKING:+ from collections.abc import AsyncGenerator, Generator+ from pathlib import Path+++def pyodide_app_file(tmp_path: Path) -> Path:+ filename = tmp_path / "test.py"+ filename.write_text(+ """+import marimo++app = marimo.App()++def _():+ "Hello, world!"+ return+"""+ )+ return filename+++def mock_pyodide_http() -> Generator[MagicMock, None, None]:+ import sys++ mock = MagicMock()+ sys.modules["pyodide_http"] = mock+ mock.patch_urllib.return_value = None+ yield mock+ del sys.modules["pyodide_http"]+++def mock_pyodide() -> Generator[MagicMock, None, None]:+ import sys+ from types import ModuleType++ # Create a proper module structure for pyodide+ mock = MagicMock(spec=ModuleType)+ mock.code = MagicMock(spec=ModuleType)+ mock.code.find_imports = MagicMock(+ return_value=["numpy", "pandas", "sklearn"]+ )++ # Save original module if it exists+ original_module = sys.modules.get("pyodide", None)++ # Install our mock+ sys.modules["pyodide"] = mock+ sys.modules["pyodide.code"] = mock++ yield mock++ # Restore original state+ if original_module is not None:+ sys.modules["pyodide"] = original_module+ else:+ del sys.modules["pyodide"]+++async def pyodide_session(+ pyodide_app_file: Path,+) -> AsyncGenerator[PyodideSession, None]:+ def _on_write(msg: KernelMessage) -> None:+ pass++ session = PyodideSession(+ app=AppFileManager(filename=str(pyodide_app_file)),+ mode=SessionMode.EDIT,+ on_write=_on_write,+ app_metadata=AppMetadata(+ query_params={},+ cli_args={},+ app_config=_AppConfig(),+ filename=str(pyodide_app_file),+ ),+ user_config=DEFAULT_CONFIG,+ )+ yield session+ teardown_context()+++async def test_async_queue_manager() -> None:+ async_queue_manager = AsyncQueueManager()+ # Test putting and getting from queues+ stop_request = StopRequest()+ set_ui_element_request = SetUIElementValueRequest(+ object_ids=[UIElementId("test")], values=["test"]+ )++ async_queue_manager.control_queue.put_nowait(stop_request)+ async_queue_manager.set_ui_element_queue.put_nowait(set_ui_element_request)++ assert await async_queue_manager.control_queue.get() == stop_request+ assert (+ await async_queue_manager.set_ui_element_queue.get()+ == set_ui_element_request+ )+++async def test_pyodide_session_start(+ pyodide_session: PyodideSession,+ mock_pyodide_http: MagicMock,+) -> None:+ # Test starting the session+ start_task = asyncio.create_task(pyodide_session.start())+ await asyncio.sleep(0) # Let the task start+ assert pyodide_session.kernel_task is not None+ mock_pyodide_http.patch_urllib.assert_called_once()+ pyodide_session.kernel_task.stop()+ start_task.cancel()+ try:+ await start_task+ except asyncio.CancelledError:+ pass+++async def test_pyodide_session_put_control_request(+ pyodide_session: PyodideSession,+) -> None:+ # Test putting control requests+ execution_request = ExecuteMultipleRequest(+ cell_ids=[CellId_t("test")],+ codes=["test"],+ )+ set_ui_element_request = SetUIElementValueRequest(+ object_ids=[UIElementId("test")], values=["test"]+ )++ pyodide_session.put_control_request(execution_request)+ pyodide_session.put_control_request(set_ui_element_request)++ assert not pyodide_session._queue_manager.control_queue.empty()+ assert not pyodide_session._queue_manager.set_ui_element_queue.empty()+++async def test_pyodide_session_find_packages(+ pyodide_session: PyodideSession,+ mock_pyodide: MagicMock,+) -> None:+ # Test finding packages in code+ code = dedent(+ """+ import numpy as np+ import pandas as pd+ from sklearn.linear_model import LinearRegression+ """+ )++ packages = pyodide_session.find_packages(code)+ # sklearn gets converted to scikit-learn+ assert sorted(packages) == sorted(["numpy", "pandas", "scikit-learn"])+ mock_pyodide.code.find_imports.assert_called_once_with(code)+++async def test_pyodide_session_find_packages_with_script_metadata(+ pyodide_session: PyodideSession,+ mock_pyodide: MagicMock,+) -> None:+ # Test finding packages in code+ code = dedent(+ """+ # /// script+ # dependencies = [+ # "foo",+ # "bar==1.0.0",+ # "baz>=2.0.0",+ # ]+ # ///++ import numpy as np+ import pandas as pd+ """+ )++ packages = pyodide_session.find_packages(code)+ assert sorted(packages) == sorted(["foo", "bar", "baz"])+ mock_pyodide.code.find_imports.assert_not_called()+++async def test_pyodide_session_put_input(+ pyodide_session: PyodideSession,+) -> None:+ # Test putting input+ input_text = "test input"+ pyodide_session.put_input(input_text)++ assert not pyodide_session._queue_manager.input_queue.empty()+ assert await pyodide_session._queue_manager.input_queue.get() == input_textdiff --git a/tests/_pyodide/test_pyodide_streams.py b/tests/_pyodide/test_pyodide_streams.pynew file mode 100644index 0000000000..93f1cf6ea7--- /dev/null+++ b/tests/_pyodide/test_pyodide_streams.py@@ -0,0 +1,186 @@+import asyncio+from unittest.mock import Mock++import pytest++from marimo._pyodide.streams import (+ PyodideStderr,+ PyodideStdin,+ PyodideStdout,+ PyodideStream,+)+from marimo._types.ids import CellId_t++cell_id = CellId_t("test-cell-id")+++def pyodide_pipe() -> Mock:+ return Mock()+++async def pyodide_input_queue() -> asyncio.Queue[str]:+ return asyncio.Queue()+++def pyodide_(+ pyodide_pipe: Mock,+ pyodide_input_queue: asyncio.Queue[str],+) -> PyodideStream:+ return PyodideStream(pyodide_pipe, pyodide_input_queue, cell_id)+++def pyodide_stdout(pyodide_: PyodideStream) -> PyodideStdout:+ return PyodideStdout(pyodide_)+++def pyodide_stderr(pyodide_: PyodideStream) -> PyodideStderr:+ return PyodideStderr(pyodide_)+++def pyodide_stdin(pyodide_: PyodideStream) -> PyodideStdin:+ stdin = PyodideStdin(pyodide_)+ stdin._get_response = lambda: "test input\n"+ return stdin+++class TestPyodideStream:+ def test_write(self, pyodide_: PyodideStream, pyodide_pipe: Mock) -> None:+ op = "test-op"+ data = {"key": "value"}+ pyodide_.write(op, data)+ pyodide_pipe.assert_called_once_with((op, data))+++class TestPyodideStdout:+ def test_writable(self, pyodide_stdout: PyodideStdout) -> None:+ assert pyodide_stdout.writable() is True++ def test_readable(self, pyodide_stdout: PyodideStdout) -> None:+ assert pyodide_stdout.readable() is False++ def test_seekable(self, pyodide_stdout: PyodideStdout) -> None:+ assert pyodide_stdout.seekable() is False++ def test_write(+ self, pyodide_stdout: PyodideStdout, pyodide_pipe: Mock+ ) -> None:+ data = "test output"+ pyodide_stdout.write(data)+ assert pyodide_pipe.call_count == 1+ op, msg = pyodide_pipe.call_args[0][0]+ assert op == "cell-op"+ assert msg["cell_id"] == pyodide_stdout.stream.cell_id+ assert msg["console"]["mimetype"] == "text/plain"+ assert msg["console"]["data"] == data++ def test_writelines(+ self, pyodide_stdout: PyodideStdout, pyodide_pipe: Mock+ ) -> None:+ lines = ["line1\n", "line2\n", "line3\n"]+ pyodide_stdout.writelines(lines)+ assert pyodide_pipe.call_count == 3+++class TestPyodideStderr:+ def test_writable(self, pyodide_stderr: PyodideStderr) -> None:+ assert pyodide_stderr.writable() is True++ def test_readable(self, pyodide_stderr: PyodideStderr) -> None:+ assert pyodide_stderr.readable() is False++ def test_seekable(self, pyodide_stderr: PyodideStderr) -> None:+ assert pyodide_stderr.seekable() is False++ def test_write(+ self, pyodide_stderr: PyodideStderr, pyodide_pipe: Mock+ ) -> None:+ data = "test error"+ pyodide_stderr.write(data)+ assert pyodide_pipe.call_count == 1+ op, msg = pyodide_pipe.call_args[0][0]+ assert op == "cell-op"+ assert msg["cell_id"] == pyodide_stderr.stream.cell_id+ assert msg["console"]["mimetype"] == "text/plain"+ assert msg["console"]["data"] == data++ def test_writelines(+ self, pyodide_stderr: PyodideStderr, pyodide_pipe: Mock+ ) -> None:+ lines = ["error1\n", "error2\n", "error3\n"]+ pyodide_stderr.writelines(lines)+ assert pyodide_pipe.call_count == 3+++class TestPyodideStdin:+ def test_writable(self, pyodide_stdin: PyodideStdin) -> None:+ assert pyodide_stdin.writable() is False++ def test_readable(self, pyodide_stdin: PyodideStdin) -> None:+ assert pyodide_stdin.readable() is True++ async def test_readline(+ self,+ pyodide_stdin: PyodideStdin,+ pyodide_pipe: Mock,+ pyodide_input_queue: asyncio.Queue[str],+ ) -> None:+ # Queue up a response+ await pyodide_input_queue.put("test input\n")+ # Read the line+ result = pyodide_stdin.readline()+ assert result == "test input\n"+ # Verify prompt was sent+ assert pyodide_pipe.call_count == 1+ op, msg = pyodide_pipe.call_args[0][0]+ assert op == "cell-op"+ assert msg["cell_id"] == pyodide_stdin.stream.cell_id+ assert msg["console"]["mimetype"] == "text/plain"+ assert msg["console"]["data"] == ""++ async def test_readline_with_prompt(+ self,+ pyodide_stdin: PyodideStdin,+ pyodide_pipe: Mock,+ pyodide_input_queue: asyncio.Queue[str],+ ) -> None:+ # Queue up a response+ await pyodide_input_queue.put("test input\n")+ # Read the line with prompt+ result = pyodide_stdin._readline_with_prompt("Enter: ")+ assert result == "test input\n"+ # Verify prompt was sent+ assert pyodide_pipe.call_count == 1+ op, msg = pyodide_pipe.call_args[0][0]+ assert op == "cell-op"+ assert msg["cell_id"] == pyodide_stdin.stream.cell_id+ assert msg["console"]["mimetype"] == "text/plain"+ assert msg["console"]["data"] == "Enter: "++ async def test_readlines(+ self,+ pyodide_stdin: PyodideStdin,+ pyodide_pipe: Mock,+ pyodide_input_queue: asyncio.Queue[str],+ ) -> None:+ pyodide_stdin._get_response = Mock(+ return_value="line1\nline2\nline3\n"+ )++ # Queue up a response+ await pyodide_input_queue.put("line1\nline2\nline3\n")+ # Read the lines+ result = pyodide_stdin.readlines()+ assert result == ["line1", "line2", "line3", ""]+ # Verify prompt was sent+ assert pyodide_pipe.call_count == 1+ op, msg = pyodide_pipe.call_args[0][0]+ assert op == "cell-op"+ assert msg["cell_id"] == pyodide_stdin.stream.cell_id+ assert msg["console"]["mimetype"] == "text/plain"+ assert msg["console"]["data"] == ""diff --git a/tests/_pyodide/test_restartable_task.py b/tests/_pyodide/test_restartable_task.pynew file mode 100644index 0000000000..7550b36e55--- /dev/null+++ b/tests/_pyodide/test_restartable_task.py@@ -0,0 +1,124 @@+import asyncio++from marimo._pyodide.restartable_task import RestartableTask+++async def test_restartable_task():+ # Test basic start/stop+ counter = 0+ event = asyncio.Event()++ async def increment_counter():+ nonlocal counter+ counter += 1+ event.set() # Signal that we've incremented+ await asyncio.sleep(0.1)++ task = RestartableTask(increment_counter)+ assert counter == 0++ # Start task+ start_task = asyncio.create_task(task.start())+ await event.wait() # Wait for increment+ assert counter == 1+ event.clear()++ # Stop task+ task.stop()+ await asyncio.sleep(0.1) # Let stop take effect+ assert counter == 1 # Shouldn't increment after stop++ # Cleanup+ start_task.cancel()+ try:+ await start_task+ except asyncio.CancelledError:+ pass+++async def test_restartable_task_restart():+ # Test restart functionality+ counter = 0+ event = asyncio.Event()++ async def increment_counter():+ nonlocal counter+ counter += 1+ event.set() # Signal that we've incremented+ await asyncio.sleep(0.1)++ task = RestartableTask(increment_counter)+ start_task = asyncio.create_task(task.start())++ # Let it run once+ await event.wait()+ assert counter == 1+ event.clear()++ # Restart task+ task.restart()+ await event.wait()+ assert counter == 2 # Should increment again after restart+ event.clear()++ # Stop task+ task.stop()+ await asyncio.sleep(0.1)+ assert counter == 2 # Shouldn't increment after stop++ # Cleanup+ start_task.cancel()+ try:+ await start_task+ except asyncio.CancelledError:+ pass+++async def test_restartable_task_cancellation():+ # Test cancellation handling+ counter = 0+ event = asyncio.Event()+ cancelled = False++ async def increment_counter():+ nonlocal counter, cancelled+ try:+ counter += 1+ event.set() # Signal that we've incremented+ await asyncio.sleep(0.1)+ except asyncio.CancelledError:+ cancelled = True+ event.set() # Signal cancellation+ raise++ task = RestartableTask(increment_counter)+ start_task = asyncio.create_task(task.start())++ # Let it run once+ await event.wait()+ assert counter == 1+ assert not cancelled+ event.clear()++ # Cancel task+ task.restart() # This will cancel the current task+ await event.wait()+ assert cancelled # Should have been cancelled+ event.clear()++ # Let new task run+ await event.wait()+ assert counter == 2 # Should have restarted and incremented again+ event.clear()++ # Stop task+ task.stop()+ await asyncio.sleep(0.1)+ assert counter == 2 # Shouldn't increment after stop++ # Cleanup+ start_task.cancel()+ try:+ await start_task+ except asyncio.CancelledError:+ passdiff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex b5df1b4c4d..2f0811f6ac 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -605,12 +605,11 @@ def __():@save_and_restore_main-def test_watch_mode_config_override() -> None:+def test_watch_mode_config_override(tmp_path: Path) -> None:"""Test that watch mode properly overrides config settings."""# Create a temporary file- with NamedTemporaryFile(delete=False, suffix=".py") as tmp_file:- tmp_path = Path(tmp_file.name)- tmp_file.write(b"import marimo as mo")+ tmp_file = tmp_path / "test_watch_mode_config_override.py"+ tmp_file.write_text("import marimo as mo")# Create a config with autosave enabledconfig_reader = get_default_config_manager(current_path=None)@@ -625,7 +624,7 @@ def test_watch_mode_config_override() -> None:)# Create a session manager with watch mode enabled- file_router = AppFileRouter.from_filename(MarimoPath(str(tmp_path)))+ file_router = AppFileRouter.from_filename(MarimoPath(str(tmp_file)))session_manager = SessionManager(file_router=file_router,mode=SessionMode.EDIT,@@ -673,7 +672,6 @@ def test_watch_mode_config_override() -> None:# Cleanupsession_manager.shutdown()session_manager_no_watch.shutdown()- os.remove(tmp_path)@pytest.mark.skipif(@@ -1059,6 +1057,7 @@ def __():kernel_manager.kernel_task.join()+@save_and_restore_maindef test_session_with_script_config_overrides(tmp_path: Path,) -> None:@@ -1066,7 +1065,7 @@ def test_session_with_script_config_overrides(session_consumer.connection_state.return_value = ConnectionState.OPEN# Create a temporary file with script config- tmp_file = tmp_path / "test.py"+ tmp_file = tmp_path / "test_script_config.py"tmp_file.write_text(dedent("""diff --git a/tests/_utils/test_inline_script_metadata.py b/tests/_utils/test_inline_script_metadata.pynew file mode 100644index 0000000000..4dc480f42b--- /dev/null+++ b/tests/_utils/test_inline_script_metadata.py@@ -0,0 +1,266 @@+from __future__ import annotations++import pytest++from marimo._utils.inline_script_metadata import (+ PyProjectReader,+ _pyproject_toml_to_requirements_txt,+ is_marimo_dependency,+)+from marimo._utils.scripts import read_pyproject_from_script+++def test_get_dependencies():+ SCRIPT = """+# Copyright 2024 Marimo. All rights reserved.+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "polars",+# "marimo>=0.8.0",+# "quak",+# "vega-datasets",+# ]+# ///++import marimo++__generated_with = "0.8.2"+app = marimo.App(width="medium")+"""+ assert PyProjectReader.from_script(SCRIPT).dependencies == [+ "polars",+ "marimo>=0.8.0",+ "quak",+ "vega-datasets",+ ]+++def test_get_dependencies_github():+ url = "https://github.com/marimo-team/marimo/blob/a1e1be3190023a86650904249f911b2e6ffb8fac/examples/third_party/leafmap/leafmap_example.py"+ assert PyProjectReader.from_filename(url).dependencies == [+ "leafmap==0.41.0",+ "marimo",+ ]+++def test_no_dependencies():+ SCRIPT = """+import marimo++__generated_with = "0.8.2"+app = marimo.App(width="medium")+"""+ assert PyProjectReader.from_script(SCRIPT).dependencies == []+++def test_pyproject_toml_to_requirements_txt_git_sources():+ pyproject = {+ "dependencies": [+ "marimo",+ "numpy",+ "polars",+ "altair",+ ],+ "tool": {+ "uv": {+ "sources": {+ "marimo": {+ "git": "https://github.com/marimo-team/marimo.git",+ "rev": "main",+ },+ "numpy": {+ "git": "https://github.com/numpy/numpy.git",+ "branch": "main",+ },+ "polars": {+ "git": "https://github.com/pola/polars.git",+ "branch": "dev",+ },+ }+ }+ },+ }+ assert _pyproject_toml_to_requirements_txt(pyproject) == [+ "marimo @ git+https://github.com/marimo-team/marimo.git@main",+ "numpy @ git+https://github.com/numpy/numpy.git@main",+ "polars @ git+https://github.com/pola/polars.git@dev",+ "altair",+ ]+++def test_pyproject_toml_to_requirements_txt_with_marker():+ pyproject = {+ "dependencies": [+ "marimo",+ "polars",+ ],+ "tool": {+ "uv": {+ "sources": {+ "marimo": {+ "git": "https://github.com/marimo-team/marimo.git",+ "tag": "0.1.0",+ "marker": "python_version >= '3.12'",+ }+ }+ }+ },+ }+ assert _pyproject_toml_to_requirements_txt(pyproject) == [+ "marimo @ git+https://github.com/marimo-team/[email protected]; python_version >= '3.12'", # noqa: E501+ "polars",+ ]+++def test_pyproject_toml_to_requirements_txt_with_url_sources():+ pyproject = {+ "dependencies": [+ "marimo",+ "polars",+ ],+ "tool": {+ "uv": {+ "sources": {+ "marimo": {+ "url": "https://github.com/marimo-team/marimo/archive/refs/heads/main.zip",+ }+ }+ }+ },+ }+ assert _pyproject_toml_to_requirements_txt(pyproject) == [+ "marimo @ https://github.com/marimo-team/marimo/archive/refs/heads/main.zip", # noqa: E501+ "polars",+ ]+++def test_pyproject_toml_to_requirements_txt_with_local_path():+ pyproject = {+ "dependencies": [+ "marimo",+ "polars",+ ],+ "tool": {+ "uv": {+ "sources": {+ "marimo": {+ "path": "/Users/me/work/marimo",+ }+ }+ }+ },+ }+ assert _pyproject_toml_to_requirements_txt(pyproject) == [+ "marimo @ /Users/me/work/marimo",+ "polars",+ ]+++ "version_spec",+ [+ "marimo>=0.1.0",+ "marimo==0.1.0",+ "marimo<=0.1.0",+ "marimo>0.1.0",+ "marimo<0.1.0",+ "marimo~=0.1.0",+ ],+)+def test_pyproject_toml_to_requirements_txt_with_versioned_dependencies(+ version_spec: str,+):+ pyproject = {+ "dependencies": [+ version_spec,+ ],+ "tool": {+ "uv": {+ "sources": {+ "marimo": {+ "git": "https://github.com/marimo-team/marimo.git",+ "rev": "main",+ },+ }+ }+ },+ }+ assert _pyproject_toml_to_requirements_txt(pyproject) == [+ "marimo @ git+https://github.com/marimo-team/marimo.git@main",+ ]+++def test_get_python_version_requirement():+ pyproject = {"requires-python": ">=3.11"}+ assert PyProjectReader(pyproject).python_version == ">=3.11"++ pyproject = {"dependencies": ["polars"]}+ assert PyProjectReader(pyproject).python_version is None++ assert PyProjectReader({}).python_version is None++ pyproject = {"requires-python": {"invalid": "type"}}+ assert PyProjectReader(pyproject).python_version is None+++def test_get_dependencies_with_python_version():+ SCRIPT = """+# /// script+# requires-python = ">=3.11"+# dependencies = ["polars"]+# ///++import marimo+"""+ assert PyProjectReader.from_script(SCRIPT).dependencies == ["polars"]++ pyproject = read_pyproject_from_script(SCRIPT)+ assert pyproject is not None+ assert PyProjectReader(pyproject).python_version == ">=3.11"++ SCRIPT_NO_PYTHON = """+# /// script+# dependencies = ["polars"]+# ///++import marimo+"""+ pyproject_no_python = read_pyproject_from_script(SCRIPT_NO_PYTHON)+ assert pyproject_no_python is not None+ assert PyProjectReader(pyproject_no_python).python_version is None+ assert PyProjectReader.from_script(SCRIPT_NO_PYTHON).dependencies == [+ "polars"+ ]+++def test_get_dependencies_with_nonexistent_file():+ # Test with a non-existent file+ assert (+ PyProjectReader.from_filename("nonexistent_file.py").dependencies == []+ )++ # Test with empty+ assert PyProjectReader.from_filename("").dependencies == []+++def test_is_marimo_dependency():+ assert is_marimo_dependency("marimo")+ assert is_marimo_dependency("marimo[extras]")+ assert not is_marimo_dependency("marimo-extras")+ assert not is_marimo_dependency("marimo-ai")++ # With version specifiers+ assert is_marimo_dependency("marimo==0.1.0")+ assert is_marimo_dependency("marimo[extras]>=0.1.0")+ assert is_marimo_dependency("marimo[extras]==0.1.0")+ assert is_marimo_dependency("marimo[extras]~=0.1.0")+ assert is_marimo_dependency("marimo[extras]<=0.1.0")+ assert is_marimo_dependency("marimo[extras]>=0.1.0")+ assert is_marimo_dependency("marimo[extras]<=0.1.0")++ # With other packages+ assert not is_marimo_dependency("numpy")+ assert not is_marimo_dependency("pandas")+ assert not is_marimo_dependency("marimo-ai")+ assert not is_marimo_dependency("marimo-ai==0.1.0")