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: rich notebook previews through OpenGraph metadata (#8097)
Péter Gyarmatie7ba7bc558be
diff --git a/frontend/src/components/pages/gallery-page.tsx b/frontend/src/components/pages/gallery-page.tsxindex 0e952ff84a..2acfcd374a 100644--- a/frontend/src/components/pages/gallery-page.tsx+++ b/frontend/src/components/pages/gallery-page.tsx@@ -33,6 +33,15 @@ const tabTarget = (path: string): string => {return `${getSessionId()}-${encodeURIComponent(path)}`;};+const isHttpsUrl = (value: string): boolean => {+ try {+ const url = new URL(value);+ return url.protocol === "https:";+ } catch {+ return false;+ }+};+const SEARCH_THRESHOLD = 10;const GalleryPage: React.FC = () => {@@ -43,10 +52,10 @@ const GalleryPage: React.FC = () => {[],);const workspace = response.data;- const files = workspace?.files ?? [];- const root = workspace?.root ?? "";const formattedFiles = useMemo(() => {+ const files = workspace?.files ?? [];+ const root = workspace?.root ?? "";return files.filter((file) => !file.isDirectory).map((file) => {@@ -54,17 +63,28 @@ const GalleryPage: React.FC = () => {root && Paths.isAbsolute(file.path) && file.path.startsWith(root)? Paths.rest(file.path, root): file.path;- const title = titleCase(Paths.basename(relativePath));+ const title =+ file.opengraph?.title ?? titleCase(Paths.basename(relativePath));const subtitle = titleCase(Paths.dirname(relativePath));+ const description = file.opengraph?.description ?? "";+ const opengraphImage = file.opengraph?.image;+ const thumbnailUrl =+ opengraphImage && isHttpsUrl(opengraphImage)+ ? opengraphImage+ : asURL(+ `/og/thumbnail?file=${encodeURIComponent(relativePath)}`,+ ).toString();return {...file,relativePath,title,subtitle,+ description,+ thumbnailUrl,};}).sort((a, b) => a.relativePath.localeCompare(b.relativePath));- }, [files, root]);+ }, [workspace?.files, workspace?.root]);const filteredFiles = useMemo(() => {if (!searchQuery) {@@ -130,8 +150,14 @@ const GalleryPage: React.FC = () => {target={tabTarget(file.path)}className="no-underline">- <Card className="h-full hover:bg-accent/20 transition-colors">- <CardContent className="p-6">+ <Card className="h-full overflow-hidden hover:bg-accent/20 transition-colors">+ <img+ src={file.thumbnailUrl}+ alt={file.title}+ loading="lazy"+ className="w-full aspect-1200/630 object-cover border-b border-border/60"+ />+ <CardContent className="p-6 pt-4"><div className="flex flex-col gap-1">{file.subtitle && (<div className="text-sm font-semibold text-muted-foreground">@@ -141,6 +167,11 @@ const GalleryPage: React.FC = () => {<div className="text-lg font-medium">{file.title}</div>+ {file.description && (+ <div className="text-sm text-muted-foreground line-clamp-3 mt-1">+ {file.description}+ </div>+ )}</div></CardContent></Card>diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 9b81154523..87c8d27178 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -27,6 +27,7 @@ from marimo._cli.print import redfrom marimo._cli.run_docker import (prompt_run_in_docker_container,)+from marimo._cli.tools.commands import toolsfrom marimo._cli.upgrade import check_for_updates, print_latest_versionfrom marimo._cli.utils import (check_app_correctness,@@ -1476,3 +1477,4 @@ main.command()(convert)main.add_command(export)main.add_command(config)main.add_command(development)+main.add_command(tools)diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 200170e4f6..ca1a3b3a69 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -28,6 +28,7 @@ def _generate_server_api_schema() -> dict[str, Any]:import marimo._data.models as dataimport marimo._messaging.errors as errorsimport marimo._messaging.notification as notifications+ import marimo._metadata.opengraph as opengraphimport marimo._runtime.commands as commandsimport marimo._secrets.models as secrets_modelsimport marimo._server.models.completion as completion@@ -132,6 +133,7 @@ def _generate_server_api_schema() -> dict[str, Any]:ToolDefinition,# Sub componentshome.MarimoFile,+ opengraph.OpenGraphMetadata,files.FileInfo,commands.ExecuteCellCommand,snippets.SnippetSection,diff --git a/marimo/_cli/tools/__init__.py b/marimo/_cli/tools/__init__.pynew file mode 100644index 0000000000..fe2d2e388e--- /dev/null+++ b/marimo/_cli/tools/__init__.py@@ -0,0 +1 @@+# Copyright 2026 Marimo. All rights reserved.diff --git a/marimo/_cli/tools/commands.py b/marimo/_cli/tools/commands.pynew file mode 100644index 0000000000..fa33a6b97a--- /dev/null+++ b/marimo/_cli/tools/commands.py@@ -0,0 +1,14 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import click++from marimo._cli.tools.thumbnails import thumbnails++[email protected](help="Utilities for marimo notebooks.")+def tools() -> None:+ pass+++tools.add_command(thumbnails)diff --git a/marimo/_cli/tools/thumbnails.py b/marimo/_cli/tools/thumbnails.pynew file mode 100644index 0000000000..9c9d782d40--- /dev/null+++ b/marimo/_cli/tools/thumbnails.py@@ -0,0 +1,570 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+import json+import subprocess+import threading+from contextlib import AbstractContextManager+from functools import partial+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import TYPE_CHECKING, Any, Optional++import click++from marimo._cli.parse_args import parse_args+from marimo._cli.print import echo, green, red+from marimo._dependencies.dependencies import DependencyManager+from marimo._server.export import run_app_then_export_as_html+from marimo._server.file_router import flatten_files+from marimo._server.files.directory_scanner import DirectoryScanner+from marimo._server.utils import asyncio_run+from marimo._utils.http import HTTPException, HTTPStatus+from marimo._utils.marimo_path import MarimoPath+from marimo._utils.paths import marimo_package_path, maybe_make_dirs++if TYPE_CHECKING:+ from collections.abc import Iterable+ from types import TracebackType+++_sandbox_message = (+ "Render notebooks in an isolated environment, with dependencies tracked "+ "via PEP 723 inline metadata. If already declared, dependencies will "+ "install automatically. Requires uv. Only applies when --execute is used."+)++[email protected](help="Generate and manage notebook thumbnails.")+def thumbnails() -> None:+ pass+++def _split_paths_and_args(+ name: str, args: tuple[str, ...]+) -> tuple[list[str], tuple[str, ...]]:+ paths = [name]+ for index, arg in enumerate(args):+ if arg == "--":+ return paths, args[index + 1 :]+ paths.append(arg)+ return paths, ()+++def _collect_notebooks(paths: Iterable[Path]) -> list[MarimoPath]:+ notebooks: dict[str, MarimoPath] = {}++ for path in paths:+ if path.is_dir():+ scanner = DirectoryScanner(str(path), include_markdown=True)+ try:+ file_infos = scanner.scan()+ except HTTPException as e:+ if e.status_code != HTTPStatus.REQUEST_TIMEOUT:+ raise+ # Match server behavior: use partial results on scan timeout.+ file_infos = scanner.partial_results+ for file_info in flatten_files(file_infos):+ if not file_info.is_marimo_file or file_info.is_directory:+ continue+ absolute_path = str(Path(path) / file_info.path)+ notebooks[absolute_path] = MarimoPath(absolute_path)+ else:+ notebooks[str(path)] = MarimoPath(str(path))++ return [notebooks[k] for k in sorted(notebooks)]+++async def _render_html(+ marimo_path: MarimoPath,+ *,+ execute: bool,+ include_code: bool,+ args: tuple[str, ...],+ asset_url: str | None = None,+ venv_python: str | None = None,+) -> str:+ if not execute:+ from marimo._server.export import export_as_html_without_execution++ result = await export_as_html_without_execution(+ marimo_path, include_code=True, asset_url=asset_url+ )+ return result.text++ if venv_python is None:+ cli_args = parse_args(args) if args else {}+ result = await run_app_then_export_as_html(+ marimo_path,+ include_code=include_code,+ cli_args=cli_args,+ argv=list(args),+ asset_url=asset_url,+ )+ return result.text++ payload = {+ "path": marimo_path.absolute_name,+ "include_code": include_code,+ "args": list(args),+ "asset_url": asset_url,+ }++ # Render in a separate process so we can use a sandboxed venv without polluting the current environment.+ return await asyncio.to_thread(+ _render_html_in_subprocess,+ venv_python,+ payload,+ )+++def _render_html_in_subprocess(+ venv_python: str, payload: dict[str, Any]+) -> str:+ """Render a notebook to HTML in a separate Python process."""+ script = r"""+import asyncio+import json+import sys++from marimo._cli.parse_args import parse_args+from marimo._server.export import run_app_then_export_as_html+from marimo._utils.marimo_path import MarimoPath++payload = json.loads(sys.argv[1])+path = MarimoPath(payload["path"])+include_code = bool(payload.get("include_code", False))+args = payload.get("args") or []+asset_url = payload.get("asset_url")++cli_args = parse_args(tuple(args)) if args else {}+result = asyncio.run(+ run_app_then_export_as_html(+ path,+ include_code=include_code,+ cli_args=cli_args,+ argv=list(args),+ asset_url=asset_url,+ )+)+sys.stdout.write(result.text)+"""++ result = subprocess.run(+ [venv_python, "-c", script, json.dumps(payload)],+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ stderr = result.stderr.strip()+ raise click.ClickException(+ "Failed to render notebook in sandbox.\n\n"+ f"Command:\n\n {venv_python} -c <script>\n\n"+ f"Stderr:\n\n{stderr}"+ )+ return result.stdout+++class _ThumbnailRequestHandler(SimpleHTTPRequestHandler):+ def do_GET(self) -> None: # noqa: N802+ if self.path.split("?", 1)[0] == "/__marimo_thumbnail__.html":+ html = getattr(self.server, "thumbnail_html", "")+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(html.encode("utf-8"))+ return+ return super().do_GET()++ def log_message(self, format: str, *args: Any) -> None: # noqa: A002+ # Silence noisy server logs for CLI usage.+ del format+ del args+ return+++class _ThumbnailHTTPServer(ThreadingHTTPServer):+ # Set by _ThumbnailAssetServer to serve a fresh HTML document per notebook.+ thumbnail_html: str+++class _ThumbnailAssetServer(AbstractContextManager["_ThumbnailAssetServer"]):+ def __init__(self, *, directory: Path) -> None:+ self._directory = directory+ self._server: _ThumbnailHTTPServer | None = None+ self._thread: threading.Thread | None = None++ @property+ def base_url(self) -> str:+ assert self._server is not None+ host, port = self._server.server_address[:2]+ if isinstance(host, bytes):+ host = host.decode("utf-8")+ return f"http://{host}:{port}"++ @property+ def page_url(self) -> str:+ return f"{self.base_url}/__marimo_thumbnail__.html"++ def set_html(self, html: str) -> None:+ assert self._server is not None+ self._server.thumbnail_html = html++ def __enter__(self) -> _ThumbnailAssetServer:+ if not self._directory.is_dir():+ raise click.ClickException(+ f"Static assets not found at {self._directory}"+ )++ handler = partial(+ _ThumbnailRequestHandler, directory=str(self._directory)+ )+ self._server = _ThumbnailHTTPServer(("127.0.0.1", 0), handler)+ self._server.thumbnail_html = ""++ self._thread = threading.Thread(+ target=self._server.serve_forever, daemon=True+ )+ self._thread.start()+ return self++ def __exit__(+ self,+ exc_type: type[BaseException] | None,+ exc: BaseException | None,+ tb: TracebackType | None,+ ) -> None:+ del exc_type+ del exc+ del tb+ if self._server is not None:+ self._server.shutdown()+ self._server.server_close()+ self._server = None+ if self._thread is not None:+ self._thread.join(timeout=1)+ self._thread = None+ return None+++class _SandboxVenvPool:+ def __init__(self) -> None:+ self._envs: dict[tuple[str, ...], tuple[str, str]] = {}++ def get_python(self, notebook_path: str) -> str:+ """Return a venv python path for the notebook's sandbox requirements."""+ from marimo._cli.sandbox import (+ build_sandbox_venv,+ get_sandbox_requirements,+ )++ requirements = tuple(get_sandbox_requirements(notebook_path))+ existing = self._envs.get(requirements)+ if existing is not None:+ return existing[1]++ sandbox_dir, venv_python = build_sandbox_venv(notebook_path)+ self._envs[requirements] = (sandbox_dir, venv_python)+ return venv_python++ def close(self) -> None:+ """Clean up any sandbox environments we created."""+ from marimo._cli.sandbox import cleanup_sandbox_dir++ for sandbox_dir, _ in self._envs.values():+ cleanup_sandbox_dir(sandbox_dir)+ self._envs.clear()+++async def _generate_thumbnails(+ *,+ notebooks: list[MarimoPath],+ width: int,+ height: int,+ scale: int,+ timeout_ms: int,+ output: Optional[Path],+ overwrite: bool,+ include_code: bool,+ execute: bool,+ notebook_args: tuple[str, ...],+ continue_on_error: bool,+ sandbox: bool,+) -> None:+ from marimo._metadata.opengraph import default_opengraph_image++ failures: list[tuple[MarimoPath, Exception]] = []++ try:+ from playwright.async_api import ( # type: ignore[import-not-found]+ async_playwright,+ )+ except ModuleNotFoundError as e:+ if getattr(e, "name", None) == "playwright":+ raise click.ClickException(+ "Playwright is required to generate thumbnails.\n\n"+ " Tip: Install dependencies with:\n\n"+ " pip install 'nbconvert[webpdf]'\n\n"+ " and install Chromium with:\n\n"+ " python -m playwright install chromium"+ ) from None+ raise++ if sandbox and not DependencyManager.which("uv"):+ raise click.ClickException(+ "uv is required for --sandbox thumbnail generation.\n\n"+ " Tip: Install uv from https://github.com/astral-sh/uv"+ )++ static_dir = marimo_package_path() / "_static"++ sandbox_pool: _SandboxVenvPool | None = (+ _SandboxVenvPool() if sandbox else None+ )+ try:+ with _ThumbnailAssetServer(directory=static_dir) as server:+ async with async_playwright() as playwright:+ browser = await playwright.chromium.launch()+ context = await browser.new_context(+ viewport={"width": width, "height": height},+ device_scale_factor=scale,+ )+ page = await context.new_page()+ await page.emulate_media(reduced_motion="reduce")++ for index, notebook in enumerate(notebooks):+ try:+ notebook_dir = notebook.path.parent+ out_path = (+ output+ if output is not None+ else notebook_dir+ / default_opengraph_image(str(notebook.path))+ )+ if out_path.exists() and not overwrite:+ echo(+ red("skip")+ + f": {notebook.short_name} (exists, use --overwrite)"+ )+ continue++ maybe_make_dirs(out_path)++ echo(f"Rendering {notebook.short_name}...")+ venv_python = (+ sandbox_pool.get_python(str(notebook.path))+ if sandbox_pool is not None+ else None+ )+ html = await _render_html(+ notebook,+ execute=execute,+ include_code=include_code,+ args=notebook_args,+ asset_url=server.base_url,+ venv_python=venv_python,+ )+ server.set_html(html)++ echo(f"Screenshotting -> {out_path}...")+ page_url = f"{server.page_url}?v={index}"+ await page.goto(page_url, wait_until="load")+ # Hide chrome and watermarks marked for print so thumbnails stay focused on notebook content.+ await page.add_style_tag(+ content=(+ '.print\\:hidden,[data-testid="watermark"]{display:none !important;}'+ )+ )+ # Nb renderer starts cell contents as invisible for a short period to avoid flicker+ # --> we wait for the first cell container to be visible before snapshotting.+ await page.wait_for_function(+ r"""+() => {+ const root = document.getElementById("root");+ if (!root) return false;++ const cell = document.querySelector('div[id^="cell-"]');+ if (cell) {+ const style = window.getComputedStyle(cell);+ return style.visibility !== "hidden" && style.display !== "none";+ }++ return root.childElementCount > 0;+}+""",+ timeout=30_000,+ )+ await page.wait_for_timeout(timeout_ms)+ await page.screenshot(+ path=str(out_path), full_page=False+ )++ echo(green("ok") + f": {out_path}")+ except Exception as e:+ failures.append((notebook, e))+ echo(red("error") + f": {notebook.short_name}: {e}")+ if not continue_on_error:+ raise++ await context.close()+ await browser.close()+ finally:+ if sandbox_pool is not None:+ sandbox_pool.close()++ if failures:+ raise click.ClickException(+ f"Failed to generate thumbnails for {len(failures)} notebooks."+ )++[email protected](help="Generate OpenGraph thumbnails for notebooks.")+ "name",+ type=click.Path(+ exists=True, file_okay=True, dir_okay=True, path_type=Path+ ),+)+ "--width",+ type=int,+ default=1200,+ show_default=True,+ help="Viewport width for the screenshot.",+)+ "--height",+ type=int,+ default=630,+ show_default=True,+ help="Viewport height for the screenshot.",+)+ "--scale",+ type=click.IntRange(min=1, max=4),+ default=2,+ show_default=True,+ help=(+ "Device scale factor for screenshots. Output resolution will be "+ "`width*scale` x `height*scale`."+ ),+)+ "--timeout-ms",+ type=int,+ default=1500,+ show_default=True,+ help="Additional time to wait after page load before screenshot.",+)+ "--output",+ type=click.Path(path_type=Path),+ default=None,+ help=(+ "Output filename. If omitted, writes to "+ "`<notebook_dir>/__marimo__/assets/<notebook_stem>/opengraph.png`."+ ),+)+ "--overwrite/--no-overwrite",+ default=False,+ show_default=True,+ help="Overwrite existing thumbnails.",+)+ "--include-code/--no-include-code",+ default=False,+ show_default=True,+ help="Whether to include code in the rendered HTML before screenshot.",+)+ "--execute/--no-execute",+ default=False,+ show_default=True,+ help=(+ "Execute notebooks and include their outputs in thumbnails. "+ "In --no-execute mode (default), thumbnails are generated from notebook "+ "structure without running code (and will not include outputs)."+ ),+)+ "--sandbox/--no-sandbox",+ is_flag=True,+ default=None,+ show_default=False,+ type=bool,+ help=_sandbox_message,+)+ "--continue-on-error/--fail-fast",+ default=True,+ show_default=True,+ help="Continue processing other notebooks if one notebook fails.",+)[email protected]("args", nargs=-1, type=click.UNPROCESSED)+def generate(+ name: Path,+ width: int,+ height: int,+ scale: int,+ timeout_ms: int,+ output: Optional[Path],+ overwrite: bool,+ include_code: bool,+ execute: bool,+ sandbox: Optional[bool],+ continue_on_error: bool,+ args: tuple[str, ...],+) -> None:+ """Generate thumbnails for one or more notebooks (or directories)."""+ try:+ DependencyManager.playwright.require("for thumbnail generation")+ except ModuleNotFoundError as e:+ if getattr(e, "name", None) == "playwright":+ raise click.ClickException(+ "Playwright is required for thumbnail generation.\n\n"+ " Tip: Install with:\n\n"+ " python -m pip install playwright\n\n"+ " and install Chromium with:\n\n"+ " python -m playwright install chromium"+ ) from None+ raise++ paths, notebook_args = _split_paths_and_args(str(name), args)+ notebooks = _collect_notebooks([Path(p) for p in paths])+ if not notebooks:+ raise click.ClickException("No marimo notebooks found.")+ if output is not None and len(notebooks) > 1:+ raise click.UsageError(+ "--output can only be used when generating thumbnail for a single notebook."+ )++ from marimo._cli.sandbox import resolve_sandbox_mode++ if not execute and sandbox:+ raise click.UsageError("--sandbox requires --execute.")++ sandbox_mode = (+ resolve_sandbox_mode(sandbox=sandbox, name=str(name))+ if execute+ else None+ )++ asyncio_run(+ _generate_thumbnails(+ notebooks=notebooks,+ width=width,+ height=height,+ scale=scale,+ timeout_ms=timeout_ms,+ output=output,+ overwrite=overwrite,+ include_code=include_code,+ execute=execute,+ notebook_args=notebook_args,+ continue_on_error=continue_on_error,+ sandbox=sandbox_mode is not None,+ )+ )diff --git a/marimo/_metadata/__init__.py b/marimo/_metadata/__init__.pynew file mode 100644index 0000000000..d4c8317748--- /dev/null+++ b/marimo/_metadata/__init__.py@@ -0,0 +1,16 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from marimo._metadata.opengraph import (+ DEFAULT_OPENGRAPH_PLACEHOLDER_IMAGE_GENERATOR,+ OpenGraphMetadata,+ default_opengraph_image,+ resolve_opengraph_metadata,+)++__all__ = [+ "DEFAULT_OPENGRAPH_PLACEHOLDER_IMAGE_GENERATOR",+ "OpenGraphMetadata",+ "default_opengraph_image",+ "resolve_opengraph_metadata",+]diff --git a/marimo/_metadata/opengraph.py b/marimo/_metadata/opengraph.pynew file mode 100644index 0000000000..66176ec2c4--- /dev/null+++ b/marimo/_metadata/opengraph.py@@ -0,0 +1,612 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import ast+import asyncio+import importlib+import inspect+import re+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Literal, cast+from urllib.parse import urlparse++import msgspec++from marimo import _loggers+from marimo._utils.paths import normalize_path+from marimo._utils.scripts import read_pyproject_from_script++LOGGER = _loggers.marimo_logger()++DEFAULT_OPENGRAPH_IMAGE_FILENAME = "opengraph.png"+_WORD_SPLIT_RE = re.compile(r"[_-]+")+_MARIMO_GREEN = "#59b39a"+++class OpenGraphMetadata(msgspec.Struct, rename="camel"):+ """OpenGraph-style metadata for a notebook.++ The `image` field may be either:+ - a relative path (typically under `__marimo__/`), or+ - an absolute HTTPS URL.+ """++ title: str | None = None+ description: str | None = None+ image: str | None = None+++@dataclass(frozen=True)+class OpenGraphConfig:+ """Declarative configuration for resolving notebook OpenGraph metadata."""++ title: str | None = None+ description: str | None = None+ image: str | None = None+ generator: str | None = None+++def _maybe_str(value: Any) -> str | None:+ return value if isinstance(value, str) else None+++def is_https_url(value: str) -> bool:+ """Return True if value is an absolute HTTPS URL."""+ try:+ parsed = urlparse(value)+ except Exception:+ return False+ return parsed.scheme == "https" and bool(parsed.netloc)+++def _normalize_opengraph_image(value: str | None) -> str | None:+ """Normalize an opengraph image value to a safe path (typically under `__marimo__/`) or HTTPS URL."""+ if value is None:+ return None+ if is_https_url(value):+ return value++ # Disallow URLs with other schemes (e.g. http, data, file).+ parsed = urlparse(value)+ if parsed.scheme:+ return None++ path = Path(value)+ if path.is_absolute():+ return None+ return value+++OpenGraphMode = Literal["run", "edit"]+++@dataclass(frozen=True)+class OpenGraphContext:+ """Context passed to OpenGraph generator functions."""++ filepath: str+ # File router key (often a workspace-relative path); may be None.+ file_key: str | None = None+ # Server base URL (e.g. http://localhost:2718); may be None in CLI contexts.+ base_url: str | None = None+ mode: OpenGraphMode | None = None+++OpenGraphGeneratorReturn = OpenGraphMetadata | dict[str, Any] | None+OpenGraphGenerator = Callable[..., OpenGraphGeneratorReturn]+OpenGraphGeneratorArity = Literal[0, 1, 2]+++@dataclass(frozen=True)+class OpenGraphGeneratorSpec:+ fn: OpenGraphGenerator+ arity: OpenGraphGeneratorArity+++def read_opengraph_from_pyproject(+ pyproject: dict[str, Any],+) -> OpenGraphConfig | None:+ """Extract OpenGraph metadata from a parsed PEP 723 pyproject dict."""+ tool = pyproject.get("tool")+ if not isinstance(tool, dict):+ return None+ marimo = tool.get("marimo")+ if not isinstance(marimo, dict):+ return None+ opengraph = marimo.get("opengraph")+ if not isinstance(opengraph, dict):+ return None++ config = OpenGraphConfig(+ title=_maybe_str(opengraph.get("title")),+ description=_maybe_str(opengraph.get("description")),+ image=_normalize_opengraph_image(_maybe_str(opengraph.get("image"))),+ generator=_maybe_str(opengraph.get("generator")),+ )++ if (+ config.title is None+ and config.description is None+ and config.image is None+ and config.generator is None+ ):+ return None+ return config+++def read_opengraph_from_file(filepath: str) -> OpenGraphConfig | None:+ """Read OpenGraph metadata from a notebook's PEP 723 header."""+ try:+ script = Path(filepath).read_text(encoding="utf-8")+ project = read_pyproject_from_script(script) or {}+ except Exception:+ # Parsing errors are treated as "no metadata" so that listing and thumbnail generation don't spam warnings on malformed headers.+ return None+ return read_opengraph_from_pyproject(project)+++def _title_case(text: str) -> str:+ return text[:1].upper() + text[1:].lower()+++def derive_title_from_path(filepath: str) -> str:+ stem = Path(filepath).stem+ return " ".join(+ _title_case(part) for part in _WORD_SPLIT_RE.split(stem) if part+ )+++def default_opengraph_image(filepath: str) -> str:+ """Return the default relative image path for a given notebook."""+ stem = Path(filepath).stem+ return f"__marimo__/assets/{stem}/{DEFAULT_OPENGRAPH_IMAGE_FILENAME}"+++def _default_image_exists(filepath: str) -> bool:+ notebook_dir = normalize_path(Path(filepath)).parent+ return (notebook_dir / default_opengraph_image(filepath)).is_file()+++def _merge_opengraph_metadata(+ parent: OpenGraphMetadata,+ override: OpenGraphMetadata | None,+) -> OpenGraphMetadata:+ """Merge two metadata objects with override values taking precedence."""+ if override is None:+ return parent++ def coalesce(a: Any, b: Any) -> Any:+ return a if a is not None else b++ return OpenGraphMetadata(+ title=coalesce(override.title, parent.title),+ description=coalesce(override.description, parent.description),+ image=coalesce(override.image, parent.image),+ )+++def _coerce_opengraph_metadata(value: Any) -> OpenGraphMetadata | None:+ """Coerce a generator return value into OpenGraphMetadata."""+ if value is None:+ return None+ if isinstance(value, OpenGraphMetadata):+ return value+ if isinstance(value, dict):+ image = _maybe_str(value.get("image"))+ if image is None:+ image = _maybe_str(value.get("imageUrl"))+ return OpenGraphMetadata(+ title=_maybe_str(value.get("title")),+ description=_maybe_str(value.get("description")),+ image=_normalize_opengraph_image(image),+ )+ return None+++def _parse_generator_signature(+ fn: OpenGraphGenerator, *, generator: str+) -> OpenGraphGeneratorSpec | None:+ """Validate a generator signature and return a normalized call spec."""+ if asyncio.iscoroutinefunction(fn):+ LOGGER.warning(+ "OpenGraph generator must be synchronous: %s", generator+ )+ return None+ try:+ sig = inspect.signature(fn)+ except Exception as e:+ LOGGER.warning(+ "Failed to inspect OpenGraph generator signature (%s): %s",+ generator,+ e,+ )+ return None++ params = tuple(sig.parameters.values())+ unsupported = tuple(+ param+ for param in params+ if param.kind+ in (+ inspect.Parameter.VAR_POSITIONAL,+ inspect.Parameter.VAR_KEYWORD,+ inspect.Parameter.KEYWORD_ONLY,+ )+ )+ if unsupported:+ LOGGER.warning(+ "OpenGraph generator signature must use 0-2 positional args: %s",+ generator,+ )+ return None++ positional = tuple(+ param+ for param in params+ if param.kind+ in (+ inspect.Parameter.POSITIONAL_ONLY,+ inspect.Parameter.POSITIONAL_OR_KEYWORD,+ )+ )+ if len(positional) > 2:+ LOGGER.warning(+ "OpenGraph generator signature must accept at most 2 args: %s",+ generator,+ )+ return None++ arity = cast(OpenGraphGeneratorArity, len(positional))+ return OpenGraphGeneratorSpec(fn=fn, arity=arity)+++def _load_generator_from_module(+ module_spec: str, name: str, *, generator: str+) -> OpenGraphGeneratorSpec | None:+ try:+ module = importlib.import_module(module_spec)+ except Exception as e:+ LOGGER.warning("Failed to import OpenGraph generator module: %s", e)+ return None+ attr = getattr(module, name, None)+ if attr is None:+ LOGGER.warning(+ "OpenGraph generator %s not found in module %s", name, module_spec+ )+ return None+ if not callable(attr):+ LOGGER.warning("OpenGraph generator is not callable: %s", generator)+ return None+ return _parse_generator_signature(+ cast(OpenGraphGenerator, attr), generator=generator+ )+++def _load_generator_from_notebook_source(+ notebook_path: str, name: str+) -> OpenGraphGeneratorSpec | None:+ """Load a generator function from the notebook source without executing it.++ We compile and exec a small synthetic module containing only:+ - import statements (so the generator can import deps)+ - the named function definition+ """+ try:+ source = Path(notebook_path).read_text(encoding="utf-8")+ except Exception as e:+ LOGGER.warning(+ "Failed to read notebook when loading OpenGraph generator: %s", e+ )+ return None++ try:+ module_ast = ast.parse(source, filename=notebook_path)+ except Exception as e:+ LOGGER.warning(+ "Failed to parse notebook when loading OpenGraph generator: %s", e+ )+ return None++ def is_setup_expr(expr: ast.expr) -> bool:+ if isinstance(expr, ast.Attribute):+ return (+ isinstance(expr.value, ast.Name)+ and expr.value.id == "app"+ and expr.attr == "setup"+ )+ if isinstance(expr, ast.Call):+ return is_setup_expr(expr.func)+ return False++ imports: list[ast.stmt] = []+ setup: list[ast.stmt] = []+ target: ast.FunctionDef | ast.AsyncFunctionDef | None = None+ for node in module_ast.body:+ if isinstance(node, (ast.Import, ast.ImportFrom)):+ imports.append(node)+ elif isinstance(node, ast.With) and len(node.items) == 1:+ context_expr = node.items[0].context_expr+ if is_setup_expr(context_expr):+ # Inline the setup block body so that dependencies imported under `with app.setup:`+ # are available to the generator, without invoking marimo's setup cell registration.+ setup.extend(node.body)+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ if node.name == name:+ target = node++ if target is None:+ LOGGER.warning(+ "OpenGraph generator %s not found in notebook %s",+ name,+ notebook_path,+ )+ return None++ # Ignore decorators so we don't execute notebook/app registration logic.+ # Metadata generators are treated as plain Python functions.+ if getattr(target, "decorator_list", None):+ target.decorator_list = []++ extracted = ast.Module(body=[*imports, *setup, target], type_ignores=[])+ ast.fix_missing_locations(extracted)+ namespace: dict[str, Any] = {}+ try:+ exec(compile(extracted, notebook_path, "exec"), namespace)+ except Exception as e:+ LOGGER.warning("Failed to exec OpenGraph generator stub: %s", e)+ return None+ fn = namespace.get(name)+ if not callable(fn):+ LOGGER.warning(+ "OpenGraph generator %s is not callable (in %s)",+ name,+ notebook_path,+ )+ return None+ return _parse_generator_signature(+ cast(OpenGraphGenerator, fn), generator=name+ )+++def _load_opengraph_generator(+ generator: str, *, notebook_path: str+) -> OpenGraphGeneratorSpec | None:+ """Resolve a generator string into a callable.++ Supported forms:+ - "module.submodule:function"+ - "module.submodule.function"+ - "function_name" (loaded from notebook source via AST extraction)+ """+ value = generator.strip()+ if not value:+ return None++ module_spec: str | None+ name: str+ if ":" in value:+ module_spec, name = value.split(":", 1)+ module_spec = module_spec.strip()+ name = name.strip()+ elif "." in value:+ module_spec, name = value.rsplit(".", 1)+ module_spec = module_spec.strip()+ name = name.strip()+ else:+ return _load_generator_from_notebook_source(notebook_path, value)++ if not module_spec or not name:+ return None++ # Disallow filesystem-based generator specs to keep behavior predictable+ if (+ module_spec.endswith(".py")+ or "/" in module_spec+ or "\\" in module_spec+ ):+ LOGGER.warning(+ "OpenGraph generator must be importable as a Python module: %s",+ generator,+ )+ return None++ return _load_generator_from_module(module_spec, name, generator=generator)+++def _call_opengraph_generator(+ spec: OpenGraphGeneratorSpec,+ *,+ context: OpenGraphContext,+ parent: OpenGraphMetadata,+) -> OpenGraphGeneratorReturn:+ """Invoke a generator with a stable calling convention."""+ if spec.arity == 2:+ return spec.fn(context, parent)+ if spec.arity == 1:+ return spec.fn(context)+ return spec.fn()+++def _run_opengraph_generator(+ generator: str,+ *,+ context: OpenGraphContext,+ parent: OpenGraphMetadata,+) -> OpenGraphMetadata | None:+ spec = _load_opengraph_generator(generator, notebook_path=context.filepath)+ if spec is None:+ return None++ try:+ result = _call_opengraph_generator(+ spec, context=context, parent=parent+ )+ except Exception as e:+ LOGGER.warning("OpenGraph generator raised: %s", e)+ return None+ if inspect.isawaitable(result):+ # Avoid "coroutine was never awaited" warnings.+ close = getattr(result, "close", None)+ if callable(close):+ try:+ close()+ except Exception:+ pass+ LOGGER.warning(+ "OpenGraph generator returned an awaitable (must be sync): %s",+ generator,+ )+ return None++ dynamic = _coerce_opengraph_metadata(result)+ if dynamic is None:+ LOGGER.warning(+ "OpenGraph generator returned unsupported value: %s", type(result)+ )+ return None+ return dynamic+++def resolve_opengraph_metadata(+ filepath: str,+ *,+ app_title: str | None = None,+ context: OpenGraphContext | None = None,+) -> OpenGraphMetadata:+ """Resolve OpenGraph metadata from config, defaults, and a generator hook."""+ declared = read_opengraph_from_file(filepath) or OpenGraphConfig()++ title = declared.title or app_title or derive_title_from_path(filepath)+ description = declared.description+ image = _normalize_opengraph_image(declared.image)+ if image is None and _default_image_exists(filepath):+ image = default_opengraph_image(filepath)++ resolved = OpenGraphMetadata(+ title=title,+ description=description,+ image=image,+ )++ if declared.generator:+ ctx = context or OpenGraphContext(filepath=filepath)+ dynamic = _run_opengraph_generator(+ declared.generator, context=ctx, parent=resolved+ )+ resolved = _merge_opengraph_metadata(resolved, dynamic)++ return resolved+++def _xml_escape(text: str) -> str:+ return (+ text.replace("&", "&")+ .replace("<", "<")+ .replace(">", ">")+ .replace('"', """)+ .replace("'", "'")+ )+++def _wrap_title_lines(title: str, *, max_chars: int = 32) -> list[str]:+ words = title.split()+ if not words:+ return ["marimo"]++ lines: list[str] = []+ current: list[str] = []+ current_len = 0+ for word in words:+ extra = (1 if current else 0) + len(word)+ if current and current_len + extra > max_chars:+ lines.append(" ".join(current))+ current = [word]+ current_len = len(word)+ else:+ current.append(word)+ current_len += extra++ if current:+ lines.append(" ".join(current))++ # Keep the placeholder compact.+ if len(lines) > 3:+ lines = lines[:3]+ lines[-1] = lines[-1].rstrip(".") + "..."++ return lines+++@dataclass(frozen=True)+class OpenGraphImage:+ content: bytes+ media_type: str+++@dataclass(frozen=True)+class DefaultOpenGraphPlaceholderImageGenerator:+ """Generate a deterministic placeholder thumbnail image."""++ width: int = 1200+ height: int = 630++ def __call__(self, title: str) -> OpenGraphImage:+ svg = self._render_svg(title)+ return OpenGraphImage(+ content=svg.encode("utf-8"),+ media_type="image/svg+xml",+ )++ def _render_svg(self, title: str) -> str:+ accent = _MARIMO_GREEN++ lines = _wrap_title_lines(title)+ escaped = [_xml_escape(line) for line in lines]++ # Center the title inside an inset card.+ card_x = 48+ card_y = 48+ card_w = self.width - 2 * card_x+ card_h = self.height - 2 * card_y+ stripe_w = 16++ line_height = 72+ block_height = line_height * len(escaped)+ start_y = card_y + int((card_h - block_height) / 2) + 56+ text_x = card_x + stripe_w + 36++ text_nodes: list[str] = []+ for i, line in enumerate(escaped):+ y = start_y + i * line_height+ text_nodes.append(+ f'<text x="{text_x}" y="{y}" font-size="60">{line}</text>'+ )++ text_svg = "\n ".join(text_nodes)++ return f"""<svg xmlns="http://www.w3.org/2000/svg" width="{self.width}" height="{self.height}" viewBox="0 0 {self.width} {self.height}">+ <defs>+ <clipPath id="card">+ <rect x="{card_x}" y="{card_y}" width="{card_w}" height="{card_h}" rx="24" />+ </clipPath>+ </defs>++ <rect width="{self.width}" height="{self.height}" fill="#f8fafc"/>+ <rect x="{card_x}" y="{card_y}" width="{card_w}" height="{card_h}" rx="24" fill="#ffffff" stroke="#e2e8f0" stroke-width="2"/>+ <rect x="{card_x}" y="{card_y}" width="{stripe_w}" height="{card_h}" fill="{accent}" clip-path="url(#card)"/>++ <g fill="#0f172a" font-family="ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial" font-weight="700">+ {text_svg}+ </g>++ <text x="{text_x}" y="{card_y + card_h - 32}" fill="#64748b" font-family="ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial" font-size="22" font-weight="600">+ marimo+ </text>+</svg>+"""+++DEFAULT_OPENGRAPH_PLACEHOLDER_IMAGE_GENERATOR = (+ DefaultOpenGraphPlaceholderImageGenerator()+)diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex fe3dfab96c..b7c635409c 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -8,7 +8,12 @@ from typing import TYPE_CHECKINGfrom starlette.authentication import requiresfrom starlette.exceptions import HTTPException-from starlette.responses import FileResponse, HTMLResponse, Response+from starlette.responses import (+ FileResponse,+ HTMLResponse,+ RedirectResponse,+ Response,+)from starlette.staticfiles import StaticFilesfrom marimo import _loggers@@ -75,6 +80,89 @@ except RuntimeError:FILE_QUERY_PARAM_KEY = "file"[email protected]("/og/thumbnail", include_in_schema=False)+@requires("read")+def og_thumbnail(*, request: Request) -> Response:+ """Serve a notebook thumbnail for gallery/OpenGraph use."""+ from pathlib import Path++ from marimo._metadata.opengraph import (+ DEFAULT_OPENGRAPH_PLACEHOLDER_IMAGE_GENERATOR,+ OpenGraphContext,+ is_https_url,+ resolve_opengraph_metadata,+ )+ from marimo._utils.http import HTTPException, HTTPStatus+ from marimo._utils.paths import normalize_path++ app_state = AppState(request)+ file_key = (+ app_state.query_params(FILE_QUERY_PARAM_KEY)+ or app_state.session_manager.file_router.get_unique_file_key()+ )+ if not file_key:+ raise HTTPException(+ status_code=HTTPStatus.NOT_FOUND, detail="File not found"+ )++ notebook_path = app_state.session_manager.file_router.resolve_file_path(+ file_key+ )+ if notebook_path is None:+ raise HTTPException(+ status_code=HTTPStatus.NOT_FOUND, detail="File not found"+ )++ notebook_dir = normalize_path(Path(notebook_path)).parent+ marimo_dir = notebook_dir / "__marimo__"++ # User-defined OpenGraph generators receive this context (file key, base URL, mode)+ # so they can compute metadata dynamically for gallery cards, social previews, and other modes.+ opengraph = resolve_opengraph_metadata(+ notebook_path,+ context=OpenGraphContext(+ filepath=notebook_path,+ file_key=file_key,+ base_url=app_state.base_url,+ mode=app_state.mode.value,+ ),+ )+ title = opengraph.title or "marimo"+ image = opengraph.image++ validator = PathValidator()+ if image:+ if is_https_url(image):+ return RedirectResponse(+ url=image,+ status_code=307,+ headers={"Cache-Control": "max-age=3600"},+ )++ rel_path = Path(image)+ if not rel_path.is_absolute():+ file_path = normalize_path(notebook_dir / rel_path)+ # Only allow serving from the notebook's __marimo__ directory.+ try:+ if file_path.is_file():+ validator.validate_inside_directory(marimo_dir, file_path)+ return FileResponse(+ file_path,+ headers={"Cache-Control": "max-age=3600"},+ )+ except HTTPException:+ # Treat invalid paths as a miss; fall back to placeholder.+ pass++ placeholder = DEFAULT_OPENGRAPH_PLACEHOLDER_IMAGE_GENERATOR(title)+ return Response(+ content=placeholder.content,+ media_type=placeholder.media_type,+ # Avoid caching placeholders so newly-generated screenshots show up immediately on refresh.+ headers={"Cache-Control": "no-store"},+ )++async def _fetch_index_html_from_url(asset_url: str) -> str:"""Fetch index.html from the given asset URL."""import marimo._utils.requests as requests@@ -108,8 +196,9 @@ async def index(request: Request) -> HTMLResponse:app_state = AppState(request)index_html = root / "index.html"+ file_key_from_query = app_state.query_params(FILE_QUERY_PARAM_KEY)file_key = (- app_state.query_params(FILE_QUERY_PARAM_KEY)+ file_key_from_queryor app_state.session_manager.file_router.get_unique_file_key())@@ -147,6 +236,7 @@ async def index(request: Request) -> HTMLResponse:LOGGER.debug(f"File key provided: {file_key}")app_manager = app_state.session_manager.app_manager(file_key)app_config = app_manager.app.config+ absolute_filepath = app_manager.filename# Pre-compute notebook snapshot for faster initial render# Only in EDIT + SandboxMode.MULTI where each notebook gets its own IPC@@ -186,6 +276,7 @@ async def index(request: Request) -> HTMLResponse:server_token=app_state.skew_protection_token,app_config=app_config,filename=filename,+ filepath=absolute_filepath,mode=app_state.mode,notebook_snapshot=notebook_snapshot,runtime_config=[{"url": app_state.remote_url}]diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.pyindex bb71e85022..27e8c40cd1 100644--- a/marimo/_server/api/endpoints/home.py+++ b/marimo/_server/api/endpoints/home.py@@ -91,15 +91,56 @@ async def workspace_files($ref: "#/components/schemas/WorkspaceFilesResponse""""body = await parse_request(request, cls=WorkspaceFilesRequest)- session_manager = AppState(request).session_manager+ app_state = AppState(request)+ session_manager = app_state.session_managerif session_manager.mode == SessionMode.RUN:- files = await asyncio.to_thread(- lambda: session_manager.file_router.files+ from marimo._metadata.opengraph import (+ OpenGraphContext,+ resolve_opengraph_metadata,)- marimo_files = [- file for file in flatten_files(files) if file.is_marimo_file- ]+ from marimo._server.models.files import FileInfo++ base_url = app_state.base_url+ mode = session_manager.mode.value++ def get_files_with_metadata() -> list[FileInfo]:+ files = session_manager.file_router.files+ marimo_files = [+ file for file in flatten_files(files) if file.is_marimo_file+ ]+ result: list[FileInfo] = []+ for file in marimo_files:+ resolved_path = session_manager.file_router.resolve_file_path(+ file.path+ )+ opengraph = None+ if resolved_path is not None:+ # User-defined OpenGraph generators receive this context for dynamic metadata+ opengraph = resolve_opengraph_metadata(+ resolved_path,+ context=OpenGraphContext(+ filepath=resolved_path,+ file_key=file.path,+ base_url=base_url,+ mode=mode,+ ),+ )+ result.append(+ FileInfo(+ id=file.id,+ path=file.path,+ name=file.name,+ is_directory=file.is_directory,+ is_marimo_file=file.is_marimo_file,+ last_modified=file.last_modified,+ children=file.children,+ opengraph=opengraph,+ )+ )+ return result++ marimo_files = await asyncio.to_thread(get_files_with_metadata)file_count = len(marimo_files)has_more = file_count >= MAX_FILESreturn WorkspaceFilesResponse(diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex c5b8e24e9b..7a1715da15 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -13,7 +13,7 @@ from marimo._ast.app import InternalAppfrom marimo._ast.errors import CycleError, MultipleDefinitionErrorfrom marimo._ast.load import load_appfrom marimo._cli.print import echo-from marimo._config.config import RuntimeConfig+from marimo._config.config import DisplayConfig, RuntimeConfigfrom marimo._config.manager import (get_default_config_manager,)@@ -245,6 +245,8 @@ async def run_app_then_export_as_html(include_code: bool,cli_args: SerializedCLIArgs,argv: list[str],+ *,+ asset_url: str | None = None,) -> ExportResult:# Create a file router and file managerfile_router = AppFileRouter.from_filename(path)@@ -256,6 +258,7 @@ async def run_app_then_export_as_html(file_manager.app.inline_layout_file()config = get_default_config_manager(current_path=file_manager.path)+ display_config = cast(DisplayConfig, config.get_config()["display"])session_view, did_error = await run_app_until_completion(file_manager,cli_args,@@ -266,11 +269,12 @@ async def run_app_then_export_as_html(filename=file_manager.filename,app=file_manager.app,session_view=session_view,- display_config=config.get_config()["display"],+ display_config=display_config,request=ExportAsHTMLRequest(include_code=include_code,download=False,files=[],+ asset_url=asset_url,),)return ExportResult(@@ -280,6 +284,53 @@ async def run_app_then_export_as_html()+async def export_as_html_without_execution(+ path: MarimoPath,+ include_code: bool,+ *,+ asset_url: str | None = None,+) -> ExportResult:+ """Export a notebook to HTML without executing its cells."""+ from marimo._session.state.session_view import SessionView++ file_router = AppFileRouter.from_filename(path)+ file_key = file_router.get_unique_file_key()+ if file_key is None:+ raise RuntimeError(+ "Expected a unique file key when exporting a single notebook: "+ f"{path.absolute_name}"+ )+ file_manager = file_router.get_file_manager(file_key)++ # Inline the layout file, if it exists.+ file_manager.app.inline_layout_file()++ view = SessionView()+ for cell_data in file_manager.app.cell_manager.cell_data():+ view.last_executed_code[cell_data.cell_id] = cell_data.code++ config = get_default_config_manager(current_path=file_manager.path)+ display_config = cast(DisplayConfig, config.get_config()["display"])++ html, filename = Exporter().export_as_html(+ filename=file_manager.filename,+ app=file_manager.app,+ session_view=view,+ display_config=display_config,+ request=ExportAsHTMLRequest(+ include_code=include_code,+ download=False,+ files=[],+ asset_url=asset_url,+ ),+ )+ return ExportResult(+ contents=html,+ download_filename=filename,+ did_error=False,+ )++async def run_app_then_export_as_reactive_html(path: MarimoPath,include_code: bool,diff --git a/marimo/_server/file_router.py b/marimo/_server/file_router.pyindex c57ddf382c..7078c05f25 100644--- a/marimo/_server/file_router.py+++ b/marimo/_server/file_router.py@@ -111,6 +111,24 @@ class AppFileRouter(abc.ABC):detail=f"File {key} not found",)+ def resolve_file_path(self, key: MarimoFileKey) -> str | None:+ """Resolve a file key to an absolute file path, without loading the app.++ This is useful for endpoints that need file-backed resources (e.g. thumbnails)+ without the overhead of parsing/loading a notebook.++ Returns:+ Absolute file path if resolvable, otherwise None (e.g. new file).+ """+ if key.startswith(AppFileRouter.NEW_FILE):+ return None+ if os.path.exists(key):+ return key+ raise HTTPException(+ status_code=HTTPStatus.NOT_FOUND,+ detail=f"File {key} not found",+ )+@abc.abstractmethoddef get_unique_file_key(self) -> Optional[MarimoFileKey]:"""@@ -187,9 +205,15 @@ class ListOfFilesAppFileRouter(AppFileRouter):) -> AppFileManager:defaults = defaults or AppDefaults()+ resolved_path = self.resolve_file_path(key)+ if resolved_path is None:+ return AppFileManager(None, defaults=defaults)+ return AppFileManager(resolved_path, defaults=defaults)++ def resolve_file_path(self, key: MarimoFileKey) -> str | None:if key.startswith(AppFileRouter.NEW_FILE):if self._allow_single_file_key:- return AppFileManager(None, defaults=defaults)+ return Noneraise HTTPException(status_code=HTTPStatus.NOT_FOUND,detail=f"File {key} not found",@@ -207,7 +231,7 @@ class ListOfFilesAppFileRouter(AppFileRouter):)if normalized_path.exists():- return AppFileManager(absolute_path, defaults=defaults)+ return absolute_pathraise HTTPException(status_code=HTTPStatus.NOT_FOUND,@@ -298,9 +322,14 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):the source's directory for security."""defaults = defaults or AppDefaults()+ resolved_path = self.resolve_file_path(key)+ if resolved_path is None:+ return AppFileManager(None, defaults=defaults)+ return AppFileManager(resolved_path, defaults=defaults)+ def resolve_file_path(self, key: MarimoFileKey) -> str | None:if key.startswith(AppFileRouter.NEW_FILE):- return AppFileManager(None, defaults=defaults)+ return Nonedirectory = Path(self._directory)filepath = Path(key)@@ -322,7 +351,7 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):self._validator.validate_inside_directory(directory, filepath)if filepath.exists():- return AppFileManager(str(filepath), defaults=defaults)+ return str(filepath)raise HTTPException(status_code=HTTPStatus.NOT_FOUND,diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.pyindex 9453939b6d..b8f375d23f 100644--- a/marimo/_server/models/files.py+++ b/marimo/_server/models/files.py@@ -5,6 +5,7 @@ from typing import Literal, Optionalimport msgspec+from marimo._metadata.opengraph import OpenGraphMetadatafrom marimo._server.models.models import BaseResponse@@ -16,6 +17,7 @@ class FileInfo(msgspec.Struct, rename="camel"):is_marimo_file: boollast_modified: Optional[float] = Nonechildren: list[FileInfo] = msgspec.field(default_factory=list)+ opengraph: OpenGraphMetadata | None = Noneclass FileListRequest(msgspec.Struct, rename="camel"):diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 68cf482065..bb8948b2f5 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -137,6 +137,76 @@ def home_page_template(return html+def opengraph_metadata_template(+ *,+ base_url: str,+ mode: SessionMode,+ app_config: _AppConfig,+ filename: Optional[str],+ filepath: Optional[str],+) -> str:+ """Return OpenGraph `<meta>` tags for a notebook, or an empty string."""+ if not filepath:+ return ""++ try:+ from marimo._metadata.opengraph import (+ OpenGraphContext,+ is_https_url,+ resolve_opengraph_metadata,+ )++ file_key = (+ filename if filename and not Path(filename).is_absolute() else None+ )+ opengraph = resolve_opengraph_metadata(+ filepath,+ app_title=app_config.app_title,+ context=OpenGraphContext(+ filepath=filepath,+ file_key=file_key,+ base_url=base_url,+ mode=mode.value,+ ),+ )+ except Exception:+ return ""++ if not opengraph.title and not opengraph.description:+ return ""++ if opengraph.image and is_https_url(opengraph.image):+ thumbnail_url = opengraph.image+ else:+ # Server-resolvable thumbnail URL, falling back to a placeholder when+ # no screenshot exists.+ thumbnail_url = f"{base_url}/og/thumbnail"+ if filename and not Path(filename).is_absolute():+ thumbnail_url = (+ f"{thumbnail_url}?file={uri_encode_component(filename)}"+ )++ meta_tags: list[str] = []+ if opengraph.title:+ meta_tags.append(+ f'<meta property="og:title" content="{_html_escape(opengraph.title)}" />'+ )+ if opengraph.description:+ meta_tags.append(+ f'<meta property="og:description" content="{_html_escape(opengraph.description)}" />'+ )+ meta_tags.append(+ f'<meta name="description" content="{_html_escape(opengraph.description)}" />'+ )+ meta_tags.append(+ f'<meta property="og:image" content="{_html_escape(thumbnail_url)}" />'+ )+ meta_tags.append(+ '<meta name="twitter:card" content="summary_large_image" />'+ )+ return "\n".join(meta_tags)++def notebook_page_template(*,html: str,@@ -146,6 +216,7 @@ def notebook_page_template(server_token: SkewProtectionToken,app_config: _AppConfig,filename: Optional[str],+ filepath: Optional[str] = None,mode: SessionMode,session_snapshot: Optional[NotebookSessionV1] = None,notebook_snapshot: Optional[NotebookV1] = None,@@ -156,12 +227,16 @@ def notebook_page_template(# When we have a remote URL, let's pre-populate the index.html page# with a view of the notebook.- if runtime_config and filename and notebook_snapshot is None:- filepath = Path(filename)- if filepath.exists():- notebook_snapshot = MarimoConvert.from_py(- filepath.read_text(encoding="utf-8")- ).to_notebook_v1()+ if runtime_config and notebook_snapshot is None:+ # Prefer the absolute path for IO, since `filename` can be a display+ # path (workspace-relative) in gallery mode.+ path = filepath or filename+ if path:+ path_obj = Path(path)+ if path_obj.exists():+ notebook_snapshot = MarimoConvert.from_py(+ path_obj.read_text(encoding="utf-8")+ ).to_notebook_v1()html = html.replace("{{ filename }}", _html_escape(filename or ""))@@ -198,6 +273,16 @@ def notebook_page_template(),)+ opengraph_tags = opengraph_metadata_template(+ base_url=base_url,+ mode=mode,+ app_config=app_config,+ filename=filename,+ filepath=filepath,+ )+ if opengraph_tags:+ html = html.replace("</head>", f"{opengraph_tags}\n</head>")+# If has custom css, inline the css and add to the headif app_config.css_file:css_contents = read_css_file(app_config.css_file, filename=filename)diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 865334b21e..7f87dab51d 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -1635,6 +1635,11 @@ components:default: nullname:type: string+ opengraph:+ anyOf:+ - type: 'null'+ - $ref: '#/components/schemas/OpenGraphMetadata'+ default: nullpath:type: stringrequired:@@ -3084,6 +3089,29 @@ components:required: []title: OpenAiConfigtype: object+ OpenGraphMetadata:+ description: "OpenGraph-style metadata for a notebook.\n\n The `image` field\+ \ may be either:\n - a relative path (typically under `__marimo__/`), or\n\+ \ - an absolute HTTPS URL."+ properties:+ description:+ anyOf:+ - type: string+ - type: 'null'+ default: null+ image:+ anyOf:+ - type: string+ - type: 'null'+ default: null+ title:+ anyOf:+ - type: string+ - type: 'null'+ default: null+ required: []+ title: OpenGraphMetadata+ type: objectOpenTutorialRequest:properties:tutorialId:@@ -4658,7 +4686,7 @@ components:type: objectinfo:title: marimo API- version: 0.19.6+ version: 0.19.7openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 16abfbf0ac..1c58317ba9 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -4040,6 +4040,8 @@ export interface components {/** @default null */lastModified?: number | null;name: string;+ /** @default null */+ opengraph?: null | components["schemas"]["OpenGraphMetadata"];path: string;};/** FileListRequest */@@ -4895,6 +4897,22 @@ export interface components {project?: string;ssl_verify?: boolean;};+ /**+ * OpenGraphMetadata+ * @description OpenGraph-style metadata for a notebook.+ *+ * The `image` field may be either:+ * - a relative path (typically under `__marimo__/`), or+ * - an absolute HTTPS URL.+ */+ OpenGraphMetadata: {+ /** @default null */+ description?: string | null;+ /** @default null */+ image?: string | null;+ /** @default null */+ title?: string | null;+ };/** OpenTutorialRequest */OpenTutorialRequest: {tutorialId:diff --git a/tests/_metadata/test_opengraph.py b/tests/_metadata/test_opengraph.pynew file mode 100644index 0000000000..1f4e490447--- /dev/null+++ b/tests/_metadata/test_opengraph.py@@ -0,0 +1,217 @@+from __future__ import annotations++import textwrap++from marimo._metadata.opengraph import (+ DEFAULT_OPENGRAPH_PLACEHOLDER_IMAGE_GENERATOR,+ OpenGraphConfig,+ default_opengraph_image,+ read_opengraph_from_file,+ read_opengraph_from_pyproject,+ resolve_opengraph_metadata,+)+++def test_read_opengraph_from_pyproject() -> None:+ pyproject = {+ "tool": {+ "marimo": {+ "opengraph": {+ "title": "My Title",+ "description": "My Description",+ "image": "__marimo__/opengraph.png",+ }+ }+ }+ }++ assert read_opengraph_from_pyproject(pyproject) == OpenGraphConfig(+ title="My Title",+ description="My Description",+ image="__marimo__/opengraph.png",+ generator=None,+ )++ # Invalid shapes should be ignored.+ assert (+ read_opengraph_from_pyproject(+ {"tool": {"marimo": {"opengraph": {"title": 123}}}}+ )+ is None+ )+++def test_read_opengraph_from_file(tmp_path) -> None:+ script = textwrap.dedent(+ """+ # /// script+ # [tool.marimo.opengraph]+ # title = "Hello World"+ # description = "A notebook"+ # image = "__marimo__/opengraph.png"+ # ///+ """+ ).lstrip()++ path = tmp_path / "notebook.py"+ path.write_text(script, encoding="utf-8")++ assert read_opengraph_from_file(str(path)) == OpenGraphConfig(+ title="Hello World",+ description="A notebook",+ image="__marimo__/opengraph.png",+ generator=None,+ )+++def test_resolve_opengraph_metadata_defaults(tmp_path) -> None:+ script = "import marimo as mo\napp = mo.App()\n"+ path = tmp_path / "my_notebook.py"+ path.write_text(script, encoding="utf-8")++ resolved = resolve_opengraph_metadata(str(path))+ assert resolved.title == "My Notebook"+ assert resolved.description is None+ assert resolved.image is None+++def test_resolve_opengraph_metadata_uses_app_title(tmp_path) -> None:+ script = textwrap.dedent(+ """+ # /// script+ # [tool.marimo.opengraph]+ # description = "desc"+ # ///+ import marimo as mo+ app = mo.App(app_title="App Title")+ """+ ).lstrip()+ path = tmp_path / "notebook.py"+ path.write_text(script, encoding="utf-8")++ resolved = resolve_opengraph_metadata(str(path), app_title="App Title")+ assert resolved.title == "App Title"+ assert resolved.description == "desc"+++def test_resolve_opengraph_metadata_defaults_image_if_present(+ tmp_path,+) -> None:+ script = "import marimo as mo\napp = mo.App()\n"+ path = tmp_path / "notebook.py"+ path.write_text(script, encoding="utf-8")++ default_image = default_opengraph_image(str(path))+ image_path = tmp_path / default_image+ image_path.parent.mkdir(parents=True, exist_ok=True)+ image_path.write_bytes(b"fake-png")++ resolved = resolve_opengraph_metadata(str(path))+ assert resolved.image == default_image+++def test_resolve_opengraph_metadata_supports_https_url_image(tmp_path) -> None:+ script = textwrap.dedent(+ """+ # /// script+ # [tool.marimo.opengraph]+ # image = "https://example.com/opengraph.png"+ # ///+ import marimo as mo+ app = mo.App()+ """+ ).lstrip()+ path = tmp_path / "notebook.py"+ path.write_text(script, encoding="utf-8")++ resolved = resolve_opengraph_metadata(str(path))+ assert resolved.image == "https://example.com/opengraph.png"+++def test_default_opengraph_placeholder_generator() -> None:+ image = DEFAULT_OPENGRAPH_PLACEHOLDER_IMAGE_GENERATOR("Hello World")+ assert image.media_type == "image/svg+xml"+ assert image.content.startswith(b"<svg")+ assert b"Hello World" in image.content+++def test_resolve_opengraph_metadata_merges_generator_overrides(+ tmp_path,+) -> None:+ script = textwrap.dedent(+ """+ # /// script+ # [tool.marimo.opengraph]+ # title = "Static Title"+ # generator = "generate_opengraph"+ # ///+ def generate_opengraph(ctx, parent):+ # Merge semantics: return only what you want to override.+ return {+ "image": "https://example.com/generated.png",+ }++ import marimo as mo+ app = mo.App()+ """+ ).lstrip()+ path = tmp_path / "notebook.py"+ path.write_text(script, encoding="utf-8")++ resolved = resolve_opengraph_metadata(str(path))+ assert resolved.title == "Static Title"+ assert resolved.image == "https://example.com/generated.png"+++def test_resolve_opengraph_metadata_ignores_invalid_generator_signature(+ tmp_path,+) -> None:+ script = textwrap.dedent(+ """+ # /// script+ # [tool.marimo.opengraph]+ # title = "Static Title"+ # generator = "generate_opengraph"+ # ///+ def generate_opengraph(ctx, parent, extra):+ return {"image": "https://example.com/generated.png"}++ import marimo as mo+ app = mo.App()+ """+ ).lstrip()+ path = tmp_path / "notebook.py"+ path.write_text(script, encoding="utf-8")++ resolved = resolve_opengraph_metadata(str(path))+ assert resolved.title == "Static Title"+ assert resolved.image is None+++def test_resolve_opengraph_metadata_supports_app_setup_imports(+ tmp_path,+) -> None:+ script = textwrap.dedent(+ """+ # /// script+ # [tool.marimo.opengraph]+ # title = "Static Title"+ # generator = "generate_opengraph"+ # ///+ import marimo+ app = marimo.App()++ with app.setup:+ import math++ @app.function+ def generate_opengraph(ctx, parent):+ return {"image": f"https://example.com/{math.floor(math.pi)}.png"}+ """+ ).lstrip()+ path = tmp_path / "notebook.py"+ path.write_text(script, encoding="utf-8")++ resolved = resolve_opengraph_metadata(str(path))+ assert resolved.title == "Static Title"+ assert resolved.image == "https://example.com/3.png"diff --git a/tests/_server/api/endpoints/test_home.py b/tests/_server/api/endpoints/test_home.pyindex 16a26b9664..48a3fde24e 100644--- a/tests/_server/api/endpoints/test_home.py+++ b/tests/_server/api/endpoints/test_home.py@@ -5,6 +5,7 @@ import inspectimport osimport sysimport tempfile+import textwrapfrom pathlib import Pathfrom typing import TYPE_CHECKING@@ -205,6 +206,41 @@ def test_workspace_files_run_mode_allowlist(client: TestClient) -> None:}+@with_session(SESSION_ID)+def test_thumbnail_redirects_for_https_opengraph_image(+ client: TestClient,+) -> None:+ session_manager = get_session_manager(client)+ session_manager.mode = SessionMode.RUN++ with tempfile.TemporaryDirectory() as temp_dir:+ marimo_file = Path(temp_dir) / "notebook.py"+ marimo_file.write_text(+ textwrap.dedent(+ """+ # /// script+ # [tool.marimo.opengraph]+ # image = "https://example.com/opengraph.png"+ # ///+ import marimo+ app = marimo.App()+ """+ ).lstrip()+ )++ session_manager.file_router = AppFileRouter.from_directory(temp_dir)++ response = client.get(+ "/og/thumbnail?file=notebook.py",+ headers=HEADERS,+ follow_redirects=False,+ )+ assert response.status_code == 307+ assert (+ response.headers["location"] == "https://example.com/opengraph.png"+ )++@with_session(SESSION_ID)def test_tutorial_file_accessible_after_open(client: TestClient) -> None:"""Test that a tutorial file can be accessed after being opened.diff --git a/tests/_server/test_file_router.py b/tests/_server/test_file_router.pyindex 90bc4735e6..e9cda6d65e 100644--- a/tests/_server/test_file_router.py+++ b/tests/_server/test_file_router.py@@ -180,6 +180,21 @@ class TestAppFileRouter(unittest.TestCase):router.get_file_manager(AppFileRouter.NEW_FILE)assert exc.value.status_code == HTTPStatus.NOT_FOUND+ def test_list_of_files_resolve_file_path_supports_relative_key(self):+ files = [+ MarimoFile(+ name="test.py",+ path=self.test_file1.name,+ last_modified=os.path.getmtime(self.test_file1.name),+ )+ ]+ router = ListOfFilesAppFileRouter(files, directory=self.test_dir)+ relative_key = str(+ Path(self.test_file1.name).relative_to(self.test_dir)+ )+ resolved = router.resolve_file_path(relative_key)+ assert resolved == self.test_file1.name+def test_lazy_list_of_get_app_file_manager(self):router = LazyListOfFilesAppFileRouter(self.test_dir, include_markdown=False