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: lazy backend (#7523)

Myles Scolnick694b9312c971
diff --git a/frontend/src/components/editor/alerts/connecting-alert.tsx b/frontend/src/components/editor/alerts/connecting-alert.tsx
index 131234e2a1..4934a9da39 100644
--- a/frontend/src/components/editor/alerts/connecting-alert.tsx
+++ b/frontend/src/components/editor/alerts/connecting-alert.tsx
@@ -3,8 +3,14 @@
import { useAtomValue } from "jotai";
import { LoadingEllipsis } from "@/components/icons/loading-ellipsis";
import { Spinner } from "@/components/icons/spinner";
+import { Button } from "@/components/ui/button";
import { DelayMount } from "@/components/utils/delay-mount";
-import { isClosedAtom, isConnectingAtom } from "@/core/network/connection";
+import {
+ isClosedAtom,
+ isConnectingAtom,
+ isNotStartedAtom,
+} from "@/core/network/connection";
+import { useConnectToRuntime } from "@/core/runtime/config";
import { Tooltip } from "../../ui/tooltip";
import { FloatingAlert } from "./floating-alert";
@@ -15,8 +21,8 @@ export const ConnectingAlert: React.FC = () => {
const isConnecting = useAtomValue(isConnectingAtom);
const isClosed = useAtomValue(isClosedAtom);
- return (
- (isConnecting && (
+ if (isConnecting) {
+ return (
<>
<DelayMount milliseconds={SHORT_DELAY_MS}>
<div className="absolute top-4 m-0 flex items-center min-h-[28px] left-1/2 transform -translate-x-1/2 z-200 ">
@@ -34,13 +40,36 @@ export const ConnectingAlert: React.FC = () => {
</div>
</FloatingAlert>
</>
- )) ||
- (isClosed && (
+ );
+ }
+
+ if (isClosed) {
+ return (
<FloatingAlert show={isClosed} kind="danger">
<div className="flex items-center gap-2">
<p>Failed to connect.</p>
</div>
</FloatingAlert>
- ))
- );
+ );
+ }
+};
+
+export const NotStartedConnectionAlert: React.FC = () => {
+ const isNotStarted = useAtomValue(isNotStartedAtom);
+ const connectToRuntime = useConnectToRuntime();
+
+ if (isNotStarted) {
+ return (
+ <FloatingAlert show={isNotStarted} kind="info">
+ <div className="flex items-center gap-2">
+ <p>Not connected to a runtime.</p>
+ <Button variant="link" onClick={connectToRuntime}>
+ Click to connect
+ </Button>
+ </div>
+ </FloatingAlert>
+ );
+ }
+
+ return null;
};
diff --git a/frontend/src/components/editor/app-container.tsx b/frontend/src/components/editor/app-container.tsx
index 155a450a5a..362a096240 100644
--- a/frontend/src/components/editor/app-container.tsx
+++ b/frontend/src/components/editor/app-container.tsx
@@ -4,7 +4,8 @@ import type React from "react";
import type { PropsWithChildren } from "react";
import type { AppConfig } from "@/core/config/config-schema";
import { PyodideLoader } from "@/core/wasm/PyodideLoader";
-import { type ConnectionStatus, WebSocketState } from "@/core/websocket/types";
+import { isAppClosed } from "@/core/websocket/connection-utils";
+import type { ConnectionStatus } from "@/core/websocket/types";
import { cn } from "@/utils/cn";
import { DynamicFavicon } from "./dynamic-favicon";
import { StatusOverlay } from "./header/status";
@@ -30,13 +31,14 @@ export const AppContainer: React.FC<PropsWithChildren<Props>> = ({
<StatusOverlay connection={connection} isRunning={isRunning} />
<PyodideLoader>
<WrappedWithSidebar>
+ {/** biome-ignore lint/correctness/useUniqueElementIds: ID is used by other components to grab the DOM element */}
<div
id="App"
data-config-width={width}
data-connection-state={connectionState}
className={cn(
"mathjax_ignore",
- connectionState === WebSocketState.CLOSED && "disconnected",
+ isAppClosed(connectionState) && "disconnected",
"bg-background w-full h-full text-textColor",
"flex flex-col overflow-y-auto",
width === "full" && "config-width-full",
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index cdac32dc60..3511937db7 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -31,7 +31,7 @@ import { connectionAtom } from "@/core/network/connection";
import { useRequestClient } from "@/core/network/requests";
import { isRtcEnabled } from "@/core/rtc/state";
import { useSaveNotebook } from "@/core/saving/save-component";
-import { WebSocketState } from "@/core/websocket/types";
+import { isAppConnecting } from "@/core/websocket/connection-utils";
import type { Theme } from "@/theme/useTheme";
import { cn } from "@/utils/cn";
import { invariant } from "@/utils/invariant";
@@ -525,10 +525,7 @@ function WithWaitUntilConnected<T extends {}>(
const connection = useAtomValue(connectionAtom);
const [rtcDoc, setRtcDoc] = useAtom(connectedDocAtom);
- if (
- connection.state === WebSocketState.CONNECTING ||
- rtcDoc === undefined
- ) {
+ if (isAppConnecting(connection.state) || rtcDoc === undefined) {
return (
<div className="flex h-full w-full items-baseline p-4">
<DelayMount milliseconds={1000} fallback={null}>
diff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx
index dd3486fae2..f724367792 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx
@@ -1,16 +1,21 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { atom, useAtomValue } from "jotai";
+import { atom, useAtomValue, useSetAtom } from "jotai";
import { startCase } from "lodash-es";
import { AlertCircleIcon, CheckCircle2Icon, PowerOffIcon } from "lucide-react";
import type React from "react";
import { Spinner } from "@/components/icons/spinner";
import { Tooltip } from "@/components/ui/tooltip";
import { connectionAtom } from "@/core/network/connection";
-import { useRuntimeManager } from "@/core/runtime/config";
+import { useConnectToRuntime, useRuntimeManager } from "@/core/runtime/config";
import { store } from "@/core/state/jotai";
import { isWasm } from "@/core/wasm/utils";
-import { WebSocketState } from "@/core/websocket/types";
+import {
+ isAppClosing,
+ isAppConnected,
+ isAppConnecting,
+ isAppNotStarted,
+} from "@/core/websocket/connection-utils";
import { useAsyncData } from "@/hooks/useAsyncData";
import { useInterval } from "@/hooks/useInterval";
@@ -31,15 +36,19 @@ export function getConnectionStatus(): ConnectionStatus {
export const BackendConnectionStatus: React.FC = () => {
const connection = useAtomValue(connectionAtom).state;
const runtime = useRuntimeManager();
+ const connectToRuntime = useConnectToRuntime();
+ const setConnectionStatus = useSetAtom(connectionStatusAtom);
const { isFetching, error, data, refetch } = useAsyncData(async () => {
- if (connection !== WebSocketState.OPEN) {
- store.set(connectionStatusAtom, "disconnected");
+ // If the connection is not connected, return
+ if (!isAppConnected(connection)) {
+ setConnectionStatus("disconnected");
return;
}
+ // Skip wasm since there is no health check for wasm
if (isWasm()) {
- store.set(connectionStatusAtom, "healthy");
+ setConnectionStatus("healthy");
return {
isHealthy: true,
lastChecked: new Date(),
@@ -49,14 +58,14 @@ export const BackendConnectionStatus: React.FC = () => {
try {
const isHealthy = await runtime.isHealthy();
- store.set(connectionStatusAtom, isHealthy ? "healthy" : "unhealthy");
+ setConnectionStatus(isHealthy ? "healthy" : "unhealthy");
return {
isHealthy,
lastChecked: new Date(),
error: undefined,
};
} catch (error) {
- store.set(connectionStatusAtom, "unhealthy");
+ setConnectionStatus("unhealthy");
return {
isHealthy: false,
lastChecked: new Date(),
@@ -66,12 +75,15 @@ export const BackendConnectionStatus: React.FC = () => {
}, [runtime, connection]);
useInterval(refetch, {
- delayMs:
- connection === WebSocketState.OPEN ? CHECK_HEALTH_INTERVAL_MS : null,
+ delayMs: isAppConnected(connection) ? CHECK_HEALTH_INTERVAL_MS : null,
whenVisible: true,
});
const getStatusInfo = () => {
+ if (isAppNotStarted(connection)) {
+ return "Not connected to a runtime";
+ }
+
const baseStatus = startCase(connection.toLowerCase());
const healthInfo = data?.lastChecked
? data.isHealthy
@@ -85,15 +97,15 @@ export const BackendConnectionStatus: React.FC = () => {
};
const getStatusIcon = () => {
- if (isFetching || connection === WebSocketState.CONNECTING) {
+ if (isFetching || isAppConnecting(connection)) {
return <Spinner size="small" />;
}
- if (connection === WebSocketState.CLOSING) {
+ if (isAppClosing(connection)) {
return <Spinner className="text-destructive" size="small" />;
}
- if (connection === WebSocketState.OPEN) {
+ if (isAppConnected(connection)) {
if (data?.isHealthy) {
return <CheckCircle2Icon className="w-4 h-4 text-(--green-9)" />;
}
@@ -102,26 +114,38 @@ export const BackendConnectionStatus: React.FC = () => {
}
return <CheckCircle2Icon className="w-4 h-4" />;
}
+ if (isAppNotStarted(connection)) {
+ return <PowerOffIcon className="w-4 h-4" />;
+ }
return <PowerOffIcon className="w-4 h-4 text-red-500" />;
};
+ const handleClick = () => {
+ if (isAppNotStarted(connection)) {
+ void connectToRuntime();
+ } else {
+ void refetch();
+ }
+ };
+
return (
<Tooltip
content={
<div className="text-sm whitespace-pre-line">
{getStatusInfo()}
- {connection === WebSocketState.OPEN && (
+ {isAppConnected(connection) && (
<div className="mt-2 text-xs text-muted-foreground">
Click to refresh health status
</div>
)}
</div>
}
+ data-testid="footer-backend-status"
>
<button
type="button"
- onClick={refetch}
+ onClick={handleClick}
className="p-1 hover:bg-accent rounded flex items-center gap-1.5 text-xs text-muted-foreground"
data-testid="backend-status"
>
diff --git a/frontend/src/components/editor/controls/Controls.tsx b/frontend/src/components/editor/controls/Controls.tsx
index de217e045d..f72e1f6164 100644
--- a/frontend/src/components/editor/controls/Controls.tsx
+++ b/frontend/src/components/editor/controls/Controls.tsx
@@ -15,7 +15,7 @@ import { ShutdownButton } from "@/components/editor/controls/shutdown-button";
import { Button } from "@/components/editor/inputs/Inputs";
import { FindReplace } from "@/components/find-replace/find-replace";
import type { AppConfig } from "@/core/config/config-schema";
-import { isConnectedAtom } from "@/core/network/connection";
+import { canInteractWithAppAtom } from "@/core/network/connection";
import { SaveComponent } from "@/core/saving/save-component";
import {
getConnectionTooltip,
@@ -155,7 +155,7 @@ const RunControlButton = ({
needsRun: boolean;
onRun: () => void;
}) => {
- const isConnected = useAtomValue(isConnectedAtom);
+ const canInteractWithApp = useAtomValue(canInteractWithAppAtom);
if (needsRun) {
return (
@@ -165,8 +165,8 @@ const RunControlButton = ({
size="medium"
color="yellow"
shape="circle"
- onClick={isConnected ? onRun : undefined}
- disabled={!isConnected}
+ onClick={onRun}
+ disabled={!canInteractWithApp}
>
<PlayIcon strokeWidth={1.5} size={16} />
</Button>
@@ -182,7 +182,7 @@ const RunControlButton = ({
color="disabled"
size="medium"
shape="circle"
- disabled={!isConnected}
+ disabled={!canInteractWithApp}
>
<PlayIcon strokeWidth={1.5} size={16} />
</Button>
diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsx
index cc2564fb82..8fa5dc347f 100644
--- a/frontend/src/components/editor/notebook-cell.tsx
+++ b/frontend/src/components/editor/notebook-cell.tsx
@@ -50,10 +50,7 @@ import {
import { type CellId, SETUP_CELL_ID } from "../../core/cells/ids";
import { isUninstantiated } from "../../core/cells/utils";
import type { UserConfig } from "../../core/config/config-schema";
-import {
- isAppConnected,
- isAppInteractionDisabled,
-} from "../../core/websocket/connection-utils";
+import { isAppInteractionDisabled } from "../../core/websocket/connection-utils";
import { useCellRenderCount } from "../../hooks/useCellRenderCount";
import type { Theme } from "../../theme/useTheme";
import { derefNotNull } from "../../utils/dereference";
@@ -842,7 +839,6 @@ const CellLeftSideActions = memo(
actions.createNewCell({ cellId, before: true, ...opts }),
);
- const isConnected = isAppConnected(connection.state);
const oneClickShortcut = "mod";
return (
@@ -856,7 +852,7 @@ const CellLeftSideActions = memo(
<CreateCellButton
tooltipContent={renderShortcut("cell.createAbove")}
connectionState={connection.state}
- onClick={isConnected ? createAbove : undefined}
+ onClick={createAbove}
oneClickShortcut={oneClickShortcut}
/>
</div>
@@ -866,7 +862,7 @@ const CellLeftSideActions = memo(
<CreateCellButton
tooltipContent={renderShortcut("cell.createBelow")}
connectionState={connection.state}
- onClick={isConnected ? createBelow : undefined}
+ onClick={createBelow}
oneClickShortcut={oneClickShortcut}
/>
</div>
@@ -908,7 +904,6 @@ const CellToolbar = memo(
includeCellActions = true,
}: CellToolbarProps) => {
const connection = useAtomValue(connectionAtom);
- const isConnected = isAppConnected(connection.state);
return (
<Toolbar
@@ -919,7 +914,7 @@ const CellToolbar = memo(
>
<RunButton
edited={edited}
- onClick={isConnected ? onRun : Functions.NOOP}
+ onClick={onRun}
connectionState={connection.state}
status={status}
config={cellConfig}
diff --git a/frontend/src/components/editor/renderers/cell-array.tsx b/frontend/src/components/editor/renderers/cell-array.tsx
index 7b81e728e8..24841d27f3 100644
--- a/frontend/src/components/editor/renderers/cell-array.tsx
+++ b/frontend/src/components/editor/renderers/cell-array.tsx
@@ -23,7 +23,7 @@ import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
import { SETUP_CELL_ID } from "@/core/cells/ids";
import { LanguageAdapters } from "@/core/codemirror/language/LanguageAdapters";
import { aiEnabledAtom } from "@/core/config/config";
-import { isConnectedAtom } from "@/core/network/connection";
+import { canInteractWithAppAtom } from "@/core/network/connection";
import { useBoolean } from "@/hooks/useBoolean";
import { cn } from "@/utils/cn";
import { Functions } from "@/utils/functions";
@@ -41,7 +41,10 @@ import type { AppMode } from "../../../core/mode";
import { useHotkey } from "../../../hooks/useHotkey";
import { type Theme, useTheme } from "../../../theme/useTheme";
import { AddCellWithAI } from "../ai/add-cell-with-ai";
-import { ConnectingAlert } from "../alerts/connecting-alert";
+import {
+ ConnectingAlert,
+ NotStartedConnectionAlert,
+} from "../alerts/connecting-alert";
import { FloatingOutline } from "../chrome/panels/outline/floating-outline";
import { useChromeActions } from "../chrome/state";
import { Column } from "../columns/cell-column";
@@ -124,6 +127,8 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
<StdinBlockingAlert />
<ConnectingAlert />
<NotebookBanner width={appConfig.width} />
+ {/* Only show if not cells, otherwise running a single cell will start the connection */}
+ {cellIds.idLength === 0 && <NotStartedConnectionAlert />}
<div
className={cn(
appConfig.width === "columns" &&
@@ -247,7 +252,7 @@ const AddCellButtons: React.FC<{
const { createNewCell } = useCellActions();
const [isAiButtonOpen, isAiButtonOpenActions] = useBoolean(false);
const aiEnabled = useAtomValue(aiEnabledAtom);
- const isConnected = useAtomValue(isConnectedAtom);
+ const canInteractWithApp = useAtomValue(canInteractWithAppAtom);
const buttonClass = cn(
"mb-0 rounded-none sm:px-4 md:px-5 lg:px-8 tracking-wide no-wrap whitespace-nowrap",
@@ -265,7 +270,7 @@ const AddCellButtons: React.FC<{
className={buttonClass}
variant="text"
size="sm"
- disabled={!isConnected}
+ disabled={!canInteractWithApp}
onClick={() =>
createNewCell({
cellId: { type: "__end__", columnId },
@@ -280,7 +285,7 @@ const AddCellButtons: React.FC<{
className={buttonClass}
variant="text"
size="sm"
- disabled={!isConnected}
+ disabled={!canInteractWithApp}
onClick={() => {
maybeAddMarimoImport({ autoInstantiate: true, createNewCell });
@@ -299,7 +304,7 @@ const AddCellButtons: React.FC<{
className={buttonClass}
variant="text"
size="sm"
- disabled={!isConnected}
+ disabled={!canInteractWithApp}
onClick={() => {
maybeAddMarimoImport({ autoInstantiate: true, createNewCell });
@@ -324,7 +329,7 @@ const AddCellButtons: React.FC<{
className={buttonClass}
variant="text"
size="sm"
- disabled={!aiEnabled || !isConnected}
+ disabled={!aiEnabled || !canInteractWithApp}
onClick={isAiButtonOpenActions.toggle}
>
<SparklesIcon className="mr-2 size-4 shrink-0" />
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.ts
index 6e2a229083..a7e9d6f841 100644
--- a/frontend/src/core/codemirror/cm.ts
+++ b/frontend/src/core/codemirror/cm.ts
@@ -47,7 +47,6 @@ import type {
LSPConfig,
} from "../config/config-schema";
import type { HotkeyProvider } from "../hotkeys/hotkeys";
-import { store } from "../state/jotai";
import { requestEditCompletion } from "./ai/request";
import { cellBundle } from "./cells/extensions";
import type { CodemirrorCellActions } from "./cells/state";
@@ -66,7 +65,6 @@ import { adaptiveLanguageConfiguration } from "./language/extension";
import { dndBundle } from "./misc/dnd";
import { pasteBundle } from "./misc/paste";
import { reactiveReferencesBundle } from "./reactive-references/extension";
-import { dynamicReadonly } from "./readonly/extension";
import { darkTheme } from "./theme/dark";
import { lightTheme } from "./theme/light";
@@ -147,8 +145,6 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {
}),
]
: [],
- // Readonly extension
- dynamicReadonly(store),
// Reactive references highlighting
reactiveReferencesBundle(
cellId,
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 08cbae03aa..8dd6fef546 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -4,6 +4,7 @@ import { usePrevious } from "@dnd-kit/utilities";
import { TooltipProvider } from "@radix-ui/react-tooltip";
import { useAtomValue, useSetAtom } from "jotai";
import { useEffect } from "react";
+import { NotStartedConnectionAlert } from "@/components/editor/alerts/connecting-alert";
import { Controls } from "@/components/editor/controls/Controls";
import { AppHeader } from "@/components/editor/header/app-header";
import { FilenameForm } from "@/components/editor/header/filename-form";
@@ -169,6 +170,7 @@ export const EditApp: React.FC<AppProps> = ({
{editableCellsArray}
</CellsRenderer>
)}
+ {!hasCells && <NotStartedConnectionAlert />}
</AppContainer>
<MultiCellActionToolbar />
{!hideControls && (
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index c81a6e0d95..36bf8099a1 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -133,6 +133,7 @@ export async function initialize() {
setLayoutData: Functions.NOOP,
setAppConfig: Functions.NOOP,
setCapabilities: Functions.NOOP,
+ setKernelState: Functions.NOOP,
onError: Logger.error,
});
// Define the custom element for the marimo-island tag.
diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.ts
index 548c74e2a9..354b9bd965 100644
--- a/frontend/src/core/kernel/handlers.ts
+++ b/frontend/src/core/kernel/handlers.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { deserializeLayout } from "@/components/editor/renderers/plugins";
import type { LayoutType } from "@/components/editor/renderers/types";
+import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
import type { CellId, UIElementId } from "../cells/ids";
import { type CellData, createCell } from "../cells/types";
@@ -18,6 +19,7 @@ import type {
CellMessage,
NotificationMessageData,
} from "./messages";
+import type { KernelState } from "./state";
type KernelReadyData = NotificationMessageData<"kernel-ready">;
@@ -108,6 +110,7 @@ export function handleKernelReady(
data: LayoutData;
}) => void;
setCapabilities: (capabilities: Capabilities) => void;
+ setKernelState: (state: KernelState) => void;
setAppConfig: (config: AppConfig) => void;
onError: (error: Error) => void;
/**
@@ -124,14 +127,17 @@ export function handleKernelReady(
setLayoutData,
setAppConfig,
setCapabilities,
+ setKernelState,
onError,
} = opts;
const { resumed, ui_values, app_config, capabilities, auto_instantiated } =
data;
// Use existing cells if provided (local pre-connect edits), otherwise build from kernel-ready
+ // If the kernel was resumed, we don't want to use the existing cells because they may be stale.
const hasExistingCells = existingCells && existingCells.length > 0;
- const cells = hasExistingCells ? existingCells : buildCellData(data);
+ const cells =
+ hasExistingCells && !resumed ? existingCells : buildCellData(data);
// Set up layout and cells
const layoutState = buildLayoutState(data, cells, setLayoutData);
@@ -141,6 +147,8 @@ export function handleKernelReady(
const parsedAppConfig = AppConfigSchema.safeParse(app_config);
if (parsedAppConfig.success) {
setAppConfig(parsedAppConfig.data);
+ } else {
+ Logger.error("Failed to parse app config", parsedAppConfig.error);
}
setCapabilities(capabilities);
@@ -157,8 +165,6 @@ export function handleKernelReady(
return;
}
- // Send instantiate request to kernel
-
// If we already have values for some objects, we should
// send them to the kernel. This may happen after re-connecting
// to the kernel after the computer wakes from sleep.
@@ -167,6 +173,7 @@ export function handleKernelReady(
? Object.fromEntries(existingCells.map((c) => [c.id, c.code]))
: undefined;
+ // Send instantiate request to kernel
void getRequestClient()
.sendInstantiate({
objectIds,
@@ -174,7 +181,11 @@ export function handleKernelReady(
autoRun: autoInstantiate,
codes: codesToSend,
})
+ .then(() => {
+ setKernelState({ isInstantiated: true, error: null });
+ })
.catch((error) => {
+ setKernelState({ isInstantiated: false, error: error });
onError(new Error("Failed to instantiate", { cause: error }));
});
}
diff --git a/frontend/src/core/kernel/state.ts b/frontend/src/core/kernel/state.ts
new file mode 100644
index 0000000000..414bf5eaec
--- /dev/null
+++ b/frontend/src/core/kernel/state.ts
@@ -0,0 +1,16 @@
+import { atom } from "jotai";
+import { waitFor } from "../state/jotai";
+
+export interface KernelState {
+ isInstantiated: boolean;
+ error: Error | null;
+}
+
+export const kernelStateAtom = atom<KernelState>({
+ isInstantiated: false,
+ error: null,
+});
+
+export function waitForKernelToBeInstantiated(): Promise<KernelState> {
+ return waitFor(kernelStateAtom, (value) => value.isInstantiated);
+}
diff --git a/frontend/src/core/network/__tests__/requests-lazy.test.ts b/frontend/src/core/network/__tests__/requests-lazy.test.ts
new file mode 100644
index 0000000000..7b244333bd
--- /dev/null
+++ b/frontend/src/core/network/__tests__/requests-lazy.test.ts
@@ -0,0 +1,322 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { RuntimeManager } from "../../runtime/runtime";
+import { createLazyRequests } from "../requests-lazy";
+import type { EditRequests, RunRequests } from "../types";
+
+// Mock the connection module
+vi.mock("../connection", () => ({
+ waitForConnectionOpen: vi.fn().mockResolvedValue(undefined),
+}));
+
+// Mock the kernel state module
+vi.mock("../../kernel/state", () => ({
+ waitForKernelToBeInstantiated: vi.fn().mockResolvedValue(undefined),
+}));
+
+describe("createLazyRequests", () => {
+ let mockDelegate: EditRequests & RunRequests;
+ let mockRuntimeManager: RuntimeManager;
+ let mockGetRuntimeManager: () => RuntimeManager;
+ let mockInit: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ // Mock init function
+ mockInit = vi.fn().mockResolvedValue(undefined);
+
+ // Mock runtime manager
+ mockRuntimeManager = {
+ init: mockInit,
+ } as unknown as RuntimeManager;
+
+ // Mock getter function
+ mockGetRuntimeManager = vi.fn(() => mockRuntimeManager);
+
+ // Mock delegate with some sample methods
+ mockDelegate = {
+ sendRun: vi.fn().mockResolvedValue({ success: true }),
+ sendInstantiate: vi.fn().mockResolvedValue({ instantiated: true }),
+ sendFunctionRequest: vi.fn().mockResolvedValue({ result: "data" }),
+ sendRestart: vi.fn().mockResolvedValue({ restarted: true }),
+ sendDeleteCell: vi.fn().mockResolvedValue({ deleted: true }),
+ sendInterrupt: vi.fn().mockResolvedValue({ interrupted: true }),
+ sendPdb: vi.fn().mockResolvedValue({ pdb: true }),
+ sendRunScratchpad: vi.fn().mockResolvedValue({ run: true }),
+ } as unknown as EditRequests & RunRequests;
+ });
+
+ it("should call init once before first request", async () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendRun({ cellIds: ["cell1"], codes: ["code"] });
+
+ expect(mockInit).toHaveBeenCalledTimes(1);
+ });
+
+ it("should only call init once across multiple requests", async () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendRun({ cellIds: ["cell1"], codes: ["code"] });
+ await lazyRequests.sendInstantiate({ objectIds: ["obj1"], values: [] });
+ await lazyRequests.sendFunctionRequest({
+ functionCallId: "func1",
+ functionName: "testFunc",
+ args: {},
+ namespace: "test",
+ });
+
+ expect(mockInit).toHaveBeenCalledTimes(1);
+ });
+
+ it("should wait for connection before calling delegate method", async () => {
+ const { waitForConnectionOpen } = await import("../connection");
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendRun({ cellIds: ["cell1"], codes: ["code"] });
+
+ expect(waitForConnectionOpen).toHaveBeenCalled();
+ });
+
+ it("should call delegate method with correct arguments", async () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ const args = { cellIds: ["cell1"], codes: ["code"] };
+ await lazyRequests.sendRun(args);
+
+ expect(mockDelegate.sendRun).toHaveBeenCalledWith(args);
+ });
+
+ it("should return the result from delegate method", async () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ const result = await lazyRequests.sendFunctionRequest({
+ functionCallId: "func1",
+ functionName: "testFunc",
+ args: {},
+ namespace: "test",
+ });
+
+ expect(result).toEqual({ result: "data" });
+ });
+
+ it("should wrap all methods from delegate", () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ expect(lazyRequests.sendRun).toBeDefined();
+ expect(lazyRequests.sendInstantiate).toBeDefined();
+ expect(lazyRequests.sendFunctionRequest).toBeDefined();
+ });
+
+ it("should handle errors from init", async () => {
+ const error = new Error("Init failed");
+ mockInit.mockRejectedValue(error);
+
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await expect(
+ lazyRequests.sendRun({ cellIds: ["cell1"], codes: ["code"] }),
+ ).rejects.toThrow("Init failed");
+ });
+
+ it("should handle errors from delegate method", async () => {
+ const error = new Error("Request failed");
+ mockDelegate.sendRun = vi.fn().mockRejectedValue(error);
+
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await expect(
+ lazyRequests.sendRun({ cellIds: ["cell1"], codes: ["code"] }),
+ ).rejects.toThrow("Request failed");
+ });
+
+ describe("SKIP_REQUESTS", () => {
+ it("should not wait for init or connection for sendRestart", async () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendRestart();
+
+ // Should not call init or wait for connection
+ expect(mockInit).not.toHaveBeenCalled();
+ expect(mockGetRuntimeManager).not.toHaveBeenCalled();
+ // Should call the delegate method directly
+ expect(mockDelegate.sendRestart).toHaveBeenCalled();
+ });
+
+ it("should call sendRestart immediately without waiting", async () => {
+ const { waitForConnectionOpen } = await import("../connection");
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendRestart();
+
+ expect(waitForConnectionOpen).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("WAIT_FOR_INSTANTIATE_REQUESTS", () => {
+ it("should wait for kernel instantiation for sendRun", async () => {
+ const { waitForKernelToBeInstantiated } = await import(
+ "../../kernel/state"
+ );
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendRun({ cellIds: ["cell1"], codes: ["code"] });
+
+ expect(waitForKernelToBeInstantiated).toHaveBeenCalled();
+ });
+
+ it("should wait for kernel instantiation for sendDeleteCell", async () => {
+ const { waitForKernelToBeInstantiated } = await import(
+ "../../kernel/state"
+ );
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendDeleteCell({ cellId: "cell1" });
+
+ expect(waitForKernelToBeInstantiated).toHaveBeenCalled();
+ });
+
+ it("should wait for kernel instantiation for sendInterrupt", async () => {
+ const { waitForKernelToBeInstantiated } = await import(
+ "../../kernel/state"
+ );
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendInterrupt();
+
+ expect(waitForKernelToBeInstantiated).toHaveBeenCalled();
+ });
+
+ it("should wait for kernel instantiation for sendPdb", async () => {
+ const { waitForKernelToBeInstantiated } = await import(
+ "../../kernel/state"
+ );
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendPdb({ cellId: "cell1" });
+
+ expect(waitForKernelToBeInstantiated).toHaveBeenCalled();
+ });
+
+ it("should wait for kernel instantiation for sendRunScratchpad", async () => {
+ const { waitForKernelToBeInstantiated } = await import(
+ "../../kernel/state"
+ );
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendRunScratchpad({ code: "print('test')" });
+
+ expect(waitForKernelToBeInstantiated).toHaveBeenCalled();
+ });
+
+ it("should not wait for kernel instantiation for other requests", async () => {
+ const { waitForKernelToBeInstantiated } = await import(
+ "../../kernel/state"
+ );
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ await lazyRequests.sendInstantiate({ objectIds: ["obj1"], values: [] });
+
+ expect(waitForKernelToBeInstantiated).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("Memoization", () => {
+ it("should re-initialize if runtime manager changes", async () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ // First request with first runtime manager
+ await lazyRequests.sendRun({ cellIds: ["cell1"], codes: ["code"] });
+ expect(mockInit).toHaveBeenCalledTimes(1);
+
+ // Create a new runtime manager
+ const mockInit2 = vi.fn().mockResolvedValue(undefined);
+ const mockRuntimeManager2 = {
+ init: mockInit2,
+ } as unknown as RuntimeManager;
+ mockGetRuntimeManager = vi.fn(() => mockRuntimeManager2);
+
+ // Create new lazy requests with new getter
+ const lazyRequests2 = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ // Second request with second runtime manager
+ await lazyRequests2.sendRun({ cellIds: ["cell2"], codes: ["code2"] });
+
+ // Both inits should have been called
+ expect(mockInit).toHaveBeenCalledTimes(1);
+ expect(mockInit2).toHaveBeenCalledTimes(1);
+ });
+
+ it("should only initialize once per runtime manager instance", async () => {
+ const lazyRequests = createLazyRequests(
+ mockDelegate,
+ mockGetRuntimeManager,
+ );
+
+ // Multiple requests
+ await lazyRequests.sendRun({ cellIds: ["cell1"], codes: ["code"] });
+ await lazyRequests.sendDeleteCell({ cellId: "cell2" });
+ await lazyRequests.sendInstantiate({ objectIds: ["obj1"], values: [] });
+
+ // Init should only be called once
+ expect(mockInit).toHaveBeenCalledTimes(1);
+ expect(mockGetRuntimeManager).toHaveBeenCalledTimes(3);
+ });
+ });
+});
diff --git a/frontend/src/core/network/connection.ts b/frontend/src/core/network/connection.ts
index 071c5e6ce3..45b71b834b 100644
--- a/frontend/src/core/network/connection.ts
+++ b/frontend/src/core/network/connection.ts
@@ -5,10 +5,10 @@ import { type ConnectionStatus, WebSocketState } from "../websocket/types";
/**
* Atom for storing the connection status.
- * Initialized to CONNECTING for normal mode, OPEN for static mode.
+ * Initialized to NOT_STARTED.
*/
export const connectionAtom = atom<ConnectionStatus>({
- state: WebSocketState.CONNECTING,
+ state: WebSocketState.NOT_STARTED,
});
export function waitForConnectionOpen() {
@@ -27,7 +27,20 @@ export const isConnectedAtom = atom((get) => {
return connection.state === WebSocketState.OPEN;
});
+export const canInteractWithAppAtom = atom((get) => {
+ const connection = get(connectionAtom);
+ return (
+ connection.state === WebSocketState.OPEN ||
+ connection.state === WebSocketState.NOT_STARTED
+ );
+});
+
export const isClosedAtom = atom((get) => {
const connection = get(connectionAtom);
return connection.state === WebSocketState.CLOSED;
});
+
+export const isNotStartedAtom = atom((get) => {
+ const connection = get(connectionAtom);
+ return connection.state === WebSocketState.NOT_STARTED;
+});
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
new file mode 100644
index 0000000000..5821b23a30
--- /dev/null
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -0,0 +1,65 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { Objects } from "@/utils/objects";
+import { memoizeLastValue } from "@/utils/once";
+import { waitForKernelToBeInstantiated } from "../kernel/state";
+import type { RuntimeManager } from "../runtime/runtime";
+import { waitForConnectionOpen } from "./connection";
+import type { EditRequests, RunRequests } from "./types";
+
+type AllRequests = EditRequests & RunRequests;
+
+const SKIP_REQUESTS = new Set<keyof AllRequests>([
+ "sendRestart",
+ "sendCodeCompletionRequest",
+]);
+
+const WAIT_FOR_INSTANTIATE_REQUESTS = new Set<keyof AllRequests>([
+ "sendDeleteCell",
+ "sendInterrupt",
+ "sendPdb",
+ "sendRun",
+ "sendRunScratchpad",
+]);
+
+/**
+ * Create a lazy requests client.
+ * On any request, we will initialize the runtime manager (if not already initialized)
+ * and wait for the connection to be open.
+ */
+export function createLazyRequests(
+ delegate: AllRequests,
+ getRuntimeManager: () => RuntimeManager,
+): AllRequests {
+ // Memoize the init call, just once per runtime manager
+ const initOnce = memoizeLastValue((runtimeManager: RuntimeManager) => {
+ return runtimeManager.init();
+ });
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ function connectAndThen<T extends (...args: any[]) => Promise<any>>(
+ request: T,
+ key: keyof AllRequests,
+ ): T {
+ const wrapped = (async (...args) => {
+ // Call init, just once per runtime manager
+ // This needs to be a getter because the runtime manager is created lazily.
+ await initOnce(getRuntimeManager());
+ // Wait for connection to be open
+ await waitForConnectionOpen();
+ if (WAIT_FOR_INSTANTIATE_REQUESTS.has(key)) {
+ await waitForKernelToBeInstantiated();
+ }
+ // Call the request
+ return request(...args);
+ }) as T;
+ return wrapped;
+ }
+
+ return Objects.mapValues(delegate, (value, key) => {
+ if (SKIP_REQUESTS.has(key)) {
+ return value;
+ }
+ return connectAndThen(value, key);
+ }) as AllRequests;
+}
diff --git a/frontend/src/core/network/resolve.ts b/frontend/src/core/network/resolve.ts
index 959e325d4b..2a62903e74 100644
--- a/frontend/src/core/network/resolve.ts
+++ b/frontend/src/core/network/resolve.ts
@@ -1,17 +1,24 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import { getRuntimeManager } from "../runtime/config";
import { isStaticNotebook } from "../static/static-state";
import { PyodideBridge } from "../wasm/bridge";
import { isWasm } from "../wasm/utils";
+import { createLazyRequests } from "./requests-lazy";
import { createNetworkRequests } from "./requests-network";
import { createStaticRequests } from "./requests-static";
import { createErrorToastingRequests } from "./requests-toasting";
import type { EditRequests, RunRequests } from "./types";
export function resolveRequestClient(): EditRequests & RunRequests {
- const base = isWasm()
- ? PyodideBridge.INSTANCE
- : isStaticNotebook()
- ? createStaticRequests()
- : createNetworkRequests();
+ let base: EditRequests & RunRequests;
+ if (isWasm()) {
+ base = PyodideBridge.INSTANCE;
+ } else if (isStaticNotebook()) {
+ base = createStaticRequests();
+ } else {
+ base = createLazyRequests(createNetworkRequests(), () =>
+ getRuntimeManager(),
+ );
+ }
return createErrorToastingRequests(base);
}
diff --git a/frontend/src/core/runtime/__tests__/createWsUrl.test.ts b/frontend/src/core/runtime/__tests__/createWsUrl.test.ts
index a8039d8484..6159eeadc4 100644
--- a/frontend/src/core/runtime/__tests__/createWsUrl.test.ts
+++ b/frontend/src/core/runtime/__tests__/createWsUrl.test.ts
@@ -7,7 +7,10 @@ import { RuntimeManager } from "../runtime";
describe("RuntimeManager.getWsURL", () => {
it("should return a URL with the wss protocol when the baseURI uses https", () => {
- const runtime = new RuntimeManager({ url: "https://marimo.app/" });
+ const runtime = new RuntimeManager({
+ url: "https://marimo.app/",
+ lazy: true,
+ });
const sessionId = "1234" as SessionId;
const url = runtime.getWsURL(sessionId);
expect(url.toString()).toBe("wss://marimo.app/ws?session_id=1234");
@@ -15,7 +18,10 @@ describe("RuntimeManager.getWsURL", () => {
});
it("should return a URL with the ws protocol when the baseURI uses http", () => {
- const runtime = new RuntimeManager({ url: "http://marimo.app/" });
+ const runtime = new RuntimeManager({
+ url: "http://marimo.app/",
+ lazy: true,
+ });
const sessionId = "1234" as SessionId;
const url = runtime.getWsURL(sessionId);
expect(url.toString()).toBe("ws://marimo.app/ws?session_id=1234");
@@ -23,7 +29,10 @@ describe("RuntimeManager.getWsURL", () => {
});
it("should work with nested baseURI", () => {
- const runtime = new RuntimeManager({ url: "http://marimo.app/nested/" });
+ const runtime = new RuntimeManager({
+ url: "http://marimo.app/nested/",
+ lazy: true,
+ });
const sessionId = "1234" as SessionId;
const url = runtime.getWsURL(sessionId);
expect(url.toString()).toBe("ws://marimo.app/nested/ws?session_id=1234");
@@ -33,6 +42,7 @@ describe("RuntimeManager.getWsURL", () => {
it("should work with nested baseURI and query params", () => {
const runtime = new RuntimeManager({
url: "http://marimo.app/nested/?foo=bar",
+ lazy: true,
});
window.history.pushState({}, "", "/nested/?file=test.py");
const sessionId = "1234" as SessionId;
@@ -46,6 +56,7 @@ describe("RuntimeManager.getWsURL", () => {
it("should include all query params from current page", () => {
const runtime = new RuntimeManager({
url: "http://marimo.app/",
+ lazy: true,
});
window.history.pushState({}, "", "/?file=test.py&search=test&other=last");
const sessionId = "1234" as SessionId;
diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.ts
index 2c60e7cf4a..6a6194fdc3 100644
--- a/frontend/src/core/runtime/__tests__/runtime.test.ts
+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts
@@ -14,6 +14,7 @@ vi.mock("@/core/kernel/session", () => ({
// Mock the Logger module
vi.mock("@/utils/Logger", () => ({
Logger: {
+ debug: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
@@ -22,11 +23,13 @@ vi.mock("@/utils/Logger", () => ({
describe("RuntimeManager", () => {
const mockConfig: RuntimeConfig = {
url: "https://example.com",
+ lazy: true,
authToken: "test-token",
};
const mockConfigWithoutToken: RuntimeConfig = {
url: "http://localhost:8080",
+ lazy: true,
};
describe("constructor", () => {
@@ -45,7 +48,10 @@ describe("RuntimeManager", () => {
});
it("should handle URLs without trailing slash", () => {
- const runtime = new RuntimeManager({ url: "https://example.com/path" });
+ const runtime = new RuntimeManager({
+ url: "https://example.com/path",
+ lazy: true,
+ });
expect(runtime.httpURL.toString()).toBe("https://example.com/path");
});
});
@@ -74,7 +80,10 @@ describe("RuntimeManager", () => {
});
it("should preserve existing query params", () => {
- const runtime = new RuntimeManager({ url: "http://example.com?foo=bar" });
+ const runtime = new RuntimeManager({
+ url: "http://example.com?foo=bar",
+ lazy: true,
+ });
const sessionId = "1234" as SessionId;
const url = runtime.getWsURL(sessionId);
@@ -335,6 +344,7 @@ describe("RuntimeManager", () => {
it("should remove query params from base URI", async () => {
const configWithQueryParams: RuntimeConfig = {
url: "https://example.com/foo?param1=value1&param2=value2",
+ lazy: true,
authToken: "test-token",
};
@@ -358,6 +368,7 @@ describe("RuntimeManager", () => {
it("should handle URLs with nested paths", () => {
const runtime = new RuntimeManager({
url: "https://example.com/nested/path/",
+ lazy: true,
});
const wsUrl = runtime.getWsURL("test" as SessionId);
const aiUrl = runtime.getAiURL("completion");
@@ -379,6 +390,7 @@ describe("RuntimeManager", () => {
const runtime = new RuntimeManager({
url: "https://example.com/path?base_param=existing",
+ lazy: true,
});
const wsUrl = runtime.getWsURL("test" as SessionId);
@@ -413,6 +425,7 @@ describe("RuntimeManager", () => {
it("should handle URLs with query parameters and fragments", () => {
const runtime = new RuntimeManager({
url: "https://example.com/path?existing=param#fragment",
+ lazy: true,
});
const wsUrl = runtime.getWsURL("test" as SessionId);
@@ -424,13 +437,19 @@ describe("RuntimeManager", () => {
it("should throw for invalid URLs", () => {
expect(() => {
- new RuntimeManager({ url: "not-a-url" });
+ new RuntimeManager({ url: "not-a-url", lazy: true });
}).toThrow();
});
it("should handle http to ws conversion correctly", () => {
- const httpRuntime = new RuntimeManager({ url: "http://localhost" });
- const httpsRuntime = new RuntimeManager({ url: "https://localhost" });
+ const httpRuntime = new RuntimeManager({
+ url: "http://localhost",
+ lazy: true,
+ });
+ const httpsRuntime = new RuntimeManager({
+ url: "https://localhost",
+ lazy: true,
+ });
expect(httpRuntime.getWsURL("test" as SessionId).protocol).toBe("ws:");
expect(httpsRuntime.getWsURL("test" as SessionId).protocol).toBe("wss:");
@@ -439,6 +458,7 @@ describe("RuntimeManager", () => {
it("should handle blob URLs", () => {
const runtime = new RuntimeManager({
url: "blob:https://example.com/12345678-1234-1234-1234-123456789abc",
+ lazy: true,
});
expect(runtime.httpURL.toString()).toBe(
@@ -449,6 +469,7 @@ describe("RuntimeManager", () => {
it("should throw when creating WebSocket URLs from blob URLs", () => {
const runtime = new RuntimeManager({
url: "blob:https://example.com/12345678-1234-1234-1234-123456789abc",
+ lazy: true,
});
const sessionId = "test" as SessionId;
@@ -461,6 +482,7 @@ describe("RuntimeManager", () => {
it("should handle blob URLs in AI URLs", () => {
const runtime = new RuntimeManager({
url: "blob:https://example.com/12345678-1234-1234-1234-123456789abc",
+ lazy: true,
});
const aiUrl = runtime.getAiURL("completion");
@@ -473,6 +495,7 @@ describe("RuntimeManager", () => {
it("should handle blob URLs in health check URLs", () => {
const runtime = new RuntimeManager({
url: "blob:https://example.com/12345678-1234-1234-1234-123456789abc",
+ lazy: true,
});
const healthUrl = runtime.healthURL();
@@ -485,6 +508,7 @@ describe("RuntimeManager", () => {
it("should handle URLs with userinfo", () => {
const runtime = new RuntimeManager({
url: "https://user:[email protected]",
+ lazy: true,
});
const wsUrl = runtime.getWsURL("test" as SessionId);
@@ -497,6 +521,7 @@ describe("RuntimeManager", () => {
it("should handle IPv6 addresses", () => {
const runtime = new RuntimeManager({
url: "http://[::1]:8080",
+ lazy: true,
});
const wsUrl = runtime.getWsURL("test" as SessionId);
@@ -508,6 +533,7 @@ describe("RuntimeManager", () => {
it("should handle URLs with encoded characters", () => {
const runtime = new RuntimeManager({
url: "https://example.com/path%20with%20spaces",
+ lazy: true,
});
const aiUrl = runtime.getAiURL("completion");
@@ -517,6 +543,7 @@ describe("RuntimeManager", () => {
it("should handle URLs with multiple trailing slashes", () => {
const runtime = new RuntimeManager({
url: "https://example.com/path///",
+ lazy: true,
});
const aiUrl = runtime.getAiURL("completion");
@@ -526,6 +553,7 @@ describe("RuntimeManager", () => {
it("should handle URLs with port numbers", () => {
const runtime = new RuntimeManager({
url: "https://example.com:9443/app",
+ lazy: true,
});
const wsUrl = runtime.getWsURL("test" as SessionId);
@@ -543,7 +571,7 @@ describe("RuntimeManager", () => {
];
variants.forEach((url) => {
- const runtime = new RuntimeManager({ url });
+ const runtime = new RuntimeManager({ url, lazy: true });
const wsUrl = runtime.getWsURL("test" as SessionId);
expect(wsUrl.protocol).toBe("ws:");
});
@@ -552,6 +580,7 @@ describe("RuntimeManager", () => {
it("should handle URLs with complex query parameters", () => {
const runtime = new RuntimeManager({
url: "https://example.com?param1=value1&param2=value%20encoded&empty=",
+ lazy: true,
});
const wsUrl = runtime.getWsURL("test" as SessionId);
@@ -564,23 +593,30 @@ describe("RuntimeManager", () => {
it("should accept data URLs (valid URL format)", () => {
const runtime = new RuntimeManager({
url: "data:text/plain;base64,SGVsbG8gV29ybGQ=",
+ lazy: true,
});
expect(runtime.httpURL.protocol).toBe("data:");
});
it("should accept file URLs (valid URL format)", () => {
- const runtime = new RuntimeManager({ url: "file:///path/to/file" });
+ const runtime = new RuntimeManager({
+ url: "file:///path/to/file",
+ lazy: true,
+ });
expect(runtime.httpURL.protocol).toBe("file:");
});
it("should accept custom protocol URLs (valid URL format)", () => {
- const runtime = new RuntimeManager({ url: "custom://example.com" });
+ const runtime = new RuntimeManager({
+ url: "custom://example.com",
+ lazy: true,
+ });
expect(runtime.httpURL.protocol).toBe("custom:");
});
it("should handle empty string URL", () => {
expect(() => {
- new RuntimeManager({ url: "" });
+ new RuntimeManager({ url: "", lazy: true });
}).toThrow("Invalid runtime URL");
});
@@ -595,7 +631,7 @@ describe("RuntimeManager", () => {
malformedUrls.forEach((url) => {
expect(() => {
- new RuntimeManager({ url });
+ new RuntimeManager({ url, lazy: true });
}).toThrow("Invalid runtime URL");
});
});
diff --git a/frontend/src/core/runtime/config.ts b/frontend/src/core/runtime/config.ts
index 104005957a..e849a5d01d 100644
--- a/frontend/src/core/runtime/config.ts
+++ b/frontend/src/core/runtime/config.ts
@@ -1,7 +1,11 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { atom, useAtomValue } from "jotai";
-import { isStaticNotebook } from "@/core/static/static-state";
+import { atom, useAtom, useAtomValue } from "jotai";
+import useEvent from "react-use-event-hook";
+import { Logger } from "@/utils/Logger";
+import { connectionAtom } from "../network/connection";
import { store } from "../state/jotai";
+import { isAppNotStarted } from "../websocket/connection-utils";
+import { WebSocketState } from "../websocket/types";
import { RuntimeManager } from "./runtime";
import type { RuntimeConfig } from "./types";
@@ -13,22 +17,33 @@ function getBaseURI(): string {
}
export const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
+ lazy: true,
url: getBaseURI(),
};
export const runtimeConfigAtom = atom<RuntimeConfig>(DEFAULT_RUNTIME_CONFIG);
const runtimeManagerAtom = atom<RuntimeManager>((get) => {
const config = get(runtimeConfigAtom);
- // "lazy" means that the runtime manager will not attempt to connect to a
- // server, which in the case of a static notebook, will not be available.
- const lazy = isStaticNotebook();
- return new RuntimeManager(config, lazy);
+ return new RuntimeManager(config, config.lazy);
});
export function useRuntimeManager(): RuntimeManager {
return useAtomValue(runtimeManagerAtom);
}
+export function useConnectToRuntime(): () => Promise<void> {
+ const runtimeManager = useRuntimeManager();
+ const [connection, setConnection] = useAtom(connectionAtom);
+ return useEvent(async () => {
+ if (isAppNotStarted(connection.state)) {
+ setConnection({ state: WebSocketState.CONNECTING });
+ await runtimeManager.init();
+ } else {
+ Logger.log("Runtime already started or starting...");
+ }
+ });
+}
+
/**
* Prefer to use useRuntimeManager instead of this function.
*/
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index 29ddccc620..d045b8cd67 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -216,6 +216,7 @@ export class RuntimeManager {
}
async init(options?: { disableRetryDelay?: boolean }) {
+ Logger.debug("Initializing runtime...");
let retries = 0;
// This matches backoff logic elsewhere.
const maxRetries = 25;
@@ -238,6 +239,7 @@ export class RuntimeManager {
retries++;
}
+ Logger.debug("Runtime is healthy");
this.initialHealthyCheck.resolve();
}
diff --git a/frontend/src/core/runtime/types.ts b/frontend/src/core/runtime/types.ts
index 4c9f1874f1..30ea9d4ff0 100644
--- a/frontend/src/core/runtime/types.ts
+++ b/frontend/src/core/runtime/types.ts
@@ -1,7 +1,21 @@
/* Copyright 2026 Marimo. All rights reserved. */
export interface RuntimeConfig {
+ /**
+ * The URL of the runtime server.
+ */
url: string;
- serverToken?: string; // Skew protection token
- authToken?: string | null; // API key or JWT token for remote backend
+ /**
+ * If true, the runtime will not be loaded until the user interacts with the notebook.
+ * If false, the runtime will be loaded immediately.
+ */
+ lazy: boolean;
+ /**
+ * The server token for the runtime (Skew protection token)
+ */
+ serverToken?: string;
+ /**
+ * The API key or JWT token for the remote backend (used for authentication)
+ */
+ authToken?: string | null;
}
diff --git a/frontend/src/core/websocket/connection-utils.ts b/frontend/src/core/websocket/connection-utils.ts
index f24cb2b9a9..7bf3f00caf 100644
--- a/frontend/src/core/websocket/connection-utils.ts
+++ b/frontend/src/core/websocket/connection-utils.ts
@@ -29,6 +29,13 @@ export function isAppClosing(state: WebSocketState): boolean {
return state === WebSocketState.CLOSING;
}
+/**
+ * Check if the app is in a not started state
+ */
+export function isAppNotStarted(state: WebSocketState): boolean {
+ return state === WebSocketState.NOT_STARTED;
+}
+
/**
* Check if the app is in a state where user interactions should be disabled
*/
@@ -53,6 +60,8 @@ export function getConnectionTooltip(state: WebSocketState): string {
return "App disconnecting...";
case WebSocketState.OPEN:
return "";
+ case WebSocketState.NOT_STARTED:
+ return "Click to connect to a runtime";
default:
return "";
}
diff --git a/frontend/src/core/websocket/types.ts b/frontend/src/core/websocket/types.ts
index 694c799554..8ed793e833 100644
--- a/frontend/src/core/websocket/types.ts
+++ b/frontend/src/core/websocket/types.ts
@@ -2,6 +2,7 @@
// TODO: rename to ConnectionState
export const WebSocketState = {
+ NOT_STARTED: "NOT_STARTED",
CONNECTING: "CONNECTING",
OPEN: "OPEN",
CLOSING: "CLOSING",
@@ -38,5 +39,6 @@ export type ConnectionStatus =
state:
| typeof WebSocketState.CONNECTING
| typeof WebSocketState.OPEN
- | typeof WebSocketState.CLOSING;
+ | typeof WebSocketState.CLOSING
+ | typeof WebSocketState.NOT_STARTED;
};
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index c2fb10fea6..ad43c7f75a 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -49,6 +49,7 @@ import {
} from "../kernel/handlers";
import { queryParamHandlers } from "../kernel/queryParamHandlers";
import type { SessionId } from "../kernel/session";
+import { kernelStateAtom } from "../kernel/state";
import { type LayoutState, useLayoutActions } from "../layout/layout";
import { kioskModeAtom } from "../mode";
import { connectionAtom } from "../network/connection";
@@ -61,7 +62,7 @@ import type { VariableName } from "../variables/types";
import { isWasm } from "../wasm/utils";
import { WebSocketClosedReason, WebSocketState } from "./types";
-const SUPPORTS_LAZY_KERNELS = false;
+const SUPPORTS_LAZY_KERNELS = true;
function getExistingCells(): CellData[] | undefined {
if (!SUPPORTS_LAZY_KERNELS) {
@@ -89,6 +90,7 @@ export function useMarimoKernelConnection(opts: {
const { handleCellMessage, setCellCodes, setCellIds } = useCellActions();
const { addCellNotification } = useRunsActions();
+ const setKernelState = useSetAtom(kernelStateAtom);
const setAppConfig = useSetAppConfig();
const { setVariables, setMetadata } = useVariablesActions();
const { addColumnPreview } = useDatasetsActions();
@@ -111,8 +113,6 @@ export function useMarimoKernelConnection(opts: {
reloadSafe();
return;
case "kernel-ready": {
- // TODO(mscolnick): For lazy kernels, we should grab existing cells from the page
- // in case they have been edited locally.
const existingCells = getExistingCells();
handleKernelReady(msg.data, {
@@ -121,6 +121,7 @@ export function useMarimoKernelConnection(opts: {
setLayoutData,
setAppConfig,
setCapabilities,
+ setKernelState,
onError: showBoundary,
existingCells,
});
diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsx
index b68bde3bcb..925b9f9fce 100644
--- a/frontend/src/mount.tsx
+++ b/frontend/src/mount.tsx
@@ -104,8 +104,7 @@ export function mount(options: unknown, el: Element): Error | undefined {
}
const passthroughObject = z
- .object({})
- .passthrough() // Allow any extra fields
+ .looseObject({})
.nullish()
.default({}) // Default to empty object
.transform((val) => {
@@ -201,13 +200,12 @@ const mountOptionsSchema = z.object({
session: z.union([
z.null().optional(),
z
- .object({
+ .looseObject({
// Rough shape, we don't need to validate the full schema
version: z.literal("1"),
metadata: z.any(),
cells: z.array(z.any()),
})
- .passthrough()
.transform((val) => val as api.Session["NotebookSessionV1"]),
]),
@@ -217,13 +215,12 @@ const mountOptionsSchema = z.object({
notebook: z.union([
z.null().optional(),
z
- .object({
+ .looseObject({
// Rough shape, we don't need to validate the full schema
version: z.literal("1"),
metadata: z.any(),
cells: z.array(z.any()),
})
- .passthrough()
.transform((val) => val as api.Notebook["NotebookV1"]),
]),
@@ -232,12 +229,10 @@ const mountOptionsSchema = z.object({
*/
runtimeConfig: z
.array(
- z
- .object({
- url: z.string(),
- authToken: z.string().nullish(),
- })
- .passthrough(),
+ z.looseObject({
+ url: z.string(),
+ authToken: z.string().nullish(),
+ }),
)
.nullish()
.transform((val) => val ?? []),
@@ -305,11 +300,13 @@ function initStore(options: unknown) {
Logger.debug("⚡ Runtime URL", firstRuntimeConfig.url);
store.set(runtimeConfigAtom, {
...firstRuntimeConfig,
+ lazy: true,
serverToken: parsedOptions.data.serverToken,
});
} else {
store.set(runtimeConfigAtom, {
...DEFAULT_RUNTIME_CONFIG,
+ lazy: false,
serverToken: parsedOptions.data.serverToken,
});
}