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
[rtc] awareness (#4839)
Myles Scolnick4df3636ce27a
diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsxindex 148f7c9068..af517c5540 100644--- a/frontend/src/components/editor/ai/ai-completion-editor.tsx+++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx@@ -124,15 +124,10 @@ export const AiCompletionEditor: React.FC<Props> = ({const { theme } = useTheme();return (- <div- className={cn(- "flex flex-col w-full rounded-[inherit] overflow-hidden",- className,- )}- >+ <div className={cn("flex flex-col w-full rounded-[inherit]", className)}><divclassName={cn(- "flex items-center gap-2 border-b px-3 transition-all rounded-[inherit] rounded-b-none duration-300 overflow-hidden",+ "flex items-center gap-2 border-b px-3 transition-all rounded-[inherit] rounded-b-none duration-300",enabled && "max-h-[400px] min-h-11 visible",!enabled && "max-h-0 min-h-0 invisible",)}diff --git a/frontend/src/components/editor/chrome/wrapper/footer-item.tsx b/frontend/src/components/editor/chrome/wrapper/footer-item.tsxindex 77b00f2370..4c3c9b2ad3 100644--- a/frontend/src/components/editor/chrome/wrapper/footer-item.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer-item.tsx@@ -2,18 +2,20 @@import { Tooltip } from "@/components/ui/tooltip";import { cn } from "@/utils/cn";import type React from "react";-import type { PropsWithChildren } from "react";+import { forwardRef } from "react";-export const FooterItem: React.FC<- PropsWithChildren<- {- selected: boolean;- tooltip: React.ReactNode;- } & React.HTMLAttributes<HTMLDivElement>- >-> = ({ children, tooltip, selected, className, ...rest }) => {+type FooterItemProps = {+ selected: boolean;+ tooltip: React.ReactNode;+} & React.HTMLAttributes<HTMLDivElement>;++export const FooterItem: React.FC<FooterItemProps> = forwardRef<+ HTMLDivElement,+ FooterItemProps+>(({ children, tooltip, selected, className, ...rest }, ref) => {const content = (<div+ ref={ref}className={cn("h-full flex items-center p-2 text-sm shadow-inset font-mono cursor-pointer rounded",!selected && "hover:bg-[var(--sage-3)]",@@ -35,4 +37,6 @@ export const FooterItem: React.FC<}return content;-};+});++FooterItem.displayName = "FooterItem";diff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/ai-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/ai-status.tsxnew file mode 100644index 0000000000..cabee41fb2--- /dev/null+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/ai-status.tsx@@ -0,0 +1,40 @@+/* Copyright 2024 Marimo. All rights reserved. */+import React from "react";+import { useAtomValue } from "jotai";+import { aiAtom, aiEnabledAtom } from "@/core/config/config";+import { SparklesIcon } from "lucide-react";+import { FooterItem } from "../footer-item";+import { useOpenSettingsToTab } from "@/components/app-config/state";++export const AIStatusIcon: React.FC = () => {+ const ai = useAtomValue(aiAtom);+ const aiEnabled = useAtomValue(aiEnabledAtom);+ const model = ai?.open_ai?.model || "gpt-4-turbo";+ const { handleClick } = useOpenSettingsToTab();++ if (!aiEnabled) {+ return (+ <FooterItem+ tooltip="Assist is disabled"+ selected={false}+ onClick={() => handleClick("ai")}+ >+ <SparklesIcon className="h-4 w-4 opacity-60" />+ </FooterItem>+ );+ }++ return (+ <FooterItem+ tooltip={+ <>+ <b>Assist model:</b> {model}+ </>+ }+ onClick={() => handleClick("ai")}+ selected={false}+ >+ <SparklesIcon className="h-4 w-4" />+ </FooterItem>+ );+};diff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsxnew file mode 100644index 0000000000..eeaef6922b--- /dev/null+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/backend-status.tsx@@ -0,0 +1,30 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { Spinner } from "@/components/icons/spinner";+import { Tooltip } from "@/components/ui/tooltip";+import { connectionAtom } from "@/core/network/connection";+import { WebSocketState } from "@/core/websocket/types";+import { useAtomValue } from "jotai";+import { startCase } from "lodash-es";+import { CheckCircle2Icon, PowerOffIcon } from "lucide-react";+import type React from "react";++export const BackendConnection: React.FC = () => {+ const connection = useAtomValue(connectionAtom).state;++ return (+ <Tooltip delayDuration={200} content={startCase(connection.toLowerCase())}>+ <div className="px-2">+ {connection === WebSocketState.OPEN && (+ <CheckCircle2Icon className="w-4 h-4" />+ )}+ {connection === WebSocketState.CLOSED && (+ <PowerOffIcon className="w-4 h-4" />+ )}+ {connection === WebSocketState.CONNECTING && <Spinner size="small" />}+ {connection === WebSocketState.CLOSING && (+ <Spinner className="text-destructive" size="small" />+ )}+ </div>+ </Tooltip>+ );+};diff --git a/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/copilot-status.tsxsimilarity index 78%rename from frontend/src/components/editor/chrome/wrapper/copilot-status.tsxrename to frontend/src/components/editor/chrome/wrapper/footer-items/copilot-status.tsxindex 7a8674f5e3..078c63cb40 100644--- a/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/copilot-status.tsx@@ -8,14 +8,9 @@ import {copilotSignedInState,} from "@/core/codemirror/copilot/state";import { atom, useAtomValue, useSetAtom } from "jotai";-import {- aiAtom,- aiEnabledAtom,- resolvedMarimoConfigAtom,-} from "@/core/config/config";+import { resolvedMarimoConfigAtom } from "@/core/config/config";import { GitHubCopilotIcon } from "@/components/icons/github-copilot";-import { SparklesIcon } from "lucide-react";-import { FooterItem } from "./footer-item";+import { FooterItem } from "../footer-item";import { toast } from "@/components/ui/use-toast";import { getCopilotClient } from "@/core/codemirror/copilot/client";import { Logger } from "@/utils/Logger";@@ -23,39 +18,6 @@ import { Button } from "@/components/ui/button";import { useOnMount } from "@/hooks/useLifecycle";import { useOpenSettingsToTab } from "@/components/app-config/state";-export const AIStatusIcon: React.FC = () => {- const ai = useAtomValue(aiAtom);- const aiEnabled = useAtomValue(aiEnabledAtom);- const model = ai?.open_ai?.model || "gpt-4-turbo";- const { handleClick } = useOpenSettingsToTab();-- if (!aiEnabled) {- return (- <FooterItem- tooltip="Assist is disabled"- selected={false}- onClick={() => handleClick("ai")}- >- <SparklesIcon className="h-4 w-4 opacity-60" />- </FooterItem>- );- }-- return (- <FooterItem- tooltip={- <>- <b>Assist model:</b> {model}- </>- }- onClick={() => handleClick("ai")}- selected={false}- >- <SparklesIcon className="h-4 w-4" />- </FooterItem>- );-};-const copilotAtom = atom((get) => {return get(resolvedMarimoConfigAtom).completion.copilot;});diff --git a/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/machine-stats.tsxsimilarity index 80%rename from frontend/src/components/editor/chrome/wrapper/machine-stats.tsxrename to frontend/src/components/editor/chrome/wrapper/footer-items/machine-stats.tsxindex c2765f1598..09592609f4 100644--- a/frontend/src/components/editor/chrome/wrapper/machine-stats.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/machine-stats.tsx@@ -1,5 +1,4 @@/* Copyright 2024 Marimo. All rights reserved. */-import { Spinner } from "@/components/icons/spinner";import { Tooltip } from "@/components/ui/tooltip";import { connectionAtom } from "@/core/network/connection";import { getUsageStats } from "@/core/network/requests";@@ -9,17 +8,9 @@ import { WebSocketState } from "@/core/websocket/types";import { useAsyncData } from "@/hooks/useAsyncData";import { useInterval } from "@/hooks/useInterval";import { useAtomValue } from "jotai";-import { startCase } from "lodash-es";-import {- CheckCircle2Icon,- CpuIcon,- MemoryStickIcon,- MicrochipIcon,- PowerOffIcon,-} from "lucide-react";+import { CpuIcon, MemoryStickIcon, MicrochipIcon } from "lucide-react";import type React from "react";import { useState } from "react";-import { AIStatusIcon, CopilotStatusIcon } from "./copilot-status";import { cn } from "@/utils/cn";export const MachineStats: React.FC = (props) => {@@ -42,7 +33,7 @@ export const MachineStats: React.FC = (props) => {}, [nonce, connection.state]);return (- <div className="flex gap-2 items-center">+ <div className="flex gap-2 items-center px-1">{data?.gpu && data.gpu.length > 0 && <GPUBar gpus={data.gpu} />}{data && (<MemoryUsageBar@@ -52,36 +43,10 @@ export const MachineStats: React.FC = (props) => {/>)}{data && <CPUBar cpu={data.cpu} />}- <div className="flex items-center">- <AIStatusIcon />- <CopilotStatusIcon />- </div>- <BackendConnection connection={connection.state} /></div>);};-const BackendConnection: React.FC<{ connection: WebSocketState }> = ({- connection,-}) => {- return (- <Tooltip delayDuration={200} content={startCase(connection.toLowerCase())}>- <div>- {connection === WebSocketState.OPEN && (- <CheckCircle2Icon className="w-4 h-4" />- )}- {connection === WebSocketState.CLOSED && (- <PowerOffIcon className="w-4 h-4" />- )}- {connection === WebSocketState.CONNECTING && <Spinner size="small" />}- {connection === WebSocketState.CLOSING && (- <Spinner className="text-destructive" size="small" />- )}- </div>- </Tooltip>- );-};-const MemoryUsageBar: React.FC<{memory: UsageResponse["memory"];kernel: UsageResponse["kernel"];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.tsxnew file mode 100644index 0000000000..a1cd47b651--- /dev/null+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/rtc-status.tsx@@ -0,0 +1,62 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { connectedDocAtom } from "@/core/codemirror/rtc/extension";+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,+ PopoverTrigger,+} from "@/components/ui/popover";+import { Input } from "@/components/ui/input";+import { useState } from "react";+import { 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")) {+ 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}>+ <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 eed46d62d3..ab9f35ceec 100644--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx@@ -6,7 +6,7 @@ import { Tooltip } from "@/components/ui/tooltip";import { useAtomValue } from "jotai";import { cellErrorCount } from "@/core/cells/cells";import { type PanelDescriptor, PANELS } from "../types";-import { MachineStats } from "./machine-stats";+import { MachineStats } from "./footer-items/machine-stats";import { useResolvedMarimoConfig } from "@/core/config/config";import {PowerOffIcon,@@ -29,6 +29,10 @@ import { ChevronDownIcon } from "lucide-react";import { FooterItem } from "./footer-item";import { useHotkey } from "@/hooks/useHotkey";import { isWasm } from "@/core/wasm/utils";+import { AIStatusIcon } from "./footer-items/ai-status";+import { BackendConnection } from "./footer-items/backend-status";+import { CopilotStatusIcon } from "./footer-items/copilot-status";+import { RTCStatus } from "./footer-items/rtc-status";export const Footer: React.FC = () => {const { selectedPanel, isTerminalOpen } = useChromeState();@@ -48,7 +52,7 @@ export const Footer: React.FC = () => {});return (- <footer className="h-10 py-2 bg-background flex items-center text-muted-foreground text-md pl-1 pr-4 border-t border-border select-none no-print text-sm shadow-[0_0_4px_1px_rgba(0,0,0,0.1)] z-50 print:hidden hide-on-fullscreen">+ <footer className="h-10 py-2 bg-background flex items-center text-muted-foreground text-md px-1 border-t border-border select-none no-print text-sm shadow-[0_0_4px_1px_rgba(0,0,0,0.1)] z-50 print:hidden hide-on-fullscreen"><FooterItemtooltip={errorPanel.tooltip}selected={selectedPanel === errorPanel.type}@@ -209,7 +213,13 @@ export const Footer: React.FC = () => {</Tooltip></ShowInKioskMode>- <MachineStats />+ <div className="flex items-center">+ <MachineStats />+ <AIStatusIcon />+ <CopilotStatusIcon />+ <RTCStatus />+ <BackendConnection />+ </div></footer>);};diff --git a/frontend/src/core/codemirror/rtc/extension.ts b/frontend/src/core/codemirror/rtc/extension.tsindex 86588d7a2d..12b3311b31 100644--- a/frontend/src/core/codemirror/rtc/extension.ts+++ b/frontend/src/core/codemirror/rtc/extension.ts@@ -8,7 +8,7 @@ import ReconnectingWebSocket from "partysocket/ws";import { createWsUrl } from "@/core/websocket/createWsUrl";import { getSessionId } from "@/core/kernel/session";import { once } from "@/utils/once";-import { LoroSyncPlugin } from "./loro/sync";+import { loroSyncPlugin } from "./loro/sync";import { EditorView, ViewPlugin } from "@codemirror/view";import {getInitialLanguageAdapter,@@ -21,9 +21,36 @@ import type { LanguageAdapterType } from "../language/types";import { atom } from "jotai";import { waitForConnectionOpen } from "@/core/network/connection";import { store } from "@/core/state/jotai";+import { Logger } from "@/utils/Logger";+import { loroCursorTheme, RemoteAwarenessPlugin } from "./loro/awareness";+import type { AwarenessState, ScopeId, Uid } from "./loro/awareness";+import { AwarenessPlugin } from "./loro/awareness";+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 { Logger } from "@/utils/Logger";+import { usernameAtom } from "@/core/rtc/state";+import { getColor } from "./loro/colors";++const AWARENESS_PREFIX = "awareness:";++// Utility functions for message handling+function prefixMessage(token: string, message: Uint8Array): Uint8Array {+ 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,@@ -31,7 +58,7 @@ export const connectedDocAtom = atom<LoroDoc | "disabled" | undefined>(// Create a Loro documentconst doc = new LoroDoc();-const awareness: Awareness = new Awareness(doc.peerIdStr);+const awareness = new Awareness<AwarenessState>(doc.peerIdStr);// const undoManager = new UndoManager(doc, {});// Create a websocket connection to the server@@ -63,7 +90,18 @@ const getWs = once(() => {ws.addEventListener("message", async (event) => {const blob: Blob = event.data;const bytes = await blob.arrayBuffer();- doc.import(new Uint8Array(bytes));+ const data = new Uint8Array(bytes);++ // Handle awareness update+ if (hasPrefix(data, AWARENESS_PREFIX)) {+ const awarenessData = removePrefix(data, AWARENESS_PREFIX);+ awareness.apply(awarenessData);+ Logger.debug("[rtc] applied awareness update");+ return;+ }++ // Handle doc update+ doc.import(data);Logger.debug("[rtc] imported doc change. new doc:", doc.toJSON());// Set the active doc only once the first message is received@@ -109,7 +147,7 @@ awareness.addListener((updates, origin) => {if (origin === "local") {Logger.debug("[rtc] awareness changes", changes);const ws = getWs();- ws.send(awareness.encode(changes));+ ws.send(prefixMessage(AWARENESS_PREFIX, awareness.encode(changes)));}});@@ -125,6 +163,7 @@ export function realTimeCollaboration(};}+ // Get or create the code containerconst hasPath = doc.getByPath(`codes/${cellId}`) !== undefined;const loroText = doc.getMap("codes")@@ -134,12 +173,23 @@ export function realTimeCollaboration(loroText.insert(0, initialCode);}+ const userName = store.get(usernameAtom) || "Anonymous";return {code: initialCode.toString(),extension: [languageObserverExtension(cellId),languageListenerExtension(cellId),- LoroSyncPlugin(doc, ["codes", cellId], () => {+ loroAwarenessPlugin(+ doc,+ awareness,+ {+ name: userName,+ colorClassName: getColor(userName),+ },+ () => loroText,+ cellId,+ ),+ loroSyncPlugin(doc, ["codes", cellId], () => {return loroText;}),],@@ -229,3 +279,39 @@ function languageListenerExtension(cellId: CellId) {}});}++/**+ * Create a plugin to observe awareness changes+ */+function loroAwarenessPlugin(+ 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/awareness.ts b/frontend/src/core/codemirror/rtc/loro/awareness.tsnew file mode 100644index 0000000000..49b1d43784--- /dev/null+++ b/frontend/src/core/codemirror/rtc/loro/awareness.ts@@ -0,0 +1,490 @@+/* Copyright 2024 Marimo. All rights reserved. */+import {+ EditorView,+ type PluginValue,+ type ViewUpdate,+ layer,+ type LayerMarker,+ type Rect,+ Direction,+ RectangleMarker,+} from "@codemirror/view";+import {+ type Awareness,+ type AwarenessListener,+ Cursor,+ type LoroDoc,+ type LoroText,+ type PeerID,+ type Subscription,+} from "loro-crdt";+import {+ Annotation,+ EditorSelection,+ type Extension,+ type SelectionRange,+ StateEffect,+ StateField,+} from "@codemirror/state";+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,+ // eslint-disable-next-line @typescript-eslint/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 {+ constructor(+ private left: number,+ private top: number,+ private height: number,+ private name: string,+ private colorClassName: string,+ ) {}++ draw(): HTMLElement {+ const elt = document.createElement("div");+ this.adjust(elt);+ return elt;+ }++ update(elt: HTMLElement): boolean {+ this.adjust(elt);+ return true;+ }++ 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}"`);+ }++ 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(+ absolutePosition.left - baseLeft,+ absolutePosition.top - baseTop,+ absolutePosition.bottom - absolutePosition.top,+ 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,+): Array<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;+ let headPos = anchorPos;+ if (state.cursor.head) {+ // range+ const head = Cursor.decode(state.cursor.head);+ headPos = doc.getCursorPos(head).offset;+ }+ 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 {+ sub: Subscription;++ constructor(+ public view: EditorView,+ public doc: LoroDoc,+ public user: UserState,+ public awareness: Awareness<AwarenessState>,+ private getTextFromDoc: (doc: LoroDoc) => LoroText,+ private scopeId: ScopeId,+ private getUserId?: () => Uid,+ ) {+ 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(),+ }),+ ],+ });+ }+ });+ }++ 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(+ this.doc,+ this.getTextFromDoc,+ selection.anchor,+ 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,+ });+ }+ }++ 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 {+ _awarenessListener?: AwarenessListener;+ constructor(+ public view: EditorView,+ public doc: LoroDoc,+ public awareness: Awareness<AwarenessState>,+ private 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);+ }++ destroy(): void {+ if (this._awarenessListener) {+ this.awareness.removeListener(this._awarenessListener);+ }+ }+}++const getCursorState = (+ 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 = 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.tsnew file mode 100644index 0000000000..ec14e9f9f2--- /dev/null+++ b/frontend/src/core/codemirror/rtc/loro/colors.ts@@ -0,0 +1,38 @@+/* Copyright 2024 Marimo. All rights reserved. */++export const COLORS = [+ "bg-[var(--amber-6)]",+ "bg-[var(--blue-6)]",+ "bg-[var(--crimson-6)]",+ "bg-[var(--cyan-6)]",+ "bg-[var(--grass-6)]",+ "bg-[var(--gray-6)]",+ "bg-[var(--green-6)]",+ "bg-[var(--lime-6)]",+ "bg-[var(--orange-6)]",+ "bg-[var(--purple-6)]",+ "bg-[var(--red-6)]",+ "bg-[var(--sage-6)]",+ "bg-[var(--sky-6)]",+ "bg-[var(--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.tsindex 4895c66f3a..10daa3fbef 100644--- a/frontend/src/core/codemirror/rtc/loro/sync.ts+++ b/frontend/src/core/codemirror/rtc/loro/sync.ts@@ -23,7 +23,7 @@ import { Logger } from "@/utils/Logger";* @param doc - LoroDoc instance* @returns Extension*/-export const LoroSyncPlugin = (+export const loroSyncPlugin = (doc: LoroDoc,docPath: string[],getTextFromDoc: (doc: LoroDoc) => LoroText,diff --git a/frontend/src/core/rtc/state.ts b/frontend/src/core/rtc/state.tsnew file mode 100644index 0000000000..c53f6cdfad--- /dev/null+++ b/frontend/src/core/rtc/state.ts@@ -0,0 +1,8 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { atomWithStorage } from "jotai/utils";++/**+ * The username for the current user when using real-time collaboration.+ * This is stored in localStorage.+ */+export const usernameAtom = atomWithStorage<string>("marimo:rtc:username", "");diff --git a/frontend/src/css/app/codemirror.css b/frontend/src/css/app/codemirror.cssindex 2bdf1ac324..a700d69128 100644--- a/frontend/src/css/app/codemirror.css+++ b/frontend/src/css/app/codemirror.css@@ -27,8 +27,9 @@background-color: transparent;}-.cm-scroller {- overflow: auto;+.marimo-cell .cm-scroller {+ /* this needs to be visible to show RTC cursors and inline AI edit buttons */+ overflow: visible;}/* -- Tooltips: code completion and type hints -- */diff --git a/frontend/src/css/globals.css b/frontend/src/css/globals.cssindex 0e888ccbb3..033d735f6b 100644--- a/frontend/src/css/globals.css+++ b/frontend/src/css/globals.css@@ -1,33 +1,33 @@-@import url("@radix-ui/colors/grass.css");+@import url("@radix-ui/colors/amber-dark.css");+@import url("@radix-ui/colors/amber.css");+@import url("@radix-ui/colors/blue-dark.css");+@import url("@radix-ui/colors/blue.css");+@import url("@radix-ui/colors/crimson-dark.css");+@import url("@radix-ui/colors/crimson.css");+@import url("@radix-ui/colors/cyan-dark.css");+@import url("@radix-ui/colors/cyan.css");@import url("@radix-ui/colors/grass-dark.css");-@import url("@radix-ui/colors/gray.css");+@import url("@radix-ui/colors/grass.css");@import url("@radix-ui/colors/gray-dark.css");-@import url("@radix-ui/colors/lime.css");+@import url("@radix-ui/colors/gray.css");+@import url("@radix-ui/colors/green-dark.css");+@import url("@radix-ui/colors/green.css");@import url("@radix-ui/colors/lime-dark.css");-@import url("@radix-ui/colors/red.css");+@import url("@radix-ui/colors/lime.css");+@import url("@radix-ui/colors/orange-dark.css");+@import url("@radix-ui/colors/orange.css");+@import url("@radix-ui/colors/purple-dark.css");+@import url("@radix-ui/colors/purple.css");@import url("@radix-ui/colors/red-dark.css");-@import url("@radix-ui/colors/sky.css");+@import url("@radix-ui/colors/red.css");+@import url("@radix-ui/colors/sage-dark.css");+@import url("@radix-ui/colors/sage.css");@import url("@radix-ui/colors/sky-dark.css");-@import url("@radix-ui/colors/orange.css");-@import url("@radix-ui/colors/orange-dark.css");-@import url("@radix-ui/colors/cyan.css");-@import url("@radix-ui/colors/cyan-dark.css");-@import url("@radix-ui/colors/slate.css");+@import url("@radix-ui/colors/sky.css");@import url("@radix-ui/colors/slate-dark.css");-@import url("@radix-ui/colors/sage.css");-@import url("@radix-ui/colors/sage-dark.css");-@import url("@radix-ui/colors/amber.css");-@import url("@radix-ui/colors/amber-dark.css");-@import url("@radix-ui/colors/yellow.css");+@import url("@radix-ui/colors/slate.css");@import url("@radix-ui/colors/yellow-dark.css");-@import url("@radix-ui/colors/blue.css");-@import url("@radix-ui/colors/blue-dark.css");-@import url("@radix-ui/colors/purple.css");-@import url("@radix-ui/colors/purple-dark.css");-@import url("@radix-ui/colors/green.css");-@import url("@radix-ui/colors/green-dark.css");-@import url("@radix-ui/colors/crimson.css");-@import url("@radix-ui/colors/crimson-dark.css");+@import url("@radix-ui/colors/yellow.css");@tailwind base;@tailwind components;