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
cell config, disabled cells (#105)
Myles Scolnick86746a424b48
diff --git a/frontend/.storybook/preview-head.html b/frontend/.storybook/preview-head.htmlnew file mode 100644index 0000000000..c1c1c65bc8--- /dev/null+++ b/frontend/.storybook/preview-head.html@@ -0,0 +1,7 @@+<marimo-filename hidden>app.py</marimo-filename>+<marimo-mode data-mode="edit" hidden></marimo-mode>+<marimo-user-config+ data-config='{"completion":{"activate_on_typing":false},"save":{"autosave":"off","autosave_delay":0},"keymap":{"preset":"default"},"experimental":{"theming":true}}'+ hidden+></marimo-user-config>+<marimo-app-config data-config="{}" hidden></marimo-app-config>diff --git a/frontend/e2e-tests/disabled.spec.ts b/frontend/e2e-tests/disabled.spec.tsnew file mode 100644index 0000000000..5b8994b632--- /dev/null+++ b/frontend/e2e-tests/disabled.spec.ts@@ -0,0 +1,115 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { test, expect } from "@playwright/test";+import { getAppUrl, resetFile } from "../playwright.config";++const appUrl = getAppUrl("cells.py");+test.beforeEach(async ({ page }, info) => {+ await page.goto(appUrl);+ if (info.retry) {+ await page.reload();+ }+});++test.beforeEach(async () => {+ // Need to reset the file because this test modifies it+ await resetFile("cells.py");+});++test("disabled cells", async ({ page }) => {+ // Can see output / code+ await expect(page.locator("h1").getByText("Cell 1")).toBeVisible();+ await expect(page.locator("h1").getByText("Cell 2")).toBeVisible();++ // No add buttons are visible+ await expect(+ page.getByTestId("create-cell-button").locator(":visible").count()+ ).resolves.toBe(0);++ // Hover over a cell the drag button button appears+ // Click the drag button and then disable the cell+ await page.hover("text=Cell 1");+ await page.getByTestId("drag-button").locator(":visible").first().click();+ await page.getByText("Disable").click();++ // Check the cell status+ await expect(page.getByTitle("This cell is disabled")).toBeVisible();+ await expect(+ page.getByTitle("This cell has a disabled ancestor")+ ).toBeVisible();+ await expect(+ page+ .getByTestId("cell-status")+ .first()+ .evaluate((el) => el.dataset.status)+ ).resolves.toBe("disabled");+ await expect(+ page+ .getByTestId("cell-status")+ .last()+ .evaluate((el) => el.dataset.status)+ ).resolves.toBe("disabled-transitively");++ // Add code to the first cell and save+ // The result should be stale+ await page.click(".cm-editor");+ await page.keyboard.type("\nx = 2");+ await page.getByTestId("run-button").locator(":visible").first().click();+ await expect(page.getByTitle("This cell is disabled")).toBeVisible();+ await expect(+ page.getByTitle("This cell has a disabled ancestor")+ ).toBeVisible();+ await expect(+ page+ .getByTestId("cell-status")+ .first()+ .evaluate((el) => el.dataset.status)+ ).resolves.toBe("stale");+ await expect(+ page+ .getByTestId("cell-status")+ .last()+ .evaluate((el) => el.dataset.status)+ ).resolves.toBe("stale");++ // Disable the second cell+ await page.hover("text=Cell 2");+ await page.getByTestId("drag-button").locator(":visible").first().click();+ await page.getByText("Disable").click();++ // Check they are still stale+ await expect(page.getByTitle("This cell is disabled").count()).resolves.toBe(+ 2+ );+ await expect(+ page+ .getByTestId("cell-status")+ .first()+ .evaluate((el) => el.dataset.status)+ ).resolves.toBe("stale");+ await expect(+ page+ .getByTestId("cell-status")+ .last()+ .evaluate((el) => el.dataset.status)+ ).resolves.toBe("stale");++ // Enable the first+ await page.hover("text=Cell 1");+ await page.getByTestId("drag-button").locator(":visible").first().click();+ await page.getByText("Enable").click();++ // Check the status+ await expect(page.getByTitle("This cell is disabled").count()).resolves.toBe(+ 1+ );++ // Enable the second+ await page.hover("text=Cell 2");+ await page.getByTestId("drag-button").locator(":visible").first().click();+ await page.getByText("Enable").click();++ // Check the status+ await expect(page.getByTitle("This cell is disabled").count()).resolves.toBe(+ 0+ );+});diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 71f88bd154..d3317731d6 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -7,7 +7,6 @@ import { useCallback, useEffect, useState } from "react";import {sendInterrupt,sendRename,- sendRunMultiple,sendSave,sendShutdown,} from "@/core/network/requests";@@ -21,7 +20,6 @@ import { WebSocketState } from "./core/websocket/types";import { useMarimoWebSocket } from "./core/websocket/useMarimoWebSocket";import { useCellActions, useCells } from "./core/state/cells";import { Disconnected } from "./editor/Disconnected";-import { derefNotNull } from "./utils/dereference";import { AppConfig, UserConfig } from "./core/config/config";import { toggleAppMode, viewStateAtom } from "./core/mode";import { useHotkey } from "./hooks/useHotkey";@@ -41,10 +39,12 @@ import { useWindowEventListener } from "./hooks/useEventListener";import { toast } from "./components/ui/use-toast";import { SortableCellsProvider } from "./components/sort/SortableCellsProvider";import { CellId, HTMLCellId } from "./core/model/ids";+import { CellConfig } from "./core/model/cells";import { getFilenameFromDOM } from "./core/dom/htmlUtils";import { CellArray } from "./editor/renderers/CellArray";import { RuntimeState } from "./core/RuntimeState";import { useAtom } from "jotai";+import { useRunStaleCells } from "./editor/cell/useRunCells";interface AppProps {userConfig: UserConfig;@@ -57,6 +57,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {const [viewState, setViewState] = useAtom(viewStateAtom);const [filename, setFilename] = useState(getFilenameFromDOM());const [savedCodes, setSavedCodes] = useState<string[]>([""]);+ const [savedConfigs, setSavedConfigs] = useState<CellConfig[]>([]);const { openModal, closeModal, openAlert } = useImperativeModal();const isEditing = viewState.mode === "edit";@@ -79,6 +80,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {const { connStatus } = useMarimoWebSocket({setCells,setInitialCodes: setSavedCodes,+ setInitialConfigs: setSavedConfigs,sessionId: UUID,});@@ -103,9 +105,12 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {const codes = cells.present.map((cell) => cell.code);const cellNames = cells.present.map((cell) => cell.name);+ const configs = cells.present.map((cell) => cell.config);const needsSave =savedCodes.length !== codes.length ||- savedCodes.some((code, index) => codes[index] !== code);+ savedCodes.some((code, index) => codes[index] !== code) ||+ savedConfigs.length !== configs.length ||+ savedConfigs.some((config, index) => configs[index] !== config);// Save the notebook with the given filenameconst saveNotebook = useEvent((filename: string, showToast: boolean) => {@@ -126,12 +131,13 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {}Logger.log("saving to ", filename);- sendSave(codes, cellNames, filename)+ sendSave({ codes, names: cellNames, filename, configs }).then(() => {if (showToast) {toast({ title: "Notebook saved" });}setSavedCodes(codes);+ setSavedConfigs(configs);}).catch((error) => {openAlert(error.message);@@ -163,9 +169,10 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {useAutoSave({// Only run autosave if the file is namedonSave: saveIfNotebookIsNamed,- // Reset autosave when needsSave or codes have changed+ // Reset autosave when needsSave, or codes/configs have changedneedsSave: needsSave,codes: codes,+ cellConfigs: configs,connStatus: connStatus,config: userConfig,});@@ -197,22 +204,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {});};- const runStaleCells = useEvent(() => {- const cellIds: CellId[] = [];- const codes: string[] = [];- for (const cell of cells.present) {- if (cell.edited || cell.interrupted) {- cellIds.push(cell.key);- codes.push(derefNotNull(cell.ref).editorView.state.doc.toString());- derefNotNull(cell.ref).registerRun();- }- }-- if (cellIds.length > 0) {- RuntimeState.INSTANCE.registerRunStart();- sendRunMultiple(cellIds, codes);- }- });+ const runStaleCells = useRunStaleCells();// Toggle the array's presenting state, and sets a cell to anchor scrolling toconst togglePresenting = useCallback(() => {@@ -249,7 +241,9 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {}, [setViewState]);// HOTKEYS- useHotkey("global.runStale", runStaleCells);+ useHotkey("global.runStale", () => {+ runStaleCells();+ });useHotkey("global.save", saveOrNameNotebook);useHotkey("global.interrupt", () => {sendInterrupt();diff --git a/frontend/src/components/export/menu-dropdown.tsx b/frontend/src/components/export/menu-dropdown.tsxdeleted file mode 100644index 33582478fc..0000000000--- a/frontend/src/components/export/menu-dropdown.tsx+++ /dev/null@@ -1,76 +0,0 @@-/* Copyright 2023 Marimo. All rights reserved. */-import { Button } from "@/editor/inputs/Inputs";-import { CommandIcon, ImageIcon, MenuIcon } from "lucide-react";-import React from "react";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import { downloadHTMLAsImage } from "@/utils/download";-import { commandPalletteAtom } from "@/editor/CommandPallette";-import { useSetAtom } from "jotai";-import { HotkeyAction } from "@/core/hotkeys/hotkeys";-import { renderMinimalShortcut } from "../shortcuts/renderShortcut";-import { runDuringPresentMode } from "@/core/mode";--interface Props {- filename: string | null;-}--interface Action {- label: string;- hotkey?: HotkeyAction;- icon?: React.ReactNode;- handle: () => void;-}--export const MenuDropdown: React.FC<Props> = ({ filename }) => {- const setCommandPalletteOpen = useSetAtom(commandPalletteAtom);-- const button = (- <Button- aria-label="Config"- shape="circle"- size="small"- className="h-[27px] w-[27px]"- color="hint-green"- >- <MenuIcon strokeWidth={1.8} />- </Button>- );-- const actions: Action[] = [- {- icon: <ImageIcon size={13} strokeWidth={1.5} />,- label: "Export to PNG",- handle: async () => {- await runDuringPresentMode(() => {- downloadHTMLAsImage(document.body, filename || "screenshot.png");- });- },- },- {- icon: <CommandIcon size={13} strokeWidth={1.5} />,- label: "Command Palette",- hotkey: "global.commandPalette",- handle: () => setCommandPalletteOpen((open) => !open),- },- ];-- return (- <DropdownMenu modal={false}>- <DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>- <DropdownMenuContent align="end" className="no-print w-[220px]">- {actions.map((action) => (- <DropdownMenuItem key={action.label} onSelect={() => action.handle()}>- {action.icon && <span className="flex-0 mr-2">{action.icon}</span>}- <span className="flex-1">{action.label}</span>- {action.hotkey && renderMinimalShortcut(action.hotkey)}- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- );-};diff --git a/frontend/src/components/icons/multi-icon.css b/frontend/src/components/icons/multi-icon.cssnew file mode 100644index 0000000000..5657538ca4--- /dev/null+++ b/frontend/src/components/icons/multi-icon.css@@ -0,0 +1,7 @@+.multi-icon .second-icon {+ @apply bg-background;+}++.menu-item:hover .multi-icon .second-icon {+ @apply bg-accent;+}diff --git a/frontend/src/components/icons/multi-icon.tsx b/frontend/src/components/icons/multi-icon.tsxindex 8c60a40858..12dcfdb9cb 100644--- a/frontend/src/components/icons/multi-icon.tsx+++ b/frontend/src/components/icons/multi-icon.tsx@@ -1,15 +1,28 @@/* Copyright 2023 Marimo. All rights reserved. */import React, { PropsWithChildren } from "react";+import "./multi-icon.css";++interface MultiIconProps {+ layerTop?: boolean;+}+/**- * First icon is left untouched, and second icon is layered to the bottom right/+ * By default, first icon is left untouched, and second icon is layered to the+ * bottom right. When `layerTop`, second icon is layered to the top left.*/-export const MultiIcon = (props: PropsWithChildren) => {- const [first, second] = React.Children.toArray(props.children);+export const MultiIcon = ({+ children,+ layerTop = false,+}: PropsWithChildren<MultiIconProps>) => {+ const [first, second] = React.Children.toArray(children);+ const positioning = layerTop+ ? "top-[-1px] left-[-1px]"+ : "bottom-[-1px] right-[-1px]";return (- <div className="relative">+ <div className="multi-icon relative w-fit">{first}- <div className="absolute bottom-0 right-1 transform translate-x-1/2 translate-y-1/2">+ <div className={`second-icon absolute ${positioning} rounded-full`}>{second}</div></div>diff --git a/frontend/src/components/ui/command.tsx b/frontend/src/components/ui/command.tsxindex 48271b81b2..99ef52dcc0 100644--- a/frontend/src/components/ui/command.tsx+++ b/frontend/src/components/ui/command.tsx@@ -124,7 +124,7 @@ const CommandItem = React.forwardRef<<CommandPrimitive.Itemref={ref}className={cn(- "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ "menu-item relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",className)}{...props}diff --git a/frontend/src/components/ui/kbd.tsx b/frontend/src/components/ui/kbd.tsxindex 229af38b12..f2839d4fb8 100644--- a/frontend/src/components/ui/kbd.tsx+++ b/frontend/src/components/ui/kbd.tsx@@ -13,7 +13,7 @@ export const Kbd: React.FC<Props> = (props) => {props.className,// text-[0.75rem]: don't want to set line height; want to inherit// whatever line height is used to make sure text is not off-center- "rounded-md border bg-muted px-2 text-[0.75rem] font-code"+ "rounded-md border border-border bg-muted px-2 text-[0.75rem] font-code")}>{props.children}diff --git a/frontend/src/components/ui/tooltip.tsx b/frontend/src/components/ui/tooltip.tsxindex 4e4fee0990..d5e5d66f7c 100644--- a/frontend/src/components/ui/tooltip.tsx+++ b/frontend/src/components/ui/tooltip.tsx@@ -33,7 +33,7 @@ const Tooltip: React.FC<children: React.ReactNode;} & React.ComponentPropsWithoutRef<typeof TooltipRoot>> = ({ content, children, usePortal = true, ...rootProps }) => (- <TooltipRoot {...rootProps}>+ <TooltipRoot disableHoverableContent={true} {...rootProps}><TooltipTrigger asChild={true}>{children}</TooltipTrigger>{usePortal ? (<TooltipPrimitive.TooltipPortal>diff --git a/frontend/src/core/kernel/messages.tsx b/frontend/src/core/kernel/messages.tsxindex 51b3106de3..99fd590ff5 100644--- a/frontend/src/core/kernel/messages.tsx+++ b/frontend/src/core/kernel/messages.tsx@@ -1,5 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */+import { CellConfig, CellStatus } from "../model/cells";import { CellId } from "../model/ids";export type MarimoError =@@ -70,7 +71,7 @@ export interface CellMessage {* Encodes status transitions. Non-null means a transition happened. Null* means no transition in status.*/- status: "idle" | "queued" | "running" | "stale" | null;+ status: CellStatus | null;/*** Timestamp in seconds since epoch, when the message was sent*/@@ -114,6 +115,10 @@ export type OperationMessage =* The cell codes. Will be empty in Read mode.*/codes: string[];+ /**+ * The cell configs.+ */+ configs: CellConfig[];};}| {diff --git a/frontend/src/core/model/cells.ts b/frontend/src/core/model/cells.tsindex 9cbd53039d..89e8e50551 100644--- a/frontend/src/core/model/cells.ts+++ b/frontend/src/core/model/cells.ts@@ -13,9 +13,15 @@ export const DEFAULT_CELL_NAME = "__";* queued: queued by the kernel.* running: currently executing.* idle: not running.- * stale: not run because auto-run is disabled.+ * stale: stale, likely because the cell was disabled or an ancestor was disabled.+ * disabled-transitively: disabled because an ancestor was disabled.*/-export type CellStatus = "queued" | "running" | "idle" | "stale";+export type CellStatus =+ | "queued"+ | "running"+ | "idle"+ | "stale"+ | "disabled-transitively";/*** Create a new cell with default state.@@ -104,8 +110,7 @@ export interface CellState {export interface CellConfig {/**- * If false, the cell will not be run automatically.- * Cannot be true, and instead will be set to null.+ * If true, the cell and its descendants are unable to run.*/- autoRun?: false | null;+ disabled?: boolean;}diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex 8a045f0297..1450027470 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -8,14 +8,16 @@ import {FormatRequest,InstantiateRequest,RenameRequest,- RunMultipleRequest,+ RunRequest,SaveKernelRequest,SendDirectoryAutocompleteRequest,SendDirectoryAutocompleteResponse,SetComponentValuesRequest,SaveUserConfigRequest,SaveAppConfigRequest,+ SaveCellConfigRequest,} from "./types";+import { invariant } from "@/utils/invariant";interface ValueUpdate {objectId: string;@@ -42,12 +44,18 @@ export function sendRename(filename: string | null) {});}-export function sendSave(codes: string[], names: string[], filename: string) {- return API.post<SaveKernelRequest>("/kernel/save/", {- codes: codes,- names: names,- filename: filename,- });+export function sendSave(request: SaveKernelRequest) {+ // Validate same length+ invariant(+ request.codes.length === request.names.length,+ "cell codes and names must be the same length"+ );+ invariant(+ request.codes.length === request.configs.length,+ "cell codes and configs must be the same length"+ );++ return API.post<SaveKernelRequest>("/kernel/save/", request);}export function sendFormat(codes: Record<CellId, string>) {@@ -69,11 +77,20 @@ export function sendRun(cellId: CellId, code: string) {}export function sendInstantiate(request: InstantiateRequest) {+ // Validate same length+ invariant(+ request.objectIds.length === request.values.length,+ "must be the same length"+ );+return API.post<InstantiateRequest>("/kernel/instantiate/", request);}export function sendRunMultiple(cellIds: CellId[], codes: string[]) {- return API.post<RunMultipleRequest>("/kernel/run/", {+ // Validate same length+ invariant(cellIds.length === codes.length, "must be the same length");++ return API.post<RunRequest>("/kernel/run/", {cellIds: cellIds,codes: codes,});@@ -113,3 +130,7 @@ export function saveUserConfig(request: SaveUserConfigRequest) {export function saveAppConfig(request: SaveAppConfigRequest) {return API.post<SaveAppConfigRequest>("/kernel/save_app_config/", request);}++export function saveCellConfig(request: SaveCellConfigRequest) {+ return API.post<SaveCellConfigRequest>("/kernel/set_cell_config/", request);+}diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 6f1155959f..0e03b55e14 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -1,6 +1,7 @@/* Copyright 2023 Marimo. All rights reserved. */import { AppConfig, UserConfig } from "../config/config";import { CellId } from "../../core/model/ids";+import { CellConfig } from "../model/cells";export interface DeleteRequest {cellId: CellId;@@ -31,11 +32,6 @@ export interface RenameRequest {}export interface RunRequest {- cellId: CellId;- code: string;-}--export interface RunMultipleRequest {cellIds: CellId[];codes: string[];}@@ -44,6 +40,7 @@ export interface SaveKernelRequest {filename: string;codes: string[];names: string[];+ configs: CellConfig[];}export interface SendDirectoryAutocompleteRequest {@@ -51,7 +48,6 @@ export interface SendDirectoryAutocompleteRequest {}export interface SendDirectoryAutocompleteResponse {- status: "ok";directories: string[];files: string[];}@@ -74,3 +70,7 @@ export interface SaveUserConfigRequest {export interface SaveAppConfigRequest {config: AppConfig;}++export interface SaveCellConfigRequest {+ configs: Record<CellId, CellConfig>;+}diff --git a/frontend/src/core/saving/useAutoSave.ts b/frontend/src/core/saving/useAutoSave.tsindex 9d06d0e719..101cce1e21 100644--- a/frontend/src/core/saving/useAutoSave.ts+++ b/frontend/src/core/saving/useAutoSave.ts@@ -2,15 +2,17 @@import { useEffect, useRef } from "react";import { ConnectionStatus, WebSocketState } from "../websocket/types";import { UserConfig } from "../config/config";+import { CellConfig } from "../model/cells";export function useAutoSave(opts: {codes: string[];+ cellConfigs: CellConfig[];config: UserConfig;connStatus: ConnectionStatus;needsSave: boolean;onSave: () => void;}) {- const { codes, config, connStatus, needsSave, onSave } = opts;+ const { codes, cellConfigs, config, connStatus, needsSave, onSave } = opts;const autosaveTimeoutId = useRef<NodeJS.Timeout | null>(null);useEffect(() => {@@ -32,5 +34,7 @@ export function useAutoSave(opts: {clearTimeout(autosaveTimeoutId.current);}};- }, [codes, config.save, connStatus.state, onSave, needsSave]);+ // codes, cellConfigs needed in deps array to prevent race condition+ // with needsSave when user changes state rapidly+ }, [codes, cellConfigs, config.save, connStatus.state, onSave, needsSave]);}diff --git a/frontend/src/core/state/__tests__/cells.test.ts b/frontend/src/core/state/__tests__/cells.test.tsindex d879f7f133..1096e675d4 100644--- a/frontend/src/core/state/__tests__/cells.test.ts+++ b/frontend/src/core/state/__tests__/cells.test.ts@@ -599,17 +599,17 @@ describe("cell reducer", () => {actions.updateCellConfig({cellId: firstCellId,- config: { autoRun: false },+ config: { disabled: true },});cell = state.present[0];- expect(cell.config.autoRun).toBe(false);+ expect(cell.config.disabled).toBe(true);// Revertactions.updateCellConfig({cellId: firstCellId,- config: { autoRun: null },+ config: { disabled: false },});cell = state.present[0];- expect(cell.config.autoRun).toBe(null);+ expect(cell.config.disabled).toBe(false);});});diff --git a/frontend/src/core/state/cell.ts b/frontend/src/core/state/cell.tsindex 751587d5f3..ba16b0ac97 100644--- a/frontend/src/core/state/cell.ts+++ b/frontend/src/core/state/cell.ts@@ -25,7 +25,6 @@ export function transitionCell(nextCell.runStartTimestamp = message.timestamp;break;case "idle":- nextCell.output = message.output;if (cell.runStartTimestamp) {nextCell.runElapsedTimeMs =(message.timestamp - cell.runStartTimestamp) * 1000;@@ -37,9 +36,13 @@ export function transitionCell(case "stale":// Everything should already be up to date from prepareCellForExecutionbreak;+ case "disabled-transitively":+ // Everything should already be up to date from prepareCellForExecution+ break;default:logNever(message.status);}+ nextCell.output = message.output ?? cell.output;nextCell.status = message.status ?? cell.status;// Handle errors: marimo includes an error output when a cell is interrupteddiff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 858725665e..0fcb5be8eb 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -9,8 +9,9 @@ import { RuntimeState } from "@/core/RuntimeState";import { COMPLETION_REQUESTS } from "@/core/codemirror/completion/CompletionRequests";import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";import { OperationMessage } from "@/core/kernel/messages";-import { sendInstantiate } from "../network/requests";+import { saveCellConfig, sendInstantiate } from "../network/requests";import { CellId } from "../model/ids";+import { CellConfig } from "../model/cells";import { CellState, createCell } from "../model/cells";import { useErrorBoundary } from "react-error-boundary";import { Logger } from "@/utils/Logger";@@ -22,8 +23,9 @@ export function useMarimoWebSocket(opts: {sessionId: string;setCells: (cells: CellState[]) => void;setInitialCodes: (codes: string[]) => void;+ setInitialConfigs: (cellConfigs: CellConfig[]) => void;}) {- const { sessionId, setCells, setInitialCodes } = opts;+ const { sessionId, setCells, setInitialCodes, setInitialConfigs } = opts;const { showBoundary } = useErrorBoundary();const { handleCellMessage } = useCellActions();@@ -49,7 +51,7 @@ export function useMarimoWebSocket(opts: {const msg = JSON.parse(e.data) as OperationMessage;switch (msg.op) {case "kernel-ready": {- const { codes, names } = msg.data;+ const { codes, names, configs } = msg.data;// TODO(akshayka): Get rid of this once the kernel sends cell IDs in// kernel-ready.@@ -62,10 +64,12 @@ export function useMarimoWebSocket(opts: {code,initialContents: code,name: names[i],+ config: configs[i],}));setCells(cells);setInitialCodes(codes);+ setInitialConfigs(configs);// Auto-instantiate, in future this can be configurable// or include initial values@@ -80,6 +84,16 @@ export function useMarimoWebSocket(opts: {});// Start the runRuntimeState.INSTANCE.registerRunStart();+ // Register the configs+ saveCellConfig({+ configs: Object.fromEntries(+ cells.map((cell) => [cell.key, cell.config])+ ),+ }).catch((error) => {+ showBoundary(+ new Error("Failed to register configs", { cause: error })+ );+ });// Send the instantiate messagesendInstantiate({ objectIds, values }).catch((error) => {showBoundary(new Error("Failed to instantiate", { cause: error }));diff --git a/frontend/src/css/Cell.css b/frontend/src/css/Cell.cssindex dd4ed10811..e6e92bc8f4 100644--- a/frontend/src/css/Cell.css+++ b/frontend/src/css/Cell.css@@ -19,10 +19,27 @@background-color: transparent;}-.Cell:hover {+.Cell:not(.disabled):hover {box-shadow: var(--medium-shadow);}+.Cell.disabled .OutputArea,+.Cell.disabled.stale .OutputArea,+.Cell.disabled .cm-gutters,+.Cell.disabled.stale .cm-gutters,+.Cell.disabled .cm,+.Cell.disabled.stale .cm {+ background-color: var(--gray-2);+ opacity: 0.5;+}++.Cell.stale .OutputArea,+.Cell.stale .cm,+.Cell.stale .cm-gutters {+ background-color: var(--gray-1);+ opacity: 0.5;+}+.Cell.has-error,.Cell.error-outline {outline: 1px solid var(--red-4);@@ -139,6 +156,7 @@position: absolute;right: -98px;width: 80px;+ gap: 4px;z-index: 2;}@@ -149,55 +167,6 @@z-index: 2; /* lie above editor */}-/* --------------------------- Status Indicators ---------------------------- */-.cell-status-icon {- margin-top: 4px;- margin-left: 3px;- margin-bottom: auto;-}--@keyframes appear {- from {- visibility: visible;- }-- to {- visibility: visible;- }-}--.elapsed-time {- font-family: var(--monospace-font);- font-size: 0.8125rem;- color: var(--gray-11);-}--.elapsed-time.running {- animation: appear 1000ms;- animation-timing-function: linear;- animation-iteration-count: infinite;- animation-delay: 50ms;-}--#App.disconnected .elapsed-time {- visibility: hidden;-}--.cell-status-queued,-.cell-status-stale {- animation: appear 1000ms;- animation-timing-function: linear;- animation-iteration-count: infinite;- animation-delay: 100ms;-}--.cell-status-queued svg,-.cell-status-stale svg {- color: var(--gray-10);- width: 16px;- height: 16px;-}-/* ------------------------ CodeMirror Editor ----------------------------- */.cm {@@ -361,7 +330,9 @@overflow: auto;}-.marimo-output-stale {+.marimo-output-stale,+.Cell.stale .OutputArea.marimo-output-stale,+.Cell.stale .ConsoleOutputArea.marimo-output-stale {opacity: 0.2;transition: opacity 300ms;transition-delay: 200ms;@@ -454,10 +425,6 @@border-bottom: 1px solid var(--stale-color);}-.Cell.needs-run .RunButton {- visibility: visible;-}-/* ------------------------ Output Formatting ---------------------------- */.output,.media,diff --git a/frontend/src/css/globals.css b/frontend/src/css/globals.cssindex 4683a8dd43..79929ae5a5 100644--- a/frontend/src/css/globals.css+++ b/frontend/src/css/globals.css@@ -29,29 +29,20 @@--background: 0 0% 100%;--foreground: 222.2 47.4% 11.2%;---muted: 210 40% 96.1%;--muted-foreground: 215.4 16.3% 46.9%;---popover: 0 0% 100%;--popover-foreground: 222.2 47.4% 11.2%;---card: 0 0% 100%;--card-foreground: 222.2 47.4% 11.2%;---border: 214.3 31.8% 91.4%;---input: 0 0% 64%; /* tailwind slate-400 */---primary: 208 93.5% 47.4%; /* blue-10 */--primary-foreground: 210 40% 98%;---secondary: 210 40% 96.1%;--secondary-foreground: 222.2 47.4% 11.2%;---accent: 209 100% 96.5%; /* blue-3 */--accent-foreground: 211 90% 42%; /* blue-11 */---destructive: 0 100% 70%;--destructive-foreground: 210 40% 98%;--error: 0 77% 64%;@@ -61,7 +52,6 @@--action: 52 96.8% 82%;--action-hover: 54 100% 86.7%;--action-foreground: 42 100% 29%;---link: 211 90% 42% /* blue-11 */;--link-visited: 272 51% 54% /* purple-9 */;--ring: 215 20.2% 65.1%;diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsxindex 28d0216713..794f5a2059 100644--- a/frontend/src/editor/Cell.tsx+++ b/frontend/src/editor/Cell.tsx@@ -375,7 +375,7 @@ const CellComponent = (<OutputAreaoutput={output}cellId={cellId}- stale={(loading || edited) && !interrupted}+ stale={(loading || edited || status === "stale") && !interrupted}/>);@@ -384,6 +384,8 @@ const CellComponent = ("needs-run": needsRun,"has-error": errored,stopped: stopped,+ disabled: cellConfig.disabled,+ stale: status === "stale" || status === "disabled-transitively",});const HTMLId = HTMLCellId.create(cellId);@@ -396,6 +398,19 @@ const CellComponent = ();}+ // TODO(akshayka): Move to our own Tooltip component once it's easier+ // to get the tooltip to show next to the cursor ...+ // https://github.com/radix-ui/primitives/discussions/1090+ const cellTitle = () => {+ if (cellConfig.disabled) {+ return "This cell is disabled";+ } else if (status === "stale" || status === "disabled-transitively") {+ return "This cell has a disabled ancestor";+ } else {+ return undefined;+ }+ };+const editor = <div className="cm" ref={editorViewParentRef} />;return (@@ -404,9 +419,11 @@ const CellComponent = (id={HTMLId}ref={cellRef}className={className}+ data-status={status}onBlur={closeCompletionHandler}onKeyDown={resumeCompletionHandler}cellId={cellId}+ title={cellTitle()}>{outputArea}<div className="tray">@@ -433,13 +450,16 @@ const CellComponent = (interrupted={interrupted}editing={editing}edited={edited}+ disabled={cellConfig.disabled ?? false}elapsedTime={runElapsedTimeMs}/><div className="flex align-bottom"><RunButton+ edited={edited}onClick={appClosed ? Functions.NOOP : onRun}appClosed={appClosed}status={status}+ config={cellConfig}needsRun={needsRun}/><CellActionsDropdown@@ -469,7 +489,9 @@ const CellComponent = (<ConsoleOutputAreaconsoleOutputs={consoleOutputs}cellId={cellId}- stale={(status === "queued" || edited) && !interrupted}+ stale={+ (status === "queued" || edited || status === "stale") && !interrupted+ }/></SortableCell>);diff --git a/frontend/src/editor/Controls.tsx b/frontend/src/editor/Controls.tsxindex 3690370a1c..c364405ce0 100644--- a/frontend/src/editor/Controls.tsx+++ b/frontend/src/editor/Controls.tsx@@ -19,7 +19,7 @@ import { renderShortcut } from "../components/shortcuts/renderShortcut";import { useCellActions } from "../core/state/cells";import { AppConfigButton } from "../components/app-config/app-config-button";import { useState, useEffect } from "react";-import { MenuDropdown } from "@/components/export/menu-dropdown";+import { NotebookMenuDropdown } from "@/editor/notebook-menu-dropdown";import { FindReplace } from "@/components/find-replace/find-replace";interface ControlsProps {@@ -83,7 +83,7 @@ export const Controls = ({{!closed && (<div className={styles.topRightControls}>- <MenuDropdown filename={filename} />+ <NotebookMenuDropdown filename={filename} /><AppConfigButton /><ShutdownButton onShutdown={onShutdown} /></div>diff --git a/frontend/src/editor/Output.tsx b/frontend/src/editor/Output.tsxindex 7719095834..23a18785b1 100644--- a/frontend/src/editor/Output.tsx+++ b/frontend/src/editor/Output.tsx@@ -83,6 +83,10 @@ export const OutputArea = React.memo(} else if (props.output.channel === "output" && props.output.data === "") {return null;} else {+ // TODO(akshayka): More descriptive title+ // 1. This output is stale (this cell has been edited but not run)+ // 2. This output is stale (this cell is queued to run)+ // 3. This output is stale (its inputs have changed)const title = props.stale ? "This output is stale" : undefined;return (<divdiff --git a/frontend/src/editor/SortableCell.tsx b/frontend/src/editor/SortableCell.tsxindex 71f91b5b33..c803c59e88 100644--- a/frontend/src/editor/SortableCell.tsx+++ b/frontend/src/editor/SortableCell.tsx@@ -54,7 +54,7 @@ const SortableCellInternal = React.forwardRef({...attributes}{...listeners}data-testid="drag-button"- className="py-[1px] mx-2 cursor-grab opacity-50 hover:opacity-100 hover-action hover:bg-muted rounded"+ className="py-[1px] mx-2 cursor-grab opacity-50 hover:opacity-100 hover-action hover:bg-muted rounded border border-transparent hover:border-border active:bg-accent"><GripVerticalIcon strokeWidth={1} size={20} /></div>diff --git a/frontend/src/editor/actions/useNotebookActions.tsx b/frontend/src/editor/actions/useNotebookActions.tsxnew file mode 100644index 0000000000..140a1191f2--- /dev/null+++ b/frontend/src/editor/actions/useNotebookActions.tsx@@ -0,0 +1,85 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { HotkeyAction } from "@/core/hotkeys/hotkeys";+import { runDuringPresentMode } from "@/core/mode";+import { downloadHTMLAsImage } from "@/utils/download";+import { useSetAtom } from "jotai";+import { ImageIcon, CommandIcon, ZapIcon, ZapOffIcon } from "lucide-react";+import { commandPalletteAtom } from "../CommandPallette";+import { useCellActions, useCells } from "@/core/state/cells";+import { saveCellConfig } from "@/core/network/requests";+import { Objects } from "@/utils/objects";++interface Action {+ label: string;+ hotkey?: HotkeyAction;+ icon?: React.ReactNode;+ hidden?: boolean;+ handle: () => void;+}++export function useNotebookActions(opts: { filename?: string | null }) {+ const { filename } = opts;++ const cells = useCells();+ const { updateCellConfig } = useCellActions();+ const setCommandPalletteOpen = useSetAtom(commandPalletteAtom);++ const disabledCells = cells.present.filter((cell) => cell.config.disabled);+ const enabledCells = cells.present.filter((cell) => !cell.config.disabled);++ const actions: Action[] = [+ // TODO(akshayka): Add these to the command palette+ {+ icon: <ImageIcon size={13} strokeWidth={1.5} />,+ label: "Export to PNG",+ handle: async () => {+ await runDuringPresentMode(() => {+ downloadHTMLAsImage(document.body, filename || "screenshot.png");+ });+ },+ },+ {+ icon: <ZapIcon size={13} strokeWidth={1.5} />,+ label: "Enable all cells",+ hidden: disabledCells.length === 0,+ handle: async () => {+ const ids = disabledCells.map((cell) => cell.key);+ const newConfigs = Objects.fromEntries(+ ids.map((cellId) => [cellId, { disabled: false }])+ );+ // send to BE+ await saveCellConfig({ configs: newConfigs });+ // update on FE+ ids.forEach((cellId) =>+ updateCellConfig({ cellId, config: { disabled: false } })+ );+ },+ },+ {+ icon: <ZapOffIcon size={13} strokeWidth={1.5} />,+ label: "Disable all cells",+ hidden: enabledCells.length === 0,+ handle: async () => {+ const ids = enabledCells.map((cell) => cell.key);+ const newConfigs = Objects.fromEntries(+ ids.map((cellId) => [cellId, { disabled: true }])+ );+ // send to BE+ await saveCellConfig({ configs: newConfigs });+ // update on FE+ ids.forEach((cellId) =>+ updateCellConfig({ cellId, config: { disabled: true } })+ );+ },+ },++ {+ icon: <CommandIcon size={13} strokeWidth={1.5} />,+ label: "Command Palette",+ hotkey: "global.commandPalette",+ handle: () => setCommandPalletteOpen((open) => !open),+ },+ ];++ return actions.filter((a) => !a.hidden);+}diff --git a/frontend/src/editor/cell/CellStatus.tsx b/frontend/src/editor/cell/CellStatus.tsxindex 27d2448b1f..deb66e46f7 100644--- a/frontend/src/editor/cell/CellStatus.tsx+++ b/frontend/src/editor/cell/CellStatus.tsx@@ -1,20 +1,31 @@/* Copyright 2023 Marimo. All rights reserved. */-import { MoreHorizontalIcon, RefreshCwIcon } from "lucide-react";+import {+ BanIcon,+ MoreHorizontalIcon,+ WorkflowIcon,+ RefreshCwIcon,+} from "lucide-react";import { Tooltip } from "../../components/ui/tooltip";import { CellStatus } from "../../core/model/cells";import { useElapsedTime } from "../../hooks/useElapsedTime";+import { Logger } from "@/utils/Logger";+import { MultiIcon } from "@/components/icons/multi-icon";-interface Props {+import "./cell-status.css";++export interface CellStatusComponentProps {editing: boolean;status: CellStatus;edited: boolean;interrupted: boolean;+ disabled: boolean;elapsedTime: number | null;}-export const CellStatusComponent: React.FC<Props> = ({+export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({editing,status,+ disabled,edited,interrupted,elapsedTime,@@ -23,8 +34,91 @@ export const CellStatusComponent: React.FC<Props> = ({return null;}- // Styling: CellStatusIcon visible if queued, running, or needs run.- //+ // unexpected states+ if (disabled && status === "running") {+ Logger.error("CellStatusComponent: disabled and running");+ return null;+ }+ // stale and disabled by self+ if (disabled && status === "stale") {+ return (+ <Tooltip+ content={"This cell is stale, but it's disabled and can't be run"}+ usePortal={false}+ >+ <div+ className="cell-status-icon cell-status-stale"+ data-testid="cell-status"+ data-status="stale"+ >+ <MultiIcon>+ <BanIcon className="h-4 w-4" strokeWidth={1.5} />+ <RefreshCwIcon className="h-3 w-3" strokeWidth={2.5} />+ </MultiIcon>+ </div>+ </Tooltip>+ );+ }++ // disabled, but not stale+ if (disabled) {+ return (+ <Tooltip content={"This cell is disabled"} usePortal={false}>+ <div+ className="cell-status-icon cell-status-disabled"+ data-testid="cell-status"+ data-status="disabled"+ >+ <BanIcon className="h-4 w-4" strokeWidth={1.5} />+ </div>+ </Tooltip>+ );+ }++ // disabled from parent+ if (status === "disabled-transitively") {+ return (+ <Tooltip+ content={"An ancestor of this cell is disabled, so it can't be run"}+ usePortal={false}+ >+ <div+ className="cell-status-icon cell-status-stale"+ data-testid="cell-status"+ data-status="disabled-transitively"+ >+ <MultiIcon layerTop={true}>+ <WorkflowIcon className="h-5 w-5" strokeWidth={1.5} />+ <BanIcon className="h-3 w-3" strokeWidth={2.5} />+ </MultiIcon>+ </div>+ </Tooltip>+ );+ }++ // stale from parent being disabled+ if (status === "stale") {+ return (+ <Tooltip+ content={+ "This cell is stale, but an ancestor is disabled so it can't be run"+ }+ usePortal={false}+ >+ <div+ className="cell-status-icon cell-status-stale"+ data-testid="cell-status"+ data-status="stale"+ >+ <MultiIcon>+ <RefreshCwIcon className="h-5 w-5" strokeWidth={1} />+ <BanIcon className="h-3 w-3" strokeWidth={2.5} />+ </MultiIcon>+ </div>+ </Tooltip>+ );+ }+// running & queued icons get priority over edited/interruptedif (status === "running") {return (@@ -32,28 +126,31 @@ export const CellStatusComponent: React.FC<Props> = ({<divclassName={"cell-status-icon elapsed-time running"}data-testid="cell-status"+ data-status="running"><CellTimer /></div></Tooltip>);- } else if (status === "queued" && elapsedTime) {- // If elapsed time < 16ms (60fps), don't show the elapsed time,- // otherwise it will flicker.- if (elapsedTime < 16) {- return null;- }+ }++ // queued+ if (status === "queued") {return (<Tooltip content={"This cell is queued to run"} usePortal={false}><divclassName="cell-status-icon cell-status-queued"data-testid="cell-status"+ data-status="queued">- <MoreHorizontalIcon strokeWidth={1.5} />+ <MoreHorizontalIcon className="h-5 w-5" strokeWidth={1.5} /></div></Tooltip>);- } else if (edited || interrupted) {+ }++ // outdated+ if (edited || interrupted) {const title = interrupted? "This cell was interrupted when it was last run": "This cell has been modified since it was last run";@@ -62,12 +159,16 @@ export const CellStatusComponent: React.FC<Props> = ({<divclassName="cell-status-icon cell-status-stale"data-testid="cell-status"+ data-status="outdated">- <RefreshCwIcon strokeWidth={1.5} />+ <RefreshCwIcon className="h-4 w-4" strokeWidth={1.5} /></div></Tooltip>);- } else if (elapsedTime !== null) {+ }++ // either running or finished+ if (elapsedTime !== null) {const elapsedTimeStr = formatElapsedTime(elapsedTime);return (<Tooltip@@ -77,6 +178,7 @@ export const CellStatusComponent: React.FC<Props> = ({<divclassName={"cell-status-icon elapsed-time hover-action"}data-testid="cell-status"+ data-status="idle"><span>{elapsedTimeStr}</span></div>@@ -84,6 +186,7 @@ export const CellStatusComponent: React.FC<Props> = ({);}+ // defaultreturn null;};diff --git a/frontend/src/editor/cell/RunButton.tsx b/frontend/src/editor/cell/RunButton.tsxindex 2e72118fdb..df8dad433a 100644--- a/frontend/src/editor/cell/RunButton.tsx+++ b/frontend/src/editor/cell/RunButton.tsx@@ -1,31 +1,84 @@/* Copyright 2023 Marimo. All rights reserved. */-import { PlayIcon } from "lucide-react";+import { HardDriveDownloadIcon, PlayIcon } from "lucide-react";import { Button } from "@/editor/inputs/Inputs";import { Tooltip } from "../../components/ui/tooltip";import { renderShortcut } from "../../components/shortcuts/renderShortcut";import { cn } from "../../lib/utils";-import { CellStatus } from "../../core/model/cells";+import { CellConfig, CellStatus } from "../../core/model/cells";-function computeColor(appClosed: boolean, needsRun: boolean, loading: boolean) {+function computeColor(+ appClosed: boolean,+ needsRun: boolean,+ loading: boolean,+ inactive: boolean+) {if (appClosed) {return "disabled";} else if (needsRun && !loading) {return "yellow";- } else if (loading) {+ } else if (loading || inactive) {return "disabled";} else {return "hint-green";}}export const RunButton = (props: {+ edited: boolean;status: CellStatus;needsRun: boolean;appClosed: boolean;+ config: CellConfig;onClick?: () => void;}): JSX.Element => {- const { onClick, appClosed, needsRun, status } = props;+ const { onClick, appClosed, needsRun, status, config, edited } = props;++ const blockedStatus =+ status === "stale" || status === "disabled-transitively";const loading = status === "running" || status === "queued";- const color = computeColor(appClosed, needsRun, loading);+ const inactive =+ appClosed || loading || (!config.disabled && blockedStatus && !edited);+ const color = computeColor(appClosed, needsRun, loading, inactive);++ if (config.disabled) {+ return (+ <Tooltip content="Add code to notebook" usePortal={false}>+ <Button+ className={cn(+ !needsRun && "hover-action",+ inactive && "inactive-button"+ )}+ onClick={onClick}+ color={color}+ shape="circle"+ size="small"+ data-testid="run-button"+ >+ <HardDriveDownloadIcon strokeWidth={1.8} />+ </Button>+ </Tooltip>+ );+ } else if (!config.disabled && blockedStatus && !edited) {+ return (+ <Tooltip+ content="This cell can't be run because it has a disabled ancestor"+ usePortal={false}+ >+ <Button+ className={cn(+ !needsRun && "hover-action",+ inactive && "inactive-button"+ )}+ onClick={onClick}+ color={color}+ shape="circle"+ size="small"+ data-testid="run-button"+ >+ <PlayIcon strokeWidth={1.8} />+ </Button>+ </Tooltip>+ );+ }let tooltipMsg: React.ReactNode = "";if (appClosed) {@@ -42,9 +95,8 @@ export const RunButton = (props: {<Tooltip content={tooltipMsg} usePortal={false}><ButtonclassName={cn(- "RunButton",!needsRun && "hover-action",- (appClosed || loading) && "inactive-button",+ inactive && "inactive-button",loading && "running")}onClick={onClick}diff --git a/frontend/src/editor/cell/cell-actions.tsx b/frontend/src/editor/cell/cell-actions.tsxindex 4a6e3b749e..eadfe83663 100644--- a/frontend/src/editor/cell/cell-actions.tsx+++ b/frontend/src/editor/cell/cell-actions.tsx@@ -33,6 +33,7 @@ import {PlusCircleIcon,Trash2Icon,ZapIcon,+ ZapOffIcon,} from "lucide-react";import { downloadCellOutput } from "@/components/export/export-output-button";import { HotkeyAction } from "@/core/hotkeys/hotkeys";@@ -43,6 +44,7 @@ import { renderMinimalShortcut } from "@/components/shortcuts/renderShortcut";import { CellConfig } from "@/core/model/cells";import { Switch } from "@/components/ui/switch";import React from "react";+import { saveCellConfig } from "@/core/network/requests";interface Props {editorView: EditorView | null;@@ -79,11 +81,13 @@ export const CellActionsDropdown = ({sendToTop,sendToBottom,} = useCellActions();- const toggleAutoRun = () => {- if (config.autoRun === false) {- updateCellConfig({ cellId, config: { autoRun: null } });+ const toggleDisabled = async () => {+ if (config.disabled) {+ await saveCellConfig({ configs: { [cellId]: { disabled: false } } });+ updateCellConfig({ cellId, config: { disabled: false } });} else {- updateCellConfig({ cellId, config: { autoRun: false } });+ await saveCellConfig({ configs: { [cellId]: { disabled: true } } });+ updateCellConfig({ cellId, config: { disabled: true } });}};@@ -108,20 +112,20 @@ export const CellActionsDropdown = ({},},{- icon: <ZapIcon size={13} strokeWidth={1.5} />,- // TODO: this feature is still a WIP- hidden: true,- label:- config.autoRun === false ? "Enable auto-run" : "Disable auto-run",+ icon: config.disabled ? (+ <ZapIcon size={13} strokeWidth={1.5} />+ ) : (+ <ZapOffIcon size={13} strokeWidth={1.5} />+ ),+ label: config.disabled === true ? "Enable cell" : "Disable cell",rightElement: (<Switch- // null implies true- checked={config.autoRun === false ? false : true}+ checked={!config.disabled}size="sm"- onCheckedChange={toggleAutoRun}+ onCheckedChange={toggleDisabled}/>),- handle: toggleAutoRun,+ handle: toggleDisabled,},],@@ -131,7 +135,7 @@ export const CellActionsDropdown = ({icon: (<MultiIcon><PlusCircleIcon size={13} strokeWidth={1.5} />- <ChevronUpIcon size={12} strokeWidth={1.5} />+ <ChevronUpIcon size={8} strokeWidth={2} /></MultiIcon>),label: "Create cell above",@@ -142,7 +146,7 @@ export const CellActionsDropdown = ({icon: (<MultiIcon><PlusCircleIcon size={13} strokeWidth={1.5} />- <ChevronDownIcon size={12} strokeWidth={1.5} />+ <ChevronDownIcon size={8} strokeWidth={2} /></MultiIcon>),label: "Create cell below",@@ -165,7 +169,7 @@ export const CellActionsDropdown = ({icon: (<MultiIcon><FocusIcon size={13} strokeWidth={1.5} />- <ChevronUpIcon size={12} strokeWidth={1.5} />+ <ChevronUpIcon size={8} strokeWidth={2} /></MultiIcon>),label: "Focus cell above",@@ -176,7 +180,7 @@ export const CellActionsDropdown = ({icon: (<MultiIcon><FocusIcon size={13} strokeWidth={1.5} />- <ChevronDownIcon size={12} strokeWidth={1.5} />+ <ChevronDownIcon size={8} strokeWidth={2} /></MultiIcon>),label: "Focus cell below",@@ -226,12 +230,13 @@ export const CellActionsDropdown = ({</TooltipContent>)}<TooltipTrigger>- <PopoverTrigger>{children}</PopoverTrigger>+ <PopoverTrigger className="flex">{children}</PopoverTrigger></TooltipTrigger></TooltipRoot><PopoverContentclassName="w-[300px] p-0 pt-1"onOpenAutoFocus={(e) => e.preventDefault()}+ onCloseAutoFocus={(e) => e.preventDefault()}><Command><CommandInput@@ -267,6 +272,7 @@ export const CellActionsDropdown = ({<div className="flex-shrink-0 text-sm">{action.hotkey &&renderMinimalShortcut(action.hotkey)}+ {action.rightElement}</div></div></CommandItem>diff --git a/frontend/src/editor/cell/cell-status.css b/frontend/src/editor/cell/cell-status.cssnew file mode 100644index 0000000000..115b27428a--- /dev/null+++ b/frontend/src/editor/cell/cell-status.css@@ -0,0 +1,19 @@+.cell-status-icon {+ margin-left: 3px;+}++.elapsed-time {+ font-family: var(--monospace-font);+ font-size: 0.8125rem;+ color: var(--gray-11);+}++#App.disconnected .elapsed-time {+ visibility: hidden;+}++.cell-status-disabled,+.cell-status-queued,+.cell-status-stale {+ color: var(--gray-10);+}diff --git a/frontend/src/editor/cell/useRunCells.ts b/frontend/src/editor/cell/useRunCells.tsnew file mode 100644index 0000000000..776fb4a31f--- /dev/null+++ b/frontend/src/editor/cell/useRunCells.ts@@ -0,0 +1,46 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { RuntimeState } from "@/core/RuntimeState";+import { CellState } from "@/core/model/cells";+import { CellId } from "@/core/model/ids";+import { sendRunMultiple } from "@/core/network/requests";+import { useCells } from "@/core/state/cells";+import { derefNotNull } from "@/utils/dereference";+import useEvent from "react-use-event-hook";++export function useRunStaleCells() {+ const cells = useCells();+ const runCells = useRunCells();++ const runStaleCells = useEvent(async () => {+ const staleCells = cells.present.filter((cell) => {+ return cell.edited || cell.interrupted;+ });+ await runCells(staleCells);+ });++ return runStaleCells;+}++export function useRunCells() {+ const runCells = useEvent(async (cells: CellState[]) => {+ if (cells.length === 0) {+ return;+ }++ const cellIds: CellId[] = [];+ const codes: string[] = [];+ for (const cell of cells) {+ const ref = derefNotNull(cell.ref);++ cellIds.push(cell.key);+ codes.push(ref.editorView.state.doc.toString());++ ref.registerRun();+ }++ RuntimeState.INSTANCE.registerRunStart();+ await sendRunMultiple(cellIds, codes);+ });++ return runCells;+}diff --git a/frontend/src/editor/notebook-menu-dropdown.tsx b/frontend/src/editor/notebook-menu-dropdown.tsxnew file mode 100644index 0000000000..f4dee3e70a--- /dev/null+++ b/frontend/src/editor/notebook-menu-dropdown.tsx@@ -0,0 +1,47 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { Button } from "@/editor/inputs/Inputs";+import { MenuIcon } from "lucide-react";+import React from "react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { renderMinimalShortcut } from "../components/shortcuts/renderShortcut";+import { useNotebookActions } from "./actions/useNotebookActions";++interface Props {+ filename: string | null;+}++export const NotebookMenuDropdown: React.FC<Props> = ({ filename }) => {+ const actions = useNotebookActions({ filename });++ const button = (+ <Button+ aria-label="Config"+ shape="circle"+ size="small"+ className="h-[27px] w-[27px]"+ color="hint-green"+ >+ <MenuIcon strokeWidth={1.8} />+ </Button>+ );++ return (+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="no-print w-[220px]">+ {actions.map((action) => (+ <DropdownMenuItem key={action.label} onSelect={() => action.handle()}>+ {action.icon && <span className="flex-0 mr-2">{action.icon}</span>}+ <span className="flex-1">{action.label}</span>+ {action.hotkey && renderMinimalShortcut(action.hotkey)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+};diff --git a/frontend/src/stories/cell-status.stories.tsx b/frontend/src/stories/cell-status.stories.tsxnew file mode 100644index 0000000000..b10613f2e1--- /dev/null+++ b/frontend/src/stories/cell-status.stories.tsx@@ -0,0 +1,143 @@+/* Copyright 2023 Marimo. All rights reserved. */+import type { Meta, StoryFn } from "@storybook/react";+import {+ CellStatusComponent,+ CellStatusComponentProps,+} from "@/editor/cell/CellStatus";+import { TooltipProvider } from "@/components/ui/tooltip";++const meta: Meta<typeof CellStatusComponent> = {+ title: "CellStatusComponent",+ component: CellStatusComponent,+ args: {},+};++export default meta;++const Template: StoryFn<CellStatusComponentProps> = (args) => (+ <TooltipProvider>+ <div className="bg-background">+ <CellStatusComponent {...args} />+ </div>+ </TooltipProvider>+);++export const Idle = Template.bind({});+Idle.args = {+ editing: true,+ status: "idle",+ edited: false,+ interrupted: false,+ disabled: false,+ elapsedTime: null,+};++export const Edited = Template.bind({});+Edited.args = {+ editing: true,+ status: "idle",+ edited: true,+ interrupted: false,+ disabled: false,+ elapsedTime: 100,+};++export const Interrupted = Template.bind({});+Interrupted.args = {+ editing: true,+ status: "idle",+ edited: false,+ interrupted: true,+ disabled: false,+ elapsedTime: 50,+};++export const Running = Template.bind({});+Running.args = {+ editing: true,+ status: "running",+ edited: false,+ interrupted: true,+ disabled: false,+ elapsedTime: 50,+};++export const Queued = Template.bind({});+Queued.args = {+ editing: true,+ status: "queued",+ edited: false,+ interrupted: true,+ disabled: false,+ elapsedTime: 50,+};++export const Disabled = Template.bind({});+Disabled.args = {+ editing: true,+ status: "idle",+ edited: false,+ interrupted: false,+ disabled: true,+ elapsedTime: null,+};++export const DisabledTransitively = Template.bind({});+DisabledTransitively.args = {+ editing: true,+ status: "disabled-transitively",+ edited: false,+ interrupted: false,+ disabled: false,+ elapsedTime: null,+};++export const DisabledTransitivelyAndEdited = Template.bind({});+DisabledTransitivelyAndEdited.args = {+ editing: true,+ status: "disabled-transitively",+ edited: true,+ interrupted: false,+ disabled: false,+ elapsedTime: null,+};++export const Stale = Template.bind({});+Stale.args = {+ editing: true,+ status: "stale",+ edited: false,+ interrupted: false,+ disabled: false,+ elapsedTime: null,+};++export const StaleAndDisabled = Template.bind({});+StaleAndDisabled.args = {+ editing: true,+ status: "stale",+ edited: false,+ interrupted: false,+ disabled: true,+ elapsedTime: null,+};++export const EditedStaleAndDisabled = Template.bind({});+EditedStaleAndDisabled.args = {+ editing: true,+ status: "stale",+ edited: true,+ interrupted: false,+ disabled: true,+ elapsedTime: null,+};++export const EditedAndStale = Template.bind({});+EditedAndStale.args = {+ editing: true,+ status: "stale",+ edited: true,+ interrupted: false,+ disabled: false,+ elapsedTime: null,+};diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 95b9993059..19b25e17bb 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -84,7 +84,7 @@ export const WithOutput: Story = {),};-export const StaleOutput: Story = {+export const UnsavedEditsOutput: Story = {render: () => (<div className="p-20 max-w-4xl"><TooltipProvider>@@ -104,6 +104,26 @@ export const StaleOutput: Story = {),};+export const InterruptedOutput: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <Cell+ {...props}+ runElapsedTimeMs={20}+ interrupted={true}+ output={{+ channel: "output",+ data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",+ mimetype: "text/html",+ timestamp: "1686863788",+ }}+ />+ </TooltipProvider>+ </div>+ ),+};+export const WithError: Story = {render: () => (<div className="p-20 max-w-4xl">@@ -123,3 +143,128 @@ export const WithError: Story = {</div>),};++export const Disabled: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <Cell+ {...props}+ runElapsedTimeMs={20}+ config={{+ disabled: true,+ }}+ output={{+ channel: "output",+ data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",+ mimetype: "text/html",+ timestamp: "1686863788",+ }}+ />+ </TooltipProvider>+ </div>+ ),+};++export const DisabledTransitively: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <Cell+ {...props}+ runElapsedTimeMs={20}+ status="disabled-transitively"+ output={{+ channel: "output",+ data: "This data is stale because a parent is disabled",+ mimetype: "text/html",+ timestamp: "1686863788",+ }}+ />+ </TooltipProvider>+ </div>+ ),+};++export const StaleStatus: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <Cell+ {...props}+ runElapsedTimeMs={20}+ status="stale"+ output={{+ channel: "output",+ data: "This data is stale because a parent is disabled",+ mimetype: "text/html",+ timestamp: "1686863788",+ }}+ />+ </TooltipProvider>+ </div>+ ),+};++export const StaleAndEditedStatus: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <Cell+ {...props}+ runElapsedTimeMs={20}+ status="stale"+ output={{+ channel: "output",+ data: "This data is stale because a parent is disabled, but this cell has been edited since.",+ mimetype: "text/html",+ timestamp: "1686863788",+ }}+ />+ </TooltipProvider>+ </div>+ ),+};++export const DisabledAndStaleStatus: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <Cell+ {...props}+ runElapsedTimeMs={20}+ config={{+ disabled: true,+ }}+ status="stale"+ output={{+ channel: "output",+ data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",+ mimetype: "text/html",+ timestamp: "1686863788",+ }}+ />+ </TooltipProvider>+ </div>+ ),+};++export const Running: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <Cell+ {...props}+ runElapsedTimeMs={20}+ status="running"+ output={{+ channel: "output",+ data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",+ mimetype: "text/html",+ timestamp: "1686863788",+ }}+ />+ </TooltipProvider>+ </div>+ ),+};diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 6f40d700f6..46e9b4e438 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -6,13 +6,15 @@ import itertoolsimport textwrapfrom collections.abc import Sequencefrom dataclasses import asdict, dataclass-from typing import Any, Iterable, Literal, Optional+from typing import Any, Callable, Iterable, Literal, Optional, Union, castfrom marimo._ast.cell import (+ CellConfig,CellFunction,+ CellFuncType,+ CellFuncTypeBound,CellId_t,cell_factory,- cell_func_t,execute_cell,)from marimo._ast.errors import (@@ -54,8 +56,11 @@ class CellData:code: str# User-provided name for cell (or default)name: str+ # Cell config+ config: CellConfig+# Callable cell, or None if cell was not parsable- cell_function: Optional[CellFunction]+ cell_function: Optional[CellFunction[CellFuncType]]@mddoc@@ -85,7 +90,7 @@ class App:self._initialized = Falsedef _create_cell_id(- self, cell_function: Optional[CellFunction]+ self, cell_function: Optional[CellFunction[CellFuncTypeBound]]) -> CellId_t:del cell_functioncell_id = str(self._cell_id_counter)@@ -93,16 +98,77 @@ class App:self._cell_id_counter += 1return str(cell_id)- def cell(self, f: cell_func_t) -> CellFunction:- cell_function = cell_factory(f)+ def cell(+ self,+ func: Optional[CellFuncTypeBound] = None,+ *,+ disabled: bool = False,+ **kwargs: Any,+ ) -> Union[+ Callable[[CellFuncType], CellFunction[CellFuncTypeBound]],+ CellFunction[CellFuncTypeBound],+ ]:+ """A decorator to add a cell to the app++ This decorator can be called with or without parentheses. Each of the+ following is valid:++ ```+ @app.cell+ def __(mo):+ # ...++ @app.cell()+ def __(mo):+ # ...++ @app.cell(disabled=True)+ def __(mo):+ # ...+ ```++ Args:+ - func: The decorated function+ - disabled: Whether to disable the cell+ - kwargs: For forward-compatibility with future arguments+ """+ del kwargs++ if func is None:+ # If the decorator was used with parentheses, func will be None,+ # and we return a decorator that takes the decorated function as an+ # argument+ def decorator(+ func: CellFuncTypeBound,+ ) -> CellFunction[CellFuncTypeBound]:+ cell_function = cell_factory(func)+ cell_function.cell.configure(CellConfig(disabled=disabled))+ self._register_cell(cell_function)+ return cell_function++ return cast(+ Callable[[CellFuncType], CellFunction[CellFuncTypeBound]],+ decorator,+ )+ else:+ # If the decorator was used without parentheses, func will be the+ # decorated function+ cell_function = cell_factory(func)+ cell_function.cell.configure(CellConfig(disabled=disabled))+ self._register_cell(cell_function)+ return cell_function++ def _register_cell(+ self, cell_function: CellFunction[CellFuncTypeBound]+ ) -> None:cell_id = self._create_cell_id(cell_function)self._cell_data[cell_id] = CellData(cell_id=cell_id,code=cell_function.cell.code,- name=f.__name__,- cell_function=cell_function,+ name=cell_function.__name__,+ config=cell_function.cell.config,+ cell_function=cast(CellFunction[CellFuncType], cell_function),)- return cell_functiondef _names(self) -> Iterable[str]:return (cell_data.name for cell_data in self._cell_data.values())@@ -110,7 +176,12 @@ class App:def _codes(self) -> Iterable[str]:return (cell_data.code for cell_data in self._cell_data.values())- def _cell_functions(self) -> Iterable[Optional[CellFunction]]:+ def _configs(self) -> Iterable[CellConfig]:+ return (cell_data.config for cell_data in self._cell_data.values())++ def _cell_functions(+ self,+ ) -> Iterable[Optional[CellFunction[CellFuncType]]]:return (cell_data.cell_function for cell_data in self._cell_data.values())@@ -148,7 +219,12 @@ class App:f"Fix: Make '{suggested_sig}' this function's signature.")- def _unparsable_cell(self, code: str, name: Optional[str] = None) -> None:+ def _unparsable_cell(+ self,+ code: str,+ name: Optional[str] = None,+ **config: Any,+ ) -> None:cell_id = self._create_cell_id(None)name = name if name is not None else "__"# - code.split("\n")[1:-1] disregards first and last lines, which are@@ -160,7 +236,11 @@ class App:[line[4:].replace('\\"', '"') for line in code.split("\n")[1:-1]])self._cell_data[cell_id] = CellData(- cell_id=cell_id, code=code, name=name, cell_function=None+ cell_id=cell_id,+ code=code,+ name=name,+ config=CellConfig.from_dict(config),+ cell_function=None,)self._unparsable = Truediff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 875fc4cac8..2bb4332fb7 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -2,18 +2,30 @@from __future__ import annotationsimport ast+import dataclassesimport functoolsimport inspectimport ioimport textwrapimport token as token_typesfrom collections.abc import Iterator-from dataclasses import dataclassfrom tokenize import TokenInfo, tokenizefrom types import CodeType-from typing import Any, Callable, Optional, Protocol, Set, Tuple, Union, cast+from typing import (+ Any,+ Callable,+ Literal,+ Optional,+ Protocol,+ Set,+ Tuple,+ TypeVar,+ Union,+ cast,+)from marimo._ast.visitor import Name, ScopedVisitor, _is_local+from marimo._utils.deep_merge import deep_mergeCellId_t = str@@ -22,7 +34,52 @@ def code_key(code: str) -> int:return hash(code)-@dataclass(frozen=True)+class CellConfig:+ # If True, the cell and its descendants cannot be executed,+ # but they can still be added to the graph.+ disabled: bool = False++ @classmethod+ def from_dict(cls, kwargs: dict[str, Any]) -> CellConfig:+ return cls(**{k: v for k, v in kwargs.items() if k in CellConfigKeys})++ def configure(self, update: dict[str, Any] | CellConfig) -> None:+ """Update the config in-place.++ `update` can be a partial config or a CellConfig+ """+ if isinstance(update, CellConfig):+ update = dataclasses.asdict(update)+ new_config = dataclasses.asdict(+ CellConfig.from_dict(deep_merge(dataclasses.asdict(self), update))+ )+ for key, value in new_config.items():+ self.__setattr__(key, value)+++CellConfigKeys = frozenset(+ {field.name for field in dataclasses.fields(CellConfig)}+)++"""+idle: cell has run with latest inputs+queued: cell is queued to run+running: cell is running+stale: cell hasn't run with latest inputs, and can't run (disabled)+disabled-transitively: cell is disabled because a parent is disabled+"""+CellStatusType = Literal[+ "idle", "queued", "running", "stale", "disabled-transitively"+]+++class CellStatus:+ state: Optional[CellStatusType] = None++[email protected](frozen=True)class Cell:key: intcode: str@@ -34,11 +91,48 @@ class Cell:body: Optional[CodeType]last_expr: Optional[CodeType]+ # Mutable fields+ # config: explicit configuration of cell+ config: CellConfig = dataclasses.field(default_factory=CellConfig)+ # staus: status, inferred at runtime+ _status: CellStatus = dataclasses.field(default_factory=CellStatus)++ def configure(self, update: dict[str, Any] | CellConfig) -> Cell:+ """Update the cel config.++ `update` can be a partial config.+ """+ self.config.configure(update)+ return self++ @property+ def status(self) -> Optional[CellStatusType]:+ return self._status.state++ @property+ def stale(self) -> bool:+ return self.status == "stale"++ @property+ def disabled_transitively(self) -> bool:+ return self.status == "disabled-transitively"++ def set_status(self, status: Optional[CellStatusType]) -> None:+ self._status.state = status+++CellFuncType = Callable[..., Optional[Tuple[Any, ...]]]+# Cumbersome, but used to ensure function types don't get erased in decorators+# or creation of CellFunction+CellFuncTypeBound = TypeVar(+ "CellFuncTypeBound",+ bound=Callable[..., Optional[Tuple[Any, ...]]],+)-cell_func_t = Callable[..., Optional[Tuple[Any, ...]]]+class CellFunction(Protocol[CellFuncTypeBound]):+ """Wraps a function from which a Cell object was created."""-class CellFunction(Protocol):cell: Cell# function name__name__: str@@ -46,12 +140,12 @@ class CellFunction(Protocol):code: str# arg names of wrapped functionargs: set[str]- __call__: cell_func_t+ __call__: CellFuncTypeBounddef cell_function(- cell: Cell, args: set[str], code: str, f: cell_func_t-) -> CellFunction:+ cell: Cell, args: set[str], code: str, f: CellFuncTypeBound+) -> CellFunction[CellFuncTypeBound]:signature = inspect.signature(f)n_args = 0@@ -104,7 +198,7 @@ def cell_function(_ = execute_cell(cell, glbls)return tuple(glbls[name] for name in return_names)- cell_func = cast(CellFunction, func)+ cell_func = cast(CellFunction[CellFuncTypeBound], func)cell_func.cell = cellcell_func.args = argscell_func.code = code@@ -157,7 +251,7 @@ def is_ws(char: str) -> bool:return char == " " or char == "\n" or char == "\t"-def cell_factory(f: Callable[..., Any]) -> CellFunction:+def cell_factory(f: CellFuncTypeBound) -> CellFunction[CellFuncTypeBound]:function_code = textwrap.dedent(inspect.getsource(f))# tokenize to find the start of the function body, includingdiff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex 1d59aad19f..d96e9c2a71 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -9,7 +9,7 @@ from typing import Any, Optional, Unionfrom marimo import __version__from marimo._ast.app import App, _AppConfig-from marimo._ast.cell import Cell, parse_cell+from marimo._ast.cell import Cell, CellConfig, parse_cellfrom marimo._ast.visitor import NameINDENT = " "@@ -29,6 +29,19 @@ def _multiline_tuple(elems: Sequence[str]) -> str:return "()"+def _to_decorator(config: Optional[CellConfig]) -> str:+ if config is None or config == CellConfig():+ return "@app.cell"+ else:+ return (+ "@app.cell("+ + ", ".join(+ f"{key}={value}" for key, value in config.__dict__.items()+ )+ + ")"+ )++def to_functiondef(cell: Cell, name: str, unshadowed_builtins: Optional[set[Name]] = None) -> str:@@ -41,7 +54,7 @@ def to_functiondef(refs = [ref for ref in sorted(cell.refs) if ref not in unshadowed_builtins]args = ", ".join(refs)- decorator = "@app.cell"+ decorator = _to_decorator(cell.config)signature = f"def {name}({args}):"if len(INDENT + signature) >= MAX_LINE_LENGTH:signature = f"def {name}{_multiline_tuple(refs)}:"@@ -67,23 +80,27 @@ def to_functiondef(return fndef-def generate_unparseable_cell(code: str, name: Optional[str]) -> str:+def generate_unparseable_cell(+ code: str, name: Optional[str], config: CellConfig+) -> str:# escape double quotes to not interfere with stringquote_escaped_code = code.replace('"', '\\"')# use r-string to handle backslashes (don't want to write# escape characters, want to actually write backslash characters)code_as_str = f'r"""\n{quote_escaped_code}\n"""'- if name is None:- return "app._unparsable_cell(\n" + indent_text(code_as_str) + "\n)"- else:- return (- "app._unparsable_cell(\n"- + indent_text(code_as_str)- + ",\n"+ text = "app._unparsable_cell(\n" + indent_text(code_as_str)+ if name is not None:+ text += ",\n" + INDENT + f'name="{name}"'+ if config != CellConfig():+ text += (+ ",\n"+ INDENT- + f'name="{name}"'- + "\n)"+ + ", ".join(+ f"{key}={value}" for key, value in config.__dict__.items()+ ))+ text += "\n)"+ return textdef generate_app_constructor(config: Optional[_AppConfig]) -> str:@@ -111,19 +128,22 @@ def generate_app_constructor(config: Optional[_AppConfig]) -> str:def generate_filecontents(- codes: list[str], names: list[str], config: Optional[_AppConfig] = None+ codes: list[str],+ names: list[str],+ cell_configs: list[CellConfig],+ config: Optional[_AppConfig] = None,) -> str:"""Translates a sequences of codes (cells) to a Python file"""- cell_function_data: list[Union[Cell, str]] = []+ cell_function_data: list[Union[Cell, tuple[str, CellConfig]]] = []defs: set[Name] = set()- for code in codes:+ for code, cell_config in zip(codes, cell_configs):try:- cell = parse_cell(code)+ cell = parse_cell(code).configure(cell_config)defs |= cell.defscell_function_data.append(cell)except SyntaxError:- cell_function_data.append(code)+ cell_function_data.append((code, cell_config))unshadowed_builtins = set(builtins.__dict__.keys()) - defsfndefs: list[str] = []@@ -131,7 +151,11 @@ def generate_filecontents(if isinstance(data, Cell):fndefs.append(to_functiondef(data, name, unshadowed_builtins))else:- fndefs.append(generate_unparseable_cell(data, name))+ fndefs.append(+ generate_unparseable_cell(+ code=data[0], config=data[1], name=name+ )+ )filecontents = ("import marimo"@@ -190,7 +214,16 @@ def recover(filename: str) -> str:with open(filename, "r") as f:contents = f.read()cells = json.loads(contents)["cells"]- codes, names = tuple(- zip(*[(cell["code"], cell["name"]) for cell in cells])+ codes, names, configs = tuple(+ zip(+ *[+ (+ cell["code"],+ cell["name"],+ cell["config"] if "config" in cell else CellConfig(),+ )+ for cell in cells+ ]+ ))- return generate_filecontents(codes, names)+ return generate_filecontents(codes, names, configs)diff --git a/marimo/_ast/test_app_cell.py b/marimo/_ast/test_app_cell.pynew file mode 100644index 0000000000..83d994d453--- /dev/null+++ b/marimo/_ast/test_app_cell.py@@ -0,0 +1,77 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++from marimo._ast.app import App+from marimo._ast.cell import CellFunction, CellFuncType++# Arg capture+cell_function: CellFunction[CellFuncType] = None # type: ignore[assignment]+++def mock_register_cell(cf: CellFunction[CellFuncType]) -> None:+ global cell_function+ cell_function = cf+++app = App()+app._register_cell = mock_register_cell # type: ignore[method-assign, assignment] # noqa: E501+++def test_decorator_called() -> None:+ # Decorator called+ @app.cell()+ def mock_func1() -> tuple[int]:+ x = 2 + 2+ return (x,)++ assert cell_function.cell.code == "x = 2 + 2"+ assert cell_function.cell.config.disabled is False+ assert len(cell_function.args) == 0+ assert cell_function.__name__ == "mock_func1"+ assert cell_function.__call__ is not None+ assert cell_function.__call__() == (4,)+++def test_decorator_uncalled() -> None:+ # Decorator uncalled+ @app.cell+ def __() -> tuple[int]:+ z = 3 + 3+ return (z,)++ assert cell_function.cell.code == "z = 3 + 3"+ assert cell_function.cell.config.disabled is False+ assert len(cell_function.args) == 0+ assert cell_function.__name__ == "__"+ assert cell_function.__call__ is not None+ assert cell_function.__call__() == (6,)+++def test_decorator_with_args() -> None:+ # Decorator with args+ @app.cell(disabled=True)+ def mock_func3(x: int) -> tuple[int]:+ y = x + 2+ return (y,)++ assert cell_function.cell.code == "y = x + 2"+ assert cell_function.cell.config.disabled is True+ assert cell_function.args == {"x"}+ assert cell_function.__name__ == "mock_func3"+ assert cell_function.__call__ is not None+ assert cell_function.__call__(2) == (4,)+++def test_decorator_with_unknown_args() -> None:+ # Decorator with unknown args+ @app.cell(foo=True)+ def __() -> tuple[int]:+ x = 2 + 2+ return (x,)++ assert cell_function.cell.code == "x = 2 + 2"+ assert cell_function.cell.config.disabled is False+ assert len(cell_function.args) == 0+ assert cell_function.__name__ == "__"+ assert cell_function.__call__ is not None+ assert cell_function.__call__() == (4,)diff --git a/marimo/_ast/test_cell.py b/marimo/_ast/test_cell.pyindex 016144b783..911f8de7db 100644--- a/marimo/_ast/test_cell.py+++ b/marimo/_ast/test_cell.py@@ -76,7 +76,7 @@ class TestCellFactory:return xwith pytest.raises(ValueError) as e:- cell_factory(f)+ cell_factory(f) # type: ignore[type-var]assert "must return a tuple" in str(e.value)@@ -110,8 +110,8 @@ class TestCellFactory:@staticmethoddef test_extra_returns() -> None:- def f() -> int:- return 1+ def f() -> tuple[int]:+ return (1,)with pytest.raises(ValueError) as e:cell_factory(f)diff --git a/marimo/_ast/test_codegen.py b/marimo/_ast/test_codegen.pyindex 3b37441f15..2c7c0b2868 100644--- a/marimo/_ast/test_codegen.py+++ b/marimo/_ast/test_codegen.py@@ -5,10 +5,11 @@ import jsonimport osimport tempfilefrom inspect import cleandoc+from typing import Optionalfrom marimo import __version__from marimo._ast import codegen-from marimo._ast.cell import parse_cell+from marimo._ast.cell import CellConfig, parse_cellDIR_PATH = os.path.dirname(os.path.realpath(__file__))@@ -36,6 +37,20 @@ def get_filepath(name: str) -> str:return os.path.join(DIR_PATH, f"../_test_utils/codegen_data/{name}.py")+def generate_filecontents(+ codes: list[str],+ names: list[str],+ configs: Optional[list[CellConfig]] = None,+) -> str:+ if configs is None:+ resolved_configs = [CellConfig() for _ in range(len(codes))]+ else:+ resolved_configs = configs+ return codegen.generate_filecontents(+ codes, names, cell_configs=resolved_configs+ )++class TestGeneration:@staticmethoddef test_generate_filecontents() -> None:@@ -46,7 +61,7 @@ class TestGeneration:cell_five = "# just a comment"codes = [cell_one, cell_two, cell_three, cell_four, cell_five]names = ["one", "two", "three", "four", "five"]- contents = codegen.generate_filecontents(codes, names)+ contents = generate_filecontents(codes, names)assert contents == get_expected_filecontents("test_generate_filecontents")@@ -56,7 +71,7 @@ class TestGeneration:cell_one = "import numpy as np"codes = [cell_one]names = ["one"]- contents = codegen.generate_filecontents(codes, names)+ contents = generate_filecontents(codes, names)assert contents == get_expected_filecontents("test_generate_filecontents_single_cell")@@ -69,7 +84,7 @@ class TestGeneration:cell_four = '_ another_error\n_ and """another"""\n\n \\t'codes = [cell_one, cell_two, cell_three, cell_four]names = ["one", "two", "__", "__"]- contents = codegen.generate_filecontents(codes, names)+ contents = generate_filecontents(codes, names)assert contents == get_expected_filecontents("test_generate_filecontents_with_syntax_error")@@ -77,10 +92,8 @@ class TestGeneration:@staticmethoddef test_generate_unparseable_cell() -> None:code = " error\n\\t"- raw = codegen.generate_unparseable_cell(code, None)- print(raw)+ raw = codegen.generate_unparseable_cell(code, None, CellConfig())stringified = eval("\n".join(raw.split("\n")[1:5])).split("\n")- print(stringified)# first line emptyassert not stringified[0]# leading 4 spaces followed by source line@@ -104,9 +117,7 @@ class TestGeneration:+ "i_am_another_very_long_name + "+ "yet_another_very_long_name")- contents = codegen.generate_filecontents(- [cell_one, cell_two], ["one", "two"]- )+ contents = generate_filecontents([cell_one, cell_two], ["one", "two"])assert contents == get_expected_filecontents("test_long_line_in_main")@staticmethod@@ -114,7 +125,7 @@ class TestGeneration:cell_one = "type"codes = [cell_one]names = ["one"]- contents = codegen.generate_filecontents(codes, names)+ contents = generate_filecontents(codes, names)assert contents == get_expected_filecontents("test_generate_filecontents_unshadowed_builtin")@@ -125,7 +136,7 @@ class TestGeneration:cell_two = "type"codes = [cell_one, cell_two]names = ["one", "two"]- contents = codegen.generate_filecontents(codes, names)+ contents = generate_filecontents(codes, names)assert contents == get_expected_filecontents("test_generate_filecontents_shadowed_builtin")@@ -287,6 +298,31 @@ class TestToFunctionDef:)assert fndef == expected+ def test_with_empty_config(self) -> None:+ code = "x = 0"+ cell = parse_cell(code)+ cell = cell.configure(CellConfig())+ fndef = codegen.to_functiondef(cell, "foo")+ expected = "\n".join(+ ["@app.cell", "def foo():", " x = 0", " return x,"]+ )+ assert fndef == expected++ def test_with_some_config(self) -> None:+ code = "x = 0"+ cell = parse_cell(code)+ cell = cell.configure(CellConfig(disabled=True))+ fndef = codegen.to_functiondef(cell, "foo")+ expected = "\n".join(+ [+ "@app.cell(disabled=True)",+ "def foo():",+ " x = 0",+ " return x,",+ ]+ )+ assert fndef == expected+def test_recover() -> None:cells = {@@ -309,7 +345,7 @@ def test_recover() -> None:]names = ["a", "b", "c"]- expected = codegen.generate_filecontents(codes, names)+ expected = generate_filecontents(codes, names)assert recovered == expecteddiff --git a/marimo/_cli/ipynb_to_marimo.py b/marimo/_cli/ipynb_to_marimo.pyindex 907e53a7f6..24181af913 100644--- a/marimo/_cli/ipynb_to_marimo.py+++ b/marimo/_cli/ipynb_to_marimo.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonfrom marimo._ast import codegen+from marimo._ast.cell import CellConfigdef convert(ipynb_path: str) -> str:@@ -33,4 +34,8 @@ def convert(ipynb_path: str) -> str:if has_markdown:sources.append("import marimo as mo")- return codegen.generate_filecontents(sources, ["_" for _ in sources])+ return codegen.generate_filecontents(+ sources,+ ["_" for _ in sources],+ [CellConfig() for _ in range(len(sources))],+ )diff --git a/marimo/_cli/test_cli.py b/marimo/_cli/test_cli.pyindex 7b8bddfc2f..cb44958765 100644--- a/marimo/_cli/test_cli.py+++ b/marimo/_cli/test_cli.py@@ -13,6 +13,7 @@ import urllib.requestfrom typing import Optionalfrom marimo._ast import codegen+from marimo._ast.cell import CellConfigdef _try_fetch(port: int) -> Optional[bytes]:@@ -75,7 +76,7 @@ def test_cli_edit() -> None:def test_cli_run() -> None:filecontents = codegen.generate_filecontents(- ["import marimo as mo"], ["one"]+ ["import marimo as mo"], ["one"], cell_configs=[CellConfig()])d = tempfile.TemporaryDirectory()path = os.path.join(d.name, "run.py")diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 43105e4147..a59e532d3a 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -2,7 +2,7 @@from __future__ import annotationsimport sys-from typing import Any, Optional, TypeVar, cast+from typing import Any, Dict, Optional, castfrom typing_extensions import Literal@@ -12,6 +12,7 @@ else:from typing import TypedDictfrom marimo._output.rich_help import mddoc+from marimo._utils.deep_merge import deep_merge@mddoc@@ -86,7 +87,7 @@ class MarimoConfig(TypedDict, total=False):completion: CompletionConfigsave: SaveConfigkeymap: KeymapConfig- experimental: dict[str, Any]+ experimental: Dict[str, Any]DEFAULT_CONFIG: MarimoConfig = {@@ -96,35 +97,6 @@ DEFAULT_CONFIG: MarimoConfig = {}_USER_CONFIG: Optional[MarimoConfig] = None-ConfigType = TypeVar(- "ConfigType", MarimoConfig, SaveConfig, CompletionConfig, KeymapConfig-)---# TODO(akshayka): Type-safety, can't index into TypedDict with nonliteral-def _merge_key(defaults: Any, override: Any, key: str) -> Any:- if key not in defaults:- # forward compatibility: old versions of marimo won't be aware of new- # settings. Config might also have misspelled keys, but shouldn't fail- # if that happens.- return override[key]- elif key not in override:- return defaults[key]- elif not isinstance(defaults[key], dict):- return override[key]- else:- return _merge_configs(defaults[key], override[key])---def _merge_configs(defaults: ConfigType, override: ConfigType) -> ConfigType:- return cast(- ConfigType,- {- key: _merge_key(defaults, override, key)- for key in set(defaults.keys()).union(set(override.keys()))- },- )-@mddocdef configure(config: MarimoConfig) -> MarimoConfig:@@ -135,8 +107,12 @@ def configure(config: MarimoConfig) -> MarimoConfig:- `config`: A configuration object."""global _USER_CONFIG- # Robust merging of configs (want to merge on leaves, not just keys)- _USER_CONFIG = cast(MarimoConfig, _merge_configs(DEFAULT_CONFIG, config))+ _USER_CONFIG = cast(+ MarimoConfig,+ deep_merge(+ cast(Dict[Any, Any], DEFAULT_CONFIG), cast(Dict[Any, Any], config)+ ),+ )return _USER_CONFIGdiff --git a/marimo/_messaging/message_types.py b/marimo/_messaging/message_types.pyindex 0350c90d22..cac44a5eaf 100644--- a/marimo/_messaging/message_types.py+++ b/marimo/_messaging/message_types.py@@ -8,9 +8,9 @@ from __future__ import annotationsimport timefrom dataclasses import asdict, dataclass, field-from typing import ClassVar, Dict, Literal, Optional, Union, cast+from typing import ClassVar, Dict, Optional, Union, cast-from marimo._ast.cell import CellId_t+from marimo._ast.cell import CellConfig, CellId_t, CellStatusTypefrom marimo._messaging.cell_output import CellOutputfrom marimo._messaging.completion_option import CompletionOptionfrom marimo._plugins.core.web_component import JSONType@@ -20,7 +20,7 @@ from marimo._plugins.core.web_component import JSONType## output - a CellOutput# console - a CellOutput (console message to append), or a list of CellOutputs-# status - execution status (idle, queued, running)+# status - execution status## NB: omitting a field means that its value should be unchanged#@@ -33,7 +33,7 @@ class CellOp:cell_id: CellId_toutput: Optional[CellOutput] = Noneconsole: Optional[Union[CellOutput, list[CellOutput]]] = None- status: Optional[Literal["idle", "queued", "running"]] = None+ status: Optional[CellStatusType] = Nonetimestamp: float = field(default_factory=lambda: time.time())@@ -58,6 +58,7 @@ class KernelReady:name: ClassVar[str] = "kernel-ready"codes: tuple[str, ...]names: tuple[str, ...]+ configs: tuple[CellConfig, ...]@dataclassdiff --git a/marimo/_messaging/messages.py b/marimo/_messaging/messages.pyindex d4e338191e..40da7b02d2 100644--- a/marimo/_messaging/messages.py+++ b/marimo/_messaging/messages.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport sysfrom typing import Any, Optional, Sequence-from marimo._ast.cell import CellId_t+from marimo._ast.cell import CellId_t, CellStatusTypefrom marimo._messaging.cell_output import CellOutputfrom marimo._messaging.errors import Errorfrom marimo._messaging.message_types import (@@ -20,7 +20,11 @@ from marimo._runtime.context import get_contextdef write_output(- channel: str, mimetype: str, data: str, cell_id: CellId_t+ channel: str,+ mimetype: str,+ data: str,+ cell_id: CellId_t,+ status: Optional[CellStatusType],) -> None:if (size := sys.getsizeof(data)) > OUTPUT_MAX_BYTES:from marimo._output.md import md@@ -53,12 +57,35 @@ def write_output(mimetype=mimetype,data=data,),- status="idle",+ status=status,)),)+def write_stale(cell_id: CellId_t) -> None:+ get_context().stream.write(+ op=CellOp.name,+ data=serialize(CellOp(cell_id=cell_id, status="stale")),+ )+++def write_idle(cell_id: CellId_t) -> None:+ get_context().stream.write(+ op=CellOp.name,+ data=serialize(CellOp(cell_id=cell_id, status="idle")),+ )+++def write_disabled_transitively(cell_id: CellId_t) -> None:+ get_context().stream.write(+ op=CellOp.name,+ data=serialize(+ CellOp(cell_id=cell_id, status="disabled-transitively")+ ),+ )++def write_queued(cell_id: CellId_t) -> None:get_context().stream.write(op=CellOp.name,@@ -74,7 +101,10 @@ def write_new_run(cell_id: CellId_t) -> None:def write_marimo_error(- data: Sequence[Error], clear_console: bool, cell_id: CellId_t+ data: Sequence[Error],+ clear_console: bool,+ cell_id: CellId_t,+ status: Optional[CellStatusType],) -> None:console: Optional[list[CellOutput]] = [] if clear_console else Noneget_context().stream.write(@@ -88,7 +118,7 @@ def write_marimo_error(data=data,),console=console,- status="idle",+ status=status,)),)@@ -114,7 +144,7 @@ def write_output_to_global_stream() -> None:stream = get_context().streamassert stream.cell_id is not None- write_output(channel, mimetype, data, stream.cell_id)+ write_output(channel, mimetype, data, stream.cell_id, status=None)def write_to_global_console_stream(diff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/cell_runner.pyindex 4437ebe4fd..4625c6d100 100644--- a/marimo/_runtime/cell_runner.py+++ b/marimo/_runtime/cell_runner.py@@ -148,12 +148,19 @@ class Runner:glbls: dict[Any, Any],):self.graph = graph+ # runtime globalsself.glbls = glbls+ # cells that the runner will run.self.cells_to_run = dataflow.topological_sort(graph, cell_ids)+ # map from a cell that was cancelled to its descendants that have+ # not yet run:self.cells_cancelled: dict[CellId_t, set[CellId_t]] = {}+ # whether the runner has been interruptedself.interrupted = False+ # mapping from cell_id to exception it raisedself.exceptions: dict[CellId_t, Exception] = {}+ # each cell's position in the run queueself._run_position = {cell_id: index for index, cell_id in enumerate(self.cells_to_run)}@@ -270,11 +277,13 @@ class Runner:return_value = execute_cell(cell, self.glbls)run_result = RunResult(output=return_value, exception=None)except MarimoInterrupt as e:+ # User interrupt# interrupt the entire runnerself.interrupted = Truerun_result = RunResult(output=None, exception=e)self.print_traceback()except MarimoStopError as e:+ # Raised by mo.stop().# cancel only the descendants of this cellself.cancel(cell_id)run_result = RunResult(output=e.output, exception=e)diff --git a/marimo/_runtime/conftest.py b/marimo/_runtime/conftest.pyindex 032e23a911..1690249917 100644--- a/marimo/_runtime/conftest.py+++ b/marimo/_runtime/conftest.py@@ -6,6 +6,7 @@ from typing import Any, Generatorimport pytest+from marimo._ast.cell import CellId_tfrom marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.context import get_contextfrom marimo._runtime.requests import ExecutionRequest@@ -48,6 +49,9 @@ class ExecReqProvider:self.counter += 1return ExecutionRequest(key, textwrap.dedent(code))+ def get_with_id(self, cell_id: CellId_t, code: str) -> ExecutionRequest:+ return ExecutionRequest(cell_id, textwrap.dedent(code))+# fixture that provides an ExecReqProvider@pytest.fixturediff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.pyindex bb81bc0f4f..3ced2043b5 100644--- a/marimo/_runtime/dataflow.py+++ b/marimo/_runtime/dataflow.py@@ -14,6 +14,8 @@ Edge = Tuple[CellId_t, CellId_t]LOGGER = _loggers.marimo_logger()+# TODO(akshayka): Add method disable_cell, enable_cell which handle+# state transitions on cells@dataclass(frozen=True)class DirectedGraph:# Nodes in the graph@@ -190,6 +192,26 @@ class DirectedGraph:return children+ def is_disabled(self, cell_id: CellId_t) -> bool:+ if cell_id not in self.cells:+ raise ValueError(f"Cell {cell_id} not in graph.")+ cell = self.cells[cell_id]+ if cell.config.disabled:+ return True+ seen: set[CellId_t] = set()+ queue = [cell_id]+ while queue:+ cid = queue.pop()+ seen.add(cid)+ for parent_id in self.parents[cid]:+ if parent_id in seen:+ continue+ elif self.cells[parent_id].config.disabled:+ return True+ else:+ queue.append(parent_id)+ return False+def transitive_closure(graph: DirectedGraph, cell_ids: set[CellId_t]diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 9ec02faa97..e25d809fb5 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -25,6 +25,11 @@ class SetUIElementValueRequest:ids_and_values: Iterable[tuple[str, Any]]+@dataclass+class SetCellConfigRequest:+ configs: dict[CellId_t, dict[str, object]]++@dataclassclass CreationRequest:execution_requests: tuple[ExecutionRequest, ...]@@ -59,6 +64,7 @@ Request = Union[ExecuteMultipleRequest,CreationRequest,DeleteRequest,+ SetCellConfigRequest,SetUIElementValueRequest,StopRequest,CompletionRequest,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 89a2016acc..c2dae199dd 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport builtinsimport contextlib+import dataclassesimport ioimport itertoolsimport multiprocessing as mp@@ -13,12 +14,11 @@ import threadingimport timeimport tracebackfrom collections.abc import Iterable, Sequence-from dataclasses import dataclassfrom queue import Empty as QueueEmptyfrom typing import Any, Iterator, Optionalfrom marimo import _loggers-from marimo._ast.cell import CellId_t, parse_cell+from marimo._ast.cell import CellConfig, CellId_t, parse_cellfrom marimo._config.config import configurefrom marimo._messaging.errors import (Error,@@ -30,12 +30,15 @@ from marimo._messaging.errors import ()from marimo._messaging.messages import (write_completed_run,+ write_disabled_transitively,+ write_idle,write_interrupted,write_marimo_error,write_new_run,write_output,write_queued,write_remove_ui_elements,+ write_stale,)from marimo._messaging.streams import Stderr, Stdout, Stream, redirect_streamsfrom marimo._output.rich_help import mddoc@@ -57,6 +60,7 @@ from marimo._runtime.requests import (ExecuteMultipleRequest,ExecutionRequest,Request,+ SetCellConfigRequest,SetUIElementValueRequest,StopRequest,)@@ -114,12 +118,24 @@ def refs() -> tuple[str, ...]:return tuple()-@dataclassclass ExecutionContext:cell_id: CellId_tsetting_element_value: bool+class CellMetadata:+ """CellMetadata++ Metadata the kernel needs to persist, even when a cell is removed+ from the graph or when a cell can't be formed from user code due to syntax+ errors.+ """++ config: CellConfig = dataclasses.field(default_factory=CellConfig)++class Kernel:def __init__(self) -> None:self.globals: dict[Any, Any] = {@@ -127,6 +143,8 @@ class Kernel:"__builtins__": globals()["__builtins__"],}self.graph = dataflow.DirectedGraph()+ self.cell_metadata: dict[CellId_t, CellMetadata] = {}+self.execution_context: Optional[ExecutionContext] = None# initializers to override construction of ui elementsself.ui_initializers: dict[str, Any] = {}@@ -191,11 +209,21 @@ class Kernel:tmpio.seek(0)error = UnknownError(msg=tmpio.read())+ if cell_id in self.cell_metadata and cell is not None:+ # If we already have a config for this cell id, restore it+ # This can happen when a cell was previously deactivated (due to a+ # syntax error or multiple definition error, for example) and then+ # re-registered+ cell.configure(self.cell_metadata[cell_id].config)+ elif cell_id not in self.cell_metadata:+ self.cell_metadata[cell_id] = CellMetadata()+if cell is not None:self.graph.register_cell(cell_id, cell)LOGGER.debug("registered cell %s", cell_id)LOGGER.debug("parents: %s", self.graph.parents[cell_id])LOGGER.debug("children: %s", self.graph.children[cell_id])+return errordef _maybe_register_cell(@@ -218,7 +246,7 @@ class Kernel:if not self.graph.is_cell_cached(cell_id, code):if cell_id in self.graph.cells:LOGGER.debug("Deleting cell %s", cell_id)- previous_children = self._delete_cell(cell_id)+ previous_children = self._deactivate_cell(cell_id)error = self._try_registering_cell(cell_id, code)LOGGER.debug(@@ -262,13 +290,13 @@ class Kernel:)write_remove_ui_elements(cell_id)- def _delete_cell(self, cell_id: CellId_t) -> set[CellId_t]:- """Delete a cell from the kernel and the graph.+ def _deactivate_cell(self, cell_id: CellId_t) -> set[CellId_t]:+ """Deactivate: remove from graph, invalidate state, but keep metadata- Deletion from the kernel involves removing cell's defs and- de-registering its UI Elements.+ Keeps the cell's config, in case we see the same cell again.- Deletion from graph is forwarded to graph object.+ In contrast to deleting a cell, which fully scrubs the cell+ from the kernel and graph."""if cell_id not in self.errors:self._invalidate_cell_state(cell_id)@@ -277,10 +305,22 @@ class Kernel:# An errored cell can be thought of as a cell that's in the graph# but that has no state in the kernel (because it was never run).# Its defs may overlap with defs of a non-errored cell, so we MUST- # NOT delete/cleanup its defs from the kernel.+ # NOT delete/cleanup its defs from the kernel (i.e., an errored+ # cell shouldn't invalidate state of another cell).self.graph.delete_cell(cell_id)return set()+ def _delete_cell(self, cell_id: CellId_t) -> set[CellId_t]:+ """Delete a cell from the kernel and the graph.++ Deletion from the kernel involves removing cell's defs and+ de-registering its UI Elements.++ Deletion from graph is forwarded to graph object.+ """+ del self.cell_metadata[cell_id]+ return self._deactivate_cell(cell_id)+def mutate_graph(self,execution_requests: Sequence[ExecutionRequest],@@ -290,10 +330,10 @@ class Kernel:This method adds the cells in `execution_requests` to the kernel'sgraph (deleting old versions of these cells, if any), and removes the- cells in `execution_requests` from the kernel's graph.+ cells in `deletion_requests` from the kernel's graph.The mutations that this method makes to the graph renders the- kernel inconsistent.+ kernel inconsistent (stale).This method does not register errors for cells that were previouslyvalid and are not descendants of any of the newly registered cells.@@ -396,6 +436,15 @@ class Kernel:cells_with_errors_before_mutation- cells_with_errors_after_mutation) & cells_in_graph+ for cid in cells_that_no_longer_have_errors:+ # clear error outputs before running+ write_output(+ "output",+ mimetype="text/plain",+ data="",+ cell_id=cid,+ status=None,+ )# Cells that were successfully registered need to be runcells_registered_without_error = (@@ -442,8 +491,21 @@ class Kernel:self.errors = all_errorsfor cid in self.errors:+ if (+ # Cells with syntax errors are not in the graph+ cid in self.graph.cells+ and not self.graph.cells[cid].config.disabled+ and self.graph.is_disabled(cid)+ ):+ # this may be the first time we're seeing the cell: set its+ # status+ self.graph.cells[cid].set_status("disabled-transitively")+ write_disabled_transitively(cid)write_marimo_error(- data=self.errors[cid], clear_console=True, cell_id=cid+ data=self.errors[cid],+ clear_console=True,+ cell_id=cid,+ status=None,)return descendants@@ -459,11 +521,21 @@ class Kernel:write_completed_run()def _run_cells_internal(self, cell_ids: set[CellId_t]) -> set[CellId_t]:- """Run cells, send outputs to frontends"""+ """Run cells, send outputs to frontends++ Returns set of cells that need to be re-run due to state updates.+ """LOGGER.debug("preparing to evaluate cells %s", cell_ids)- for cid in cell_ids:- write_queued(cell_id=cid)+ # Status updates: cells transition to queued, except for+ # cells that are disabled (explicity or implicitly).+ for cid in cell_ids:+ if self.graph.is_disabled(cid):+ self.graph.cells[cid].set_status(status="stale")+ write_stale(cell_id=cid)+ else:+ self.graph.cells[cid].set_status(status="queued")+ write_queued(cell_id=cid)runner = cell_runner.Runner(cell_ids=cell_ids,graph=self.graph,@@ -485,15 +557,20 @@ class Kernel:cell_id = runner.pop_cell()if runner.cancelled(cell_id):continue+ # State clean-up: don't leak names, UI elements, ...+ self._invalidate_cell_state(cell_id)+ cell = self.graph.cells[cell_id]+ if cell.stale:+ continueLOGGER.debug("running cell %s", cell_id)+ cell.set_status(status="running")write_new_run(cell_id)- # State clean-up: don't leak names, UI elements, ...- self._invalidate_cell_state(cell_id)with self._install_execution_context(cell_id):run_result = runner.run(cell_id)+ cell.set_status(status="idle")if run_result.success():formatted_output = run_result.format_output()if formatted_output.traceback is not None:@@ -504,6 +581,7 @@ class Kernel:mimetype=formatted_output.mimetype,data=formatted_output.data,cell_id=cell_id,+ status=cell.status,)elif isinstance(run_result.exception, MarimoStopError):LOGGER.debug("Cell %s was stopped via mo.stop()", cell_id)@@ -516,6 +594,7 @@ class Kernel:mimetype=formatted_output.mimetype,data=formatted_output.data,cell_id=cell_id,+ status=cell.status,)elif isinstance(run_result.exception, MarimoInterrupt):LOGGER.debug("Cell %s was interrupted", cell_id)@@ -525,6 +604,7 @@ class Kernel:data=[MarimoInterruptionError()],clear_console=False,cell_id=cell_id,+ status=cell.status,)elif run_result.exception is not None:LOGGER.debug(@@ -551,6 +631,7 @@ class Kernel:],clear_console=False,cell_id=cell_id,+ status=cell.status,)if get_global_context().mpl_installed:@@ -561,6 +642,7 @@ class Kernel:assert runner.interruptedfor cid in runner.cells_to_run:# `cid` was not run. Its defs should be deleted.+ self.graph.cells[cid].set_status("idle")self._invalidate_cell_state(cid)write_marimo_error(data=[MarimoInterruptionError()],@@ -569,11 +651,13 @@ class Kernel:# reflect a previous run and should be clearedclear_console=True,cell_id=cid,+ status="idle",)for raising_cell in runner.cells_cancelled:for cid in runner.cells_cancelled[raising_cell]:# `cid` was not run. Its defs should be deleted.+ self.graph.cells[cid].set_status("idle")self._invalidate_cell_state(cid)exception = runner.exceptions[raising_cell]data: Error@@ -604,6 +688,7 @@ class Kernel:# reflect a previous run and should be clearedclear_console=True,cell_id=cid,+ status="idle",)cells_with_stale_state = runner.resolve_state_updates(@@ -643,6 +728,56 @@ class Kernel:self.mutate_graph(execution_requests, deletion_requests=[]))+ def set_cell_config(self, request: SetCellConfigRequest) -> None:+ """Update cell configs.++ Cells that are enabled (via config) but stale are run as a side-effect.+ """+ # TODO: state transitions to disabled-transitively, stale, idle should+ # be handled by the graph, not by kernel ...+ # Stale cells that are enabled will need to be run.+ cells_to_run: set[CellId_t] = set()+ for cell_id, config in request.configs.items():+ cell = self.graph.cells.get(cell_id)+ if cell is not None:+ cell.configure(config)+ if not cell.config.disabled:+ # When a cell is enabled, previously stale cells will+ # need to run+ for cid in dataflow.transitive_closure(+ self.graph, set([cell_id])+ ):+ if not self.graph.is_disabled(cid):+ child = self.graph.cells[cid]+ if child.stale:+ # cell was previously disabled, is no longer+ # disabled, and is stale: needs to run.+ cells_to_run.add(cid)+ elif child.disabled_transitively:+ write_idle(cid)+ # cell is no longer disabled: status -> idle+ child.set_status("idle")+ elif cell.config.disabled:+ # When a cell is disabled, we need to tell the frontend+ # that its children are transitively disabled+ for cid in dataflow.transitive_closure(+ self.graph, set([cell_id])+ ):+ if not self.graph.cells[cid].stale and cid != cell_id:+ self.graph.cells[cid].set_status(+ status="disabled-transitively"+ )+ write_disabled_transitively(cid)++ # store the config, regardless of whether we've seen the cell yet+ self.cell_metadata[cell_id] = CellMetadata(+ config=CellConfig.from_dict(config)+ )+ if cells_to_run:+ self._run_cells(+ dataflow.transitive_closure(self.graph, cells_to_run)+ )+def set_ui_element_value(self, request: SetUIElementValueRequest) -> None:"""Set the value of a UI element bound to a global variable.@@ -843,6 +978,8 @@ def launch_kernel(kernel.instantiate(request)elif isinstance(request, ExecuteMultipleRequest):kernel.run(request.execution_requests)+ elif isinstance(request, SetCellConfigRequest):+ kernel.set_cell_config(request)elif isinstance(request, SetUIElementValueRequest):kernel.set_ui_element_value(request)elif isinstance(request, DeleteRequest):diff --git a/marimo/_runtime/test_runtime.py b/marimo/_runtime/test_runtime.pyindex 5add4d63e8..9e876fcd4a 100644--- a/marimo/_runtime/test_runtime.py+++ b/marimo/_runtime/test_runtime.py@@ -10,11 +10,13 @@ from marimo._messaging.errors import (MultipleDefinitionError,)from marimo._plugins.ui._core.ids import IDProvider+from marimo._runtime.conftest import ExecReqProviderfrom marimo._runtime.dataflow import Edgefrom marimo._runtime.requests import (CreationRequest,DeleteRequest,ExecutionRequest,+ SetCellConfigRequest,SetUIElementValueRequest,)from marimo._runtime.runtime import Kernel@@ -278,3 +280,296 @@ def test_syntax_error(k: Kernel) -> None:assert "0" in k.graph.cellsassert "1" in k.graph.cellsassert not k.errors+++def test_disable_and_reenable_not_stale(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ k.run(+ [+ (+ er_1 := exec_req.get(+ """+ class namespace:+ ...+ ns = namespace()+ ns.count = 0+ """+ )+ ),+ (er_2 := exec_req.get("ns.count += 1")),+ ]+ )+ assert k.globals["ns"].count == 1+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale++ # disable and re-enable cell 2: cell 2 should not re-run because it+ # shouldn't have passed through stale status+ # disable cell 2+ k.set_cell_config(SetCellConfigRequest({er_2.cell_id: {"disabled": True}}))+ assert k.globals["ns"].count == 1+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale++ # re-enable cell 2+ k.set_cell_config(+ SetCellConfigRequest({er_2.cell_id: {"disabled": False}})+ )+ # cell 2 should **not** have re-run+ assert k.globals["ns"].count == 1+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+++def test_disable_and_reenable_stale(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ k.run(+ [+ (+ er_1 := exec_req.get(+ """+ class namespace:+ ...+ ns = namespace()+ ns.count = 0+ """+ )+ ),+ (er_2 := exec_req.get("ns.count += 1")),+ ]+ )+ assert k.globals["ns"].count == 1+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale++ # disable and re-enable cell 2, making it stale in between;+ # cell 2 should re-run on enable+ k.set_cell_config(SetCellConfigRequest({er_2.cell_id: {"disabled": True}}))+ k.run(+ [+ exec_req.get_with_id(+ er_1.cell_id,+ """+ class namespace:+ ...+ ns = namespace()+ ns.count = 10+ """,+ )+ ]+ )++ assert k.globals["ns"].count == 10+ assert not k.graph.cells[er_1.cell_id].stale+ assert k.graph.cells[er_2.cell_id].stale++ # re-enable cell 2+ k.set_cell_config(+ SetCellConfigRequest({er_2.cell_id: {"disabled": False}})+ )+ # cell 2 should have re-run+ assert k.globals["ns"].count == 11+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+++def test_disable_and_reenable_tree(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ # x+ # x --> y+ # x, y --> z+ k.run(+ [+ (er_1 := exec_req.get("x = 1")),+ (er_2 := exec_req.get("y = x + 1")),+ (er_3 := exec_req.get("z = x + y")),+ (er_4 := exec_req.get("zz = z + 1")),+ (er_5 := exec_req.get("zzz = x + 1")),+ ]+ )+ assert k.globals["x"] == 1+ assert k.globals["y"] == 2+ assert k.globals["z"] == 3+ assert k.globals["zz"] == 4+ assert k.globals["zzz"] == 2++ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ assert not k.graph.cells[er_4.cell_id].stale+ assert not k.graph.cells[er_5.cell_id].stale++ # disable cell 2+ k.set_cell_config(SetCellConfigRequest({er_2.cell_id: {"disabled": True}}))++ k.run([ExecutionRequest(er_1.cell_id, "x = 2")])+ assert k.globals["x"] == 2+ assert k.globals["zzz"] == 3++ # stale cells' state is gone+ assert "y" not in k.globals+ assert "z" not in k.globals+ assert "zz" not in k.globals++ # cell 1 is not disabled+ assert not k.graph.cells[er_1.cell_id].stale+ # cell 2 stale because disabled and cannot run+ assert k.graph.cells[er_2.cell_id].stale+ # cell 3 stale because its parent (cell 2) is disabled+ assert k.graph.cells[er_3.cell_id].stale+ # cell 4 stale because cell 2 (an ancestor) is disabled+ assert k.graph.cells[er_4.cell_id].stale+ # cell 5 is not disabled+ assert not k.graph.cells[er_5.cell_id].stale++ # enable cell 2: should run stale cells as a side-effect+ k.set_cell_config(+ SetCellConfigRequest({er_2.cell_id: {"disabled": False}})+ )+ assert k.globals["x"] == 2+ assert k.globals["zzz"] == 3++ # stale cells **should have** updated+ assert k.globals["y"] == 3+ assert k.globals["z"] == 5+ assert k.globals["zz"] == 6++ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ assert not k.graph.cells[er_4.cell_id].stale+ assert not k.graph.cells[er_5.cell_id].stale+++def test_disable_consecutive(k: Kernel, exec_req: ExecReqProvider) -> None:+ k.run(+ [+ (er_1 := exec_req.get("x = 1")),+ (er_2 := exec_req.get("y = x + 1")),+ ]+ )+ assert k.globals["x"] == 1+ assert k.globals["y"] == 2+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale++ # disable both cells+ k.set_cell_config(SetCellConfigRequest({er_1.cell_id: {"disabled": True}}))+ k.set_cell_config(SetCellConfigRequest({er_2.cell_id: {"disabled": True}}))+ # update the code of cell 1 -- both cells stale+ k.run([exec_req.get_with_id(er_1.cell_id, "x = 2")])+ assert "x" not in k.globals+ assert "y" not in k.globals+ assert k.graph.cells[er_1.cell_id].stale+ assert k.graph.cells[er_2.cell_id].stale++ # enable cell 1, but 2 still disabled+ k.set_cell_config(+ SetCellConfigRequest({er_1.cell_id: {"disabled": False}})+ )+ assert k.globals["x"] == 2+ assert "y" not in k.globals+ assert not k.graph.cells[er_1.cell_id].stale+ assert k.graph.cells[er_2.cell_id].stale++ # enable cell 2+ k.set_cell_config(+ SetCellConfigRequest({er_2.cell_id: {"disabled": False}})+ )+ assert k.globals["x"] == 2+ assert k.globals["y"] == 3+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+++def test_disable_syntax_error(k: Kernel, exec_req: ExecReqProvider) -> None:+ k.run(+ [+ (er_1 := exec_req.get("x = 1")),+ ]+ )+ assert k.globals["x"] == 1++ # disable cell+ k.set_cell_config(SetCellConfigRequest({er_1.cell_id: {"disabled": True}}))++ # add a syntax error+ k.run([exec_req.get_with_id(er_1.cell_id, "x 2")])+ assert "x" not in k.globals++ # repair syntax, cell should still be disabled+ k.run([exec_req.get_with_id(er_1.cell_id, "x = 2")])+ assert "x" not in k.globals+ assert k.graph.cells[er_1.cell_id].stale++ # enable: should run+ k.set_cell_config(+ SetCellConfigRequest({er_1.cell_id: {"disabled": False}})+ )+ assert k.globals["x"] == 2+ assert not k.graph.cells[er_1.cell_id].stale+++def test_disable_cycle(k: Kernel, exec_req: ExecReqProvider) -> None:+ k.run(+ [+ (er_1 := exec_req.get("a = b")),+ (er_2 := exec_req.get("b = a")),+ ]+ )+ k.set_cell_config(SetCellConfigRequest({er_1.cell_id: {"disabled": True}}))+ assert k.graph.cells[er_1.cell_id].config.disabled+ assert k.graph.cells[er_2.cell_id].disabled_transitively++ k.set_cell_config(SetCellConfigRequest({er_2.cell_id: {"disabled": True}}))+ k.set_cell_config(+ SetCellConfigRequest({er_1.cell_id: {"disabled": False}})+ )+ assert k.graph.cells[er_1.cell_id].disabled_transitively+ assert k.graph.cells[er_2.cell_id].config.disabled++ # adding a new cell shouldn't toggle disabled states of either+ k.run([exec_req.get("c = 0")])+ assert k.graph.cells[er_1.cell_id].disabled_transitively+ assert k.graph.cells[er_2.cell_id].config.disabled++ # breaking the cycle should re-enable+ k.run([ExecutionRequest(er_1.cell_id, "a = 0")])+ assert not k.graph.cells[er_1.cell_id].disabled_transitively+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_1.cell_id].config.disabled+ assert k.graph.cells[er_2.cell_id].config.disabled+++def test_disable_cycle_incremental(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ k.run([er_1 := exec_req.get("a = b")])+ k.set_cell_config(SetCellConfigRequest({er_1.cell_id: {"disabled": True}}))+ assert k.graph.cells[er_1.cell_id].config.disabled++ k.run([er_2 := exec_req.get("b = a")])+ assert k.graph.cells[er_2.cell_id].disabled_transitively+++def test_enable_cycle_incremental(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ k.run(+ [+ (er_1 := exec_req.get("a = b")),+ (er_2 := exec_req.get("b = a")),+ ]+ )+ k.set_cell_config(SetCellConfigRequest({er_1.cell_id: {"disabled": True}}))+ assert k.graph.cells[er_1.cell_id].config.disabled+ assert k.graph.cells[er_2.cell_id].disabled_transitively++ k.set_cell_config(+ SetCellConfigRequest({er_1.cell_id: {"disabled": False}})+ )+ assert not k.graph.cells[er_1.cell_id].config.disabled+ assert k.graph.cells[er_2.cell_id].status == "idle"diff --git a/marimo/_server/api/__init__.py b/marimo/_server/api/__init__.pyindex 3bcbbc3e11..bc63b0b01a 100644--- a/marimo/_server/api/__init__.py+++ b/marimo/_server/api/__init__.py@@ -11,6 +11,7 @@ __all__ = ["SaveAppConfigurationHandler","SaveHandler","SaveUserConfigurationHandler",+ "SetCellConfigHandler","SetUIElementValueHandler",]@@ -27,4 +28,5 @@ from marimo._server.api.run import RunHandlerfrom marimo._server.api.save import SaveHandlerfrom marimo._server.api.save_app_config import SaveAppConfigurationHandlerfrom marimo._server.api.save_user_config import SaveUserConfigurationHandler+from marimo._server.api.set_cell_config import SetCellConfigHandlerfrom marimo._server.api.set_ui_element_value import SetUIElementValueHandlerdiff --git a/marimo/_server/api/save.py b/marimo/_server/api/save.pyindex 7a0fdb8730..aecab78fd1 100644--- a/marimo/_server/api/save.py+++ b/marimo/_server/api/save.py@@ -9,6 +9,7 @@ import tornado.webfrom marimo import _loggersfrom marimo._ast import codegen+from marimo._ast.cell import CellConfigfrom marimo._server import sessionsfrom marimo._server.api.model import parse_rawfrom marimo._server.api.status import HTTPStatus@@ -23,6 +24,8 @@ class Save:codes: List[str]# name of each cellnames: List[str]+ # config for each cell+ configs: List[CellConfig]# path to appfilename: str@@ -49,7 +52,7 @@ class SaveHandler(tornado.web.RequestHandler):else:# try to save the app under the name `filename`contents = codegen.generate_filecontents(- codes, names, config=mgr.app_config+ codes, names, cell_configs=args.configs, config=mgr.app_config)LOGGER.debug("Saving app to %s", filename)try:diff --git a/marimo/_server/api/save_app_config.py b/marimo/_server/api/save_app_config.pyindex ff351f223a..8435c26461 100644--- a/marimo/_server/api/save_app_config.py+++ b/marimo/_server/api/save_app_config.py@@ -36,10 +36,11 @@ class SaveAppConfigurationHandler(tornado.web.RequestHandler):if app is not None and mgr.filename is not None:codes = list(app._codes())names = list(app._names())+ configs = list(app._configs())# Try to save the app under the name `mgr.filename`contents = codegen.generate_filecontents(- codes, names, config=mgr.app_config+ codes, names, cell_configs=configs, config=mgr.app_config)try:with open(mgr.filename, "w", encoding="utf-8") as f:diff --git a/marimo/_server/api/set_cell_config.py b/marimo/_server/api/set_cell_config.pynew file mode 100644index 0000000000..2bb713e0e3--- /dev/null+++ b/marimo/_server/api/set_cell_config.py@@ -0,0 +1,24 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++from dataclasses import dataclass++import tornado.web++from marimo._ast.cell import CellId_t+from marimo._runtime import requests+from marimo._server import sessions+from marimo._server.api.model import parse_raw+++@dataclass+class SetCellConfig:+ # Map from Cell ID to (possibily partial) CellConfig+ configs: dict[CellId_t, dict[str, object]]+++class SetCellConfigHandler(tornado.web.RequestHandler):+ def post(self) -> None:+ session = sessions.require_session_from_header(self.request.headers)+ args = parse_raw(self.request.body, SetCellConfig)+ session.queue.put(requests.SetCellConfigRequest(args.configs))diff --git a/marimo/_server/server.py b/marimo/_server/server.pyindex b2650479bc..0639d17ac5 100644--- a/marimo/_server/server.py+++ b/marimo/_server/server.py@@ -196,6 +196,10 @@ async def start_server(r"/api/kernel/set_ui_element_value/",api.SetUIElementValueHandler,),+ (+ r"/api/kernel/set_cell_config/",+ api.SetCellConfigHandler,+ ),(r"/api/kernel/interrupt/",api.InterruptHandler,diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 0b3c5614c3..0fe9c8ad06 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -33,6 +33,7 @@ import tornado.websocketfrom marimo import _loggersfrom marimo._ast import codegenfrom marimo._ast.app import App, _AppConfig+from marimo._ast.cell import CellConfigfrom marimo._messaging.message_types import KernelReady, serializefrom marimo._output.formatters.formatters import register_formattersfrom marimo._runtime import requests, runtime@@ -84,28 +85,44 @@ class IOSocketHandler(tornado.websocket.WebSocketHandler):return asyncio.ensure_future(return_none())def write_kernel_ready(self) -> None:- """Communicates to the client that the kernel is ready."""+ """Communicates to the client that the kernel is ready.++ Sends cell code and other metadata to client.+ """mgr = get_manager()codes: tuple[str, ...]names: tuple[str, ...]+ configs: tuple[CellConfig, ...]app = mgr.load_app()if app is None:codes = ("",)names = ("__",)+ configs = (CellConfig(),)elif mgr.mode == SessionMode.EDIT:- codes = tuple(- cell_data.code for cell_data in app._cell_data.values()- )- names = tuple(- cell_data.name for cell_data in app._cell_data.values()+ codes, names, configs = tuple(+ zip(+ *tuple(+ (cell_data.code, cell_data.name, cell_data.config)+ for cell_data in app._cell_data.values()+ )+ ))else:- # Don't send code to frontend in run mode- codes = tuple("" for _ in app._cell_data)- names = tuple("" for _ in app._cell_data)+ codes, names, configs = tuple(+ zip(+ *tuple(+ # Don't send code to frontend in run mode+ ("", "", cell_data.config)+ for cell_data in app._cell_data.values()+ )+ )+ )+self.write_op(op=KernelReady.name,- data=serialize(KernelReady(codes=codes, names=names)),+ data=serialize(+ KernelReady(codes=codes, names=names, configs=configs)+ ),)def reconnect_session(self, session: "Session") -> None:diff --git a/marimo/_utils/deep_merge.py b/marimo/_utils/deep_merge.pynew file mode 100644index 0000000000..001934fff6--- /dev/null+++ b/marimo/_utils/deep_merge.py@@ -0,0 +1,33 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any+++def _merge_key(+ original: dict[Any, Any], update: dict[Any, Any], key: str+) -> Any:+ # Precondition: key is in at least one of original and update+ if key not in update:+ # keep keys in original if they aren't in the update+ return original[key]+ elif key not in original:+ # new keys in update get added to original+ return update[key]+ elif isinstance(original[key], dict) and isinstance(update[key], dict):+ # both dicts, so recurse+ return deep_merge(original[key], update[key])+ else:+ # key is present in both original and update, but values are not+ # both dicts; just take the update value.+ return update[key]+++def deep_merge(+ original: dict[Any, Any], update: dict[Any, Any]+) -> dict[Any, Any]:+ """Deep merge of two dicts."""+ return {+ key: _merge_key(original, update, key)+ for key in set(original.keys()).union(set(update.keys()))+ }