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.

improvement: better loading indicator while pyodide is bootstrapping (#2330)

Myles Scolnick48d640c6e448
diff --git a/frontend/src/components/icons/large-spinner.tsx b/frontend/src/components/icons/large-spinner.tsx
index 217ce82e1a..09d28a3d70 100644
--- a/frontend/src/components/icons/large-spinner.tsx
+++ b/frontend/src/components/icons/large-spinner.tsx
@@ -1,15 +1,36 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { cn } from "@/utils/cn";
import { Loader2Icon } from "lucide-react";
+import { useState, useEffect } from "react";
+
+export const LargeSpinner = ({ title }: { title?: string }) => {
+ const [currentTitle, setCurrentTitle] = useState(title);
+ const [isVisible, setIsVisible] = useState(true);
+
+ useEffect(() => {
+ if (title !== currentTitle) {
+ setIsVisible(false);
+ const timer = setTimeout(() => {
+ setCurrentTitle(title);
+ setIsVisible(true);
+ }, 300); // Wait for fade out animation to complete
+ return () => clearTimeout(timer);
+ }
+ }, [title, currentTitle]);
-export const LargeSpinner = () => {
return (
<div className="flex flex-col h-full flex-1 items-center justify-center p-4">
<Loader2Icon
className="size-20 animate-spin text-primary"
strokeWidth={1}
/>
- <div className="mt-2 text-muted-foreground font-semibold text-lg">
- Initializing...
+ <div
+ className={cn(
+ "mt-2 text-muted-foreground font-semibold text-lg transition-opacity duration-300",
+ isVisible ? "opacity-100" : "opacity-0",
+ )}
+ >
+ {currentTitle}
</div>
</div>
);
diff --git a/frontend/src/core/wasm/PyodideLoader.tsx b/frontend/src/core/wasm/PyodideLoader.tsx
index a2f0031c7c..87f549571d 100644
--- a/frontend/src/core/wasm/PyodideLoader.tsx
+++ b/frontend/src/core/wasm/PyodideLoader.tsx
@@ -5,6 +5,11 @@ import { useAsyncData } from "@/hooks/useAsyncData";
import { isWasm } from "./utils";
import { PyodideBridge } from "./bridge";
import { LargeSpinner } from "@/components/icons/large-spinner";
+import { useAtomValue } from "jotai";
+import { hasAnyOutputAtom, wasmInitializationAtom } from "./state";
+import { initialMode } from "../mode";
+import { hasQueryParam } from "@/utils/urls";
+import { KnownQueryParams } from "../constants";
/**
* HOC to load Pyodide before rendering children, if necessary.
@@ -21,8 +26,24 @@ export const PyodideLoader: React.FC<PropsWithChildren> = ({ children }) => {
return true;
}, []);
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ const hasOutput = useAtomValue(hasAnyOutputAtom);
+
if (loading) {
- return <LargeSpinner />;
+ return <WasmSpinner />;
+ }
+
+ // If we:
+ // - are in read mode
+ // - we are not showing the code
+ // - and there is no output
+ // then show the spinner
+ if (
+ !hasOutput &&
+ initialMode === "read" &&
+ hasQueryParam(KnownQueryParams.showCode, "false")
+ ) {
+ return <WasmSpinner />;
}
// Propagate back up to our error boundary
@@ -32,3 +53,9 @@ export const PyodideLoader: React.FC<PropsWithChildren> = ({ children }) => {
return children;
};
+
+export const WasmSpinner: React.FC<PropsWithChildren> = ({ children }) => {
+ const wasmInitialization = useAtomValue(wasmInitializationAtom);
+
+ return <LargeSpinner title={wasmInitialization} />;
+};
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 8916db189d..176e9bb298 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -33,7 +33,12 @@ import { toast } from "@/components/ui/use-toast";
import { generateUUID } from "@/utils/uuid";
import { store } from "../state/jotai";
import { notebookIsRunningAtom } from "../cells/cells";
-import { getInitialAppMode } from "../mode";
+import { getInitialAppMode, initialMode } from "../mode";
+import { wasmInitializationAtom } from "./state";
+
+type SaveWorker = ReturnType<
+ typeof getWorkerRPC<SaveWorkerSchema>
+>["proxy"]["request"];
export class PyodideBridge implements RunRequests, EditRequests {
static get INSTANCE(): PyodideBridge {
@@ -45,21 +50,26 @@ export class PyodideBridge implements RunRequests, EditRequests {
}
private rpc!: ReturnType<typeof getWorkerRPC<WorkerSchema>>;
- private saveRpc!: ReturnType<typeof getWorkerRPC<SaveWorkerSchema>>;
+ private saveRpc!: SaveWorker;
private interruptBuffer?: Uint8Array;
private messageConsumer: ((message: string) => void) | undefined;
public initialized = new Deferred<void>();
- private constructor() {
- if (!isWasm()) {
- return;
+ private getSaveWorker(): SaveWorker {
+ if (initialMode === "read") {
+ Logger.debug("Skipping SaveWorker in read-mode");
+ return {
+ readFile: throwNotImplemented,
+ readNotebook: throwNotImplemented,
+ saveNotebook: throwNotImplemented,
+ };
}
- // Create a worker
- const worker = new Worker(
+ // Create save worker
+ const saveWorker = new Worker(
// eslint-disable-next-line unicorn/relative-url-style
- new URL("./worker/worker.ts", import.meta.url),
+ new URL("./worker/save-worker.ts", import.meta.url),
{
type: "module",
// Pass the version to the worker
@@ -68,13 +78,21 @@ export class PyodideBridge implements RunRequests, EditRequests {
},
);
- // Create save worker
- const saveWorker = new Worker(
+ return getWorkerRPC<SaveWorkerSchema>(saveWorker).proxy.request;
+ }
+
+ private constructor() {
+ if (!isWasm()) {
+ return;
+ }
+
+ // Create a worker
+ const worker = new Worker(
// eslint-disable-next-line unicorn/relative-url-style
- new URL("./worker/save-worker.ts", import.meta.url),
+ new URL("./worker/worker.ts", import.meta.url),
{
type: "module",
- // Pass the version
+ // Pass the version to the worker
/* @vite-ignore */
name: getMarimoVersion(),
},
@@ -82,7 +100,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
// Create the RPC
this.rpc = getWorkerRPC<WorkerSchema>(worker);
- this.saveRpc = getWorkerRPC<SaveWorkerSchema>(saveWorker);
+ this.saveRpc = this.getSaveWorker();
// Listeners
this.rpc.addMessageListener("ready", () => {
@@ -92,6 +110,9 @@ export class PyodideBridge implements RunRequests, EditRequests {
this.setInterruptBuffer();
this.initialized.resolve();
});
+ this.rpc.addMessageListener("initializingMessage", ({ message }) => {
+ store.set(wasmInitializationAtom, message);
+ });
this.rpc.addMessageListener("initializedError", ({ error }) => {
// If already resolved, show a toast
if (this.initialized.status === "resolved") {
@@ -178,7 +199,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
sendSave: EditRequests["sendSave"] = async (request) => {
- await this.saveRpc.proxy.request.saveNotebook(request);
+ await this.saveRpc.saveNotebook(request);
const code = await this.readCode();
if (code.contents) {
notebookFileStore.saveFile(code.contents);
@@ -294,7 +315,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
readCode: EditRequests["readCode"] = async () => {
- const contents = await this.saveRpc.proxy.request.readNotebook();
+ const contents = await this.saveRpc.readNotebook();
return { contents };
};
diff --git a/frontend/src/core/wasm/state.ts b/frontend/src/core/wasm/state.ts
new file mode 100644
index 0000000000..4ebfba1bdc
--- /dev/null
+++ b/frontend/src/core/wasm/state.ts
@@ -0,0 +1,12 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { atom } from "jotai";
+import { notebookAtom } from "../cells/cells";
+
+export const wasmInitializationAtom = atom<string>("Initializing...");
+
+export const hasAnyOutputAtom = atom<boolean>((get) => {
+ const notebook = get(notebookAtom);
+ return Object.values(notebook.cellRuntime).some((runtime) =>
+ Boolean(runtime.output),
+ );
+});
diff --git a/frontend/src/core/wasm/worker/bootstrap.ts b/frontend/src/core/wasm/worker/bootstrap.ts
index 1a9e088817..a551bbe6c0 100644
--- a/frontend/src/core/wasm/worker/bootstrap.ts
+++ b/frontend/src/core/wasm/worker/bootstrap.ts
@@ -15,6 +15,16 @@ declare let loadPyodide: (opts: {
indexURL: string;
}) => Promise<PyodideInterface>;
+// This class initializes the wasm environment
+// We would like this initialization to be parallelizable
+// however, there is some waterfall in the initialization process
+// 1. Load Pyodide
+// 2. Install marimo and it's required dependencies
+// 3. Install the dependencies from the notebook
+// 3.a Install from pyodide supported wheels
+// 3.b Install from micropip
+// 4. Initialize the notebook
+
export class DefaultWasmController implements WasmController {
protected pyodide: PyodideInterface | null = null;
@@ -27,7 +37,7 @@ export class DefaultWasmController implements WasmController {
version: string;
pyodideVersion: string;
}): Promise<PyodideInterface> {
- const pyodide = await this.loadPyoideAndPackages(opts.pyodideVersion);
+ const pyodide = await this.loadPyodideAndPackages(opts.pyodideVersion);
const { version } = opts;
@@ -42,7 +52,7 @@ export class DefaultWasmController implements WasmController {
return pyodide;
}
- private async loadPyoideAndPackages(
+ private async loadPyodideAndPackages(
pyodideVersion: string,
): Promise<PyodideInterface> {
if (!loadPyodide) {
@@ -148,7 +158,8 @@ export class DefaultWasmController implements WasmController {
self.user_config = userConfig;
const span = t.startSpan("startSession.runPython");
- const [bridge, init] = this.requirePyodide.runPython(
+ const nbFilename = filename || WasmFileSystem.NOTEBOOK_FILENAME;
+ const [bridge, init, imports] = this.requirePyodide.runPython(
`
print("[py] Starting marimo...")
import asyncio
@@ -159,7 +170,7 @@ export class DefaultWasmController implements WasmController {
assert js.query_params, "query_params is not defined"
session, bridge = create_session(
- filename="${filename || WasmFileSystem.NOTEBOOK_FILENAME}",
+ filename="${nbFilename}",
query_params=js.query_params.to_py(),
message_callback=js.messenger.callback,
user_config=js.user_config.to_py(),
@@ -170,30 +181,66 @@ export class DefaultWasmController implements WasmController {
instantiate(session)
asyncio.create_task(session.start())
- bridge, init`,
+ # Load the imports
+ import pyodide.code
+ with open("${nbFilename}", "r") as f:
+ imports = pyodide.code.find_imports(f.read())
+
+ bridge, init, imports`,
);
span.end();
+ const moduleImports = new Set<string>(imports.toJs());
+
// Fire and forgot load packages and instantiation
// We don't want to wait for this to finish,
// as it blocks the initial code from being shown.
- let codeForPackages = code;
- if (codeForPackages.includes("mo.sql")) {
- // Add pandas and duckdb to the codeForPackages
- codeForPackages = `import pandas\n${codeForPackages}`;
- codeForPackages = `import duckdb\n${codeForPackages}`;
- }
- const loadSpan = t.startSpan("loadPackagesFromImports");
- void this.requirePyodide
- .loadPackagesFromImports(codeForPackages, {
- messageCallback: Logger.log,
- errorCallback: Logger.error,
- })
- .then(() => {
- loadSpan.end();
- init(userConfig.runtime.auto_instantiate);
- });
+ void this.loadNotebookDeps(code, moduleImports).then(() => {
+ return init(userConfig.runtime.auto_instantiate);
+ });
return bridge;
}
+
+ private async loadNotebookDeps(code: string, foundImports: Set<string>) {
+ const pyodide = this.requirePyodide;
+
+ if (code.includes("mo.sql")) {
+ // We need pandas and duckdb for mo.sql
+ code = `import pandas\n${code}`;
+ code = `import duckdb\n${code}`;
+ }
+
+ const imports = [...foundImports];
+
+ // Load from pyodide
+ let loadSpan = t.startSpan("pyodide.loadPackage");
+ await pyodide.loadPackagesFromImports(code, {
+ errorCallback: Logger.error,
+ messageCallback: Logger.log,
+ });
+ loadSpan.end();
+
+ // Load from micropip
+ loadSpan = t.startSpan("micropip.install");
+ const missingPackages = imports.filter(
+ (pkg) => !pyodide.loadedPackages[pkg],
+ );
+ if (missingPackages.length > 0) {
+ await pyodide
+ .runPythonAsync(`
+ import micropip
+ import sys
+ # Filter out builtins
+ missing = [p for p in ${JSON.stringify(missingPackages)} if p not in sys.modules]
+ print("[py] Loading packages from micropip:", missing)
+ await micropip.install(missing)
+ `)
+ .catch((error) => {
+ // Don't let micropip loading failures stop the notebook from loading
+ Logger.error("Failed to load packages from micropip", error);
+ });
+ }
+ loadSpan.end();
+ }
}
diff --git a/frontend/src/core/wasm/worker/worker.ts b/frontend/src/core/wasm/worker/worker.ts
index 1d9938b5f9..f9040a61f5 100644
--- a/frontend/src/core/wasm/worker/worker.ts
+++ b/frontend/src/core/wasm/worker/worker.ts
@@ -43,6 +43,9 @@ async function loadPyodideAndPackages() {
await t.wrapAsync(importPyodide)(marimoVersion);
const controller = await t.wrapAsync(getController)(marimoVersion);
self.controller = controller;
+ rpc.send.initializingMessage({
+ message: "Loading marimo's dependencies...",
+ });
self.pyodide = await t.wrapAsync(controller.bootstrap.bind(controller))({
version: marimoVersion,
pyodideVersion: pyodideVersion,
@@ -55,7 +58,6 @@ async function loadPyodideAndPackages() {
}
}
-const pyodideReadyPromise = t.wrapAsync(loadPyodideAndPackages)();
const messageBuffer = new MessageBuffer(
(message: JsonString<OperationMessage>) => {
rpc.send.kernelMessage({ message });
@@ -93,8 +95,14 @@ const requestHandler = createRPCRequestHandler({
self.controller.startSession.bind(self.controller),
);
const initializeOnce = once(() => {
+ rpc.send.initializingMessage({
+ message: "Initializing notebook...",
+ });
rpc.send.initialized({});
});
+ rpc.send.initializingMessage({
+ message: "Loading notebook and dependencies...",
+ });
const bridge = await startSession({
code: opts.code,
filename: opts.filename,
@@ -237,6 +245,8 @@ export type WorkerSchema = RPCSchema<
kernelMessage: { message: JsonString<OperationMessage> };
// Emitted when the Pyodide is initialized
initialized: {};
+ // Emitted when the Pyodide is initializing, with new messages
+ initializingMessage: { message: string };
// Emitted when the Pyodide fails to initialize
initializedError: { error: string };
};
@@ -273,3 +283,5 @@ const namesThatRequireSync = new Set<keyof RawBridge>([
function getMarimoVersion() {
return self.name; // We store the version in the worker name
}
+
+const pyodideReadyPromise = t.wrapAsync(loadPyodideAndPackages)();
diff --git a/frontend/src/utils/urls.ts b/frontend/src/utils/urls.ts
index d0f29a6b0d..78a0ab237e 100644
--- a/frontend/src/utils/urls.ts
+++ b/frontend/src/utils/urls.ts
@@ -4,3 +4,16 @@ export function updateQueryParams(updater: (params: URLSearchParams) => void) {
updater(url.searchParams);
window.history.replaceState({}, "", url.toString());
}
+
+export function hasQueryParam(key: string, value?: string): boolean {
+ if (typeof window === "undefined") {
+ return false;
+ }
+ const urlParams = new URLSearchParams(window.location.search);
+
+ if (value === undefined) {
+ return urlParams.has(key);
+ }
+
+ return urlParams.get(key) === value;
+}