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(frontend): publish HTML to web through molab (#10763)
Shahmir Varqhace0e849c103f
diff --git a/frontend/src/components/static-html/__tests__/share-modal.test.tsx b/frontend/src/components/static-html/__tests__/share-modal.test.tsxnew file mode 100644index 0000000000..d14dc3634d--- /dev/null+++ b/frontend/src/components/static-html/__tests__/share-modal.test.tsx@@ -0,0 +1,154 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import type React from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Dialog } from "@/components/ui/dialog";+import { TooltipProvider } from "@/components/ui/tooltip";+import { ShareStaticNotebookModal } from "../share-modal";+import { stageForPublish } from "../stage-for-publish";++const exportAsHTML = vi.fn();++vi.mock("@/core/network/requests", () => ({+ useRequestClient: () => ({ exportAsHTML }),+}));+vi.mock("@/core/export/layout", () => ({+ getExportLayout: vi.fn().mockResolvedValue(undefined),+}));+vi.mock("@/core/static/virtual-file-tracker", () => ({+ VirtualFileTracker: { INSTANCE: { filenames: () => [] } },+}));+vi.mock("../stage-for-publish", () => ({+ stageForPublish: vi.fn(),+}));++const stageForPublishMock = vi.mocked(stageForPublish);+const CLAIM_URL = "https://claim.example/abc";++function wrapper({ children }: { children: React.ReactNode }) {+ return (+ <TooltipProvider>+ <Dialog open={true}>{children}</Dialog>+ </TooltipProvider>+ );+}++describe("ShareStaticNotebookModal", () => {+ const onClose = vi.fn();+ const windowOpen = vi.fn<typeof window.open>();++ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("open", windowOpen);+ exportAsHTML.mockResolvedValue({+ contents: "<html></html>",+ filename: "nb.html",+ });+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ function renderModal() {+ return render(<ShareStaticNotebookModal onClose={onClose} />, {+ wrapper,+ });+ }++ it("exports with CDN assets, opens the claim page, and keeps the link in the dialog", async () => {+ stageForPublishMock.mockResolvedValue(CLAIM_URL);+ renderModal();++ fireEvent.click(screen.getByTestId("share-static-notebook-button"));++ const link = await screen.findByTestId("open-claim-page-link");+ expect(link).toHaveAttribute("href", CLAIM_URL);+ expect(link).toHaveAttribute("rel", "noopener noreferrer");+ expect(link).toHaveAttribute("target", "_blank");++ expect(windowOpen).toHaveBeenCalledWith(+ CLAIM_URL,+ "_blank",+ "noopener,noreferrer",+ );+ expect(exportAsHTML).toHaveBeenCalledWith(+ expect.objectContaining({+ includeCode: true,+ download: false,+ assetUrl: expect.stringContaining("cdn.jsdelivr.net"),+ }),+ );+ expect(stageForPublishMock).toHaveBeenCalledWith(+ "nb.html",+ "<html></html>",+ );+ // The dialog stays open so the link survives a blocked popup.+ expect(onClose).not.toHaveBeenCalled();+ expect(+ screen.queryByTestId("share-static-notebook-button"),+ ).not.toBeInTheDocument();+ });++ it("closes from the staged view via Done", async () => {+ stageForPublishMock.mockResolvedValue(CLAIM_URL);+ renderModal();++ fireEvent.click(screen.getByTestId("share-static-notebook-button"));+ fireEvent.click(+ await screen.findByTestId("done-share-static-notebook-button"),+ );++ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("shows the failure in the dialog and allows retrying", async () => {+ stageForPublishMock+ .mockRejectedValueOnce(new Error("Too many uploads, try again later"))+ .mockResolvedValueOnce(CLAIM_URL);+ renderModal();++ fireEvent.click(screen.getByTestId("share-static-notebook-button"));++ const error = await screen.findByTestId("share-static-notebook-error");+ expect(error).toHaveTextContent(+ "Publish failed: Too many uploads, try again later",+ );+ expect(windowOpen).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();++ const retry = screen.getByTestId("share-static-notebook-button");+ expect(retry).toHaveTextContent("Try again");+ expect(retry).toBeEnabled();+ fireEvent.click(retry);++ expect(await screen.findByTestId("open-claim-page-link")).toHaveAttribute(+ "href",+ CLAIM_URL,+ );+ });++ it("disables both buttons while staging", async () => {+ let resolveStage: (url: string) => void = () => undefined;+ stageForPublishMock.mockImplementation(+ () =>+ new Promise<string>((resolve) => {+ resolveStage = resolve;+ }),+ );+ renderModal();++ fireEvent.click(screen.getByTestId("share-static-notebook-button"));++ await waitFor(() => {+ expect(screen.getByTestId("share-static-notebook-button")).toBeDisabled();+ });+ expect(+ screen.getByTestId("cancel-share-static-notebook-button"),+ ).toBeDisabled();++ resolveStage(CLAIM_URL);+ await screen.findByTestId("open-claim-page-link");+ });+});diff --git a/frontend/src/components/static-html/__tests__/stage-for-publish.test.ts b/frontend/src/components/static-html/__tests__/stage-for-publish.test.tsnew file mode 100644index 0000000000..1505229612--- /dev/null+++ b/frontend/src/components/static-html/__tests__/stage-for-publish.test.ts@@ -0,0 +1,111 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { MAX_PUBLISH_BYTES, stageForPublish } from "../stage-for-publish";++// Opaque to the client; the shapes here are deliberately not molab's.+const PENDING = {+ pendingId: "id-1",+ presignedUrl: "https://upload.example/put?token=abc",+ claimUrl: "https://claim.example/abc",+ expiresAt: "2026-01-01T00:00:00Z",+};++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++describe("stageForPublish", () => {+ const fetchMock = vi.fn<typeof fetch>();++ beforeEach(() => {+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ fetchMock.mockReset();+ vi.unstubAllGlobals();+ });++ it("reserves a pending upload, PUTs the export, and returns the claim URL", async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse(PENDING))+ .mockResolvedValueOnce(new Response(null, { status: 200 }));++ const claimUrl = await stageForPublish("nb.html", "<html>hi</html>");++ expect(claimUrl).toBe(PENDING.claimUrl);+ expect(fetchMock).toHaveBeenCalledTimes(2);++ const [stageUrl, stageInit] = fetchMock.mock.calls[0];+ expect(String(stageUrl)).toMatch(/\/api\/artifacts\/pending$/);+ expect(stageInit?.method).toBe("POST");+ expect(JSON.parse(String(stageInit?.body))).toEqual({+ fileName: "nb.html",+ fileSize: new Blob(["<html>hi</html>"]).size,+ });++ const [putUrl, putInit] = fetchMock.mock.calls[1];+ expect(putUrl).toBe(PENDING.presignedUrl);+ expect(putInit?.method).toBe("PUT");+ expect(putInit?.body).toBeInstanceOf(Blob);+ });++ it("surfaces the server's error message when staging is rejected", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ error: "Only .html or .htm files are supported" }, 400),+ );++ await expect(stageForPublish("nb.txt", "x")).rejects.toThrow(+ "Only .html or .htm files are supported",+ );+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it("explains a 429 when the body carries no message", async () => {+ fetchMock.mockResolvedValueOnce(new Response("", { status: 429 }));++ await expect(stageForPublish("nb.html", "x")).rejects.toThrow(+ "Too many uploads, try again later",+ );+ });++ it("falls back to a generic message for other bodiless failures", async () => {+ fetchMock.mockResolvedValueOnce(new Response("", { status: 500 }));++ await expect(stageForPublish("nb.html", "x")).rejects.toThrow(+ "Failed to prepare the upload",+ );+ });++ it("fails when the presigned PUT is rejected", async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse(PENDING))+ .mockResolvedValueOnce(new Response(null, { status: 403 }));++ await expect(stageForPublish("nb.html", "x")).rejects.toThrow(+ "Failed to upload the notebook export",+ );+ });++ it("rejects exports over the size limit before touching the network", async () => {+ // Stub Blob so the test doesn't allocate 100 MB.+ const RealBlob = globalThis.Blob;+ vi.stubGlobal(+ "Blob",+ class extends RealBlob {+ override get size() {+ return MAX_PUBLISH_BYTES + 1;+ }+ },+ );++ await expect(stageForPublish("nb.html", "x")).rejects.toThrow(+ "File is too large. Maximum size is 100 MB.",+ );+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/components/static-html/share-modal.tsx b/frontend/src/components/static-html/share-modal.tsxindex c0b5ade9be..dfe6f518e9 100644--- a/frontend/src/components/static-html/share-modal.tsx+++ b/frontend/src/components/static-html/share-modal.tsx@@ -1,7 +1,8 @@/* Copyright 2026 Marimo. All rights reserved. */-import { CopyIcon } from "lucide-react";-import React, { useMemo, useState } from "react";+import { ExternalLinkIcon } from "lucide-react";+import type React from "react";+import { useState } from "react";import { Button } from "@/components/ui/button";import {DialogContent,@@ -10,176 +11,144 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";-import { toast } from "@/components/ui/use-toast";import { Constants } from "@/core/constants";import { getExportLayout } from "@/core/export/layout";import { useRequestClient } from "@/core/network/requests";import { VirtualFileTracker } from "@/core/static/virtual-file-tracker";-import { copyToClipboard } from "@/utils/copy";-import { Events } from "@/utils/events";-import { Input } from "../ui/input";-import { Tooltip } from "../ui/tooltip";+import { Spinner } from "../icons/spinner";+import { stageForPublish } from "./stage-for-publish";++type PublishState =+ | { kind: "idle" }+ | { kind: "publishing" }+ | { kind: "staged"; claimUrl: string }+ | { kind: "failed"; message: string };-const BASE_URL = "https://static.marimo.app";export const ShareStaticNotebookModal: React.FC<{onClose: () => void;}> = ({ onClose }) => {- const [slug, setSlug] = useState("");+ const [state, setState] = useState<PublishState>({ kind: "idle" });const { exportAsHTML } = useRequestClient();- // Keep one random suffix for the lifetime of the modal.- // oxlint-disable-next-line react/purity- const randomHash = useMemo(() => Math.random().toString(36).slice(2, 6), []);-- // Globally unique path- const path = `${slug}-${randomHash}`;- const url = `${BASE_URL}/static/${path}`;-- return (- <DialogContent className="w-fit">- <form- onSubmit={async (e) => {- e.preventDefault();-- onClose();- const { contents: html } = await exportAsHTML({- download: false,- includeCode: true,- files: VirtualFileTracker.INSTANCE.filenames(),- layout: await getExportLayout(),- });+ const handlePublish = async () => {+ setState({ kind: "publishing" });+ try {+ const { contents: html, filename } = await exportAsHTML({+ download: false,+ includeCode: true,+ files: VirtualFileTracker.INSTANCE.filenames(),+ layout: await getExportLayout(),+ // Published notebooks are served from a remote origin, so assets must+ // come from the CDN — never the local server (which is the dev-mode+ // default). The server substitutes {version}.+ assetUrl:+ "https://cdn.jsdelivr.net/npm/@marimo-team/frontend@{version}/dist",+ });- const prevToast = toast({- title: "Uploading static notebook...",- description: "Please wait.",- });+ const claimUrl = await stageForPublish(filename, html);- await fetch(`${BASE_URL}/api/static`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- html: html,- path: path,- }),- }).catch(() => {- prevToast.dismiss();- toast({- title: "Error uploading static page",- description: (- <div>- Please try again later. If the problem persists, please file a- bug report on{" "}- <a- href={Constants.issuesPage}- target="_blank"- rel="noreferrer"- className="underline"- >- GitHub- </a>- .- </div>- ),- });- });+ // Best effort: after the async work above, browsers may treat this as a+ // popup and block it. The dialog keeps the link either way.+ window.open(claimUrl, "_blank", "noopener,noreferrer");+ setState({ kind: "staged", claimUrl });+ } catch (error) {+ setState({+ kind: "failed",+ message:+ error instanceof Error ? error.message : "Something went wrong",+ });+ }+ };- prevToast.dismiss();- toast({- title: "Static page uploaded!",- description: (- <div>- The URL has been copied to your clipboard.- <br />- You can share it with anyone.- </div>- ),- });- }}- >+ if (state.kind === "staged") {+ return (+ <DialogContent className="sm:max-w-[480px]"><DialogHeader>- <DialogTitle>Share static notebook</DialogTitle>+ <DialogTitle>Finish publishing</DialogTitle><DialogDescription>- You can publish a static, non-interactive version of this notebook- to the public web. We will create a link for you that lives on{" "}- <a href={BASE_URL} target="_blank" rel="noreferrer">- {BASE_URL}- </a>- .+ If the confirmation page didn't open in a new tab, open it below.</DialogDescription></DialogHeader>- <div className="flex flex-col gap-6 py-4">- <Input- data-testid="slug-input"- id="slug"- autoFocus={true}- value={slug}- placeholder="Notebook slug"- onChange={(e) => {- const newSlug = e.target.value- .toLowerCase()- .replaceAll(/\s/g, "-")- .replaceAll(/[^\da-z-]/g, "");- setSlug(newSlug);- }}- required={true}- autoComplete="off"- />-- <div className="font-semibold text-sm text-muted-foreground gap-2 flex flex-col">- Anyone will be able to access your notebook at this URL:- <div className="flex items-center gap-2">- <CopyButton text={url} />- <span className="text-primary">{url}</span>- </div>- </div>- </div><DialogFooter><Button- data-testid="cancel-share-static-notebook-button"+ data-testid="done-share-static-notebook-button"variant="secondary"onClick={onClose}>- Cancel+ Done</Button>- <Button- data-testid="share-static-notebook-button"- aria-label="Save"- variant="default"- type="submit"- onClick={async () => {- await copyToClipboard(url);- }}- >- Create+ <Button asChild={true} variant="default">+ <a+ data-testid="open-claim-page-link"+ href={state.claimUrl}+ target="_blank"+ rel="noopener noreferrer"+ >+ <ExternalLinkIcon size={14} strokeWidth={1.5} className="mr-2" />+ Open confirmation page+ </a></Button></DialogFooter>- </form>- </DialogContent>- );-};--const CopyButton = (props: { text: string }) => {- const [copied, setCopied] = React.useState(false);+ </DialogContent>+ );+ }- const copy = Events.stopPropagation(async (e) => {- e.preventDefault();- await copyToClipboard(props.text);- setCopied(true);- setTimeout(() => setCopied(false), 2000);- });+ const isPublishing = state.kind === "publishing";return (- <Tooltip content="Copied!" open={copied}>- <Button- data-testid="copy-static-notebook-url-button"- onClick={copy}- size="xs"- variant="secondary"- >- <CopyIcon size={14} strokeWidth={1.5} />- </Button>- </Tooltip>+ <DialogContent className="sm:max-w-[480px]">+ <DialogHeader>+ <DialogTitle>Publish HTML to web</DialogTitle>+ <DialogDescription>+ Publish a static snapshot of this notebook to{" "}+ <a+ href={Constants.molab}+ target="_blank"+ rel="noopener noreferrer"+ className="underline"+ >+ molab+ </a>+ . Snapshots can be viewed by anyone on the internet.+ </DialogDescription>+ </DialogHeader>+ {state.kind === "failed" && (+ <p+ role="alert"+ className="text-sm text-destructive"+ data-testid="share-static-notebook-error"+ >+ Publish failed: {state.message}+ </p>+ )}+ <DialogFooter>+ <Button+ data-testid="cancel-share-static-notebook-button"+ variant="secondary"+ onClick={onClose}+ disabled={isPublishing}+ >+ Cancel+ </Button>+ <Button+ data-testid="share-static-notebook-button"+ variant="default"+ disabled={isPublishing}+ onClick={handlePublish}+ >+ {isPublishing ? (+ <>+ <Spinner className="mr-2" size="small" />+ Snapshotting notebook ...+ </>+ ) : (+ <>+ <ExternalLinkIcon size={14} strokeWidth={1.5} className="mr-2" />+ {state.kind === "failed" ? "Try again" : "Publish"}+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>);};diff --git a/frontend/src/components/static-html/stage-for-publish.ts b/frontend/src/components/static-html/stage-for-publish.tsnew file mode 100644index 0000000000..867369e93e--- /dev/null+++ b/frontend/src/components/static-html/stage-for-publish.ts@@ -0,0 +1,56 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { Constants } from "@/core/constants";++interface PendingUploadResponse {+ pendingId: string;+ presignedUrl: string;+ claimUrl: string;+ expiresAt: string;+}++// Keep in sync with molab.+export const MAX_PUBLISH_BYTES = 100 * 1024 * 1024;++/**+ * Stage an HTML export for publishing on molab: reserve a pending upload,+ * PUT the bytes to the presigned URL, and return the claim URL where the+ * user finishes publishing after signing in.+ */+export async function stageForPublish(+ fileName: string,+ html: string,+): Promise<string> {+ const blob = new Blob([html], { type: "text/html" });+ if (blob.size > MAX_PUBLISH_BYTES) {+ throw new Error("File is too large. Maximum size is 100 MB.");+ }++ const staged = await fetch(`${Constants.molab}/api/artifacts/pending`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ fileName, fileSize: blob.size }),+ });+ if (!staged.ok) {+ const body = (await staged.json().catch(() => null)) as {+ error?: string;+ } | null;+ throw new Error(+ body?.error ??+ (staged.status === 429+ ? "Too many uploads, try again later"+ : "Failed to prepare the upload"),+ );+ }+ const { presignedUrl, claimUrl } =+ (await staged.json()) as PendingUploadResponse;++ // The presigned PUT is capped to the declared size; the browser sends the+ // matching Content-Length automatically from the blob.+ const put = await fetch(presignedUrl, { method: "PUT", body: blob });+ if (!put.ok) {+ throw new Error("Failed to upload the notebook export");+ }++ return claimUrl;+}diff --git a/frontend/src/core/network/__tests__/export-asset-url.test.ts b/frontend/src/core/network/__tests__/export-asset-url.test.tsnew file mode 100644index 0000000000..1bfe043e2b--- /dev/null+++ b/frontend/src/core/network/__tests__/export-asset-url.test.ts@@ -0,0 +1,45 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { afterEach, describe, expect, it } from "vitest";+import { withDevAssetUrl } from "../export-asset-url";+import type { ExportAsHTMLRequest } from "../types";++const REQUEST: ExportAsHTMLRequest = {+ download: false,+ includeCode: true,+ files: [],+};++describe("withDevAssetUrl", () => {+ const originalEnv = process.env.NODE_ENV;++ afterEach(() => {+ process.env.NODE_ENV = originalEnv;+ });++ it.each(["development", "test"])(+ "defaults assetUrl to the dev server in %s",+ (env) => {+ process.env.NODE_ENV = env;+ expect(withDevAssetUrl(REQUEST).assetUrl).toBe(window.location.origin);+ },+ );++ it("leaves a caller-provided assetUrl alone in dev", () => {+ process.env.NODE_ENV = "development";+ const cdn = "https://cdn.example.com/dist";+ expect(withDevAssetUrl({ ...REQUEST, assetUrl: cdn }).assetUrl).toBe(cdn);+ });++ it("does nothing in production", () => {+ process.env.NODE_ENV = "production";+ expect(withDevAssetUrl(REQUEST)).toBe(REQUEST);+ });++ it("does not mutate the caller's request", () => {+ process.env.NODE_ENV = "development";+ const request = { ...REQUEST };+ withDevAssetUrl(request);+ expect(request.assetUrl).toBeUndefined();+ });+});diff --git a/frontend/src/core/network/export-asset-url.ts b/frontend/src/core/network/export-asset-url.tsnew file mode 100644index 0000000000..d21ecf87cd--- /dev/null+++ b/frontend/src/core/network/export-asset-url.ts@@ -0,0 +1,19 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { ExportAsHTMLRequest } from "./types";++/**+ * In dev/test the CDN has no assets for the local build, so exports default+ * to the dev server. Callers publishing to a remote origin pass their own+ * assetUrl, which is left untouched.+ */+export function withDevAssetUrl(+ request: ExportAsHTMLRequest,+): ExportAsHTMLRequest {+ const isDevOrTest =+ process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";+ if (request.assetUrl == null && isDevOrTest) {+ return { ...request, assetUrl: window.location.origin };+ }+ return request;+}diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.tsindex 3a17562b1c..a55ffa71f2 100644--- a/frontend/src/core/network/requests-network.ts+++ b/frontend/src/core/network/requests-network.ts@@ -11,6 +11,7 @@ import {waitForConnectionOpen,waitForConnectionOpenIfNotebook,} from "./connection";+import { withDevAssetUrl } from "./export-asset-url";import type { EditRequests, RunRequests } from "./types";/**@@ -430,15 +431,9 @@ export function createNetworkRequests(): EditRequests & RunRequests {.then(handleResponse);},exportAsHTML: async (request) => {- if (- process.env.NODE_ENV === "development" ||- process.env.NODE_ENV === "test"- ) {- request.assetUrl = window.location.origin;- }return getClient().POST("/api/export/html", {- body: request,+ body: withDevAssetUrl(request),parseAs: "text",params: getParams(),})diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.tsindex c0fb07f73d..8e3ebf0735 100644--- a/frontend/src/core/wasm/bridge.ts+++ b/frontend/src/core/wasm/bridge.ts@@ -14,6 +14,7 @@ import { notebookIsRunningAtom } from "../cells/cells";import type { CommandMessage } from "../kernel/messages";import { getInitialAppMode } from "../mode";import { API } from "../network/api";+import { withDevAssetUrl } from "../network/export-asset-url";import type {EditRequests,EnvironmentInfo,@@ -535,15 +536,9 @@ export class PyodideBridge implements RunRequests, EditRequests {request: ExportAsHTMLRequest,) => {await this.pendingSessionSave;- if (- process.env.NODE_ENV === "development" ||- process.env.NODE_ENV === "test"- ) {- request.assetUrl = window.location.origin;- }const response = await this.rpc.proxy.request.bridge({functionName: "export_html",- payload: request,+ payload: withDevAssetUrl(request),});return response as ExportedFile<string>;};