Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: [rtc] edge cases for auto-run and focus (#4861)

Myles Scolnick35f44056f0b5
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index eefe7be23a..dfa6a7a11b 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -338,6 +338,10 @@ export interface CellHandle {
* The CodeMirror editor view.
*/
editorView: EditorView;
+ /**
+ * The CodeMirror editor view, or null if it is not yet mounted.
+ */
+ editorViewOrNull: EditorView | null;
}
export interface CellProps
@@ -418,6 +422,9 @@ const CellComponent = (
get editorView() {
return derefNotNull(editorView);
},
+ get editorViewOrNull() {
+ return editorView.current;
+ },
}),
[editorView],
);
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 2d83632923..2dc8ba357c 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -5,7 +5,6 @@ import { EditorView, ViewPlugin } from "@codemirror/view";
import React, { memo, useEffect, useRef, useMemo } from "react";
import { setupCodeMirror } from "@/core/codemirror/cm";
-import { getFeatureFlag } from "@/core/config/feature-flag";
import useEvent from "react-use-event-hook";
import { notebookAtom, useCellActions } from "@/core/cells/cells";
import type { CellRuntimeState, CellData } from "@/core/cells/types";
@@ -43,6 +42,7 @@ import { useDeleteCellCallback } from "../useDeleteCell";
import { useSaveNotebook } from "@/core/saving/save-component";
import { DelayMount } from "@/components/utils/delay-mount";
import { Button } from "@/components/ui/button";
+import { isRtcEnabled } from "@/core/rtc/state";
export interface CellEditorProps
extends Pick<CellRuntimeState, "status">,
@@ -239,7 +239,7 @@ const CellEditorInternal = ({
saveOrNameNotebook,
]);
- const rtcEnabled = getFeatureFlag("rtc_v2");
+ const rtcEnabled = isRtcEnabled();
const handleInitializeEditor = useEvent(() => {
// If rtc is enabled, use collaborative editing
if (rtcEnabled) {
@@ -365,8 +365,10 @@ const CellEditorInternal = ({
]);
// Auto-focus. Should focus newly created editors.
+ // We don't focus if RTC is enabled, since other players will be creating editors
const shouldFocus =
- editorViewRef.current === null || serializedEditorState !== null;
+ (editorViewRef.current === null || serializedEditorState !== null) &&
+ !isRtcEnabled();
useEffect(() => {
// Perf:
// We don't pass this in from the props since it causes lots of re-renders for unrelated cells
@@ -548,6 +550,6 @@ function WithWaitUntilConnected<T extends {}>(
return WaitUntilConnectedComponent;
}
-export const CellEditor = getFeatureFlag("rtc_v2")
+export const CellEditor = isRtcEnabled()
? WithWaitUntilConnected(memo(CellEditorInternal))
: memo(CellEditorInternal);
diff --git a/frontend/src/components/editor/cell/collapse.tsx b/frontend/src/components/editor/cell/collapse.tsx
index 37dc6d03fc..a48c52b594 100644
--- a/frontend/src/components/editor/cell/collapse.tsx
+++ b/frontend/src/components/editor/cell/collapse.tsx
@@ -33,7 +33,9 @@ export const CollapseToggle: React.FC<Props> = (props) => {
return (
<Button variant="text" size="icon" onClick={props.onClick}>
<Tooltip content={props.isCollapsed ? "Expand" : "Collapse"}>
- <Arrow isCollapsed={props.isCollapsed} />
+ <span>
+ <Arrow isCollapsed={props.isCollapsed} />
+ </span>
</Tooltip>
</Button>
);
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.tsx
index a1cd47b651..7cfc57c970 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer-items/rtc-status.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/rtc-status.tsx
@@ -5,7 +5,6 @@ import { useAtomValue, useAtom } from "jotai";
import { UsersIcon } from "lucide-react";
import type React from "react";
import { FooterItem } from "../footer-item";
-import { getFeatureFlag } from "@/core/config/feature-flag";
import {
Popover,
PopoverContent,
@@ -13,14 +12,14 @@ import {
} from "@/components/ui/popover";
import { Input } from "@/components/ui/input";
import { useState } from "react";
-import { usernameAtom } from "@/core/rtc/state";
+import { isRtcEnabled, usernameAtom } from "@/core/rtc/state";
export const RTCStatus: React.FC = () => {
const connectedDoc = useAtomValue(connectedDocAtom);
const [username, setUsername] = useAtom(usernameAtom);
const [open, setOpen] = useState(false);
- if (!getFeatureFlag("rtc_v2")) {
+ if (!isRtcEnabled()) {
return null;
}
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
index 61cc46a2eb..35e1a4a88b 100644
--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
@@ -142,7 +142,7 @@ export const MarimoErrorOutput = ({
if (syntaxErrors.length > 0 || unknownErrors.length > 0) {
messages.push(
- <li key="syntax-unknown">
+ <div key="syntax-unknown">
{syntaxErrors.map((error, idx) => (
<p key={`syntax-${idx}`}>{error.msg}</p>
))}
@@ -155,13 +155,13 @@ export const MarimoErrorOutput = ({
cellId={cellId}
/>
)}
- </li>,
+ </div>,
);
}
if (setupErrors.length > 0) {
messages.push(
- <li key="setup-refs">
+ <div key="setup-refs">
<p className="text-muted-foreground font-medium">
The setup cell cannot be run because it has references.
</p>
@@ -206,13 +206,13 @@ export const MarimoErrorOutput = ({
.
</p>
</Tip>
- </li>,
+ </div>,
);
}
if (cycleErrors.length > 0) {
messages.push(
- <li key="cycle">
+ <div key="cycle">
<p className="text-muted-foreground font-medium">
This cell is in a cycle.
</p>
@@ -255,13 +255,13 @@ export const MarimoErrorOutput = ({
.
</p>
</Tip>
- </li>,
+ </div>,
);
}
if (multipleDefsErrors.length > 0) {
messages.push(
- <li key="multiple-defs">
+ <div key="multiple-defs">
<p className="text-muted-foreground font-medium">
This cell redefines variables from other cells.
</p>
@@ -320,13 +320,13 @@ export const MarimoErrorOutput = ({
<span>to experiment without restrictions on variable names.</span>
</div>
</Tip>
- </li>,
+ </div>,
);
}
if (importStarErrors.length > 0) {
messages.push(
- <li key="import-star">
+ <div key="import-star">
{importStarErrors.map((error, idx) => (
<p key={`import-star-${idx}`} className="text-muted-foreground">
{error.msg}
@@ -361,13 +361,13 @@ export const MarimoErrorOutput = ({
.
</p>
</Tip>
- </li>,
+ </div>,
);
}
if (deleteNonlocalErrors.length > 0) {
messages.push(
- <li key="delete-nonlocal">
+ <div key="delete-nonlocal">
{deleteNonlocalErrors.map((error, idx) => (
<div key={`delete-nonlocal-${idx}`}>
{`The variable '${error.name}' can't be deleted because it was defined by another cell (`}
@@ -385,13 +385,13 @@ export const MarimoErrorOutput = ({
order. Try refactoring so that you can delete variables in the cells
that create them.
</Tip>
- </li>,
+ </div>,
);
}
if (interruptionErrors.length > 0) {
messages.push(
- <li key="interruption">
+ <div key="interruption">
{interruptionErrors.map((_, idx) => (
<p key={`interruption-${idx}`}>
{"This cell was interrupted and needs to be re-run."}
@@ -400,22 +400,22 @@ export const MarimoErrorOutput = ({
{cellId && (
<AutoFixButton errors={interruptionErrors} cellId={cellId} />
)}
- </li>,
+ </div>,
);
}
if (exceptionErrors.length > 0) {
messages.push(
- <li key="exception">
+ <div key="exception">
{exceptionErrors.map((error, idx) => (
<li className="my-2" key={`exception-${idx}`}>
{error.raising_cell == null ? (
- <li>
+ <div>
<p className="text-muted-foreground">{error.msg}</p>
<div className="text-muted-foreground mt-2">
See the console area for a traceback.
</div>
- </li>
+ </div>
) : (
<div>
{error.msg}
@@ -431,13 +431,13 @@ export const MarimoErrorOutput = ({
</Tip>
)}
{cellId && <AutoFixButton errors={exceptionErrors} cellId={cellId} />}
- </li>,
+ </div>,
);
}
if (strictExceptionErrors.length > 0) {
messages.push(
- <li key="strict-exception">
+ <div key="strict-exception">
{strictExceptionErrors.map((error, idx) => (
<li className="my-2" key={`strict-exception-${idx}`}>
{error.blamed_cell == null ? (
@@ -458,24 +458,24 @@ export const MarimoErrorOutput = ({
? "Ensure that the referenced cells define the required variables, or turn off strict execution."
: "Something is wrong with your declarations. Fix any discrepancies, or turn off strict execution."}
</Tip>
- </li>,
+ </div>,
);
}
if (internalErrors.length > 0) {
messages.push(
- <li key="internal">
+ <div key="internal">
{internalErrors.map((error, idx) => (
<p key={`internal-${idx}`}>{error.msg}</p>
))}
{cellId && <AutoFixButton errors={internalErrors} cellId={cellId} />}
- </li>,
+ </div>,
);
}
if (ancestorPreventedErrors.length > 0) {
messages.push(
- <li key="ancestor-prevented">
+ <div key="ancestor-prevented">
{ancestorPreventedErrors.map((error, idx) => (
<div key={`ancestor-prevented-${idx}`}>
{error.msg}
@@ -495,13 +495,13 @@ export const MarimoErrorOutput = ({
{cellId && (
<AutoFixButton errors={ancestorPreventedErrors} cellId={cellId} />
)}
- </li>,
+ </div>,
);
}
if (ancestorStoppedErrors.length > 0) {
messages.push(
- <li key="ancestor-stopped">
+ <div key="ancestor-stopped">
{ancestorStoppedErrors.map((error, idx) => (
<div key={`ancestor-stopped-${idx}`}>
{error.msg}
@@ -511,7 +511,7 @@ export const MarimoErrorOutput = ({
{cellId && (
<AutoFixButton errors={ancestorStoppedErrors} cellId={cellId} />
)}
- </li>,
+ </div>,
);
}
@@ -534,7 +534,7 @@ export const MarimoErrorOutput = ({
>
{title}
<div>
- <ul className="flex flex-col gap-8">{renderMessages()}</ul>
+ <div className="flex flex-col gap-8">{renderMessages()}</div>
</div>
</Alert>
);
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 5a0f044939..9f42cb0166 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -111,8 +111,10 @@ describe("cell reducer", () => {
state = reducer(state, action);
for (const [cellId, handle] of Object.entries(state.cellHandles)) {
if (!handle.current) {
+ const view = createEditor(state.cellData[cellId as CellId].code);
const handle: CellHandle = {
- editorView: createEditor(state.cellData[cellId as CellId].code),
+ editorView: view,
+ editorViewOrNull: view,
};
state.cellHandles[cellId as CellId] = { current: handle };
}
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 3f143ab996..5fb427510d 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -50,6 +50,7 @@ import {
import { isEqual, zip } from "lodash-es";
import { isErrorMime } from "../mime";
import { extractAllTracebackInfo, type TracebackInfo } from "@/utils/traceback";
+import { isRtcEnabled } from "../rtc/state";
export const SCRATCH_CELL_ID = "__scratch__" as CellId;
export const SETUP_CELL_ID = "setup" as CellId;
@@ -832,9 +833,12 @@ const {
}
// Update codemirror if mounted
- const cellHandle = nextState.cellHandles[cellId].current;
- if (cellHandle?.editorView) {
- updateEditorCodeFromPython(cellHandle.editorView, code);
+ // If RTC is enabled, the editor view will already be updated, so we don't need to do this
+ if (!isRtcEnabled()) {
+ const cellHandle = nextState.cellHandles[cellId].current;
+ if (cellHandle?.editorViewOrNull) {
+ updateEditorCodeFromPython(cellHandle.editorViewOrNull, code);
+ }
}
return {
@@ -1002,7 +1006,7 @@ const {
// browser fails to scrollIntoView an element at the end of a long page
if (index === column.length - 1) {
const cellId = column.last();
- state.cellHandles[cellId].current?.editorView.focus();
+ state.cellHandles[cellId].current?.editorViewOrNull?.focus();
} else {
const nextCellId = column.atOrThrow(index);
focusAndScrollCellIntoView({
diff --git a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts
index e66239edf2..0e39116c00 100644
--- a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts
+++ b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts
@@ -60,6 +60,7 @@ function createMockEditorView(code: string) {
return {
editorView: view,
+ editorViewOrNull: view,
};
}
diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.ts
index 071c9d3a6d..6b2d6b45f0 100644
--- a/frontend/src/core/codemirror/format.ts
+++ b/frontend/src/core/codemirror/format.ts
@@ -105,12 +105,15 @@ export async function formatSQL(editor: EditorView) {
});
// Update editor with formatted SQL
+ const doc = editor.state.doc;
+
+ // Noop if the code is the same
+ if (doc.toString() === formattedSQL) {
+ return;
+ }
+
editor.dispatch({
- changes: {
- from: 0,
- to: editor.state.doc.length,
- insert: formattedSQL,
- },
+ changes: { from: 0, to: doc.length, insert: formattedSQL },
effects: [formattingChangeEffect.of(true)],
});
}
diff --git a/frontend/src/core/codemirror/language/languages/markdown.ts b/frontend/src/core/codemirror/language/languages/markdown.ts
index 340ad15df3..e81beaf7fe 100644
--- a/frontend/src/core/codemirror/language/languages/markdown.ts
+++ b/frontend/src/core/codemirror/language/languages/markdown.ts
@@ -25,7 +25,7 @@ import { parsePython } from "../embedded/embedded-python";
import { conditionalCompletion } from "../../completion/utils";
import { pythonCompletionSource } from "../../completion/completer";
import { markdownCompletionSources } from "../../markdown/completions";
-import { ViewPlugin } from "@codemirror/view";
+import { type EditorView, ViewPlugin } from "@codemirror/view";
import { languageMetadataField } from "../metadata";
export interface MarkdownLanguageAdapterMetadata {
@@ -204,19 +204,20 @@ export class MarkdownLanguageAdapter
_: PlaceholderType,
): Extension[] {
const markdownLanguageData = markdown().language.data;
+ let view: EditorView | undefined;
// Only activate completions for f-strings
- let isFStringActive = () => false;
+ const isFStringActive = () => {
+ const metadata = view?.state.field(languageMetadataField);
+ if (metadata === undefined) {
+ return false;
+ }
+ return metadata.quotePrefix?.includes("f") ?? false;
+ };
return [
- ViewPlugin.define((view) => {
- isFStringActive = () => {
- const metadata = view.state.field(languageMetadataField);
- if (metadata === undefined) {
- return false;
- }
- return metadata.quotePrefix?.includes("f") ?? false;
- };
+ ViewPlugin.define((_view) => {
+ view = _view;
return {};
}),
markdown({
diff --git a/frontend/src/core/codemirror/language/panel/panel.tsx b/frontend/src/core/codemirror/language/panel/panel.tsx
index 61fd8322b9..022c89a0db 100644
--- a/frontend/src/core/codemirror/language/panel/panel.tsx
+++ b/frontend/src/core/codemirror/language/panel/panel.tsx
@@ -123,7 +123,13 @@ export const LanguagePanelComponent: React.FC<{
type Metadata = LanguageMetadataOf<MarkdownLanguageAdapter>;
const metadata = view.state.field(languageMetadataField) as Metadata;
- const { quotePrefix } = metadata;
+ let { quotePrefix } = metadata;
+
+ // Handle the case where the quote prefix is not set
+ if (quotePrefix === undefined) {
+ quotePrefix = "r";
+ triggerUpdate<Metadata>({ quotePrefix });
+ }
const togglePrefix = (
prefix: QuotePrefixKind,
diff --git a/frontend/src/core/codemirror/language/utils.ts b/frontend/src/core/codemirror/language/utils.ts
index 8221766c67..dd082f069f 100644
--- a/frontend/src/core/codemirror/language/utils.ts
+++ b/frontend/src/core/codemirror/language/utils.ts
@@ -32,15 +32,16 @@ export function getEditorCodeAsPython(
export function updateEditorCodeFromPython(
editor: EditorView,
pythonCode: string,
-) {
+): string {
const languageAdapter = editor.state.field(languageAdapterState);
const [code] = languageAdapter.transformIn(pythonCode);
+ const doc = editor.state.doc;
+ // Noop if the code is the same
+ if (doc.toString() === code) {
+ return code;
+ }
editor.dispatch({
- changes: {
- from: 0,
- to: editor.state.doc.length,
- insert: code,
- },
+ changes: { from: 0, to: doc.length, insert: code },
});
return code;
}
diff --git a/frontend/src/core/codemirror/placeholder/extensions.ts b/frontend/src/core/codemirror/placeholder/extensions.ts
index 7b252c5151..01287c8f44 100644
--- a/frontend/src/core/codemirror/placeholder/extensions.ts
+++ b/frontend/src/core/codemirror/placeholder/extensions.ts
@@ -26,19 +26,17 @@ export function smartPlaceholderExtension(text: string): Extension[] {
function acceptPlaceholder(cm: EditorView, text: string) {
// if empty, insert the placeholder
- if (cm.state.doc.length === 0) {
+ const docLength = cm.state.doc.length;
+ if (docLength === 0) {
cm.dispatch({
changes: {
from: 0,
- to: cm.state.doc.length,
+ to: docLength,
insert: text,
},
- });
- // move cursor to end of placeholder
- cm.dispatch({
selection: {
- anchor: cm.state.doc.length,
- head: cm.state.doc.length,
+ head: text.length,
+ anchor: text.length,
},
});
return true;
diff --git a/frontend/src/core/codemirror/rtc/extension.ts b/frontend/src/core/codemirror/rtc/extension.ts
index 905db8dbf7..6d0802223a 100644
--- a/frontend/src/core/codemirror/rtc/extension.ts
+++ b/frontend/src/core/codemirror/rtc/extension.ts
@@ -28,9 +28,8 @@ import { createSelectionLayer } from "./loro/awareness";
import { createCursorLayer } from "./loro/awareness";
import { remoteAwarenessStateField } from "./loro/awareness";
import type { UserState } from "./loro/awareness";
-import { getFeatureFlag } from "@/core/config/feature-flag";
import { initialMode } from "@/core/mode";
-import { usernameAtom } from "@/core/rtc/state";
+import { isRtcEnabled, usernameAtom } from "@/core/rtc/state";
import { getColor } from "./loro/colors";
import {
languageMetadataField,
@@ -138,8 +137,8 @@ const getWs = once(() => {
return ws;
});
-// Kick off the connection for edit mode
-if (getFeatureFlag("rtc_v2") && initialMode === "edit") {
+// Kickoff the WS connection for edit mode
+if (isRtcEnabled() && initialMode === "edit") {
getWs();
}
@@ -182,22 +181,22 @@ export function realTimeCollaboration(
loroText.insert(0, initialCode);
}
- const userName = store.get(usernameAtom) || "Anonymous";
+ 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,
- {
- name: userName,
- colorClassName: getColor(userName),
- },
- () => loroText,
- cellId,
- ),
+ loroAwarenessPlugin(doc, awareness, userState, () => loroText, cellId),
loroSyncPlugin(doc, ["codes", cellId], () => {
return loroText;
}),
diff --git a/frontend/src/core/rtc/state.ts b/frontend/src/core/rtc/state.ts
index c53f6cdfad..d2d5cd2a8f 100644
--- a/frontend/src/core/rtc/state.ts
+++ b/frontend/src/core/rtc/state.ts
@@ -1,8 +1,16 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { atomWithStorage } from "jotai/utils";
+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", "");
+
+/**
+ * Whether RTC is enabled.
+ */
+export function isRtcEnabled() {
+ return getFeatureFlag("rtc_v2");
+}
diff --git a/frontend/src/plugins/core/RenderHTML.tsx b/frontend/src/plugins/core/RenderHTML.tsx
index 0fe08edd6b..0e85bffddc 100644
--- a/frontend/src/plugins/core/RenderHTML.tsx
+++ b/frontend/src/plugins/core/RenderHTML.tsx
@@ -67,13 +67,14 @@ const replaceSrcScripts = (domNode: DOMNode): JSX.Element | undefined => {
const addCopyButtonToCodehilite: TransformFn = (
reactNode: ReactNode,
domNode: DOMNode,
+ index: number,
): JSX.Element | undefined => {
if (
domNode instanceof Element &&
domNode.name === "div" &&
domNode.attribs?.class?.includes("codehilite")
) {
- return <CopyableCode>{reactNode}</CopyableCode>;
+ return <CopyableCode key={index}>{reactNode}</CopyableCode>;
}
};
diff --git a/frontend/src/utils/__tests__/createReducer.test.ts b/frontend/src/utils/__tests__/createReducer.test.ts
index 69c2dec29b..8d9d1c6607 100644
--- a/frontend/src/utils/__tests__/createReducer.test.ts
+++ b/frontend/src/utils/__tests__/createReducer.test.ts
@@ -138,4 +138,47 @@ describe("createReducerAndAtoms", () => {
expect(middleware).toHaveBeenCalledWith(state, { count: 5 }, action);
});
+
+ it("should log an error for non-existent action types", () => {
+ const initialState = () => ({ count: 0 });
+ const reducers = {
+ increment: (state: State, payload: number) => ({
+ count: state.count + payload,
+ }),
+ };
+ const loggerSpy = vi.spyOn(Logger, "error");
+
+ const { reducer } = createReducerAndAtoms(initialState, reducers);
+ const state = { count: 0 };
+ const newState = reducer(state, { type: "nonexistent", payload: null });
+
+ expect(newState).toBe(state);
+ expect(loggerSpy).toHaveBeenCalledWith(
+ "Action type nonexistent is not defined in reducers.",
+ );
+ });
+
+ it("should handle errors thrown by actions", () => {
+ const initialState = () => ({ count: 0 });
+ const errorMessage = "Test error in reducer";
+ const reducers = {
+ buggyAction: () => {
+ throw new Error(errorMessage);
+ },
+ };
+ const originalLoggerError = Logger.error;
+ Logger.error = vi.fn();
+
+ const { reducer } = createReducerAndAtoms(initialState, reducers);
+ const state = { count: 0 };
+ const newState = reducer(state, { type: "buggyAction", payload: null });
+
+ expect(newState).toBe(state);
+ expect(Logger.error).toHaveBeenCalledWith(
+ "Error in reducer for action buggyAction:",
+ expect.any(Error),
+ );
+
+ Logger.error = originalLoggerError;
+ });
});
diff --git a/frontend/src/utils/createReducer.ts b/frontend/src/utils/createReducer.ts
index b83bcf37ce..62a2440d21 100644
--- a/frontend/src/utils/createReducer.ts
+++ b/frontend/src/utils/createReducer.ts
@@ -86,13 +86,25 @@ export function createReducerAndAtoms<
const { reducer, createActions } = createReducer(initialState, reducers);
const reducerWithMiddleware = (state: State, action: ReducerAction<any>) => {
- const newState = reducer(state, action);
- if (middleware) {
- for (const mw of middleware) {
- mw(state, newState, action);
+ try {
+ const newState = reducer(state, action);
+ if (middleware) {
+ for (const mw of middleware) {
+ try {
+ mw(state, newState, action);
+ } catch (error) {
+ Logger.error(
+ `Error in middleware for action ${action.type}:`,
+ error,
+ );
+ }
+ }
}
+ return newState;
+ } catch (error) {
+ Logger.error(`Error in reducer for action ${action.type}:`, error);
+ return state;
}
- return newState;
};
const valueAtom = atom(initialState());
diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.py
index 7ae8bb0c38..cc8b4afff1 100644
--- a/marimo/_server/api/deps.py
+++ b/marimo/_server/api/deps.py
@@ -131,9 +131,17 @@ class AppState(AppStateBase):
session = self.session_manager.get_session(session_id)
if session is None:
LOGGER.warning(
- "Valid sessions: %s",
+ "Valid sessions ids: %s",
list(self.session_manager.sessions.keys()),
)
+ LOGGER.warning(
+ "Valid consumers ids: %s",
+ [
+ list(session.room.consumers.values())
+ for session in self.session_manager.sessions.values()
+ if session.room.consumers
+ ],
+ )
raise ValueError(f"Invalid session id: {session_id}")
return session
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index cc8f63e126..fabb18e0b1 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -266,12 +266,14 @@ 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()
session_manager.close_session(session_id)
# Close RTC doc if it exists
file_key: Optional[MarimoFileKey] = (
app_state.query_params(FILE_QUERY_PARAM_KEY)
or session_manager.file_router.get_unique_file_key()
+ or session.app_file_manager.path
)
if file_key is not None:
await DOC_MANAGER.remove_doc(file_key)
diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.py
index 02d126eb16..0ade6c0351 100644
--- a/marimo/_server/api/endpoints/ws.py
+++ b/marimo/_server/api/endpoints/ws.py
@@ -152,16 +152,19 @@ async def ws_sync(
await websocket.accept()
# Get or create the LoroDoc and add the client to it
+ LOGGER.debug("RTC: getting document")
update_queue = asyncio.Queue[bytes]()
doc = await DOC_MANAGER.get_or_create_doc(file_key)
DOC_MANAGER.add_client_to_doc(file_key, update_queue)
# Send initial sync
# Use shallow snapshot for fewer bytes
+ LOGGER.debug("RTC: sending initial sync")
init_sync_msg = doc.export(
ExportMode.ShallowSnapshot(frontiers=doc.state_frontiers)
)
await websocket.send_bytes(init_sync_msg)
+ LOGGER.debug("RTC: initial sync sent")
def handle_doc_update(event: DiffEvent) -> None:
LOGGER.debug("RTC: doc updated", event)
@@ -193,7 +196,7 @@ async def ws_sync(
# Apply the update to the LoroDoc
doc.import_(message)
except WebSocketDisconnect:
- LOGGER.warning("RTC: WebSocket disconnected")
+ LOGGER.debug("RTC: WebSocket disconnected")
# Normal disconnection
pass
except Exception as e:
@@ -201,7 +204,7 @@ async def ws_sync(
f"RTC: Exception in websocket loop for file {file_key}: {str(e)}"
)
finally:
- LOGGER.warning("RTC: Cleaning up resources")
+ LOGGER.debug("RTC: Cleaning up resources")
# Cleanup resources
send_task.cancel()
subscription.unsubscribe()
@@ -296,15 +299,11 @@ class WebsocketHandler(SessionConsumer):
"RTC: Loro is not installed, disabling real-time collaboration"
)
self.rtc_enabled = False
- return
-
- async def init_loro_doc() -> None:
- await DOC_MANAGER.create_doc(
- self.file_key, cell_ids, codes
+ else:
+ asyncio.create_task(
+ DOC_MANAGER.create_doc(self.file_key, cell_ids, codes)
)
- asyncio.create_task(init_loro_doc())
-
else:
codes, names, configs, cell_ids = tuple(
zip(
diff --git a/marimo/_server/print.py b/marimo/_server/print.py
index 28663b4430..4633dcbfe2 100644
--- a/marimo/_server/print.py
+++ b/marimo/_server/print.py
@@ -64,10 +64,30 @@ def _get_network_url(url: str) -> str:
hostname = socket.gethostname()
try:
- local_ip = socket.gethostbyname(hostname)
+ # Find a non-loopback IPv4 address
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ # Doesn't need to be reachable
+ s.connect(("255.255.255.254", 1))
+ local_ip = s.getsockname()[0]
+ s.close()
except Exception:
- # Fallback to hostname if we can't get network address
- local_ip = hostname
+ try:
+ # Get all IPs for the hostname
+ all_ips = socket.getaddrinfo(hostname, None)
+ # Filter for IPv4 addresses that aren't loopback
+ for ip_info in all_ips:
+ family, _, _, _, addr = ip_info
+ if family == socket.AF_INET and not str(addr[0]).startswith(
+ "127."
+ ):
+ local_ip = addr[0]
+ break
+ else:
+ # If no suitable IP found, fall back to hostname
+ local_ip = hostname
+ except Exception:
+ # Final fallback to hostname
+ local_ip = hostname
# Replace the host part of the URL with the local IP
from urllib.parse import urlparse, urlunparse
diff --git a/marimo/_server/rtc/doc.py b/marimo/_server/rtc/doc.py
index 8eadbc4182..4e5b08bdc0 100644
--- a/marimo/_server/rtc/doc.py
+++ b/marimo/_server/rtc/doc.py
@@ -143,9 +143,16 @@ class LoroDocManager:
cleaner.cancel()
self.loro_docs_cleaners[file_key] = None
# Create a new cleaner with timeout of 60 seconds
- self.loro_docs_cleaners[file_key] = asyncio.create_task(
- self._clean_loro_doc(file_key, 60.0)
- )
+ self.loro_docs_cleaners[file_key] = None
+
+ # Create the cleaner task outside the lock
+ if (
+ file_key in self.loro_docs_clients
+ and len(self.loro_docs_clients[file_key]) == 0
+ ):
+ self.loro_docs_cleaners[file_key] = asyncio.create_task(
+ self._clean_loro_doc(file_key, 60.0)
+ )
async def remove_doc(self, file_key: MarimoFileKey) -> None:
"""Remove a loro doc and all associated clients, without waiting."""
diff --git a/tests/_server/api/endpoints/test_ws_rtc.py b/tests/_server/api/endpoints/test_ws_rtc.py
index 1d99fd3e8d..380b8df443 100644
--- a/tests/_server/api/endpoints/test_ws_rtc.py
+++ b/tests/_server/api/endpoints/test_ws_rtc.py
@@ -3,16 +3,13 @@ from __future__ import annotations
import asyncio
from contextlib import contextmanager
from dataclasses import asdict
-from typing import TYPE_CHECKING, Any, Optional, cast
+from typing import TYPE_CHECKING, Any, Optional
import pytest
-from loro import LoroDoc, LoroText
from marimo._config.manager import UserConfigManager
from marimo._messaging.ops import KernelCapabilities, KernelReady
from marimo._server.api.endpoints.ws import DOC_MANAGER
-from marimo._server.file_router import MarimoFileKey
-from marimo._types.ids import CellId_t
from marimo._utils.parse_dataclass import parse_raw
from tests._server.conftest import get_session_manager, get_user_config_manager
from tests._server.mocks import token_header
@@ -94,86 +91,6 @@ async def setup_loro_docs() -> AsyncGenerator[None, None]:
DOC_MANAGER.loro_docs_cleaners.clear()
-async def test_quick_reconnection(setup_loro_docs: None) -> None:
- """Test that quick reconnection properly handles cleanup task cancellation"""
- del setup_loro_docs
- # 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
-
-
-async def test_two_users_sync(setup_loro_docs: None) -> None:
- """Test that two users can connect and sync text properly without duplicates"""
- del setup_loro_docs
- 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"
-
-
@contextmanager
def rtc_enabled(config: UserConfigManager):
prev_config = config.get_config()
diff --git a/tests/_server/rtc/test_rtc_doc.py b/tests/_server/rtc/test_rtc_doc.py
new file mode 100644
index 0000000000..c5136430f6
--- /dev/null
+++ b/tests/_server/rtc/test_rtc_doc.py
@@ -0,0 +1,242 @@
+import asyncio
+from collections.abc import AsyncGenerator
+from typing import cast
+
+import pytest
+from loro import LoroDoc, LoroText
+
+from marimo._server.file_router import MarimoFileKey
+from marimo._server.rtc.doc import LoroDocManager
+from marimo._types.ids import CellId_t
+
+doc_manager = LoroDocManager()
+
+
[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()
+
+
+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
+
+
+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"
+
+
+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
+
+
+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
+
+
+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)
+
+
+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
+
+
+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
+
+
+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
+
+
+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
diff --git a/tests/_server/test_print.py b/tests/_server/test_print.py
index b9e3a484f6..bb67721c02 100644
--- a/tests/_server/test_print.py
+++ b/tests/_server/test_print.py
@@ -45,21 +45,39 @@ def test_colorized_url() -> None:
def test_get_network_url() -> None:
"""Test the _get_network_url function."""
- # Test with a simple URL
- with patch("socket.gethostname") as mock_gethostname:
- mock_gethostname.return_value = "test-host"
- with patch("socket.gethostbyname") as mock_gethostbyname:
- mock_gethostbyname.return_value = "192.168.1.100"
- result = _get_network_url("http://localhost:8000")
- assert result == "http://192.168.1.100:8000"
-
- # Test with socket.gethostbyname raising an exception
- with patch("socket.gethostname") as mock_gethostname:
- mock_gethostname.return_value = "test-host"
- with patch("socket.gethostbyname") as mock_gethostbyname:
- mock_gethostbyname.side_effect = Exception("Test exception")
- result = _get_network_url("http://localhost:8000")
- assert result == "http://test-host:8000"
+ # Test with a simple URL using socket connection method
+ with patch("socket.socket") as mock_socket:
+ mock_socket_instance = mock_socket.return_value
+ mock_socket_instance.getsockname.return_value = ("192.168.1.100", 0)
+ result = _get_network_url("http://localhost:8000")
+ assert result == "http://192.168.1.100:8000"
+
+ # Test with socket connection failing, falling back to getaddrinfo
+ with patch("socket.socket") as mock_socket:
+ mock_socket.return_value.connect.side_effect = Exception(
+ "Test exception"
+ )
+ with patch("socket.gethostname") as mock_gethostname:
+ mock_gethostname.return_value = "test-host"
+ with patch("socket.getaddrinfo") as mock_getaddrinfo:
+ mock_getaddrinfo.return_value = [
+ (2, 1, 6, "", ("192.168.1.100", 0)),
+ (2, 1, 6, "", ("127.0.0.1", 0)),
+ ]
+ result = _get_network_url("http://localhost:8000")
+ assert result == "http://192.168.1.100:8000"
+
+ # Test with both socket and getaddrinfo failing
+ with patch("socket.socket") as mock_socket:
+ mock_socket.return_value.connect.side_effect = Exception(
+ "Test exception"
+ )
+ with patch("socket.gethostname") as mock_gethostname:
+ mock_gethostname.return_value = "test-host"
+ with patch("socket.getaddrinfo") as mock_getaddrinfo:
+ mock_getaddrinfo.side_effect = Exception("Test exception")
+ result = _get_network_url("http://localhost:8000")
+ assert result == "http://test-host:8000"
def test_print_startup() -> None: