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.

feat: non-destructive local takeover (read-only viewer + bidirectional takeover) (#9746)

Kiran Gadhave6dcaff7dd83c
diff --git a/frontend/src/components/editor/Disconnected.tsx b/frontend/src/components/editor/Disconnected.tsx
index b335f3a3a0..e81b2659c0 100644
--- a/frontend/src/components/editor/Disconnected.tsx
+++ b/frontend/src/components/editor/Disconnected.tsx
@@ -1,69 +1,10 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { ArrowRightSquareIcon } from "lucide-react";
-import { API } from "@/core/network/api";
-import { Banner } from "@/plugins/impl/common/error-banner";
-import { prettyError } from "@/utils/errors";
-import { reloadSafe } from "@/utils/reload-safe";
-import { Button } from "../ui/button";
-import { toast } from "../ui/use-toast";
-
interface DisconnectedProps {
reason: string;
- canTakeover: boolean | undefined;
}
-export const Disconnected = ({
- reason,
- canTakeover = false,
-}: DisconnectedProps) => {
- const handleTakeover = async () => {
- try {
- const searchParams = new URL(window.location.href).searchParams;
- await API.post(`/kernel/takeover?${searchParams.toString()}`, {});
-
- // Refresh the page to reconnect
- reloadSafe();
- } catch (error) {
- toast({
- title: "Failed to take over session",
- description: prettyError(error),
- variant: "danger",
- });
- }
- };
-
- if (canTakeover) {
- return (
- <div className="flex justify-center">
- <Banner
- kind="info"
- className="mt-10 flex flex-col rounded p-3 max-w-[800px] mx-4"
- >
- <div className="flex justify-between">
- <span className="font-bold text-xl flex items-center mb-2">
- Notebook already connected
- </span>
- </div>
- <div className="flex justify-between items-end text-base gap-20">
- <span>{reason}</span>
- {canTakeover && (
- <Button
- onClick={handleTakeover}
- variant="outline"
- data-testid="takeover-button"
- className="shrink-0"
- >
- <ArrowRightSquareIcon className="w-4 h-4 mr-2" />
- Take over session
- </Button>
- )}
- </div>
- </Banner>
- </div>
- );
- }
-
+export const Disconnected = ({ reason }: DisconnectedProps) => {
return (
<div className="font-mono text-center text-base text-(--red-11)">
<p>{reason}</p>
diff --git a/frontend/src/components/editor/__tests__/viewer-banner.test.tsx b/frontend/src/components/editor/__tests__/viewer-banner.test.tsx
new file mode 100644
index 0000000000..23f0839b43
--- /dev/null
+++ b/frontend/src/components/editor/__tests__/viewer-banner.test.tsx
@@ -0,0 +1,89 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { render, screen } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { describe, expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { layoutStateAtom } from "@/core/layout/layout";
+import { kioskModeAtom, viewStateAtom } from "@/core/mode";
+import { API } from "@/core/network/api";
+import { ViewerBanner } from "../viewer-banner";
+
+describe("ViewerBanner", () => {
+ it("renders nothing when not in kiosk mode", () => {
+ const store = createStore();
+ store.set(kioskModeAtom, false);
+ const { container } = render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <ViewerBanner />
+ </TooltipProvider>
+ </Provider>,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing for an intentional kiosk client (?kiosk=true)", () => {
+ const store = createStore();
+ store.set(kioskModeAtom, true);
+ window.history.pushState({}, "", "/?kiosk=true");
+ try {
+ const { container } = render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <ViewerBanner />
+ </TooltipProvider>
+ </Provider>,
+ );
+ expect(container).toBeEmptyDOMElement();
+ } finally {
+ window.history.pushState({}, "", "/");
+ }
+ });
+
+ it("renders nothing in a non-vertical layout (grid/slides)", () => {
+ const store = createStore();
+ store.set(kioskModeAtom, true);
+ store.set(layoutStateAtom, { selectedLayout: "grid", layoutData: {} });
+ const { container } = render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <ViewerBanner />
+ </TooltipProvider>
+ </Provider>,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing in present mode", () => {
+ const store = createStore();
+ store.set(kioskModeAtom, true);
+ store.set(viewStateAtom, { mode: "present", cellAnchor: null });
+ const { container } = render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <ViewerBanner />
+ </TooltipProvider>
+ </Provider>,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("shows take over and posts without reload when viewing", () => {
+ const store = createStore();
+ store.set(kioskModeAtom, true);
+ const post = vi.spyOn(API, "post").mockResolvedValue({} as never);
+ render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <ViewerBanner />
+ </TooltipProvider>
+ </Provider>,
+ );
+ const button = screen.getByTestId("takeover-button");
+ button.click();
+ expect(post).toHaveBeenCalledWith(
+ expect.stringContaining("/kernel/takeover"),
+ {},
+ );
+ });
+});
diff --git a/frontend/src/components/editor/header/__tests__/status.test.tsx b/frontend/src/components/editor/header/__tests__/status.test.tsx
index 7a811d52e1..579eb6234b 100644
--- a/frontend/src/components/editor/header/__tests__/status.test.tsx
+++ b/frontend/src/components/editor/header/__tests__/status.test.tsx
@@ -90,19 +90,4 @@ describe("StatusOverlay disconnect indicator", () => {
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/app-header.tsx b/frontend/src/components/editor/header/app-header.tsx
index d05832d411..4d34874378 100644
--- a/frontend/src/components/editor/header/app-header.tsx
+++ b/frontend/src/components/editor/header/app-header.tsx
@@ -18,10 +18,7 @@ export const AppHeader: React.FC<PropsWithChildren<Props>> = ({
<div className={className}>
{children}
{connection.state === WebSocketState.CLOSED && (
- <Disconnected
- reason={connection.reason}
- canTakeover={connection.canTakeover}
- />
+ <Disconnected reason={connection.reason} />
)}
</div>
);
diff --git a/frontend/src/components/editor/header/status.tsx b/frontend/src/components/editor/header/status.tsx
index d4f609b770..3a5558cfc3 100644
--- a/frontend/src/components/editor/header/status.tsx
+++ b/frontend/src/components/editor/header/status.tsx
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { useAtomValue } from "jotai";
-import { HourglassIcon, LockIcon, UnlinkIcon } from "lucide-react";
+import { HourglassIcon, UnlinkIcon } from "lucide-react";
import React from "react";
import { Tooltip } from "@/components/ui/tooltip";
import { notebookScrollToRunning } from "@/core/cells/actions";
@@ -24,13 +24,13 @@ export const StatusOverlay: React.FC<{
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.
+ // fail the same way.
const canReconnect =
isClosed && connection.code === WebSocketClosedReason.KERNEL_DISCONNECTED;
return (
<>
- {isClosed && !connection.canTakeover && <NoiseBackground />}
+ {isClosed && <NoiseBackground />}
<div
className={cn(
"z-50 top-4 left-4",
@@ -38,12 +38,11 @@ export const StatusOverlay: React.FC<{
)}
>
{isOpen && isRunning && <RunningIcon />}
- {isClosed && !connection.canTakeover && (
+ {isClosed && (
<DisconnectedIcon
onReconnect={canReconnect ? onReconnect : undefined}
/>
)}
- {isClosed && connection.canTakeover && <LockedIcon />}
</div>
</>
);
@@ -79,14 +78,6 @@ const DisconnectedIcon: React.FC<{ onReconnect?: () => void }> = ({
);
};
-const LockedIcon = () => (
- <Tooltip content="Notebook locked">
- <div className={topLeftStatus}>
- <LockIcon className="w-[25px] h-[25px] text-(--blue-11)" />
- </div>
- </Tooltip>
-);
-
const RunningIcon = () => {
const scratchpadOnly = useAtomValue(onlyScratchpadIsRunningAtom);
const tooltip = scratchpadOnly
diff --git a/frontend/src/components/editor/viewer-banner.tsx b/frontend/src/components/editor/viewer-banner.tsx
new file mode 100644
index 0000000000..2e53956b93
--- /dev/null
+++ b/frontend/src/components/editor/viewer-banner.tsx
@@ -0,0 +1,82 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useAtomValue } from "jotai/react";
+import { ArrowRightSquareIcon, EyeIcon } from "lucide-react";
+import { KnownQueryParams } from "@/core/constants";
+import { useLayoutState } from "@/core/layout/layout";
+import { kioskModeAtom, viewStateAtom } from "@/core/mode";
+import { API } from "@/core/network/api";
+import { Banner } from "@/plugins/impl/common/error-banner";
+import { prettyError } from "@/utils/errors";
+import { Button } from "../ui/button";
+import { Tooltip } from "../ui/tooltip";
+import { toast } from "../ui/use-toast";
+
+export const ViewerBanner = () => {
+ const isViewing = useAtomValue(kioskModeAtom);
+ const { selectedLayout } = useLayoutState();
+ const { mode } = useAtomValue(viewStateAtom);
+
+ // Only a demoted editor (a second tab auto-routed to read-only) is offered
+ // takeover. A client that explicitly requested kiosk (?kiosk=true: embeds,
+ // slide previews, dashboards) is an intentional viewer and gets no banner.
+ const isIntentionalKiosk = new URL(window.location.href).searchParams.has(
+ KnownQueryParams.kiosk,
+ );
+
+ // Takeover is an editing affordance: only surface it in the default vertical
+ // reading view. Grid/slides layouts and present mode are app-style views
+ // where a floating take-over banner is out of place.
+ if (
+ !isViewing ||
+ isIntentionalKiosk ||
+ selectedLayout !== "vertical" ||
+ mode === "present"
+ ) {
+ return null;
+ }
+
+ const handleTakeover = async () => {
+ try {
+ const searchParams = new URL(window.location.href).searchParams;
+ // No reload: the server replies with consumer-capabilities
+ // (edit: true), which flips kiosk mode off and hides this banner.
+ await API.post(`/kernel/takeover?${searchParams.toString()}`, {});
+ } catch (error) {
+ toast({
+ title: "Failed to take over session",
+ description: prettyError(error),
+ variant: "danger",
+ });
+ }
+ };
+
+ return (
+ <div className="absolute top-2 left-2 z-50 w-fit print:hidden">
+ <Banner
+ kind="info"
+ className="flex items-center gap-2 rounded px-2 py-1 text-xs shadow-sm"
+ >
+ <span className="flex items-center gap-1 text-muted-foreground">
+ <EyeIcon className="w-3.5 h-3.5 shrink-0" />
+ You are currently connected as a reader.
+ </span>
+ <Tooltip
+ content="Switch editing to this tab. The current editor becomes read-only."
+ side="bottom"
+ >
+ <Button
+ onClick={handleTakeover}
+ variant="outline"
+ size="xs"
+ data-testid="takeover-button"
+ className="shrink-0"
+ >
+ <ArrowRightSquareIcon className="w-3 h-3 mr-1" />
+ Take over
+ </Button>
+ </Tooltip>
+ </Banner>
+ </div>
+ );
+};
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 901d16d0c4..0ad3af5057 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -12,6 +12,7 @@ import { Controls } from "@/components/editor/controls/Controls";
import { AppHeader } from "@/components/editor/header/app-header";
import { FilenameForm } from "@/components/editor/header/filename-form";
import { MultiCellActionToolbar } from "@/components/editor/navigation/multi-cell-action-toolbar";
+import { ViewerBanner } from "@/components/editor/viewer-banner";
import { cn } from "@/utils/cn";
import { Paths } from "@/utils/paths";
import { AppContainer } from "../components/editor/app-container";
@@ -164,6 +165,8 @@ export const EditApp: React.FC<AppProps> = ({
)}
</AppHeader>
+ <ViewerBanner />
+
{/* Don't render until we have a single cell */}
{hasCells && (
<CellsRenderer appConfig={appConfig} mode={viewState.mode}>
diff --git a/frontend/src/core/islands/bootstrap.ts b/frontend/src/core/islands/bootstrap.ts
index c3a79a0597..255434141b 100644
--- a/frontend/src/core/islands/bootstrap.ts
+++ b/frontend/src/core/islands/bootstrap.ts
@@ -255,6 +255,8 @@ function handleMessage(
handleWidgetMessage(MODEL_MANAGER, msg.data);
return;
+ case "consumer-capabilities":
+ return;
default:
logNever(msg);
return;
diff --git a/frontend/src/core/kernel/__tests__/handlers.test.ts b/frontend/src/core/kernel/__tests__/handlers.test.ts
index 7048cfa2da..fa295242c1 100644
--- a/frontend/src/core/kernel/__tests__/handlers.test.ts
+++ b/frontend/src/core/kernel/__tests__/handlers.test.ts
@@ -90,6 +90,7 @@ describe("buildCellData", () => {
terminal: false,
},
auto_instantiated: false,
+ consumer_capabilities: { edit: true, interact: true },
};
const cells = buildCellData(kernelReadyData);
@@ -158,6 +159,7 @@ describe("buildCellData", () => {
terminal: false,
},
auto_instantiated: false,
+ consumer_capabilities: { edit: true, interact: true },
};
const cells = buildCellData(kernelReadyData);
@@ -191,6 +193,7 @@ describe("buildCellData", () => {
terminal: false,
},
auto_instantiated: false,
+ consumer_capabilities: { edit: true, interact: true },
};
const cells = buildCellData(kernelReadyData);
@@ -223,6 +226,7 @@ describe("buildLayoutState", () => {
terminal: false,
},
auto_instantiated: false,
+ consumer_capabilities: { edit: true, interact: true },
};
const cells = buildCellData(kernelReadyData);
@@ -271,6 +275,7 @@ describe("buildLayoutState", () => {
terminal: false,
},
auto_instantiated: false,
+ consumer_capabilities: { edit: true, interact: true },
};
const cells = buildCellData(kernelReadyData);
diff --git a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts
index e794fb1a89..4bb0a999f9 100644
--- a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts
+++ b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts
@@ -31,19 +31,6 @@ describe("classifyCloseEvent", () => {
});
describe("terminal closes (server-initiated)", () => {
- it("MARIMO_ALREADY_CONNECTED → terminal + closeTransport, with takeover", () => {
- const decision = classify("MARIMO_ALREADY_CONNECTED");
- 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",
diff --git a/frontend/src/core/websocket/types.ts b/frontend/src/core/websocket/types.ts
index 6ad83b7758..709ff0f9c7 100644
--- a/frontend/src/core/websocket/types.ts
+++ b/frontend/src/core/websocket/types.ts
@@ -14,7 +14,6 @@ export type WebSocketState =
export const WebSocketClosedReason = {
KERNEL_DISCONNECTED: "KERNEL_DISCONNECTED",
- ALREADY_RUNNING: "ALREADY_RUNNING",
MALFORMED_QUERY: "MALFORMED_QUERY",
KERNEL_STARTUP_ERROR: "KERNEL_STARTUP_ERROR",
} as const;
@@ -30,11 +29,6 @@ export type ConnectionStatus =
* Human-readable reason for closing the connection.
*/
reason: string;
- /**
- * Whether the current session can be taken over by another session,
- * since we only allow single-user editing.
- */
- canTakeover?: boolean;
}
| {
state:
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index 5101323259..3547ea9554 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -82,7 +82,6 @@ const SUPPORTS_LAZY_KERNELS = true;
// (marimo/_server/api/endpoints/ws_endpoint.py and ws/*.py). Keep in sync with
// the backend literals.
export type CloseReason =
- | "MARIMO_ALREADY_CONNECTED"
| "MARIMO_WRONG_KERNEL_ID"
| "MARIMO_NO_FILE_KEY"
| "MARIMO_NO_SESSION_ID"
@@ -99,17 +98,6 @@ export type CloseDecision =
export function classifyCloseEvent(event: { reason?: string }): CloseDecision {
switch (event.reason as CloseReason | undefined) {
- 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 TRANSPORT_EXHAUSTED_REASON:
return {
kind: "gave-up",
@@ -421,6 +409,9 @@ export function useMarimoKernelConnection(opts: {
case "notebook-document-transaction":
handleDocumentTransaction(msg.data.transaction);
return;
+ case "consumer-capabilities":
+ setKioskMode(!msg.data.consumer_capabilities.edit);
+ return;
default:
logNever(msg.data);
}
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 5dd775293b..94db98b5f6 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -328,6 +328,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
notifications.QueryParamsDeleteNotification,
notifications.QueryParamsClearNotification,
notifications.FocusCellNotification,
+ notifications.ConsumerCapabilitiesNotification,
notifications.NotificationMessage,
# ai
ChatMessage,
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index 15fd418a9e..8dc845fbfe 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -279,6 +279,34 @@ class KernelCapabilitiesNotification(msgspec.Struct):
self.pyrefly = DependencyManager.pyrefly.has()
+class ConsumerCapabilities(msgspec.Struct, frozen=True):
+ """Per-consumer access capabilities for a session connection.
+
+ - editor: `{edit: True, interact: True}`
+ - viewer: `{edit: False, interact: False}`
+
+ These gate the frontend UI; they are not the server's authority boundary.
+ Scopes are granted per session mode (see `@requires`), so in an edit session
+ every connection (viewers included) carries the `edit` scope and can issue
+ edit requests. A viewer's read-only status is enforced by the client hiding
+ edit affordances, not by the server rejecting the request.
+ """
+
+ edit: bool
+ interact: bool
+
+
+class ConsumerCapabilitiesNotification(
+ Notification, tag="consumer-capabilities"
+):
+ """
+ Notification of the frontend consumer's capabilities.
+ """
+
+ name: ClassVar[str] = "consumer-capabilities"
+ consumer_capabilities: ConsumerCapabilities
+
+
class KernelReadyNotification(Notification, tag="kernel-ready"):
"""Kernel ready for execution. First notification sent at startup.
@@ -311,6 +339,7 @@ class KernelReadyNotification(Notification, tag="kernel-ready"):
app_config: _AppConfig
kiosk: bool
capabilities: KernelCapabilitiesNotification
+ consumer_capabilities: ConsumerCapabilities
auto_instantiated: bool = False
@@ -869,4 +898,6 @@ NotificationMessage = (
| FocusCellNotification
# Document
| NotebookDocumentTransactionNotification
+ # Consumer
+ | ConsumerCapabilitiesNotification
)
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index ae86a68b2c..bb6e3290a2 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING
from marimo._config.config import merge_config
from marimo._messaging.notification import (
+ ConsumerCapabilities,
KernelCapabilitiesNotification,
KernelReadyNotification,
)
@@ -132,6 +133,9 @@ def create_session(
app_config=app.config,
kiosk=False,
capabilities=KernelCapabilitiesNotification(),
+ consumer_capabilities=ConsumerCapabilities(
+ edit=True, interact=True
+ ),
)
),
)
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index 3bb283ef8a..d5e4e19439 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -9,7 +9,6 @@ from starlette.authentication import requires
from starlette.responses import JSONResponse, StreamingResponse
from marimo import _loggers
-from marimo._messaging.notification import AlertNotification
from marimo._runtime.commands import HTTPRequest, UpdateUIElementCommand
from marimo._server.api.deps import AppState
from marimo._server.api.endpoints.ws.ws_connection_validator import (
@@ -32,6 +31,10 @@ from marimo._server.models.models import (
from marimo._server.router import APIRouter
from marimo._server.uvicorn_utils import close_uvicorn
from marimo._server.workspace import MarimoFileKey
+from marimo._session.consumer_policy import (
+ TakeoverDecision,
+ can_take_over_editing,
+)
from marimo._session.types import KernelState
from marimo._types.ids import ConsumerId
from marimo._utils.asyncio_utils import cancel_and_wait
@@ -566,35 +569,39 @@ async def takeover_endpoint(
"""
app_state = AppState(request)
- file_key: MarimoFileKey | None = (
- app_state.query_params(FILE_QUERY_PARAM_KEY)
- or app_state.session_manager.workspace.get_unique_file_key()
- )
- if file_key is None:
- LOGGER.error("No file key provided")
+ session_id = app_state.get_current_session_id()
+ if session_id is None:
+ LOGGER.error("Missing Marimo-Session-Id header")
return JSONResponse(
status_code=400,
content={"error": "Cannot take over session."},
)
+ caller_id = ConsumerId(session_id)
- # Find and close any existing sessions for this file
- existing_session = app_state.session_manager.get_session_by_file_key(
- file_key
- )
- if existing_session is not None:
- # Send a disconnect message to the client
- existing_session.notify(
- AlertNotification(
- title="Session taken over",
- description="Another user has taken over this session.",
- variant="danger",
- ),
- from_consumer_id=None,
+ session = app_state.get_current_session()
+ if not session:
+ LOGGER.error("No current session found")
+ return JSONResponse(
+ status_code=400,
+ content={"error": "Cannot take over session."},
)
- # Wait 100ms to ensure the client has received the message
- await asyncio.sleep(0.1)
- existing_session.disconnect_main_consumer()
- else:
- LOGGER.warning("No existing session found for file key %s", file_key)
+
+ caller = session.room.get_consumer(caller_id)
+ if not caller:
+ LOGGER.error("No consumer found for caller ID %s", caller_id)
+ return JSONResponse(
+ status_code=400,
+ content={"error": "Cannot take over session."},
+ )
+
+ takeover_decision = can_take_over_editing(session, caller_id)
+ if takeover_decision != TakeoverDecision.ALLOW:
+ LOGGER.debug("Takeover denied by policy for consumer %s", caller_id)
+ return JSONResponse(
+ status_code=403,
+ content={"error": "Not allowed to take over session."},
+ )
+
+ session.room.promote_consumer_to_main(caller)
return JSONResponse(status_code=200, content={"status": "ok"})
diff --git a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py
index f3bdea78cf..7e8e795af0 100644
--- a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py
+++ b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py
@@ -10,6 +10,7 @@ from marimo._ast.cell import CellConfig
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.notebook.document import NotebookDocument
from marimo._messaging.notification import (
+ ConsumerCapabilities,
KernelCapabilitiesNotification,
KernelReadyNotification,
)
@@ -85,6 +86,9 @@ def build_kernel_ready(
last_execution_time=last_execution_time,
app_config=session.app_file_manager.app.config,
kiosk=kiosk,
+ consumer_capabilities=ConsumerCapabilities(
+ edit=not kiosk, interact=not kiosk
+ ),
capabilities=KernelCapabilitiesNotification(),
auto_instantiated=auto_instantiated,
)
diff --git a/marimo/_server/api/endpoints/ws/ws_message_loop.py b/marimo/_server/api/endpoints/ws/ws_message_loop.py
index 05a844baed..21ef55ea21 100644
--- a/marimo/_server/api/endpoints/ws/ws_message_loop.py
+++ b/marimo/_server/api/endpoints/ws/ws_message_loop.py
@@ -40,13 +40,13 @@ class WebSocketMessageLoop:
self,
websocket: WebSocket,
message_queue: asyncio.Queue[KernelMessage],
- kiosk: bool,
+ is_kiosk: Callable[[], bool],
on_disconnect: Callable[[Exception, Callable[[], Any]], None],
on_check_status_update: Callable[[], None],
):
self.websocket = websocket
self.message_queue = message_queue
- self.kiosk = kiosk
+ self.is_kiosk = is_kiosk
self.on_disconnect = on_disconnect
self.on_check_status_update = on_check_status_update
self._listen_messages_task: asyncio.Task[None] | None = None
@@ -134,13 +134,14 @@ class WebSocketMessageLoop:
True if the operation should be filtered (not sent), False
otherwise.
"""
- if op in KIOSK_ONLY_OPERATIONS and not self.kiosk:
+ kiosk = self.is_kiosk()
+ if op in KIOSK_ONLY_OPERATIONS and not kiosk:
LOGGER.debug(
"Ignoring operation %s, not in kiosk mode",
op,
)
return True
- if op in KIOSK_EXCLUDED_OPERATIONS and self.kiosk:
+ if op in KIOSK_EXCLUDED_OPERATIONS and kiosk:
LOGGER.debug(
"Ignoring operation %s, in kiosk mode",
op,
diff --git a/marimo/_server/api/endpoints/ws/ws_session_connector.py b/marimo/_server/api/endpoints/ws/ws_session_connector.py
index 352e303830..304ea7aaf1 100644
--- a/marimo/_server/api/endpoints/ws/ws_session_connector.py
+++ b/marimo/_server/api/endpoints/ws/ws_session_connector.py
@@ -4,6 +4,8 @@ from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING
+from marimo._session.consumer_policy import initial_capabilities
+
if TYPE_CHECKING:
from starlette.websockets import WebSocket
@@ -36,6 +38,21 @@ class ConnectionType(Enum):
NEW = "new"
+def is_viewer_connection(
+ *, connection_type: ConnectionType, is_main_consumer: bool
+) -> bool:
+ """Whether a connection should receive read-only (kiosk) message filtering.
+
+ RTC collaborators are full editors even though they are not the room's
+ main consumer, so they are never treated as viewers. For the single-editor
+ model, the viewer is whichever connection is not currently the main
+ consumer; takeover flips this by reassigning the main consumer.
+ """
+ if connection_type is ConnectionType.RTC_EXISTING:
+ return False
+ return not is_main_consumer
+
+
class SessionConnector:
"""Handles different session connection strategies."""
@@ -70,17 +87,29 @@ class SessionConnector:
if existing_by_id is not None:
return self._reconnect_session(existing_by_id)
- # 3. Connect to existing session (RTC mode)
+ # 3. Connect to existing session
+ # 3a. If RTC enabled and session exists for file key, connect to it
+
existing_by_file = self.manager.get_session_by_file_key(
self.params.file_key
)
+ session_in_edit_mode = self.manager.mode == SessionMode.EDIT
+
if (
existing_by_file is not None
+ and session_in_edit_mode
and self.params.rtc_enabled
- and self.manager.mode == SessionMode.EDIT
):
return self._connect_rtc_session(existing_by_file)
+ # 3b. Viewer only mode: a second connection request is auto routed as reader only
+ if (
+ existing_by_file is not None
+ and session_in_edit_mode
+ and not initial_capabilities(existing_by_file, self.params).edit
+ ):
+ return self._connect_kiosk()
+
# 4. Resume previous session
resumable = self.manager.maybe_resume_session(
self.params.session_id, self.params.file_key
diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.py
index e19b4196e6..b92a9e167d 100644
--- a/marimo/_server/api/endpoints/ws_endpoint.py
+++ b/marimo/_server/api/endpoints/ws_endpoint.py
@@ -40,6 +40,7 @@ from marimo._server.api.endpoints.ws.ws_message_loop import (
from marimo._server.api.endpoints.ws.ws_rtc_handler import RTCWebSocketHandler
from marimo._server.api.endpoints.ws.ws_session_connector import (
SessionConnector,
+ is_viewer_connection,
)
from marimo._server.codes import WebSocketCodes
from marimo._server.router import APIRouter
@@ -395,11 +396,6 @@ class WebSocketHandler(SessionConsumer):
)
LOGGER.debug("Existing sessions: %s", self.manager.sessions)
- # Check if connection is allowed
- if not self._can_connect():
- await self._close_already_connected()
- return
-
# Use SessionConnector to establish session connection
connector = SessionConnector(
manager=self.manager,
@@ -423,7 +419,10 @@ class WebSocketHandler(SessionConsumer):
message_loop = WebSocketMessageLoop(
websocket=self.websocket,
message_queue=self.message_queue,
- kiosk=self.params.kiosk,
+ is_kiosk=lambda: is_viewer_connection(
+ connection_type=connection_type,
+ is_main_consumer=session.room.main_consumer is self,
+ ),
on_disconnect=self._on_disconnect,
on_check_status_update=self._check_status_update,
)
@@ -434,24 +433,6 @@ class WebSocketHandler(SessionConsumer):
except asyncio.CancelledError:
LOGGER.debug("Websocket terminated with CancelledError")
- def _can_connect(self) -> bool:
- """Check if this connection is allowed.
-
- Only one frontend can be connected at a time in edit mode,
- if RTC is not enabled.
- """
- if (
- self.manager.mode == SessionMode.EDIT
- and self.manager.any_clients_connected(self.params.file_key)
- and not self.params.kiosk
- and not self.params.rtc_enabled
- ):
- LOGGER.debug(
- "Refusing connection; a frontend is already connected."
- )
- return False
- return True
-
async def _safe_close(self, code: int, reason: str) -> None:
"""Close the WebSocket, ignoring errors from uninitialized state.
@@ -471,14 +452,6 @@ class WebSocketHandler(SessionConsumer):
exc_info=True,
)
- async def _close_already_connected(self) -> None:
- """Close the WebSocket with an 'already connected' error."""
- if self.websocket.application_state is WebSocketState.CONNECTED:
- await self._safe_close(
- WebSocketCodes.ALREADY_CONNECTED,
- "MARIMO_ALREADY_CONNECTED",
- )
-
async def _close_kernel_startup_error(self, error_message: str) -> None:
"""Send full error as message, then close the WebSocket."""
if self.websocket.application_state is WebSocketState.CONNECTED:
diff --git a/marimo/_session/consumer_policy.py b/marimo/_session/consumer_policy.py
new file mode 100644
index 0000000000..8f26e0bc30
--- /dev/null
+++ b/marimo/_session/consumer_policy.py
@@ -0,0 +1,51 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from enum import Enum
+from typing import TYPE_CHECKING
+
+from marimo._messaging.notification import ConsumerCapabilities
+from marimo._session.model import ConnectionState
+
+if TYPE_CHECKING:
+ from marimo._server.api.endpoints.ws.ws_connection_validator import (
+ ConnectionParams,
+ )
+ from marimo._session.types import Session
+ from marimo._types.ids import ConsumerId
+
+
+class TakeoverDecision(Enum):
+ """Outcome of a takeover request
+
+ **ALLOW**: The takeover request is allowed, and the consumer can take over the session.
+
+ **DENY**: The takeover request is denied, and the consumer cannot take over the session.
+ """
+
+ ALLOW = "allow"
+ DENY = "deny"
+
+
+def initial_capabilities(
+ session: Session, connection_params: ConnectionParams
+) -> ConsumerCapabilities:
+ """Determine whether to allow takeover based on initial capabilities."""
+
+ has_live_editor = session.connection_state() == ConnectionState.OPEN
+
+ if connection_params.kiosk or has_live_editor:
+ return ConsumerCapabilities(edit=False, interact=False)
+
+ return ConsumerCapabilities(edit=True, interact=True)
+
+
+def can_take_over_editing(
+ session: Session, consumer_id: ConsumerId
+) -> TakeoverDecision:
+ """Whether the `consumer` may take over editing. Local policy, always allow."""
+ del (
+ session,
+ consumer_id,
+ ) # Not used in this policy, but may be used in other policies
+ return TakeoverDecision.ALLOW
diff --git a/marimo/_session/room.py b/marimo/_session/room.py
index 035cbfbb82..c2e32df5c7 100644
--- a/marimo/_session/room.py
+++ b/marimo/_session/room.py
@@ -11,6 +11,11 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from marimo import _loggers
+from marimo._messaging.notification import (
+ ConsumerCapabilities,
+ ConsumerCapabilitiesNotification,
+)
+from marimo._messaging.serde import serialize_kernel_message
from marimo._messaging.types import KernelMessage
from marimo._session.model import ConnectionState
from marimo._types.ids import ConsumerId
@@ -64,6 +69,56 @@ class Room:
self.consumers.pop(consumer)
consumer.on_detach()
+ def promote_consumer_to_main(self, consumer: SessionConsumer) -> None:
+ """Promote a consumer to be the main consumer of the room.
+
+ Demotes the current main consumer (editor) to a regular consumer (reader).
+ Emits a targeted notification to each targeted consumer to inform capability change.
+ """
+
+ assert consumer in self.consumers, (
+ "Consumer must be in the room to be promoted."
+ )
+ previous_main_consumer = self.main_consumer
+
+ if previous_main_consumer is consumer:
+ # The consumer is already the main consumer, no need to promote.
+ return
+
+ self.main_consumer = consumer
+
+ if previous_main_consumer is not None:
+ self._notify_consumer_capability_change(
+ previous_main_consumer,
+ self.get_capabilities(previous_main_consumer),
+ )
+ self._notify_consumer_capability_change(
+ consumer, self.get_capabilities(consumer)
+ )
+
+ def get_capabilities(
+ self, consumer: SessionConsumer
+ ) -> ConsumerCapabilities:
+ """Get the capabilities of a consumer based on its role in the room."""
+ is_editor = consumer is self.main_consumer
+ return ConsumerCapabilities(edit=is_editor, interact=is_editor)
+
+ def get_consumer(self, consumer_id: ConsumerId) -> SessionConsumer | None:
+ for consumer, cid in self.consumers.items():
+ if cid == consumer_id:
+ return consumer
+ return None
+
+ def _notify_consumer_capability_change(
+ self, consumer: SessionConsumer, capabilities: ConsumerCapabilities
+ ) -> None:
+ if consumer.connection_state() != ConnectionState.OPEN:
+ return
+ notification = ConsumerCapabilitiesNotification(
+ consumer_capabilities=capabilities
+ )
+ consumer.notify(serialize_kernel_message(notification))
+
def broadcast(
self,
notification: KernelMessage,
diff --git a/marimo/_session/types.py b/marimo/_session/types.py
index 3014a03b4d..b896dd3ac3 100644
--- a/marimo/_session/types.py
+++ b/marimo/_session/types.py
@@ -31,6 +31,7 @@ if TYPE_CHECKING:
)
from marimo._session.notebook.file_manager import AppFileManager
from marimo._session.queue import ProcessLike, QueueType
+ from marimo._session.room import Room
from marimo._session.state.session_view import SessionView
from marimo._types.ids import ConsumerId
from marimo._utils.typed_connection import TypedConnection
@@ -133,6 +134,7 @@ class Session(Protocol):
session_view: SessionView
ttl_seconds: int
scratchpad_lock: asyncio.Lock
+ room: Room
@property
def document(self) -> NotebookDocument:
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index e4a5f66d68..e854c67893 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -859,6 +859,38 @@ components:
- options
title: CompletionResultNotification
type: object
+ ConsumerCapabilities:
+ description: "Per-consumer access capabilities for a session connection.\n\n\
+ \ - editor: `{edit: True, interact: True}`\n - viewer: `{edit: False,\
+ \ interact: False}`\n\n These gate the frontend UI; they are not the server's\
+ \ authority boundary.\n Scopes are granted per session mode (see `@requires`),\
+ \ so in an edit session\n every connection (viewers included) carries the\
+ \ `edit` scope and can issue\n edit requests. A viewer's read-only status\
+ \ is enforced by the client hiding\n edit affordances, not by the server\
+ \ rejecting the request."
+ properties:
+ edit:
+ type: boolean
+ interact:
+ type: boolean
+ required:
+ - edit
+ - interact
+ title: ConsumerCapabilities
+ type: object
+ ConsumerCapabilitiesNotification:
+ description: Notification of the frontend consumer's capabilities.
+ properties:
+ consumer_capabilities:
+ $ref: '#/components/schemas/ConsumerCapabilities'
+ op:
+ enum:
+ - consumer-capabilities
+ required:
+ - op
+ - consumer_capabilities
+ title: ConsumerCapabilitiesNotification
+ type: object
CopyNotebookRequest:
properties:
destination:
@@ -2479,6 +2511,8 @@ components:
items:
$ref: '#/components/schemas/CellConfig'
type: array
+ consumer_capabilities:
+ $ref: '#/components/schemas/ConsumerCapabilities'
kiosk:
type: boolean
last_executed_code:
@@ -2524,6 +2558,7 @@ components:
- app_config
- kiosk
- capabilities
+ - consumer_capabilities
title: KernelReadyNotification
type: object
KernelStartupErrorNotification:
@@ -2720,6 +2755,7 @@ components:
- $ref: '#/components/schemas/CacheInfoNotification'
- $ref: '#/components/schemas/FocusCellNotification'
- $ref: '#/components/schemas/NotebookDocumentTransactionNotification'
+ - $ref: '#/components/schemas/ConsumerCapabilitiesNotification'
discriminator:
mapping:
alert: '#/components/schemas/AlertNotification'
@@ -2729,6 +2765,7 @@ components:
cell-op: '#/components/schemas/CellNotification'
completed-run: '#/components/schemas/CompletedRunNotification'
completion-result: '#/components/schemas/CompletionResultNotification'
+ consumer-capabilities: '#/components/schemas/ConsumerCapabilitiesNotification'
data-column-preview: '#/components/schemas/DataColumnPreviewNotification'
data-source-connections: '#/components/schemas/DataSourceConnectionsNotification'
datasets: '#/components/schemas/DatasetsNotification'
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index ac664dadc5..6c43a64a8f 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -3927,6 +3927,32 @@ export interface components {
options: components["schemas"]["CompletionOption"][];
prefix_length: number;
};
+ /**
+ * ConsumerCapabilities
+ * @description Per-consumer access capabilities for a session connection.
+ *
+ * - editor: `{edit: True, interact: True}`
+ * - viewer: `{edit: False, interact: False}`
+ *
+ * These gate the frontend UI; they are not the server's authority boundary.
+ * Scopes are granted per session mode (see `@requires`), so in an edit session
+ * every connection (viewers included) carries the `edit` scope and can issue
+ * edit requests. A viewer's read-only status is enforced by the client hiding
+ * edit affordances, not by the server rejecting the request.
+ */
+ ConsumerCapabilities: {
+ edit: boolean;
+ interact: boolean;
+ };
+ /**
+ * ConsumerCapabilitiesNotification
+ * @description Notification of the frontend consumer's capabilities.
+ */
+ ConsumerCapabilitiesNotification: {
+ consumer_capabilities: components["schemas"]["ConsumerCapabilities"];
+ /** @enum {unknown} */
+ op: "consumer-capabilities";
+ };
/** CopyNotebookRequest */
CopyNotebookRequest: {
destination: string;
@@ -4916,6 +4942,7 @@ export interface components {
cell_ids: components["schemas"]["CellId"][];
codes: string[];
configs: components["schemas"]["CellConfig"][];
+ consumer_capabilities: components["schemas"]["ConsumerCapabilities"];
kiosk: boolean;
last_executed_code: {
[key: string]: string;
@@ -5060,7 +5087,8 @@ export interface components {
| components["schemas"]["CacheClearedNotification"]
| components["schemas"]["CacheInfoNotification"]
| components["schemas"]["FocusCellNotification"]
- | components["schemas"]["NotebookDocumentTransactionNotification"];
+ | components["schemas"]["NotebookDocumentTransactionNotification"]
+ | components["schemas"]["ConsumerCapabilitiesNotification"];
};
/**
* LanguageServersConfig
diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.py
index 39255e0c3a..f683ca3ad9 100644
--- a/tests/_server/api/endpoints/test_execution.py
+++ b/tests/_server/api/endpoints/test_execution.py
@@ -4,12 +4,17 @@ from __future__ import annotations
import json
import sys
import time
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
import pytest
from marimo._types.ids import CellId_t, SessionId
from marimo._utils.lists import first
+from tests._server.api.endpoints.ws_helpers import (
+ HEADERS as WS_HEADERS,
+ assert_kernel_ready_response,
+ create_response,
+)
from tests._server.mocks import (
get_session_manager,
token_header,
@@ -18,7 +23,7 @@ from tests._server.mocks import (
)
if TYPE_CHECKING:
- from starlette.testclient import TestClient
+ from starlette.testclient import TestClient, WebSocketTestSession
SESSION_ID = SessionId("session-123")
HEADERS = {
@@ -326,6 +331,15 @@ class TestExecutionRoutes_EditMode:
assert response.headers["content-type"] == "application/json"
assert response.json()["status"] == "ok"
+ @staticmethod
+ @with_session(SESSION_ID)
+ def test_takeover_missing_session_id_header(client: TestClient) -> None:
+ response = client.post(
+ "/api/kernel/takeover",
+ headers=token_header("fake-token"),
+ )
+ assert response.status_code == 400, response.text
+
@staticmethod
@with_session(SESSION_ID)
def test_takeover_file_key(client: TestClient) -> None:
@@ -585,3 +599,52 @@ def get_printed_object(
pytest.fail(f"Console is an error: {console.data}")
assert isinstance(console.data, str)
return json.loads(console.data)
+
+
+def _receive_until(op: str, websocket: WebSocketTestSession) -> dict[str, Any]:
+ while True:
+ data = websocket.receive_json()
+ if data["op"] == op:
+ return data
+
+
+def test_takeover_transfers_edit_without_disconnect(
+ client: TestClient,
+) -> None:
+ with client.websocket_connect(
+ "/ws?session_id=ed1", headers=WS_HEADERS
+ ) as editor:
+ assert_kernel_ready_response(editor.receive_json())
+ with client.websocket_connect(
+ "/ws?session_id=vw1", headers=WS_HEADERS
+ ) as viewer:
+ assert_kernel_ready_response(
+ viewer.receive_json(),
+ create_response(
+ {
+ "kiosk": True,
+ "resumed": True,
+ "consumer_capabilities": {
+ "edit": False,
+ "interact": False,
+ },
+ }
+ ),
+ )
+
+ resp = client.post(
+ "/api/kernel/takeover",
+ headers={**WS_HEADERS, "Marimo-Session-Id": "vw1"},
+ )
+ assert resp.status_code == 200, resp.text
+
+ ed = _receive_until("consumer-capabilities", editor)
+ vw = _receive_until("consumer-capabilities", viewer)
+ assert ed["data"]["consumer_capabilities"] == {
+ "edit": False,
+ "interact": False,
+ }
+ assert vw["data"]["consumer_capabilities"] == {
+ "edit": True,
+ "interact": True,
+ }
diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.py
index 5961f84ba8..f1486a3061 100644
--- a/tests/_server/api/endpoints/test_kiosk.py
+++ b/tests/_server/api/endpoints/test_kiosk.py
@@ -3,8 +3,6 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
-import pytest
-
from tests._server.api.endpoints.ws_helpers import (
HEADERS as _HEADERS,
assert_kernel_ready_response,
@@ -21,20 +19,31 @@ HEADERS = {
}
async def test_connect_kiosk_with_session(client: TestClient) -> None:
# Create the first session
- with client.websocket_connect("/ws?session_id=123") as websocket:
+ with client.websocket_connect(
+ "/ws?session_id=123", headers=_HEADERS
+ ) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
# Connect in kiosk mode
with client.websocket_connect(
- "/ws?session_id=456&kiosk=true"
+ "/ws?session_id=456&kiosk=true", headers=_HEADERS
) as other_websocket:
data = other_websocket.receive_json()
assert_kernel_ready_response(
- data, create_response({"kiosk": True, "resumed": True})
+ data,
+ create_response(
+ {
+ "kiosk": True,
+ "resumed": True,
+ "consumer_capabilities": {
+ "edit": False,
+ "interact": False,
+ },
+ }
+ ),
)
# Send document transaction to reorder cells
@@ -61,17 +70,151 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:
"/api/kernel/run",
headers=HEADERS,
json={
- "cell_ids": ["cell-3"],
+ "cellIds": ["cell-3"],
"codes": ["print('Hello, cell-3')"],
},
)
# Assert kiosk session received a focused cell notification
data = _receive_until("focus-cell", other_websocket)
- assert data == {
- "op": "focus-cell",
- "data": {"cell_id": "cell-3"},
- }
+ assert data["op"] == "focus-cell"
+ assert data["data"]["cell_id"] == "cell-3"
+
+
+def test_second_edit_connection_joins_as_viewer(client: TestClient) -> None:
+ with client.websocket_connect(
+ "/ws?session_id=ed1", headers=_HEADERS
+ ) as editor:
+ assert_kernel_ready_response(editor.receive_json())
+
+ with client.websocket_connect(
+ "/ws?session_id=vw1", headers=_HEADERS
+ ) as viewer:
+ data = viewer.receive_json()
+ assert_kernel_ready_response(
+ data,
+ create_response(
+ {
+ "kiosk": True,
+ "resumed": True,
+ "consumer_capabilities": {
+ "edit": False,
+ "interact": False,
+ },
+ }
+ ),
+ )
+
+
+def test_takeover_ping_pong_preserves_membership(client: TestClient) -> None:
+ with client.websocket_connect("/ws?session_id=a", headers=_HEADERS) as ta:
+ assert_kernel_ready_response(ta.receive_json())
+ with client.websocket_connect(
+ "/ws?session_id=b", headers=_HEADERS
+ ) as tb:
+ _receive_until("kernel-ready", tb)
+
+ # Drain both tabs each round so per-tab queues stay aligned: every
+ # takeover enqueues one capabilities-changed per tab.
+ rounds = [("b", tb, ta), ("a", ta, tb), ("b", tb, ta)]
+ for caller, ws_caller, ws_other in rounds:
+ resp = client.post(
+ "/api/kernel/takeover",
+ headers={**HEADERS, "Marimo-Session-Id": caller},
+ )
+ assert resp.status_code == 200, resp.text
+ caller_msg = _receive_until("consumer-capabilities", ws_caller)
+ other_msg = _receive_until("consumer-capabilities", ws_other)
+ assert (
+ caller_msg["data"]["consumer_capabilities"]["edit"] is True
+ )
+ assert (
+ other_msg["data"]["consumer_capabilities"]["edit"] is False
+ )
+
+
+def test_third_viewer_survives_takeover(client: TestClient) -> None:
+ with client.websocket_connect("/ws?session_id=a", headers=_HEADERS) as ta:
+ assert_kernel_ready_response(ta.receive_json())
+ with client.websocket_connect(
+ "/ws?session_id=b", headers=_HEADERS
+ ) as tb:
+ _receive_until("kernel-ready", tb)
+ with client.websocket_connect(
+ "/ws?session_id=c", headers=_HEADERS
+ ) as tc:
+ _receive_until("kernel-ready", tc)
+
+ resp = client.post(
+ "/api/kernel/takeover",
+ headers={**HEADERS, "Marimo-Session-Id": "b"},
+ )
+ assert resp.status_code == 200, resp.text
+ _receive_until("consumer-capabilities", tb)
+
+ # New editor (b) broadcasts; the third viewer (c) still gets it.
+ resp = client.post(
+ "/api/document/transaction",
+ headers={**HEADERS, "Marimo-Session-Id": "b"},
+ json={
+ "changes": [
+ {"type": "reorder-cells", "cellIds": ["cell-123"]}
+ ]
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ data = _receive_until("notebook-document-transaction", tc)
+ assert data["op"] == "notebook-document-transaction"
+
+
+def test_capabilities_changed_is_not_recorded(client: TestClient) -> None:
+ from marimo._messaging.serde import deserialize_kernel_message
+
+ with client.websocket_connect("/ws?session_id=a", headers=_HEADERS) as ta:
+ assert_kernel_ready_response(ta.receive_json())
+ with client.websocket_connect(
+ "/ws?session_id=b", headers=_HEADERS
+ ) as tb:
+ _receive_until("kernel-ready", tb)
+ client.post(
+ "/api/kernel/takeover",
+ headers={**HEADERS, "Marimo-Session-Id": "b"},
+ )
+ _receive_until("consumer-capabilities", tb)
+
+ sm = client.app.state.session_manager
+ session = next(iter(sm.sessions.values()))
+ recorded = [
+ deserialize_kernel_message(n).name
+ for n in session.session_view.notifications
+ ]
+ assert "consumer-capabilities" not in recorded
+
+
+def test_refresh_resumes_as_editor(client: TestClient) -> None:
+ with client.websocket_connect(
+ "/ws?session_id=ed1", headers=_HEADERS
+ ) as editor:
+ assert_kernel_ready_response(editor.receive_json())
+ # editor socket closed on block exit -> session is orphaned
+
+ with client.websocket_connect(
+ "/ws?session_id=ed2", headers=_HEADERS
+ ) as refreshed:
+ assert refreshed.receive_json() == {
+ "op": "reconnected",
+ "data": {"op": "reconnected"},
+ }
+ assert_kernel_ready_response(
+ _receive_until("kernel-ready", refreshed),
+ create_response(
+ {
+ "resumed": True,
+ "kiosk": False,
+ "consumer_capabilities": {"edit": True, "interact": True},
+ }
+ ),
+ )
def _receive_until(op: str, websocket: WebSocketTestSession) -> dict[str, Any]:
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 33b7a084e1..25186c7a18 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -104,18 +104,18 @@ def test_allows_multiple_connections_with_other_sessions(
)
-def test_fails_on_multiple_connections_with_other_sessions(
+def test_second_connection_with_other_session_joins_as_viewer(
client: TestClient,
) -> None:
with client.websocket_connect(WS_URL) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
- with pytest.raises(WebSocketDisconnect) as exc_info: # noqa: PT012
- with client.websocket_connect(OTHER_WS_URL) as other_websocket:
- other_websocket.receive_json()
- raise AssertionError()
- assert exc_info.value.code == 1003
- assert exc_info.value.reason == "MARIMO_ALREADY_CONNECTED"
+ # A second EDIT connection is not refused; auto-routes to a viewer.
+ with client.websocket_connect(OTHER_WS_URL) as other_websocket:
+ assert_kernel_ready_response(
+ other_websocket.receive_json(),
+ create_response({"kiosk": True, "resumed": True}),
+ )
def test_allows_multiple_connections_with_same_file(
@@ -135,7 +135,7 @@ def test_allows_multiple_connections_with_same_file(
assert_parse_ready_response(data)
-def test_fails_on_multiple_connections_with_same_file(
+def test_second_connection_with_same_file_joins_as_viewer(
client: TestClient,
temp_marimo_file: str,
) -> None:
@@ -144,12 +144,15 @@ def test_fails_on_multiple_connections_with_same_file(
with client.websocket_connect(ws_1) as websocket:
data = websocket.receive_json()
assert_parse_ready_response(data)
- with pytest.raises(WebSocketDisconnect) as exc_info: # noqa: PT012
- with client.websocket_connect(ws_2) as other_websocket:
- other_websocket.receive_json()
- raise AssertionError()
- assert exc_info.value.code == 1003
- assert exc_info.value.reason == "MARIMO_ALREADY_CONNECTED"
+ # A second EDIT connection is not refused; auto-routes to a viewer.
+ with client.websocket_connect(ws_2) as other_websocket:
+ viewer = parse_raw(
+ other_websocket.receive_json()["data"],
+ KernelReadyNotification,
+ )
+ assert viewer.kiosk is True
+ assert viewer.resumed is True
+ assert viewer.consumer_capabilities.edit is False
async def test_file_watcher_calls_reload(client: TestClient) -> None:
diff --git a/tests/_server/api/endpoints/test_ws_message_loop.py b/tests/_server/api/endpoints/test_ws_message_loop.py
new file mode 100644
index 0000000000..8e88376466
--- /dev/null
+++ b/tests/_server/api/endpoints/test_ws_message_loop.py
@@ -0,0 +1,54 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+from marimo._messaging.notification import (
+ CompletionResultNotification,
+ FocusCellNotification,
+)
+from marimo._server.api.endpoints.ws.ws_message_loop import (
+ WebSocketMessageLoop,
+)
+
+
+def _loop(is_kiosk: bool) -> WebSocketMessageLoop:
+ return WebSocketMessageLoop(
+ websocket=MagicMock(),
+ message_queue=MagicMock(),
+ is_kiosk=lambda: is_kiosk,
+ on_disconnect=MagicMock(),
+ on_check_status_update=MagicMock(),
+ )
+
+
+def test_editor_filters_kiosk_only_and_keeps_completions() -> None:
+ loop = _loop(is_kiosk=False)
+ assert loop._should_filter_operation(FocusCellNotification.name) is True
+ assert (
+ loop._should_filter_operation(CompletionResultNotification.name)
+ is False
+ )
+
+
+def test_viewer_keeps_kiosk_only_and_filters_completions() -> None:
+ loop = _loop(is_kiosk=True)
+ assert loop._should_filter_operation(FocusCellNotification.name) is False
+ assert (
+ loop._should_filter_operation(CompletionResultNotification.name)
+ is True
+ )
+
+
+def test_derived_flag_follows_live_value() -> None:
+ state = {"kiosk": True}
+ loop = WebSocketMessageLoop(
+ websocket=MagicMock(),
+ message_queue=MagicMock(),
+ is_kiosk=lambda: state["kiosk"],
+ on_disconnect=MagicMock(),
+ on_check_status_update=MagicMock(),
+ )
+ assert loop._should_filter_operation(FocusCellNotification.name) is False
+ state["kiosk"] = False # takeover happened
+ assert loop._should_filter_operation(FocusCellNotification.name) is True
diff --git a/tests/_server/api/endpoints/test_ws_session_connector.py b/tests/_server/api/endpoints/test_ws_session_connector.py
new file mode 100644
index 0000000000..f758eb9509
--- /dev/null
+++ b/tests/_server/api/endpoints/test_ws_session_connector.py
@@ -0,0 +1,58 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._server.api.endpoints.ws.ws_session_connector import (
+ ConnectionType,
+ is_viewer_connection,
+)
+
+
+def test_main_editor_is_not_viewer() -> None:
+ for connection_type in (
+ ConnectionType.NEW,
+ ConnectionType.RECONNECT,
+ ConnectionType.RESUME,
+ ):
+ assert (
+ is_viewer_connection(
+ connection_type=connection_type, is_main_consumer=True
+ )
+ is False
+ )
+
+
+def test_kiosk_connection_is_viewer_until_takeover() -> None:
+ assert (
+ is_viewer_connection(
+ connection_type=ConnectionType.KIOSK, is_main_consumer=False
+ )
+ is True
+ )
+ # After taking over, the kiosk viewer becomes the main consumer.
+ assert (
+ is_viewer_connection(
+ connection_type=ConnectionType.KIOSK, is_main_consumer=True
+ )
+ is False
+ )
+
+
+def test_rtc_collaborator_is_never_viewer() -> None:
+ # RTC collaborators connect with main=False but are full editors.
+ assert (
+ is_viewer_connection(
+ connection_type=ConnectionType.RTC_EXISTING,
+ is_main_consumer=False,
+ )
+ is False
+ )
+
+
+def test_demoted_editor_becomes_viewer() -> None:
+ # An editor that was taken over is no longer the main consumer.
+ assert (
+ is_viewer_connection(
+ connection_type=ConnectionType.NEW, is_main_consumer=False
+ )
+ is True
+ )
diff --git a/tests/_server/api/endpoints/ws_helpers.py b/tests/_server/api/endpoints/ws_helpers.py
index e6e30e915d..dfd786b9fd 100644
--- a/tests/_server/api/endpoints/ws_helpers.py
+++ b/tests/_server/api/endpoints/ws_helpers.py
@@ -5,6 +5,7 @@ from typing import Any
from marimo._messaging.msgspec_encoder import asdict
from marimo._messaging.notification import (
+ ConsumerCapabilities,
KernelCapabilitiesNotification,
KernelReadyNotification,
)
@@ -30,6 +31,17 @@ def create_response(
"capabilities": asdict(KernelCapabilitiesNotification()),
}
response.update(partial_response)
+
+ if "consumer_capabilities" not in partial_response:
+ kiosk = response.get("kiosk", False)
+ response.update(
+ {
+ "consumer_capabilities": asdict(
+ ConsumerCapabilities(edit=not kiosk, interact=not kiosk)
+ )
+ }
+ )
+
return response
@@ -63,6 +75,7 @@ def assert_kernel_ready_response(
assert data.kiosk == expected.kiosk
assert data.last_execution_time == expected.last_execution_time
assert data.capabilities == expected.capabilities
+ assert data.consumer_capabilities == expected.consumer_capabilities
def assert_parse_ready_response(raw_data: dict[str, Any]) -> None:
diff --git a/tests/_session/test_consumer_policy.py b/tests/_session/test_consumer_policy.py
new file mode 100644
index 0000000000..2b001ad821
--- /dev/null
+++ b/tests/_session/test_consumer_policy.py
@@ -0,0 +1,47 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+from marimo._messaging.notification import ConsumerCapabilities
+from marimo._session.consumer_policy import (
+ TakeoverDecision,
+ can_take_over_editing,
+ initial_capabilities,
+)
+from marimo._session.model import ConnectionState
+from marimo._types.ids import ConsumerId
+
+
+def _params(*, kiosk: bool) -> MagicMock:
+ params = MagicMock()
+ params.kiosk = kiosk
+ return params
+
+
+def test_initial_capabilities_editor_when_no_live_editor() -> None:
+ session = MagicMock()
+ session.connection_state.return_value = ConnectionState.ORPHANED
+ caps = initial_capabilities(session, _params(kiosk=False))
+ assert caps == ConsumerCapabilities(edit=True, interact=True)
+
+
+def test_initial_capabilities_viewer_when_live_editor() -> None:
+ session = MagicMock()
+ session.connection_state.return_value = ConnectionState.OPEN
+ caps = initial_capabilities(session, _params(kiosk=False))
+ assert caps == ConsumerCapabilities(edit=False, interact=False)
+
+
+def test_initial_capabilities_viewer_when_kiosk_requested() -> None:
+ session = MagicMock()
+ session.connection_state.return_value = ConnectionState.ORPHANED
+ caps = initial_capabilities(session, _params(kiosk=True))
+ assert caps == ConsumerCapabilities(edit=False, interact=False)
+
+
+def test_can_take_over_editing_allows_locally() -> None:
+ assert (
+ can_take_over_editing(MagicMock(), ConsumerId("abc"))
+ is TakeoverDecision.ALLOW
+ )
diff --git a/tests/_session/test_room.py b/tests/_session/test_room.py
new file mode 100644
index 0000000000..99b1b2a0a9
--- /dev/null
+++ b/tests/_session/test_room.py
@@ -0,0 +1,112 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._messaging.notification import ConsumerCapabilities
+from marimo._messaging.serde import deserialize_kernel_message
+from marimo._messaging.types import KernelMessage
+from marimo._session.consumer import SessionConsumer
+from marimo._session.model import ConnectionState
+from marimo._session.room import Room
+from marimo._types.ids import ConsumerId
+
+
+class FakeConsumer(SessionConsumer):
+ def __init__(self, cid: str) -> None:
+ self._cid = ConsumerId(cid)
+ self.received: list[KernelMessage] = []
+ self.state = ConnectionState.OPEN
+
+ @property
+ def consumer_id(self) -> ConsumerId:
+ return self._cid
+
+ def notify(self, notification: KernelMessage) -> None:
+ self.received.append(notification)
+
+ def connection_state(self) -> ConnectionState:
+ return self.state
+
+ def on_attach(self, session, event_bus) -> None: # type: ignore[no-untyped-def]
+ del session, event_bus
+
+ def on_detach(self) -> None:
+ return
+
+
+def _caps(received: list[KernelMessage]) -> list[ConsumerCapabilities]:
+ out: list[ConsumerCapabilities] = []
+ for raw in received:
+ notif = deserialize_kernel_message(raw)
+ if notif.name == "consumer-capabilities":
+ out.append(notif.consumer_capabilities) # type: ignore[attr-defined]
+ return out
+
+
+def _room_with(editor: FakeConsumer, *viewers: FakeConsumer) -> Room:
+ room = Room()
+ room.add_consumer(editor, consumer_id=editor.consumer_id, main=True)
+ for v in viewers:
+ room.add_consumer(v, consumer_id=v.consumer_id, main=False)
+ return room
+
+
+def test_get_consumer_resolves_by_id() -> None:
+ a, b = FakeConsumer("a"), FakeConsumer("b")
+ room = _room_with(a, b)
+ assert room.get_consumer(ConsumerId("b")) is b
+ assert room.get_consumer(ConsumerId("missing")) is None
+
+
+def test_get_capabilities_editor_vs_viewer() -> None:
+ a, b = FakeConsumer("a"), FakeConsumer("b")
+ room = _room_with(a, b)
+ assert room.get_capabilities(a) == ConsumerCapabilities(
+ edit=True, interact=True
+ )
+ assert room.get_capabilities(b) == ConsumerCapabilities(
+ edit=False, interact=False
+ )
+
+
+def test_promote_demotes_old_grants_new_no_disconnect() -> None:
+ a, b = FakeConsumer("a"), FakeConsumer("b")
+ room = _room_with(a, b)
+
+ room.promote_consumer_to_main(b)
+
+ assert room.main_consumer is b
+ # both still members; no disconnect
+ assert a in room.consumers
+ assert b in room.consumers
+ # old editor -> viewer caps; new editor -> editor caps
+ assert _caps(a.received) == [
+ ConsumerCapabilities(edit=False, interact=False)
+ ]
+ assert _caps(b.received) == [
+ ConsumerCapabilities(edit=True, interact=True)
+ ]
+
+
+def test_promote_third_viewer_untouched() -> None:
+ a, b, c = FakeConsumer("a"), FakeConsumer("b"), FakeConsumer("c")
+ room = _room_with(a, b, c)
+ room.promote_consumer_to_main(b)
+ assert _caps(c.received) == []
+
+
+def test_promote_noop_when_already_editor() -> None:
+ a = FakeConsumer("a")
+ room = _room_with(a)
+ room.promote_consumer_to_main(a)
+ assert _caps(a.received) == []
+
+
+def test_promote_skips_closed_consumer() -> None:
+ a, b = FakeConsumer("a"), FakeConsumer("b")
+ room = _room_with(a, b)
+ a.state = ConnectionState.CLOSED
+ room.promote_consumer_to_main(b)
+ assert _caps(a.received) == [] # closed: not notified
+ assert _caps(b.received) == [
+ ConsumerCapabilities(edit=True, interact=True)
+ ]