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
feat: kiosk consumers (#1639)
Myles Scolnick3c1ec8022124
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex 4d6f4128f0..eaf84b42b7 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -51,6 +51,7 @@ import { aiEnabledAtom, autoInstantiateAtom } from "@/core/config/config";import { useDeleteCellCallback } from "../cell/useDeleteCell";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { CellConfig, CellStatus } from "@/core/network/types";+import { kioskModeAtom } from "@/core/mode";export interface CellActionButtonPropsextends Pick<CellData, "name" | "config"> {@@ -83,8 +84,9 @@ export function useCellActionButtons({ cell }: Props) {const aiEnabled = useAtomValue(aiEnabledAtom);const autoInstantiate = useAtomValue(autoInstantiateAtom);const cellIds = useCellIds();+ const kioskMode = useAtomValue(kioskModeAtom);- if (!cell) {+ if (!cell || kioskMode) {return [];}diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex 8e332c73d3..14757c671e 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -1,7 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */-import { runDuringPresentMode } from "@/core/mode";+import { kioskModeAtom, runDuringPresentMode } from "@/core/mode";import { downloadBlob, downloadHTMLAsImage } from "@/utils/download";-import { useSetAtom } from "jotai";+import { useAtomValue, useSetAtom } from "jotai";import {ImageIcon,CommandIcon,@@ -59,6 +59,7 @@ export function useNotebookActions() {const { openModal, closeModal } = useImperativeModal();const { openApplication } = useChromeActions();const { selectedPanel } = useChromeState();+ const kioskMode = useAtomValue(kioskModeAtom);const notebook = useNotebook();const { updateCellConfig, undoDeleteCell } = useCellActions();@@ -205,7 +206,7 @@ export function useNotebookActions() {{icon: <ZapIcon size={14} strokeWidth={1.5} />,label: "Enable all cells",- hidden: disabledCells.length === 0,+ hidden: disabledCells.length === 0 || kioskMode,handle: async () => {const ids = disabledCells.map((cell) => cell.id);const newConfigs = Objects.fromEntries(@@ -222,7 +223,7 @@ export function useNotebookActions() {{icon: <ZapOffIcon size={14} strokeWidth={1.5} />,label: "Disable all cells",- hidden: enabledCells.length === 0,+ hidden: enabledCells.length === 0 || kioskMode,handle: async () => {const ids = enabledCells.map((cell) => cell.id);const newConfigs = Objects.fromEntries(@@ -239,7 +240,7 @@ export function useNotebookActions() {{icon: <Undo2Icon size={14} strokeWidth={1.5} />,label: "Undo cell deletion",- hidden: !canUndoDeletes(notebook),+ hidden: !canUndoDeletes(notebook) || kioskMode,handle: () => {undoDeleteCell();},diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx b/frontend/src/components/editor/chrome/panels/snippets-panel.tsxindex 075e966001..620fe66132 100644--- a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx@@ -28,6 +28,7 @@ import { useCellActions } from "@/core/cells/cells";import { cn } from "@/utils/cn";import { ContributeSnippetButton } from "../components/contribute-snippet-button";import { Spinner } from "@/components/icons/spinner";+import { HideInKioskMode } from "../../kiosk-mode";const extensions = [EditorView.lineWrapping];@@ -128,15 +129,17 @@ const SnippetViewer: React.FC<{ snippet: Snippet }> = ({ snippet }) => {</div><div className="px-2 py-2 space-y-4 overflow-auto flex-1"><div className="flex justify-end">- <Button- className="float-right"- size="xs"- variant="outline"- onClick={handleInsertSnippet}- >- Insert snippet- <BetweenHorizontalStartIcon className="ml-2 h-4 w-4" />- </Button>+ <HideInKioskMode>+ <Button+ className="float-right"+ size="xs"+ variant="outline"+ onClick={handleInsertSnippet}+ >+ Insert snippet+ <BetweenHorizontalStartIcon className="ml-2 h-4 w-4" />+ </Button>+ </HideInKioskMode></div>{snippet.sections.map((section) => {const { code, html, id } = section;@@ -157,18 +160,20 @@ const SnippetViewer: React.FC<{ snippet: Snippet }> = ({ snippet }) => {className="relative hover-actions-parent pr-2"key={`${snippet.title}-${id}`}>- <Tooltip content="Insert snippet">- <Button- className="absolute -top-2 -right-1 z-10 hover-action px-2 bg-background"- size="sm"- variant="outline"- onClick={() => {- handleInsertCode(code);- }}- >- <BetweenHorizontalStartIcon className="h-5 w-5" />- </Button>- </Tooltip>+ <HideInKioskMode>+ <Tooltip content="Insert snippet">+ <Button+ className="absolute -top-2 -right-1 z-10 hover-action px-2 bg-background"+ size="sm"+ variant="outline"+ onClick={() => {+ handleInsertCode(code);+ }}+ >+ <BetweenHorizontalStartIcon className="h-5 w-5" />+ </Button>+ </Tooltip>+ </HideInKioskMode><LazyAnyLanguageCodeMirrorkey={`${snippet.title}-${id}`}theme={theme === "dark" ? "dark" : "light"}diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsxindex 000fd818a6..6c2dee1cb3 100644--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx@@ -11,6 +11,7 @@ import { useUserConfig } from "@/core/config/config";import { ZapIcon, ZapOffIcon } from "lucide-react";import { saveUserConfig } from "@/core/network/requests";import { UserConfig } from "@/core/config/config-schema";+import { ShowInKioskMode } from "../../kiosk-mode";export const Footer: React.FC = () => {const { selectedPanel } = useChromeState();@@ -103,6 +104,19 @@ export const Footer: React.FC = () => {<div className="mx-auto" />+ <ShowInKioskMode>+ <Tooltip+ content={+ <div className="w-[200px]">+ Kiosk mode is enabled. This allows you to view the outputs of the+ cells without the ability to edit them.+ </div>+ }+ >+ <span className="text-muted-foreground text-sm mr-4">kiosk mode</span>+ </Tooltip>+ </ShowInKioskMode>+<MachineStats /></footer>);diff --git a/frontend/src/components/editor/code/readonly-python-code.tsx b/frontend/src/components/editor/code/readonly-python-code.tsxindex dd8d2c7bef..33dba98da1 100644--- a/frontend/src/components/editor/code/readonly-python-code.tsx+++ b/frontend/src/components/editor/code/readonly-python-code.tsx@@ -4,7 +4,7 @@ import CodeMirror, {EditorView,ReactCodeMirrorProps,} from "@uiw/react-codemirror";-import { CopyIcon, EyeIcon } from "lucide-react";+import { CopyIcon, EyeIcon, EyeOffIcon } from "lucide-react";import { Button } from "@/components/ui/button";import { Events } from "@/utils/events";import { toast } from "@/components/ui/use-toast";@@ -32,7 +32,12 @@ export const ReadonlyPythonCode = memo()}>{hideCode && <HideCodeButton onClick={() => setHideCode(false)} />}- {!hideCode && <FloatingCopyButton text={code} />}+ {!hideCode && (+ <div className="absolute top-0 right-0 my-1 mx-2 z-10 hover-action flex gap-2">+ <CopyButton text={code} />+ <EyeCloseButton onClick={() => setHideCode(true)} />+ </div>+ )}<CodeMirror{...rest}className={cn("cm", hideCode && "opacity-20 h-8 overflow-hidden")}@@ -49,20 +54,28 @@ export const ReadonlyPythonCode = memo();ReadonlyPythonCode.displayName = "ReadonlyPythonCode";-const FloatingCopyButton = (props: { text: string }) => {+const CopyButton = (props: { text: string }) => {const copy = Events.stopPropagation(() => {navigator.clipboard.writeText(props.text);toast({ title: "Copied to clipboard" });});+ return (+ <Button onClick={copy} size="xs" className="py-0" variant="secondary">+ <CopyIcon size={14} strokeWidth={1.5} />+ </Button>+ );+};++const EyeCloseButton = (props: { onClick: () => void }) => {return (<Button- onClick={copy}- className="absolute top-0 right-0 m-2 z-10 hover-action"+ onClick={props.onClick}size="xs"+ className="py-0"variant="secondary">- <CopyIcon size={14} strokeWidth={1.5} />+ <EyeOffIcon size={14} strokeWidth={1.5} /></Button>);};diff --git a/frontend/src/components/editor/controls/Controls.tsx b/frontend/src/components/editor/controls/Controls.tsxindex 44316cdaef..b5174a2c3f 100644--- a/frontend/src/components/editor/controls/Controls.tsx+++ b/frontend/src/components/editor/controls/Controls.tsx@@ -24,6 +24,7 @@ import { AppConfig } from "@/core/config/config-schema";import { useShouldShowInterrupt } from "../cell/useShouldShowInterrupt";import { CommandPaletteButton } from "./command-palette-button";import { cn } from "@/utils/cn";+import { HideInKioskMode } from "../kiosk-mode";interface ControlsProps {filename: string | null;@@ -100,25 +101,27 @@ export const Controls = ({appWidth === "compact" && "xl:flex-row items-end",)}>- {closed ? (- <RecoveryButton- filename={filename}- getCellsAsJSON={getCellsAsJSON}- needsSave={needsSave}- />- ) : (- <Tooltip content={renderShortcut("global.save")}>- <Button- data-testid="save-button"- id="save-button"- shape="rectangle"- color={needsSave ? "yellow" : "hint-green"}- onClick={handleSaveClick}- >- <SaveIcon strokeWidth={1.5} size={18} />- </Button>- </Tooltip>- )}+ <HideInKioskMode>+ {closed ? (+ <RecoveryButton+ filename={filename}+ getCellsAsJSON={getCellsAsJSON}+ needsSave={needsSave}+ />+ ) : (+ <Tooltip content={renderShortcut("global.save")}>+ <Button+ data-testid="save-button"+ id="save-button"+ shape="rectangle"+ color={needsSave ? "yellow" : "hint-green"}+ onClick={handleSaveClick}+ >+ <SaveIcon strokeWidth={1.5} size={18} />+ </Button>+ </Tooltip>+ )}+ </HideInKioskMode><Tooltip content={renderShortcut("global.hideCode")}><Button@@ -141,17 +144,19 @@ export const Controls = ({<div />- <div className="flex flex-col gap-2 items-center">- {undoControl}- {!closed && (- <RunControlButton- running={running}- needsRun={needsRun}- onRun={onRun}- onInterrupt={onInterrupt}- />- )}- </div>+ <HideInKioskMode>+ <div className="flex flex-col gap-2 items-center">+ {undoControl}+ {!closed && (+ <RunControlButton+ running={running}+ needsRun={needsRun}+ onRun={onRun}+ onInterrupt={onInterrupt}+ />+ )}+ </div>+ </HideInKioskMode></div></>);diff --git a/frontend/src/components/editor/kiosk-mode.tsx b/frontend/src/components/editor/kiosk-mode.tsxnew file mode 100644index 0000000000..c4e823eb4a--- /dev/null+++ b/frontend/src/components/editor/kiosk-mode.tsx@@ -0,0 +1,24 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { kioskModeAtom } from "@/core/mode";+import { useAtomValue } from "jotai";+import React from "react";++interface Props {+ children: React.ReactNode;+}++export const HideInKioskMode: React.FC<Props> = ({ children }) => {+ const kioskMode = useAtomValue(kioskModeAtom);+ if (kioskMode) {+ return null;+ }+ return children;+};++export const ShowInKioskMode: React.FC<Props> = ({ children }) => {+ const kioskMode = useAtomValue(kioskModeAtom);+ if (kioskMode) {+ return children;+ }+ return null;+};diff --git a/frontend/src/components/editor/renderers/cells-renderer.tsx b/frontend/src/components/editor/renderers/cells-renderer.tsxindex 766785851a..504c99c74b 100644--- a/frontend/src/components/editor/renderers/cells-renderer.tsx+++ b/frontend/src/components/editor/renderers/cells-renderer.tsx@@ -3,8 +3,9 @@ import { flattenNotebookCells, useNotebook } from "@/core/cells/cells";import React, { PropsWithChildren, memo } from "react";import { cellRendererPlugins } from "./plugins";import { AppConfig } from "@/core/config/config-schema";-import { AppMode } from "@/core/mode";+import { AppMode, kioskModeAtom } from "@/core/mode";import { useLayoutActions, useLayoutState } from "@/core/layout/layout";+import { useAtomValue } from "jotai";interface Props {appConfig: AppConfig;@@ -16,9 +17,10 @@ export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(const notebook = useNotebook();const { selectedLayout, layoutData } = useLayoutState();const { setCurrentLayoutData } = useLayoutActions();+ const kioskMode = useAtomValue(kioskModeAtom);// Just render children if we are in edit mode- if (mode === "edit") {+ if (mode === "edit" && !kioskMode) {return children;}diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex e0ffb545cd..889a55e209 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -7,7 +7,7 @@ import { ICellRendererPlugin, ICellRendererProps } from "../types";import { VerticalLayoutWrapper } from "./vertical-layout-wrapper";import { z } from "zod";import { useDelayVisibility } from "./useDelayVisibility";-import { AppMode } from "@/core/mode";+import { AppMode, kioskModeAtom } from "@/core/mode";import { ReadonlyPythonCode } from "@/components/editor/code/readonly-python-code";import {ChevronDown,@@ -31,6 +31,7 @@ import { downloadHTMLAsImage } from "@/utils/download";import { downloadAsHTML } from "@/core/static/download-html";import { isPyodide } from "@/core/pyodide/utils";import { CellConfig } from "@/core/network/types";+import { useAtomValue } from "jotai";type VerticalLayout = null;type VerticalLayoutProps = ICellRendererProps<VerticalLayout>;@@ -41,6 +42,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({mode,}) => {const { invisible } = useDelayVisibility(cells.length, mode);+ const kioskMode = useAtomValue(kioskModeAtom);const urlParams = new URLSearchParams(window.location.search);const showCodeDefault = urlParams.get("show-code");@@ -54,6 +56,10 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({const evaluateCanShowCode = () => {const cellsHaveCode = cells.some((cell) => Boolean(cell.code));+ if (kioskMode) {+ return true;+ }+// Only show code if in read mode and there is at least one cell with code// If it is a static-notebook or wasm-read-only-notebook, code is always included,@@ -84,6 +90,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({interrupted={cell.interrupted}staleInputs={cell.staleInputs}name={cell.name}+ kiosk={kioskMode}/>))}{mode === "read" && (@@ -180,6 +187,7 @@ interface VerticalCellPropsmode: AppMode;showCode: boolean;name: string;+ kiosk: boolean;}const VerticalCell = memo(@@ -198,6 +206,7 @@ const VerticalCell = memo(showCode,mode,name,+ kiosk,}: VerticalCellProps) => {const cellRef = useRef<HTMLDivElement>(null);@@ -212,18 +221,20 @@ const VerticalCell = memo(false,);+ // Kiosk and not presenting+ const kioskFull = kiosk && mode !== "present";+const className = cn("Cell", "hover-actions-parent", {- published: !showCode,+ published: !showCode && !kioskFull,interactive: mode === "edit","has-error": errored,stopped: stopped,});const HTMLId = HTMLCellId.create(cellId);- const hidden = errored || interrupted || stopped;// Read mode and show code- if (mode === "read" && showCode) {+ if ((mode === "read" && showCode) || kioskFull) {return (<div tabIndex={-1} id={HTMLId} ref={cellRef} className={className}><OutputArea@@ -235,7 +246,7 @@ const VerticalCell = memo(/><div className="tray"><ReadonlyPythonCode- initiallyHideCode={config.hide_code}+ initiallyHideCode={config.hide_code || kiosk}code={code}/></div>@@ -251,6 +262,8 @@ const VerticalCell = memo();}+ const hidden = errored || interrupted || stopped;+return hidden ? null : (<div tabIndex={-1} id={HTMLId} ref={cellRef} className={className}><OutputAreadiff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 382d61d233..bc4b935cff 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -37,8 +37,10 @@ import {updateEditorCodeFromPython,} from "../codemirror/language/utils";import { invariant } from "@/utils/invariant";-import { CellConfig, CellStatus } from "../network/types";+import { CellConfig, CellStatus, UpdateCellIdsRequest } from "../network/types";import { getUserConfig } from "@/core/config/config";+import { syncCellIds } from "../network/requests";+import { kioskModeAtom } from "../mode";/*** The state of the notebook.@@ -471,6 +473,54 @@ const {cellLogs: [...nextState.cellLogs, ...getCellLogsForMessage(message)],};},+ setCellIds: (state, action: { cellIds: CellId[] }) => {+ // Create new cell data and runtime states for the new cell IDs+ const nextCellData = { ...state.cellData };+ const nextCellRuntime = { ...state.cellRuntime };+ const nextCellHandles = { ...state.cellHandles };++ for (const cellId of action.cellIds) {+ if (!(cellId in state.cellData)) {+ nextCellData[cellId] = createCell({ id: cellId });+ }+ if (!(cellId in state.cellRuntime)) {+ nextCellRuntime[cellId] = createCellRuntimeState();+ }+ if (!(cellId in state.cellHandles)) {+ nextCellHandles[cellId] = createRef();+ }+ }++ return {+ ...state,+ cellIds: action.cellIds,+ cellData: nextCellData,+ cellRuntime: nextCellRuntime,+ cellHandles: nextCellHandles,+ };+ },+ setCellCodes: (state, action: { codes: string[]; ids: CellId[] }) => {+ invariant(+ action.codes.length === action.ids.length,+ "Expected codes and ids to have the same length",+ );++ for (let i = 0; i < action.codes.length; i++) {+ const cellId = action.ids[i];+ const code = action.codes[i];++ state = updateCellData(state, cellId, (cell) => {+ return {+ ...cell,+ code,+ edited: false,+ lastCodeRun: code,+ };+ });+ }++ return state;+ },setStdinResponse: (state,action: { cellId: CellId; response: string; outputIndex: number },@@ -738,7 +788,7 @@ export {/// ATOMS-const cellIdsAtom = atom((get) => get(notebookAtom).cellIds);+export const cellIdsAtom = atom((get) => get(notebookAtom).cellIds);export const hasOnlyOneCellAtom = atom((get) => get(cellIdsAtom).length === 1);@@ -936,6 +986,32 @@ export function useCellActions() {*/export type CellActions = ReturnType<typeof createActions>;+export const CellEffects = {+ onCellIdsChange: (cellIds: CellId[], prevCellIds: CellId[]) => {+ const kioskMode = store.get(kioskModeAtom);+ if (kioskMode) {+ return;+ }+ // If cellIds is empty, return early+ if (cellIds.length === 0) {+ return;+ }+ // If prevCellIds is empty, also return early+ // this means that the notebook was just created+ if (prevCellIds.length === 0) {+ return;+ }++ // If they are different references, send an update to the server+ if (cellIds !== prevCellIds) {+ // "name" property is not actually required+ void syncCellIds({+ cell_ids: cellIds,+ } as unknown as UpdateCellIdsRequest);+ }+ },+};+/*** This is exported for testing purposes only.*/diff --git a/frontend/src/core/cells/scrollCellIntoView.ts b/frontend/src/core/cells/scrollCellIntoView.tsindex 3687ef8ea1..f6a989d4d1 100644--- a/frontend/src/core/cells/scrollCellIntoView.ts+++ b/frontend/src/core/cells/scrollCellIntoView.ts@@ -67,6 +67,24 @@ export function focusAndScrollCellIntoView({});}+export function focusAndScrollCellOutputIntoView(cellId: CellId) {+ const element = document.getElementById(HTMLCellId.create(cellId));+ if (!element) {+ Logger.warn("scrollCellIntoView: element not found");+ return;+ }++ element.classList.add("focus-outline");+ setTimeout(() => {+ element.classList.remove("focus-outline");+ }, 2000);++ element.scrollIntoView({+ behavior: "smooth",+ block: "center",+ });+}+/*** Scroll to bottom and top of page.*diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsxindex 1669af8118..59b178381e 100644--- a/frontend/src/core/edit-app.tsx+++ b/frontend/src/core/edit-app.tsx@@ -18,6 +18,8 @@ import {notebookIsRunningAtom,useCellActions,useNotebook,+ CellEffects,+ cellIdsAtom,} from "./cells/cells";import {canUndoDeletes,@@ -57,6 +59,7 @@ import { getSessionId } from "./kernel/session";import { updateQueryParams } from "@/utils/urls";import { AppHeader } from "@/components/editor/header/app-header";import { AppContainer } from "../components/editor/app-container";+import { useJotaiEffect } from "./state/jotai";import { Paths } from "@/utils/paths";interface AppProps {@@ -66,6 +69,9 @@ interface AppProps {export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {const notebook = useNotebook();++ useJotaiEffect(cellIdsAtom, CellEffects.onCellIdsChange);+const { setCells, updateCellCode } = useCellActions();const [viewState, setViewState] = useAtom(viewStateAtom);const [filename, setFilename] = useFilename();diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.tsindex ee2b9759b4..39f60115e2 100644--- a/frontend/src/core/islands/bridge.ts+++ b/frontend/src/core/islands/bridge.ts@@ -136,6 +136,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {saveAppConfig = throwNotImplemented;saveCellConfig = throwNotImplemented;sendRestart = throwNotImplemented;+ syncCellIds = throwNotImplemented;readCode = throwNotImplemented;readSnippets = throwNotImplemented;previewDatasetColumn = throwNotImplemented;diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.tsindex ccf7650f44..b74d0dd1e5 100644--- a/frontend/src/core/islands/main.ts+++ b/frontend/src/core/islands/main.ts@@ -67,6 +67,13 @@ export async function initialize() {case "installing-package-alert":case "completion-result":case "reload":+ case "update-cell-codes":+ case "update-cell-ids":+ case "focus-cell":+ case "variables":+ case "variable-values":+ case "data-column-preview":+ case "datasets":// Unsupportedreturn;case "kernel-ready":@@ -97,11 +104,6 @@ export async function initialize() {case "cell-op":handleCellOperation(msg.data, actions.handleCellMessage);return;- case "variables":- case "variable-values":- case "data-column-preview":- case "datasets":- return;case "alert":// TODO: support toast with islandstoast({diff --git a/frontend/src/core/kernel/session.ts b/frontend/src/core/kernel/session.tsindex 384829370d..d9c1338ef4 100644--- a/frontend/src/core/kernel/session.ts+++ b/frontend/src/core/kernel/session.ts@@ -2,6 +2,7 @@import { init } from "@paralleldrive/cuid2";import { TypedString } from "@/utils/typed";import { updateQueryParams } from "@/utils/urls";+import { Logger } from "@/utils/Logger";export type SessionId = TypedString<"SessionId">;@@ -24,10 +25,17 @@ const sessionId = (() => {if (isSessionId(id)) {// Remove the session_id from the URLupdateQueryParams((params) => {+ // Keep the session_id if we are in kiosk mode+ // this is so we can resume the same session if the user refreshes the page+ if (params.has("kiosk")) {+ return;+ }params.delete("session_id");});+ Logger.debug("Connecting to existing session", { sessionId: id });return id;}+ Logger.debug("Starting a new session", { sessionId: id });return generateSessionId();})();diff --git a/frontend/src/core/mode.ts b/frontend/src/core/mode.tsindex d7b0b61e8c..e8e6b5810b 100644--- a/frontend/src/core/mode.ts+++ b/frontend/src/core/mode.ts@@ -12,7 +12,6 @@ import { Logger } from "@/utils/Logger";* - `edit`: A user is editing the notebook. Can switch to present mode.* - `present`: A user is presenting the notebook, it looks like read mode but with some editing features. Cannot switch to present mode.* - `home`: A user is in the home page.- * - `island`: A user is interacting with marimo from an external application.*/export type AppMode = "read" | "edit" | "present" | "home";@@ -90,3 +89,5 @@ export const viewStateAtom = atom<ViewState>({mode: initialMode,cellAnchor: null,});++export const kioskModeAtom = atom<boolean>(false);diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.tsindex 9547bc8b12..2ae20fa308 100644--- a/frontend/src/core/network/requests-network.ts+++ b/frontend/src/core/network/requests-network.ts@@ -18,6 +18,13 @@ export function createNetworkRequests(): EditRequests & RunRequests {.POST("/api/kernel/restart_session").then(handleResponseReturnNull);},+ syncCellIds: (request) => {+ return marimoClient+ .POST("/api/kernel/sync/cell_ids", {+ body: request,+ })+ .then(handleResponseReturnNull);+ },sendRename: (request) => {return marimoClient.POST("/api/kernel/rename", {diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.tsindex fd61bf3869..937b0a709f 100644--- a/frontend/src/core/network/requests-static.ts+++ b/frontend/src/core/network/requests-static.ts@@ -32,6 +32,7 @@ export function createStaticRequests(): EditRequests & RunRequests {return null;},sendRestart: throwNotInEditMode,+ syncCellIds: throwNotInEditMode,sendRun: throwNotInEditMode,sendRename: throwNotInEditMode,sendSave: throwNotInEditMode,diff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.tsindex 24a9b3b6ef..d35eb3f98e 100644--- a/frontend/src/core/network/requests-toasting.ts+++ b/frontend/src/core/network/requests-toasting.ts@@ -13,6 +13,7 @@ export function createErrorToastingRequests(sendInstantiate: "Failed to instantiate",sendFunctionRequest: "Failed to send function request",sendRestart: "Failed to restart",+ syncCellIds: "Failed to sync cell IDs",sendRun: "Failed to run",sendRename: "Failed to rename",sendSave: "Failed to save",diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex d62a35eaff..9e2e4c4bb1 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -29,6 +29,7 @@ export const {sendComponentValues,sendRename,sendRestart,+ syncCellIds,sendSave,sendStdin,sendFormat,diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex aba6f040f9..3004a98b01 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -18,7 +18,7 @@ export type CellConfig = schemas["CellConfig"];export type CellStatus = schemas["CellStatus"];export type CodeCompletionRequest = schemas["CodeCompletionRequest"];export type CreationRequest = schemas["CreationRequest"];-export type DeleteRequest = schemas["DeleteRequest"];+export type DeleteCellRequest = schemas["DeleteCellRequest"];export type ExecuteMultipleRequest = schemas["ExecuteMultipleRequest"];export type ExecutionRequest = schemas["ExecutionRequest"];export type ExportAsHTMLRequest = schemas["ExportAsHTMLRequest"];@@ -61,6 +61,7 @@ export interface SetCellConfigRequest {configs: Record<CellId, Partial<CellConfig>>;}export type SetUIElementValueRequest = schemas["SetUIElementValueRequest"];+export type UpdateCellIdsRequest = schemas["UpdateCellIdsRequest"];export type SetUserConfigRequest = schemas["SetUserConfigRequest"];export type ShutdownSessionRequest = schemas["ShutdownSessionRequest"];export type Snippet = schemas["Snippet"];@@ -95,12 +96,13 @@ export interface EditRequests {sendInterrupt: () => Promise<null>;sendShutdown: () => Promise<null>;sendFormat: (request: FormatRequest) => Promise<FormatResponse>;- sendDeleteCell: (request: DeleteRequest) => Promise<null>;+ sendDeleteCell: (request: DeleteCellRequest) => Promise<null>;sendCodeCompletionRequest: (request: CodeCompletionRequest) => Promise<null>;saveUserConfig: (request: SaveUserConfigurationRequest) => Promise<null>;saveAppConfig: (request: SaveAppConfigurationRequest) => Promise<null>;saveCellConfig: (request: SetCellConfigRequest) => Promise<null>;sendRestart: () => Promise<null>;+ syncCellIds: (request: UpdateCellIdsRequest) => Promise<null>;sendInstallMissingPackages: (request: InstallMissingPackagesRequest,) => Promise<null>;diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.tsindex 1879d70603..03ba7b3f3f 100644--- a/frontend/src/core/pyodide/bridge.ts+++ b/frontend/src/core/pyodide/bridge.ts@@ -405,6 +405,7 @@ export class PyodideBridge implements RunRequests, EditRequests {await this.putControlRequest(request);return null;};+ syncCellIds = throwNotImplemented;getUsageStats = throwNotImplemented;getRecentFiles = throwNotImplemented;getWorkspaceFiles = throwNotImplemented;diff --git a/frontend/src/core/state/jotai.ts b/frontend/src/core/state/jotai.tsindex 134445f55b..73f0c0faa7 100644--- a/frontend/src/core/state/jotai.ts+++ b/frontend/src/core/state/jotai.ts@@ -1,5 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */-import { Atom, createStore } from "jotai";+import { Atom, createStore, useStore } from "jotai";+import { useEffect } from "react";/*** Global store allows getting and setting global state outside of React components.@@ -27,3 +28,21 @@ export async function waitFor<T>(});});}++/**+ * Create a Jotai effect that runs when an atom changes.+ */+export function useJotaiEffect<T>(+ atom: Atom<T>,+ effect: (value: T, prevValue: T) => void,+) {+ const store = useStore();+ useEffect(() => {+ let prevValue = store.get(atom);+ store.sub(atom, () => {+ const value = store.get(atom);+ effect(value, prevValue);+ prevValue = value;+ });+ }, [atom, effect, store]);+}diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 5d3e7d903c..2ae8e4c07d 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { WebSocketClosedReason, WebSocketState } from "./types";-import { useAtom } from "jotai";+import { useAtom, useSetAtom } from "jotai";import { connectionAtom } from "../network/connection";import { useWebSocket } from "@/core/websocket/useWebSocket";import { logNever } from "@/utils/assertNever";@@ -35,6 +35,8 @@ import { useDatasetsActions } from "../datasets/state";import { RequestId } from "../network/DeferredRequestRegistry";import { VariableName } from "../variables/types";import { CellId } from "../cells/ids";+import { kioskModeAtom } from "../mode";+import { focusAndScrollCellOutputIntoView } from "../cells/scrollCellIntoView";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -49,7 +51,7 @@ export function useMarimoWebSocket(opts: {const { autoInstantiate, sessionId, setCells } = opts;const { showBoundary } = useErrorBoundary();- const { handleCellMessage } = useCellActions();+ const { handleCellMessage, setCellCodes, setCellIds } = useCellActions();const setAppConfig = useSetAppConfig();const { setVariables, setMetadata } = useVariablesActions();const { addColumnPreview } = useDatasetsActions();@@ -58,6 +60,7 @@ export function useMarimoWebSocket(opts: {const [connection, setConnection] = useAtom(connectionAtom);const { addBanner } = useBannersActions();const { addPackageAlert } = useAlertActions();+ const setKioskMode = useSetAtom(kioskModeAtom);const handleMessage = (e: MessageEvent<JsonString<OperationMessage>>) => {const msg = jsonParseWithSpecialChar(e.data);@@ -73,6 +76,7 @@ export function useMarimoWebSocket(opts: {setAppConfig,onError: showBoundary,});+ setKioskMode(msg.data.kiosk);return;case "completed-run":@@ -168,6 +172,18 @@ export function useMarimoWebSocket(opts: {case "reconnected":return;+ case "focus-cell":+ focusAndScrollCellOutputIntoView(msg.data.cell_id as CellId);+ return;+ case "update-cell-codes":+ setCellCodes({+ codes: msg.data.codes,+ ids: msg.data.cell_ids as CellId[],+ });+ return;+ case "update-cell-ids":+ setCellIds({ cellIds: msg.data.cell_ids as CellId[] });+ return;default:logNever(msg);}@@ -218,6 +234,7 @@ export function useMarimoWebSocket(opts: {* Handle a close event. We may want to reconnect.*/onClose: (e) => {+ Logger.warn("WebSocket closed", e.code, e.reason);switch (e.reason) {case "MARIMO_ALREADY_CONNECTED":setConnection({@@ -229,8 +246,10 @@ export function useMarimoWebSocket(opts: {return;case "MARIMO_WRONG_KERNEL_ID":+ case "MARIMO_NO_FILE_KEY":+ case "MARIMO_NO_SESSION_ID":+ case "MARIMO_NO_SESSION":case "MARIMO_SHUTDOWN":- Logger.warn("WebSocket closed", e.reason);setConnection({state: WebSocketState.CLOSED,code: WebSocketClosedReason.KERNEL_DISCONNECTED,diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.cssindex 7c62efaac9..db17caccc1 100644--- a/frontend/src/css/app/Cell.css+++ b/frontend/src/css/app/Cell.css@@ -161,6 +161,7 @@/* Focus state */&.focus-outline {+ transition: all 0.6s;border-color: var(--blue-8) !important;/* custom shadow until our theme overrides can support colored shadow */diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex b777fef7d2..d2d75839aa 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -85,6 +85,9 @@ def _generate_schema() -> dict[str, Any]:ops.QueryParamsAppend,ops.QueryParamsDelete,ops.QueryParamsClear,+ ops.UpdateCellCodes,+ ops.UpdateCellIdsRequest,+ ops.FocusCell,ops.MessageOperation,]@@ -137,7 +140,7 @@ def _generate_schema() -> dict[str, Any]:models.UpdateComponentValuesRequest,requests.CodeCompletionRequest,requests.CreationRequest,- requests.DeleteRequest,+ requests.DeleteCellRequest,requests.ExecuteMultipleRequest,requests.ExecuteStaleRequest,requests.ExecutionRequest,diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex fd497375a7..267818f365 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -342,6 +342,8 @@ class KernelReady(Op):last_execution_time: Optional[Dict[CellId_t, float]]# App configapp_config: _AppConfig+ # Whether the kernel is kiosk mode+ kiosk: bool@dataclass@@ -521,6 +523,32 @@ class QueryParamsClear(Op):name: ClassVar[str] = "query-params-clear"+@dataclass+class FocusCell(Op):+ name: ClassVar[str] = "focus-cell"+ cell_id: CellId_t+++@dataclass+class UpdateCellCodes(Op):+ name: ClassVar[str] = "update-cell-codes"+ cell_ids: List[CellId_t]+ codes: List[str]+++@dataclass+class UpdateCellIdsRequest(Op):+ """+ Update the cell ID ordering of the cells in the notebook.++ Right now we send the entire list of cell IDs,+ but in the future we might want to send change-deltas.+ """++ name: ClassVar[str] = "update-cell-ids"+ cell_ids: List[CellId_t]++MessageOperation = Union[# Cell operationsCellOp,@@ -550,4 +578,8 @@ MessageOperation = Union[# DatasetsDatasets,DataColumnPreview,+ # Kiosk specific+ FocusCell,+ UpdateCellCodes,+ UpdateCellIdsRequest,]diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.pyindex 31a7ff6d1a..e9b1c806bd 100644--- a/marimo/_pyodide/bootstrap.py+++ b/marimo/_pyodide/bootstrap.py@@ -76,6 +76,7 @@ def create_session(last_executed_code={},last_execution_time={},app_config=app.config,+ kiosk=False,)),)diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 292d997294..687d0e0a23 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -114,7 +114,7 @@ class CreationRequest:@dataclass-class DeleteRequest:+class DeleteCellRequest:cell_id: CellId_t@@ -151,7 +151,7 @@ ControlRequest = Union[ExecuteMultipleRequest,ExecuteStaleRequest,CreationRequest,- DeleteRequest,+ DeleteCellRequest,FunctionCallRequest,SetCellConfigRequest,SetUserConfigRequest,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 1190df6df3..e4dfaf8ce5 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -82,7 +82,7 @@ from marimo._runtime.requests import (CodeCompletionRequest,ControlRequest,CreationRequest,- DeleteRequest,+ DeleteCellRequest,ExecuteMultipleRequest,ExecuteStaleRequest,ExecutionRequest,@@ -676,7 +676,7 @@ class Kernel:def mutate_graph(self,execution_requests: Sequence[ExecutionRequest],- deletion_requests: Sequence[DeleteRequest],+ deletion_requests: Sequence[DeleteCellRequest],) -> set[CellId_t]:"""Add and remove cells to/from the graph.@@ -970,7 +970,7 @@ class Kernel:# TODO(akshayka): Send VariableValues message for any globals# bound to this state object (just like UI elements)- async def delete(self, request: DeleteRequest) -> None:+ async def delete(self, request: DeleteCellRequest) -> None:"""Delete a cell from kernel and graph."""cell_id = request.cell_idif cell_id in self.graph.cells:@@ -1408,7 +1408,7 @@ class Kernel:status=status,).broadcast()CompletedRun().broadcast()- elif isinstance(request, DeleteRequest):+ elif isinstance(request, DeleteCellRequest):await self.delete(request)elif isinstance(request, InstallMissingPackagesRequest):await self.install_missing_packages(request)diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.pyindex f7124e7bba..26d2219341 100644--- a/marimo/_server/api/endpoints/editing.py+++ b/marimo/_server/api/endpoints/editing.py@@ -5,9 +5,10 @@ from typing import TYPE_CHECKINGfrom starlette.authentication import requires+from marimo._messaging.ops import UpdateCellIdsRequestfrom marimo._runtime.requests import (CodeCompletionRequest,- DeleteRequest,+ DeleteCellRequest,InstallMissingPackagesRequest,SetCellConfigRequest,)@@ -62,7 +63,7 @@ async def delete_cell(request: Request) -> BaseResponse:content:application/json:schema:- $ref: "#/components/schemas/DeleteRequest"+ $ref: "#/components/schemas/DeleteCellRequest"responses:200:description: Delete a cell@@ -72,12 +73,35 @@ async def delete_cell(request: Request) -> BaseResponse:$ref: "#/components/schemas/SuccessResponse""""app_state = AppState(request)- body = await parse_request(request, cls=DeleteRequest)+ body = await parse_request(request, cls=DeleteCellRequest)app_state.require_current_session().put_control_request(body)return SuccessResponse()[email protected]("/sync/cell_ids")+@requires("edit")+async def sync_cell_ids(request: Request) -> BaseResponse:+ """+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/UpdateCellIdsRequest"+ responses:+ 200:+ description: Sync cell ids+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/SuccessResponse"+ """+ app_state = AppState(request)+ body = await parse_request(request, cls=UpdateCellIdsRequest)+ app_state.require_current_session().write_operation(body)+ return SuccessResponse()++@router.post("/format")@requires("edit")async def format_cell(request: Request) -> FormatResponse:diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex 63a0edfbf9..89712eb2eb 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -13,9 +13,13 @@ from marimo._ast.cell import CellConfig, CellId_tfrom marimo._messaging.ops import (Alert,Banner,+ CompletionResult,+ FocusCell,KernelReady,MessageOperation,Reconnected,+ UpdateCellCodes,+ UpdateCellIdsRequest,serialize,)from marimo._messaging.types import KernelMessage, NoopStream@@ -24,6 +28,7 @@ from marimo._plugins.core.web_component import JSONTypefrom marimo._runtime.params import QueryParamsfrom marimo._server.api.deps import AppStatefrom marimo._server.file_router import MarimoFileKey+from marimo._server.ids import ConsumerIdfrom marimo._server.model import (ConnectionState,SessionConsumer,@@ -38,11 +43,13 @@ router = APIRouter()SESSION_QUERY_PARAM_KEY = "session_id"FILE_QUERY_PARAM_KEY = "file"+KIOSK_QUERY_PARAM_KEY = "kiosk"class WebSocketCodes(IntEnum):ALREADY_CONNECTED = 1003NORMAL_CLOSE = 1000+ FORBIDDEN = 1008@router.websocket("/ws")@@ -73,15 +80,28 @@ async def websocket_endpoint()return+ kiosk = app_state.query_params(KIOSK_QUERY_PARAM_KEY) == "true"+await WebsocketHandler(websocket=websocket,manager=app_state.session_manager,session_id=session_id,mode=app_state.mode,file_key=file_key,+ kiosk=kiosk,).start()+KIOSK_ONLY_OPERATIONS = {+ FocusCell.name,+ UpdateCellCodes.name,+ UpdateCellIdsRequest.name,+}+KIOSK_EXCLUDED_OPERATIONS = {+ CompletionResult.name,+}++class WebsocketHandler(SessionConsumer):"""WebSocket that sessions use to send messages to frontends.@@ -96,6 +116,7 @@ class WebsocketHandler(SessionConsumer):session_id: str,mode: SessionMode,file_key: MarimoFileKey,+ kiosk: bool,):self.websocket = websocketself.manager = manager@@ -103,19 +124,23 @@ class WebsocketHandler(SessionConsumer):self.file_key = file_keyself.mode = modeself.status: ConnectionState+ self.kiosk = kioskself.cancel_close_handle: Optional[asyncio.TimerHandle] = Noneself.heartbeat_task: Optional[asyncio.Task[None]] = None# Messages from the kernel are put in this queue# to be sent to the frontendself.message_queue: asyncio.Queue[KernelMessage]- async def _write_kernel_ready(+ super().__init__(consumer_id=ConsumerId(session_id))++ def _write_kernel_ready(self,session: Session,resumed: bool,ui_values: dict[str, JSONType],last_executed_code: dict[CellId_t, str],last_execution_time: dict[CellId_t, float],+ kiosk: bool,) -> None:"""Communicates to the client that the kernel is ready.@@ -157,7 +182,7 @@ class WebsocketHandler(SessionConsumer):last_executed_code = {}last_execution_time = {}- await self.message_queue.put(+ self.message_queue.put_nowait((KernelReady.name,serialize(@@ -172,14 +197,13 @@ class WebsocketHandler(SessionConsumer):last_executed_code=last_executed_code,last_execution_time=last_execution_time,app_config=app.config,+ kiosk=kiosk,)),))- async def _reconnect_session(- self, session: "Session", replay: bool- ) -> None:+ def _reconnect_session(self, session: "Session", replay: bool) -> None:"""Reconnect to an existing session (kernel).A websocket can be closed when a user's computer goes to sleep,@@ -190,14 +214,14 @@ class WebsocketHandler(SessionConsumer):self.cancel_close_handle.cancel()self.status = ConnectionState.OPEN- session.connect_consumer(self)+ session.connect_consumer(self, main=True)# Write reconnected message- await self.write_operation(Reconnected())+ self.write_operation(Reconnected())# If not replaying, just send a toastif not replay:- await self.write_operation(+ self.write_operation(Alert(title="Reconnected",description="You have reconnected to an existing session.",@@ -211,14 +235,15 @@ class WebsocketHandler(SessionConsumer):f"Replaying {len(operations)} operations to the consumer",)- await self._write_kernel_ready(+ self._write_kernel_ready(session=session,resumed=True,ui_values=session.get_current_state().ui_values,last_executed_code=session.get_current_state().last_executed_code,last_execution_time=session.get_current_state().last_execution_time,+ kiosk=self.kiosk,)- await self.write_operation(+ self.write_operation(Banner(title="Reconnected",description="You have reconnected to an existing session.",@@ -227,7 +252,43 @@ class WebsocketHandler(SessionConsumer):for op in operations:LOGGER.debug("Replaying operation %s", serialize(op))- await self.write_operation(op)+ self.write_operation(op)++ def _connect_kiosk(self, session: Session) -> None:+ """Connect to a kiosk session.++ A kiosk session is a write-ish session that is connected to a+ frontend. It can set UI elements and interact with the sidebar,+ but cannot change or execute code. This is not a permission limitation,+ but rather we don't have full multi-player support yet.++ Kiosk mode is useful when the user is using an editor (VSCode or VIM)+ that does not easily support our reactive frontend or our panels.+ The user uses VSCode or VIM to write code, and the+ marimo kiosk/frontend to visualize the output.+ """++ self.status = ConnectionState.OPEN+ session.connect_consumer(self, main=False)++ operations = session.get_current_state().operations+ # Replay the current session view+ LOGGER.debug(+ f"Replaying {len(operations)} operations to the kiosk consumer",+ )++ self._write_kernel_ready(+ session=session,+ resumed=True,+ ui_values=session.get_current_state().ui_values,+ last_executed_code=session.get_current_state().last_executed_code,+ last_execution_time=session.get_current_state().last_execution_time,+ kiosk=True,+ )++ for op in operations:+ LOGGER.debug("Replaying operation %s", serialize(op))+ self.write_operation(op)async def start(self) -> None:# Accept the websocket connection@@ -243,8 +304,10 @@ class WebsocketHandler(SessionConsumer):LOGGER.debug("Existing sessions: %s", mgr.sessions)# Only one frontend can be connected at a time in edit mode.- if mgr.mode == SessionMode.EDIT and mgr.any_clients_connected(- self.file_key+ if (+ mgr.mode == SessionMode.EDIT+ and mgr.any_clients_connected(self.file_key)+ and not self.kiosk):LOGGER.debug("Refusing connection; a frontend is already connected."@@ -256,8 +319,35 @@ class WebsocketHandler(SessionConsumer):)return- async def get_session() -> Session:- # 1. Handle reconnection+ def get_session() -> Session:+ # 1. If we are in kiosk mode, connect to the existing session+ if self.kiosk:+ if self.mode is not SessionMode.EDIT:+ LOGGER.debug("Kiosk mode is only supported in edit mode")+ raise WebSocketDisconnect(+ WebSocketCodes.FORBIDDEN, "MARIMO_KIOSK_NOT_ALLOWED"+ )+ kiosk_session = mgr.get_session(session_id)+ if kiosk_session is None:+ LOGGER.debug(+ "Kiosk session not found for session id %s",+ session_id,+ )+ kiosk_session = mgr.get_session_by_file_key(self.file_key)+ if kiosk_session is None:+ LOGGER.debug(+ "Kiosk session not found for file key %s",+ self.file_key,+ )+ raise WebSocketDisconnect(+ WebSocketCodes.NORMAL_CLOSE, "MARIMO_NO_SESSION"+ )+ self.status = ConnectionState.OPEN+ LOGGER.debug("Connecting to kiosk session")+ self._connect_kiosk(kiosk_session)+ return kiosk_session++ # 2. Handle reconnection# The session already exists, but it was disconnected.# This can happen in local development when the client@@ -268,10 +358,10 @@ class WebsocketHandler(SessionConsumer):LOGGER.debug("Reconnecting session %s", session_id)# In case there is a lingering connection, close itexisting_session.maybe_disconnect_consumer()- await self._reconnect_session(existing_session, replay=False)+ self._reconnect_session(existing_session, replay=False)return existing_session- # 2. Handle resume+ # 3. Handle resume# Get resumable possible resumable sessionresumable_session = mgr.maybe_resume_session(@@ -279,10 +369,10 @@ class WebsocketHandler(SessionConsumer):)if resumable_session is not None:LOGGER.debug("Resuming session %s", session_id)- await self._reconnect_session(resumable_session, replay=True)+ self._reconnect_session(resumable_session, replay=True)return resumable_session- # 3. Create a new session+ # 4. Create a new session# If the client refreshed their page, there will be one# existing session with a closed socket for a different session@@ -308,21 +398,34 @@ class WebsocketHandler(SessionConsumer):)self.status = ConnectionState.OPEN# Let the frontend know it can instantiate the app.- await self._write_kernel_ready(+ self._write_kernel_ready(new_session,resumed=False,ui_values={},last_executed_code={},last_execution_time={},+ kiosk=False,)return new_session- await get_session()+ get_session()async def listen_for_messages() -> None:while True:(op, data) = await self.message_queue.get()try:+ if op in KIOSK_ONLY_OPERATIONS and not self.kiosk:+ LOGGER.debug(+ "Ignoring operation %s, not in kiosk mode",+ op,+ )+ continue+ if op in KIOSK_EXCLUDED_OPERATIONS and self.kiosk:+ LOGGER.debug(+ "Ignoring operation %s, in kiosk mode",+ op,+ )+ continueawait self.websocket.send_text(json.dumps({@@ -354,7 +457,7 @@ class WebsocketHandler(SessionConsumer):# Disconnect the consumersession = self.manager.get_session(self.session_id)if session:- session.disconnect_consumer()+ session.disconnect_consumer(self)if self.manager.mode == SessionMode.RUN:# When the websocket is closed, we wait TTL_SECONDS before@@ -398,23 +501,14 @@ class WebsocketHandler(SessionConsumer):def on_start(self,- check_alive: Callable[[], None],) -> Callable[[KernelMessage], None]:- # Start a heartbeat task- async def _heartbeat() -> None:- while True:- await asyncio.sleep(1)- check_alive()-- self.heartbeat_task = asyncio.create_task(_heartbeat())-def listener(response: KernelMessage) -> None:self.message_queue.put_nowait(response)return listener- async def write_operation(self, op: MessageOperation) -> None:- await self.message_queue.put((op.name, serialize(op)))+ def write_operation(self, op: MessageOperation) -> None:+ self.message_queue.put_nowait((op.name, serialize(op)))def on_stop(self) -> None:# Cancel the heartbeat task, readerdiff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex d48ebf1baa..0af7d4ce7b 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -108,10 +108,7 @@ async def run_app_until_completion(class NoopSessionConsumer(SessionConsumer):def on_start(self,- check_alive: Callable[[], None],) -> Callable[[KernelMessage], None]:- del check_alive-def listener(message: KernelMessage) -> None:if message[0] == "completed-run":instantiated_event.set()@@ -121,7 +118,7 @@ async def run_app_until_completion(def on_stop(self) -> None:pass- async def write_operation(self, op: MessageOperation) -> None:+ def write_operation(self, op: MessageOperation) -> None:passdef connection_state(self) -> ConnectionState:@@ -133,7 +130,7 @@ async def run_app_until_completion(session = Session.create(# Any initialization ID will doinitialization_id="_any_",- session_consumer=NoopSessionConsumer(),+ session_consumer=NoopSessionConsumer(consumer_id="noop"),# Run in EDIT mode so that console outputs are capturedmode=SessionMode.EDIT,app_metadata=AppMetadata(diff --git a/marimo/_server/ids.py b/marimo/_server/ids.pyindex ff954208ab..e2a55e4f6c 100644--- a/marimo/_server/ids.py+++ b/marimo/_server/ids.py@@ -1,2 +1,5 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+SessionId = str+ConsumerId = strdiff --git a/marimo/_server/model.py b/marimo/_server/model.pyindex 94cc0a8c34..03b77c0264 100644--- a/marimo/_server/model.py+++ b/marimo/_server/model.py@@ -5,6 +5,8 @@ import abcfrom enum import Enumfrom typing import TYPE_CHECKING, Callable+from marimo._server.ids import ConsumerId+if TYPE_CHECKING:from marimo._messaging.ops import MessageOperationfrom marimo._messaging.types import KernelMessage@@ -35,10 +37,12 @@ class SessionConsumer(metaclass=abc.ABCMeta):connection types. Currently we consume a session via WebSocket"""+ def __init__(self, consumer_id: ConsumerId) -> None:+ self.consumer_id = consumer_id+@abc.abstractmethoddef on_start(self,- check_alive: Callable[[], None],) -> Callable[[KernelMessage], None]:"""Start the session consumer@@ -51,7 +55,7 @@ class SessionConsumer(metaclass=abc.ABCMeta):raise NotImplementedError@abc.abstractmethod- async def write_operation(self, op: MessageOperation) -> None:+ def write_operation(self, op: MessageOperation) -> None:raise NotImplementedError@abc.abstractmethoddiff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.pyindex d013e6c328..66ea04d5a2 100644--- a/marimo/_server/session/session_view.py+++ b/marimo/_server/session/session_view.py@@ -186,11 +186,15 @@ class SessionView:@propertydef operations(self) -> list[MessageOperation]:- all_ops: list[MessageOperation] = [- self.variable_operations,- VariableValues(variables=list(self.variable_values.values())),- self.datasets,- ]+ all_ops: list[MessageOperation] = []+ if self.variable_operations.variables:+ all_ops.append(self.variable_operations)+ if self.variable_values:+ all_ops.append(+ VariableValues(variables=list(self.variable_values.values()))+ )+ if self.datasets.tables:+ all_ops.append(self.datasets)all_ops.extend(self.cell_operations.values())return all_opsdiff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 6b14c41843..ff4b40be08 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -14,6 +14,7 @@ even if its socket is closed.from __future__ import annotations+import asyncioimport multiprocessing as mpimport osimport queue@@ -25,20 +26,27 @@ import threadingfrom multiprocessing import connectionfrom multiprocessing.queues import Queue as MPQueuefrom pathlib import Path-from typing import Any, Optional+from typing import Any, Dict, Optionalfrom uuid import uuid4from marimo import _loggersfrom marimo._ast.cell import CellConfig, CellId_tfrom marimo._cli.print import redfrom marimo._config.manager import UserConfigManager-from marimo._messaging.ops import Alert, MessageOperation, Reload+from marimo._messaging.ops import (+ Alert,+ FocusCell,+ MessageOperation,+ Reload,+ UpdateCellCodes,+)from marimo._messaging.types import KernelMessagefrom marimo._output.formatters.formatters import register_formattersfrom marimo._runtime import requests, runtimefrom marimo._runtime.requests import (AppMetadata,CreationRequest,+ ExecuteMultipleRequest,ExecutionRequest,SerializedCLIArgs,SerializedQueryParams,@@ -47,7 +55,7 @@ from marimo._runtime.requests import (from marimo._server.exceptions import InvalidSessionExceptionfrom marimo._server.file_manager import AppFileManagerfrom marimo._server.file_router import AppFileRouter, MarimoFileKey-from marimo._server.ids import SessionId+from marimo._server.ids import ConsumerId, SessionIdfrom marimo._server.model import ConnectionState, SessionConsumer, SessionModefrom marimo._server.models.models import InstantiateRequestfrom marimo._server.recents import RecentFilesManager@@ -264,6 +272,58 @@ class KernelManager:return self._read_conn+class Room:+ """+ A room is a collection of SessionConsumers+ that can be used to broadcast messages to all+ of them.+ """++ def __init__(self) -> None:+ self.main_consumer: Optional[SessionConsumer] = None+ self.consumers: Dict[SessionConsumer, ConsumerId] = {}+ self.disposables: Dict[SessionConsumer, Disposable] = {}++ def add_consumer(+ self,+ consumer: SessionConsumer,+ dispose: Disposable,+ consumer_id: ConsumerId,+ # Whether the consumer is the main session consumer+ # We only allow one main consumer, the rest are kiosk consumers+ main: bool,+ ) -> None:+ self.consumers[consumer] = consumer_id+ self.disposables[consumer] = dispose+ if main:+ assert (+ self.main_consumer is None+ ), "Main session consumer already exists"+ self.main_consumer = consumer++ def remove_consumer(self, consumer: SessionConsumer) -> None:+ assert consumer in self.consumers, "Consumer not in room"++ if consumer == self.main_consumer:+ self.main_consumer = None+ self.consumers.pop(consumer)+ disposable = self.disposables.pop(consumer)+ consumer.on_stop()+ disposable.dispose()++ def broadcast(self, operation: MessageOperation) -> None:+ for consumer in self.consumers:+ consumer.write_operation(operation)++ def close(self) -> None:+ for consumer in self.consumers:+ disposable = self.disposables.pop(consumer)+ consumer.on_stop()+ disposable.dispose()+ self.consumers = {}+ self.main_consumer = None++class Session:"""A client session.@@ -284,6 +344,9 @@ class Session:user_config_manager: UserConfigManager,virtual_files_supported: bool,) -> Session:+ """+ Create a new session.+ """configs = app_file_manager.app.cell_manager.config_map()use_multiprocessing = mode == SessionMode.EDITqueue_manager = QueueManager(use_multiprocessing)@@ -318,9 +381,7 @@ class Session:self.initialization_id = initialization_idself._queue_manager: QueueManagerself.app_file_manager = app_file_manager- # This can be optional in case a consumer gets disconnected,- # and we want to continue the session without a consumer.- self.session_consumer: Optional[SessionConsumer] = None+ self.room = Room()self._queue_manager = queue_managerself.kernel_manager = kernel_managerself.session_view = SessionView()@@ -334,84 +395,135 @@ class Session:self.message_distributor.add_consumer(lambda msg: self.session_view.add_raw_operation(msg[1]))- self.connect_consumer(session_consumer)+ self.connect_consumer(session_consumer, main=True)+self.message_distributor.start()+ self.heartbeat_task: Optional[asyncio.Task[Any]] = None+ self._start_heartbeat()+ self._closed = False++ def _start_heartbeat(self) -> None:+ def _check_alive() -> None:+ if not self.kernel_manager.is_alive():+ LOGGER.debug("Closing session because kernel died")+ self.close()+ print()+ print_tabbed(red("The Python kernel died unexpectedly."))+ print()+ sys.exit()++ # Start a heartbeat task, which checks if the kernel is alive+ # every second++ async def _heartbeat() -> None:+ while True:+ await asyncio.sleep(1)+ _check_alive()- def _check_alive(self) -> None:- if not self.kernel_manager.is_alive():- LOGGER.debug("Closing session because kernel died")- self.close()- print()- print_tabbed(red("The Python kernel died unexpectedly."))- print()- sys.exit()+ try:+ loop = asyncio.get_event_loop()+ self.heartbeat_task = loop.create_task(_heartbeat())+ except RuntimeError:+ # This can happen if there is no event loop running+ self.heartbeat_task = Nonedef try_interrupt(self) -> None:+ """Try to interrupt the kernel."""self.kernel_manager.interrupt_kernel()def put_control_request(self, request: requests.ControlRequest) -> None:+ """Put a control request in the control queue."""self._queue_manager.control_queue.put(request)if isinstance(request, SetUIElementValueRequest):self._queue_manager.set_ui_element_queue.put(request)+ # Propagate the control request to the room+ if isinstance(request, ExecuteMultipleRequest):+ self.room.broadcast(+ UpdateCellCodes(+ cell_ids=request.cell_ids,+ codes=request.codes,+ )+ )+ if len(request.cell_ids) == 1:+ self.room.broadcast(FocusCell(cell_id=request.cell_ids[0]))self.session_view.add_control_request(request)def put_completion_request(self, request: requests.CodeCompletionRequest) -> None:+ """Put a code completion request in the completion queue."""self._queue_manager.completion_queue.put(request)def put_input(self, text: str) -> None:+ """Put an input() request in the input queue."""self._queue_manager.input_queue.put(text)self.session_view.add_stdin(text)- def disconnect_consumer(self) -> None:- """Stop the session consumer but keep the kernel running"""- assert (- self.session_consumer is not None- ), "Expecting a session consumer to pause"- LOGGER.debug("Disconnecting session consumer")- self.session_consumer.on_stop()- self.unsubscribe_consumer()- self.session_consumer = None+ def disconnect_consumer(self, session_consumer: SessionConsumer) -> None:+ """+ Stop the session consumer but keep the kernel running.- def maybe_disconnect_consumer(self) -> None:- if self.session_consumer is not None:- self.disconnect_consumer()+ This will disconnect the main session consumer,+ or a kiosk consumer.+ """+ self.room.remove_consumer(session_consumer)- def connect_consumer(self, session_consumer: SessionConsumer) -> None:- """Connect or resume the session with a new consumer"""- assert (- self.session_consumer is None- ), "Expecting no existing session consumer"+ def maybe_disconnect_consumer(self) -> None:+ """+ Disconnect the main session consumer if it connected.+ """+ if self.room.main_consumer is not None:+ self.disconnect_consumer(self.room.main_consumer)- self.session_consumer = session_consumer+ def connect_consumer(+ self, session_consumer: SessionConsumer, *, main: bool+ ) -> None:+ """+ Connect or resume the session with a new consumer.- subscribe = self.session_consumer.on_start(self._check_alive)- self.unsubscribe_consumer = self.message_distributor.add_consumer(- subscribe+ If its the main consumer and one already exists,+ an exception is raised.+ """+ subscribe = session_consumer.on_start()+ unsubscribe_consumer = self.message_distributor.add_consumer(subscribe)+ self.room.add_consumer(+ session_consumer,+ unsubscribe_consumer,+ session_consumer.consumer_id,+ main=main,)def get_current_state(self) -> SessionView:+ """Return the current state of the session."""return self.session_viewdef connection_state(self) -> ConnectionState:- if self.session_consumer is None:+ """Return the connection state of the session."""+ if self._closed:+ return ConnectionState.CLOSED+ if self.room.main_consumer is None:return ConnectionState.ORPHANED- return self.session_consumer.connection_state()+ return self.room.main_consumer.connection_state()- async def write_operation(self, operation: MessageOperation) -> None:+ def write_operation(self, operation: MessageOperation) -> None:+ """Write an operation to the session consumer and the session view."""self.session_view.add_operation(operation)- if self.session_consumer is not None:- await self.session_consumer.write_operation(operation)+ self.room.broadcast(operation)def close(self) -> None:- # Could be no consumer if we already disconnect, but the session- # is running in the background- if self.session_consumer is not None:- self.session_consumer.on_stop()+ """+ Close the session.++ This will close the session consumer, kernel, and all kiosk consumers.+ """+ self._closed = True+ # Close the room+ self.room.close()+ # Close the kernelself.message_distributor.stop()+ if self.heartbeat_task:+ self.heartbeat_task.cancel()self.kernel_manager.close_kernel()- self.unsubscribe_consumer()def instantiate(self, request: InstantiateRequest) -> None:"""Instantiate the app."""@@ -436,7 +548,7 @@ class Session:self,{"connection_state": self.connection_state(),- "consumer": self.session_consumer,+ "room": self.room,},)@@ -547,7 +659,24 @@ class SessionManager:return self.sessions[session_id]def get_session(self, session_id: SessionId) -> Optional[Session]:- return self.sessions.get(session_id)+ session = self.sessions.get(session_id)+ if session:+ return session++ # Search for kiosk sessions+ for session in self.sessions.values():+ if session_id in session.room.consumers.values():+ return session++ return None++ def get_session_by_file_key(+ self, file_key: MarimoFileKey+ ) -> Optional[Session]:+ for session in self.sessions.values():+ if session.initialization_id == file_key:+ return session+ return Nonedef maybe_resume_session(self, new_session_id: SessionId, file_key: MarimoFileKey@@ -618,6 +747,15 @@ class SessionManager:return Truereturn False+ def get_session_for_key(self, key: MarimoFileKey) -> Optional[Session]:+ for session in self.sessions.values():+ if (+ session.app_file_manager.path == os.path.abspath(key)+ or session.initialization_id == key+ ) and session.connection_state() == ConnectionState.OPEN:+ return session+ return None+async def start_lsp_server(self) -> None:"""Starts the lsp server if it is not already started.@@ -631,7 +769,7 @@ class SessionManager:if alert is not None:for _, session in self.sessions.items():- await session.write_operation(alert)+ session.write_operation(alert)returndef close_session(self, session_id: SessionId) -> bool:@@ -681,7 +819,7 @@ class SessionManager:LOGGER.debug(f"{path} was modified")for _, session in self.sessions.items():session.app_file_manager.reload()- await session.write_operation(Reload())+ session.write_operation(Reload())LOGGER.debug("Starting file watcher for %s", file_path)self.watcher = FileWatcher.create(Path(file_path), on_file_changed)diff --git a/openapi/api.yaml b/openapi/api.yamlindex f6bb289824..fe2093a971 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -394,6 +394,13 @@ components:- tables- nametype: object+ DeleteCellRequest:+ properties:+ cellId:+ type: string+ required:+ - cellId+ type: objectDeleteNonlocalError:properties:cells:@@ -411,13 +418,6 @@ components:- cells- typetype: object- DeleteRequest:- properties:- cellId:- type: string- required:- - cellId- type: objectError:oneOf:- $ref: '#/components/schemas/CycleError'@@ -646,6 +646,18 @@ components:required:- successtype: object+ FocusCell:+ properties:+ cell_id:+ type: string+ name:+ enum:+ - focus-cell+ type: string+ required:+ - cell_id+ - name+ type: objectFormatRequest:properties:codes:@@ -805,6 +817,8 @@ components:items:$ref: '#/components/schemas/CellConfig'type: array+ kiosk:+ type: booleanlast_executed_code:additionalProperties:type: string@@ -861,6 +875,7 @@ components:- configs- resumed- app_config+ - kiosk- nametype: objectMIME:@@ -1156,6 +1171,9 @@ components:- $ref: '#/components/schemas/QueryParamsClear'- $ref: '#/components/schemas/Datasets'- $ref: '#/components/schemas/DataColumnPreview'+ - $ref: '#/components/schemas/FocusCell'+ - $ref: '#/components/schemas/UpdateCellCodes'+ - $ref: '#/components/schemas/UpdateCellIdsRequest'MimeType:enum:- application/json@@ -1521,6 +1539,39 @@ components:- msg- typetype: object+ UpdateCellCodes:+ properties:+ cell_ids:+ items:+ type: string+ type: array+ codes:+ items:+ type: string+ type: array+ name:+ enum:+ - update-cell-codes+ type: string+ required:+ - cell_ids+ - codes+ - name+ type: object+ UpdateCellIdsRequest:+ properties:+ cell_ids:+ items:+ type: string+ type: array+ name:+ enum:+ - update-cell-ids+ type: string+ required:+ - cell_ids+ - name+ type: objectUpdateComponentValuesRequest:properties:objectIds:@@ -1869,7 +1920,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/DeleteRequest'+ $ref: '#/components/schemas/DeleteCellRequest'responses:200:content:@@ -2101,6 +2152,20 @@ paths:schema:$ref: '#/components/schemas/SuccessResponse'description: Send input to the stdin stream+ /api/kernel/sync/cell_ids:+ post:+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/UpdateCellIdsRequest'+ responses:+ 200:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SuccessResponse'+ description: Sync cell ids/api/status:get:responses:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex b377323d73..cda8de4f38 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -330,7 +330,7 @@ export interface paths {post: {requestBody?: {content: {- "application/json": components["schemas"]["DeleteRequest"];+ "application/json": components["schemas"]["DeleteCellRequest"];};};responses: {@@ -620,6 +620,23 @@ export interface paths {};};};+ "/api/kernel/sync/cell_ids": {+ post: {+ requestBody?: {+ content: {+ "application/json": components["schemas"]["UpdateCellIdsRequest"];+ };+ };+ responses: {+ /** @description Sync cell ids */+ 200: {+ content: {+ "application/json": components["schemas"]["SuccessResponse"];+ };+ };+ };+ };+ };"/api/status": {get: {responses: {@@ -872,15 +889,15 @@ export interface components {name: "datasets";tables: components["schemas"]["DataTable"][];};+ DeleteCellRequest: {+ cellId: string;+ };DeleteNonlocalError: {cells: string[];name: string;/** @enum {string} */type: "delete-nonlocal";};- DeleteRequest: {- cellId: string;- };Error:| components["schemas"]["CycleError"]| components["schemas"]["MultipleDefinitionError"]@@ -973,6 +990,11 @@ export interface components {message?: string | null;success: boolean;};+ FocusCell: {+ cell_id: string;+ /** @enum {string} */+ name: "focus-cell";+ };FormatRequest: {codes: {[key: string]: string;@@ -1040,6 +1062,7 @@ export interface components {cell_ids: string[];codes: string[];configs: components["schemas"]["CellConfig"][];+ kiosk: boolean;last_executed_code?: {[key: string]: string;} | null;@@ -1190,7 +1213,10 @@ export interface components {| components["schemas"]["QueryParamsDelete"]| components["schemas"]["QueryParamsClear"]| components["schemas"]["Datasets"]- | components["schemas"]["DataColumnPreview"];+ | components["schemas"]["DataColumnPreview"]+ | components["schemas"]["FocusCell"]+ | components["schemas"]["UpdateCellCodes"]+ | components["schemas"]["UpdateCellIdsRequest"];/** @enum {string} */MimeType:| "application/json"@@ -1338,6 +1364,17 @@ export interface components {/** @enum {string} */type: "unknown";};+ UpdateCellCodes: {+ cell_ids: string[];+ codes: string[];+ /** @enum {string} */+ name: "update-cell-codes";+ };+ UpdateCellIdsRequest: {+ cell_ids: string[];+ /** @enum {string} */+ name: "update-cell-ids";+ };UpdateComponentValuesRequest: {objectIds: string[];values: unknown[];diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex e5458b641b..f6764b9179 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -20,7 +20,7 @@ from marimo._runtime.dataflow import EdgeWithVarfrom marimo._runtime.requests import (AppMetadata,CreationRequest,- DeleteRequest,+ DeleteCellRequest,ExecutionRequest,SetCellConfigRequest,SetUIElementValueRequest,@@ -89,7 +89,7 @@ class TestExecution:await k.run([er2])assert k.globals["z"] == 2- await k.delete(DeleteRequest(cell_id="1"))+ await k.delete(DeleteCellRequest(cell_id="1"))assert k.globals["x"] == 2assert "y" not in k.globalsif k.lazy():@@ -97,7 +97,7 @@ class TestExecution:await k.run([er2])assert "z" not in k.globals- await k.delete(DeleteRequest(cell_id="0"))+ await k.delete(DeleteCellRequest(cell_id="0"))assert "x" not in k.globalsassert "y" not in k.globalsassert "z" not in k.globals@@ -384,7 +384,7 @@ class TestExecution:assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)# issue delete request for cell 1 to clear error and run cell 0- await k.delete(DeleteRequest(cell_id="1"))+ await k.delete(DeleteCellRequest(cell_id="1"))if k.lazy():assert k.graph.cells[er.cell_id].staleawait k.run([er])@@ -464,7 +464,7 @@ class TestExecution:_check_edges(k.errors["0"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])# break cycle by deleting cell- await k.delete(DeleteRequest(cell_id="1"))+ await k.delete(DeleteCellRequest(cell_id="1"))assert not k.errorsasync def test_delete_nonlocal_error(self, any_kernel: Kernel) -> None:@@ -507,7 +507,7 @@ class TestExecution:# Delete the cell that defines x. There shouldn't be any more errors# because x no longer exists.- await k.delete(DeleteRequest(cell_id="0"))+ await k.delete(DeleteCellRequest(cell_id="0"))assert not k.errors# Add x back in.diff --git a/tests/_runtime/test_virtual_file.py b/tests/_runtime/test_virtual_file.pyindex cffe5277ab..cb60f480ee 100644--- a/tests/_runtime/test_virtual_file.py+++ b/tests/_runtime/test_virtual_file.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom marimo._runtime.context import get_context-from marimo._runtime.requests import DeleteRequest+from marimo._runtime.requests import DeleteCellRequestfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider@@ -48,7 +48,7 @@ async def test_virtual_file_deletion(for fname, _ in get_context().virtual_file_registry.registry.items():assert fname.endswith(".pdf")- await k.delete(DeleteRequest(cell_id=er.cell_id))+ await k.delete(DeleteCellRequest(cell_id=er.cell_id))assert not get_context().virtual_file_registry.registry@@ -89,8 +89,8 @@ async def test_cached_virtual_file_not_deleted(assert len(get_context().virtual_file_registry.registry) == 2# Remove the cells that create the vfiles- await k.delete(DeleteRequest(cell_id=create_vfile_1.cell_id))- await k.delete(DeleteRequest(cell_id=create_vfile_2.cell_id))+ await k.delete(DeleteCellRequest(cell_id=create_vfile_1.cell_id))+ await k.delete(DeleteCellRequest(cell_id=create_vfile_2.cell_id))# Reset the vfile cacheawait k.run([vfile_cache])@@ -124,7 +124,7 @@ async def test_cell_deletion_clears_vfiles(assert len(get_context().virtual_file_registry.registry) == 1# Delete the vfile cache: virtual file registry should be empty- await k.delete(DeleteRequest(cell_id=vfile_cache.cell_id))+ await k.delete(DeleteCellRequest(cell_id=vfile_cache.cell_id))assert len(get_context().virtual_file_registry.registry) == 0diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.pynew file mode 100644index 0000000000..989ca51316--- /dev/null+++ b/tests/_server/api/endpoints/test_kiosk.py@@ -0,0 +1,152 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING, Any, Optional++from marimo._messaging.ops import KernelReady+from marimo._utils.parse_dataclass import parse_raw+from tests._server.mocks import token_header++if TYPE_CHECKING:+ from starlette.testclient import TestClient, WebSocketTestSession+++def create_response(+ partial_response: dict[str, Any],+) -> dict[str, Any]:+ response: dict[str, Any] = {+ "cell_ids": ["Hbol"],+ "codes": ["import marimo as mo"],+ "names": ["__"],+ "layout": None,+ "resumed": False,+ "ui_values": {},+ "last_executed_code": {},+ "last_execution_time": {},+ "kiosk": False,+ "configs": [{"disabled": False, "hide_code": False}],+ "app_config": {"width": "full"},+ }+ response.update(partial_response)+ return response+++HEADERS = {+ **token_header("fake-token"),+ "Marimo-Session-Id": "123",+}+++def assert_kernel_ready_response(+ raw_data: dict[str, Any], response: Optional[dict[str, Any]] = None+) -> None:+ if response is None:+ response = create_response({})+ data = parse_raw(raw_data["data"], KernelReady)+ expected = parse_raw(response, KernelReady)+ assert data.cell_ids == expected.cell_ids+ assert data.codes == expected.codes+ assert data.names == expected.names+ assert data.layout == expected.layout+ assert data.resumed == expected.resumed+ assert data.ui_values == expected.ui_values+ assert data.configs == expected.configs+ assert data.app_config == expected.app_config+ assert data.kiosk == expected.kiosk+++def assert_parse_ready_response(raw_data: dict[str, Any]) -> None:+ data = parse_raw(raw_data["data"], KernelReady)+ assert data is not None+++async def test_connect_kiosk_with_session(client: TestClient) -> None:+ # Create the first session+ with client.websocket_connect("/ws?session_id=123") as websocket:+ data = websocket.receive_json()+ assert_kernel_ready_response(data)++ # Connect in kiosk mode+ with client.websocket_connect(+ "/ws?session_id=456&kiosk=true"+ ) as other_websocket:+ data = other_websocket.receive_json()+ assert_kernel_ready_response(+ data, create_response({"kiosk": True, "resumed": True})+ )++ # Send sync cell_ids+ response = client.post(+ "/api/kernel/sync/cell_ids",+ headers=HEADERS,+ json={"cell_ids": ["cell-123"]},+ )+ assert response.status_code == 200, response.text++ # Assert kiosk session received the sync cell_ids+ data = other_websocket.receive_json()+ assert data == {+ "op": "update-cell-ids",+ "data": {"cell_ids": ["cell-123"]},+ }++ # Send run cell+ response = client.post(+ "/api/kernel/run",+ headers=HEADERS,+ json={+ "cell_ids": ["cell-1", "cell-2"],+ "codes": [+ "print('Hello, cell-1')",+ "print('Hello, cell-2')",+ ],+ },+ )++ # Assert kiosk session received the updated cell codes+ data = other_websocket.receive_json()+ assert data == {+ "op": "update-cell-codes",+ "data": {+ "cell_ids": ["cell-1", "cell-2"],+ "codes": [+ "print('Hello, cell-1')",+ "print('Hello, cell-2')",+ ],+ },+ }++ # Send run single cell+ response = client.post(+ "/api/kernel/run",+ headers=HEADERS,+ json={+ "cell_ids": ["cell-3"],+ "codes": ["print('Hello, cell-3')"],+ },+ )++ # Assert kiosk session received the updated cell codes+ data = _receive_until("update-cell-codes", other_websocket)+ assert data == {+ "op": "update-cell-codes",+ "data": {+ "cell_ids": ["cell-3"],+ "codes": ["print('Hello, cell-3')"],+ },+ }+ # And a focused cell+ data = _receive_until("focus-cell", other_websocket)+ assert data == {+ "op": "focus-cell",+ "data": {"cell_id": "cell-3"},+ }++ client.post("/api/kernel/shutdown", headers=HEADERS)+++def _receive_until(op: str, websocket: WebSocketTestSession) -> dict[str, Any]:+ while True:+ data = websocket.receive_json()+ if data["op"] == op:+ return datadiff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pyindex 777be60619..cd328f26ff 100644--- a/tests/_server/api/endpoints/test_resume_session.py+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -26,6 +26,7 @@ def create_response("ui_values": {},"last_executed_code": {},"last_execution_time": {},+ "kiosk": False,"configs": [{"disabled": False, "hide_code": False}],"app_config": {"width": "full"},}diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex bbfee468b6..179d09f281 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -8,6 +8,7 @@ import pytestfrom starlette.websockets import WebSocketDisconnectfrom marimo._messaging.ops import KernelReady+from marimo._server.api.endpoints.ws import WebSocketCodesfrom marimo._server.model import SessionModefrom marimo._server.sessions import SessionManagerfrom marimo._utils.parse_dataclass import parse_raw@@ -30,6 +31,7 @@ def create_response("ui_values": {},"last_executed_code": {},"last_execution_time": {},+ "kiosk": False,"configs": [{"disabled": False, "hide_code": False}],"app_config": {"width": "full"},}@@ -57,6 +59,7 @@ def assert_kernel_ready_response(assert data.ui_values == expected.ui_valuesassert data.configs == expected.configsassert data.app_config == expected.app_config+ assert data.kiosk == expected.kioskdef assert_parse_ready_response(raw_data: dict[str, Any]) -> None:@@ -152,7 +155,6 @@ def test_fails_on_multiple_connections_with_same_file(client.post("/api/kernel/shutdown", headers=HEADERS)async def test_file_watcher_calls_reload(client: TestClient) -> None:session_manager: SessionManager = get_session_manager(client)with client.websocket_connect("/ws?session_id=123") as websocket:@@ -174,7 +176,6 @@ async def test_file_watcher_calls_reload(client: TestClient) -> None:client.post("/api/kernel/shutdown", headers=HEADERS)async def test_query_params(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123&foo=1&bar=2&bar=3&baz=4"@@ -190,3 +191,56 @@ async def test_query_params(client: TestClient) -> None:"baz": "4",}client.post("/api/kernel/shutdown", headers=HEADERS)+++async def test_connect_kiosk_without_session(client: TestClient) -> None:+ with pytest.raises(WebSocketDisconnect) as exc_info: # noqa: PT012+ with client.websocket_connect(+ "/ws?session_id=123&kiosk=true"+ ) as websocket:+ websocket.receive_json()+ raise AssertionError()+ assert exc_info.value.code == WebSocketCodes.NORMAL_CLOSE+ assert exc_info.value.reason == "MARIMO_NO_SESSION"+ client.post("/api/kernel/shutdown", headers=HEADERS)+++async def test_connect_kiosk_with_session(client: TestClient) -> None:+ # Create the first session+ with client.websocket_connect("/ws?session_id=123") as websocket:+ data = websocket.receive_json()+ assert_kernel_ready_response(data)++ # Connect by the same session id in kiosk mode+ with client.websocket_connect(+ "/ws?session_id=123&kiosk=true"+ ) as other_websocket:+ data = other_websocket.receive_json()+ assert_kernel_ready_response(+ data, create_response({"kiosk": True, "resumed": True})+ )+ client.post("/api/kernel/shutdown", headers=HEADERS)+++async def test_cannot_connect_kiosk_with_run_session(+ client: TestClient,+) -> None:+ # Create the first session+ session_manager = get_session_manager(client)+ session_manager.mode = SessionMode.RUN+ with client.websocket_connect("/ws?session_id=123") as websocket:+ data = websocket.receive_json()+ assert_kernel_ready_response(data)++ # Connect by the same session id in kiosk mode+ with pytest.raises(WebSocketDisconnect) as exc_info: # noqa: PT012+ with client.websocket_connect(+ "/ws?session_id=123&kiosk=true"+ ) as other_websocket:+ data = other_websocket.receive_json()+ raise AssertionError()+ assert exc_info.value.code == WebSocketCodes.FORBIDDEN+ assert exc_info.value.reason == "MARIMO_KIOSK_NOT_ALLOWED"++ client.post("/api/kernel/shutdown", headers=HEADERS)+ session_manager.mode = SessionMode.EDITdiff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.pyindex e22a48eb64..7dd0277cf7 100644--- a/tests/_server/test_file_manager.py+++ b/tests/_server/test_file_manager.py@@ -108,14 +108,17 @@ def test_rename_create_new_file(app_file_manager: AppFileManager) -> None:def test_rename_different_filetype(app_file_manager: AppFileManager) -> None:initial_filename = app_file_manager.filename+ assert initial_filenameassert initial_filename.endswith(".py")- with open(app_file_manager.filename, "r") as f:+ with open(initial_filename, "r") as f:contents = f.read()assert "app = marimo.App()" in contentsassert "marimo-version" not in contentsapp_file_manager.rename(initial_filename[:-3] + ".md")- assert app_file_manager.filename.endswith(".md")- with open(app_file_manager.filename, "r") as f:+ next_filename = app_file_manager.filename+ assert next_filename+ assert next_filename.endswith(".md")+ with open(next_filename, "r") as f:contents = f.read()assert "marimo-version" in contentsassert "app = marimo.App()" not in contentsdiff --git a/tests/_server/test_session_manager.py b/tests/_server/test_session_manager.pyindex f7e90867c6..95878274bf 100644--- a/tests/_server/test_session_manager.py+++ b/tests/_server/test_session_manager.py@@ -14,7 +14,9 @@ from marimo._server.sessions import LspServer, Session, SessionManager@pytest.fixturedef mock_session_consumer():- return Mock(spec=SessionConsumer)+ mock = Mock(spec=SessionConsumer)+ mock.consumer_id = "test_consumer_id"+ return mock@pytest.fixturediff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex 200c6ffe23..d2e4162fca 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -202,7 +202,7 @@ def test_session() -> None:)# Assert startup- assert session.session_consumer == session_consumer+ assert session.room.main_consumer == session_consumerassert session._queue_manager == queue_managerassert session.kernel_manager == kernel_managersession_consumer.on_start.assert_called_once()@@ -210,7 +210,6 @@ def test_session() -> None:assert session.connection_state() == ConnectionState.OPENsession.close()- session_consumer.connection_state.return_value = ConnectionState.CLOSED# Assert shutdownassert kernel_manager.kernel_task is not None@@ -247,22 +246,22 @@ def test_session_disconnect_reconnect() -> None:)# Assert startup- assert session.session_consumer == session_consumer+ assert session.room.main_consumer == session_consumersession_consumer.on_start.assert_called_once()assert session_consumer.on_stop.call_count == 0- session.disconnect_consumer()+ session.disconnect_consumer(session_consumer)# Assert shutdown of consumer- assert session.session_consumer is None+ assert session.room.main_consumer is Nonesession_consumer.on_start.assert_called_once()session_consumer.on_stop.assert_called_once()assert session.connection_state() == ConnectionState.ORPHANED# Reconnectnew_session_consumer = MagicMock()- session.connect_consumer(new_session_consumer)- assert session.session_consumer == new_session_consumer+ session.connect_consumer(new_session_consumer, main=True)+ assert session.room.main_consumer == new_session_consumernew_session_consumer.on_start.assert_called_once()assert new_session_consumer.on_stop.call_count == 0@@ -276,3 +275,65 @@ def test_session_disconnect_reconnect() -> None:new_session_consumer.on_start.assert_called_once()new_session_consumer.on_stop.assert_called_once()assert session.connection_state() == ConnectionState.CLOSED+++@save_and_restore_main+def test_session_with_kiosk_consumers() -> None:+ session_consumer: Any = MagicMock()+ session_consumer.connection_state.return_value = ConnectionState.OPEN+ queue_manager = QueueManager(use_multiprocessing=False)+ kernel_manager = KernelManager(+ queue_manager,+ SessionMode.RUN,+ {},+ app_metadata,+ UserConfigManager(),+ virtual_files_supported=True,+ )++ # Instantiate a Session+ session = Session(+ "test",+ session_consumer,+ queue_manager,+ kernel_manager,+ AppFileManager.from_app(InternalApp(App())),+ )++ # Assert startup+ assert session.room.main_consumer == session_consumer+ assert session._queue_manager == queue_manager+ assert session.kernel_manager == kernel_manager+ session_consumer.on_start.assert_called_once()+ assert session_consumer.on_stop.call_count == 0+ assert session.connection_state() == ConnectionState.OPEN++ # Create a kiosk consumer+ kiosk_consumer: Any = MagicMock()+ kiosk_consumer.connection_state.return_value = ConnectionState.OPEN+ session.connect_consumer(kiosk_consumer, main=False)++ # Assert startup of kiosk consumer+ assert session.room.main_consumer != kiosk_consumer+ assert kiosk_consumer in session.room.consumers+ kiosk_consumer.on_start.assert_called_once()+ assert kiosk_consumer.on_stop.call_count == 0+ assert session.connection_state() == ConnectionState.OPEN++ session.close()+ session_consumer.connection_state.return_value = ConnectionState.CLOSED+ kiosk_consumer.connection_state.return_value = ConnectionState.CLOSED++ # Assert shutdown+ assert kernel_manager.kernel_task is not None+ kernel_manager.kernel_task.join()+ assert not kernel_manager.is_alive()+ assert queue_manager.input_queue.empty()+ assert queue_manager.control_queue.empty()+ session_consumer.on_start.assert_called_once()+ session_consumer.on_stop.assert_called_once()+ kiosk_consumer.on_start.assert_called_once()+ kiosk_consumer.on_stop.assert_called_once()+ assert session.connection_state() == ConnectionState.CLOSED+ assert not session.room.consumers+ assert session.room.main_consumer is Nonediff --git a/tests/_utils/test_file_watcher.py b/tests/_utils/test_file_watcher.pyindex 0d565148f2..ad891a87e1 100644--- a/tests/_utils/test_file_watcher.py+++ b/tests/_utils/test_file_watcher.py@@ -1,16 +1,15 @@# Test for PollingFileWatcher+from __future__ import annotations+import asyncioimport osfrom pathlib import Pathfrom tempfile import NamedTemporaryFilefrom typing import List-import pytest-from marimo._utils.file_watcher import PollingFileWatcherasync def test_polling_file_watcher() -> None:with NamedTemporaryFile(delete=False) as tmp_file:tmp_path = Path(tmp_file.name)