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.

fix: circular dep in wasm controller (#1369)

Myles Scolnick69830587f343
diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsx
index faead16d64..853fa4f801 100644
--- a/frontend/src/core/MarimoApp.tsx
+++ b/frontend/src/core/MarimoApp.tsx
@@ -19,11 +19,29 @@ import { LargeSpinner } from "@/components/icons/large-spinner";
import { TailwindIndicator } from "@/components/debug/indicator";
import { Provider as SlotzProvider } from "@marimo-team/react-slotz";
import { slotsController } from "./slots/slots";
+import { reactLazyWithPreload } from "@/utils/lazy";
// Lazy imports
-const LazyHomePage = React.lazy(() => import("@/components/pages/home-page"));
-const LazyRunPage = React.lazy(() => import("@/components/pages/run-page"));
-const LazyEditPage = React.lazy(() => import("@/components/pages/edit-page"));
+const LazyHomePage = reactLazyWithPreload(
+ () => import("@/components/pages/home-page"),
+);
+const LazyRunPage = reactLazyWithPreload(
+ () => import("@/components/pages/run-page"),
+);
+const LazyEditPage = reactLazyWithPreload(
+ () => import("@/components/pages/edit-page"),
+);
+
+function preload(mode: string) {
+ if (mode === "home") {
+ LazyHomePage.preload();
+ } else if (mode === "read") {
+ LazyRunPage.preload();
+ } else {
+ LazyEditPage.preload();
+ }
+}
+preload(initialMode);
/**
* The root component of the Marimo app.
@@ -35,11 +53,13 @@ export const MarimoApp: React.FC = memo(() => {
const renderBody = () => {
if (initialMode === "home") {
- return <LazyHomePage />;
+ return <LazyHomePage.Component />;
} else if (initialMode === "read") {
- return <LazyRunPage appConfig={appConfig} />;
+ return <LazyRunPage.Component appConfig={appConfig} />;
} else {
- return <LazyEditPage userConfig={userConfig} appConfig={appConfig} />;
+ return (
+ <LazyEditPage.Component userConfig={userConfig} appConfig={appConfig} />
+ );
}
};
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 3b07f6d660..61477c3b08 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -1,7 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { useCallback, useEffect, useState } from "react";
-import { sendInterrupt, sendRename, sendSave } from "@/core/network/requests";
+import {
+ sendComponentValues,
+ sendInterrupt,
+ sendRename,
+ sendSave,
+} from "@/core/network/requests";
import { Controls } from "@/components/editor/controls/Controls";
import { FilenameInput } from "@/components/editor/header/filename-input";
@@ -78,7 +83,7 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
// Initialize RuntimeState event-listeners
useEffect(() => {
- RuntimeState.INSTANCE.start();
+ RuntimeState.INSTANCE.start(sendComponentValues);
return () => {
RuntimeState.INSTANCE.stop();
};
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index 112d66a3c4..dda88f7d08 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -28,6 +28,7 @@ import { Functions } from "@/utils/functions";
import { defineCustomElement } from "../dom/defineCustomElement";
import { MarimoIslandElement } from "./components/web-components";
import { RuntimeState } from "../kernel/RuntimeState";
+import { sendComponentValues } from "../network/requests";
/**
* Main entry point for the js bundle for embedded marimo apps.
@@ -121,7 +122,7 @@ export async function initialize() {
});
// Start the runtime
- RuntimeState.INSTANCE.start();
+ RuntimeState.INSTANCE.start(sendComponentValues);
}
initialize();
diff --git a/frontend/src/core/kernel/RuntimeState.ts b/frontend/src/core/kernel/RuntimeState.ts
index 085988d190..66a1ff106b 100644
--- a/frontend/src/core/kernel/RuntimeState.ts
+++ b/frontend/src/core/kernel/RuntimeState.ts
@@ -1,5 +1,4 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { sendComponentValues } from "@/core/network/requests";
import {
marimoValueReadyEvent,
MarimoValueReadyEventType,
@@ -16,9 +15,7 @@ export class RuntimeState {
/**
* Shared instance of RuntimeState since this must be a singleton.
*/
- static readonly INSTANCE = new RuntimeState(UI_ELEMENT_REGISTRY, {
- sendComponentValues,
- });
+ static readonly INSTANCE = new RuntimeState(UI_ELEMENT_REGISTRY);
// TODO(akshayka): move the running-count state machine to the Python kernel;
// keeping track of it in the frontend is very brittle. the kernel can simply
@@ -32,22 +29,26 @@ export class RuntimeState {
* ObjectIds of UIElements whose values need to be updated in the kernel
*/
private componentsToUpdate: Set<string>;
+ private _sendComponentValues: RunRequests["sendComponentValues"] | undefined;
- constructor(
- private uiElementRegistry: UIElementRegistry,
- private opts: {
- sendComponentValues: RunRequests["sendComponentValues"];
- },
- ) {
+ constructor(private uiElementRegistry: UIElementRegistry) {
this.runningCount = 0;
this.componentsToUpdate = new Set();
repl(RuntimeState.INSTANCE, "RuntimeState");
}
+ private get sendComponentValues(): RunRequests["sendComponentValues"] {
+ if (!this._sendComponentValues) {
+ throw new Error("sendComponentValues is not set");
+ }
+ return this._sendComponentValues;
+ }
+
/**
* Start listening for events from UIElements
*/
- start() {
+ start(sendComponentValues: RunRequests["sendComponentValues"]) {
+ this._sendComponentValues = sendComponentValues;
document.addEventListener(marimoValueReadyEvent, this.handleReadyEvent);
}
@@ -80,24 +81,22 @@ export class RuntimeState {
// Store the components to update, in case the run fails to be sent
const previousComponentsToUpdate = new Set(this.componentsToUpdate);
- this.opts
- .sendComponentValues(
- Array.from(this.componentsToUpdate.values(), (objectId) => ({
- objectId: objectId,
- value: this.uiElementRegistry.lookupValue(objectId),
- })).filter((update) => update.value !== undefined),
- )
- .catch(() => {
- // This happens if the run was failed to register (401, 403, network error, etc.)
- // If the run fails, restore the components to update and finish the run
- // A run may fail if the kernel is restarted or the notebook is closed,
- // but if we don't restore registerRunEnd() will never be able to flush updates.
- this.registerRunEnd();
- // Merge the previous components to update with the current ones
- previousComponentsToUpdate.forEach((objectId) =>
- this.componentsToUpdate.add(objectId),
- );
- });
+ this.sendComponentValues(
+ Array.from(this.componentsToUpdate.values(), (objectId) => ({
+ objectId: objectId,
+ value: this.uiElementRegistry.lookupValue(objectId),
+ })).filter((update) => update.value !== undefined),
+ ).catch(() => {
+ // This happens if the run was failed to register (401, 403, network error, etc.)
+ // If the run fails, restore the components to update and finish the run
+ // A run may fail if the kernel is restarted or the notebook is closed,
+ // but if we don't restore registerRunEnd() will never be able to flush updates.
+ this.registerRunEnd();
+ // Merge the previous components to update with the current ones
+ previousComponentsToUpdate.forEach((objectId) =>
+ this.componentsToUpdate.add(objectId),
+ );
+ });
this.componentsToUpdate.clear();
}
}
diff --git a/frontend/src/core/kernel/__tests__/RuntimeState.test.ts b/frontend/src/core/kernel/__tests__/RuntimeState.test.ts
index 05a461970d..de6ed6bedf 100644
--- a/frontend/src/core/kernel/__tests__/RuntimeState.test.ts
+++ b/frontend/src/core/kernel/__tests__/RuntimeState.test.ts
@@ -27,13 +27,11 @@ describe("RuntimeState", () => {
uiElementRegistry = UIElementRegistry.INSTANCE;
uiElementRegistry.entries.clear();
- runtimeState = new RuntimeState(uiElementRegistry, {
- sendComponentValues: mockSendComponentValues,
- });
+ runtimeState = new RuntimeState(uiElementRegistry);
});
test("start should register event listener", () => {
- runtimeState.start();
+ runtimeState.start(mockSendComponentValues);
expect(addEventListenerSpy).toHaveBeenCalledWith(
marimoValueReadyEvent,
expect.any(Function),
@@ -68,7 +66,7 @@ describe("RuntimeState", () => {
});
test("flushUpdates should call sendComponentValues with updates", async () => {
- runtimeState.start();
+ runtimeState.start(mockSendComponentValues);
uiElementRegistry.registerInstance(uiElementOneId, elementOne);
expect(uiElementRegistry.entries).toHaveLength(1);
expect(mockSendComponentValues).not.toHaveBeenCalled();
@@ -87,7 +85,7 @@ describe("RuntimeState", () => {
});
test("will only send one broadcast at a time and hold future events", () => {
- runtimeState.start();
+ runtimeState.start(mockSendComponentValues);
uiElementRegistry.registerInstance(uiElementOneId, elementOne);
uiElementRegistry.registerInstance(uiElementTwoId, elementTwo);
uiElementRegistry.broadcastValueUpdate(elementOne, uiElementOneId, "10");
@@ -130,7 +128,7 @@ describe("RuntimeState", () => {
});
test("handle when sendComponentValues fails", async () => {
- runtimeState.start();
+ runtimeState.start(mockSendComponentValues);
uiElementRegistry.registerInstance(uiElementOneId, elementOne);
uiElementRegistry.registerInstance(uiElementTwoId, elementTwo);
expect(uiElementRegistry.entries).toHaveLength(2);
diff --git a/frontend/src/core/run-app.tsx b/frontend/src/core/run-app.tsx
index e973771bea..96df71efcd 100644
--- a/frontend/src/core/run-app.tsx
+++ b/frontend/src/core/run-app.tsx
@@ -11,6 +11,7 @@ import { AppContainer } from "@/components/editor/app-container";
import { AppHeader } from "@/components/editor/header/app-header";
import { getSessionId } from "./kernel/session";
import { useMarimoWebSocket } from "./websocket/useMarimoWebSocket";
+import { sendComponentValues } from "./network/requests";
interface AppProps {
appConfig: AppConfig;
@@ -21,7 +22,7 @@ export const RunApp: React.FC<AppProps> = ({ appConfig }) => {
// Initialize RuntimeState event-listeners
useEffect(() => {
- RuntimeState.INSTANCE.start();
+ RuntimeState.INSTANCE.start(sendComponentValues);
return () => {
RuntimeState.INSTANCE.stop();
};
diff --git a/frontend/src/utils/lazy.ts b/frontend/src/utils/lazy.ts
new file mode 100644
index 0000000000..8ea474aced
--- /dev/null
+++ b/frontend/src/utils/lazy.ts
@@ -0,0 +1,39 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import React from "react";
+
+interface LazyComponentWithPreload<T> {
+ preload: () => void;
+ Component: React.LazyExoticComponent<React.ComponentType<T>>;
+}
+
+export const reactLazyWithPreload = <T>(
+ factory: () => Promise<{ default: React.ComponentType<T> }>,
+): LazyComponentWithPreload<T> => {
+ let component: React.ComponentType<T> | null = null;
+ const init = factory().then((module) => {
+ component = module.default;
+ });
+
+ const preload = () => {
+ init.then(() => {
+ if (!component) {
+ throw new Error("Component is not loaded");
+ }
+ });
+ };
+
+ const LazyComponent = React.lazy(() => {
+ return init.then(() => {
+ if (!component) {
+ throw new Error("Component is not loaded");
+ }
+ return { default: component };
+ });
+ });
+
+ return {
+ preload,
+ Component: LazyComponent,
+ };
+};