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(frontend): make disconnect indicator clickable to reconnect (#9410)

Vaibhav Aggarwalb040213a8ede
diff --git a/frontend/package.json b/frontend/package.json
index d278d057d0..f91118ec43 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -120,7 +120,7 @@
"lz-string": "^1.5.0",
"marked": "^15.0.12",
"mermaid": "^11.12.3",
- "partysocket": "1.1.10",
+ "partysocket": "1.1.13",
"path-to-regexp": "^8.4.0",
"plotly.js": "^3.3.1",
"pyodide": "0.27.7",
diff --git a/frontend/src/components/editor/app-container.tsx b/frontend/src/components/editor/app-container.tsx
index a50a915681..a5a5dac556 100644
--- a/frontend/src/components/editor/app-container.tsx
+++ b/frontend/src/components/editor/app-container.tsx
@@ -15,6 +15,7 @@ interface Props {
connection: ConnectionStatus;
isRunning: boolean;
width: AppConfig["width"];
+ onReconnect?: () => void;
}
export const AppContainer: React.FC<PropsWithChildren<Props>> = ({
@@ -22,13 +23,18 @@ export const AppContainer: React.FC<PropsWithChildren<Props>> = ({
connection,
isRunning,
children,
+ onReconnect,
}) => {
const connectionState = connection.state;
return (
<>
<DynamicFavicon isRunning={isRunning} />
- <StatusOverlay connection={connection} isRunning={isRunning} />
+ <StatusOverlay
+ connection={connection}
+ isRunning={isRunning}
+ onReconnect={onReconnect}
+ />
<PyodideLoader>
<WrappedWithSidebar>
{/** oxlint-ignore-next-line -- ID is used by other components to grab the DOM element */}
diff --git a/frontend/src/components/editor/header/__tests__/status.test.tsx b/frontend/src/components/editor/header/__tests__/status.test.tsx
new file mode 100644
index 0000000000..7a811d52e1
--- /dev/null
+++ b/frontend/src/components/editor/header/__tests__/status.test.tsx
@@ -0,0 +1,108 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+// @vitest-environment jsdom
+
+import { fireEvent, render } from "@testing-library/react";
+import { createStore, Provider as JotaiProvider } from "jotai";
+import type React from "react";
+import { describe, expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { viewStateAtom } from "@/core/mode";
+import {
+ type ConnectionStatus,
+ WebSocketClosedReason,
+ WebSocketState,
+} from "@/core/websocket/types";
+import { StatusOverlay } from "../status";
+
+function renderOverlay(
+ connection: ConnectionStatus,
+ onReconnect?: () => void,
+): ReturnType<typeof render> {
+ const store = createStore();
+ store.set(viewStateAtom, { mode: "edit", cellAnchor: null });
+ const wrapper: React.FC<React.PropsWithChildren> = ({ children }) => (
+ <JotaiProvider store={store}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </JotaiProvider>
+ );
+ return render(
+ <StatusOverlay
+ connection={connection}
+ isRunning={false}
+ onReconnect={onReconnect}
+ />,
+ { wrapper },
+ );
+}
+
+describe("StatusOverlay disconnect indicator", () => {
+ it("invokes onReconnect when the disconnect icon is clicked", () => {
+ const onReconnect = vi.fn();
+ const { getByTestId } = renderOverlay(
+ {
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,
+ reason: "kernel not found",
+ },
+ onReconnect,
+ );
+
+ const icon = getByTestId("disconnected-indicator") as HTMLButtonElement;
+ expect(icon.tagName).toBe("BUTTON");
+ expect(icon.disabled).toBe(false);
+ expect(icon.getAttribute("aria-label")).toBe("Reconnect to app");
+ fireEvent.click(icon);
+ expect(onReconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it("renders a disabled button when no onReconnect is provided", () => {
+ const { getByTestId } = renderOverlay({
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,
+ reason: "kernel not found",
+ });
+
+ const button = getByTestId("disconnected-indicator");
+ expect((button as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ it.each([
+ [
+ WebSocketClosedReason.MALFORMED_QUERY,
+ "the kernel did not recognize a request; please file a bug with marimo",
+ ],
+ [
+ WebSocketClosedReason.KERNEL_STARTUP_ERROR,
+ "Failed to start kernel sandbox",
+ ],
+ ])(
+ "renders a disabled button for non-recoverable close reason %s",
+ (code, reason) => {
+ const onReconnect = vi.fn();
+ const { getByTestId } = renderOverlay(
+ { state: WebSocketState.CLOSED, code, reason },
+ onReconnect,
+ );
+
+ const button = getByTestId("disconnected-indicator") as HTMLButtonElement;
+ expect(button.disabled).toBe(true);
+ fireEvent.click(button);
+ expect(onReconnect).not.toHaveBeenCalled();
+ },
+ );
+
+ it("does not render the disconnect icon when another tab has taken over", () => {
+ const onReconnect = vi.fn();
+ const { queryByTestId } = renderOverlay(
+ {
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.ALREADY_RUNNING,
+ reason: "another browser tab is already connected to the kernel",
+ canTakeover: true,
+ },
+ onReconnect,
+ );
+
+ expect(queryByTestId("disconnected-indicator")).toBeNull();
+ });
+});
diff --git a/frontend/src/components/editor/header/status.tsx b/frontend/src/components/editor/header/status.tsx
index 28d91ea24d..d4f609b770 100644
--- a/frontend/src/components/editor/header/status.tsx
+++ b/frontend/src/components/editor/header/status.tsx
@@ -7,16 +7,26 @@ import { Tooltip } from "@/components/ui/tooltip";
import { notebookScrollToRunning } from "@/core/cells/actions";
import { onlyScratchpadIsRunningAtom } from "@/core/cells/cells";
import { viewStateAtom } from "@/core/mode";
-import { type ConnectionStatus, WebSocketState } from "@/core/websocket/types";
+import {
+ type ConnectionStatus,
+ WebSocketClosedReason,
+ WebSocketState,
+} from "@/core/websocket/types";
import { cn } from "@/utils/cn";
export const StatusOverlay: React.FC<{
connection: ConnectionStatus;
isRunning: boolean;
-}> = ({ connection, isRunning }) => {
+ onReconnect?: () => void;
+}> = ({ connection, isRunning, onReconnect }) => {
const { mode } = useAtomValue(viewStateAtom);
const isClosed = connection.state === WebSocketState.CLOSED;
const isOpen = connection.state === WebSocketState.OPEN;
+ // Only KERNEL_DISCONNECTED is recoverable by a retry. Other terminal
+ // reasons (MALFORMED_QUERY, KERNEL_STARTUP_ERROR) would deterministically
+ // fail the same way; ALREADY_RUNNING is handled by `LockedIcon` below.
+ const canReconnect =
+ isClosed && connection.code === WebSocketClosedReason.KERNEL_DISCONNECTED;
return (
<>
@@ -28,7 +38,11 @@ export const StatusOverlay: React.FC<{
)}
>
{isOpen && isRunning && <RunningIcon />}
- {isClosed && !connection.canTakeover && <DisconnectedIcon />}
+ {isClosed && !connection.canTakeover && (
+ <DisconnectedIcon
+ onReconnect={canReconnect ? onReconnect : undefined}
+ />
+ )}
{isClosed && connection.canTakeover && <LockedIcon />}
</div>
</>
@@ -37,13 +51,33 @@ export const StatusOverlay: React.FC<{
const topLeftStatus = "print:hidden pointer-events-auto hover:cursor-pointer";
-const DisconnectedIcon = () => (
- <Tooltip content="App disconnected">
- <div className={topLeftStatus}>
- <UnlinkIcon className="w-[25px] h-[25px] text-(--red-11)" />
- </div>
- </Tooltip>
-);
+const DisconnectedIcon: React.FC<{ onReconnect?: () => void }> = ({
+ onReconnect,
+}) => {
+ const disabled = !onReconnect;
+ return (
+ <Tooltip
+ content={
+ disabled ? "App disconnected" : "App disconnected — click to reconnect"
+ }
+ >
+ {/* Wrapper span keeps the tooltip reachable when the button is
+ disabled — a disabled <button> swallows pointer events. */}
+ <span tabIndex={disabled ? 0 : -1}>
+ <button
+ type="button"
+ className={cn(topLeftStatus, "bg-transparent border-0 p-0")}
+ aria-label={disabled ? "App disconnected" : "Reconnect to app"}
+ data-testid="disconnected-indicator"
+ onClick={onReconnect}
+ disabled={disabled}
+ >
+ <UnlinkIcon className="w-[25px] h-[25px] text-(--red-11)" />
+ </button>
+ </span>
+ </Tooltip>
+ );
+};
const LockedIcon = () => (
<Tooltip content="Notebook locked">
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 968bd85045..716be3e607 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -79,7 +79,7 @@ export const EditApp: React.FC<AppProps> = ({
};
}, []);
- const { connection } = useMarimoKernelConnection({
+ const { connection, reconnect } = useMarimoKernelConnection({
autoInstantiate: userConfig.runtime.auto_instantiate,
setCells: (cells, layout) => {
setCells(cells);
@@ -147,6 +147,7 @@ export const EditApp: React.FC<AppProps> = ({
connection={connection}
isRunning={isRunning}
width={appConfig.width}
+ onReconnect={reconnect}
>
<AppHeader
connection={connection}
diff --git a/frontend/src/core/run-app.tsx b/frontend/src/core/run-app.tsx
index a50aceabf8..30a53e4abf 100644
--- a/frontend/src/core/run-app.tsx
+++ b/frontend/src/core/run-app.tsx
@@ -38,7 +38,7 @@ export const RunApp: React.FC<AppProps> = ({ appConfig }) => {
};
}, []);
- const { connection } = useMarimoKernelConnection({
+ const { connection, reconnect } = useMarimoKernelConnection({
autoInstantiate: true,
setCells: setCells,
sessionId: getSessionId(),
@@ -84,6 +84,7 @@ export const RunApp: React.FC<AppProps> = ({ appConfig }) => {
connection={connection}
isRunning={isRunning}
width={appConfig.width}
+ onReconnect={reconnect}
>
<AppHeader connection={connection} className="sm:pt-8">
{galleryHref && (
diff --git a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx
new file mode 100644
index 0000000000..3dab479f2c
--- /dev/null
+++ b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx
@@ -0,0 +1,155 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+// @vitest-environment jsdom
+
+import { act, renderHook } from "@testing-library/react";
+import { createStore, Provider as JotaiProvider } from "jotai";
+import type React from "react";
+import { ErrorBoundary } from "react-error-boundary";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/core/websocket/useWebSocket", async () => {
+ const actual =
+ await vi.importActual<typeof import("../useWebSocket")>("../useWebSocket");
+ return {
+ ...actual,
+ useConnectionTransport: vi.fn(),
+ };
+});
+
+vi.mock("@/core/runtime/config", async () => {
+ const actual = await vi.importActual<typeof import("@/core/runtime/config")>(
+ "@/core/runtime/config",
+ );
+ return {
+ ...actual,
+ useRuntimeManager: vi.fn(),
+ };
+});
+
+import { useRuntimeManager } from "@/core/runtime/config";
+import { connectionAtom } from "../../network/connection";
+import type { SessionId } from "../../kernel/session";
+import { WebSocketClosedReason, WebSocketState } from "../types";
+import { useMarimoKernelConnection } from "../useMarimoKernelConnection";
+import { useConnectionTransport } from "../useWebSocket";
+
+interface MockTransport {
+ readyState: 0 | 1 | 2 | 3;
+ retryCount: number;
+ reconnect: ReturnType<typeof vi.fn>;
+ close: ReturnType<typeof vi.fn>;
+ send: ReturnType<typeof vi.fn>;
+ addEventListener: ReturnType<typeof vi.fn>;
+ removeEventListener: ReturnType<typeof vi.fn>;
+}
+
+function makeTransport(
+ readyState: 0 | 1 | 2 | 3 = WebSocket.CLOSED,
+): MockTransport {
+ return {
+ readyState,
+ retryCount: 0,
+ reconnect: vi.fn(),
+ close: vi.fn(),
+ send: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ };
+}
+
+function makeRuntimeManager(isHealthy = vi.fn().mockResolvedValue(true)) {
+ return {
+ isHealthy,
+ getWsURL: () => new URL("ws://localhost/ws"),
+ waitForHealthy: vi.fn().mockResolvedValue(undefined),
+ isSameOrigin: true,
+ };
+}
+
+describe("useMarimoKernelConnection.reconnect()", () => {
+ let transport: MockTransport;
+ let isHealthy: ReturnType<typeof vi.fn>;
+ let store: ReturnType<typeof createStore>;
+
+ beforeEach(() => {
+ transport = makeTransport(WebSocket.CLOSED);
+ isHealthy = vi.fn().mockResolvedValue(true);
+ store = createStore();
+ store.set(connectionAtom, {
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,
+ reason: "kernel not found",
+ });
+ vi.mocked(useConnectionTransport).mockReturnValue(transport);
+ vi.mocked(useRuntimeManager).mockReturnValue(
+ makeRuntimeManager(isHealthy) as unknown as ReturnType<
+ typeof useRuntimeManager
+ >,
+ );
+ });
+
+ function renderUseHook() {
+ const wrapper: React.FC<React.PropsWithChildren> = ({ children }) => (
+ <JotaiProvider store={store}>
+ <ErrorBoundary fallback={null}>{children}</ErrorBoundary>
+ </JotaiProvider>
+ );
+ return renderHook(
+ () =>
+ useMarimoKernelConnection({
+ sessionId: "test-session" as SessionId,
+ autoInstantiate: false,
+ setCells: () => {},
+ }),
+ { wrapper },
+ );
+ }
+
+ it("is a no-op when the transport is already OPEN", async () => {
+ transport.readyState = WebSocket.OPEN;
+ const { result } = renderUseHook();
+ await act(async () => {
+ await result.current.reconnect();
+ });
+ expect(isHealthy).not.toHaveBeenCalled();
+ expect(transport.reconnect).not.toHaveBeenCalled();
+ });
+
+ it("is a no-op when the transport is already CONNECTING", async () => {
+ transport.readyState = WebSocket.CONNECTING;
+ const { result } = renderUseHook();
+ await act(async () => {
+ await result.current.reconnect();
+ });
+ expect(isHealthy).not.toHaveBeenCalled();
+ expect(transport.reconnect).not.toHaveBeenCalled();
+ });
+
+ it("probes /health and reconnects when the runtime is healthy", async () => {
+ isHealthy.mockResolvedValue(true);
+ const { result } = renderUseHook();
+ await act(async () => {
+ await result.current.reconnect();
+ });
+ expect(isHealthy).toHaveBeenCalledOnce();
+ expect(transport.reconnect).toHaveBeenCalledOnce();
+ expect(store.get(connectionAtom)).toEqual({
+ state: WebSocketState.CONNECTING,
+ });
+ });
+
+ it("transitions to CLOSED and does not call ws.reconnect when the probe fails", async () => {
+ isHealthy.mockResolvedValue(false);
+ const { result } = renderUseHook();
+ await act(async () => {
+ await result.current.reconnect();
+ });
+ expect(isHealthy).toHaveBeenCalledOnce();
+ expect(transport.reconnect).not.toHaveBeenCalled();
+ expect(store.get(connectionAtom)).toEqual({
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,
+ reason: "kernel not found",
+ });
+ });
+});
diff --git a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts
new file mode 100644
index 0000000000..523ee94dcb
--- /dev/null
+++ b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts
@@ -0,0 +1,137 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Logger } from "@/utils/Logger";
+import { WebSocketClosedReason, WebSocketState } from "../types";
+import { classifyCloseEvent } from "../useMarimoKernelConnection";
+import { MAX_RETRIES } from "../useWebSocket";
+
+function classify(
+ reason: string | undefined,
+ retryCount = 0,
+ maxRetries = MAX_RETRIES,
+) {
+ return classifyCloseEvent({ reason }, { retryCount, maxRetries });
+}
+
+describe("classifyCloseEvent", () => {
+ describe("transient closes (default branch)", () => {
+ it("retries when retryCount < maxRetries", () => {
+ const decision = classify(undefined, 0);
+ expect(decision.kind).toBe("retry");
+ expect(decision.status).toEqual({ state: WebSocketState.CONNECTING });
+ });
+
+ it("retries on each intermediate close event during a retry storm", () => {
+ for (let n = 0; n < MAX_RETRIES; n++) {
+ const decision = classify(undefined, n);
+ expect(decision.kind).toBe("retry");
+ expect(decision.status).toEqual({ state: WebSocketState.CONNECTING });
+ }
+ });
+
+ it("transitions to CLOSED when retryCount reaches maxRetries", () => {
+ const decision = classify(undefined, MAX_RETRIES);
+ expect(decision.kind).toBe("gave-up");
+ expect(decision.status).toEqual({
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,
+ reason: "kernel not found",
+ });
+ });
+
+ it("transitions to CLOSED when retryCount exceeds maxRetries", () => {
+ const decision = classify(undefined, MAX_RETRIES + 5);
+ expect(decision.kind).toBe("gave-up");
+ });
+
+ it("treats unknown reason strings as transient and logs a warning", () => {
+ const logger = vi.spyOn(Logger, "warn").mockImplementation(() => {});
+ const decision = classify("something-else", 3);
+ expect(decision.kind).toBe("retry");
+ expect(logger).toHaveBeenCalled();
+ logger.mockRestore();
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ describe("terminal closes (server-initiated)", () => {
+ it("MARIMO_ALREADY_CONNECTED → terminal + closeTransport, with takeover", () => {
+ const decision = classify("MARIMO_ALREADY_CONNECTED", 0);
+ expect(decision.kind).toBe("terminal");
+ expect(decision.status).toMatchObject({
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.ALREADY_RUNNING,
+ canTakeover: true,
+ });
+ if (decision.kind === "terminal") {
+ expect(decision.closeTransport).toBe(true);
+ }
+ });
+
+ it.each([
+ "MARIMO_WRONG_KERNEL_ID",
+ "MARIMO_NO_FILE_KEY",
+ "MARIMO_NO_SESSION_ID",
+ "MARIMO_NO_SESSION",
+ "MARIMO_SHUTDOWN",
+ ])("%s → terminal with KERNEL_DISCONNECTED, closes transport", (reason) => {
+ const decision = classify(reason, 0);
+ expect(decision.kind).toBe("terminal");
+ expect(decision.status).toMatchObject({
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,
+ });
+ if (decision.kind === "terminal") {
+ expect(decision.closeTransport).toBe(true);
+ }
+ });
+
+ it("MARIMO_MALFORMED_QUERY → terminal but does NOT close transport", () => {
+ const decision = classify("MARIMO_MALFORMED_QUERY", 0);
+ expect(decision.kind).toBe("terminal");
+ expect(decision.status).toMatchObject({
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.MALFORMED_QUERY,
+ });
+ if (decision.kind === "terminal") {
+ expect(decision.closeTransport).toBe(false);
+ }
+ });
+
+ it("MARIMO_KERNEL_STARTUP_ERROR → terminal + closeTransport", () => {
+ const decision = classify("MARIMO_KERNEL_STARTUP_ERROR", 0);
+ expect(decision.kind).toBe("terminal");
+ expect(decision.status).toMatchObject({
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_STARTUP_ERROR,
+ });
+ if (decision.kind === "terminal") {
+ expect(decision.closeTransport).toBe(true);
+ }
+ });
+
+ it("terminal closes ignore retryCount entirely", () => {
+ const decision = classify("MARIMO_SHUTDOWN", 99);
+ expect(decision.kind).toBe("terminal");
+ });
+ });
+
+ describe("retry budget exhaustion", () => {
+ it("yields retry on attempts 1..maxRetries-1 and gave-up on the final close", () => {
+ const states: string[] = [];
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
+ states.push(classify(undefined, attempt - 1).kind);
+ }
+ states.push(classify(undefined, MAX_RETRIES).kind);
+
+ expect(states).toEqual([
+ ...Array.from({ length: MAX_RETRIES }, () => "retry"),
+ "gave-up",
+ ]);
+ });
+ });
+});
diff --git a/frontend/src/core/websocket/transports/basic.ts b/frontend/src/core/websocket/transports/basic.ts
index d3a37690ae..226fd83389 100644
--- a/frontend/src/core/websocket/transports/basic.ts
+++ b/frontend/src/core/websocket/transports/basic.ts
@@ -43,6 +43,8 @@ export class BasicTransport implements IConnectionTransport {
return WebSocket.OPEN;
}
+ readonly retryCount = 0;
+
reconnect(code?: number | undefined, reason?: string | undefined): void {
this.close();
this.connect();
diff --git a/frontend/src/core/websocket/transports/transport.ts b/frontend/src/core/websocket/transports/transport.ts
index 77ce4e699c..9cae75820b 100644
--- a/frontend/src/core/websocket/transports/transport.ts
+++ b/frontend/src/core/websocket/transports/transport.ts
@@ -25,6 +25,7 @@ export interface IConnectionTransport {
callback: ConnectionTransportCallback<T>,
): void;
readyState: WebSocket["readyState"];
+ readonly retryCount: number;
}
export class ConnectionSubscriptions {
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index 89c261a705..73f610bbba 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -11,7 +11,10 @@ import type {
NotificationMessageData,
NotificationPayload,
} from "@/core/kernel/messages";
-import { useConnectionTransport } from "@/core/websocket/useWebSocket";
+import {
+ MAX_RETRIES,
+ useConnectionTransport,
+} from "@/core/websocket/useWebSocket";
import { renderHTML } from "@/plugins/core/RenderHTML";
import {
handleWidgetMessage,
@@ -69,10 +72,96 @@ import { useStorageActions } from "../storage/state";
import { useVariablesActions } from "../variables/state";
import type { VariableName } from "../variables/types";
import { isWasm } from "../wasm/utils";
-import { WebSocketClosedReason, WebSocketState } from "./types";
+import {
+ type ConnectionStatus,
+ WebSocketClosedReason,
+ WebSocketState,
+} from "./types";
const SUPPORTS_LAZY_KERNELS = true;
+export type CloseDecision =
+ | { kind: "terminal"; status: ConnectionStatus; closeTransport: boolean }
+ | { kind: "gave-up"; status: ConnectionStatus }
+ | { kind: "retry"; status: ConnectionStatus };
+
+export function classifyCloseEvent(
+ event: { reason?: string },
+ context: { retryCount: number; maxRetries: number },
+): CloseDecision {
+ switch (event.reason) {
+ case "MARIMO_ALREADY_CONNECTED":
+ return {
+ kind: "terminal",
+ status: {
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.ALREADY_RUNNING,
+ reason: "another browser tab is already connected to the kernel",
+ canTakeover: true,
+ },
+ closeTransport: true,
+ };
+ case "MARIMO_WRONG_KERNEL_ID":
+ case "MARIMO_NO_FILE_KEY":
+ case "MARIMO_NO_SESSION_ID":
+ case "MARIMO_NO_SESSION":
+ case "MARIMO_SHUTDOWN":
+ return {
+ kind: "terminal",
+ status: {
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,
+ reason: "kernel not found",
+ },
+ closeTransport: true,
+ };
+ case "MARIMO_MALFORMED_QUERY":
+ return {
+ kind: "terminal",
+ status: {
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.MALFORMED_QUERY,
+ reason:
+ "the kernel did not recognize a request; please file a bug with marimo",
+ },
+ closeTransport: false,
+ };
+ case "MARIMO_KERNEL_STARTUP_ERROR":
+ return {
+ kind: "terminal",
+ status: {
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_STARTUP_ERROR,
+ reason: "Failed to start kernel sandbox",
+ },
+ closeTransport: true,
+ };
+ default:
+ // Empty/undefined reasons are normal transient closes. Anything else is
+ // an unknown server reason; warn so a new MARIMO_* reason doesn't fall
+ // silently into the retry path.
+ if (event.reason) {
+ logNever(event.reason as never);
+ }
+ }
+ // partysocket stops retrying silently once `maxRetries` is hit; surface
+ // CLOSED so callers can detect the give-up.
+ if (context.retryCount >= context.maxRetries) {
+ return {
+ kind: "gave-up",
+ status: {
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,
+ reason: "kernel not found",
+ },
+ };
+ }
+ return {
+ kind: "retry",
+ status: { state: WebSocketState.CONNECTING },
+ };
+}
+
function getExistingCells(): CellData[] | undefined {
if (!SUPPORTS_LAZY_KERNELS) {
return undefined;
@@ -340,6 +429,30 @@ export function useMarimoKernelConnection(opts: {
}
};
+ // Manual reconnect. Probes /health first to fail fast when the runtime
+ // is unreachable, instead of waiting on partysocket's retry budget.
+ const reconnect = async () => {
+ if (
+ ws.readyState === WebSocket.OPEN ||
+ ws.readyState === WebSocket.CONNECTING
+ ) {
+ return;
+ }
+ shouldTryReconnecting.current = true;
+ setConnection({ state: WebSocketState.CONNECTING });
+ const healthy = await runtimeManager.isHealthy();
+ if (!healthy) {
+ shouldTryReconnecting.current = false;
+ setConnection({
+ state: WebSocketState.CLOSED,
+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,
+ reason: "kernel not found",
+ });
+ return;
+ }
+ ws.reconnect();
+ };
+
const ws = useConnectionTransport({
static: isStaticNotebook(),
/**
@@ -399,58 +512,20 @@ export function useMarimoKernelConnection(opts: {
*/
onClose: (e) => {
Logger.warn("WebSocket closed", e.code, e.reason);
- switch (e.reason) {
- case "MARIMO_ALREADY_CONNECTED":
- setConnection({
- state: WebSocketState.CLOSED,
- code: WebSocketClosedReason.ALREADY_RUNNING,
- reason: "another browser tab is already connected to the kernel",
- canTakeover: true,
- });
- ws.close(); // close to prevent reconnecting
- return;
-
- case "MARIMO_WRONG_KERNEL_ID":
- case "MARIMO_NO_FILE_KEY":
- case "MARIMO_NO_SESSION_ID":
- case "MARIMO_NO_SESSION":
- case "MARIMO_SHUTDOWN":
- setConnection({
- state: WebSocketState.CLOSED,
- code: WebSocketClosedReason.KERNEL_DISCONNECTED,
- reason: "kernel not found",
- });
- ws.close(); // close to prevent reconnecting
- return;
-
- case "MARIMO_MALFORMED_QUERY":
- setConnection({
- state: WebSocketState.CLOSED,
- code: WebSocketClosedReason.MALFORMED_QUERY,
- reason:
- "the kernel did not recognize a request; please file a bug with marimo",
- });
- return;
-
- default:
- // Check for kernel startup error (full error already received via message)
- if (e.reason === "MARIMO_KERNEL_STARTUP_ERROR") {
- setConnection({
- state: WebSocketState.CLOSED,
- code: WebSocketClosedReason.KERNEL_STARTUP_ERROR,
- reason: "Failed to start kernel sandbox",
- });
- ws.close(); // prevent reconnecting
- return;
- }
-
- // Session should be valid
- // - browser tab might have been closed or re-opened
- // - computer might have just woken from sleep
- //
- // so try reconnecting.
- setConnection({ state: WebSocketState.CONNECTING });
- tryReconnecting(e.code, e.reason);
+ const decision = classifyCloseEvent(e, {
+ retryCount: ws.retryCount,
+ maxRetries: MAX_RETRIES,
+ });
+ setConnection(decision.status);
+ if (decision.kind === "terminal" && decision.closeTransport) {
+ ws.close(); // close to prevent reconnecting
+ return;
+ }
+ if (decision.kind === "retry") {
+ // Session should be valid
+ // - browser tab might have been closed or re-opened
+ // - computer might have just woken from sleep
+ tryReconnecting(e.code, e.reason);
}
},
@@ -468,5 +543,5 @@ export function useMarimoKernelConnection(opts: {
},
});
- return { connection };
+ return { connection, reconnect };
}
diff --git a/frontend/src/core/websocket/useWebSocket.tsx b/frontend/src/core/websocket/useWebSocket.tsx
index 07d66993e0..d367c70432 100644
--- a/frontend/src/core/websocket/useWebSocket.tsx
+++ b/frontend/src/core/websocket/useWebSocket.tsx
@@ -18,6 +18,10 @@ interface UseConnectionTransportOptions {
onError: (event: WebSocketEventMap["error"]) => void;
}
+// Per-`reconnect()` retry budget for partysocket. After exhaustion, partysocket
+// stops silently; treat `retryCount >= MAX_RETRIES` as the give-up signal.
+export const MAX_RETRIES = 10;
+
function createConnectionTransport(
options: Pick<UseConnectionTransportOptions, "url" | "static">,
): IConnectionTransport {
@@ -33,8 +37,7 @@ function createConnectionTransport(
// Cast needed: ReconnectingWebSocket types readyState as `number`
// but IConnectionTransport expects `0 | 1 | 2 | 3`
return new ReconnectingWebSocket(urlProvider, undefined, {
- // We don't want Infinity retries
- maxRetries: 10,
+ maxRetries: MAX_RETRIES,
debug: false,
startClosed: true,
// long timeout -- the server can become slow when many notebooks
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9378f0d639..579bc20a64 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -335,8 +335,8 @@ importers:
specifier: ^11.12.3
version: 11.12.3
partysocket:
- specifier: 1.1.10
- version: 1.1.10
+ specifier: 1.1.13
+ version: 1.1.13
path-to-regexp:
specifier: ^8.4.0
version: 8.4.2
@@ -7572,8 +7572,8 @@ packages:
resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}
engines: {node: '>= 0.8'}
- resolution: {integrity: sha512-ACfn0P6lQuj8/AqB4L5ZDFcIEbpnIteNNObrlxqV1Ge80GTGhjuJ2sNKwNQlFzhGi4kI7fP/C1Eqh8TR78HjDQ==}
+ resolution: {integrity: sha512-RNXGzc6j0NISGE84+VTHHtbPwmnzZuOYJm9XZ+en+aZlIA2vC4AfwPlYxAHmGGGko3pQF7xRNhoe7bu1Brej4Q==}
resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}
@@ -18054,7 +18054,7 @@ snapshots:
dependencies:
event-target-polyfill: 0.0.4