Skip to content

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.

feat(export): install server requirements (#10473)

Péter Gyarmati397fae2de140
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index c78981f57c..ece24aba1d 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -100,6 +100,10 @@ export const MockRequestClient = {
},
],
}),
+ installExportRequirements: vi.fn().mockResolvedValue({
+ source: "server",
+ formats: [],
+ }),
exportAsHTML: vi.fn().mockResolvedValue({
contents: "",
filename: "notebook.html",
diff --git a/frontend/src/components/editor/actions/export-dialog/__tests__/export-dialog.test.tsx b/frontend/src/components/editor/actions/export-dialog/__tests__/export-dialog.test.tsx
index 3c02be33aa..a262e729a2 100644
--- a/frontend/src/components/editor/actions/export-dialog/__tests__/export-dialog.test.tsx
+++ b/frontend/src/components/editor/actions/export-dialog/__tests__/export-dialog.test.tsx
@@ -13,12 +13,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MockRequestClient } from "@/__mocks__/requests";
import { Dialog } from "@/components/ui/dialog";
import { TooltipProvider } from "@/components/ui/tooltip";
-import { viewStateAtom } from "@/core/mode";
+import { kioskModeAtom, viewStateAtom } from "@/core/mode";
import { requestClientAtom } from "@/core/network/requests";
+import { createErrorToastingRequests } from "@/core/network/requests-toasting";
+import type { ExportAvailabilityResponse } from "@/core/network/types";
import { filenameAtom } from "@/core/saving/file-state";
import { store } from "@/core/state/jotai";
import { isWasm } from "@/core/wasm/utils";
import * as copyModule from "@/utils/copy";
+import { Deferred } from "@/utils/Deferred";
+import { HTTPError } from "@/utils/errors";
import { ExportDialog } from "../export-dialog";
import {
DEFAULT_EXPORT_OPTIONS,
@@ -27,14 +31,22 @@ import {
lastExportFormatAtom,
} from "../state";
-const { exportNotebookMock } = vi.hoisted(() => ({
+const { exportNotebookMock, toastMock } = vi.hoisted(() => ({
exportNotebookMock: vi.fn().mockResolvedValue(undefined),
+ toastMock: vi.fn(() => ({
+ dismiss: vi.fn(),
+ update: vi.fn(),
+ })),
}));
vi.mock("@/utils/copy", () => ({
copyToClipboard: vi.fn().mockResolvedValue(undefined),
}));
+vi.mock("@/components/ui/use-toast", () => ({
+ toast: toastMock,
+}));
+
vi.mock("@/core/wasm/utils", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/core/wasm/utils")>();
return { ...actual, isWasm: vi.fn(() => false) };
@@ -67,6 +79,32 @@ async function waitForExportEnabled() {
);
}
+type FormatAvailability = ExportAvailabilityResponse["formats"][number];
+
+function formatAvailability(
+ format: FormatAvailability["format"],
+ overrides: Partial<Omit<FormatAvailability, "format">> = {},
+): FormatAvailability {
+ return {
+ format,
+ dependenciesAvailable: true,
+ missingPackages: [],
+ missingSetup: [],
+ ...overrides,
+ };
+}
+
+function serverAvailability(
+ ...formats: FormatAvailability[]
+): ExportAvailabilityResponse {
+ return { source: "server", formats };
+}
+
+const PLAYWRIGHT_SETUP = {
+ name: "playwright-chromium",
+ command: "uv run playwright install chromium",
+} as const;
+
describe("ExportDialog", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -74,8 +112,10 @@ describe("ExportDialog", () => {
store.set(requestClientAtom, MockRequestClient.create());
store.set(filenameAtom, "/project/notebook.py");
store.set(viewStateAtom, { mode: "edit", cellAnchor: null });
+ store.set(kioskModeAtom, false);
store.set(exportOptionsAtom, DEFAULT_EXPORT_OPTIONS);
store.set(lastExportFormatAtom, "html");
+ window.history.replaceState(null, "", "/");
vi.mocked(isWasm).mockReturnValue(false);
vi.stubGlobal("matchMedia", () => ({
matches: false,
@@ -248,54 +288,80 @@ describe("ExportDialog", () => {
expect(tablist).toHaveAttribute("aria-orientation", "vertical");
});
- it("keeps unavailable formats visible and names missing packages", async () => {
+ it("installs missing packages and applies refreshed availability", async () => {
+ const install = new Deferred<ExportAvailabilityResponse>();
+ const installExportRequirements = vi.fn(() => install.promise);
+ const getExportAvailability = vi.fn().mockResolvedValue(
+ serverAvailability(
+ formatAvailability("ipynb", {
+ dependenciesAvailable: false,
+ missingPackages: ["nbformat"],
+ }),
+ formatAvailability("pdf", {
+ dependenciesAvailable: false,
+ missingPackages: ["nbconvert[webpdf]", "nbformat"],
+ }),
+ ),
+ );
store.set(
requestClientAtom,
MockRequestClient.create({
- getExportAvailability: vi.fn().mockResolvedValue({
- source: "server",
- formats: [
- {
- format: "pdf",
- dependenciesAvailable: false,
- missingPackages: ["nbconvert[webpdf]"],
- missingSetup: [],
- },
- ],
- }),
+ getExportAvailability,
+ installExportRequirements,
}),
);
renderDialog("pdf");
- expect(await screen.findByText("nbconvert[webpdf]")).toBeVisible();
- expect(
- screen.getByText(/where marimo is running to use this export/),
- ).toBeVisible();
+ const packages = await screen.findByText("nbconvert[webpdf], nbformat");
+ expect(packages.parentElement).toHaveTextContent(
+ "PDF export requires nbconvert[webpdf], nbformat.",
+ );
expect(screen.getByTestId("export-submit")).toBeDisabled();
expect(screen.getByTestId("export-format-pdf")).toBeVisible();
+
+ const installButton = screen.getByRole("button", { name: "Install" });
+ const pdfTab = screen.getByTestId("export-format-pdf");
+ const htmlTab = screen.getByTestId("export-format-html");
+
+ fireEvent.click(installButton);
+
+ await waitFor(() =>
+ expect(installExportRequirements).toHaveBeenCalledWith({ format: "pdf" }),
+ );
+ expect(installButton).toHaveAttribute("aria-busy", "true");
+ expect(htmlTab).toBeDisabled();
+
+ fireEvent.click(installButton);
+ fireEvent.click(htmlTab);
+ expect(installExportRequirements).toHaveBeenCalledOnce();
+ expect(pdfTab).toHaveAttribute("data-state", "active");
+
+ install.resolve(
+ serverAvailability(
+ formatAvailability("ipynb"),
+ formatAvailability("pdf"),
+ ),
+ );
+ await waitForExportEnabled();
+ expect(getExportAvailability).toHaveBeenCalledOnce();
+
+ fireEvent.click(screen.getByTestId("export-format-ipynb"));
+ expect(screen.getByTestId("export-submit")).toBeEnabled();
});
it("explains missing Playwright Chromium setup", async () => {
store.set(
requestClientAtom,
MockRequestClient.create({
- getExportAvailability: vi.fn().mockResolvedValue({
- source: "server",
- formats: [
- {
- format: "pdf",
+ getExportAvailability: vi.fn().mockResolvedValue(
+ serverAvailability(
+ formatAvailability("pdf", {
dependenciesAvailable: false,
- missingPackages: [],
- missingSetup: [
- {
- name: "playwright-chromium",
- command: "uv run playwright install chromium",
- },
- ],
- },
- ],
- }),
+ missingSetup: [PLAYWRIGHT_SETUP],
+ }),
+ ),
+ ),
}),
);
@@ -305,9 +371,115 @@ describe("ExportDialog", () => {
await screen.findByText("PDF export requires Playwright Chromium."),
).toBeVisible();
expect(
- screen.getByText("uv run playwright install chromium"),
+ screen.queryByText("uv run playwright install chromium"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByTestId("export-submit")).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Install" })).toBeVisible();
+ });
+
+ it.each([
+ ["read mode", "read", false, false],
+ ["connected kiosk mode", "edit", true, false],
+ ["pre-connection kiosk mode", "edit", false, true],
+ ] as const)(
+ "shows the setup command when installation is not allowed in %s",
+ async (_label, mode, kioskMode, kioskRequested) => {
+ store.set(viewStateAtom, { mode, cellAnchor: null });
+ store.set(kioskModeAtom, kioskMode);
+ if (kioskRequested) {
+ window.history.replaceState(null, "", "/?kiosk=true");
+ }
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getExportAvailability: vi.fn().mockResolvedValue(
+ serverAvailability(
+ formatAvailability("pdf", {
+ dependenciesAvailable: false,
+ missingSetup: [PLAYWRIGHT_SETUP],
+ }),
+ ),
+ ),
+ }),
+ );
+
+ renderDialog("pdf");
+
+ expect(
+ await screen.findByText("PDF export requires Playwright Chromium."),
+ ).toBeVisible();
+ expect(
+ screen.getByText("uv run playwright install chromium"),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Install" }),
+ ).not.toBeInTheDocument();
+ },
+ );
+
+ it("allows requirement installation when kiosk is false", async () => {
+ window.history.replaceState(null, "", "/?kiosk=false");
+ store.set(
+ requestClientAtom,
+ MockRequestClient.create({
+ getExportAvailability: vi.fn().mockResolvedValue(
+ serverAvailability(
+ formatAvailability("pdf", {
+ dependenciesAvailable: false,
+ missingSetup: [PLAYWRIGHT_SETUP],
+ }),
+ ),
+ ),
+ }),
+ );
+
+ renderDialog("pdf");
+
+ expect(
+ await screen.findByRole("button", { name: "Install" }),
).toBeVisible();
+ });
+
+ it("restores the install action when installation fails", async () => {
+ const error = new HTTPError(500, "Server Error", {
+ detail: "Playwright Chromium installation failed. Check the server logs.",
+ });
+ const installExportRequirements = vi.fn().mockRejectedValue(error);
+ const getExportAvailability = vi.fn().mockResolvedValue(
+ serverAvailability(
+ formatAvailability("pdf", {
+ dependenciesAvailable: false,
+ missingPackages: ["nbconvert[webpdf]"],
+ }),
+ ),
+ );
+ store.set(
+ requestClientAtom,
+ createErrorToastingRequests(
+ MockRequestClient.create({
+ getExportAvailability,
+ installExportRequirements,
+ }),
+ ),
+ );
+
+ renderDialog("pdf");
+
+ const install = await screen.findByRole("button", { name: "Install" });
+ fireEvent.click(install);
+
+ await waitFor(() =>
+ expect(toastMock).toHaveBeenCalledWith({
+ title: "Failed to install export requirements",
+ description:
+ "Playwright Chromium installation failed. Check the server logs.",
+ variant: "danger",
+ }),
+ );
+ expect(install).toBeEnabled();
+ expect(install).toHaveAttribute("aria-busy", "false");
expect(screen.getByTestId("export-submit")).toBeDisabled();
+ expect(getExportAvailability).toHaveBeenCalledOnce();
});
it("announces requirement checks as status updates", () => {
diff --git a/frontend/src/components/editor/actions/export-dialog/export-dialog.tsx b/frontend/src/components/editor/actions/export-dialog/export-dialog.tsx
index f1430a778d..ac22ecdd3f 100644
--- a/frontend/src/components/editor/actions/export-dialog/export-dialog.tsx
+++ b/frontend/src/components/editor/actions/export-dialog/export-dialog.tsx
@@ -28,13 +28,17 @@ export const ExportDialog: React.FC<{
const {
dialogRef,
isExporting,
+ isInstalling,
+ canInstall,
formats,
options,
selected,
selectFormat,
updateOptions,
+ installRequirements,
submit,
} = useExportDialog({ initialFormat, onClose });
+ const isBusy = isExporting || isInstalling;
const desktopLayout = useMediaQuery(DESKTOP_LAYOUT_QUERY);
const {
format,
@@ -86,7 +90,7 @@ export const ExportDialog: React.FC<{
<TabsTrigger
key={candidate}
value={candidate}
- disabled={isExporting}
+ disabled={isBusy}
className="min-w-0 justify-start gap-2 px-2.5 py-2 text-xs data-[state=active]:shadow-xs sm:w-full sm:text-sm"
data-testid={`export-format-${candidate}`}
>
@@ -119,13 +123,15 @@ export const ExportDialog: React.FC<{
format={format}
formatLabel={definition.label}
status={status}
+ onInstall={canInstall ? installRequirements : undefined}
+ isInstalling={isInstalling}
/>
{usesBrowserPrint ? null : (
<FormatOptions
options={options}
updateOptions={updateOptions}
- disabled={isExporting}
+ disabled={isBusy}
/>
)}
</TabsContent>
@@ -173,7 +179,7 @@ export const ExportDialog: React.FC<{
) : null}
<Button
type="button"
- disabled={!status.available || isExporting}
+ disabled={!status.available || isBusy}
aria-busy={isExporting}
onClick={submit}
className={cn(
diff --git a/frontend/src/components/editor/actions/export-dialog/format-notice.tsx b/frontend/src/components/editor/actions/export-dialog/format-notice.tsx
index 4efe214a08..f2811b76da 100644
--- a/frontend/src/components/editor/actions/export-dialog/format-notice.tsx
+++ b/frontend/src/components/editor/actions/export-dialog/format-notice.tsx
@@ -1,9 +1,10 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { AlertCircleIcon } from "lucide-react";
+import { AlertCircleIcon, DownloadCloudIcon } from "lucide-react";
import type { PropsWithChildren } from "react";
import { Spinner } from "@/components/icons/spinner";
import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
import { assertNever } from "@/utils/assertNever";
import { cn } from "@/utils/cn";
import type {
@@ -56,10 +57,14 @@ export function FormatNotice({
format,
formatLabel,
status,
+ onInstall,
+ isInstalling = false,
}: {
format: ExportFormat;
formatLabel: string;
status: ExportFormatStatus;
+ onInstall?: () => void;
+ isInstalling?: boolean;
}) {
if (status.availabilityCheckFailed) {
return (
@@ -80,20 +85,47 @@ export function FormatNotice({
format={format}
formatLabel={formatLabel}
reason={status.reason}
+ onInstall={onInstall}
+ isInstalling={isInstalling}
/>
</div>
);
}
-function Notice({ children }: PropsWithChildren) {
+function Notice({
+ children,
+ onInstall,
+ isInstalling = false,
+}: PropsWithChildren<{
+ onInstall?: () => void;
+ isInstalling?: boolean;
+}>) {
return (
<Alert
variant="warning"
- className="flex items-start gap-2.5 p-3 text-(--yellow-12) has-[svg]:pl-3 sm:items-center [&>svg]:static [&>svg+div]:translate-y-0"
+ className="flex items-center gap-2.5 px-3 py-2 text-(--yellow-12) has-[svg]:pl-3 [&>svg]:static [&>svg+div]:translate-y-0"
>
- <AlertCircleIcon className="mt-0.5 size-4 shrink-0 sm:mt-0" />
- <AlertDescription className="min-w-0 flex-1 text-sm leading-5">
- {children}
+ <AlertCircleIcon className="size-4 shrink-0" />
+ <AlertDescription className="flex min-w-0 flex-1 items-center gap-3 text-sm leading-5">
+ <span className="min-w-0 flex-1">{children}</span>
+ {onInstall ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ className="shrink-0 border-input bg-background text-foreground hover:border-input hover:bg-muted hover:text-foreground"
+ disabled={isInstalling}
+ aria-busy={isInstalling}
+ onClick={onInstall}
+ >
+ {isInstalling ? (
+ <Spinner size="small" className="mr-1.5 size-3.5" />
+ ) : (
+ <DownloadCloudIcon className="mr-1.5 size-3.5" />
+ )}
+ Install
+ </Button>
+ ) : null}
</AlertDescription>
</Alert>
);
@@ -103,10 +135,14 @@ function ReasonNotice({
format,
formatLabel,
reason,
+ onInstall,
+ isInstalling,
}: {
format: ExportFormat;
formatLabel: string;
reason: ExportBlockReason;
+ onInstall?: () => void;
+ isInstalling: boolean;
}) {
switch (reason.type) {
case "checking-requirements":
@@ -126,30 +162,39 @@ function ReasonNotice({
return <Notice>Name and save this notebook before exporting.</Notice>;
case "missing-packages":
return (
- <Notice>
- Install{" "}
+ <Notice onInstall={onInstall} isInstalling={isInstalling}>
+ {formatLabel} export requires{" "}
<code className="break-words font-mono">
{reason.packages.join(", ")}
- </code>{" "}
- where marimo is running to use this export.
+ </code>
+ .
</Notice>
);
case "missing-setup":
return (
- <Notice>
- <span className="block min-w-0">
- {reason.requirements.map((requirement) => {
- const details = SETUP_REQUIREMENTS[requirement.name];
- return (
- <span className="block" key={requirement.name}>
- {details.description}
- <code className="mt-1 block break-all font-mono">
- {requirement.command}
- </code>
- </span>
- );
- })}
- </span>
+ <Notice onInstall={onInstall} isInstalling={isInstalling}>
+ {onInstall ? (
+ reason.requirements
+ .map(
+ (requirement) =>
+ SETUP_REQUIREMENTS[requirement.name].description,
+ )
+ .join(" ")
+ ) : (
+ <span className="block min-w-0">
+ {reason.requirements.map((requirement) => {
+ const details = SETUP_REQUIREMENTS[requirement.name];
+ return (
+ <span className="block" key={requirement.name}>
+ {details.description}
+ <code className="mt-1 block break-all font-mono">
+ {requirement.command}
+ </code>
+ </span>
+ );
+ })}
+ </span>
+ )}
</Notice>
);
case "wasm-runtime":
diff --git a/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts b/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts
index f0dcd1fa5a..23194645f2 100644
--- a/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts
+++ b/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts
@@ -7,7 +7,7 @@ import {
updateCellOutputsWithScreenshots,
useEnrichCellOutputs,
} from "@/core/export/hooks";
-import { runDuringPresentMode } from "@/core/mode";
+import { runDuringPresentMode, useInstallAllowed } from "@/core/mode";
import { useRequestClient } from "@/core/network/requests";
import type { ExportAvailabilityResponse } from "@/core/network/types";
import { useFilename } from "@/core/saving/filename";
@@ -116,6 +116,8 @@ function useExportDialogState(initialFormat?: ExportFormat) {
);
const runtime = isWasm() ? "wasm" : "server";
const requests = useRequestClient();
+ const installAllowed = useInstallAllowed();
+ const [isInstalling, setIsInstalling] = useState(false);
const availabilityRequest =
useAsyncData<ExportAvailabilityResponse | null>(async () => {
@@ -135,6 +137,10 @@ function useExportDialogState(initialFormat?: ExportFormat) {
availability,
});
const status = statusFor(format);
+ const canInstall =
+ installAllowed &&
+ (status.reason?.type === "missing-packages" ||
+ status.reason?.type === "missing-setup");
const formats = EXPORT_FORMATS.map((candidate) => ({
format: candidate,
status: statusFor(candidate),
@@ -184,6 +190,22 @@ function useExportDialogState(initialFormat?: ExportFormat) {
});
};
+ const installRequirements = async () => {
+ if (!canInstall || isInstalling || format === "png") {
+ return;
+ }
+
+ setIsInstalling(true);
+ try {
+ const availability = await requests.installExportRequirements({ format });
+ availabilityRequest.setData(availability);
+ } catch {
+ // Request failures are surfaced by the shared toast layer.
+ } finally {
+ setIsInstalling(false);
+ }
+ };
+
return {
formats,
options,
@@ -205,6 +227,9 @@ function useExportDialogState(initialFormat?: ExportFormat) {
},
selectFormat,
updateOptions,
+ canInstall,
+ isInstalling,
+ installRequirements,
};
}
@@ -364,7 +389,7 @@ export function useExportDialog({
...state,
...action,
selectFormat: (value: string) => {
- if (!action.isExporting) {
+ if (!action.isExporting && !state.isInstalling) {
selectFormat(value);
}
},
diff --git a/frontend/src/components/ui/toaster.tsx b/frontend/src/components/ui/toaster.tsx
index e94d60154f..5dfb0259be 100644
--- a/frontend/src/components/ui/toaster.tsx
+++ b/frontend/src/components/ui/toaster.tsx
@@ -1,9 +1,12 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { ComponentPropsWithoutRef, ReactElement, ReactNode } from "react";
import { useRef } from "react";
+import { createPortal } from "react-dom";
import { CopyClipboardIcon } from "@/components/icons/copy-icon";
import { useToast } from "@/components/ui/use-toast";
+import { StyleNamespace } from "@/theme/namespace";
import { cn } from "@/utils/cn";
+import { withFullScreenAsRoot } from "./fullscreen";
import {
Toast,
ToastClose,
@@ -28,11 +31,21 @@ export const Toaster = () => {
{...props}
/>
))}
- <ToastViewport />
+ <ToastViewportPortal />
</ToastProvider>
);
};
+const ToastViewportPortal = withFullScreenAsRoot(
+ ({ container }: { container?: Element | DocumentFragment | null }) =>
+ createPortal(
+ <StyleNamespace>
+ <ToastViewport />
+ </StyleNamespace>,
+ container ?? document.body,
+ ),
+);
+
type ToastItemProps = Omit<
ComponentPropsWithoutRef<typeof Toast>,
"title" | "children"
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 26e86c6814..38eddcb1d8 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -356,6 +356,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
sendFileDetails = throwNotImplemented;
openTutorial = throwNotImplemented;
getExportAvailability = throwNotImplemented;
+ installExportRequirements = throwNotImplemented;
exportAsHTML = throwNotImplemented;
exportAsIPYNB = throwNotImplemented;
exportAsMarkdown = throwNotImplemented;
diff --git a/frontend/src/core/mode.ts b/frontend/src/core/mode.ts
index 8c927265d7..290bc8527a 100644
--- a/frontend/src/core/mode.ts
+++ b/frontend/src/core/mode.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { atom, useAtomValue } from "jotai";
+import { KnownQueryParams } from "@/core/constants";
import { isIslands } from "@/core/islands/utils";
import { assertExists } from "@/utils/assertExists";
import { invariant } from "@/utils/invariant";
@@ -98,5 +99,9 @@ export const kioskModeAtom = atom<boolean>(false);
*/
export function useInstallAllowed(): boolean {
const { mode } = useAtomValue(viewStateAtom);
- return mode !== "read";
+ const kioskMode = useAtomValue(kioskModeAtom);
+ const kioskRequested =
+ new URLSearchParams(window.location.search).get(KnownQueryParams.kiosk) ===
+ "true";
+ return mode !== "read" && !kioskMode && !kioskRequested;
}
diff --git a/frontend/src/core/network/__tests__/requests-lazy.test.ts b/frontend/src/core/network/__tests__/requests-lazy.test.ts
index 4a4fb75d19..91fc895ec7 100644
--- a/frontend/src/core/network/__tests__/requests-lazy.test.ts
+++ b/frontend/src/core/network/__tests__/requests-lazy.test.ts
@@ -2,7 +2,9 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { cellId, requestId, uiElementId } from "@/__tests__/branded";
+import { waitForKernelToBeInstantiated } from "../../kernel/state";
import type { RuntimeManager } from "../../runtime/runtime";
+import { waitForConnectionOpen } from "../connection";
import { createLazyRequests } from "../requests-lazy";
import type {
EditRequests,
@@ -55,6 +57,10 @@ describe("createLazyRequests", () => {
sendInterrupt: vi.fn().mockResolvedValue({ interrupted: true }),
sendPdb: vi.fn().mockResolvedValue({ pdb: true }),
sendRunScratchpad: vi.fn().mockResolvedValue({ run: true }),
+ installExportRequirements: vi.fn().mockResolvedValue({
+ source: "server",
+ formats: [],
+ }),
} as unknown as EditRequests & RunRequests;
});
@@ -104,6 +110,40 @@ describe("createLazyRequests", () => {
expect(mockDelegate.getExportAvailability).toHaveBeenCalledOnce();
});
+ it("installs export requirements without waiting for the kernel", async () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.installExportRequirements({ format: "pdf" });
+
+ expect(mockInit).toHaveBeenCalledOnce();
+ expect(waitForConnectionOpen).toHaveBeenCalledOnce();
+ expect(waitForKernelToBeInstantiated).not.toHaveBeenCalled();
+ expect(mockDelegate.installExportRequirements).toHaveBeenCalledWith({
+ format: "pdf",
+ });
+ });
+
+ it("sends instantiate without waiting for the kernel", async () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+ const request = {
+ objectIds: [uiElementId("obj1")],
+ values: [],
+ };
+
+ await lazyRequests.sendInstantiate(request);
+
+ expect(mockInit).toHaveBeenCalledOnce();
+ expect(waitForConnectionOpen).toHaveBeenCalledOnce();
+ expect(waitForKernelToBeInstantiated).not.toHaveBeenCalled();
+ expect(mockDelegate.sendInstantiate).toHaveBeenCalledWith(request);
+ });
+
it("should call init once before first request", async () => {
const lazyRequests = createLazyRequests(
mockDelegate,
diff --git a/frontend/src/core/network/__tests__/requests-network.test.ts b/frontend/src/core/network/__tests__/requests-network.test.ts
index e8726acfdc..0806eccb9a 100644
--- a/frontend/src/core/network/__tests__/requests-network.test.ts
+++ b/frontend/src/core/network/__tests__/requests-network.test.ts
@@ -143,6 +143,19 @@ describe("createNetworkRequests", () => {
expect(mockClient.GET).toHaveBeenCalledWith("/api/export/availability");
});
+ it("installExportRequirements should POST the export format", async () => {
+ const requests = createNetworkRequests();
+ await requests.installExportRequirements({ format: "pdf" });
+
+ expect(mockClient.POST).toHaveBeenCalledWith(
+ "/api/export/requirements/install",
+ expect.objectContaining({
+ body: { format: "pdf" },
+ params: expect.anything(),
+ }),
+ );
+ });
+
it("discoverDataSources should POST to the discovery endpoint", async () => {
const requests = createNetworkRequests();
const request = { requestId: "discovery-request" } as any;
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index d63904ee87..0ee57ea922 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -26,6 +26,10 @@ type AllRequests = EditRequests & RunRequests;
// executing. Use for user-initiated actions that should "just work" and
// kick off the kernel if needed (e.g., clicking Run).
//
+// - startConnectionWithoutKernel: Initializes the runtime and waits for an open
+// connection. Use for session-scoped server requests that do not need an
+// instantiated kernel.
+//
// - waitForConnectionOpen: Waits for an existing connection but won't start one.
// Use for operations that depend on a running kernel but shouldn't be the
// trigger to start it (e.g., saving, interrupting).
@@ -38,6 +42,7 @@ type Action =
| "throwError"
| "dropRequest"
| "startConnection"
+ | "startConnectionWithoutKernel"
| "waitForConnectionOpen"
| "serverOnly";
@@ -45,7 +50,7 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
// These will start a connection if not already connected and then wait until the connection is open
sendComponentValues: "startConnection",
sendModelValue: "startConnection",
- sendInstantiate: "startConnection",
+ sendInstantiate: "startConnectionWithoutKernel",
sendRun: "startConnection",
sendDeleteCell: "startConnection",
sendRunScratchpad: "startConnection",
@@ -107,6 +112,9 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
getEnvironmentInfo: "serverOnly",
getExportAvailability: "serverOnly",
+ // Session-scoped server operations
+ installExportRequirements: "startConnectionWithoutKernel",
+
// Home operations throw errors
getRecentFiles: "startConnection",
getWorkspaceFiles: "startConnection",
@@ -186,13 +194,12 @@ export function createLazyRequests(
await waitForKernelToBeInstantiated();
return request(...args);
+ case "startConnectionWithoutKernel":
case "startConnection":
// Start connection and wait for it to be open
await initOnce(runtimeManager);
await waitForConnectionOpen();
- if (key !== "sendInstantiate") {
- // We don't need to wait for kernel to be instantiated if we are sending an instantiate request
- // otherwise we will wait forever
+ if (action === "startConnection") {
await waitForKernelToBeInstantiated();
}
return request(...args);
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index e47018b367..4d6dd37d8b 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -417,6 +417,14 @@ export function createNetworkRequests(): EditRequests & RunRequests {
getExportAvailability: () => {
return getClient().GET("/api/export/availability").then(handleResponse);
},
+ installExportRequirements: (request) => {
+ return getClient()
+ .POST("/api/export/requirements/install", {
+ body: request,
+ params: getParams(),
+ })
+ .then(handleResponse);
+ },
exportAsHTML: async (request) => {
if (
process.env.NODE_ENV === "development" ||
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 16b6b8a6ba..e1343b2880 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -84,6 +84,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
getRunningNotebooks: throwNotInEditMode,
shutdownSession: throwNotInEditMode,
getExportAvailability: throwNotInEditMode,
+ installExportRequirements: throwNotInEditMode,
exportAsHTML: throwNotInEditMode,
exportAsIPYNB: throwNotInEditMode,
exportAsMarkdown: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index fb09e214b5..a16f8997c1 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -65,6 +65,7 @@ export function createErrorToastingRequests(
getRunningNotebooks: "Failed to get running notebooks",
shutdownSession: "Failed to shutdown session",
getExportAvailability: "", // No toast
+ installExportRequirements: "Failed to install export requirements",
exportAsHTML: "Failed to export HTML",
exportAsIPYNB: "Failed to export ipynb",
exportAsMarkdown: "Failed to export Markdown",
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index fae25e87dc..595ec371be 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -29,6 +29,8 @@ export type ExportAsIPYNBRequest = schemas["ExportAsIPYNBRequest"];
export type ExportAsScriptRequest = schemas["ExportAsScriptRequest"];
export type ExportAsPDFRequest = schemas["ExportAsPDFRequest"];
export type ExportAvailabilityResponse = schemas["ExportAvailabilityResponse"];
+export type InstallExportRequirementsRequest =
+ schemas["InstallExportRequirementsRequest"];
export type UpdateCellOutputsRequest = schemas["UpdateCellOutputsRequest"];
export interface ExportedFile<T extends BlobPart = BlobPart> {
@@ -223,6 +225,9 @@ export interface EditRequests {
) => Promise<RunningNotebooksResponse>;
// Export requests
getExportAvailability: () => Promise<ExportAvailabilityResponse>;
+ installExportRequirements: (
+ request: InstallExportRequirementsRequest,
+ ) => Promise<ExportAvailabilityResponse>;
exportAsHTML: (request: ExportAsHTMLRequest) => Promise<ExportedFile<string>>;
exportAsIPYNB: (
request: ExportAsIPYNBRequest,
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 3debd10726..ebb9a55358 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -675,6 +675,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
getRunningNotebooks = throwNotImplemented;
shutdownSession = throwNotImplemented;
getExportAvailability = throwNotImplemented;
+ installExportRequirements = throwNotImplemented;
exportAsIPYNB = throwNotImplemented;
exportAsPDF = throwNotImplemented;
autoExportAsHTML = throwNotImplemented;
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index e12dcabcea..325e341aef 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -360,6 +360,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
export.ExportAsIPYNBRequest,
export.ExportAsPDFRequest,
export.ExportAvailabilityResponse,
+ export.InstallExportRequirementsRequest,
export.UpdateCellOutputsRequest,
files.FileCreateMultipartRequest,
files.FileCreateRequest,
diff --git a/marimo/_export/dependencies.py b/marimo/_export/dependencies.py
index c9cb073f9d..ca107e8f2c 100644
--- a/marimo/_export/dependencies.py
+++ b/marimo/_export/dependencies.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
+import subprocess
import sys
from typing import cast
@@ -15,13 +16,17 @@ from marimo._dependencies.dependencies import (
DependencyRequirement,
)
from marimo._schemas.export import ExportSetupRequirement
-from marimo._schemas.export_options import ServerExportFormat
+from marimo._schemas.export_options import (
+ ExportSetupRequirementName,
+ ServerExportFormat,
+)
from marimo._utils.assert_never import assert_never
from marimo._utils.async_path import isfile
LOGGER = _loggers.marimo_logger()
_IPYNB_DEPENDENCIES = (DependencyManager.nbformat,)
+_PLAYWRIGHT_INSTALL_TIMEOUT_SECONDS = 600
_PDF_DEPENDENCIES = (
DependencyRequirement(
package="nbconvert[webpdf]",
@@ -61,6 +66,43 @@ def get_missing_export_packages(
)
+async def _install_playwright_chromium() -> None:
+ try:
+ result = await asyncio.to_thread(
+ subprocess.run,
+ [sys.executable, "-m", "playwright", "install", "chromium"],
+ capture_output=True,
+ text=True,
+ timeout=_PLAYWRIGHT_INSTALL_TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired:
+ LOGGER.error(
+ "Playwright Chromium installation timed out after %s seconds",
+ _PLAYWRIGHT_INSTALL_TIMEOUT_SECONDS,
+ )
+ raise RuntimeError(
+ "Playwright Chromium installation failed. Check the server logs."
+ ) from None
+ if result.returncode != 0:
+ LOGGER.error(
+ "Failed to install Playwright Chromium: %s",
+ result.stderr or result.stdout,
+ )
+ raise RuntimeError(
+ "Playwright Chromium installation failed. Check the server logs."
+ )
+
+
+async def install_export_setup(
+ requirement: ExportSetupRequirementName,
+) -> None:
+ match requirement:
+ case "playwright-chromium":
+ await _install_playwright_chromium()
+ case _:
+ assert_never(requirement)
+
+
async def get_missing_export_setup(
export_format: ServerExportFormat,
) -> list[ExportSetupRequirement]:
diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.py
index 48ac6f56e8..82fd5f6736 100644
--- a/marimo/_runtime/packages/pypi_package_manager.py
+++ b/marimo/_runtime/packages/pypi_package_manager.py
@@ -277,6 +277,14 @@ class UvPackageManager(PypiPackageManager):
docs_url = "https://docs.astral.sh/uv/"
SCRIPT_METADATA_MARKER = "# /// script"
+ _use_project = True
+
+ @classmethod
+ def for_pip_install(cls, python_exe: str) -> UvPackageManager:
+ """Target an interpreter without changing its uv project."""
+ manager = cls(python_exe=python_exe)
+ manager._use_project = False
+ return manager
@cached_property
def _uv_bin(self) -> str:
@@ -346,7 +354,24 @@ class UvPackageManager(PypiPackageManager):
log_callback=log_callback,
)
- # For uv pip install, try with output capture to enable fallback
+ import asyncio
+
+ return await asyncio.to_thread(
+ self._install_with_cache_fallback,
+ package,
+ upgrade=upgrade,
+ group=group,
+ log_callback=log_callback,
+ )
+
+ def _install_with_cache_fallback(
+ self,
+ package: str,
+ *,
+ upgrade: bool,
+ group: str | None,
+ log_callback: LogCallback | None,
+ ) -> bool:
cmd = self.install_command(package, upgrade=upgrade, group=group)
LOGGER.info(f"Running command: {cmd}")
@@ -388,9 +413,10 @@ class UvPackageManager(PypiPackageManager):
"\nRetrying with --no-cache due to cache write permission error...\n"
)
- # Retry with --no-cache flag
- cmd_with_no_cache = cmd + ["--no-cache"]
- return await self.run(cmd_with_no_cache, log_callback=log_callback)
+ return self._run_sync(
+ cmd + ["--no-cache"],
+ log_callback=log_callback,
+ )
return False
@@ -592,6 +618,9 @@ class UvPackageManager(PypiPackageManager):
we are in a temporary virtual environment (e.g. `uvx marimo edit` or `uv --with=marimo run marimo edit`)
or in the currently activated virtual environment (e.g. `uv venv`).
"""
+ if not self._use_project:
+ return False
+
# Check we have a virtual environment
venv_path = os.environ.get("VIRTUAL_ENV", None)
if not venv_path:
diff --git a/marimo/_schemas/export.py b/marimo/_schemas/export.py
index e73aec45b0..faa36e0774 100644
--- a/marimo/_schemas/export.py
+++ b/marimo/_schemas/export.py
@@ -119,5 +119,9 @@ class ExportAvailabilityResponse(msgspec.Struct, rename="camel", frozen=True):
formats: list[ExportFormatAvailability]
+class InstallExportRequirementsRequest(msgspec.Struct, rename="camel"):
+ format: ServerExportFormat
+
+
class UpdateCellOutputsRequest(msgspec.Struct, rename="camel"):
cell_ids_to_output: dict[CellId_t, MimeBundleTuple]
diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.py
index e07e7d3cc4..5bc53faa4d 100644
--- a/marimo/_server/api/endpoints/editing.py
+++ b/marimo/_server/api/endpoints/editing.py
@@ -10,6 +10,7 @@ from marimo._messaging.notification import FocusCellNotification
from marimo._server.api.deps import AppState
from marimo._server.api.utils import (
dispatch_control_request,
+ enforce_consumer_capability,
install_packages_on_server,
notify_server_missing_packages,
parse_request,
@@ -256,8 +257,9 @@ async def install_missing_packages(request: Request) -> BaseResponse:
# Used when the server itself needs a package (e.g. nbformat for
# IPYNB auto-export when running with --sandbox).
app_state = AppState(request)
- app_state.require_current_session()
- await install_packages_on_server(cmd.manager, cmd.versions)
+ enforce_consumer_capability(app_state, cmd)
+ if cmd.versions:
+ await install_packages_on_server(cmd.versions)
return SuccessResponse()
# Default ("kernel"): dispatch to kernel via ZeroMQ control queue.
diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.py
index 70ed514d34..2f7917bb8a 100644
--- a/marimo/_server/api/endpoints/export.py
+++ b/marimo/_server/api/endpoints/export.py
@@ -24,6 +24,7 @@ from marimo._convert.script import UnsupportedAsyncCodeError
from marimo._export.dependencies import (
get_missing_export_packages,
get_missing_export_setup,
+ install_export_setup,
)
from marimo._export.exporter import (
AutoExporter,
@@ -41,6 +42,7 @@ from marimo._export.requests import (
)
from marimo._export.serialization import serialize_notebook_snapshot
from marimo._messaging.msgspec_encoder import asdict
+from marimo._runtime.commands import InstallPackagesCommand
from marimo._schemas.export import (
ExportAsHTMLRequest,
ExportAsIPYNBRequest,
@@ -49,6 +51,7 @@ from marimo._schemas.export import (
ExportAsScriptRequest,
ExportAvailabilityResponse,
ExportFormatAvailability,
+ InstallExportRequirementsRequest,
UpdateCellOutputsRequest,
to_html_export_options,
to_ipynb_export_options,
@@ -59,9 +62,12 @@ from marimo._schemas.export_options import (
SERVER_EXPORT_FORMATS,
IPYNBExportOptions,
MarkdownExportOptions,
+ ServerExportFormat,
)
from marimo._server.api.deps import AppState
from marimo._server.api.utils import (
+ enforce_consumer_capability,
+ install_packages_on_server,
notify_server_missing_packages,
parse_request,
)
@@ -80,6 +86,33 @@ router = APIRouter()
auto_exporter = AutoExporter()
+async def _get_export_format_availability(
+ export_format: ServerExportFormat,
+) -> ExportFormatAvailability:
+ missing_packages = get_missing_export_packages(export_format)
+ missing_setup = (
+ []
+ if missing_packages
+ else await get_missing_export_setup(export_format)
+ )
+ return ExportFormatAvailability(
+ format=export_format,
+ dependencies_available=not missing_packages and not missing_setup,
+ missing_packages=missing_packages,
+ missing_setup=missing_setup,
+ )
+
+
+async def _get_export_availability() -> ExportAvailabilityResponse:
+ return ExportAvailabilityResponse(
+ source="server",
+ formats=[
+ await _get_export_format_availability(export_format)
+ for export_format in SERVER_EXPORT_FORMATS
+ ],
+ )
+
+
@router.get("/availability")
@requires("read")
async def get_export_availability(
@@ -96,24 +129,69 @@ async def get_export_availability(
$ref: "#/components/schemas/ExportAvailabilityResponse"
"""
del request
- formats: list[ExportFormatAvailability] = []
- for export_format in SERVER_EXPORT_FORMATS:
- missing_packages = get_missing_export_packages(export_format)
- missing_setup = (
- []
- if missing_packages
- else await get_missing_export_setup(export_format)
+ return await _get_export_availability()
+
+
[email protected]("/requirements/install")
+@requires("edit")
+async def install_export_requirements(
+ request: Request,
+) -> ExportAvailabilityResponse:
+ """
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ schema:
+ type: string
+ required: true
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/InstallExportRequirementsRequest"
+ responses:
+ 200:
+ description: Updated readiness for server-backed exports
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ExportAvailabilityResponse"
+ """
+ app_state = AppState(request)
+ body = await parse_request(request, cls=InstallExportRequirementsRequest)
+ command = InstallPackagesCommand(
+ manager=app_state.app_config_manager.package_manager,
+ versions={},
+ source="server",
+ )
+ enforce_consumer_capability(app_state, command)
+
+ format_availability = await _get_export_format_availability(body.format)
+ if format_availability.missing_packages:
+ await install_packages_on_server(
+ {package: "" for package in format_availability.missing_packages}
)
- formats.append(
- ExportFormatAvailability(
- format=export_format,
- dependencies_available=not missing_packages
- and not missing_setup,
- missing_packages=missing_packages,
- missing_setup=missing_setup,
- )
+ format_availability = await _get_export_format_availability(
+ body.format
+ )
+
+ # Setup can only be probed after its Python packages are importable.
+ for requirement in format_availability.missing_setup:
+ await install_export_setup(requirement.name)
+
+ availability = await _get_export_availability()
+ target = next(
+ item for item in availability.formats if item.format == body.format
+ )
+ if not target.dependencies_available:
+ raise HTTPException(
+ status_code=HTTPStatus.SERVER_ERROR,
+ detail=(
+ f"Failed to install requirements for "
+ f"{body.format.upper()} export. Check the server logs."
+ ),
)
- return ExportAvailabilityResponse(source="server", formats=formats)
+ return availability
@router.post("/html")
diff --git a/marimo/_server/api/utils.py b/marimo/_server/api/utils.py
index a93999a972..fc639de065 100644
--- a/marimo/_server/api/utils.py
+++ b/marimo/_server/api/utils.py
@@ -260,7 +260,6 @@ T = TypeVar("T")
async def install_packages_on_server(
- manager: str,
versions: dict[str, str],
) -> None:
"""Install packages into the server's own Python environment.
@@ -268,18 +267,34 @@ async def install_packages_on_server(
Used when the server itself needs a package (e.g. nbformat for
IPYNB auto-export when running with --sandbox).
"""
+ import asyncio
import sys
- from marimo._runtime.packages.package_managers import (
- create_package_manager,
+ from marimo._runtime.packages.package_manager import PackageManager
+ from marimo._runtime.packages.pypi_package_manager import (
+ PipPackageManager,
+ UvPackageManager,
)
- pkg_manager = create_package_manager(manager, python_exe=sys.executable)
- if not pkg_manager.is_manager_installed():
- pkg_manager.alert_not_installed()
- return
+ pip = PipPackageManager(python_exe=sys.executable)
+ uv = UvPackageManager.for_pip_install(sys.executable)
+ pkg_manager: PackageManager
+ if await asyncio.to_thread(uv.is_manager_installed):
+ pkg_manager = uv
+ elif await asyncio.to_thread(pip.is_manager_installed):
+ pkg_manager = pip
+ else:
+ raise RuntimeError(
+ "No package installer is available for the server Python."
+ )
+
for pkg, version in versions.items():
- await pkg_manager.install(pkg, version=version or None)
+ installed = await pkg_manager.install(pkg, version=version or None)
+ if not installed:
+ raise RuntimeError(
+ f"Failed to install {pkg} into the server Python. "
+ "Check the server logs."
+ )
def notify_server_missing_packages(
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 1b580e128a..a01cfb0301 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -2559,6 +2559,19 @@ components:
- msg
title: ImportStarError
type: object
+ InstallExportRequirementsRequest:
+ properties:
+ format:
+ enum:
+ - html
+ - ipynb
+ - markdown
+ - pdf
+ - script
+ required:
+ - format
+ title: InstallExportRequirementsRequest
+ type: object
InstallPackagesCommand:
description: "Install Python packages.\n\n Installs missing packages using\
\ the specified package manager. Triggered\n automatically on import errors\
@@ -6764,6 +6777,26 @@ paths:
description: File must be saved before downloading
500:
description: Export failed or dependencies missing
+ /api/export/requirements/install:
+ post:
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/InstallExportRequirementsRequest'
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ExportAvailabilityResponse'
+ description: Updated readiness for server-backed exports
/api/export/script:
post:
parameters:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 377cee3266..1b93049713 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -1124,6 +1124,47 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/export/requirements/install": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post: {
+ parameters: {
+ query?: never;
+ header: {
+ "Marimo-Session-Id": string;
+ };
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["InstallExportRequirementsRequest"];
+ };
+ };
+ responses: {
+ /** @description Updated readiness for server-backed exports */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ExportAvailabilityResponse"];
+ };
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/export/script": {
parameters: {
query?: never;
@@ -5173,6 +5214,11 @@ export interface components {
/** @enum {unknown} */
type: "import-star";
};
+ /** InstallExportRequirementsRequest */
+ InstallExportRequirementsRequest: {
+ /** @enum {unknown} */
+ format: "html" | "ipynb" | "markdown" | "pdf" | "script";
+ };
/**
* InstallPackagesCommand
* @description Install Python packages.
diff --git a/tests/_export/test_export_availability.py b/tests/_export/test_export_availability.py
index 523a58f1d2..359f5f2cdd 100644
--- a/tests/_export/test_export_availability.py
+++ b/tests/_export/test_export_availability.py
@@ -2,9 +2,10 @@
from __future__ import annotations
import asyncio
+import subprocess
import sys
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import ANY, AsyncMock, MagicMock, patch
import pytest
@@ -16,6 +17,7 @@ from marimo._export.dependencies import (
_is_playwright_chromium_installed,
get_missing_export_packages,
get_missing_export_setup,
+ install_export_setup,
require_export_dependencies,
)
from marimo._export.exporter import Exporter
@@ -77,6 +79,52 @@ def test_ipynb_requirement_uses_nbformat() -> None:
assert get_missing_export_packages("ipynb") == ["nbformat"]
+async def test_install_export_setup_uses_server_python() -> None:
+ completed = subprocess.CompletedProcess([], 0, "", "")
+ with patch(
+ "marimo._export.dependencies.subprocess.run",
+ return_value=completed,
+ ) as run:
+ await install_export_setup("playwright-chromium")
+
+ run.assert_called_once_with(
+ [sys.executable, "-m", "playwright", "install", "chromium"],
+ capture_output=True,
+ text=True,
+ timeout=ANY,
+ )
+ assert run.call_args.kwargs["timeout"] > 0
+
+
+async def test_install_export_setup_reports_failure() -> None:
+ completed = subprocess.CompletedProcess([], 1, "", "install failed")
+ with (
+ patch(
+ "marimo._export.dependencies.subprocess.run",
+ return_value=completed,
+ ),
+ pytest.raises(
+ RuntimeError,
+ match="Playwright Chromium installation failed",
+ ),
+ ):
+ await install_export_setup("playwright-chromium")
+
+
+async def test_install_export_setup_reports_timeout() -> None:
+ with (
+ patch(
+ "marimo._export.dependencies.subprocess.run",
+ side_effect=subprocess.TimeoutExpired("playwright", timeout=1),
+ ),
+ pytest.raises(
+ RuntimeError,
+ match="Playwright Chromium installation failed",
+ ),
+ ):
+ await install_export_setup("playwright-chromium")
+
+
@pytest.mark.parametrize(
("chromium_installed", "missing_setup"),
[
diff --git a/tests/_runtime/packages/test_pypi_package_manager.py b/tests/_runtime/packages/test_pypi_package_manager.py
index 62a4cdd739..16ed3ffe2b 100644
--- a/tests/_runtime/packages/test_pypi_package_manager.py
+++ b/tests/_runtime/packages/test_pypi_package_manager.py
@@ -1,9 +1,11 @@
from __future__ import annotations
+import asyncio
import json
import os
import subprocess
import sys
+import threading
from functools import partial
from pathlib import Path
from typing import Any
@@ -355,6 +357,20 @@ def test_uv_is_in_uv_project_true(mock_exists: MagicMock):
assert mgr.is_in_uv_project is True
[email protected](UvPackageManager, "_uv_bin", "uv")
+def test_uv_can_target_python_without_mutating_project() -> None:
+ mgr = UvPackageManager.for_pip_install("/server/python")
+
+ assert mgr.install_command("nbformat", upgrade=False) == [
+ "uv",
+ "pip",
+ "install",
+ "nbformat",
+ "-p",
+ "/server/python",
+ ]
+
+
@patch.dict(
"os.environ",
{"VIRTUAL_ENV": "/path/to/venv", "UV": "/path/to/venv"},
@@ -402,6 +418,32 @@ async def test_uv_install_not_in_project(mock_popen: MagicMock):
assert result is True
[email protected](UvPackageManager, "is_in_uv_project", False)
+async def test_uv_install_does_not_block_event_loop() -> None:
+ process_started = asyncio.Event()
+ release_process = threading.Event()
+ loop = asyncio.get_running_loop()
+
+ def install(*args: Any, **kwargs: Any) -> bool:
+ del args, kwargs
+ loop.call_soon_threadsafe(process_started.set)
+ release_process.wait(timeout=1)
+ return True
+
+ mgr = UvPackageManager()
+ with patch.object(
+ mgr, "_install_with_cache_fallback", side_effect=install
+ ):
+ task = asyncio.create_task(
+ mgr._install("package1", upgrade=False, group=None)
+ )
+ await process_started.wait()
+ assert not task.done()
+
+ release_process.set()
+ assert await task is True
+
+
@patch("marimo._utils.subprocess.subprocess.Popen")
@patch.object(UvPackageManager, "is_in_uv_project", False)
async def test_uv_install_not_in_project_with_target(mock_popen: MagicMock):
diff --git a/tests/_server/api/endpoints/test_editing.py b/tests/_server/api/endpoints/test_editing.py
index 42376c87b6..8657bc6c53 100644
--- a/tests/_server/api/endpoints/test_editing.py
+++ b/tests/_server/api/endpoints/test_editing.py
@@ -1,7 +1,6 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-import sys
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, MagicMock, patch
@@ -124,19 +123,13 @@ def test_install_missing_packages(client: TestClient) -> None:
assert "success" in response.json()
-def _mock_server_install(
- client: TestClient, *, manager_installed: bool = True
-) -> tuple[MagicMock, MagicMock]:
- """POST install_missing_packages with source="server" using a mocked
- package manager. Returns (mock_create, mock_pkg_manager)."""
- mock_pkg_manager = MagicMock()
- mock_pkg_manager.is_manager_installed.return_value = manager_installed
- mock_pkg_manager.install = AsyncMock()
-
+@with_session(SESSION_ID)
+def test_install_missing_packages_server_source(client: TestClient) -> None:
+ install_packages = AsyncMock()
with patch(
- "marimo._runtime.packages.package_managers.create_package_manager",
- return_value=mock_pkg_manager,
- ) as mock_create:
+ "marimo._server.api.endpoints.editing.install_packages_on_server",
+ new=install_packages,
+ ):
response = client.post(
"/api/kernel/install_missing_packages",
headers=HEADERS,
@@ -149,27 +142,7 @@ def _mock_server_install(
assert response.status_code == 200, response.text
assert "success" in response.json()
- return mock_create, mock_pkg_manager
-
-
-@with_session(SESSION_ID)
-def test_install_missing_packages_server_source(client: TestClient) -> None:
- # source="server" routes the install to the server's Python env directly
- # rather than dispatching to the kernel.
- mock_create, mock_pkg_manager = _mock_server_install(client)
- mock_create.assert_called_once_with("pip", python_exe=sys.executable)
- mock_pkg_manager.install.assert_awaited_once_with("nbformat", version=None)
-
-
-@with_session(SESSION_ID)
-def test_install_missing_packages_server_source_manager_not_installed(
- client: TestClient,
-) -> None:
- # When the package manager is not installed, alert_not_installed is called
- # and no packages are installed.
- _, mock_pkg_manager = _mock_server_install(client, manager_installed=False)
- mock_pkg_manager.alert_not_installed.assert_called_once()
- mock_pkg_manager.install.assert_not_awaited()
+ install_packages.assert_awaited_once_with({"nbformat": ""})
@with_session(SESSION_ID)
diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.py
index eec35280d1..4c3bc83a0c 100644
--- a/tests/_server/api/endpoints/test_export.py
+++ b/tests/_server/api/endpoints/test_export.py
@@ -22,10 +22,19 @@ from marimo._export.requests import PDFExportRequest
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.notification import CellNotification
from marimo._output.utils import uri_encode_component
-from marimo._schemas.export_options import PDFExportOptions
+from marimo._schemas.export import (
+ ExportAvailabilityResponse,
+ ExportFormatAvailability,
+ ExportSetupRequirement,
+)
+from marimo._schemas.export_options import (
+ PDFExportOptions,
+ ServerExportFormat,
+)
from marimo._session.model import SessionMode
from marimo._session.notebook.file_manager import AppFileManager
from marimo._types.ids import CellId_t, SessionId
+from marimo._utils.http import HTTPException
from marimo._utils.platform import is_windows
from tests._server.mocks import (
get_session_manager,
@@ -36,6 +45,7 @@ from tests._server.mocks import (
from tests.mocks import EDGE_CASE_FILENAMES, snapshotter
if TYPE_CHECKING:
+ from httpx import Response
from starlette.testclient import TestClient
snapshot = snapshotter(__file__)
@@ -49,6 +59,37 @@ HEADERS = {
CODE = uri_encode_component("import marimo as mo")
+def _format_availability(
+ export_format: ServerExportFormat,
+ *,
+ missing_packages: tuple[str, ...] = (),
+ missing_setup: tuple[ExportSetupRequirement, ...] = (),
+) -> ExportFormatAvailability:
+ return ExportFormatAvailability(
+ format=export_format,
+ dependencies_available=not missing_packages and not missing_setup,
+ missing_packages=list(missing_packages),
+ missing_setup=list(missing_setup),
+ )
+
+
+def _availability(
+ *formats: ExportFormatAvailability,
+) -> ExportAvailabilityResponse:
+ return ExportAvailabilityResponse(source="server", formats=list(formats))
+
+
+def _install_export_requirements(
+ client: TestClient,
+ export_format: ServerExportFormat,
+) -> Response:
+ return client.post(
+ "/api/export/requirements/install",
+ headers=HEADERS,
+ json={"format": export_format},
+ )
+
+
def _ipynb_export_app() -> InternalApp:
app = App()
@@ -246,6 +287,156 @@ def test_export_availability_handles_pdf_setup_probe_failure(
)
+@with_session(SESSION_ID)
+def test_install_export_requirements_resolves_server_requirements(
+ client: TestClient,
+) -> None:
+ setup = ExportSetupRequirement(
+ name="playwright-chromium",
+ command="uv run playwright install chromium",
+ )
+ install_packages = AsyncMock()
+
+ async def assert_packages_installed_first(requirement: str) -> None:
+ assert requirement == "playwright-chromium"
+ install_packages.assert_awaited_once_with({"nbconvert[webpdf]": ""})
+
+ install_setup = AsyncMock(side_effect=assert_packages_installed_first)
+ refreshed = _availability(
+ _format_availability("ipynb"),
+ _format_availability("pdf"),
+ )
+
+ with (
+ patch(
+ "marimo._server.api.endpoints.export._get_export_format_availability",
+ new=AsyncMock(
+ side_effect=[
+ _format_availability(
+ "pdf",
+ missing_packages=("nbconvert[webpdf]",),
+ ),
+ _format_availability(
+ "pdf",
+ missing_setup=(setup,),
+ ),
+ ]
+ ),
+ ),
+ patch(
+ "marimo._server.api.endpoints.export.install_packages_on_server",
+ new=install_packages,
+ ),
+ patch(
+ "marimo._server.api.endpoints.export.install_export_setup",
+ new=install_setup,
+ ),
+ patch(
+ "marimo._server.api.endpoints.export._get_export_availability",
+ new=AsyncMock(return_value=refreshed),
+ ),
+ ):
+ response = _install_export_requirements(client, "pdf")
+
+ assert response.status_code == 200, response.text
+ install_setup.assert_awaited_once_with("playwright-chromium")
+ assert all(
+ item["dependenciesAvailable"] for item in response.json()["formats"]
+ )
+
+
+@with_session(SESSION_ID)
+def test_install_export_requirements_is_idempotent(
+ client: TestClient,
+) -> None:
+ install_packages = AsyncMock()
+ install_setup = AsyncMock()
+ with (
+ patch(
+ "marimo._server.api.endpoints.export._get_export_format_availability",
+ new=AsyncMock(return_value=_format_availability("markdown")),
+ ),
+ patch(
+ "marimo._server.api.endpoints.export.install_packages_on_server",
+ new=install_packages,
+ ),
+ patch(
+ "marimo._server.api.endpoints.export.install_export_setup",
+ new=install_setup,
+ ),
+ patch(
+ "marimo._server.api.endpoints.export._get_export_availability",
+ new=AsyncMock(
+ return_value=_availability(_format_availability("markdown"))
+ ),
+ ),
+ ):
+ response = _install_export_requirements(client, "markdown")
+
+ assert response.status_code == 200, response.text
+ install_packages.assert_not_awaited()
+ install_setup.assert_not_awaited()
+
+
+@with_session(SESSION_ID)
+def test_install_export_requirements_fails_when_unresolved(
+ client: TestClient,
+) -> None:
+ install_packages = AsyncMock()
+ missing = _format_availability("ipynb", missing_packages=("nbformat",))
+ with (
+ patch(
+ "marimo._server.api.endpoints.export._get_export_format_availability",
+ new=AsyncMock(return_value=missing),
+ ),
+ patch(
+ "marimo._server.api.endpoints.export.install_packages_on_server",
+ new=install_packages,
+ ),
+ patch(
+ "marimo._server.api.endpoints.export._get_export_availability",
+ new=AsyncMock(return_value=_availability(missing)),
+ ),
+ ):
+ response = _install_export_requirements(client, "ipynb")
+
+ assert response.status_code == 500
+ assert response.json() == {
+ "detail": (
+ "Failed to install requirements for IPYNB export. "
+ "Check the server logs."
+ )
+ }
+ install_packages.assert_awaited_once_with({"nbformat": ""})
+
+
+@with_session(SESSION_ID)
+def test_install_export_requirements_enforces_consumer_capability(
+ client: TestClient,
+) -> None:
+ install_packages = AsyncMock()
+ install_setup = AsyncMock()
+ with (
+ patch(
+ "marimo._server.api.endpoints.export.enforce_consumer_capability",
+ side_effect=HTTPException(status_code=403, detail="read-only"),
+ ),
+ patch(
+ "marimo._server.api.endpoints.export.install_packages_on_server",
+ new=install_packages,
+ ),
+ patch(
+ "marimo._server.api.endpoints.export.install_export_setup",
+ new=install_setup,
+ ),
+ ):
+ response = _install_export_requirements(client, "pdf")
+
+ assert response.status_code == 403, response.text
+ install_packages.assert_not_awaited()
+ install_setup.assert_not_awaited()
+
+
@with_session(SESSION_ID)
def test_export_html(client: TestClient) -> None:
session = get_session_manager(client).get_session(SESSION_ID)
diff --git a/tests/_server/api/test_api_utils.py b/tests/_server/api/test_api_utils.py
index 5a2f39bb01..57aee7298e 100644
--- a/tests/_server/api/test_api_utils.py
+++ b/tests/_server/api/test_api_utils.py
@@ -1,8 +1,11 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import asyncio
+import threading
from types import SimpleNamespace
from typing import TYPE_CHECKING, cast
+from unittest.mock import AsyncMock, patch
import msgspec
import pytest
@@ -14,6 +17,7 @@ from starlette.testclient import TestClient
from marimo._server.api.utils import (
get_code_mode_credentials,
+ install_packages_on_server,
parse_multipart_request,
)
@@ -79,6 +83,78 @@ def test_parse_multipart_request_raises_on_missing_field() -> None:
client.post("/test", data={"name": "marimo"})
+async def test_install_packages_on_server_uses_uv_when_available() -> None:
+ with (
+ patch(
+ "marimo._runtime.packages.pypi_package_manager.UvPackageManager.is_manager_installed",
+ return_value=True,
+ ),
+ patch(
+ "marimo._runtime.packages.pypi_package_manager.UvPackageManager.install",
+ new=AsyncMock(return_value=True),
+ ) as install,
+ ):
+ await install_packages_on_server({"nbformat": ""})
+
+ install.assert_awaited_once_with("nbformat", version=None)
+
+
+async def test_install_packages_on_server_reports_install_failure() -> None:
+ with (
+ patch(
+ "marimo._runtime.packages.pypi_package_manager.UvPackageManager.is_manager_installed",
+ return_value=False,
+ ),
+ patch(
+ "marimo._runtime.packages.pypi_package_manager.PipPackageManager.is_manager_installed",
+ return_value=True,
+ ),
+ patch(
+ "marimo._runtime.packages.pypi_package_manager.PipPackageManager.install",
+ new=AsyncMock(return_value=False),
+ ),
+ pytest.raises(
+ RuntimeError,
+ match="Failed to install nbformat into the server Python",
+ ),
+ ):
+ await install_packages_on_server({"nbformat": ""})
+
+
+async def test_install_packages_on_server_checks_pip_off_event_loop() -> None:
+ check_started = asyncio.Event()
+ release_check = threading.Event()
+ loop = asyncio.get_running_loop()
+
+ def check_pip() -> bool:
+ loop.call_soon_threadsafe(check_started.set)
+ release_check.wait(timeout=1)
+ return True
+
+ with (
+ patch(
+ "marimo._runtime.packages.pypi_package_manager.UvPackageManager.is_manager_installed",
+ return_value=False,
+ ),
+ patch(
+ "marimo._runtime.packages.pypi_package_manager.PipPackageManager.is_manager_installed",
+ side_effect=check_pip,
+ ),
+ patch(
+ "marimo._runtime.packages.pypi_package_manager.PipPackageManager.install",
+ new=AsyncMock(return_value=True),
+ ),
+ ):
+ install = asyncio.create_task(
+ install_packages_on_server({"nbformat": ""})
+ )
+ await check_started.wait()
+ assert not install.done()
+
+ release_check.set()
+ await install
+
+
def _fake_app_state(
*,
host: str = "localhost",