A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: handle waiting until connection is healthy (#5259)
Myles Scolnick658c83b27d3a
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex dfa6a7a11b..ee9d518735 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -64,6 +64,11 @@ import { Events } from "@/utils/events";import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";import { useRunCell } from "./cell/useRunCells";import type { Milliseconds, Seconds } from "@/utils/time";+import {+ isAppConnected,+ isAppInteractionDisabled,+} from "../../core/websocket/connection-utils";+import type { WebSocketState } from "../../core/websocket/types";/*** Hook for handling cell completion logic@@ -370,7 +375,7 @@ export interface CellPropstheme: Theme;showPlaceholder: boolean;mode: AppMode;- appClosed: boolean;+ connectionState: WebSocketState;/*** False only when there is only one cell in the notebook.*/@@ -551,7 +556,7 @@ const EditableCellComponent = ({serializedEditorState,serialization,debuggerActive,- appClosed,+ connectionState,canDelete,actions,deleteCell,@@ -783,7 +788,7 @@ const EditableCellComponent = ({<div className="absolute right-2 -top-4 z-10"><CellToolbaredited={edited}- appClosed={appClosed}+ connectionState={connectionState}status={status}cellConfig={cellConfig}needsRun={needsRun}@@ -805,7 +810,7 @@ const EditableCellComponent = ({isCellButtonsInline &&"-left-[3.8rem]",)}- appClosed={appClosed}+ connectionState={connectionState}actions={actions}/><CellEditor@@ -846,10 +851,13 @@ const EditableCellComponent = ({<div className="shoulder-bottom hover-action">{canDelete && isCellCodeShown && (<DeleteButton- appClosed={appClosed}+ connectionState={connectionState}status={status}onClick={() => {- if (!loading && !appClosed) {+ if (+ !loading &&+ !isAppInteractionDisabled(connectionState)+ ) {deleteCell({ cellId });}}}@@ -993,10 +1001,10 @@ const CellRightSideActions = (props: {const CellLeftSideActions = (props: {className?: string;cellId: CellId;- appClosed: boolean;+ connectionState: WebSocketState;actions: CellComponentActions;}) => {- const { className, appClosed, actions, cellId } = props;+ const { className, connectionState, actions, cellId } = props;const createBelow = useEvent((opts: { code?: string } = {}) =>actions.createNewCell({ cellId, before: false, ...opts }),@@ -1005,6 +1013,8 @@ const CellLeftSideActions = (props: {actions.createNewCell({ cellId, before: true, ...opts }),);+ const isConnected = isAppConnected(connectionState);+return (<divclassName={cn(@@ -1014,14 +1024,14 @@ const CellLeftSideActions = (props: {><CreateCellButtontooltipContent={renderShortcut("cell.createAbove")}- appClosed={appClosed}- onClick={appClosed ? undefined : createAbove}+ connectionState={connectionState}+ onClick={isConnected ? createAbove : undefined}/><div className="flex-1" /><CreateCellButtontooltipContent={renderShortcut("cell.createBelow")}- appClosed={appClosed}- onClick={appClosed ? undefined : createBelow}+ connectionState={connectionState}+ onClick={isConnected ? createBelow : undefined}/></div>);@@ -1029,7 +1039,7 @@ const CellLeftSideActions = (props: {interface CellToolbarProps {edited: boolean;- appClosed: boolean;+ connectionState: WebSocketState;status: RuntimeState;cellConfig: CellConfig;needsRun: boolean;@@ -1045,7 +1055,7 @@ interface CellToolbarProps {const CellToolbar = ({edited,- appClosed,+ connectionState,status,cellConfig,needsRun,@@ -1058,6 +1068,8 @@ const CellToolbar = ({name,includeCellActions = true,}: CellToolbarProps) => {+ const isConnected = isAppConnected(connectionState);+return (<ToolbarclassName={cn(@@ -1067,13 +1079,13 @@ const CellToolbar = ({><RunButtonedited={edited}- onClick={appClosed ? Functions.NOOP : onRun}- appClosed={appClosed}+ onClick={isConnected ? onRun : Functions.NOOP}+ connectionState={connectionState}status={status}config={cellConfig}needsRun={needsRun}/>- <StopButton status={status} appClosed={appClosed} />+ <StopButton status={status} connectionState={connectionState} />{includeCellActions && (<CellActionsDropdownref={cellActionDropdownRef}@@ -1121,7 +1133,7 @@ const SetupCellComponent = ({staleInputs,serializedEditorState,debuggerActive,- appClosed,+ connectionState,canDelete,actions,deleteCell,@@ -1257,7 +1269,7 @@ const SetupCellComponent = ({<div className="absolute right-2 -top-4 z-10"><CellToolbaredited={edited}- appClosed={appClosed}+ connectionState={connectionState}status={status}cellConfig={cellConfig}needsRun={needsRun}@@ -1307,10 +1319,13 @@ const SetupCellComponent = ({<div className="shoulder-bottom hover-action">{canDelete && (<DeleteButton- appClosed={appClosed}+ connectionState={connectionState}status={status}onClick={() => {- if (!loading && !appClosed) {+ if (+ !loading &&+ !isAppInteractionDisabled(connectionState)+ ) {deleteCell({ cellId });}}}diff --git a/frontend/src/components/editor/__tests__/data-attributes.test.tsx b/frontend/src/components/editor/__tests__/data-attributes.test.tsxindex 3edf223e64..98936f6093 100644--- a/frontend/src/components/editor/__tests__/data-attributes.test.tsx+++ b/frontend/src/components/editor/__tests__/data-attributes.test.tsx@@ -9,6 +9,7 @@ import type { UserConfig } from "@/core/config/config-schema";import { TooltipProvider } from "@/components/ui/tooltip";import type { AppMode } from "@/core/mode";import { Functions } from "@/utils/functions";+import { WebSocketState } from "@/core/websocket/types";beforeAll(() => {global.ResizeObserver = class ResizeObserver {@@ -90,7 +91,7 @@ describe("Cell data attributes", () => {serializedEditorState={null}mode={mode as AppMode}debuggerActive={false}- appClosed={false}+ connectionState={WebSocketState.OPEN}canDelete={true}actions={{} as CellComponentActions}userConfig={userConfig}diff --git a/frontend/src/components/editor/cell/CreateCellButton.tsx b/frontend/src/components/editor/cell/CreateCellButton.tsxindex 21c58805fb..bc38da3255 100644--- a/frontend/src/components/editor/cell/CreateCellButton.tsx+++ b/frontend/src/components/editor/cell/CreateCellButton.tsx@@ -13,24 +13,32 @@ import { MarkdownIcon, PythonIcon } from "./code/icons";import { SQLLanguageAdapter } from "@/core/codemirror/language/languages/sql";import { cn } from "@/utils/cn";import { Events } from "@/utils/events";+import type { WebSocketState } from "@/core/websocket/types";+import {+ isAppInteractionDisabled,+ getConnectionTooltip,+} from "@/core/websocket/connection-utils";export const CreateCellButton = ({- appClosed,+ connectionState,onClick,tooltipContent,}: {- appClosed: boolean;+ connectionState: WebSocketState;tooltipContent: React.ReactNode;onClick: ((opts: { code: string }) => void) | undefined;}) => {+ const finalTooltipContent =+ getConnectionTooltip(connectionState) || tooltipContent;+return (<CreateCellButtonContextMenu onClick={onClick}>- <Tooltip content={tooltipContent} usePortal={false}>+ <Tooltip content={finalTooltipContent} usePortal={false}><ButtononClick={() => onClick?.({ code: "" })}className={cn("shoulder-button hover-action",- appClosed && " inactive-button",+ isAppInteractionDisabled(connectionState) && " inactive-button",)}onMouseDown={Events.preventFocus}shape="circle"diff --git a/frontend/src/components/editor/cell/DeleteButton.tsx b/frontend/src/components/editor/cell/DeleteButton.tsxindex e6d5e0dbca..01c54c5f4e 100644--- a/frontend/src/components/editor/cell/DeleteButton.tsx+++ b/frontend/src/components/editor/cell/DeleteButton.tsx@@ -5,19 +5,26 @@ import { Tooltip } from "../../ui/tooltip";import { Button } from "../../ui/button";import { cn } from "@/utils/cn";import { Events } from "@/utils/events";+import type { WebSocketState } from "@/core/websocket/types";+import {+ isAppInteractionDisabled,+ getConnectionTooltip,+} from "@/core/websocket/connection-utils";export const DeleteButton = (props: {status: RuntimeState;- appClosed: boolean;+ connectionState: WebSocketState;onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;}): JSX.Element => {- const { status, appClosed, onClick } = props;+ const { status, connectionState, onClick } = props;const loading = status === "running" || status === "queued";+ const isDisabled = isAppInteractionDisabled(connectionState);let tooltipMsg = null;- if (appClosed) {- tooltipMsg = "App disconnected";++ if (isDisabled) {+ tooltipMsg = getConnectionTooltip(connectionState);} else if (status === "running") {tooltipMsg = "A cell can't be deleted when it's running";} else if (status === "queued") {@@ -39,7 +46,7 @@ export const DeleteButton = (props: {onMouseDown={Events.preventFocus}className={cn("hover:bg-transparent text-destructive/60 hover:text-destructive",- (appClosed || loading) && "inactive-button",+ (isDisabled || loading) && "inactive-button",)}style={{ boxShadow: "none" }}>diff --git a/frontend/src/components/editor/cell/RunButton.tsx b/frontend/src/components/editor/cell/RunButton.tsxindex 08ae9a7efa..7de148aa80 100644--- a/frontend/src/components/editor/cell/RunButton.tsx+++ b/frontend/src/components/editor/cell/RunButton.tsx@@ -3,14 +3,19 @@ import { HardDriveDownloadIcon, PlayIcon } from "lucide-react";import { renderShortcut } from "../../shortcuts/renderShortcut";import type { RuntimeState, CellConfig } from "@/core/network/types";import { ToolbarItem } from "./toolbar";+import type { WebSocketState } from "@/core/websocket/types";+import {+ isAppInteractionDisabled,+ getConnectionTooltip,+} from "@/core/websocket/connection-utils";function computeColor(- appClosed: boolean,+ connectionState: WebSocketState,needsRun: boolean,loading: boolean,inactive: boolean,) {- if (appClosed) {+ if (isAppInteractionDisabled(connectionState)) {return "disabled";}if (needsRun && !loading) {@@ -26,17 +31,19 @@ export const RunButton = (props: {edited: boolean;status: RuntimeState;needsRun: boolean;- appClosed: boolean;+ connectionState: WebSocketState;config: CellConfig;onClick?: () => void;}): JSX.Element => {- const { onClick, appClosed, needsRun, status, config, edited } = props;+ const { onClick, connectionState, needsRun, status, config, edited } = props;const blockedStatus = status === "disabled-transitively";const loading = status === "running" || status === "queued";const inactive =- appClosed || loading || (!config.disabled && blockedStatus && !edited);- const variant = computeColor(appClosed, needsRun, loading, inactive);+ isAppInteractionDisabled(connectionState) ||+ loading ||+ (!config.disabled && blockedStatus && !edited);+ const variant = computeColor(connectionState, needsRun, loading, inactive);if (config.disabled) {return (@@ -66,8 +73,9 @@ export const RunButton = (props: {}let tooltipMsg: React.ReactNode = "";- if (appClosed) {- tooltipMsg = "App disconnected";++ if (isAppInteractionDisabled(connectionState)) {+ tooltipMsg = getConnectionTooltip(connectionState);} else if (status === "queued") {tooltipMsg = "This cell is already queued to run";} else if (status === "running") {diff --git a/frontend/src/components/editor/cell/StopButton.tsx b/frontend/src/components/editor/cell/StopButton.tsxindex 076d2fea55..8911a45e77 100644--- a/frontend/src/components/editor/cell/StopButton.tsx+++ b/frontend/src/components/editor/cell/StopButton.tsx@@ -6,12 +6,14 @@ import { useShouldShowInterrupt } from "./useShouldShowInterrupt";import type { RuntimeState } from "@/core/network/types";import { Functions } from "@/utils/functions";import { ToolbarItem } from "./toolbar";+import type { WebSocketState } from "@/core/websocket/types";+import { isAppInteractionDisabled } from "@/core/websocket/connection-utils";export const StopButton = (props: {status: RuntimeState;- appClosed: boolean;+ connectionState: WebSocketState;}): JSX.Element => {- const { appClosed, status } = props;+ const { connectionState, status } = props;const running = status === "running";@@ -21,7 +23,7 @@ export const StopButton = (props: {return (<ToolbarItemtooltip={renderShortcut("global.interrupt")}- disabled={appClosed || !showInterrupt}+ disabled={isAppInteractionDisabled(connectionState) || !showInterrupt}onClick={showInterrupt ? sendInterrupt : Functions.NOOP}variant={showInterrupt ? "stale" : "disabled"}data-testid="run-button"diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 94619876b9..71236b79b1 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -1,10 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { useEffect } from "react";import { Cell } from "@/components/editor/Cell";-import {- type ConnectionStatus,- WebSocketState,-} from "../../../core/websocket/types";+import type { ConnectionStatus } from "../../../core/websocket/types";import {useNotebook,type CellActions,@@ -194,7 +191,7 @@ const CellColumn: React.FC<{hasSetupCell,onDeleteCell,}) => {- const appClosed = connStatus.state !== WebSocketState.OPEN;+ const connectionState = connStatus.state;return (<Column@@ -236,7 +233,7 @@ const CellColumn: React.FC<{}canDelete={true}mode={mode}- appClosed={appClosed}+ connectionState={connectionState}ref={notebook.cellHandles[SETUP_CELL_ID]}userConfig={userConfig}isCollapsed={false}@@ -269,7 +266,7 @@ const CellColumn: React.FC<{}canDelete={!hasOnlyOneCell}mode={mode}- appClosed={appClosed}+ connectionState={connectionState}ref={notebook.cellHandles[cellId]}userConfig={userConfig}config={cellData.config}diff --git a/frontend/src/components/terminal/terminal.tsx b/frontend/src/components/terminal/terminal.tsxindex 98e45778c9..923d1edd70 100644--- a/frontend/src/components/terminal/terminal.tsx+++ b/frontend/src/components/terminal/terminal.tsx@@ -7,6 +7,8 @@ import "@xterm/xterm/css/xterm.css";import "./xterm.css";import { useRuntimeManager } from "@/core/runtime/config";import { Spinner } from "@/components/icons/spinner";+import { Logger } from "@/utils/Logger";+import { waitForConnectionOpen } from "@/core/network/connection";const TerminalComponent: React.FC<{visible: boolean;@@ -34,20 +36,31 @@ const TerminalComponent: React.FC<{return;}- const socket = new WebSocket(runtimeManager.getTerminalWsURL());- const attachAddon = new AttachAddon(socket);- terminal.loadAddon(attachAddon);+ const connectTerminal = async () => {+ try {+ await waitForConnectionOpen();- const handleDisconnect = () => {- onClose();- // Reset- attachAddon.dispose();- terminal.clear();- setInitialized(false);+ const socket = new WebSocket(runtimeManager.getTerminalWsURL());+ const attachAddon = new AttachAddon(socket);+ terminal.loadAddon(attachAddon);++ const handleDisconnect = () => {+ onClose();+ // Reset+ attachAddon.dispose();+ terminal.clear();+ setInitialized(false);+ };++ socket.addEventListener("close", handleDisconnect);+ setInitialized(true);+ } catch (error) {+ Logger.error("Runtime health check failed for terminal", error);+ onClose();+ }};- socket.addEventListener("close", handleDisconnect);- setInitialized(true);+ connectTerminal();return () => {// noopdiff --git a/frontend/src/core/cells/__tests__/session.test.ts b/frontend/src/core/cells/__tests__/session.test.tsindex 045c432338..fa3b9719d0 100644--- a/frontend/src/core/cells/__tests__/session.test.ts+++ b/frontend/src/core/cells/__tests__/session.test.ts@@ -83,9 +83,6 @@ describe("notebookStateFromSession", () => {describe("validation", () => {it("logs error for both session and notebook null/undefined", () => {const result = notebookStateFromSession(null, null);- expect(Logger.error).toHaveBeenCalledWith(- "Both session and notebook are null/undefined",- );expect(result).toBeNull();});diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex e5a8a5b3ed..7284ccbc32 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -1491,7 +1491,7 @@ export const columnIdsAtom = atom((get) =>export const getAllEditorViews = () => {const { cellIds, cellHandles } = store.get(notebookAtom);return cellIds.inOrderIds- .map((cellId) => cellHandles[cellId].current?.editorView)+ .map((cellId) => cellHandles[cellId]?.current?.editorView).filter(Boolean);};diff --git a/frontend/src/core/cells/session.ts b/frontend/src/core/cells/session.tsindex f3c8cade25..cc46b71a65 100644--- a/frontend/src/core/cells/session.ts+++ b/frontend/src/core/cells/session.ts@@ -30,7 +30,7 @@ function validateSessionNotebookCompatibility(if (!session && !notebook) {return {isValid: false,- error: "Both session and notebook are null/undefined",+ error: "",};}diff --git a/frontend/src/core/codemirror/ai/request.ts b/frontend/src/core/codemirror/ai/request.tsindex e787623de6..429e7d904c 100644--- a/frontend/src/core/codemirror/ai/request.ts+++ b/frontend/src/core/codemirror/ai/request.ts@@ -3,6 +3,7 @@import { getRuntimeManager } from "@/core/runtime/config";import type { LanguageAdapterType } from "../language/types";import type { AiCompletionRequest } from "@/core/network/types";+import { waitForConnectionOpen } from "@/core/network/connection";/*** Request to edit code with AI@@ -27,6 +28,8 @@ ${opts.codeAfter}const runtimeManager = getRuntimeManager();+ await waitForConnectionOpen();+const response = await fetch(runtimeManager.getAiURL("completion").toString(),{diff --git a/frontend/src/core/codemirror/language/languages/python.ts b/frontend/src/core/codemirror/language/languages/python.tsindex 85364212cb..d3db46511b 100644--- a/frontend/src/core/codemirror/language/languages/python.ts+++ b/frontend/src/core/codemirror/language/languages/python.ts@@ -41,12 +41,21 @@ import { Logger } from "@/utils/Logger";import { CellDocumentUri } from "../../lsp/types";import { hasCapability } from "@/core/config/capabilities";import { getRuntimeManager } from "@/core/runtime/config";+import { waitForConnectionOpen } from "@/core/network/connection";const pylspTransport = once(() => {const runtimeManager = getRuntimeManager();const transport = new WebSocketTransport(runtimeManager.getLSPURL("pylsp").toString(),);++ // Override connect to ensure runtime is healthy+ const originalConnect = transport.connect.bind(transport);+ transport.connect = async () => {+ await waitForConnectionOpen();+ return originalConnect();+ };+return transport;});diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.tsindex b2d16e6a97..5db1c6c770 100644--- a/frontend/src/core/runtime/__tests__/runtime.test.ts+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts@@ -199,30 +199,35 @@ describe("RuntimeManager", () => {describe("waitForHealthy", () => {it("should resolve immediately if healthy", async () => {- const runtime = new RuntimeManager(mockConfig);+ const runtime = new RuntimeManager(mockConfig, true);+vi.spyOn(runtime, "isHealthy").mockResolvedValue(true);+ runtime.init();await expect(runtime.waitForHealthy()).resolves.toBeUndefined();});it("should retry and eventually succeed", async () => {- const runtime = new RuntimeManager(mockConfig);+ const runtime = new RuntimeManager(mockConfig, true);const healthySpy = vi.spyOn(runtime, "isHealthy").mockResolvedValueOnce(false).mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ runtime.init({ disableRetryDelay: true });+await expect(runtime.waitForHealthy()).resolves.toBeUndefined();expect(healthySpy).toHaveBeenCalledTimes(3);});- it.skip("should throw after max retries", async () => {- const runtime = new RuntimeManager(mockConfig);+ it("should throw after max retries", async () => {+ const runtime = new RuntimeManager(mockConfig, true);vi.spyOn(runtime, "isHealthy").mockResolvedValue(false);+ runtime.init({ disableRetryDelay: true });await expect(runtime.waitForHealthy()).rejects.toThrow(- "Failed to connect after 5 retries",+ "Failed to connect after 6 retries",);});});diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.tsindex 8e080b5e9d..b178470d76 100644--- a/frontend/src/core/runtime/runtime.ts+++ b/frontend/src/core/runtime/runtime.ts@@ -4,9 +4,15 @@ import type { RuntimeConfig } from "./types";import { Logger } from "@/utils/Logger";import { getSessionId, type SessionId } from "../kernel/session";import { KnownQueryParams } from "../constants";+import { Deferred } from "@/utils/Deferred";export class RuntimeManager {- constructor(private config: RuntimeConfig) {+ private initialHealthyCheck = new Deferred<void>();++ constructor(+ private config: RuntimeConfig,+ private lazy = false,+ ) {// Validate the URL on constructiontry {new URL(this.config.url);@@ -15,12 +21,20 @@ export class RuntimeManager {`Invalid runtime URL: ${this.config.url}. ${error instanceof Error ? error.message : "Unknown error"}`,);}++ if (!this.lazy) {+ this.init();+ }}get httpURL(): URL {return new URL(this.config.url);}+ get isSameOrigin(): boolean {+ return this.httpURL.origin === window.location.origin;+ }+/*** The base URL of the runtime.*/@@ -108,29 +122,41 @@ export class RuntimeManager {try {const response = await fetch(this.healthURL().toString());return response.ok;- } catch (error) {- Logger.error("Failed to check health", error);+ } catch {return false;}}- /**- * Wait for the runtime to be healthy.- * @throws if the runtime is not healthy after 5 retries- */- async waitForHealthy(): Promise<void> {+ async init(options?: {+ disableRetryDelay?: boolean;+ }) {let retries = 0;- const maxRetries = 5;+ const maxRetries = 6;const baseDelay = 1000;while (!(await this.isHealthy())) {if (retries >= maxRetries) {- throw new Error("Failed to connect after 5 retries");+ Logger.error(`Failed to connect after ${maxRetries} retries`);+ this.initialHealthyCheck.reject(+ new Error(`Failed to connect after ${maxRetries} retries`),+ );+ return;+ }+ if (!options?.disableRetryDelay) {+ const delay = baseDelay * 2 ** retries;+ await new Promise((resolve) => setTimeout(resolve, delay));}- const delay = baseDelay * 2 ** retries;- await new Promise((resolve) => setTimeout(resolve, delay));retries++;}++ this.initialHealthyCheck.resolve();+ }++ /**+ * Wait for the runtime to be healthy.+ */+ async waitForHealthy(): Promise<void> {+ return this.initialHealthyCheck.promise;}headers(): Record<string, string> {diff --git a/frontend/src/core/websocket/connection-utils.ts b/frontend/src/core/websocket/connection-utils.tsnew file mode 100644index 0000000000..01b818a7fa--- /dev/null+++ b/frontend/src/core/websocket/connection-utils.ts@@ -0,0 +1,59 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { WebSocketState } from "./types";++/**+ * Check if the app is in a closed/disconnected state+ */+export function isAppClosed(state: WebSocketState): boolean {+ return state === WebSocketState.CLOSED;+}++/**+ * Check if the app is in a connecting state+ */+export function isAppConnecting(state: WebSocketState): boolean {+ return state === WebSocketState.CONNECTING;+}++/**+ * Check if the app is in an open/connected state+ */+export function isAppConnected(state: WebSocketState): boolean {+ return state === WebSocketState.OPEN;+}++/**+ * Check if the app is in a closing state+ */+export function isAppClosing(state: WebSocketState): boolean {+ return state === WebSocketState.CLOSING;+}++/**+ * Check if the app is in a state where user interactions should be disabled+ */+export function isAppInteractionDisabled(state: WebSocketState): boolean {+ return (+ state === WebSocketState.CLOSED ||+ state === WebSocketState.CLOSING ||+ state === WebSocketState.CONNECTING+ );+}++/**+ * Get a human-readable tooltip message for the connection state+ */+export function getConnectionTooltip(state: WebSocketState): string {+ switch (state) {+ case WebSocketState.CLOSED:+ return "App disconnected";+ case WebSocketState.CONNECTING:+ return "App connecting...";+ case WebSocketState.CLOSING:+ return "App disconnecting...";+ case WebSocketState.OPEN:+ return "";+ default:+ return "";+ }+}diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 9dc2efa5ff..87090c01e1 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -287,6 +287,13 @@ export function useMarimoWebSocket(opts: {setConnection({ state: WebSocketState.OPEN });},+ waitToConnect: async () => {+ if (runtimeManager.isSameOrigin) {+ return;+ }+ await runtimeManager.waitForHealthy();+ },+/*** Message callback. Handle messages sent by the kernel.*/diff --git a/frontend/src/core/websocket/useWebSocket.tsx b/frontend/src/core/websocket/useWebSocket.tsxindex 5dee7275fb..c82fd52bb8 100644--- a/frontend/src/core/websocket/useWebSocket.tsx+++ b/frontend/src/core/websocket/useWebSocket.tsx@@ -6,10 +6,12 @@ import { StaticWebsocket } from "./StaticWebsocket";import { isWasm } from "../wasm/utils";import { PyodideBridge, PyodideWebsocket } from "../wasm/bridge";import { Logger } from "@/utils/Logger";+import { isStaticNotebook } from "../static/static-state";interface UseWebSocketOptions {url: string;static: boolean;+ waitToConnect?: () => Promise<void>;onOpen?: (event: WebSocketEventMap["open"]) => void;onMessage?: (event: WebSocketEventMap["message"]) => void;onClose?: (event: WebSocketEventMap["close"]) => void;@@ -22,7 +24,8 @@ interface UseWebSocketOptions {* We use the WebSocket from partysocket, which is a wrapper around the native WebSocket API with reconnect logic.*/export function useWebSocket(options: UseWebSocketOptions) {- const { onOpen, onMessage, onClose, onError, ...rest } = options;+ const { onOpen, onMessage, onClose, onError, waitToConnect, ...rest } =+ options;// eslint-disable-next-line react/hook-use-stateconst [ws] = useState<IReconnectingWebSocket>(() => {@@ -52,7 +55,14 @@ export function useWebSocket(options: UseWebSocketOptions) {// If it's closed, reconnect// This starts closed, so we need to connect for the first timeif (ws.readyState === WebSocket.CLOSED) {- ws.reconnect();+ // Ignore waitToConnect for static and wasm notebooks+ if (waitToConnect && !isStaticNotebook() && !isWasm()) {+ waitToConnect().then(() => {+ ws.reconnect();+ });+ } else {+ ws.reconnect();+ }}return () => {diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 47c8cbabe1..7d23bb3b1b 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -6,6 +6,7 @@ import type { CellId } from "../core/cells/ids";import { Logger } from "@/utils/Logger";import type { Milliseconds, Seconds } from "@/utils/time";import { defaultUserConfig } from "@/core/config/config-schema";+import { WebSocketState } from "@/core/websocket/types";const meta: Meta<typeof Cell> = {title: "Cell",@@ -35,7 +36,7 @@ const props: CellProps = {serializedEditorState: null,mode: "edit",name: "cell_1",- appClosed: false,+ connectionState: WebSocketState.OPEN,canDelete: true,allowFocus: false,debuggerActive: false,diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 777bfd7fce..48c318a310 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -353,6 +353,13 @@ edit_help_msg = "\n".join(type=bool,help="Enable skew protection middleware to prevent version mismatch issues.",)+ "--remote-url",+ default=None,+ type=str,+ hidden=True,+ help="Remote URL for runtime configuration.",+)@click.argument("name",required=False,@@ -373,6 +380,7 @@ def edit(profile_dir: Optional[str],watch: bool,skew_protection: bool,+ remote_url: Optional[str],name: Optional[str],args: tuple[str, ...],) -> None:@@ -464,6 +472,7 @@ def edit(allow_origins=allow_origins,redirect_console_to_browser=True,ttl_seconds=None,+ remote_url=remote_url,)diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.pyindex cc8b4afff1..38ee98dfb7 100644--- a/marimo/_server/api/deps.py+++ b/marimo/_server/api/deps.py@@ -97,6 +97,10 @@ class AppStateBase:def skew_protection_token(self) -> SkewProtectionToken:return self.session_manager.skew_protection_token+ @property+ def remote_url(self) -> Optional[str]:+ return getattr(self.state, "remote_url", None)+class AppState(AppStateBase):"""The app state with a request."""diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex 98ab50447f..c16f92b174 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -111,6 +111,7 @@ async def index(request: Request) -> HTMLResponse:app_config=app_config,filename=app_manager.filename,mode=app_state.mode,+ remote_url=app_state.remote_url,)# Inject service worker registration with the notebook IDdiff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex 3fd27747ed..ae69ded7ff 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -89,6 +89,7 @@ def start(auth_token: Optional[AuthToken],redirect_console_to_browser: bool,skew_protection: bool,+ remote_url: Optional[str] = None,) -> None:"""Start the server.@@ -190,6 +191,7 @@ def start(app.state.session_manager = session_managerapp.state.base_url = base_urlapp.state.config_manager = config_reader+ app.state.remote_url = remote_url# Resource initialization# Increase the limit on open file descriptors to prevent resourcediff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 594a5b7304..18603f13f9 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -4,12 +4,14 @@ from __future__ import annotationsimport htmlimport jsonimport os+from pathlib import Pathfrom textwrap import dedentfrom typing import Any, Literal, Optional, Union, castfrom marimo import __version__from marimo._ast.app_config import _AppConfigfrom marimo._config.config import MarimoConfig, PartialMarimoConfig+from marimo._convert.converters import MarimoConvertfrom marimo._output.utils import uri_encode_componentfrom marimo._schemas.notebook import NotebookV1from marimo._schemas.session import NotebookSessionV1@@ -39,6 +41,7 @@ def _get_mount_config(show_app_code: bool = True,session_snapshot: Optional[NotebookSessionV1] = None,notebook_snapshot: Optional[NotebookV1] = None,+ remote_url: Optional[str] = None,) -> str:"""Return a JSON string with custom indentation and sorting.@@ -59,6 +62,7 @@ def _get_mount_config(},"notebook": notebook_snapshot,"session": session_snapshot,+ "runtime_config": [{"url": remote_url}] if remote_url else None,}return """{{@@ -72,6 +76,7 @@ def _get_mount_config("view": {view},"notebook": {notebook},"session": {session},+ "runtimeConfig": {runtime_config},}}""".format(**{k: json.dumps(v, sort_keys=True) for k, v in options.items()}@@ -98,6 +103,7 @@ def home_page_template(user_config=user_config,config_overrides=config_overrides,app_config=None,+ remote_url=None,),)@@ -116,9 +122,20 @@ def notebook_page_template(app_config: _AppConfig,filename: Optional[str],mode: SessionMode,+ remote_url: Optional[str] = None,) -> str:html = html.replace("{{ base_url }}", base_url)+ # When we have a remote URL, let's pre-populate the index.html page+ # with a view of the notebook.+ notebook_snapshot = None+ if remote_url and filename:+ filepath = Path(filename)+ if filepath.exists():+ notebook_snapshot = MarimoConvert.from_py(+ filepath.read_text(encoding="utf-8")+ ).to_notebook_v1()+html = html.replace("{{ filename }}", _html_escape(filename or ""))html = html.replace(MOUNT_CONFIG_TEMPLATE,@@ -129,6 +146,8 @@ def notebook_page_template(user_config=user_config,config_overrides=config_overrides,app_config=app_config,+ remote_url=remote_url,+ notebook_snapshot=notebook_snapshot,),)@@ -201,6 +220,7 @@ def static_notebook_template(app_config=app_config,session_snapshot=session_snapshot,notebook_snapshot=notebook_snapshot,+ remote_url=None,),)@@ -325,6 +345,7 @@ def wasm_notebook_template(app_config=app_config,version=version,show_app_code=show_code,+ remote_url=None,),)diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txtindex 5f352d0bed..a768b4d87c 100644--- a/tests/_server/templates/snapshots/export1.txt+++ b/tests/_server/templates/snapshots/export1.txt@@ -65,6 +65,7 @@"view": {"showAppCode": true},"notebook": {"cells": [{"code": "print('Hello, Cell 1')", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},"session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "runtimeConfig": null,};</script><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txtindex 8510c208ad..4ab724b425 100644--- a/tests/_server/templates/snapshots/export2.txt+++ b/tests/_server/templates/snapshots/export2.txt@@ -65,6 +65,7 @@"view": {"showAppCode": true},"notebook": {"cells": [{"code": "print('Hello, Cell 1')", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},"session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "runtimeConfig": null,};</script><title>marimo</title>diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txtindex 37f02631a3..ce2a10e2e1 100644--- a/tests/_server/templates/snapshots/export3.txt+++ b/tests/_server/templates/snapshots/export3.txt@@ -65,6 +65,7 @@"view": {"showAppCode": true},"notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},"session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "runtimeConfig": null,};</script><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txtindex 8bf5ea6f2a..586a359c2f 100644--- a/tests/_server/templates/snapshots/export4.txt+++ b/tests/_server/templates/snapshots/export4.txt@@ -65,6 +65,7 @@"view": {"showAppCode": true},"notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},"session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "runtimeConfig": null,};</script><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txtindex edd17ebe72..b085d380ea 100644--- a/tests/_server/templates/snapshots/export5.txt+++ b/tests/_server/templates/snapshots/export5.txt@@ -65,6 +65,7 @@"view": {"showAppCode": true},"notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},"session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "runtimeConfig": null,};</script><title>My App</title>diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txtindex 59efc653c2..46afed2927 100644--- a/tests/_server/templates/snapshots/export6.txt+++ b/tests/_server/templates/snapshots/export6.txt@@ -65,6 +65,7 @@"view": {"showAppCode": true},"notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},"session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},+ "runtimeConfig": null,};</script><title>notebook</title>