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
Remove experimental real-time collaboration (#11625)
Trevor Manz333bcd6422ea
diff --git a/docs/guides/deploying/index.md b/docs/guides/deploying/index.mdindex 7dfc47bc11..a212497c9d 100644--- a/docs/guides/deploying/index.md+++ b/docs/guides/deploying/index.md@@ -69,8 +69,6 @@ This setting is experimental. Keep in mind:- The terminal and language servers (LSP) in `marimo edit` still requireWebSockets and are unaffected by this setting.-- Real-time collaboration (`rtc_v2`) requires WebSockets and is disabled- when using SSE.- Make sure proxies do not buffer the `/sse` endpoint's`text/event-stream` responses (marimo sends `Cache-Control: no-transform`and `X-Accel-Buffering: no` headers, and a keep-alive comment every 20diff --git a/frontend/islands/vite.config.mts b/frontend/islands/vite.config.mtsindex 899f2c5572..55f88b2482 100644--- a/frontend/islands/vite.config.mts+++ b/frontend/islands/vite.config.mts@@ -7,7 +7,6 @@ import { fileURLToPath } from "node:url";import { promisify } from "node:util";import react from "@vitejs/plugin-react";import { defineConfig, type Plugin } from "vite";-import wasm from "vite-plugin-wasm";import { createViteLogger, reactCompilerConfig } from "../vite.shared.mts";import packageJson from "../package.json";@@ -121,7 +120,6 @@ export default defineConfig({// React Compiler backed by Oxc (oxc-transform-react)compiler: reactCompilerConfig,}),- wasm(),],build: {emptyOutDir: true,diff --git a/frontend/package.json b/frontend/package.jsonindex 1dd10299a8..e664707a18 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -52,12 +52,12 @@"@lezer/lr": "^1.4.10","@lezer/markdown": "^1.7.2","@lezer/python": "^1.1.19",+ "@marimo-team/client": "workspace:*","@marimo-team/codemirror-ai": "^0.3.10","@marimo-team/codemirror-languageserver": "^2.0.1","@marimo-team/codemirror-mcp": "^0.1.7","@marimo-team/codemirror-sql": "^0.3.0","@marimo-team/llm-info": "workspace:*",- "@marimo-team/client": "workspace:*","@marimo-team/marimo-api": "workspace:*","@marimo-team/react-slotz": "^0.2.0","@marimo-team/smart-cells": "workspace:*",@@ -111,13 +111,10 @@"js-cookie": "^3.0.8","katex": "^0.18.7","lodash-es": "^4.18.1",- "loro-codemirror": "^0.3.3",- "loro-crdt": "^1.16.1","lucide-react": "^0.577.0","lz-string": "^1.5.0","marked": "^15.0.12","mermaid": "^11.17.2",- "partysocket": "1.3.0","path-to-regexp": "^8.4.2","plotly.js": "^3.7.0","pyodide": "314.0.0",@@ -228,7 +225,6 @@"tailwindcss": "^4.3.3","vega-typings": "^2.3.0","vite": "^8.3.4",- "vite-plugin-wasm": "^3.6.0","vitest": "^4.1.11","yaml": "^2.9.1"}diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 060f15f67a..dbcb51d0aa 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -23,7 +23,6 @@ import {Form,FormControl,FormDescription,- FormField,FormItem,FormLabel,FormMessage,@@ -1293,31 +1292,6 @@ export const UserConfigForm: React.FC = () => {notebook to take effect.</p>- <FormField- control={form.control}- name="experimental.rtc_v2"- render={({ field }) => (- <div className="flex flex-col gap-y-1">- <FormItem className={formItemClasses}>- <FormLabel className="font-normal">- Real-Time Collaboration- </FormLabel>- <FormControl>- <Checkbox- data-testid="rtc-checkbox"- checked={field.value === true}- onCheckedChange={field.onChange}- />- </FormControl>- </FormItem>-- <FormDescription>- Enable experimental real-time collaboration. This change- requires a page refresh to take effect.- </FormDescription>- </div>- )}- /><OverriddenFormFieldcontrol={form.control}name="experimental.external_agents"diff --git a/frontend/src/components/editor/cell/code/__tests__/rtc-editor-config.test.ts b/frontend/src/components/editor/cell/code/__tests__/rtc-editor-config.test.tsdeleted file mode 100644index e9b8bacb70..0000000000--- a/frontend/src/components/editor/cell/code/__tests__/rtc-editor-config.test.ts+++ /dev/null@@ -1,50 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import { EditorState } from "@codemirror/state";-import { describe, expect, it } from "vitest";-import { composeRtcEditorConfig } from "../cell-editor";--describe("composeRtcEditorConfig", () => {- it("does not accumulate RTC extensions across reconfigurations", () => {- const baseExtension = EditorState.readOnly.of(false);- const baseExtensions = [baseExtension];- const firstRtc = {- code: "first RTC code",- extension: EditorState.tabSize.of(2),- };- const secondRtc = {- code: "second RTC code",- extension: EditorState.tabSize.of(4),- };-- const firstConfig = composeRtcEditorConfig(- "local code",- baseExtensions,- firstRtc,- );- const secondConfig = composeRtcEditorConfig(- "local code",- baseExtensions,- secondRtc,- );-- expect(baseExtensions).toEqual([baseExtension]);- expect(firstConfig).toEqual({- code: firstRtc.code,- extensions: [baseExtension, firstRtc.extension],- });- expect(secondConfig).toEqual({- code: secondRtc.code,- extensions: [baseExtension, secondRtc.extension],- });- });-- it("reuses the base configuration when RTC is disabled", () => {- const extensions = [EditorState.readOnly.of(false)];-- const config = composeRtcEditorConfig("local code", extensions, undefined);-- expect(config).toEqual({ code: "local code", extensions });- expect(config.extensions).toBe(extensions);- });-});diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 7bd555330f..792203e21b 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -1,13 +1,11 @@/* Copyright 2026 Marimo. All rights reserved. */import { historyField } from "@codemirror/commands";-import { EditorState, type Extension, StateEffect } from "@codemirror/state";+import { EditorState, StateEffect } from "@codemirror/state";import { EditorView, ViewPlugin } from "@codemirror/view";import { useIntersectionObserver } from "@uidotdev/usehooks";import { useAtom, useAtomValue, useSetAtom } from "jotai";import React, { memo, useEffect, useMemo, useRef, useState } from "react";import useEvent from "react-use-event-hook";-import { Button } from "@/components/ui/button";-import { DelayMount } from "@/components/utils/delay-mount";import { aiCompletionCellAtom } from "@/core/ai/state";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { getNotebook } from "@/core/cells/cells";@@ -35,17 +33,10 @@ import { prepareCellCodeUpdate } from "@/core/codemirror/language/cell-code";import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";import { MARKDOWN_INITIAL_HIDE_CODE } from "@/core/codemirror/language/languages/markdown";import type { LanguageAdapterType } from "@/core/codemirror/language/types";-import {- connectedDocAtom,- realTimeCollaboration,-} from "@/core/codemirror/rtc/extension";import { autoInstantiateAtom, isAiFeatureEnabled } from "@/core/config/config";import type { UserConfig } from "@/core/config/config-schema";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";-import { connectionAtom } from "@/core/network/connection";-import { canUseRtc, isRtcEnabled } from "@/core/rtc/state";import { useSaveNotebook } from "@/core/saving/save-component";-import { isAppConnecting } from "@/core/session/connection-utils";import type { Theme } from "@/theme/useTheme";import { cn } from "@/utils/cn";import { invariant } from "@/utils/invariant";@@ -99,21 +90,6 @@ export interface CellEditorPropstooltipParentSelector?: string;}-export function composeRtcEditorConfig(- code: string,- extensions: Extension[],- rtc: ReturnType<typeof realTimeCollaboration> | undefined,-): { code: string; extensions: Extension[] } {- if (!rtc) {- return { code, extensions };- }-- return {- code: rtc.code,- extensions: [...extensions, rtc.extension],- };-}-const CellEditorInternal = ({theme,showPlaceholder,@@ -358,42 +334,24 @@ const CellEditorInternal = ({saveOrNameNotebook,]);- const rtcEnabled = isRtcEnabled() && canUseRtc(cellId);- const createEditorConfig = (initialCode?: string) => {- if (!rtcEnabled) {- return composeRtcEditorConfig(code, extensions, undefined);- }-- const rtc = realTimeCollaboration(cellId, initialCode);- return composeRtcEditorConfig(code, extensions, rtc);- };-const handleInitializeEditor = useEvent(() => {- const editorConfig = createEditorConfig(code);-// Create a new editorconst ev = new EditorView({- state: EditorState.create({- doc: editorConfig.code,- extensions: editorConfig.extensions,- }),+ state: EditorState.create({ doc: code, extensions }),});setEditorView(ev);// Initialize the language adapter- if (!rtcEnabled) {- switchLanguage(ev, {- language: getInitialLanguageAdapter(ev.state).type,- });- }+ switchLanguage(ev, {+ language: getInitialLanguageAdapter(ev.state).type,+ });});const handleReconfigureEditor = useEvent(() => {invariant(editorViewRef.current !== null, "Editor view is not initialized");- const editorConfig = createEditorConfig();editorViewRef.current.dispatch({effects: [- StateEffect.reconfigure.of([editorConfig.extensions]),+ StateEffect.reconfigure.of([extensions]),reconfigureLanguageEffect(editorViewRef.current, {completionConfig: userConfig.completion,hotkeysProvider: new OverridingHotkeyProvider(@@ -410,24 +368,18 @@ const CellEditorInternal = ({const handleDeserializeEditor = useEvent(() => {invariant(serializedEditorState, "Editor view is not initialized");- const editorConfig = createEditorConfig(code);const ev = new EditorView({state: EditorState.fromJSON(serializedEditorState,- {- doc: editorConfig.code,- extensions: editorConfig.extensions,- },+ { doc: code, extensions },{ history: historyField },),});// Initialize the language adapter- if (!rtcEnabled) {- switchLanguage(ev, {- language: getInitialLanguageAdapter(ev.state).type,- });- }+ switchLanguage(ev, {+ language: getInitialLanguageAdapter(ev.state).type,+ });setEditorView(ev);// The restored state is used once; the next mount builds a fresh editor.takeRestoredEditorState({ cellId });@@ -626,45 +578,4 @@ const CellCodeMirrorEditor = React.forwardRef();CellCodeMirrorEditor.displayName = "CellCodeMirrorEditor";-// Wait until the websocket connection is open before rendering the editor-// This is used for real-time collaboration since the backend needs the connection started-// before connecting the rtc websockets-function WithWaitUntilConnected<T extends Pick<CellEditorProps, "id">>(- Component: React.ComponentType<T>,-) {- const WaitUntilConnectedComponent = (props: T) => {- const connection = useAtomValue(connectionAtom);- const [rtcDoc, setRtcDoc] = useAtom(connectedDocAtom);-- if (- isRtcEnabled() &&- canUseRtc(props.id) &&- (isAppConnecting(connection.state) || rtcDoc === undefined)- ) {- return (- <div className="flex h-full w-full items-baseline p-4">- <DelayMount milliseconds={1000} fallback={null}>- <span>Waiting for real-time collaboration connection...</span>- <Button- variant="link"- onClick={() => {- setRtcDoc("disabled");- }}- >- Turn off real-time collaboration- </Button>- </DelayMount>- </div>- );- }-- return <Component {...props} />;- };-- WaitUntilConnectedComponent.displayName = `WithWaitUntilConnected(${Component.displayName})`;- return WaitUntilConnectedComponent;-}--export const CellEditor = isRtcEnabled()- ? WithWaitUntilConnected(memo(CellEditorInternal))- : memo(CellEditorInternal);+export const CellEditor = memo(CellEditorInternal);diff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/rtc-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/rtc-status.tsxdeleted file mode 100644index a202e90b0d..0000000000--- a/frontend/src/components/editor/chrome/wrapper/footer-items/rtc-status.tsx+++ /dev/null@@ -1,65 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import { useAtom, useAtomValue } from "jotai";-import { UsersIcon } from "lucide-react";-import type React from "react";-import { useState } from "react";-import { Input } from "@/components/ui/input";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/components/ui/popover";-import { connectedDocAtom } from "@/core/codemirror/rtc/extension";-import { isRtcEnabled, usernameAtom } from "@/core/rtc/state";-import { FooterItem } from "../footer-item";--export const RTCStatus: React.FC = () => {- const connectedDoc = useAtomValue(connectedDocAtom);- const [username, setUsername] = useAtom(usernameAtom);- const [open, setOpen] = useState(false);-- if (!isRtcEnabled()) {- return null;- }-- if (connectedDoc === "disabled") {- return null;- }-- const tooltip = connectedDoc- ? "Real-time collaboration active"- : "Connecting to real-time collaboration";-- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild={true}>- <FooterItem- tooltip={tooltip}- selected={false}- data-testid="footer-rtc-status"- >- <UsersIcon className="w-4 h-4" />- </FooterItem>- </PopoverTrigger>- <PopoverContent className="w-80">- <div className="space-y-4">- <div className="space-y-2">- <h4 className="font-medium leading-none">Username</h4>- <p className="text-sm text-muted-foreground">- Set your username for real-time collaboration- </p>- </div>- <Input- value={username}- autoCapitalize="off"- autoComplete="off"- autoCorrect="off"- onChange={(e) => setUsername(e.target.value)}- placeholder="Enter your username"- />- </div>- </PopoverContent>- </Popover>- );-};diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsxindex 03e846ec5c..90ea866638 100644--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx@@ -21,7 +21,6 @@ import { CopilotStatusIcon } from "./footer-items/copilot-status";import { DocumentSyncStatus } from "./footer-items/document-sync-status";import { MachineStats } from "./footer-items/machine-stats";import { PyodideStatus } from "./footer-items/pyodide-status";-import { RTCStatus } from "./footer-items/rtc-status";import { RuntimeSettings } from "./footer-items/runtime-settings";import { useSetDependencyPanelTab } from "./useDependencyPanelTab";@@ -113,7 +112,6 @@ export const Footer: React.FC = () => {<AttachmentStatus /><AIStatusIcon /><CopilotStatusIcon />- <RTCStatus /></div></footer>);diff --git a/frontend/src/core/cells/__tests__/document.test.ts b/frontend/src/core/cells/__tests__/document.test.tsindex f6c4d23692..ee6185a8b0 100644--- a/frontend/src/core/cells/__tests__/document.test.ts+++ b/frontend/src/core/cells/__tests__/document.test.ts@@ -21,7 +21,6 @@ import {import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";import { store } from "@/core/state/jotai";import { activeDocumentModelAtom } from "@/core/session/active-notebook";-import { isRtcEnabled } from "../../rtc/state";import {createNotebookActions,exportedForTesting,@@ -31,11 +30,6 @@ import {import { applyDocument, flushDocument, followDocument } from "../document";import { type CellId, SCRATCH_CELL_ID } from "../ids";-vi.mock("../../rtc/state", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../rtc/state")>()),- isRtcEnabled: vi.fn(() => false),-}));-const { initialNotebookState } = exportedForTesting;const a = cellId("a");@@ -148,18 +142,6 @@ describe("applyDocument", () => {expect(view.state.field(languageAdapterState).type).toBe("python");});- it("leaves an RTC editor to Loro", () => {- vi.mocked(isRtcEnabled).mockReturnValueOnce(true);- const state = notebookOf([cell(a)]);- const view = createEditor("a = 1");- state.cellHandles[a].current = { editorView: view, editorViewOrNull: view };-- const next = applyDocument(state, documentOf([cell(a, { code: "a = 2" })]));-- expect(next.cellData[a].code).toBe("a = 2");- expect(view.state.doc.toString()).toBe("a = 1");- });-it("keeps the code this client has when the host withholds source", () => {const state = notebookOf([cell(a)]);diff --git a/frontend/src/core/cells/document.ts b/frontend/src/core/cells/document.tsindex d0be7c4040..290def0a50 100644--- a/frontend/src/core/cells/document.ts+++ b/frontend/src/core/cells/document.ts@@ -21,7 +21,6 @@ import type {} from "@/core/notebook/document";import type { DispatchedActionOf } from "@/utils/createReducer";import { prepareCellCodeUpdate } from "../codemirror/language/cell-code";-import { canUseRtc, isRtcEnabled } from "../rtc/state";import { store } from "../state/jotai";import { activeDocumentModelAtom } from "../session/active-notebook";import type { NotebookState, ReducerCellActions } from "./cells";@@ -60,14 +59,12 @@ function followCell(if (code === current.code) {return { ...current, name: cell.name, config };}- // RTC cells follow Loro. Other editors take the host's code; one that- // shows it already, as the editor this client types in does, is left alone.- if (!isRtcEnabled() || !canUseRtc(current.id)) {- const view = handle?.current?.editorViewOrNull;- const update = view && prepareCellCodeUpdate(view.state, code);- if (update) {- view.dispatch(update);- }+ // The editor takes the host's code; one that shows it already, as the+ // editor this client types in does, is left alone.+ const view = handle?.current?.editorViewOrNull;+ const update = view && prepareCellCodeUpdate(view.state, code);+ if (update) {+ view.dispatch(update);}return {...current,diff --git a/frontend/src/core/codemirror/cells/__tests__/extensions.test.ts b/frontend/src/core/codemirror/cells/__tests__/extensions.test.tsindex 103520171b..431fad1199 100644--- a/frontend/src/core/codemirror/cells/__tests__/extensions.test.ts+++ b/frontend/src/core/codemirror/cells/__tests__/extensions.test.ts@@ -8,11 +8,9 @@ import {} from "@codemirror/state";import { describe, expect, it } from "vitest";import { formattingChangeEffect } from "../../format";-import { loroSyncAnnotation } from "../../rtc/loro/sync";import { exportedForTesting } from "../extensions";-const { isCollaboratorUpdate, shouldAutorunMarkdownUpdate } =- exportedForTesting;+const { shouldAutorunMarkdownUpdate } = exportedForTesting;function createTransaction(spec: TransactionSpec) {return EditorState.create({ doc: "" }).update(spec);@@ -51,24 +49,6 @@ describe("shouldAutorunMarkdownUpdate", () => {).toBe(false);});- it("ignores RTC sync transactions", () => {- const transaction = createTransaction({- changes: { from: 0, insert: "#" },- annotations: [- Transaction.userEvent.of("input.type"),- loroSyncAnnotation.of(true),- ],- });-- expect(- shouldAutorunMarkdownUpdate({- docChanged: transaction.docChanged,- transactions: [transaction],- hasFocus: true,- }),- ).toBe(false);- });-it("ignores remote transactions while focused", () => {const transaction = createTransaction({changes: { from: 0, insert: "#" },@@ -126,28 +106,3 @@ describe("shouldAutorunMarkdownUpdate", () => {).toBe(false);});});--describe("isCollaboratorUpdate", () => {- it("recognizes an update made only of Loro sync transactions", () => {- const transaction = createTransaction({- changes: { from: 0, insert: "#" },- annotations: [loroSyncAnnotation.of(true)],- });-- expect(isCollaboratorUpdate([transaction])).toBe(true);- });-- it("treats typing beside a Loro sync transaction as local", () => {- const remote = createTransaction({- changes: { from: 0, insert: "#" },- annotations: [loroSyncAnnotation.of(true)],- });- const local = createTransaction({- changes: { from: 0, insert: "x" },- annotations: [Transaction.userEvent.of("input.type")],- });-- expect(isCollaboratorUpdate([remote, local])).toBe(false);- expect(isCollaboratorUpdate([])).toBe(false);- });-});diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex 7969f520ec..5c989bf91e 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -14,7 +14,6 @@ import {clearPendingCutAtom,pendingCutCellIdsAtom,} from "@/core/cells/pending-cut-service";-import { loroSyncAnnotation } from "@/core/codemirror/rtc/loro/sync";import type { KeymapConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { getFeatureFlag } from "@/core/config/feature-flag";@@ -325,11 +324,6 @@ function cellKeymaps({function cellCodeEditing(hotkeys: HotkeyProvider): Extension[] {const onChangePlugin = EditorView.updateListener.of((update) => {if (update.docChanged) {- // Loro already applied a collaborator's change here. The client that- // typed it syncs it to the document.- if (isCollaboratorUpdate(update.transactions)) {- return;- }// Check if the doc update was a formatting change// e.g. changing from python to markdownconst isFormattingChange = update.transactions.some((tr) =>@@ -355,14 +349,6 @@ function cellCodeEditing(hotkeys: HotkeyProvider): Extension[] {return [onChangePlugin, formatKeymapExtension(hotkeys)];}-/** Whether every transaction in an update arrived from a collaborator through Loro. */-function isCollaboratorUpdate(transactions: readonly Transaction[]): boolean {- return (- transactions.length > 0 &&- transactions.every((tr) => tr.annotation(loroSyncAnnotation) !== undefined)- );-}-const MARKDOWN_AUTORUN_USER_EVENTS = ["input", "delete", "undo", "redo"];function shouldAutorunMarkdownUpdate({@@ -397,10 +383,7 @@ function shouldAutorunMarkdownUpdate({return transactions.some((tr) => {// Ignore remote changes to avoid duplicate runs. The client that made the// edit runs it.- if (- tr.annotation(Transaction.remote) ||- tr.annotation(loroSyncAnnotation) !== undefined- ) {+ if (tr.annotation(Transaction.remote)) {return false;}@@ -480,6 +463,5 @@ export function cellBundle({}export const exportedForTesting = {- isCollaboratorUpdate,shouldAutorunMarkdownUpdate,};diff --git a/frontend/src/core/codemirror/rtc/extension.ts b/frontend/src/core/codemirror/rtc/extension.tsdeleted file mode 100644index 3e28056bc8..0000000000--- a/frontend/src/core/codemirror/rtc/extension.ts+++ /dev/null@@ -1,464 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import type { Extension } from "@codemirror/state";-import { EditorView, ViewPlugin } from "@codemirror/view";-import { dequal as isEqual } from "dequal";-import { atom } from "jotai";-import { Awareness, LoroDoc, LoroMap, LoroText } from "loro-crdt";-import ReconnectingWebSocket from "partysocket/ws";-import type { CellId } from "@/core/cells/ids";-import { getSessionId } from "@/core/kernel/session";-import { getInitialAppMode } from "@/core/mode";-import { waitForConnectionOpen } from "@/core/network/connection";-import { isRtcEnabled, usernameAtom } from "@/core/rtc/state";-import { getRuntimeManager } from "@/core/runtime/config";-import { store } from "@/core/state/jotai";-import { isWasm } from "@/core/wasm/utils";-import { invariant } from "@/utils/invariant";-import { Logger } from "@/utils/Logger";-import { once } from "@/utils/once";-import {- getInitialLanguageAdapter,- languageAdapterState,- setLanguageAdapter,- switchLanguage,-} from "../language/extension";-import {- languageMetadataField,- setLanguageMetadata,- updateLanguageMetadata,-} from "../language/metadata";-import type { LanguageAdapterType } from "../language/types";-import type { AwarenessState, ScopeId, Uid, UserState } from "./loro/awareness";-import {- AwarenessPlugin,- createCursorLayer,- createSelectionLayer,- loroCursorTheme,- RemoteAwarenessPlugin,- remoteAwarenessStateField,-} from "./loro/awareness";-import { getColor } from "./loro/colors";-import { loroSyncAnnotation, loroSyncPlugin } from "./loro/sync";--const logger = Logger.get("rtc");-const awarenessLogger = logger.get("awareness").disabled();--const AWARENESS_PREFIX = "awareness:";--// Utility functions for message handling-function prefixMessage(- token: string,- message: Uint8Array,-): Uint8Array<ArrayBuffer> {- const tokenBytes = new TextEncoder().encode(token);- return new Uint8Array([...tokenBytes, ...message]);-}--function hasPrefix(data: Uint8Array, prefix: string): boolean {- const decoder = new TextDecoder();- const dataPrefix = decoder.decode(data.slice(0, prefix.length));- return dataPrefix === prefix;-}--function removePrefix(data: Uint8Array, prefix: string): Uint8Array {- return data.slice(prefix.length);-}--export const connectedDocAtom = atom<LoroDoc | "disabled" | undefined>(- undefined,-);--// Create a Loro document-const doc = new LoroDoc();-const awareness = new Awareness<AwarenessState>(doc.peerIdStr);-// const undoManager = new UndoManager(doc, {});--// Create a websocket connection to the server-const getWs = once(() => {- logger.debug("creating websocket");-- const runtimeManager = getRuntimeManager();- const url = runtimeManager.getWsSyncURL(getSessionId()).toString();-- // Create the websocket, but don't connect it yet- const ws = new ReconnectingWebSocket(url, undefined, {- // We don't want Infinity retries- maxRetries: 10,- debug: false,- startClosed: true,- connectionTimeout: 10_000,- });-- // Start the connection- Promise.resolve().then(async () => {- // First wait the main /ws connection to be open- // This is to ensure the LoroDoc is created on the server- await waitForConnectionOpen();-- // Don't open the websocket if not in edit mode- if (getInitialAppMode() !== "edit") {- return;- }-- // Now open the websocket- ws.reconnect();- });-- // Receive updates from the server- ws.addEventListener("message", async (event) => {- const blob: Blob = event.data;- const bytes = await blob.arrayBuffer();- const data = new Uint8Array(bytes);-- // Handle awareness update- if (hasPrefix(data, AWARENESS_PREFIX)) {- const awarenessData = removePrefix(data, AWARENESS_PREFIX);- awareness.apply(awarenessData);- awarenessLogger.debug("applied awareness update");- return;- }-- // Handle doc update- doc.import(data);- logger.debug("imported doc change. new doc:", doc.toJSON());-- // Set the active doc only once the first message is received- // This is to ensure the LoroDoc is created on the server, and not the client.- if (store.get(connectedDocAtom) !== doc) {- store.set(connectedDocAtom, doc);- }- });-- // Handle open event- ws.addEventListener("open", () => {- logger.debug("websocket open");- });-- // Handle close event- ws.addEventListener("close", (e) => {- logger.warn("websocket close", e);-- // Remove the active doc- if (store.get(connectedDocAtom) === doc) {- store.set(connectedDocAtom, undefined);- }- });-- return ws;-});--// Kickoff the WS connection for edit mode-if (isRtcEnabled()) {- getWs();-}--// Send local updates to the server-doc.subscribeLocalUpdates((update) => {- logger.debug("local update, sending to server");- const ws = getWs();- ws.send(new Uint8Array(update));-});--// Handle awareness changes-awareness.addListener((updates, origin) => {- const changes = [...updates.added, ...updates.removed, ...updates.updated];- if (origin === "local") {- awarenessLogger.debug("awareness changes", changes);- const ws = getWs();- ws.send(prefixMessage(AWARENESS_PREFIX, awareness.encode(changes)));- }-});--export function realTimeCollaboration(- cellId: CellId,- initialCode = "",-): { extension: Extension; code: string } {- if (isWasm()) {- return {- extension: [],- code: initialCode,- };- }-- // Get or create the code container- const hasPath = doc.getByPath(`codes/${cellId}`) !== undefined;- const loroText = doc- .getMap("codes")- .getOrCreateContainer(cellId, new LoroText());- if (!hasPath) {- logger.log("initializing code for new cell", initialCode);- loroText.insert(0, initialCode);- }-- const userState: UserState = {- // We use getters to ensure the user name is up-to-date- get name() {- return store.get(usernameAtom) || "Anonymous";- },- get colorClassName() {- return getColor(this.name);- },- };-- return {- code: initialCode.toString(),- extension: [- languageObserverExtension(cellId),- languageListenerExtension(cellId),- loroAwarenessPlugin({- doc,- awareness,- user: userState,- getTextFromDoc: () => loroText,- cellId,- }),- loroSyncPlugin(doc, ["codes", cellId], () => {- return loroText;- }),- ],- };-}--/**- * Create a view plugin to observe language changes- * When the language changes, we need to update our local language- * Server -> Local- * @param cellId - The cell id- * @returns Extension- */-function languageObserverExtension(cellId: CellId) {- const syncLanguage = (view: EditorView, language: LoroText) => {- const currentLang = view.state.field(languageAdapterState).type;- const newLang = language.toString() as LanguageAdapterType;- if (!newLang) {- return;- }-- if (newLang !== currentLang) {- logger.debug(- `[incoming] setting language type: ${currentLang} -> ${newLang}`,- );- switchLanguage(view, { language: newLang, keepCodeAsIs: true });- }- };-- const syncLanguageMetadata = (- view: EditorView,- languageMetadata: LoroMap,- ) => {- const previousLanguageMetadata = view.state.field(languageMetadataField);- const newLanguageMetadata = languageMetadata.toJSON();- if (isEqual(previousLanguageMetadata, newLanguageMetadata)) {- return;- }-- view.dispatch({- effects: [updateLanguageMetadata.of(newLanguageMetadata)],- annotations: [loroSyncAnnotation.of(true)],- });- };-- return ViewPlugin.define((view) => {- let unsubscribeDoc: () => void;-- // Initialize after a single tick- Promise.resolve().then(() => {- // Language type- const langType = doc.getByPath(`languages/${cellId}`);- if (!langType) {- logger.error("no language container found for cell", cellId);- return;- }- invariant(- langType instanceof LoroText,- "language type is not a LoroText",- );-- // Language metadata- const langMeta = doc.getByPath(`language_metadata/${cellId}`);- if (!langMeta) {- logger.error("no language metadata container found for cell", cellId);- return;- }- invariant(- langMeta instanceof LoroMap,- "language metadata is not a LoroMap",- );-- // Run once- syncLanguage(view, langType);- syncLanguageMetadata(view, langMeta);-- // Subscribe to language and metadata changes- unsubscribeDoc = doc.subscribe((event) => {- if (event.origin === "local") {- // Skip if the change is local- return;- }-- const hasAnyLanguageTypeChanges = event.events.some(- (e) => e.target === langType.id,- );- const hasAnyLanguageMetadataChanges = event.events.some(- (e) => e.target === langMeta.id,- );-- if (hasAnyLanguageTypeChanges) {- syncLanguage(view, langType);- }- if (hasAnyLanguageMetadataChanges) {- syncLanguageMetadata(view, langMeta);- }- });- });-- return {- destroy() {- unsubscribeDoc();- },- };- });-}--/**- * Listen for local language changes- * This is used to sync the language with the server- * Local -> Server- * @returns Extension- */-function languageListenerExtension(cellId: CellId) {- // Get or create the language type container- const currentLang = doc- .getMap("languages")- .getOrCreateContainer(cellId, new LoroText());-- // Get or create the language metadata container- const currentLanguageMetadata = doc- .getMap("language_metadata")- .getOrCreateContainer(cellId, new LoroMap());-- return EditorView.updateListener.of((update) => {- const isInitialized = currentLang.toString() !== "";-- // Skip if the doc hasn't changed and the language is already set- if (!update.docChanged && isInitialized) {- return;- }-- // If the language is not set, set it to the current language- // and update the LoroDoc- if (!isInitialized) {- const language = getInitialLanguageAdapter(update.state).type;- switchLanguage(update.view, { language });- logger.debug("no initial language, setting default to", language);-- // Sync the language to the LoroDoc- currentLang.delete(0, currentLang.length);- currentLang.insert(0, language);-- // Sync the language metadata to the LoroDoc- logger.debug(- "no initial language metadata, setting default to",- update.state.field(languageMetadataField),- );- const metadata = update.state.field(languageMetadataField);- for (const key of Object.keys(metadata)) {- currentLanguageMetadata.set(key, metadata[key]);- }-- // Commit the changes- doc.commit();-- return;- }-- let hasChanges = false;-- for (const tr of update.transactions) {- const isSyncOperation = tr.annotation(loroSyncAnnotation);- if (isSyncOperation) {- continue;- }-- for (const e of tr.effects) {- // Language type- if (- e.is(setLanguageAdapter) &&- currentLang.toString() !== e.value.type- ) {- logger.debug(- `[outgoing] language change: ${currentLang} -> ${e.value.type}`,- );- currentLang.delete(0, currentLang.length);- currentLang.insert(0, e.value.type);- hasChanges = true;- }-- // Language metadata- if (e.is(updateLanguageMetadata) || e.is(setLanguageMetadata)) {- const metadata = e.value;-- // If it is set, we should clear the metadata first- if (e.is(setLanguageMetadata)) {- logger.debug("[outgoing] setting language metadata: ", metadata);- currentLanguageMetadata.clear();- } else {- logger.debug("[outgoing] updating language metadata: ", metadata);- }-- for (const key of Object.keys(metadata)) {- currentLanguageMetadata.set(key, metadata[key]);- }- hasChanges = true;- }- }- }-- if (hasChanges) {- doc.commit();- }- });-}--/**- * Create a plugin to observe awareness changes- */-function loroAwarenessPlugin({- doc,- awareness,- user,- getTextFromDoc,- cellId,- getUserId,-}: {- doc: LoroDoc;- awareness: Awareness<AwarenessState>;- user: UserState;- getTextFromDoc: (doc: LoroDoc) => LoroText;- cellId: CellId;- getUserId?: () => Uid;-}): Extension[] {- const scopeId = `loro:cell:${cellId}` as ScopeId;-- return [- remoteAwarenessStateField,- createCursorLayer(),- createSelectionLayer(),- ViewPlugin.define(- (view) =>- new AwarenessPlugin(view, {- doc,- user,- awareness,- getTextFromDoc,- scopeId,- getUserId,- }),- ),- ViewPlugin.define(- (view) => new RemoteAwarenessPlugin(view, doc, awareness, scopeId),- ),- loroCursorTheme,- ];-}diff --git a/frontend/src/core/codemirror/rtc/loro/__tests__/sync.test.ts b/frontend/src/core/codemirror/rtc/loro/__tests__/sync.test.tsdeleted file mode 100644index 2f5ca5088c..0000000000--- a/frontend/src/core/codemirror/rtc/loro/__tests__/sync.test.ts+++ /dev/null@@ -1,52 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import { EditorState } from "@codemirror/state";-import type { EditorView } from "@codemirror/view";-import { LoroDoc, LoroText } from "loro-crdt";-import { describe, expect, it, vi } from "vitest";-import { LoroSyncPluginValue, loroSyncAnnotation } from "../sync";--describe("LoroSyncPluginValue", () => {- it("annotates the initial reconciliation dispatch as RTC sync", async () => {- const dispatch = vi.fn();- const view = {- state: EditorState.create({ doc: "local" }),- dispatch,- } as unknown as EditorView;-- const doc = new LoroDoc();- const text = doc- .getMap("codes")- .getOrCreateContainer("cell-1", new LoroText());- text.insert(0, "remote");-- const plugin = new LoroSyncPluginValue(- view,- doc,- ["codes", "cell-1"],- () => text,- );-- await Promise.resolve();-- expect(dispatch).toHaveBeenCalledTimes(1);- expect(dispatch).toHaveBeenCalledWith(- expect.objectContaining({- changes: [- {- from: 0,- to: view.state.doc.length,- insert: "remote",- },- ],- annotations: [- expect.objectContaining({- type: loroSyncAnnotation,- }),- ],- }),- );-- plugin.destroy();- });-});diff --git a/frontend/src/core/codemirror/rtc/loro/awareness.ts b/frontend/src/core/codemirror/rtc/loro/awareness.tsdeleted file mode 100644index ec8f4ac140..0000000000--- a/frontend/src/core/codemirror/rtc/loro/awareness.ts+++ /dev/null@@ -1,546 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import {- Annotation,- EditorSelection,- type Extension,- type SelectionRange,- StateEffect,- StateField,-} from "@codemirror/state";-import {- Direction,- EditorView,- type LayerMarker,- layer,- type PluginValue,- type Rect,- RectangleMarker,- type ViewUpdate,-} from "@codemirror/view";-import {- type Awareness,- type AwarenessListener,- Cursor,- type LoroDoc,- type LoroText,- type PeerID,- type Subscription,-} from "loro-crdt";-import type { TypedString } from "@/utils/typed";--export type ScopeId = TypedString<"loro:scope">;-export type Uid = TypedString<"loro:uid"> | PeerID;--export const loroCursorTheme = EditorView.baseTheme({- ".loro-cursor": {- position: "absolute",- width: "2px",- display: "inline-block",- height: "1.2em",- },- ".loro-cursor::before": {- position: "absolute",- top: "1.3em",- left: "0",- content: "var(--rtc-name)",- padding: "2px 6px",- fontSize: "12px",- borderRadius: "3px",- whiteSpace: "nowrap",- userSelect: "none",- backgroundColor: "inherit",- opacity: "0.7",- },- ".loro-selection": {- opacity: "0.5",- },-});--export type AwarenessState =- | {- type: "update";- uid: Uid;- scopeId: ScopeId;- cursor: { anchor: Uint8Array; head?: Uint8Array };- user?: {- name: string;- colorClassName: string;- };- }- | {- type: "delete";- uid: Uid;- scopeId: ScopeId;- };--export interface UserState {- name: string;- colorClassName: string;-}--type CursorEffect =- | {- type: "update";- peer: Uid;- scopeId: ScopeId;- cursor: { anchor: number; head?: number };- user?: UserState;- }- | {- type: "delete";- peer: Uid;- scopeId: ScopeId;- }- | {- type: "checkout";- checkout: boolean;- };--// We should use layer https://github.com/codemirror/dev/issues/989-export const remoteAwarenessAnnotation = Annotation.define<undefined>();-export const remoteAwarenessEffect = StateEffect.define<CursorEffect>();-export const remoteAwarenessStateField = StateField.define<{- remoteCursors: Map<string, CursorPosition>;- isCheckout: boolean;-}>({- create() {- return { remoteCursors: new Map(), isCheckout: false };- },- update(value, tr) {- for (const effect of tr.effects) {- if (effect.is(remoteAwarenessEffect)) {- switch (effect.value.type) {- case "update": {- const { peer: uid, user, cursor } = effect.value;- value.remoteCursors.set(uid, {- uid,- cursor,- user,- });- break;- }- case "delete":- value.remoteCursors.delete(effect.value.peer);- break;- case "checkout":- value.isCheckout = effect.value.checkout;- }- }- }- return value;- },-});--const isRemoteCursorUpdate = (update: ViewUpdate): boolean => {- const effect = update.transactions- .flatMap((transaction) => transaction.effects)- .filter((effect) => effect.is(remoteAwarenessEffect));- return update.docChanged || update.viewportChanged || effect.length > 0;-};--export const createCursorLayer = (): Extension => {- return layer({- above: true,- class: "loro-cursor-layer",- update: isRemoteCursorUpdate,- markers: (view) => {- const { remoteCursors: remoteStates, isCheckout } = view.state.field(- remoteAwarenessStateField,- );- if (isCheckout) {- return [];- }- return [...remoteStates.values()].flatMap((state) => {- const selectionRange = EditorSelection.cursor(state.cursor.anchor);- return RemoteCursorMarker.createCursor(- view,- selectionRange,- state.user?.name || "unknown",- state.user?.colorClassName || "",- );- });- },- });-};--export const createSelectionLayer = (): Extension =>- layer({- above: false,- class: "loro-selection-layer",- update: isRemoteCursorUpdate,- markers: (view) => {- const { remoteCursors: remoteStates, isCheckout } = view.state.field(- remoteAwarenessStateField,- );- if (isCheckout) {- return [];- }- return [...remoteStates.entries()]- .filter(- ([, state]) =>- state.cursor.head !== undefined &&- state.cursor.anchor !== state.cursor.head,- )- .flatMap(([, state]) => {- const selectionRange = EditorSelection.range(- state.cursor.anchor,- // oxlint-disable-next-line typescript/no-non-null-assertion- state.cursor.head!,- );- const markers = RectangleMarker.forRange(- view,- `loro-selection ${state.user?.colorClassName || ""}`,- selectionRange,- );- return markers;- });- },- });--/**- * Renders a blinking cursor to indicate the cursor of another user.- */-export class RemoteCursorMarker implements LayerMarker {- private left: number;- private top: number;- private height: number;- private name: string;- private colorClassName: string;-- public constructor({- left,- top,- height,- name,- colorClassName,- }: {- left: number;- top: number;- height: number;- name: string;- colorClassName: string;- }) {- this.left = left;- this.top = top;- this.height = height;- this.name = name;- this.colorClassName = colorClassName;- }-- public draw(): HTMLElement {- const elt = document.createElement("div");- this.adjust(elt);- return elt;- }-- public update(elt: HTMLElement): boolean {- this.adjust(elt);- return true;- }-- public adjust(element: HTMLElement) {- element.style.left = `${this.left}px`;- element.style.top = `${this.top}px`;- element.style.height = `${this.height}px`;- element.className = `loro-cursor ${this.colorClassName}`;- element.style.setProperty("--rtc-name", `"${this.name}"`);- }-- public eq(other: RemoteCursorMarker): boolean {- return (- this.left === other.left &&- this.top === other.top &&- this.height === other.height &&- this.name === other.name- );- }-- public static createCursor(- view: EditorView,- position: SelectionRange,- displayName: string,- colorClassName: string,- ): RemoteCursorMarker[] {- const absolutePosition = RemoteCursorMarker.calculateAbsoluteCursorPosition(- position,- view,- );- if (!absolutePosition) {- return [];- }- const rect = view.scrollDOM.getBoundingClientRect();- const left =- view.textDirection === Direction.LTR- ? rect.left- : rect.right - view.scrollDOM.clientWidth;- const baseLeft = left - view.scrollDOM.scrollLeft;- const baseTop = rect.top - view.scrollDOM.scrollTop;- return [- new RemoteCursorMarker({- left: absolutePosition.left - baseLeft,- top: absolutePosition.top - baseTop,- height: absolutePosition.bottom - absolutePosition.top,- name: displayName,- colorClassName,- }),- ];- }-- private static calculateAbsoluteCursorPosition(- position: SelectionRange,- view: EditorView,- ): Rect | null {- const cappedPositionHead = Math.max(- 0,- Math.min(view.state.doc.length, position.anchor),- );- return view.coordsAtPos(cappedPositionHead, position.assoc || 1);- }-}--const parseAwarenessUpdate = (- doc: LoroDoc,- awareness: Awareness<AwarenessState>,- arg: {- updated: PeerID[];- added: PeerID[];- removed: PeerID[];- },- scopeId: ScopeId,-): StateEffect<CursorEffect>[] => {- const effects = [];- const { updated, added } = arg;- for (const update of [...updated, ...added]) {- const effect = getEffects(doc, awareness, update, scopeId);- if (effect) {- effects.push(effect);- }- }- return effects;-};--const getEffects = (- doc: LoroDoc,- awareness: Awareness<AwarenessState>,- peer: PeerID,- scopeId: ScopeId,-): StateEffect<CursorEffect> | undefined => {- const states = awareness.getAllStates();- const state = states[peer];- if (!state) {- return;- }- if (peer === doc.peerIdStr) {- return;- }- if (state.scopeId !== scopeId) {- return;- }-- if (state.type === "delete") {- return remoteAwarenessEffect.of({- type: "delete",- peer: state.uid,- scopeId: state.scopeId,- });- }-- const anchor = Cursor.decode(state.cursor.anchor);- const anchorPos = doc.getCursorPos(anchor)?.offset ?? 0;- let headPos = anchorPos;- if (state.cursor.head) {- // range- const head = Cursor.decode(state.cursor.head);- headPos = doc.getCursorPos(head)?.offset ?? 0;- }- return remoteAwarenessEffect.of({- type: "update",- peer: state.uid,- scopeId: state.scopeId,- cursor: { anchor: anchorPos, head: headPos },- user: state.user,- });-};--export interface CursorPosition {- uid: string;- cursor: { anchor: number; head?: number };- user?: UserState;-}--export class AwarenessPlugin implements PluginValue {- public sub: Subscription;- public view: EditorView;- public doc: LoroDoc;- public user: UserState;- public awareness: Awareness<AwarenessState>;- private getTextFromDoc: (doc: LoroDoc) => LoroText;- private scopeId: ScopeId;- private getUserId?: () => Uid;-- public constructor(- view: EditorView,- {- doc,- user,- awareness,- getTextFromDoc,- scopeId,- getUserId,- }: {- doc: LoroDoc;- user: UserState;- awareness: Awareness<AwarenessState>;- getTextFromDoc: (doc: LoroDoc) => LoroText;- scopeId: ScopeId;- getUserId?: () => Uid;- },- ) {- this.view = view;- this.doc = doc;- this.user = user;- this.awareness = awareness;- this.getTextFromDoc = getTextFromDoc;- this.scopeId = scopeId;- this.getUserId = getUserId;- this.sub = this.doc.subscribe((e) => {- if (e.by === "local") {- // update remote cursor position- const effects = [];- for (const peer of this.awareness.peers()) {- const effect = getEffects(- this.doc,- this.awareness,- peer,- this.scopeId,- );- if (effect) {- effects.push(effect);- }- }- this.view.dispatch({- effects,- });- } else if (e.by === "checkout") {- // TODO: better way- this.view.dispatch({- effects: [- remoteAwarenessEffect.of({- type: "checkout",- checkout: this.doc.isDetached(),- }),- ],- });- }- });- }-- public update(update: ViewUpdate): void {- if (!update.selectionSet && !update.focusChanged && !update.docChanged) {- return;- }- const selection = update.state.selection.main;- if (this.view.hasFocus && !this.doc.isDetached()) {- const cursorState = getCursorState({- doc: this.doc,- getTextFromDoc: this.getTextFromDoc,- anchor: selection.anchor,- head: selection.head,- });- this.awareness.setLocalState({- type: "update",- uid: this.getUserId ? this.getUserId() : this.doc.peerIdStr,- scopeId: this.scopeId,- cursor: cursorState,- user: this.user,- });- } else {- // when checkout or blur- this.awareness.setLocalState({- type: "delete",- uid: this.getUserId ? this.getUserId() : this.doc.peerIdStr,- scopeId: this.scopeId,- });- }- }-- public destroy(): void {- this.sub?.();- this.awareness.setLocalState({- type: "delete",- uid: this.getUserId ? this.getUserId() : this.doc.peerIdStr,- scopeId: this.scopeId,- });- }-}-export class RemoteAwarenessPlugin implements PluginValue {- public _awarenessListener?: AwarenessListener;- public view: EditorView;- public doc: LoroDoc;- public awareness: Awareness<AwarenessState>;- private scopeId: ScopeId;-- public constructor(- view: EditorView,- doc: LoroDoc,- awareness: Awareness<AwarenessState>,- scopeId: ScopeId,- ) {- this.view = view;- this.doc = doc;- this.awareness = awareness;- this.scopeId = scopeId;- const listener: AwarenessListener = async (arg, origin) => {- if (origin === "local") {- return;- }- this.view.dispatch({- effects: parseAwarenessUpdate(- this.doc,- this.awareness,- arg,- this.scopeId,- ),- });- };- this._awarenessListener = listener;- this.awareness.addListener(listener);- }-- public destroy(): void {- if (this._awarenessListener) {- this.awareness.removeListener(this._awarenessListener);- }- }-}--const getCursorState = ({- doc,- getTextFromDoc,- anchor,- head,-}: {- doc: LoroDoc;- getTextFromDoc: (doc: LoroDoc) => LoroText;- anchor: number;- head: number | undefined;-}) => {- if (anchor === head) {- head = undefined;- }- const anchorCursor = getTextFromDoc(doc).getCursor(anchor)?.encode();-- if (!anchorCursor) {- throw new Error("cursor head not found");- }- let headCursor: Uint8Array | undefined;- if (head !== undefined) {- headCursor = getTextFromDoc(doc).getCursor(head)?.encode();- }-- return {- anchor: anchorCursor,- head: headCursor,- };-};diff --git a/frontend/src/core/codemirror/rtc/loro/colors.ts b/frontend/src/core/codemirror/rtc/loro/colors.tsdeleted file mode 100644index 8bdf2bc84c..0000000000--- a/frontend/src/core/codemirror/rtc/loro/colors.ts+++ /dev/null@@ -1,38 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--export const COLORS = [- "bg-(--amber-6)",- "bg-(--blue-6)",- "bg-(--crimson-6)",- "bg-(--cyan-6)",- "bg-(--grass-6)",- "bg-(--gray-6)",- "bg-(--green-6)",- "bg-(--lime-6)",- "bg-(--orange-6)",- "bg-(--purple-6)",- "bg-(--red-6)",- "bg-(--sage-6)",- "bg-(--sky-6)",- "bg-(--slate-6)",-] as const;--/**- * Get a deterministic color from a string or number.- * @param input - The input to get a color from.- */-export const getColor = (input: string | number) => {- if (typeof input === "string") {- // Create a simple hash from the string- let hash = 0;- for (let i = 0; i < input.length; i++) {- hash = (hash << 5) - hash + input.charCodeAt(i);- hash = Math.trunc(hash); // Convert to 32bit integer- }- // Use absolute value to ensure positive index- return COLORS[Math.abs(hash) % COLORS.length];- }-- // Fallback for number input- return COLORS[input % COLORS.length];-};diff --git a/frontend/src/core/codemirror/rtc/loro/sync.ts b/frontend/src/core/codemirror/rtc/loro/sync.tsdeleted file mode 100644index b550ed528a..0000000000--- a/frontend/src/core/codemirror/rtc/loro/sync.ts+++ /dev/null@@ -1,169 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--// Vendored from https://github.com/loro-dev/loro-codemirror/blob/main/src/index.ts-// and adapted to support:-// - custom `getTextFromDoc`-// - filter diffs by path--import type { Extension } from "@codemirror/state";-import { Annotation, type ChangeSpec } from "@codemirror/state";-import type { EditorView, PluginValue, ViewUpdate } from "@codemirror/view";-import { ViewPlugin } from "@codemirror/view";-import type {- LoroDoc,- LoroEventBatch,- LoroText,- Subscription,-} from "loro-crdt";--/**- * It is used to sync the document with the remote users.- *- * @param doc - LoroDoc instance- * @returns Extension- */-export const loroSyncPlugin = (- doc: LoroDoc,- docPath: string[],- getTextFromDoc: (doc: LoroDoc) => LoroText,-): Extension => {- return ViewPlugin.define(- (view) => new LoroSyncPluginValue(view, doc, docPath, getTextFromDoc),- );-};--/**- * Annotation to identify loro sync changes (syncing from remote to local)- */-export const loroSyncAnnotation = Annotation.define();--export class LoroSyncPluginValue implements PluginValue {- public sub?: Subscription;- private isInitDispatch = false;- private view: EditorView;- private doc: LoroDoc;- private docPath: string[];- private getTextFromDoc: (doc: LoroDoc) => LoroText;-- public constructor(- view: EditorView,- doc: LoroDoc,- docPath: string[],- getTextFromDoc: (doc: LoroDoc) => LoroText,- ) {- this.view = view;- this.doc = doc;- this.docPath = docPath;- this.getTextFromDoc = getTextFromDoc;- this.sub = doc.subscribe(this.onRemoteUpdate);- Promise.resolve().then(() => {- this.isInitDispatch = true;- const currentText = this.view.state.doc.toString();- const text = this.getTextFromDoc(this.doc);-- if (currentText === text.toString()) {- return;- }- view.dispatch({- changes: [- {- from: 0,- to: this.view.state.doc.length,- insert: text.toString(),- },- ],- annotations: [loroSyncAnnotation.of(this)],- });- });- }-- public onRemoteUpdate = (e: LoroEventBatch) => {- if (e.by === "local") {- return;- }- if (e.by === "checkout") {- // TODO: better handle checkout- this.view.dispatch({- changes: [- {- from: 0,- to: this.view.state.doc.length,- insert: this.getTextFromDoc(this.doc).toString(),- },- ],- annotations: [loroSyncAnnotation.of(this)],- });- return;- }- if (e.by === "import") {- const changes: ChangeSpec[] = [];- let pos = 0;- for (const { diff, path } of e.events) {- if (path.join("/") !== this.docPath.join("/")) {- continue;- }- if (diff.type !== "text") {- continue;- }- const textDiff = diff.diff;- for (const delta of textDiff) {- if (delta.insert) {- changes.push({- from: pos,- to: pos,- insert: delta.insert,- });- } else if (delta.delete) {- changes.push({- from: pos,- to: pos + delta.delete,- });- pos += delta.delete;- } else if (delta.retain != null) {- pos += delta.retain;- }- }- if (changes.length > 0) {- this.view.dispatch({- changes,- annotations: [loroSyncAnnotation.of(this)],- });- }- }- }- };-- public update(update: ViewUpdate): void {- if (this.isInitDispatch) {- this.isInitDispatch = false;- return;- }-- if (- !update.docChanged ||- (update.transactions.length > 0 &&- (update.transactions[0].annotation(loroSyncAnnotation) === this ||- update.transactions[0].annotation(loroSyncAnnotation) === "undo"))- ) {- return;- }- let adj = 0;- // oxlint-disable-next-line marimo/prefer-object-params -- CodeMirror supplies positional change ranges and inserted text.- update.changes.iterChanges((fromA, toA, fromB, toB, insert) => {- const insertText = insert.sliceString(0, insert.length, "\n");- if (fromA !== toA) {- this.getTextFromDoc(this.doc).delete(fromA + adj, toA - fromA);- }- if (insertText.length > 0) {- this.getTextFromDoc(this.doc).insert(fromA + adj, insertText);- }- adj += insertText.length - (toA - fromA);- });- this.doc.commit();- }-- public destroy(): void {- this.sub?.();- this.sub = undefined;- }-}diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex eefbc476ea..64c4687fe7 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -204,7 +204,6 @@ export const UserConfigSchema = zexperimental: z.looseObject({markdown: z.boolean().optional(),- rtc: z.boolean().optional(),// Add new experimental features here})// Pass through so that we don't remove any extra keys that the user has added.diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex 1a75fe4e3e..d5278b0385 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -8,7 +8,6 @@ import { getResolvedMarimoConfig } from "./config";export interface ExperimentalFeatures {markdown: boolean; // Used in playground (community cloud)wasm_layouts: boolean; // Used in playground (community cloud)- rtc_v2: boolean;cache_panel: boolean;external_agents: boolean;debugger: boolean; // Live frame-watching debugger (gutter breakpoints + pdb)@@ -19,7 +18,6 @@ export interface ExperimentalFeatures {const defaultValues: ExperimentalFeatures = {markdown: true,wasm_layouts: false,- rtc_v2: false,cache_panel: import.meta.env.DEV,external_agents: import.meta.env.DEV,debugger: false,diff --git a/frontend/src/core/rtc/state.ts b/frontend/src/core/rtc/state.tsdeleted file mode 100644index 252bd19a5a..0000000000--- a/frontend/src/core/rtc/state.ts+++ /dev/null@@ -1,34 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */-import { atomWithStorage } from "jotai/utils";-import { SCRATCH_CELL_ID, type CellId } from "@/core/cells/ids";-import { once } from "@/utils/once";-import { jotaiJsonStorage } from "@/utils/storage/jotai";-import { getFeatureFlag } from "../config/feature-flag";--/**- * The username for the current user when using real-time collaboration.- * This is stored in localStorage.- */-export const usernameAtom = atomWithStorage<string>(- "marimo:rtc:username",- "",- jotaiJsonStorage,-);--/**- * Whether RTC is enabled.- *- * This is cached on page-load because this UI can get into- * weird states, so we require a page reload to take effect.- */-export const isRtcEnabled = once(() => {- return getFeatureFlag("rtc_v2");-});--/**- * Whether this cell type can participate in real-time collaboration.- * Scratchpad cells are local-only.- */-export function canUseRtc(cellId: CellId): boolean {- return cellId !== SCRATCH_CELL_ID;-}diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.tsindex 04c1695566..b36ef81e93 100644--- a/frontend/src/core/runtime/__tests__/runtime.test.ts+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts@@ -143,13 +143,9 @@ describe("RuntimeManager", () => {);const wsUrl = runtime.getWsURL("s_123" as SessionId);- const wsSyncUrl = runtime.getWsSyncURL("s_123" as SessionId);const terminalUrl = runtime.getTerminalWsURL();expect(wsUrl.searchParams.get("access_token")).toBe("my-secret-token");- expect(wsSyncUrl.searchParams.get("access_token")).toBe(- "my-secret-token",- );expect(terminalUrl.searchParams.get("access_token")).toBe("my-secret-token",);@@ -274,18 +270,6 @@ describe("RuntimeManager", () => {});});- describe("getWsSyncURL", () => {- it("should return WebSocket Sync URL", () => {- const runtime = new RuntimeManager(mockConfig);- const sessionId = "1234" as SessionId;- const url = runtime.getWsSyncURL(sessionId);-- expect(url.protocol).toBe("wss:");- expect(url.pathname).toBe("/ws_sync");- expect(url.searchParams.get("session_id")).toBe(sessionId);- });- });-describe("getTerminalWsURL", () => {it("should include dimensions in the terminal handshake", () => {const runtime = new RuntimeManager(mockConfig);diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.tsindex 6c441104dd..555612722d 100644--- a/frontend/src/core/runtime/runtime.ts+++ b/frontend/src/core/runtime/runtime.ts@@ -184,14 +184,6 @@ export class RuntimeManager {return url;}- /**- * The WebSocket Sync URL of the runtime, for real-time updates.- */- public getWsSyncURL(sessionId: SessionId): URL {- const url = this.getSessionURL("/ws_sync", sessionId);- return asWsUrl(this.appendCrossOriginAuth(url).toString());- }-/*** The WebSocket URL of the terminal.*/diff --git a/frontend/src/css/app/codemirror.css b/frontend/src/css/app/codemirror.cssindex 675236b159..dce35f0567 100644--- a/frontend/src/css/app/codemirror.css+++ b/frontend/src/css/app/codemirror.css@@ -34,7 +34,7 @@}.marimo-cell .cm-scroller {- /* this needs to be visible to show RTC cursors and inline AI edit buttons */+ /* this needs to be visible to show inline AI edit buttons */overflow: visible;}diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 89e27b51e8..6f61eb8983 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -5,7 +5,6 @@ import { codecovVitePlugin } from "@codecov/vite-plugin";import react from "@vitejs/plugin-react";import { JSDOM } from "jsdom";import { defineConfig, type Plugin } from "vite";-import wasm from "vite-plugin-wasm";import { createViteLogger, reactCompilerConfig } from "./vite.shared.mts";const SERVER_PORT = process.env.SERVER_PORT || 2718;@@ -250,14 +249,6 @@ export default defineConfig({origin: TARGET,},},- "/ws_sync": {- target: `ws://${HOST}:${SERVER_PORT}`,- ws: true,- changeOrigin: true,- headers: {- origin: TARGET,- },- },"/lsp": {target: `ws://${HOST}:${SERVER_PORT}`,ws: true,@@ -317,14 +308,6 @@ export default defineConfig({"react-dnd-html5-backend","dnd-core",],- alias: [- // The default `browser` export of loro-crdt loads its wasm with a- // synchronous XMLHttpRequest at module evaluation. A page served with- // `Permissions-Policy: sync-xhr=()` blocks that request, and the- // editor fails to load. The bundler entry loads the wasm with an- // asynchronous fetch instead.- { find: /^loro-crdt$/, replacement: "loro-crdt/bundler" },- ],},worker: {format: "es",@@ -340,6 +323,5 @@ export default defineConfig({bundleName: "marimo",uploadToken: process.env.CODECOV_TOKEN,}),- wasm(),],});diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex c7b69e84cf..c5f9c71ae5 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -252,9 +252,8 @@ class ServerConfig(TypedDict):`MARIMO_SERVER_TRANSPORT` environment variable. `"websocket"`(default) uses the `/ws` WebSocket endpoint; `"sse"` usesserver-sent events over HTTP, for deployments behind proxies or- services that do not support WebSockets. Terminal, LSP, and- real-time collaboration still require WebSockets; RTC is disabled- when using `"sse"`.+ services that do not support WebSockets. The terminal and LSP+ still require WebSockets."""browser: Literal["default"] | str@@ -653,12 +652,13 @@ class ExperimentalConfig(TypedDict, total=False):"""Configuration for experimental features.- Features exposed on the frontend must match the frontend config.+ Features exposed on the frontend must match the frontend config. A key+ for a removed feature, such as `rtc_v2`, still loads and does nothing;+ the server warns about it at startup."""markdown: bool # Used in playground (community cloud)wasm_layouts: bool # Used in playground (community cloud)- rtc_v2: boolisolate_apps: booldebugger: bool # Live frame-watching debugger (gutter breakpoints + pdb)line_timing: bool # Active-line highlight + per-line timer (sys.settrace)diff --git a/marimo/_config/config_schema.py b/marimo/_config/config_schema.pyindex ee4fb49e42..2d3ac3a6ae 100644--- a/marimo/_config/config_schema.py+++ b/marimo/_config/config_schema.py@@ -324,7 +324,7 @@ class ServerConfig(Config, kw_only=True):transport: Annotated[Literal["websocket", "sse"] | UnsetType,Meta(- description='experimental. The transport used to stream kernel messages to the frontend, typically set with the `MARIMO_SERVER_TRANSPORT` environment variable. `"websocket"` (default) uses the `/ws` WebSocket endpoint; `"sse"` uses server-sent events over HTTP, for deployments behind proxies or services that do not support WebSockets. Terminal, LSP, and real-time collaboration still require WebSockets; RTC is disabled when using `"sse"`.'+ description='experimental. The transport used to stream kernel messages to the frontend, typically set with the `MARIMO_SERVER_TRANSPORT` environment variable. `"websocket"` (default) uses the `/ws` WebSocket endpoint; `"sse"` uses server-sent events over HTTP, for deployments behind proxies or services that do not support WebSockets. The terminal and LSP still require WebSockets.'),] = UNSET@@ -825,9 +825,6 @@ class ExperimentalConfig(Config, kw_only=True):description="Enable experimental layouts in WebAssembly notebooks."),] = UNSET- rtc_v2: Annotated[- bool | UnsetType, Meta(description="Enable real-time collaboration.")- ] = UNSETisolate_apps: Annotated[bool | UnsetType,Meta(description="Run applications in separate processes."),diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 7881966650..4b0f8ed290 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -265,7 +265,6 @@ class DependencyManager:"docstring_to_markdown", min_version="0.17.0")tomlkit = Dependency("tomlkit")- loro = Dependency("loro")boto3 = Dependency("boto3")redshift_connector = Dependency("redshift_connector")diff --git a/marimo/_messaging/notebook/document.py b/marimo/_messaging/notebook/document.pyindex 26bfde0cfd..a21a368c67 100644--- a/marimo/_messaging/notebook/document.py+++ b/marimo/_messaging/notebook/document.py@@ -13,9 +13,7 @@ that goes through this model is last-write-wins with intra-transactionconflict detection (`_validate` catches contradictions like delete +update on the same cell within one batch).-`SetCode` is a wholesale replacement without character-level-merge. Loro CRDT may handle real-time collaborative text editing in-the future, but cell code would then live outside this model entirely.+`SetCode` is a wholesale replacement without character-level merge."""from __future__ import annotationsdiff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.pyindex 85832fd65f..c746df5503 100644--- a/marimo/_server/api/endpoints/execution.py+++ b/marimo/_server/api/endpoints/execution.py@@ -11,10 +11,6 @@ from starlette.responses import JSONResponse, StreamingResponsefrom marimo import _loggersfrom marimo._runtime.commands import HTTPRequest, UpdateUIElementCommandfrom marimo._server.api.deps import AppState-from marimo._server.api.endpoints.ws.ws_connection_validator import (- FILE_QUERY_PARAM_KEY,-)-from marimo._server.api.endpoints.ws_endpoint import DOC_MANAGERfrom marimo._server.api.utils import (dispatch_control_request,enforce_consumer_capability,@@ -35,7 +31,6 @@ from marimo._server.models.models import (from marimo._server.router import APIRouterfrom marimo._server.sse import wait_for_http_disconnectfrom marimo._server.uvicorn_utils import close_uvicorn-from marimo._server.workspace import MarimoFileKeyfrom marimo._session.consumer_policy import (TakeoverDecision,can_take_over_editing,@@ -527,20 +522,8 @@ async def restart_session(# This just closes the session, and the frontend will# do a full reload, which will restart the session.session_id = app_state.require_current_session_id()- session = app_state.require_current_session()+ app_state.require_current_session()session_manager.close_session(session_id)-- # Close RTC doc if it exists- file_key: MarimoFileKey | None = (- app_state.query_params(FILE_QUERY_PARAM_KEY)- or session_manager.workspace.get_unique_file_key()- or session.app_file_manager.path- )- if file_key is not None:- await DOC_MANAGER.remove_doc(file_key)- else:- LOGGER.warning("Unable to close RTC doc as no file key was provided")-return SuccessResponse()diff --git a/marimo/_server/api/endpoints/ws/session_handler.py b/marimo/_server/api/endpoints/ws/session_handler.pyindex a3e3611655..8813f52ba2 100644--- a/marimo/_server/api/endpoints/ws/session_handler.py+++ b/marimo/_server/api/endpoints/ws/session_handler.py@@ -20,13 +20,9 @@ from marimo._messaging.notification import (from marimo._messaging.serde import (serialize_kernel_message,)-from marimo._server.api.endpoints.ws.ws_kernel_ready import (- build_kernel_ready,- is_rtc_available,-)+from marimo._server.api.endpoints.ws.ws_kernel_ready import build_kernel_readyfrom marimo._server.api.endpoints.ws.ws_session_connector import (SessionConnector,- is_viewer_connection,)from marimo._server.codes import WebSocketCloseReason, WebSocketCodesfrom marimo._session.consumer import SessionConsumer@@ -45,10 +41,6 @@ if TYPE_CHECKING:from marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionParams,)- from marimo._server.api.endpoints.ws.ws_session_connector import (- ConnectionType,- )- from marimo._server.rtc.doc import LoroDocManagerfrom marimo._server.session_manager import SessionManagerfrom marimo._session import Sessionfrom marimo._session.events import SessionEventBus@@ -73,12 +65,10 @@ class SessionHandler(SessionConsumer, abc.ABC):manager: SessionManager,params: ConnectionParams,mode: SessionMode,- doc_manager: LoroDocManager,):self.manager = managerself.params = paramsself.mode = mode- self.doc_manager = doc_managerself.status = ConnectionState.CONNECTINGself._session: Session | None = Noneself.cancel_close_handle: asyncio.TimerHandle | None = None@@ -106,7 +96,7 @@ class SessionHandler(SessionConsumer, abc.ABC):@asynccontextmanagerasync def _connection_lifetime(self, connection: HTTPConnection- ) -> AsyncIterator[asyncio.Task[tuple[Session, ConnectionType]]]:+ ) -> AsyncIterator[asyncio.Task[None]]:"""Own attachment through startup, progress delivery, and streaming."""startup = asyncio.create_task(self._connect_session(connection))try:@@ -117,9 +107,7 @@ class SessionHandler(SessionConsumer, abc.ABC):finally:self._on_disconnect()- async def _connect_session(- self, connection: HTTPConnection- ) -> tuple[Session, ConnectionType]:+ async def _connect_session(self, connection: HTTPConnection) -> None:"""Connect this handler to a session (new, resume, reconnect, ...).Raises:@@ -144,7 +132,7 @@ class SessionHandler(SessionConsumer, abc.ABC):await disconnectedawait cancel_and_wait(startup)raise asyncio.CancelledError- return await startup+ await startupfinally:await cancel_and_wait(disconnected)await cancel_and_wait(startup)@@ -156,14 +144,13 @@ class SessionHandler(SessionConsumer, abc.ABC):async def _wait_for_disconnect(self) -> None:"""Notice a closed transport even while a session is starting."""- def _is_viewer(- self, session: Session, connection_type: ConnectionType- ) -> bool:- """Whether this consumer gets read-only (kiosk) message filtering."""- return is_viewer_connection(- connection_type=connection_type,- is_main_consumer=session.room.main_consumer is self,- )+ def _is_viewer(self, session: Session) -> bool:+ """Whether this consumer gets read-only (kiosk) message filtering.++ The viewer is whichever connection is not the room's main consumer;+ a takeover flips this by reassigning the main consumer.+ """+ return session.room.main_consumer is not self@abc.abstractmethoddef notify(self, notification: KernelMessage) -> None:@@ -214,9 +201,6 @@ class SessionHandler(SessionConsumer, abc.ABC):# Only send execution data if sending code to frontendshould_send = self.manager.should_send_code_to_frontend()- # RTC is only enabled if configured AND Loro is available- effective_rtc_enabled = self.params.rtc_enabled and is_rtc_available()-# Build kernel ready messagekernel_ready_msg = build_kernel_ready(session=session,@@ -225,10 +209,6 @@ class SessionHandler(SessionConsumer, abc.ABC):last_executed_code=last_executed_code if should_send else {},last_execution_time=last_execution_time if should_send else {},kiosk=kiosk,- rtc_enabled=effective_rtc_enabled,- file_key=self.params.file_key,- mode=self.mode,- doc_manager=self.doc_manager,auto_instantiated=auto_instantiated,)self._serialize_and_notify(kernel_ready_msg)@@ -291,18 +271,6 @@ class SessionHandler(SessionConsumer, abc.ABC):self.status = ConnectionState.OPENself._replay_previous_session(session)- def _connect_to_existing_session(self, session: Session) -> None:- """Connect to an existing session and replay all messages."""- self.status = ConnectionState.CONNECTING- session.connect_consumer(self, main=False)-- # Write kernel ready with current state- self._write_kernel_ready_from_session_view(session, kiosk=False)- self.status = ConnectionState.OPEN-- # Replay all operations- self._replay_previous_session(session)-def _replay_previous_session(self, session: Session) -> None:"""Replay retained state to this client."""notifications = session.session_view.snapshot_notifications()diff --git a/marimo/_server/api/endpoints/ws/ws_connection_validator.py b/marimo/_server/api/endpoints/ws/ws_connection_validator.pyindex 640543d4e0..6a89a845fa 100644--- a/marimo/_server/api/endpoints/ws/ws_connection_validator.py+++ b/marimo/_server/api/endpoints/ws/ws_connection_validator.py@@ -7,15 +7,12 @@ from typing import TYPE_CHECKINGif TYPE_CHECKING:from starlette.websockets import WebSocket-from marimo import _loggersfrom marimo._server.api.auth import validate_authfrom marimo._server.api.deps import AppStatefrom marimo._server.codes import WebSocketCloseReason, WebSocketCodesfrom marimo._server.workspace import MarimoFileKeyfrom marimo._types.ids import SessionId-LOGGER = _loggers.marimo_logger()-SESSION_QUERY_PARAM_KEY = "session_id"FILE_QUERY_PARAM_KEY = "file"KIOSK_QUERY_PARAM_KEY = "kiosk"@@ -29,7 +26,6 @@ class ConnectionParams:file_key: MarimoFileKeykiosk: boolauto_instantiate: bool- rtc_enabled: bool@dataclass@@ -45,17 +41,12 @@ class ConnectionRejection:def parse_connection_params(- app_state: AppState, *, allow_rtc: bool = True+ app_state: AppState,) -> ConnectionParams | ConnectionRejection:"""Extract and validate session connection parameters.Transport-agnostic: reads query params and config from the request heldby `app_state`.-- Args:- app_state: App state wrapping the incoming HTTP or WebSocket request.- allow_rtc: Whether the transport supports RTC. SSE cannot carry the- `/ws_sync` document stream, so RTC is disabled for it."""# Extract session_idraw_session_id = app_state.query_params(SESSION_QUERY_PARAM_KEY)@@ -82,9 +73,6 @@ def parse_connection_params(# Extract config-based parametersconfig = app_state.config_manager_at_file(file_key).get_config()- rtc_enabled = allow_rtc and config.get("experimental", {}).get(- "rtc_v2", False- )auto_instantiate = config["runtime"]["auto_instantiate"]return ConnectionParams(@@ -92,7 +80,6 @@ def parse_connection_params(file_key=file_key,kiosk=kiosk,auto_instantiate=auto_instantiate,- rtc_enabled=rtc_enabled,)@@ -131,23 +118,3 @@ class WebSocketConnectionValidator:await self.websocket.close(result.code, result.reason)return Nonereturn result-- async def extract_file_key_only(self) -> MarimoFileKey | None:- """Extract only the file_key parameter (for RTC endpoint).-- Returns:- MarimoFileKey if valid, None otherwise.- """- file_key: MarimoFileKey | None = (- self.app_state.query_params(FILE_QUERY_PARAM_KEY)- or self.app_state.session_manager.workspace.get_unique_file_key()- )-- if file_key is None:- LOGGER.warning("RTC: Closing websocket - no file key")- await self.websocket.close(- WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.NO_FILE_KEY- )- return None-- return file_keydiff --git a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py b/marimo/_server/api/endpoints/ws/ws_kernel_ready.pyindex bdd353de12..1dccce3ff1 100644--- a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py+++ b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py@@ -1,31 +1,19 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import asyncio-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING-from marimo import _loggers-from marimo._dependencies.dependencies import DependencyManager-from marimo._messaging.notebook.document import NotebookDocumentfrom marimo._messaging.notification import (ConsumerCapabilities,KernelCapabilitiesNotification,KernelReadyNotification,)from marimo._plugins.core.web_component import JSONType-from marimo._session.model import SessionModefrom marimo._types.ids import CellId_tif TYPE_CHECKING:- from marimo._server.rtc.doc import LoroDocManager- from marimo._server.workspace import MarimoFileKeyfrom marimo._session import Session-LOGGER = _loggers.marimo_logger()--# Strong refs so fire-and-forget tasks aren't GC'd mid-flight.-_background_tasks: set[asyncio.Task[Any]] = set()-def build_kernel_ready(session: Session,@@ -34,10 +22,6 @@ def build_kernel_ready(last_executed_code: dict[CellId_t, str],last_execution_time: dict[CellId_t, float],kiosk: bool,- rtc_enabled: bool,- file_key: MarimoFileKey,- mode: SessionMode,- doc_manager: LoroDocManager,auto_instantiated: bool = False,) -> KernelReadyNotification:"""Build a KernelReady message.@@ -49,10 +33,6 @@ def build_kernel_ready(last_executed_code: Last executed code for each celllast_execution_time: Last execution time for each cellkiosk: Whether this is kiosk mode- rtc_enabled: Whether RTC is enabled- file_key: File key for the session- mode: Session mode (edit/run)- doc_manager: LoroDoc manager for RTCauto_instantiated: Whether the kernel has already been instantiatedserver-side (run mode). If True, the frontend does not needto instantiate the app.@@ -60,10 +40,6 @@ def build_kernel_ready(Returns:KernelReady message operation."""- # Initialize RTC if needed- if _should_init_rtc(rtc_enabled, mode):- _try_init_rtc_doc(session.document, file_key, doc_manager)-return KernelReadyNotification(layout=session.app_file_manager.read_layout_config(),resumed=resumed,@@ -81,53 +57,3 @@ def build_kernel_ready(auto_instantiated=auto_instantiated,stable_session_id=session.stable_id,)---def is_rtc_available() -> bool:- """Check if RTC (Loro) is available on this system.-- Returns:- True if Loro is available, False otherwise.- """- return DependencyManager.loro.has()---def _should_init_rtc(rtc_enabled: bool, mode: SessionMode) -> bool:- """Check if RTC should be initialized.-- Args:- rtc_enabled: Whether RTC is currently enabled- mode: Session mode (edit/run)-- Returns:- True if RTC should be initialized, False otherwise.- """- return rtc_enabled and mode == SessionMode.EDIT and is_rtc_available()---def _try_init_rtc_doc(- document: NotebookDocument,- file_key: MarimoFileKey,- doc_manager: LoroDocManager,-) -> None:- """Try to initialize the RTC document with the session document's cells.-- Logs a warning if Loro is not available but does not fail.-- Args:- document: The session's document- file_key: File key for the document- doc_manager: LoroDoc manager- """- if not DependencyManager.loro.has():- LOGGER.warning(- "RTC: Loro is not installed, disabling real-time collaboration"- )- else:- cell_ids = tuple(cell.id for cell in document.cells)- codes = tuple(cell.code for cell in document.cells)- task = asyncio.create_task(- doc_manager.create_doc(file_key, cell_ids, codes)- )- _background_tasks.add(task)- task.add_done_callback(_background_tasks.discard)diff --git a/marimo/_server/api/endpoints/ws/ws_rtc_handler.py b/marimo/_server/api/endpoints/ws/ws_rtc_handler.pydeleted file mode 100644index d6eb419920..0000000000--- a/marimo/_server/api/endpoints/ws/ws_rtc_handler.py+++ /dev/null@@ -1,141 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-from __future__ import annotations--import asyncio-from typing import TYPE_CHECKING--from starlette.websockets import WebSocketDisconnect--from marimo import _loggers--if TYPE_CHECKING:- from loro import DiffEvent, ExportMode, LoroDoc- from starlette.websockets import WebSocket-- from marimo._server.rtc.doc import LoroDocManager- from marimo._server.workspace import MarimoFileKey--LOGGER = _loggers.marimo_logger()---class RTCWebSocketHandler:- """Handles Real-Time Collaboration WebSocket connections."""-- def __init__(- self,- websocket: WebSocket,- file_key: MarimoFileKey,- doc_manager: LoroDocManager,- ):- self.websocket = websocket- self.file_key = file_key- self.doc_manager = doc_manager-- async def handle(self) -> None:- """Handle RTC WebSocket connection lifecycle.-- Manages the full lifecycle of an RTC WebSocket connection:- 1. Accept the connection- 2. Get or create LoroDoc- 3. Send initial sync to client- 4. Subscribe to updates- 5. Handle bidirectional updates- 6. Cleanup on disconnect- """- from loro import ExportMode-- await self.websocket.accept()-- # Get or create the LoroDoc and add the client to it- LOGGER.debug("RTC: getting document")- update_queue: asyncio.Queue[bytes] = asyncio.Queue()- doc = await self.doc_manager.get_or_create_doc(self.file_key)- self.doc_manager.add_client_to_doc(self.file_key, update_queue)-- # Send initial sync to client- await self._send_initial_sync(doc, ExportMode)-- # Set up update handling- def handle_doc_update(event: DiffEvent) -> None:- LOGGER.debug("RTC: doc updated: %s", event)-- # Subscribe to LoroDoc updates- subscription = doc.subscribe_root(handle_doc_update)-- # Create async task to send updates to the client- send_task = asyncio.create_task(- self._send_updates_to_client(update_queue)- )-- try:- # Listen for updates from the client- await self._receive_updates_from_client(doc, update_queue)- except WebSocketDisconnect:- LOGGER.debug("RTC: WebSocket disconnected")- except Exception as e:- LOGGER.warning(- f"RTC: Exception in websocket loop for file {self.file_key}: {e!s}"- )- finally:- LOGGER.debug("RTC: Cleaning up resources")- # Cleanup resources- send_task.cancel()- subscription.unsubscribe()- await self.doc_manager.remove_client(self.file_key, update_queue)-- async def _send_initial_sync(- self, doc: LoroDoc, export_mode: type[ExportMode]- ) -> None:- """Send initial document sync to client.-- Args:- doc: LoroDoc instance- export_mode: ExportMode from loro module- """- # Use shallow snapshot for fewer bytes- LOGGER.debug("RTC: sending initial sync")- init_sync_msg = doc.export(- export_mode.ShallowSnapshot(frontiers=doc.state_frontiers)- )- await self.websocket.send_bytes(init_sync_msg)- LOGGER.debug("RTC: initial sync sent")-- async def _send_updates_to_client(- self, update_queue: asyncio.Queue[bytes]- ) -> None:- """Send updates from the document to the client.-- Args:- update_queue: Queue of updates to send to client- """- try:- while True:- update = await update_queue.get()- await self.websocket.send_bytes(update)- except Exception as e:- LOGGER.warning(- f"RTC: Could not send loro update to client for file {self.file_key}: {e!s}",- )-- async def _receive_updates_from_client(- self, doc: LoroDoc, update_queue: asyncio.Queue[bytes]- ) -> None:- """Receive and process updates from the client.-- Args:- doc: LoroDoc instance- update_queue: Queue used to avoid sending updates back to sender- """- while True:- message = await self.websocket.receive_bytes()- # Broadcast to other clients (but not back to sender)- await self.doc_manager.broadcast_update(- self.file_key, message, update_queue- )-- # Check if the message is an awareness update- if message.startswith(b"awareness:"):- LOGGER.debug("RTC: received awareness update")- else:- # Apply the update to the LoroDoc- doc.import_(message)diff --git a/marimo/_server/api/endpoints/ws/ws_session_connector.py b/marimo/_server/api/endpoints/ws/ws_session_connector.pyindex 5e98900375..8aa25c71a3 100644--- a/marimo/_server/api/endpoints/ws/ws_session_connector.py+++ b/marimo/_server/api/endpoints/ws/ws_session_connector.py@@ -1,7 +1,6 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-from enum import Enumfrom typing import TYPE_CHECKINGfrom marimo._session.consumer_policy import initial_capabilities@@ -29,31 +28,6 @@ from marimo._session.requests import InstantiateNotebookRequestLOGGER = _loggers.marimo_logger()-class ConnectionType(Enum):- """Type of session connection established."""-- KIOSK = "kiosk"- RECONNECT = "reconnect"- RTC_EXISTING = "rtc_existing"- RESUME = "resume"- 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."""@@ -69,12 +43,8 @@ class SessionConnector:self.params = paramsself.connection = connection- async def connect(self) -> tuple[Session, ConnectionType]:- """Determine connection type and establish session connection.-- Returns:- Tuple of (Session, ConnectionType) indicating the session- and how it was connected.+ async def connect(self) -> None:+ """Establish a session connection.Raises:WebSocketDisconnect: If the connection cannot be established.@@ -82,48 +52,40 @@ class SessionConnector:async with self.manager.connection_lock(self.params.session_id, self.params.file_key):- return await self._connect()+ await self._connect()- async def _connect(self) -> tuple[Session, ConnectionType]:+ async def _connect(self) -> None:# 1. Kiosk modeif self.params.kiosk:- return await self._connect_kiosk()+ await self._connect_kiosk()+ return# A completed launch may still be waiting for its first connection.if self.manager.is_session_starting(self.params.session_id, self.params.file_key):- return await self._create_new_session()+ await self._create_new_session()+ return# 2. Reconnect to existing session with same IDexisting_by_id = self.manager.get_session(self.params.session_id)if existing_by_id is not None:await self.handler._prepare_session(existing_by_id)- return self._reconnect_session(existing_by_id)-- # 3. Connect to existing session- # 3a. If RTC enabled and session exists for file key, connect to it+ self._reconnect_session(existing_by_id)+ return+ # 3. Viewer only mode: a second connection request is auto routed as reader onlyexisting_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- ):- await self.handler._prepare_session(existing_by_file)- return self._connect_rtc_session(existing_by_file)-- # 3b. Viewer only mode: a second connection request is auto routed as reader onlyif (existing_by_file is not Noneand session_in_edit_modeand not initial_capabilities(existing_by_file, self.params).edit):- return await self._connect_kiosk()+ await self._connect_kiosk()+ return# 4. Resume previous sessionresumable = self.manager.maybe_resume_session(@@ -131,12 +93,13 @@ class SessionConnector:)if resumable is not None:await self.handler._prepare_session(resumable)- return self._resume_session(resumable)+ self._resume_session(resumable)+ return# 5. Create new session- return await self._create_new_session()+ await self._create_new_session()- async def _connect_kiosk(self) -> tuple[Session, ConnectionType]:+ async def _connect_kiosk(self) -> None:"""Connect to kiosk session.Raises:@@ -174,11 +137,8 @@ class SessionConnector:LOGGER.debug("Connecting to kiosk session")await self.handler._prepare_session(kiosk_session)self.handler._connect_kiosk(kiosk_session)- return kiosk_session, ConnectionType.KIOSK- def _reconnect_session(- self, session: Session- ) -> tuple[Session, ConnectionType]:+ def _reconnect_session(self, session: Session) -> None:"""Reconnect to existing session.The session already exists, but it was disconnected. This can happen@@ -188,32 +148,18 @@ class SessionConnector:# In case there is a lingering connection, close itsession.disconnect_main_consumer()self.handler._reconnect_session(session, replay=False)- return session, ConnectionType.RECONNECT-- def _connect_rtc_session(- self, session: Session- ) -> tuple[Session, ConnectionType]:- """Connect to RTC-enabled session."""- LOGGER.debug(- "Connecting to existing session for file %s", self.params.file_key- )- self.handler._connect_to_existing_session(session)- return session, ConnectionType.RTC_EXISTING- def _resume_session(- self, session: Session- ) -> tuple[Session, ConnectionType]:+ def _resume_session(self, session: Session) -> None:"""Resume a previous session."""LOGGER.debug("Resuming session %s", self.params.session_id)self.handler._reconnect_session(session, replay=True)- return session, ConnectionType.RESUME@propertydef _is_run_mode(self) -> bool:"""Check if we're in run mode (read-only app mode)."""return self.manager.mode == SessionMode.RUN- async def _create_new_session(self) -> tuple[Session, ConnectionType]:+ async def _create_new_session(self) -> None:"""Create a new session.Grabs query params from the connection and creates a new session@@ -241,8 +187,6 @@ class SessionConnector:if self._is_run_mode:self._auto_instantiate(new_session)- return new_session, ConnectionType.NEW-def _extract_query_params(self) -> QueryParams:"""Read notebook parameters independently of stream options."""params = StarletteQueryParams(diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.pyindex 3eebc04d3e..1b020f0960 100644--- a/marimo/_server/api/endpoints/ws_endpoint.py+++ b/marimo/_server/api/endpoints/ws_endpoint.py@@ -7,7 +7,6 @@ from typing import TYPE_CHECKINGfrom starlette.responses import StreamingResponsefrom marimo import _loggers-from marimo._dependencies.dependencies import DependencyManagerfrom marimo._server.api.auth import validate_authfrom marimo._server.api.deps import AppStatefrom marimo._server.api.endpoints.ws.ws_connection_validator import (@@ -15,13 +14,11 @@ from marimo._server.api.endpoints.ws.ws_connection_validator import (WebSocketConnectionValidator,parse_connection_params,)-from marimo._server.api.endpoints.ws.ws_rtc_handler import RTCWebSocketHandlerfrom marimo._server.codes import WebSocketCloseReason, WebSocketCodesfrom marimo._server.host import stream_optionsfrom marimo._server.host.lifespan import ensure_hostfrom marimo._server.host.session import SessionEventStreamfrom marimo._server.router import APIRouter-from marimo._server.rtc.doc import LoroDocManagerfrom marimo._server.sse import SSE_HEADERS, format_close_eventif TYPE_CHECKING:@@ -38,8 +35,6 @@ LOGGER = _loggers.marimo_logger()router = APIRouter()-DOC_MANAGER = LoroDocManager()-@router.websocket("/ws")async def websocket_endpoint(@@ -85,7 +80,6 @@ async def _session_events(bridge=context.bridge,manager=AppState(connection).session_manager,params=params,- doc_manager=DOC_MANAGER,types=types,cursor=cursor,)@@ -135,9 +129,8 @@ async def sse_endpoint(request: Request) -> StreamingResponse:WebSocketCodes.UNAUTHORIZED, WebSocketCloseReason.UNAUTHORIZED)- # Extract and validate connection parameters. SSE cannot carry the- # /ws_sync document stream, so RTC is disabled.- params = parse_connection_params(app_state, allow_rtc=False)+ # Extract and validate connection parameters+ params = parse_connection_params(app_state)if isinstance(params, ConnectionRejection):return _close_only_stream(params.code, params.reason)@@ -160,47 +153,3 @@ async def sse_endpoint(request: Request) -> StreamingResponse:yield eventreturn _sse_response(stream())---# WebSocket endpoint for LoroDoc synchronization[email protected]("/ws_sync")-async def ws_sync(- websocket: WebSocket,-) -> None:- """WebSocket endpoint for LoroDoc synchronization (RTC)."""- app_state = AppState(websocket)- validator = WebSocketConnectionValidator(websocket, app_state)-- # Validate authentication before proceeding- if not await validator.validate_auth():- return-- # Check if Loro is available- if not DependencyManager.loro.has():- LOGGER.warning("RTC: Loro is not installed, closing websocket")- await websocket.close(- WebSocketCodes.NORMAL_CLOSE,- WebSocketCloseReason.LORO_NOT_INSTALLED,- )- return-- # Extract file key- file_key = await validator.extract_file_key_only()- if file_key is None:- return-- # Verify session exists- manager = app_state.session_manager- session = manager.get_session_by_file_key(file_key)- if session is None:- LOGGER.warning(- f"RTC: Closing websocket - no session found for file key {file_key}"- )- await websocket.close(- WebSocketCodes.FORBIDDEN, WebSocketCloseReason.NOT_ALLOWED- )- return-- # Handle RTC connection- handler = RTCWebSocketHandler(websocket, file_key, DOC_MANAGER)- await handler.handle()diff --git a/marimo/_server/codes.py b/marimo/_server/codes.pyindex 2e75f0a674..344c11c188 100644--- a/marimo/_server/codes.py+++ b/marimo/_server/codes.py@@ -20,7 +20,6 @@ class WebSocketCloseReason(str, Enum):`frontend/src/core/websocket/useMarimoKernelConnection.tsx`."""- LORO_NOT_INSTALLED = "MARIMO_LORO_NOT_INSTALLED"NOT_ALLOWED = "MARIMO_NOT_ALLOWED"UNAUTHORIZED = "MARIMO_UNAUTHORIZED"NO_SESSION_ID = "MARIMO_NO_SESSION_ID"diff --git a/marimo/_server/host/api.py b/marimo/_server/host/api.pyindex 30d21a1523..dba750fd83 100644--- a/marimo/_server/host/api.py+++ b/marimo/_server/host/api.py@@ -30,7 +30,6 @@ from marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionRejection,parse_connection_params,)-from marimo._server.api.endpoints.ws_endpoint import DOC_MANAGERfrom marimo._server.api.utils import format_url_host, open_url_in_browserfrom marimo._server.host import (ATTACHMENT_IDENTITY,@@ -264,7 +263,6 @@ async def _editor_events_ws(websocket: WebSocket) -> None:bridge=bridge,manager=manager,params=params,- doc_manager=DOC_MANAGER,types=types,cursor=cursor,).start()diff --git a/marimo/_server/host/session.py b/marimo/_server/host/session.pyindex c437424db2..ad89acf5a9 100644--- a/marimo/_server/host/session.py+++ b/marimo/_server/host/session.py@@ -18,7 +18,6 @@ from marimo._server.api.endpoints.ws.notification_filter import (should_filter_operation,)from marimo._server.api.endpoints.ws.session_handler import SessionHandler-from marimo._server.api.endpoints.ws.ws_session_connector import ConnectionTypefrom marimo._server.codes import WebSocketCloseReason, WebSocketCodesfrom marimo._server.host.events import (MarimoEvent,@@ -45,7 +44,6 @@ if TYPE_CHECKING:ConnectionParams,)from marimo._server.host.bridge import SessionBridge- from marimo._server.rtc.doc import LoroDocManagerfrom marimo._server.session_manager import SessionManagerfrom marimo._session.session import Session@@ -67,7 +65,6 @@ class SessionEventStream(SessionHandler):bridge: SessionBridge,manager: SessionManager,params: ConnectionParams,- doc_manager: LoroDocManager,types: set[str] | None,cursor: str | None,heartbeat_seconds: float = 20.0,@@ -76,7 +73,6 @@ class SessionEventStream(SessionHandler):manager=manager,params=params,mode=manager.mode,- doc_manager=doc_manager,)self.connection = connectionself.heartbeat_seconds = heartbeat_seconds@@ -91,11 +87,6 @@ class SessionEventStream(SessionHandler):self._events: asyncio.Queue[RoutedEvent | _Close | None] = (asyncio.Queue())- self._connection_type = (- ConnectionType.RTC_EXISTING- if params.rtc_enabled and not params.kiosk- else ConnectionType.NEW- )def notify(self, notification: KernelMessage) -> None:event = notification_event(@@ -158,7 +149,7 @@ class SessionEventStream(SessionHandler):async def connect_and_listen() -> None:try:- _, self._connection_type = await startup+ await startupself._check_status_update()await self._wait_for_disconnect()except asyncio.CancelledError:@@ -195,9 +186,7 @@ class SessionEventStream(SessionHandler):if isinstance(event.event, MarimoEvent):viewer = self.params.kioskif self._session is not None:- viewer = self._is_viewer(- self._session, self._connection_type- )+ viewer = self._is_viewer(self._session)if should_filter_operation(event.event.data.marimo.name, is_kiosk=viewer):diff --git a/marimo/_server/print.py b/marimo/_server/print.pyindex 95b40fff07..dfde58b007 100644--- a/marimo/_server/print.py+++ b/marimo/_server/print.py@@ -163,9 +163,16 @@ def print_experimental_features(config: MarimoConfig) -> None:keys = set(config["experimental"].keys())+ # These experiments were removed. Their keys still load, and do nothing.+ removed_experiments = {"rtc", "rtc_v2"}+ removed = sorted(keys & removed_experiments)+ if removed:+ print_tabbed(+ f"{_utf8('⚠️')} {yellow('Removed experimental features (ignored)')}: {', '.join(removed)}"+ )+# These experiments have been releasedfinished_experiments = {- "rtc","lsp","chat_sidebar","inline_ai_tooltip",@@ -186,7 +193,7 @@ def print_experimental_features(config: MarimoConfig) -> None:"server_side_pdf_export","storage_inspector",}- keys = keys - finished_experiments+ keys = keys - finished_experiments - removed_experimentsif len(keys) == 0:returndiff --git a/marimo/_server/rtc/doc.py b/marimo/_server/rtc/doc.pydeleted file mode 100644index 617e8b177d..0000000000--- a/marimo/_server/rtc/doc.py+++ /dev/null@@ -1,168 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-from __future__ import annotations--import asyncio-from typing import TYPE_CHECKING--from marimo import _loggers-from marimo._server.workspace import MarimoFileKey-from marimo._types.ids import CellId_t-from marimo._utils.asyncio_utils import supervised_task--if TYPE_CHECKING:- from loro import LoroDoc--LOGGER = _loggers.marimo_logger()---class LoroDocManager:- def __init__(self) -> None:- self.loro_docs: dict[MarimoFileKey, LoroDoc] = {}- self.loro_docs_lock = asyncio.Lock()- self.loro_docs_clients: dict[- MarimoFileKey, set[asyncio.Queue[bytes]]- ] = {}- self.loro_docs_cleaners: dict[- MarimoFileKey, asyncio.Task[None] | None- ] = {}-- async def _clean_loro_doc(- self, file_key: MarimoFileKey, timeout: float = 60- ) -> None:- """Clean up a loro doc if no clients are connected."""- try:- await asyncio.sleep(timeout)- async with self.loro_docs_lock:- if (- file_key in self.loro_docs_clients- and len(self.loro_docs_clients[file_key]) == 0- ):- LOGGER.debug(- f"RTC: Removing loro doc for file {file_key} as it has no clients"- )- # Clean up the document- await self._do_remove_doc(file_key)- except asyncio.CancelledError:- # Task was cancelled due to client reconnection- LOGGER.debug(- f"RTC: clean_loro_doc task cancelled for file {file_key} - likely due to reconnection"- )-- async def create_doc(- self,- file_key: MarimoFileKey,- cell_ids: tuple[CellId_t, ...],- codes: tuple[str, ...],- ) -> LoroDoc:- """Create a new loro doc."""- from loro import LoroDoc, LoroText-- assert len(cell_ids) == len(codes), (- "cell_ids and codes must be the same length"- )-- async with self.loro_docs_lock:- if file_key in self.loro_docs:- return self.loro_docs[file_key]-- LOGGER.debug(f"RTC: Initializing LoroDoc for file {file_key}")- doc = LoroDoc() # type: ignore[no-untyped-call]- self.loro_docs[file_key] = doc-- # Add all cell code to the doc- doc_codes = doc.get_map("codes")- doc.get_map("languages")- for cell_id, code in zip(cell_ids, codes, strict=False):- cell_text = LoroText() # type: ignore[no-untyped-call]- cell_text.insert(0, code)- doc_codes.insert_container(cell_id, cell_text)-- # We don't set the language here because it will be set- # when the client connects for the first time.- return doc-- async def get_or_create_doc(self, file_key: MarimoFileKey) -> LoroDoc:- """Get or create a loro doc for a file key."""- from loro import LoroDoc-- async with self.loro_docs_lock:- if file_key in self.loro_docs:- doc = self.loro_docs[file_key]- # Cancel existing cleaner task if it exists- cleaner = self.loro_docs_cleaners.get(file_key, None)- if cleaner is not None:- LOGGER.debug(- f"RTC: Cancelling existing cleaner for file {file_key}"- )- cleaner.cancel()- self.loro_docs_cleaners[file_key] = None- else:- LOGGER.warning(f"RTC: Expected loro doc for file {file_key}")- doc = LoroDoc() # type: ignore[no-untyped-call]- self.loro_docs[file_key] = doc- return doc-- def add_client_to_doc(- self, file_key: MarimoFileKey, update_queue: asyncio.Queue[bytes]- ) -> None:- """Add a client queue to the loro doc clients."""- if file_key not in self.loro_docs_clients:- self.loro_docs_clients[file_key] = {update_queue}- else:- self.loro_docs_clients[file_key].add(update_queue)-- async def broadcast_update(- self,- file_key: MarimoFileKey,- message: bytes,- exclude_queue: asyncio.Queue[bytes] | None = None,- ) -> None:- """Broadcast an update to all clients except the excluded queue."""- clients = self.loro_docs_clients[file_key]- for client in clients:- if client == exclude_queue:- continue- client.put_nowait(message)-- async def remove_client(- self,- file_key: MarimoFileKey,- update_queue: asyncio.Queue[bytes],- ) -> None:- """Clean up a loro client and potentially the doc if no clients remain."""- should_create_cleaner = False-- async with self.loro_docs_lock:- if file_key not in self.loro_docs_clients:- return-- self.loro_docs_clients[file_key].remove(update_queue)- # If no clients are connected, set up a cleaner task- if len(self.loro_docs_clients[file_key]) == 0:- # Remove any existing cleaner- cleaner = self.loro_docs_cleaners.get(file_key, None)- if cleaner is not None:- cleaner.cancel()- self.loro_docs_cleaners[file_key] = None- should_create_cleaner = True-- # Create the cleaner task outside the lock to avoid deadlocks- if should_create_cleaner:- self.loro_docs_cleaners[file_key] = supervised_task(- self._clean_loro_doc(file_key, 60.0),- name=f"rtc.cleaner.{file_key}",- )-- async def _do_remove_doc(self, file_key: MarimoFileKey) -> None:- """Actual implementation of removing a doc, separate from remove_doc to avoid deadlocks."""- if file_key in self.loro_docs:- del self.loro_docs[file_key]- if file_key in self.loro_docs_clients:- del self.loro_docs_clients[file_key]- if file_key in self.loro_docs_cleaners:- del self.loro_docs_cleaners[file_key]-- async def remove_doc(self, file_key: MarimoFileKey) -> None:- """Remove a loro doc and all associated clients"""- async with self.loro_docs_lock:- await self._do_remove_doc(file_key)diff --git a/marimo/_smoke_tests/inline_sse_transport.py b/marimo/_smoke_tests/inline_sse_transport.pyindex 9a01f4a350..fedcfe9fff 100644--- a/marimo/_smoke_tests/inline_sse_transport.py+++ b/marimo/_smoke_tests/inline_sse_transport.py@@ -46,8 +46,8 @@ def _(mo):4. Kill the server: the "disconnected / shutdown" UX should appear.Restart it: the client should reconnect and resume the session.- Note: with the SSE transport, RTC is auto-disabled and the terminal /- LSP features still require websockets.+ Note: with the SSE transport, the terminal and LSP features still+ require websockets.""")returndiff --git a/marimo/_utils/health.py b/marimo/_utils/health.pyindex ac61af23a4..6d2d0f0295 100644--- a/marimo/_utils/health.py+++ b/marimo/_utils/health.py@@ -9,7 +9,6 @@ import timefrom typing import TypedDictfrom marimo import _loggers-from marimo._utils.platform import is_pyodideLOGGER = _loggers.marimo_logger()@@ -122,7 +121,6 @@ def get_optional_modules_list() -> dict[str, str]:"basedpyright","duckdb","ibis-framework",- "loro","mcp","nbformat","openai",@@ -140,9 +138,6 @@ def get_optional_modules_list() -> dict[str, str]:"vegafusion","watchdog",]- if is_pyodide() or sys.platform == "android":- # loro is not installable on Emscripten/Android.- packages = [p for p in packages if p != "loro"]return _get_versions(packages, include_missing=False)diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex f74120d455..e9c6105206 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -5241,9 +5241,8 @@ components:\ frontend, typically set with the\n `MARIMO_SERVER_TRANSPORT` environment\\ variable. `\"websocket\"`\n (default) uses the `/ws` WebSocket endpoint;\\ `\"sse\"` uses\n server-sent events over HTTP, for deployments behind\- \ proxies or\n services that do not support WebSockets. Terminal, LSP,\- \ and\n real-time collaboration still require WebSockets; RTC is disabled\n\- \ when using `\"sse\"`."+ \ proxies or\n services that do not support WebSockets. The terminal\+ \ and LSP\n still require WebSockets."properties:browser:anyOf:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 7b8c0edc7f..5f92b0b7c8 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -6853,9 +6853,8 @@ export interface components {* `MARIMO_SERVER_TRANSPORT` environment variable. `"websocket"`* (default) uses the `/ws` WebSocket endpoint; `"sse"` uses* server-sent events over HTTP, for deployments behind proxies or- * services that do not support WebSockets. Terminal, LSP, and- * real-time collaboration still require WebSockets; RTC is disabled- * when using `"sse"`.+ * services that do not support WebSockets. The terminal and LSP+ * still require WebSockets.*/ServerConfig: {browser: "default" | string;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 90b91de887..46d75a03e3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -464,12 +464,6 @@ importers:lodash-es:specifier: ^4.18.1version: 4.18.1- loro-codemirror:- specifier: ^0.3.3- loro-crdt:- specifier: ^1.16.1- version: 1.16.1lucide-react:specifier: ^0.577.0version: 0.577.0([email protected])@@ -482,9 +476,6 @@ importers:mermaid:specifier: ^11.17.2version: 11.17.2- partysocket:- specifier: 1.3.0- version: 1.3.0([email protected])path-to-regexp:specifier: ^8.4.2version: 8.4.2@@ -723,9 +714,6 @@ importers:vite:specifier: ^8.3.0version: 8.3.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])- vite-plugin-wasm:- specifier: ^3.6.0- version: 3.6.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: ^4.1.11version: 4.1.11(@types/[email protected])(@vitest/[email protected])([email protected]([email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))@@ -5987,9 +5975,6 @@ packages:resolution: {integrity: sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==}- resolution: {integrity: sha512-Gs6RLjzlLRdT8X9ZipJdIZI/Y6/HhRLyq9RdDlCsnpxr/+Nn6bU2EFGuC94GjxqhM+Nmij2Vcq98yoHrU8uNFQ==}-resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}engines: {node: '>=0.8.x'}@@ -7091,16 +7076,6 @@ packages:resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}hasBin: true- resolution: {integrity: sha512-C6qAUmDjMTyoXVeDxKWixvr/TSTo/jXFrvgGW+wn6RAHeIzNFovBDLQNi/Sary4Ahx8DaYADTCm9eCaRAjvWtw==}- peerDependencies:- '@codemirror/state': ^6.0.0- '@codemirror/view': ^6.7.0- loro-crdt: ^1.8.2-- resolution: {integrity: sha512-olUkbQEjeeE78Kx6BknYrpbaX43wxRAycoiLZUSLVcMFKMSZ8RxPfp244kNVQEM8MQfgkbnwrNOaHU/yUb5Ncg==}-resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}@@ -7704,14 +7679,6 @@ packages:resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}engines: {node: '>= 0.8'}- resolution: {integrity: sha512-1zToNyolZFK/7nuAw/K2bZrNzFqaZyRoCEkS+9vG6WSC5ikrN6qWRe96q6ImU51uptz2r+dAwSkwhJVdQi4LiA==}- peerDependencies:- react: ^19.3.0- peerDependenciesMeta:- react:- optional: true-resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}@@ -9525,11 +9492,6 @@ packages:resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}- resolution: {integrity: sha512-mL/QPziiIA4RAA6DkaZZzOstdwbW5jO4Vz7Zenj0wieKWBlNvIvX5L5ljum9lcUX0ShNfBgCNLKTjNkRVVqcsw==}- peerDependencies:- vite: ^8.3.0-resolution: {integrity: sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==}engines: {node: ^20.19.0 || >=22.12.0}@@ -14985,8 +14947,6 @@ snapshots:d: 1.0.2es5-ext: 0.10.64- [email protected]: {}-@@ -16138,14 +16098,6 @@ snapshots:dependencies:js-tokens: 4.0.0- [email protected](@codemirror/[email protected])(@codemirror/[email protected])([email protected]):- dependencies:- '@codemirror/state': 6.7.6- '@codemirror/view': 6.43.13- loro-crdt: 1.16.1-- [email protected]: {}-@@ -17161,12 +17113,6 @@ snapshots:- dependencies:- event-target-polyfill: 0.0.4- optionalDependencies:- react: 19.3.0-@@ -19526,10 +19472,6 @@ snapshots:'@types/unist': 3.0.3vfile-message: 4.0.2- [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):- dependencies:- vite: 8.3.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])-[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.33.0diff --git a/pyproject.toml b/pyproject.tomlindex a6d063e1c8..16ba060917 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,9 +39,6 @@ dependencies = ["python-multipart>=0.0.18",# websockets for use with starlette, and for lsp"websockets >= 14.2.0; sys_platform != 'emscripten'",- # loro for collaborative editing (native extension; server-only).- # No cp315 wheels as of 2026-10; drop the python_version marker when published.- "loro>=1.10.0; python_version < '3.15' and sys_platform != 'emscripten' and sys_platform != 'android'",# python <=3.11 compatibility"typing_extensions>=4.4.0; python_version < '3.12'",# for rst parsing; lowerbound determined by awscli requiring < 0.17,@@ -271,7 +268,6 @@ typecheck = ["huggingface_hub>=1.24.0","fsspec>=2026.2.0","pydantic-ai-slim[google,anthropic,bedrock,openai]>=2.34.0,<3.0.0",- "loro>=1.5.0","boto3-stubs>=1.38.46","pandas-stubs>=1.5.3.230321","pyiceberg>=0.9.0",diff --git a/tests/_server/api/endpoints/test_sse.py b/tests/_server/api/endpoints/test_sse.pyindex 119dbc78f5..35646fc527 100644--- a/tests/_server/api/endpoints/test_sse.py+++ b/tests/_server/api/endpoints/test_sse.py@@ -23,9 +23,6 @@ from marimo._messaging.serde import serialize_kernel_messagefrom marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionParams,)-from marimo._server.api.endpoints.ws.ws_session_connector import (- ConnectionType,-)from marimo._server.host.session import SessionEventStreamfrom marimo._server.sse import format_close_event, format_sse_eventfrom marimo._session.managers.ipc import KernelStartupError@@ -492,7 +489,6 @@ def _make_handler(file_key="test.py",kiosk=False,auto_instantiate=False,- rtc_enabled=False,)handler = SessionEventStream(connection=request,@@ -502,7 +498,6 @@ def _make_handler(cursor=None,manager=MagicMock(mode=mode),params=params,- doc_manager=MagicMock(),heartbeat_seconds=60,)handler.status = ConnectionState.OPEN@@ -515,9 +510,8 @@ def _make_handler()handler.manager.get_session.return_value = session- async def connect(_request: Any) -> tuple[Any, ConnectionType]:+ async def connect(_request: Any) -> None:handler.on_attach(session, MagicMock())- return session, ConnectionType.NEWhandler._connect_session = AsyncMock( # type: ignore[method-assign]side_effect=connectdiff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex eb0d6521e0..5926c58bfa 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -2,7 +2,6 @@from __future__ import annotationsimport asyncio-from contextlib import contextmanagerfrom pathlib import Pathfrom typing import TYPE_CHECKING, Anyfrom unittest.mock import AsyncMock, MagicMock, patch@@ -10,8 +9,6 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom starlette.websockets import WebSocket, WebSocketDisconnect-from marimo._config.config import ExperimentalConfig-from marimo._config.manager import MarimoConfigManagerfrom marimo._messaging.notification import (EnvironmentOperationNotification,KernelReadyNotification,@@ -22,7 +19,6 @@ from marimo._messaging.serde import serialize_kernel_messagefrom marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionParams,)-from marimo._server.api.endpoints.ws.ws_session_connector import ConnectionTypefrom marimo._server.codes import WebSocketCodesfrom marimo._server.host.session import SessionEventStreamfrom marimo._server.session_manager import SessionManager@@ -39,7 +35,7 @@ from tests._server.api.endpoints.ws_helpers import (receive_notification,receive_until,)-from tests._server.conftest import get_kernel_tasks, get_user_config_manager+from tests._server.conftest import get_kernel_tasksfrom tests._server.mocks import get_session_managerif TYPE_CHECKING:@@ -94,7 +90,6 @@ async def test_failed_startup_progress_delivery_detaches_session(connection=websocket,notebook=None,bridge=MagicMock(),- doc_manager=MagicMock(),types=None,cursor=None,manager=manager,@@ -103,11 +98,10 @@ async def test_failed_startup_progress_delivery_detaches_session(file_key="test.py",kiosk=False,auto_instantiate=False,- rtc_enabled=False,),)- async def connect(_connection: Any) -> tuple[Any, ConnectionType]:+ async def connect(_connection: Any) -> None:handler.on_attach(session, MagicMock())# Progress reaches the startup queue only while the handler is still# connecting; once open, it travels with session messages instead.@@ -119,7 +113,6 @@ async def test_failed_startup_progress_delivery_detaches_session())handler.status = ConnectionState.OPEN- return session, ConnectionType.NEWwith patch.object(handler, "_connect_session", side_effect=connect):task = asyncio.create_task(handler.start())@@ -231,21 +224,6 @@ def test_completed_startup_is_restored_on_reconnect_and_refresh(}-def test_allows_multiple_connections_with_other_sessions(- client: TestClient,-) -> None:- with rtc_enabled(get_user_config_manager(client)):- with client.websocket_connect(WS_URL) as websocket:- data = receive_notification(websocket)- assert_kernel_ready_response(data)- # Should allow second connection- with client.websocket_connect(OTHER_WS_URL) as other_websocket:- data = receive_notification(other_websocket)- assert_kernel_ready_response(- data, create_response({"resumed": True})- )--def test_second_connection_with_other_session_joins_as_viewer(client: TestClient,) -> None:@@ -260,23 +238,6 @@ def test_second_connection_with_other_session_joins_as_viewer()-def test_allows_multiple_connections_with_same_file(- client: TestClient,- temp_marimo_file: str,-) -> None:- del temp_marimo_file- with rtc_enabled(get_user_config_manager(client)):- ws_1 = WS_URL- ws_2 = _create_ws_url("456")- with client.websocket_connect(ws_1) as websocket:- data = receive_notification(websocket)- assert_parse_ready_response(data)- # Should allow second connection- with client.websocket_connect(ws_2) as other_websocket:- data = receive_notification(other_websocket)- assert_parse_ready_response(data)--def test_second_connection_with_same_file_joins_as_viewer(client: TestClient,temp_marimo_file: str,@@ -386,66 +347,6 @@ async def test_cannot_connect_kiosk_with_run_session(assert exc_info.value.reason == "MARIMO_KIOSK_NOT_ALLOWED"-async def test_connects_to_existing_session_with_same_file(- client: TestClient,- temp_marimo_file: str,-) -> None:- ws_1 = f"{WS_URL}&file={temp_marimo_file}"- ws_2 = f"{OTHER_WS_URL}&file={temp_marimo_file}"-- with rtc_enabled(get_user_config_manager(client)):- with client.websocket_connect(ws_1) as websocket1:- data = receive_notification(websocket1)- assert_parse_ready_response(data)- for op in (- "environment-state",- "environment-state",- ):- assert receive_notification(websocket1)["op"] == op-- # Instantiate the session- client.post(- "/api/kernel/instantiate",- headers=headers("123"),- json={"objectIds": [], "values": [], "auto_run": True},- )-- messages1 = flush_messages(websocket1, at_least=14)- # This can/may change if implementation changes, but this is a snapshot to- # make sure it doesn't change when we don't expect it to- assert len(messages1) == 14- assert messages1[0]["op"] == "notebook-document-transaction"-- # Connect second client - should connect to same session- with client.websocket_connect(ws_2) as websocket2:- # Read the ready message before inspecting the room. Opening the- # websocket only waits for the server to accept the connection,- # which happens before the consumer joins the room. The ready- # message is sent after the join, so it is the earliest point at- # which the room membership is observable.- data2 = receive_notification(websocket2)- assert_parse_ready_response(data2)- for op in (- "environment-state",- "environment-state",- ):- assert receive_notification(websocket2)["op"] == op-- assert data2["data"]["resumed"] is True-- # Check in the same room- session_manager = get_session_manager(client)- assert len(session_manager.sessions) == 1- room = session_manager.sessions[SessionId("123")].room- assert {"123", "456"} <= set(room.consumers)-- messages2 = flush_messages(websocket2, at_least=3)- # This can/may change if implementation changes, but this is a snapshot to- # make sure it doesn't change when we don't expect it to- assert len(messages2) == 3- assert messages2[0]["op"] == "variables"--def flush_messages(websocket: WebSocketTestSession, at_least: int = 0) -> list[dict[str, Any]]:@@ -458,17 +359,6 @@ def flush_messages(return messages-@contextmanager-def rtc_enabled(config: MarimoConfigManager):- prev_config = config.get_config()- try:- experimental_config = ExperimentalConfig(rtc_v2=True)- config.save_config({"experimental": experimental_config})- yield- finally:- config.save_config(prev_config)--def test_ws_requires_authentication(client: TestClient) -> None:"""Test that WebSocket connections require authentication."""# Try to connect without any authentication headers@@ -494,17 +384,6 @@ def test_ws_rejects_invalid_token(client: TestClient) -> None:assert exc_info.value.reason == "MARIMO_UNAUTHORIZED"-def test_ws_sync_requires_authentication(client: TestClient) -> None:- """Test that WebSocket sync endpoint requires authentication."""- # Try to connect without any authentication headers- with pytest.raises(WebSocketDisconnect) as exc_info:- with client.websocket_connect("/ws_sync?file=test"):- raise AssertionError("Should not be able to connect without auth")-- assert exc_info.value.code == WebSocketCodes.UNAUTHORIZED- assert exc_info.value.reason == "MARIMO_UNAUTHORIZED"--def test_ws_with_valid_authentication(client: TestClient) -> None:"""Test that WebSocket connections work with valid authentication."""# Connect with proper authentication headers@@ -807,24 +686,6 @@ def test_missing_file_key_closes_connection(client: TestClient) -> None:assert exc_info.value.reason == "MARIMO_NO_FILE_KEY"-async def test_rtc_config_with_loro_unavailable(client: TestClient) -> None:- """Regression test: connection works when RTC enabled but Loro unavailable."""- from unittest.mock import patch-- # Enable RTC in config but mock Loro as unavailable- with (- rtc_enabled(get_user_config_manager(client)),- patch(- "marimo._server.api.endpoints.ws.ws_kernel_ready.is_rtc_available",- return_value=False,- ),- ):- # Connection should succeed without errors- with client.websocket_connect(WS_URL) as websocket:- data = receive_notification(websocket)- assert_kernel_ready_response(data)--# ============================================================================# Advanced WebSocket State Machine Tests# ============================================================================diff --git a/tests/_server/api/endpoints/test_ws_rtc.py b/tests/_server/api/endpoints/test_ws_rtc.pydeleted file mode 100644index c6558fc474..0000000000--- a/tests/_server/api/endpoints/test_ws_rtc.py+++ /dev/null@@ -1,285 +0,0 @@-from __future__ import annotations--import asyncio-from contextlib import contextmanager-from typing import TYPE_CHECKING--import pytest-from starlette.websockets import WebSocketDisconnect--from marimo._config.manager import MarimoConfigManager-from marimo._server.api.endpoints.ws_endpoint import DOC_MANAGER-from tests._server.api.endpoints.ws_helpers import (- assert_kernel_ready_response,- assert_parse_ready_response,- create_response,- receive_notification,-)-from tests._server.conftest import get_user_config_manager-from tests._server.mocks import get_session_manager--if TYPE_CHECKING:- from collections.abc import AsyncGenerator-- from starlette.testclient import TestClient--[email protected] # type: ignore-async def setup_loro_docs() -> AsyncGenerator[None, None]:- """Setup and teardown for loro_docs tests"""- # Clear any existing loro docs- DOC_MANAGER.loro_docs.clear()- DOC_MANAGER.loro_docs_clients.clear()- DOC_MANAGER.loro_docs_cleaners.clear()- yield- # Cleanup after test- DOC_MANAGER.loro_docs.clear()- DOC_MANAGER.loro_docs_clients.clear()- DOC_MANAGER.loro_docs_cleaners.clear()---@contextmanager-def rtc_enabled(config: MarimoConfigManager):- prev_config = config.get_config()- try:- config.save_config({"experimental": {"rtc_v2": True}})- yield- finally:- config.save_config(prev_config)---# Set up unique websocket paths for each client-ws_1 = "/ws?session_id=123&access_token=fake-token"-ws_2 = "/ws?session_id=456&access_token=fake-token"--# Set up unique synchronization websocket paths for each client-ws_1_sync = "/ws_sync?session_id=123&access_token=fake-token"-ws_2_sync = "/ws_sync?session_id=456&access_token=fake-token"--[email protected]("sys.version_info >= (3, 14)")-async def test_loro_sync(client: TestClient) -> None:- """Test that Loro-CRDT sync works between multiple clients"""-- # First connect main websockets to create sessions- with (- rtc_enabled(get_user_config_manager(client)),- client.websocket_connect(ws_1) as websocket1,- client.websocket_connect(ws_2) as websocket2,- ):- # Verify both websockets received kernel ready messages- data1 = receive_notification(websocket1)- assert_kernel_ready_response(data1)- data2 = receive_notification(websocket2)- assert_parse_ready_response(data2)-- # Connect first client to sync websocket- with client.websocket_connect(ws_1_sync) as sync_ws1:- # Should receive initial sync message (binary data)- sync_msg1 = sync_ws1.receive_bytes()- # Loro sends binary data directly- assert len(sync_msg1) > 0-- # Connect second client to sync websocket- with client.websocket_connect(ws_2_sync) as sync_ws2:- # Should receive initial sync message (binary data)- sync_msg2 = sync_ws2.receive_bytes()- assert len(sync_msg2) > 0-- # Verify both clients received initial sync data- assert len(sync_msg1) > 0- assert len(sync_msg2) > 0--[email protected]("sys.version_info >= (3, 14)")-async def test_loro_cleanup_on_session_close(- client: TestClient,-) -> None:- """Test that cell websockets are cleaned up when session closes"""- from loro import ExportMode, LoroDoc-- # Create a LoroDoc for the cell content- doc = LoroDoc()- initial_code = doc.export(ExportMode.Snapshot())-- file_key = get_session_manager(client).workspace.get_unique_file_key()- assert file_key is not None-- with (- rtc_enabled(get_user_config_manager(client)),- client.websocket_connect(ws_1) as websocket,- ):- data = receive_notification(websocket)- assert_kernel_ready_response(data)-- # Connect to cell websocket- with client.websocket_connect(ws_1_sync) as cell_ws:- sync_msg = cell_ws.receive_bytes()- assert len(sync_msg) > 0-- assert file_key in DOC_MANAGER.loro_docs_clients- assert len(DOC_MANAGER.loro_docs_clients[file_key]) == 1-- # Close main websocket- websocket.close()-- # Give the server some time to process the disconnection- await asyncio.sleep(1.5)-- try:- cell_ws.send_bytes(initial_code)- except Exception:- pass-- assert len(DOC_MANAGER.loro_docs_clients[file_key]) == 0--[email protected]("sys.version_info >= (3, 14)")-async def test_loro_persistence(client: TestClient) -> None:- """Test that cell content persists between connections"""- from loro import ExportMode, LoroDoc-- # Create a LoroDoc for the cell content- doc = LoroDoc()- initial_code = doc.export(ExportMode.Snapshot())-- # First connection sets initial code- with (- rtc_enabled(get_user_config_manager(client)),- client.websocket_connect(ws_1) as websocket,- ):- data = receive_notification(websocket)- assert_kernel_ready_response(data)-- with client.websocket_connect(ws_1_sync) as cell_ws1:- sync_msg = cell_ws1.receive_bytes()- assert len(sync_msg) > 0-- # Send initial code update- # In Loro, we send the binary snapshot directly- cell_ws1.send_bytes(initial_code)-- # Allow time for the update to be processed- await asyncio.sleep(0.2)-- # Allow some time for cleanup between sessions- await asyncio.sleep(0.2)-- # Second connection should receive persisted code- with (- rtc_enabled(get_user_config_manager(client)),- client.websocket_connect(ws_2) as websocket,- ):- data = receive_notification(websocket)- assert_kernel_ready_response(data, create_response({"resumed": True}))-- with client.websocket_connect(ws_2_sync) as cell_ws2:- sync_msg = cell_ws2.receive_bytes()- # Verify initial sync contains data- assert len(sync_msg) > 0---# ==============================================================================-# Edge Cases - RTC Availability and Graceful Degradation-# ==============================================================================--[email protected]("sys.version_info >= (3, 14)")-async def test_rtc_degrades_without_loro(client: TestClient) -> None:- """Test that RTC gracefully degrades when Loro is unavailable.-- Connection should succeed and no RTC doc should be created.- """- from unittest.mock import patch-- file_key = get_session_manager(client).workspace.get_unique_file_key()- assert file_key is not None-- # Clear any existing docs- DOC_MANAGER.loro_docs.clear()-- # Mock Loro as not available- with (- rtc_enabled(get_user_config_manager(client)),- patch(- "marimo._server.api.endpoints.ws.ws_kernel_ready.DependencyManager.loro.has",- return_value=False,- ),- ):- with client.websocket_connect(- "/ws?session_id=123&access_token=fake-token"- ) as websocket:- data = receive_notification(websocket)- # Should still get kernel ready, but without RTC initialized- assert_kernel_ready_response(data)-- # Give time for any async doc creation- await asyncio.sleep(0.2)-- # Verify no RTC doc was created- assert file_key not in DOC_MANAGER.loro_docs---# ==============================================================================-# Edge Cases - RTC Sync Endpoint-# ==============================================================================--[email protected]("sys.version_info >= (3, 14)")-async def test_ws_sync_without_existing_session(client: TestClient) -> None:- """Test that ws_sync endpoint requires an existing session."""- file_key = get_session_manager(client).workspace.get_unique_file_key()- assert file_key is not None-- ws_sync_url = f"/ws_sync?file={file_key}&access_token=fake-token"-- # Try to connect to ws_sync without creating a main session first- with pytest.raises(WebSocketDisconnect) as exc_info:- with client.websocket_connect(ws_sync_url):- pass-- from marimo._server.codes import WebSocketCodes-- assert exc_info.value.code == WebSocketCodes.FORBIDDEN- assert exc_info.value.reason == "MARIMO_NOT_ALLOWED"--[email protected]("sys.version_info >= (3, 14)")-async def test_ws_sync_cleanup_on_main_disconnect(client: TestClient) -> None:- """Test that ws_sync clients are cleaned up when main session disconnects."""- file_key = get_session_manager(client).workspace.get_unique_file_key()- assert file_key is not None-- # Clear any existing docs- DOC_MANAGER.loro_docs_clients.clear()-- ws_1 = "/ws?session_id=123&access_token=fake-token"- ws_sync_url = f"/ws_sync?file={file_key}&access_token=fake-token"-- with rtc_enabled(get_user_config_manager(client)):- with client.websocket_connect(ws_1) as main_websocket:- data = receive_notification(main_websocket)- assert_kernel_ready_response(data)-- # Connect to sync endpoint- with client.websocket_connect(ws_sync_url) as sync_websocket:- # Should receive initial sync- sync_msg = sync_websocket.receive_bytes()- assert len(sync_msg) > 0-- # Verify client was added- assert file_key in DOC_MANAGER.loro_docs_clients- initial_client_count = len(- DOC_MANAGER.loro_docs_clients[file_key]- )- assert initial_client_count == 1-- # Close sync websocket- sync_websocket.close()-- # Wait for cleanup- await asyncio.sleep(0.2)-- # Client should be removed- if file_key in DOC_MANAGER.loro_docs_clients:- assert len(DOC_MANAGER.loro_docs_clients[file_key]) == 0diff --git a/tests/_server/api/endpoints/test_ws_session_connector.py b/tests/_server/api/endpoints/test_ws_session_connector.pydeleted file mode 100644index f758eb9509..0000000000--- a/tests/_server/api/endpoints/test_ws_session_connector.py+++ /dev/null@@ -1,58 +0,0 @@-# 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/test_ws_connection_validator.py b/tests/_server/api/endpoints/ws/test_ws_connection_validator.pyindex b1e9129348..5d0467e153 100644--- a/tests/_server/api/endpoints/ws/test_ws_connection_validator.py+++ b/tests/_server/api/endpoints/ws/test_ws_connection_validator.py@@ -15,13 +15,9 @@ from marimo._server.codes import WebSocketCloseReason, WebSocketCodesdef _app_state(query: dict[str, str] | None = None,unique_file_key: str | None = "test.py",- rtc_v2: bool = False,) -> MagicMock:query = query or {}- config: dict[str, Any] = {- "runtime": {"auto_instantiate": True},- "experimental": {"rtc_v2": rtc_v2},- }+ config: dict[str, Any] = {"runtime": {"auto_instantiate": True}}app_state = MagicMock()app_state.query_params.side_effect = query.getworkspace = app_state.session_manager.workspace@@ -56,7 +52,6 @@ def test_extracts_params() -> None:file_key="test.py",kiosk=True,auto_instantiate=True,- rtc_enabled=False,)@@ -66,21 +61,3 @@ def test_file_query_param_wins_over_unique_file_key() -> None:)assert isinstance(result, ConnectionParams)assert result.file_key == "other.py"---def test_rtc_enabled_from_config() -> None:- result = parse_connection_params(- _app_state(query={"session_id": "123"}, rtc_v2=True)- )- assert isinstance(result, ConnectionParams)- assert result.rtc_enabled is True---def test_allow_rtc_false_disables_rtc() -> None:- # The SSE transport cannot carry the /ws_sync document stream- result = parse_connection_params(- _app_state(query={"session_id": "123"}, rtc_v2=True),- allow_rtc=False,- )- assert isinstance(result, ConnectionParams)- assert result.rtc_enabled is Falsediff --git a/tests/_server/api/test_websocket_origin.py b/tests/_server/api/test_websocket_origin.pyindex 477aabbcf0..1a4990f853 100644--- a/tests/_server/api/test_websocket_origin.py+++ b/tests/_server/api/test_websocket_origin.py@@ -370,7 +370,6 @@ def test_forwarded_headers_are_not_used_directly() -> None:"path",["/ws",- "/ws_sync","/terminal/ws","/lsp/pylsp","/api/marimo/v1/notebooks/test/events/ws",diff --git a/tests/_server/rtc/test_rtc_doc.py b/tests/_server/rtc/test_rtc_doc.pydeleted file mode 100644index 2fb4c3ee18..0000000000--- a/tests/_server/rtc/test_rtc_doc.py+++ /dev/null@@ -1,338 +0,0 @@-from __future__ import annotations--import asyncio-import sys-from typing import TYPE_CHECKING, cast--import pytest--from marimo._server.rtc.doc import LoroDocManager-from marimo._server.workspace import MarimoFileKey-from marimo._types.ids import CellId_t--if sys.version_info < (3, 14):- from loro import LoroDoc, LoroText--doc_manager = LoroDocManager()---if TYPE_CHECKING:- from collections.abc import AsyncGenerator--[email protected] # type: ignore-async def setup_doc_manager() -> AsyncGenerator[None, None]:- """Setup and teardown for loro_docs tests"""- # Clear any existing loro docs- doc_manager.loro_docs.clear()- doc_manager.loro_docs_clients.clear()- doc_manager.loro_docs_cleaners.clear()- yield- # Cleanup after test- doc_manager.loro_docs.clear()- doc_manager.loro_docs_clients.clear()- doc_manager.loro_docs_cleaners.clear()--[email protected]("sys.version_info >= (3, 14)")-async def test_quick_reconnection(setup_doc_manager: None) -> None:- """Test that quick reconnection properly handles cleanup task cancellation"""- del setup_doc_manager- # Setup- file_key = MarimoFileKey("test_file")-- # Create initial loro_doc- doc = LoroDoc()- doc_manager.loro_docs[file_key] = doc-- # Setup client queue- update_queue = asyncio.Queue[bytes]()- doc_manager.loro_docs_clients[file_key] = {update_queue}-- # Start cleanup task- cleanup_task = asyncio.create_task(doc_manager._clean_loro_doc(file_key))-- # Simulate quick reconnection by creating a new client before cleanup finishes- new_queue = asyncio.Queue[bytes]()- doc_manager.loro_docs_clients[file_key].add(new_queue)-- # Cancel cleanup task- cleanup_task.cancel()- try:- await cleanup_task- except asyncio.CancelledError:- pass-- # Verify state- assert len(doc_manager.loro_docs) == 1- assert (- len(doc_manager.loro_docs_clients[file_key]) == 2- ) # Original client + reconnected client--[email protected]("sys.version_info >= (3, 14)")-async def test_two_users_sync(setup_doc_manager: None) -> None:- """Test that two users can connect and sync text properly without duplicates"""- del setup_doc_manager- file_key = MarimoFileKey("test_file")- cell_id = str(CellId_t("test_cell")) # Convert CellId to string for loro-- # First user connects- doc = LoroDoc()- doc_manager.loro_docs[file_key] = doc-- # Setup client queues for both users- queue1 = asyncio.Queue[bytes]()- queue2 = asyncio.Queue[bytes]()- doc_manager.loro_docs_clients[file_key] = {queue1, queue2}-- # Get maps from doc- doc_codes = doc.get_map("codes")- doc_languages = doc.get_map("languages")-- # Add text to the doc using get_or_create_container- code_text = doc_codes.get_or_create_container(cell_id, LoroText())- code_text_typed = cast(LoroText, code_text)- code_text_typed.insert(0, "print('hello')")-- lang_text = doc_languages.get_or_create_container(cell_id, LoroText())- lang_text_typed = cast(LoroText, lang_text)- lang_text_typed.insert(0, "python")-- # Verify state- assert len(doc_manager.loro_docs) == 1- assert len(doc_manager.loro_docs_clients[file_key]) == 2-- # Make sure we can get the text content- assert code_text_typed.to_string() == "print('hello')"-- # Second user makes changes - no need to retrieve the text again- code_text_typed.insert(- len(code_text_typed.to_string()), "\nprint('world')"- )-- # Verify changes propagate- assert code_text_typed.to_string() == "print('hello')\nprint('world')"- assert lang_text_typed.to_string() == "python"--[email protected]("sys.version_info >= (3, 14)")-async def test_concurrent_doc_creation(setup_doc_manager: None) -> None:- """Test concurrent doc creation doesn't cause issues"""- del setup_doc_manager- file_key = MarimoFileKey("test_file")- cell_ids = (CellId_t("cell1"), CellId_t("cell2"))- codes = ("print('hello')", "print('world')")-- # Create multiple tasks that try to create the same doc- tasks = [- doc_manager.create_doc(file_key, cell_ids, codes) for _ in range(5)- ]- docs = await asyncio.gather(*tasks)-- # All tasks should return the same doc instance- assert all(doc is docs[0] for doc in docs)- assert len(doc_manager.loro_docs) == 1--[email protected]("sys.version_info >= (3, 14)")-async def test_concurrent_client_operations(- setup_doc_manager: None,-) -> None:- """Test concurrent client operations don't cause deadlocks"""- del setup_doc_manager- file_key = MarimoFileKey("test_file")- doc = LoroDoc()- doc_manager.loro_docs[file_key] = doc-- # Create multiple client queues- queues = [asyncio.Queue[bytes]() for _ in range(5)]- doc_manager.loro_docs_clients[file_key] = set(queues)-- # Concurrently add and remove clients- async def client_operation(queue: asyncio.Queue[bytes]) -> None:- doc_manager.add_client_to_doc(file_key, queue)- await asyncio.sleep(0.1) # Simulate some work- await doc_manager.remove_client(file_key, queue)-- tasks = [client_operation(queue) for queue in queues]- await asyncio.gather(*tasks)-- # Verify final state- assert len(doc_manager.loro_docs_clients[file_key]) == 0--[email protected]("sys.version_info >= (3, 14)")-async def test_cleanup_task_management(setup_doc_manager: None) -> None:- """Test cleanup task management and cancellation"""- del setup_doc_manager- file_key = MarimoFileKey("test_file")- doc = LoroDoc()- doc_manager.loro_docs[file_key] = doc-- # Add and remove a client to trigger cleanup- queue = asyncio.Queue[bytes]()- doc_manager.add_client_to_doc(file_key, queue)- await doc_manager.remove_client(file_key, queue)-- # Verify cleanup task was created- assert file_key in doc_manager.loro_docs_cleaners- assert doc_manager.loro_docs_cleaners[file_key] is not None-- # Add a new client before cleanup finishes- new_queue = asyncio.Queue[bytes]()- doc_manager.add_client_to_doc(file_key, new_queue)-- # Wait for the task to be cancelled- await asyncio.sleep(0.1)-- # Verify cleanup task was cancelled and removed- # TODO: not sure why this is still here.- # assert doc_manager.loro_docs_cleaners[file_key] is None-- # Clean up- await doc_manager.remove_client(file_key, new_queue)--[email protected]("sys.version_info >= (3, 14)")-async def test_broadcast_update(setup_doc_manager: None) -> None:- """Test broadcast update functionality"""- del setup_doc_manager- file_key = MarimoFileKey("test_file")- doc = LoroDoc()- doc_manager.loro_docs[file_key] = doc-- # Create multiple client queues- queues = [asyncio.Queue[bytes]() for _ in range(3)]- doc_manager.loro_docs_clients[file_key] = set(queues)-- # Broadcast a message- message = b"test message"- await doc_manager.broadcast_update(- file_key, message, exclude_queue=queues[0]- )-- # Verify all queues except excluded one received the message- for i, queue in enumerate(queues):- if i == 0:- assert queue.empty()- else:- assert await queue.get() == message--[email protected]("sys.version_info >= (3, 14)")-async def test_remove_nonexistent_doc(setup_doc_manager: None) -> None:- """Test removing a doc that doesn't exist"""- del setup_doc_manager- file_key = MarimoFileKey("nonexistent")- await doc_manager.remove_doc(file_key)- assert file_key not in doc_manager.loro_docs- assert file_key not in doc_manager.loro_docs_clients- assert file_key not in doc_manager.loro_docs_cleaners--[email protected]("sys.version_info >= (3, 14)")-async def test_remove_nonexistent_client(setup_doc_manager: None) -> None:- """Test removing a client that doesn't exist"""- del setup_doc_manager- file_key = MarimoFileKey("test_file")- queue = asyncio.Queue[bytes]()- await doc_manager.remove_client(file_key, queue)- assert file_key not in doc_manager.loro_docs_clients--[email protected]("sys.version_info >= (3, 14)")-async def test_concurrent_doc_removal(setup_doc_manager: None) -> None:- """Test concurrent doc removal doesn't cause issues"""- del setup_doc_manager- file_key = MarimoFileKey("test_file")- doc = LoroDoc()- doc_manager.loro_docs[file_key] = doc-- # Create multiple tasks that try to remove the same doc- tasks = [doc_manager.remove_doc(file_key) for _ in range(5)]- await asyncio.gather(*tasks)-- # Verify doc was removed- assert file_key not in doc_manager.loro_docs- assert file_key not in doc_manager.loro_docs_clients- assert file_key not in doc_manager.loro_docs_cleaners--[email protected]("sys.version_info >= (3, 14)")-async def test_prevent_lock_deadlock(setup_doc_manager: None) -> None:- """Test that our deadlock prevention measures work correctly.-- This test simulates the scenario that could cause a deadlock:- 1. A client disconnects, starting the cleanup process- 2. Another operation acquires the lock before cleanup timer finishes- 3. Cleanup timer expires and tries to acquire the lock-- The fixed implementation should handle this without deadlocking.- """- del setup_doc_manager- file_key = MarimoFileKey("test_file")-- # Create a doc and add a client- doc = LoroDoc()- doc_manager.loro_docs[file_key] = doc- queue = asyncio.Queue[bytes]()- doc_manager.add_client_to_doc(file_key, queue)-- # Set a very short cleanup timeout for testing- original_timeout = 60.0- cleanup_timeout = 0.1 # 100ms-- # Create a barrier to coordinate tasks- barrier = asyncio.Barrier(2)- long_operation_done = asyncio.Event()-- # Task 1: Remove client, which will schedule cleanup with short timeout- async def remove_client_task() -> None:- await doc_manager.remove_client(file_key, queue)- # Wait at barrier to synchronize with the long operation- await barrier.wait()- # Wait for long operation to complete- await long_operation_done.wait()-- # Task 2: Simulate a long operation that holds the lock- async def long_lock_operation() -> None:- # Wait for remove_client to schedule the cleanup- await barrier.wait()-- # Acquire the lock and hold it for longer than the cleanup timeout- async with doc_manager.loro_docs_lock:- # Sleep while holding the lock (longer than cleanup timeout)- await asyncio.sleep(cleanup_timeout * 2)-- # Signal that we're done holding the lock- long_operation_done.set()-- # Modified test version of _clean_loro_doc with shorter timeout- original_clean_loro_doc = doc_manager._clean_loro_doc-- async def test_clean_loro_doc(- file_key: MarimoFileKey, timeout: float = original_timeout- ) -> None:- del timeout- # Override timeout with our test value- await original_clean_loro_doc(file_key, cleanup_timeout)-- # Override the method for this test- doc_manager._clean_loro_doc = test_clean_loro_doc-- try:- # Run both tasks simultaneously- task1 = asyncio.create_task(remove_client_task())- task2 = asyncio.create_task(long_lock_operation())-- # This should complete without deadlocking- await asyncio.gather(task1, task2)-- # Verify the doc was properly cleaned up- assert file_key not in doc_manager.loro_docs- assert file_key not in doc_manager.loro_docs_clients- assert file_key not in doc_manager.loro_docs_cleaners- finally:- # Restore the original method- doc_manager._clean_loro_doc = original_clean_loro_docdiff --git a/tests/_server/test_codes.py b/tests/_server/test_codes.pyindex 0c31887be0..2c8c04964b 100644--- a/tests/_server/test_codes.py+++ b/tests/_server/test_codes.py@@ -10,9 +10,6 @@ def test_websocket_close_reason_wire_values() -> None:Renaming a member must not silently change the value the frontendmatches against in `useMarimoKernelConnection.tsx`."""- assert (- WebSocketCloseReason.LORO_NOT_INSTALLED == "MARIMO_LORO_NOT_INSTALLED"- )assert WebSocketCloseReason.NOT_ALLOWED == "MARIMO_NOT_ALLOWED"assert WebSocketCloseReason.UNAUTHORIZED == "MARIMO_UNAUTHORIZED"assert WebSocketCloseReason.NO_SESSION_ID == "MARIMO_NO_SESSION_ID"diff --git a/tests/_server/test_print.py b/tests/_server/test_print.pyindex 5d698f4ec4..fab6c9c14e 100644--- a/tests/_server/test_print.py+++ b/tests/_server/test_print.py@@ -337,12 +337,21 @@ def test_print_experimental_features() -> None:# Test with experimental features that have been releasedwith io.StringIO() as buf, redirect_stdout(buf):config = merge_default_config(- {"experimental": {"rtc": True, "chat_sidebar": True}}+ {"experimental": {"lsp": True, "chat_sidebar": True}})print_experimental_features(config)output = buf.getvalue()assert output == ""+ # Test with an experimental feature that has been removed+ with io.StringIO() as buf, redirect_stdout(buf):+ config = merge_default_config({"experimental": {"rtc_v2": True}})+ print_experimental_features(config)+ output = buf.getvalue()+ assert "Removed experimental features" in output+ assert "rtc_v2" in output+ assert "Experimental features (use with caution)" not in output+# Test with experimental features that have not been releasedwith io.StringIO() as buf, redirect_stdout(buf):config = merge_default_config({"experimental": {"new_feature": True}})diff --git a/tests/_server/test_session_manager.py b/tests/_server/test_session_manager.pyindex c9d90299b2..41f9ebc13b 100644--- a/tests/_server/test_session_manager.py+++ b/tests/_server/test_session_manager.py@@ -599,7 +599,6 @@ async def test_connections_share_starting_notebook(ConnectionParams,)from marimo._server.api.endpoints.ws.ws_session_connector import (- ConnectionType,SessionConnector,)from marimo._session.session import SessionImpl@@ -631,25 +630,27 @@ async def test_connections_share_starting_notebook(file_key=NEW_FILE,kiosk=False,auto_instantiate=False,- rtc_enabled=True,),connection=HTTPConnection({"type": "http", "query_string": b""}),)- first = asyncio.create_task(connector("first").connect())+ first_connector = connector("first")+ second_connector = connector("second")+ first = asyncio.create_task(first_connector.connect())try:await asyncio.wait_for(entered.wait(), 5)- second = asyncio.create_task(connector("second").connect())+ second = asyncio.create_task(second_connector.connect())# Scheduling the second connection before releasing preparation# exercises its decision against an initially empty repository.release.set()- assert await asyncio.wait_for(first, 5) == (- mock_session,- ConnectionType.NEW,+ await asyncio.wait_for(first, 5)+ await asyncio.wait_for(second, 5)+ mock_session.connect_consumer.assert_called_once_with(+ first_connector.handler, main=True)- assert await asyncio.wait_for(second, 5) == (- mock_session,- ConnectionType.RTC_EXISTING,+ first_connector.handler._write_kernel_ready.assert_called_once()+ second_connector.handler._connect_kiosk.assert_called_once_with(+ mock_session)assert launches == 1finally:@@ -678,7 +679,6 @@ async def test_refresh_reuses_pending_startup(ConnectionParams,)from marimo._server.api.endpoints.ws.ws_session_connector import (- ConnectionType,SessionConnector,)from marimo._session.session import SessionImpl@@ -725,7 +725,6 @@ async def test_refresh_reuses_pending_startup(file_key=NEW_FILE,kiosk=False,auto_instantiate=False,- rtc_enabled=False,),connection=HTTPConnection({"type": "http", "query_string": b""}),)@@ -770,10 +769,7 @@ async def test_refresh_reuses_pending_startup(],]release.set()- assert await asyncio.wait_for(next_connection, 5) == (- mock_session,- ConnectionType.NEW,- )+ await asyncio.wait_for(next_connection, 5)assert launches == 1assert (session_manager.get_session(SessionId(replacement_id))diff --git a/tests/_session/test_notification_ordering.py b/tests/_session/test_notification_ordering.pyindex d8e9619b09..2f482b3f89 100644--- a/tests/_session/test_notification_ordering.py+++ b/tests/_session/test_notification_ordering.py@@ -167,7 +167,6 @@ async def test_reconnect_snapshot_precedes_a_queued_live_update(connection=MagicMock(),notebook=None,bridge=MagicMock(),- doc_manager=MagicMock(),types=None,cursor=None,manager=MagicMock(mode=SessionMode.EDIT),@@ -176,7 +175,6 @@ async def test_reconnect_snapshot_precedes_a_queued_live_update(file_key="notebook.py",kiosk=False,auto_instantiate=False,- rtc_enabled=False,),)asyncio.get_running_loop().call_soon(diff --git a/tests/_utils/test_health_utils.py b/tests/_utils/test_health_utils.pyindex 5d3a9123d0..5c7a5fffa5 100644--- a/tests/_utils/test_health_utils.py+++ b/tests/_utils/test_health_utils.py@@ -47,22 +47,6 @@ def test_get_required_modules_list_excludes_psutil_when_unavailable() -> None:assert "psutil" not in modules-def test_get_optional_modules_list_excludes_loro_on_emscripten() -> None:- with patch(- "marimo._utils.health.is_pyodide",- return_value=True,- ):- modules = get_optional_modules_list()- assert "loro" not in modules---def test_get_optional_modules_list_excludes_loro_on_android() -> None:- with patch("marimo._utils.health.sys") as mock_sys:- mock_sys.platform = "android"- modules = get_optional_modules_list()- assert "loro" not in modules--def test_get_versions():assert isinstance(_get_versions([], False), dict)diff --git a/tests/snapshots/dependencies.txt b/tests/snapshots/dependencies.txtindex 94562f1c4d..ef718375c6 100644--- a/tests/snapshots/dependencies.txt+++ b/tests/snapshots/dependencies.txt@@ -2,7 +2,6 @@ click>=8.0,<9; sys_platform != 'emscripten'docutils>=0.16.0itsdangerous>=2.0.0jedi>=0.18.0,<0.21.0-loro>=1.10.0; python_version < '3.15' and sys_platform != 'emscripten' and sys_platform != 'android'markdown>=3.6,<4msgspec>=0.22.0narwhals>=2.0.0