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
Refactor `CellArray`/`Cell` to use atom-based state management (#5897)
Trevor Manz863fec4ecf38
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex a98385b064..132a6ace10 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -33,6 +33,7 @@ import type { LanguageAdapterType } from "@/core/codemirror/language/types";import { canCollapseOutline } from "@/core/dom/outline";import { isErrorMime } from "@/core/mime";import type { AppMode } from "@/core/mode";+import { connectionAtom } from "@/core/network/connection";import { sendStdin } from "@/core/network/requests";import type { CellConfig, RuntimeState } from "@/core/network/types";import { useResizeObserver } from "@/hooks/useResizeObserver";@@ -42,16 +43,18 @@ import {type CellActions,createUntouchedCellAtom,SETUP_CELL_ID,+ useCellActions,+ useCellData,+ useCellHandle,+ useCellRuntime,} from "../../core/cells/cells";import type { CellId } from "../../core/cells/ids";-import type { CellData, CellRuntimeState } from "../../core/cells/types";import { isUninstantiated } from "../../core/cells/utils";import type { UserConfig } from "../../core/config/config-schema";import {isAppConnected,isAppInteractionDisabled,} from "../../core/websocket/connection-utils";-import type { WebSocketState } from "../../core/websocket/types";import { useCellRenderCount } from "../../hooks/useCellRenderCount";import type { Theme } from "../../theme/useTheme";import { derefNotNull } from "../../utils/dereference";@@ -70,6 +73,7 @@ import { CollapsedCellBanner, CollapseToggle } from "./cell/collapse";import { DeleteButton } from "./cell/DeleteButton";import { PendingDeleteConfirmation } from "./cell/PendingDeleteConfirmation";import { RunButton } from "./cell/RunButton";+import { useDeleteCellCallback } from "./cell/useDeleteCell";import { useRunCell } from "./cell/useRunCells";import { HideCodeButton } from "./code/readonly-python-code";import { cellDomProps } from "./common";@@ -230,33 +234,11 @@ export interface CellHandle {editorViewOrNull: EditorView | null;}-export interface CellProps- extends Pick<- CellRuntimeState,- | "consoleOutputs"- | "status"- | "outline"- | "output"- | "errored"- | "interrupted"- | "stopped"- | "staleInputs"- | "runStartTimestamp"- | "lastRunStartTimestamp"- | "serialization"- | "runElapsedTimeMs"- | "debuggerActive"- >,- Pick<- CellData,- "id" | "code" | "edited" | "config" | "name" | "serializedEditorState"- > {- actions: CellComponentActions;- deleteCell: CellActions["deleteCell"];+export interface CellProps {+ cellId: CellId;theme: Theme;showPlaceholder: boolean;mode: AppMode;- connectionState: WebSocketState;/*** False only when there is only one cell in the notebook.*/@@ -276,24 +258,14 @@ export interface CellPropscollapseCount: number;}-const CellComponent = (- props: CellProps,- ref: React.ForwardedRef<CellHandle>,-) => {- const {- status,- output,- runStartTimestamp,- interrupted,- staleInputs,- edited,- id,- mode,- } = props;+const CellComponent = (props: CellProps) => {+ const { cellId, mode } = props;+ const ref = useCellHandle(cellId);useCellRenderCount().countRender();- Logger.debug("Rendering Cell", id);+ Logger.debug("Rendering Cell", cellId);+const editorView = useRef<EditorView | null>(null);// An imperative interface to the code editor@@ -310,22 +282,15 @@ const CellComponent = ([editorView],);- const outputStale = outputIsStale(- { status, output, runStartTimestamp, interrupted, staleInputs },- edited,- );-- const loading = outputIsLoading(status);-- if (id === SETUP_CELL_ID) {+ if (cellId === SETUP_CELL_ID) {return (<SetupCellComponent{...props}+ cellId={cellId}editorView={editorView}setEditorView={(ev) => {editorView.current = ev;}}- outputStale={outputStale}/>);}@@ -335,55 +300,38 @@ const CellComponent = (<ScopeProvider atoms={[temporarilyShownCodeAtom]}><EditableCellComponent{...props}+ cellId={cellId}editorView={editorView}setEditorView={(ev) => {editorView.current = ev;}}- outputStale={outputStale}/></ScopeProvider>);}- return (- <ReadonlyCellComponent- {...props}- outputStale={outputStale}- outputLoading={loading}- />- );+ return <ReadonlyCellComponent cellId={cellId} />;};const ReadonlyCellComponent = forwardRef(- (- props: Pick<- CellProps,- "id" | "output" | "interrupted" | "errored" | "stopped" | "name"- > & {- outputStale: boolean;- outputLoading: boolean;- },- ref: React.ForwardedRef<HTMLDivElement>,- ) => {- const {- id: cellId,- output,- interrupted,- errored,- stopped,- name,- outputStale,- outputLoading,- } = props;+ (props: { cellId: CellId }, ref: React.ForwardedRef<HTMLDivElement>) => {+ const { cellId } = props;+ const cellData = useCellData(cellId);+ const cellRuntime = useCellRuntime(cellId);const className = clsx("marimo-cell", "hover-actions-parent z-10", {published: true,});- const outputIsError = isErrorMime(output?.mimetype);+ const outputIsError = isErrorMime(cellRuntime.output?.mimetype);// Hide the output if it's an error or stopped.- const hidden = errored || interrupted || stopped || outputIsError;+ const hidden =+ cellRuntime.errored ||+ cellRuntime.interrupted ||+ cellRuntime.stopped ||+ outputIsError;+if (hidden) {return null;}@@ -393,16 +341,16 @@ const ReadonlyCellComponent = forwardRef(tabIndex={-1}ref={ref}className={className}- {...cellDomProps(cellId, name)}+ {...cellDomProps(cellId, cellData.name)}><OutputAreaallowExpand={false}forceExpand={true}- output={output}className="output-area"cellId={cellId}- stale={outputStale}- loading={outputLoading}+ output={cellRuntime.output}+ stale={outputIsStale(cellRuntime, cellData.edited)}+ loading={outputIsLoading(cellRuntime.status)}/></div>);@@ -413,71 +361,59 @@ ReadonlyCellComponent.displayName = "ReadonlyCellComponent";const EditableCellComponent = ({theme,showPlaceholder,- id: cellId,- code,- output,- consoleOutputs,- status,- runStartTimestamp,- lastRunStartTimestamp,- runElapsedTimeMs,- edited,- interrupted,- errored,- stopped,- staleInputs,- serializedEditorState,- serialization,- debuggerActive,- connectionState,+ cellId,canDelete,- actions,- deleteCell,userConfig,- outline,isCollapsed,collapseCount,- config: cellConfig,canMoveX,- name,editorView,setEditorView,- outputStale,}: CellProps & {editorView: React.RefObject<EditorView | null>;setEditorView: (view: EditorView) => void;- outputStale: boolean;}) => {const cellRef = useRef<HTMLDivElement>(null);+ const cellData = useCellData(cellId);+ const cellRuntime = useCellRuntime(cellId);const cellActionDropdownRef = useRef<CellActionsDropdownHandle>(null);// DOM node where the editorView will be mountedconst editorViewParentRef = useRef<HTMLDivElement>(null);const cellContainerRef = useRef<HTMLDivElement>(null);+ const actions = useCellActions();+ const connection = useAtomValue(connectionAtom);const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);+ const deleteCell = useDeleteCellCallback();const runCell = useRunCell(cellId);const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();const disabledOrAncestorDisabled =- cellConfig.disabled || status === "disabled-transitively";+ cellData.config.disabled || cellRuntime.status === "disabled-transitively";const uninstantiated = isUninstantiated({- executionTime: runElapsedTimeMs,- status,- errored,- interrupted,- stopped,+ executionTime: cellRuntime.runElapsedTimeMs ?? cellData.lastExecutionTime,+ status: cellRuntime.status,+ errored: cellRuntime.errored,+ interrupted: cellRuntime.interrupted,+ stopped: cellRuntime.stopped,});const needsRun =- edited || interrupted || (staleInputs && !disabledOrAncestorDisabled);- const loading = outputIsLoading(status);+ cellData.edited ||+ cellRuntime.interrupted ||+ (cellRuntime.staleInputs && !disabledOrAncestorDisabled);++ const loading = outputIsLoading(cellRuntime.status);// console output is cleared immediately on run, so check for queued instead// of loading to determine stalenessconst consoleOutputStale =- (status === "queued" || edited || staleInputs) && !interrupted;+ (cellRuntime.status === "queued" ||+ cellData.edited ||+ cellRuntime.staleInputs) &&+ !cellRuntime.interrupted;// Callback to get the editor view.const getEditorView = useCallback(() => editorView.current, [editorView]);@@ -496,7 +432,7 @@ const EditableCellComponent = ({showHiddenCodeIfMarkdown,} = useCellHiddenLogic({cellId,- cellConfig,+ cellConfig: cellData.config,languageAdapter,editorView,editorViewParentRef,@@ -508,9 +444,9 @@ const EditableCellComponent = ({editorView,cellActionDropdownRef,});- const canCollapse = canCollapseOutline(outline);- const hasOutput = !isOutputEmpty(output);- const hasConsoleOutput = consoleOutputs.length > 0;+ const canCollapse = canCollapseOutline(cellRuntime.outline);+ const hasOutput = !isOutputEmpty(cellRuntime.output);+ const hasConsoleOutput = cellRuntime.consoleOutputs.length > 0;const cellOutput = userConfig.display.cell_output;const hasOutputAbove = hasOutput && cellOutput === "above";@@ -567,11 +503,11 @@ const EditableCellComponent = ({allowExpand={true}// Force expand when markdown is hiddenforceExpand={isMarkdownCodeHidden}- output={output}className="output-area"cellId={cellId}- stale={outputStale}- loading={loading}+ output={cellRuntime.output}+ stale={outputIsStale(cellRuntime, cellData.edited)}+ loading={outputIsLoading(cellRuntime.status)}/>{isMarkdownCodeHidden &&hasOutputAbove &&@@ -582,10 +518,10 @@ const EditableCellComponent = ({const className = clsx("marimo-cell", "hover-actions-parent z-10", {interactive: true,"needs-run": needsRun,- "has-error": errored,- stopped: stopped,- disabled: cellConfig.disabled,- stale: status === "disabled-transitively",+ "has-error": cellRuntime.errored,+ stopped: cellRuntime.stopped,+ disabled: cellData.config.disabled,+ stale: cellRuntime.status === "disabled-transitively",borderless:isMarkdownCodeHidden && hasOutput && !navigationProps["data-selected"],});@@ -598,34 +534,24 @@ const EditableCellComponent = ({// to get the tooltip to show next to the cursor ...// https://github.com/radix-ui/primitives/discussions/1090const renderCellTitle = () => {- if (cellConfig.disabled) {+ if (cellData.config.disabled) {return "This cell is disabled";}- if (status === "disabled-transitively") {+ if (cellRuntime.status === "disabled-transitively") {return "This cell has a disabled ancestor";}return undefined;};- const isToplevel = !!(- serialization && serialization.toLowerCase() === "valid"- );+ const isToplevel = cellRuntime.serialization?.toLowerCase() === "valid";return (<TooltipProvider>- <CellActionsContextMenu- cellId={cellId}- config={cellConfig}- status={status}- getEditorView={getEditorView}- hasOutput={hasOutput}- hasConsoleOutput={hasConsoleOutput}- name={name}- >+ <CellActionsContextMenu cellId={cellId} getEditorView={getEditorView}><SortableCelltabIndex={-1}ref={cellRef}- data-status={status}+ data-status={cellRuntime.status}onBlur={closeCompletionHandler}onKeyDown={resumeCompletionHandler}cellId={cellId}@@ -641,22 +567,21 @@ const EditableCellComponent = ({"focus:ring-1 focus:ring-[var(--blue-7)] focus:ring-offset-0",)}ref={cellContainerRef}- {...cellDomProps(cellId, name)}+ {...cellDomProps(cellId, cellData.name)}>{cellOutput === "above" && outputArea}<div className={cn("tray")} data-hidden={isMarkdownCodeHidden}><div className="absolute right-2 -top-4 z-10"><CellToolbar- edited={edited}- connectionState={connectionState}- status={status}- cellConfig={cellConfig}+ edited={cellData.edited}+ status={cellRuntime.status}+ cellConfig={cellData.config}needsRun={needsRun}hasOutput={hasOutput}hasConsoleOutput={hasConsoleOutput}cellActionDropdownRef={cellActionDropdownRef}cellId={cellId}- name={name}+ name={cellData.name}getEditorView={getEditorView}onRun={runCell}/>@@ -670,17 +595,16 @@ const EditableCellComponent = ({isCellButtonsInline &&"-left-[3.8rem]",)}- connectionState={connectionState}actions={actions}/><CellEditortheme={theme}showPlaceholder={showPlaceholder}id={cellId}- code={code}- config={cellConfig}- status={status}- serializedEditorState={serializedEditorState}+ code={cellData.code}+ config={cellData.config}+ status={cellRuntime.status}+ serializedEditorState={cellData.serializedEditorState}runCell={runCell}setEditorView={setEditorView}userConfig={userConfig}@@ -696,26 +620,26 @@ const EditableCellComponent = ({className={cn(isMarkdownCodeHidden && cellOutput === "below" && "top-14",)}- edited={edited}- status={status}+ edited={cellData.edited}+ status={cellRuntime.status}isCellStatusInline={isCellStatusInline}uninstantiated={uninstantiated}- disabled={cellConfig.disabled}- runElapsedTimeMs={runElapsedTimeMs}- runStartTimestamp={runStartTimestamp}- lastRunStartTimestamp={lastRunStartTimestamp}- staleInputs={staleInputs}- interrupted={interrupted}+ disabled={cellData.config.disabled}+ runElapsedTimeMs={cellRuntime.runElapsedTimeMs}+ runStartTimestamp={cellRuntime.runStartTimestamp}+ lastRunStartTimestamp={cellRuntime.lastRunStartTimestamp}+ staleInputs={cellRuntime.staleInputs}+ interrupted={cellRuntime.interrupted}/><div className="shoulder-bottom hover-action">{canDelete && isCellCodeShown && (<DeleteButton- connectionState={connectionState}- status={status}+ status={cellRuntime.status}+ connectionState={connection.state}onClick={() => {if (!loading &&- !isAppInteractionDisabled(connectionState)+ !isAppInteractionDisabled(connection.state)) {deleteCell({ cellId });}@@ -725,7 +649,7 @@ const EditableCellComponent = ({</div></div>{cellOutput === "below" && outputArea}- {serialization && (+ {cellRuntime.serialization && (<div className="py-1 px-2 flex items-center justify-end gap-2 last:rounded-b">{isToplevel && (<a@@ -747,7 +671,7 @@ const EditableCellComponent = ({modules:<br /><br />- <pre>{serialization}</pre>+ <pre>{cellRuntime.serialization}</pre><br />Click this icon to learn more.</>@@ -784,10 +708,10 @@ const EditableCellComponent = ({</div>)}<ConsoleOutput- consoleOutputs={consoleOutputs}+ consoleOutputs={cellRuntime.consoleOutputs}stale={consoleOutputStale}// Empty name if serialization triggered- cellName={serialization ? "_" : name}+ cellName={cellRuntime.serialization ? "_" : cellData.name}onRefactorWithAI={handleRefactorWithAI}onClear={() => {actions.clearCellConsoleOutput({ cellId });@@ -801,7 +725,7 @@ const EditableCellComponent = ({sendStdin({ text });}}cellId={cellId}- debuggerActive={debuggerActive}+ debuggerActive={cellRuntime.debuggerActive}/><PendingDeleteConfirmation cellId={cellId} /></div>@@ -818,103 +742,110 @@ const EditableCellComponent = ({);};-const CellRightSideActions = (props: {- className?: string;- disabled: boolean | undefined;- edited: boolean;- interrupted: boolean;- isCellStatusInline: boolean;- lastRunStartTimestamp: Seconds | null;- runElapsedTimeMs: Milliseconds | null;- runStartTimestamp: Seconds | null;- staleInputs: boolean;- status: RuntimeState;- uninstantiated: boolean;-}) => {- const {- className,- disabled = false,- edited,- interrupted,- isCellStatusInline,- lastRunStartTimestamp,- runElapsedTimeMs,- runStartTimestamp,- staleInputs,- status,- uninstantiated,- } = props;-- const cellStatusComponent = (- <CellStatusComponent- status={status}- staleInputs={staleInputs}- interrupted={interrupted}- editing={true}- edited={edited}- disabled={disabled}- elapsedTime={runElapsedTimeMs}- runStartTimestamp={runStartTimestamp}- uninstantiated={uninstantiated}- lastRunStartTimestamp={lastRunStartTimestamp}- />- );+const CellRightSideActions = memo(+ (props: {+ className?: string;+ disabled: boolean | undefined;+ edited: boolean;+ interrupted: boolean;+ isCellStatusInline: boolean;+ lastRunStartTimestamp: Seconds | null;+ runElapsedTimeMs: Milliseconds | null;+ runStartTimestamp: Seconds | null;+ staleInputs: boolean;+ status: RuntimeState;+ uninstantiated: boolean;+ }) => {+ const {+ className,+ disabled = false,+ edited,+ interrupted,+ isCellStatusInline,+ lastRunStartTimestamp,+ runElapsedTimeMs,+ runStartTimestamp,+ staleInputs,+ status,+ uninstantiated,+ } = props;- return (- <div className={cn("shoulder-right z-20", className)}>- {!isCellStatusInline && cellStatusComponent}- <div className="flex gap-2 items-end">- <CellDragHandle />- {isCellStatusInline && cellStatusComponent}+ const cellStatusComponent = (+ <CellStatusComponent+ status={status}+ staleInputs={staleInputs}+ interrupted={interrupted}+ editing={true}+ edited={edited}+ disabled={disabled}+ elapsedTime={runElapsedTimeMs}+ runStartTimestamp={runStartTimestamp}+ uninstantiated={uninstantiated}+ lastRunStartTimestamp={lastRunStartTimestamp}+ />+ );++ return (+ <div className={cn("shoulder-right z-20", className)}>+ {!isCellStatusInline && cellStatusComponent}+ <div className="flex gap-2 items-end">+ <CellDragHandle />+ {isCellStatusInline && cellStatusComponent}+ </div></div>- </div>- );-};+ );+ },+);-const CellLeftSideActions = (props: {- className?: string;- cellId: CellId;- connectionState: WebSocketState;- actions: CellComponentActions;-}) => {- const { className, connectionState, actions, cellId } = props;+CellRightSideActions.displayName = "CellRightSideActions";- const createBelow = useEvent(- (opts: { code?: string; hideCode?: boolean } = {}) =>- actions.createNewCell({ cellId, before: false, ...opts }),- );- const createAbove = useEvent(- (opts: { code?: string; hideCode?: boolean } = {}) =>- actions.createNewCell({ cellId, before: true, ...opts }),- );+const CellLeftSideActions = memo(+ (props: {+ className?: string;+ cellId: CellId;+ actions: CellComponentActions;+ }) => {+ const connection = useAtomValue(connectionAtom);+ const { className, actions, cellId } = props;- const isConnected = isAppConnected(connectionState);+ const createBelow = useEvent(+ (opts: { code?: string; hideCode?: boolean } = {}) =>+ actions.createNewCell({ cellId, before: false, ...opts }),+ );+ const createAbove = useEvent(+ (opts: { code?: string; hideCode?: boolean } = {}) =>+ actions.createNewCell({ cellId, before: true, ...opts }),+ );- return (- <div- className={cn(- "absolute flex flex-col gap-[2px] justify-center h-full left-[-34px] z-20",- className,- )}- >- <CreateCellButton- tooltipContent={renderShortcut("cell.createAbove")}- connectionState={connectionState}- onClick={isConnected ? createAbove : undefined}- />- <div className="flex-1" />- <CreateCellButton- tooltipContent={renderShortcut("cell.createBelow")}- connectionState={connectionState}- onClick={isConnected ? createBelow : undefined}- />- </div>- );-};+ const isConnected = isAppConnected(connection.state);++ return (+ <div+ className={cn(+ "absolute flex flex-col gap-[2px] justify-center h-full left-[-34px] z-20",+ className,+ )}+ >+ <CreateCellButton+ tooltipContent={renderShortcut("cell.createAbove")}+ connectionState={connection.state}+ onClick={isConnected ? createAbove : undefined}+ />+ <div className="flex-1" />+ <CreateCellButton+ tooltipContent={renderShortcut("cell.createBelow")}+ connectionState={connection.state}+ onClick={isConnected ? createBelow : undefined}+ />+ </div>+ );+ },+);++CellLeftSideActions.displayName = "CellLeftSideActions";interface CellToolbarProps {edited: boolean;- connectionState: WebSocketState;status: RuntimeState;cellConfig: CellConfig;needsRun: boolean;@@ -928,62 +859,66 @@ interface CellToolbarProps {onRun: () => void;}-const CellToolbar = ({- edited,- connectionState,- status,- cellConfig,- needsRun,- hasOutput,- hasConsoleOutput,- onRun,- cellActionDropdownRef,- cellId,- getEditorView,- name,- includeCellActions = true,-}: CellToolbarProps) => {- const isConnected = isAppConnected(connectionState);+const CellToolbar = memo(+ ({+ edited,+ status,+ cellConfig,+ needsRun,+ hasOutput,+ hasConsoleOutput,+ onRun,+ cellActionDropdownRef,+ cellId,+ getEditorView,+ name,+ includeCellActions = true,+ }: CellToolbarProps) => {+ const connection = useAtomValue(connectionAtom);+ const isConnected = isAppConnected(connection.state);- return (- <Toolbar- className={cn(- // Show the toolbar on hover, or when the cell needs to be run- !needsRun && "hover-action",- )}- >- <RunButton- edited={edited}- onClick={isConnected ? onRun : Functions.NOOP}- connectionState={connectionState}- status={status}- config={cellConfig}- needsRun={needsRun}- />- <StopButton status={status} connectionState={connectionState} />- {includeCellActions && (- <CellActionsDropdown- ref={cellActionDropdownRef}- cellId={cellId}+ return (+ <Toolbar+ className={cn(+ // Show the toolbar on hover, or when the cell needs to be run+ !needsRun && "hover-action",+ )}+ >+ <RunButton+ edited={edited}+ onClick={isConnected ? onRun : Functions.NOOP}+ connectionState={connection.state}status={status}- getEditorView={getEditorView}- name={name}config={cellConfig}- hasOutput={hasOutput}- hasConsoleOutput={hasConsoleOutput}- >- <ToolbarItem- variant={"green"}- tooltip={null}- data-testid="cell-actions-button"+ needsRun={needsRun}+ />+ <StopButton status={status} connectionState={connection.state} />+ {includeCellActions && (+ <CellActionsDropdown+ ref={cellActionDropdownRef}+ cellId={cellId}+ status={status}+ getEditorView={getEditorView}+ name={name}+ config={cellConfig}+ hasOutput={hasOutput}+ hasConsoleOutput={hasConsoleOutput}>- <MoreHorizontalIcon strokeWidth={1.5} />- </ToolbarItem>- </CellActionsDropdown>- )}- </Toolbar>- );-};+ <ToolbarItem+ variant={"green"}+ tooltip={null}+ data-testid="cell-actions-button"+ >+ <MoreHorizontalIcon strokeWidth={1.5} />+ </ToolbarItem>+ </CellActionsDropdown>+ )}+ </Toolbar>+ );+ },+);++CellToolbar.displayName = "CellToolbar";/*** A cell that is not allowed to be deleted or moved.@@ -992,70 +927,61 @@ const CellToolbar = ({const SetupCellComponent = ({theme,showPlaceholder,- id: cellId,- code,- output,- consoleOutputs,- status,- runStartTimestamp,- lastRunStartTimestamp,- runElapsedTimeMs,- edited,- interrupted,- errored,- stopped,- staleInputs,- serializedEditorState,- debuggerActive,- connectionState,+ cellId,canDelete,- actions,- deleteCell,userConfig,- config: cellConfig,canMoveX,- name,editorView,setEditorView,}: CellProps & {editorView: React.RefObject<EditorView | null>;setEditorView: (view: EditorView) => void;- outputStale: boolean;}) => {const cellRef = useRef<HTMLDivElement>(null);+ const cellData = useCellData(cellId);+ const cellRuntime = useCellRuntime(cellId);const cellActionDropdownRef = useRef<CellActionsDropdownHandle>(null);// DOM node where the editorView will be mountedconst editorViewParentRef = useRef<HTMLDivElement>(null);+ const connection = useAtomValue(connectionAtom);+ const actions = useCellActions();+ const deleteCell = useDeleteCellCallback();const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);const runCell = useRunCell(cellId);const disabledOrAncestorDisabled =- cellConfig.disabled || status === "disabled-transitively";+ cellData.config.disabled || cellRuntime.status === "disabled-transitively";const uninstantiated = isUninstantiated({- executionTime: runElapsedTimeMs,- status,- errored,- interrupted,- stopped,+ executionTime: cellRuntime.runElapsedTimeMs ?? cellData.lastExecutionTime,+ status: cellRuntime.status,+ errored: cellRuntime.errored,+ interrupted: cellRuntime.interrupted,+ stopped: cellRuntime.stopped,});const needsRun =- edited || interrupted || (staleInputs && !disabledOrAncestorDisabled);- const loading = status === "running" || status === "queued";+ cellData.edited ||+ cellRuntime.interrupted ||+ (cellRuntime.staleInputs && !disabledOrAncestorDisabled);+ const loading =+ cellRuntime.status === "running" || cellRuntime.status === "queued";// console output is cleared immediately on run, so check for queued instead// of loading to determine stalenessconst consoleOutputStale =- (status === "queued" || edited || staleInputs) && !interrupted;+ (cellRuntime.status === "queued" ||+ cellData.edited ||+ cellRuntime.staleInputs) &&+ !cellRuntime.interrupted;// Callback to get the editor view.const getEditorView = useCallback(() => editorView.current, [editorView]);const { isCellCodeShown, showHiddenCode } = useCellHiddenLogic({cellId,- cellConfig,+ cellConfig: cellData.config,languageAdapter: "python",editorView,editorViewParentRef,@@ -1073,9 +999,9 @@ const SetupCellComponent = ({editorView,cellActionDropdownRef,});- const hasOutput = !isOutputEmpty(output);- const hasConsoleOutput = consoleOutputs.length > 0;- const isErrorOutput = isErrorMime(output?.mimetype);+ const hasOutput = !isOutputEmpty(cellRuntime.output);+ const hasConsoleOutput = cellRuntime.consoleOutputs.length > 0;+ const isErrorOutput = isErrorMime(cellRuntime.output?.mimetype);const className = clsx("marimo-cell",@@ -1083,8 +1009,8 @@ const SetupCellComponent = ({"!border-[var(--blue-5)] !rounded-sm",{"needs-run": needsRun,- "has-error": errored,- stopped: stopped,+ "has-error": cellRuntime.errored,+ stopped: cellRuntime.stopped,},);@@ -1096,10 +1022,10 @@ const SetupCellComponent = ({// to get the tooltip to show next to the cursor ...// https://github.com/radix-ui/primitives/discussions/1090const renderCellTitle = () => {- if (cellConfig.disabled) {+ if (cellData.config.disabled) {return "This cell is disabled";}- if (status === "disabled-transitively") {+ if (cellRuntime.status === "disabled-transitively") {return "This cell has a disabled ancestor";}return undefined;@@ -1107,40 +1033,31 @@ const SetupCellComponent = ({return (<TooltipProvider>- <CellActionsContextMenu- cellId={cellId}- config={cellConfig}- status={status}- getEditorView={getEditorView}- hasOutput={hasOutput}- hasConsoleOutput={hasConsoleOutput}- name={name}- >+ <CellActionsContextMenu cellId={cellId} getEditorView={getEditorView}><div- data-status={status}+ data-status={cellRuntime.status}ref={cellRef}{...mergeProps(navigationProps, {className,onBlur: closeCompletionHandler,onKeyDown: resumeCompletionHandler,})}- {...cellDomProps(cellId, name)}+ {...cellDomProps(cellId, cellData.name)}title={renderCellTitle()}data-setup-cell={true}><div className={cn("tray")} data-hidden={!isCellCodeShown}><div className="absolute right-2 -top-4 z-10"><CellToolbar- edited={edited}- connectionState={connectionState}- status={status}- cellConfig={cellConfig}+ edited={cellData.edited}+ status={cellRuntime.status}+ cellConfig={cellData.config}needsRun={needsRun}hasOutput={hasOutput}hasConsoleOutput={hasConsoleOutput}cellActionDropdownRef={cellActionDropdownRef}cellId={cellId}- name={name}+ name={cellData.name}getEditorView={getEditorView}onRun={runCell}includeCellActions={true}@@ -1150,10 +1067,10 @@ const SetupCellComponent = ({theme={theme}showPlaceholder={showPlaceholder}id={cellId}- code={code}- config={cellConfig}- status={status}- serializedEditorState={serializedEditorState}+ code={cellData.code}+ config={cellData.config}+ status={cellRuntime.status}+ serializedEditorState={cellData.serializedEditorState}runCell={runCell}setEditorView={setEditorView}userConfig={userConfig}@@ -1167,26 +1084,26 @@ const SetupCellComponent = ({showLanguageToggles={false}/><CellRightSideActions- edited={edited}- status={status}+ edited={cellData.edited}+ status={cellRuntime.status}isCellStatusInline={false}uninstantiated={uninstantiated}- disabled={cellConfig.disabled}- runElapsedTimeMs={runElapsedTimeMs}- runStartTimestamp={runStartTimestamp}- lastRunStartTimestamp={lastRunStartTimestamp}- staleInputs={staleInputs}- interrupted={interrupted}+ disabled={cellData.config.disabled}+ runElapsedTimeMs={cellRuntime.runElapsedTimeMs}+ runStartTimestamp={cellRuntime.runStartTimestamp}+ lastRunStartTimestamp={cellRuntime.lastRunStartTimestamp}+ staleInputs={cellRuntime.staleInputs}+ interrupted={cellRuntime.interrupted}/><div className="shoulder-bottom hover-action">{canDelete && (<DeleteButton- connectionState={connectionState}- status={status}+ connectionState={connection.state}+ status={cellRuntime.status}onClick={() => {if (!loading &&- !isAppInteractionDisabled(connectionState)+ !isAppInteractionDisabled(connection.state)) {deleteCell({ cellId });}@@ -1220,15 +1137,15 @@ const SetupCellComponent = ({<OutputAreaallowExpand={true}forceExpand={true}- output={output}className="output-area"cellId={cellId}+ output={cellRuntime.output}stale={false}loading={loading}/>)}<ConsoleOutput- consoleOutputs={consoleOutputs}+ consoleOutputs={cellRuntime.consoleOutputs}stale={consoleOutputStale}// Don't show namecellName={"_"}@@ -1245,7 +1162,7 @@ const SetupCellComponent = ({sendStdin({ text });}}cellId={cellId}- debuggerActive={debuggerActive}+ debuggerActive={cellRuntime.debuggerActive}/></div></CellActionsContextMenu>@@ -1253,4 +1170,4 @@ const SetupCellComponent = ({);};-export const Cell = memo(forwardRef<CellHandle, CellProps>(CellComponent));+export const Cell = memo(CellComponent);diff --git a/frontend/src/components/editor/__tests__/data-attributes.test.tsx b/frontend/src/components/editor/__tests__/data-attributes.test.tsxindex 94fe1e73e9..a627bfe019 100644--- a/frontend/src/components/editor/__tests__/data-attributes.test.tsx+++ b/frontend/src/components/editor/__tests__/data-attributes.test.tsx@@ -1,16 +1,26 @@/* Copyright 2024 Marimo. All rights reserved. */import { render } from "@testing-library/react";+import { createStore, Provider } from "jotai";import { beforeAll, describe, expect, it } from "vitest";+import { MockNotebook } from "@/__mocks__/notebook";import { TooltipProvider } from "@/components/ui/tooltip";+import { notebookAtom } from "@/core/cells/cells";import type { CellId } from "@/core/cells/ids";+import { createCellRuntimeState } from "@/core/cells/types";import type { UserConfig } from "@/core/config/config-schema";import type { OutputMessage } from "@/core/kernel/messages";import type { AppMode } from "@/core/mode";-import { WebSocketState } from "@/core/websocket/types";-import { Functions } from "@/utils/functions";-import { Cell, type CellComponentActions } from "../Cell";+import { Cell } from "../Cell";import { OutputArea } from "../Output";+function createTestWrapper() {+ const store = createStore();+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <Provider store={store}>{children}</Provider>+ );+ return { wrapper, store };+}+beforeAll(() => {global.ResizeObserver = class ResizeObserver {observe() {@@ -32,6 +42,7 @@ describe("Cell data attributes", () => {it.each(["edit", "read", "present"])("should render cell with data-cell-id and data-cell-name in %s mode",(mode) => {+ const { store, wrapper } = createTestWrapper();const cellId = "test" as CellId;const cellName = "test_cell";@@ -73,44 +84,54 @@ describe("Cell data attributes", () => {ai: {},} as UserConfig;+ const notebook = MockNotebook.notebookState({+ cellData: {+ [cellId]: {+ code: "",+ name: cellName,+ edited: false,+ serializedEditorState: null,+ config: {+ disabled: false,+ hide_code: false,+ column: null,+ },+ },+ },+ });++ notebook.cellRuntime[cellId] = createCellRuntimeState({+ status: "idle",+ output: null,+ consoleOutputs: [],+ interrupted: false,+ errored: false,+ stopped: false,+ staleInputs: false,+ runStartTimestamp: null,+ lastRunStartTimestamp: null,+ runElapsedTimeMs: null,+ debuggerActive: false,+ outline: null,+ });++ store.set(notebookAtom, notebook);+const { container } = render(<TooltipProvider><Cell- id={cellId}- name={cellName}- code=""- output={null}- consoleOutputs={[]}- status="idle"- edited={false}- interrupted={false}- errored={false}- stopped={false}- staleInputs={false}- runStartTimestamp={null}- lastRunStartTimestamp={null}- runElapsedTimeMs={null}- serializedEditorState={null}+ cellId={cellId}mode={mode as AppMode}- debuggerActive={false}- connectionState={WebSocketState.OPEN}canDelete={true}- actions={{} as CellComponentActions}userConfig={userConfig}- outline={null}isCollapsed={false}collapseCount={0}- deleteCell={Functions.NOOP}- config={{- disabled: false,- hide_code: false,- column: null,- }}canMoveX={false}theme="light"showPlaceholder={false}/></TooltipProvider>,+ { wrapper },);const cellElement = container.querySelector(`[data-cell-id="${cellId}"]`);diff --git a/frontend/src/components/editor/cell/cell-context-menu.tsx b/frontend/src/components/editor/cell/cell-context-menu.tsxindex df30b18ab1..0eeae2529f 100644--- a/frontend/src/components/editor/cell/cell-context-menu.tsx+++ b/frontend/src/components/editor/cell/cell-context-menu.tsx@@ -19,7 +19,9 @@ import {} from "@/components/ui/context-menu";import { Tooltip } from "@/components/ui/tooltip";import { toast } from "@/components/ui/use-toast";+import { useCellData, useCellRuntime } from "@/core/cells/cells";import { CellOutputId } from "@/core/cells/ids";+import { isOutputEmpty } from "@/core/cells/outputs";import { goToDefinitionAtCursorPosition } from "@/core/codemirror/go-to-definition/utils";import { sendToPanelManager } from "@/core/vscode/vscode-bindings";import { copyToClipboard } from "@/utils/copy";@@ -30,12 +32,29 @@ import {useCellActionButtons,} from "../actions/useCellActionButton";-interface Props extends CellActionButtonProps {+interface Props+ extends Pick<CellActionButtonProps, "cellId" | "getEditorView"> {children: React.ReactNode;}-export const CellActionsContextMenu = ({ children, ...props }: Props) => {- const actions = useCellActionButtons({ cell: props });+export const CellActionsContextMenu = ({+ children,+ cellId,+ getEditorView,+}: Props) => {+ const cellData = useCellData(cellId);+ const cellRuntime = useCellRuntime(cellId);+ const actions = useCellActionButtons({+ cell: {+ cellId: cellId,+ name: cellData.name,+ config: cellData.config,+ status: cellRuntime.status,+ hasOutput: !isOutputEmpty(cellRuntime.output),+ hasConsoleOutput: cellRuntime.consoleOutputs.length > 0,+ getEditorView,+ },+ });const [imageRightClicked, setImageRightClicked] =React.useState<HTMLImageElement>();@@ -53,9 +72,7 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {}// No selection, copy the full cell output- const output = document.getElementById(- CellOutputId.create(props.cellId),- );+ const output = document.getElementById(CellOutputId.create(cellId));if (!output) {Logger.warn("cell-context-menu: output not found");return;@@ -77,7 +94,6 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {hidden: Boolean(imageRightClicked),icon: <ClipboardPasteIcon size={13} strokeWidth={1.5} />,handle: async () => {- const { getEditorView } = props;const editorView = getEditorView();if (!editorView) {return;@@ -147,7 +163,6 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {label: "Go to Definition",icon: <SearchIcon size={13} strokeWidth={1.5} />,handle: () => {- const { getEditorView } = props;const editorView = getEditorView();if (editorView) {goToDefinitionAtCursorPosition(editorView);diff --git a/frontend/src/components/editor/chrome/wrapper/minimap-state.ts b/frontend/src/components/editor/chrome/wrapper/minimap-state.tsindex 3c9abc5601..95de87f2ac 100644--- a/frontend/src/components/editor/chrome/wrapper/minimap-state.ts+++ b/frontend/src/components/editor/chrome/wrapper/minimap-state.ts@@ -1,7 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { atom } from "jotai";-import { notebookAtom } from "@/core/cells/cells";+import { cellIdsAtom } from "@/core/cells/cells";import type { CellId } from "@/core/cells/ids";import { variablesAtom } from "@/core/variables/state";import type { Variable, VariableName, Variables } from "@/core/variables/types";@@ -104,9 +104,9 @@ export function buildCellGraph(}export const cellGraphsAtom = atom((get) => {- const notebook = get(notebookAtom);+ const cellIds = get(cellIdsAtom);const variables = get(variablesAtom);- return buildCellGraph(notebook.cellIds.inOrderIds, variables);+ return buildCellGraph(cellIds.inOrderIds, variables);});/**diff --git a/frontend/src/components/editor/chrome/wrapper/minimap.tsx b/frontend/src/components/editor/chrome/wrapper/minimap.tsxindex ab22992589..7c28f428c0 100644--- a/frontend/src/components/editor/chrome/wrapper/minimap.tsx+++ b/frontend/src/components/editor/chrome/wrapper/minimap.tsx@@ -4,7 +4,12 @@ import { useAtom, useAtomValue } from "jotai";import { XIcon } from "lucide-react";import * as React from "react";import { Button } from "@/components/ui/button";-import { useCellActions, useNotebook } from "@/core/cells/cells";+import {+ useCellActions,+ useCellData,+ useCellIds,+ useCellRuntime,+} from "@/core/cells/cells";import { cellFocusAtom, useCellFocusActions } from "@/core/cells/focus";import type { CellId } from "@/core/cells/ids";import { useVariables } from "@/core/variables/state";@@ -23,7 +28,6 @@ interface MinimapCellProps {}const MinimapCell: React.FC<MinimapCellProps> = (props) => {- const notebook = useNotebook();const focusState = useAtomValue(cellFocusAtom);const graphs = useAtomValue(cellGraphsAtom);const actions = useCellActions();@@ -32,8 +36,8 @@ const MinimapCell: React.FC<MinimapCellProps> = (props) => {const cell = {id: props.cellId,graph: graphs[props.cellId],- code: notebook.cellData[props.cellId].code,- hasError: notebook.cellRuntime[props.cellId].errored,+ code: useCellData(props.cellId).code,+ hasError: useCellRuntime(props.cellId).errored,};let selectedCell: undefined | { id: CellId; graph: CellGraph };@@ -125,13 +129,13 @@ const MinimapInternal: React.FC<{open: boolean;setOpen: (update: boolean) => void;}> = ({ open, setOpen }) => {- const notebook = useNotebook();+ const cellIds = useCellIds();const cellPositions: Record<CellId, number> = Object.fromEntries(- notebook.cellIds.inOrderIds.map((id, idx) => [id, idx]),+ cellIds.inOrderIds.map((id, idx) => [id, idx]),);const columnBoundaries: number[] = [];let cellCount = 0;- for (const [idx, column] of notebook.cellIds.getColumns().entries()) {+ for (const [idx, column] of cellIds.getColumns().entries()) {if (idx > 0) {columnBoundaries.push(cellCount);}@@ -158,7 +162,7 @@ const MinimapInternal: React.FC<{</div><div className="overflow-y-auto overflow-x-hidden flex-1 scrollbar-none"><div className="py-3 pl-3 pr-4 relative min-h-full">- {notebook.cellIds.inOrderIds.map((cellId, idx) => {+ {cellIds.inOrderIds.map((cellId, idx) => {const isColumnBoundary = columnBoundaries.includes(idx);return (<React.Fragment key={cellId}>diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 7c7e5a8929..c1bd6a8687 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -19,7 +19,6 @@ import { SortableCellsProvider } from "@/components/sort/SortableCellsProvider";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";-import type { CellId } from "@/core/cells/ids";import { MarkdownLanguageAdapter } from "@/core/codemirror/language/languages/markdown";import { SQLLanguageAdapter } from "@/core/codemirror/language/languages/sql";import { aiEnabledAtom } from "@/core/config/config";@@ -27,25 +26,22 @@ import { isConnectedAtom } from "@/core/network/connection";import { useBoolean } from "@/hooks/useBoolean";import { cn } from "@/utils/cn";import { Functions } from "@/utils/functions";-import type { CellColumnId, CollapsibleTree } from "@/utils/id-tree";-import type { Milliseconds } from "@/utils/time";+import type { CellColumnId } from "@/utils/id-tree";+import { invariant } from "@/utils/invariant";import {- type CellActions,columnIdsAtom,- type NotebookState,SETUP_CELL_ID,useCellActions,- useNotebook,+ useCellIds,+ useScrollKey,} from "../../../core/cells/cells";import { formatAll } from "../../../core/codemirror/format";import type { AppConfig, UserConfig } from "../../../core/config/config-schema";import type { AppMode } from "../../../core/mode";-import type { ConnectionStatus } from "../../../core/websocket/types";import { useHotkey } from "../../../hooks/useHotkey";import { type Theme, useTheme } from "../../../theme/useTheme";import { AddCellWithAI } from "../ai/add-cell-with-ai";import { ConnectingAlert } from "../alerts/connecting-alert";-import { useDeleteCellCallback } from "../cell/useDeleteCell";import { FloatingOutline } from "../chrome/panels/outline/floating-outline";import { useChromeActions } from "../chrome/state";import { Column } from "../columns/cell-column";@@ -58,7 +54,6 @@ interface CellArrayProps {mode: AppMode;userConfig: UserConfig;appConfig: AppConfig;- connStatus: ConnectionStatus;}export const CellArray: React.FC<CellArrayProps> = (props) => {@@ -82,9 +77,7 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({mode,userConfig,appConfig,- connStatus,}) => {- const notebook = useNotebook();const actions = useCellActions();const { theme } = useTheme();const { toggleSidebarPanel } = useChromeActions();@@ -106,19 +99,17 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({useHotkey("cell.hideCode", Functions.NOOP);useHotkey("cell.format", Functions.NOOP);- const onDeleteCell = useDeleteCellCallback();+ const cellIds = useCellIds();+ const scrollKey = useScrollKey();+ const columnIds = cellIds.getColumnIds();// Scroll to a cell targeted by a previous actionconst scrollToTarget = actions.scrollToTarget;useEffect(() => {- if (notebook.scrollKey !== null) {+ if (scrollKey !== null) {scrollToTarget();}- }, [notebook.cellIds, notebook.scrollKey, scrollToTarget]);-- const columns = notebook.cellIds.getColumns();- const hasOnlyOneCell = notebook.cellIds.hasOnlyOneId();- const hasSetupCell = notebook.cellIds.inOrderIds.includes(SETUP_CELL_ID);+ }, [cellIds, scrollKey, scrollToTarget]);return (<VerticalLayoutWrapper@@ -138,22 +129,16 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({"grid grid-flow-col auto-cols-min gap-6",)}>- {columns.map((column, index) => (+ {columnIds.map((columnId, index) => (<CellColumn- key={column.id}- column={column}+ key={columnId}+ columnId={columnId}index={index}- columnsLength={columns.length}+ columnsLength={columnIds.length}appConfig={appConfig}- notebook={notebook}mode={mode}userConfig={userConfig}- connStatus={connStatus}- actions={actions}theme={theme}- hasOnlyOneCell={hasOnlyOneCell}- hasSetupCell={hasSetupCell}- onDeleteCell={onDeleteCell}/>))}</div>@@ -166,39 +151,32 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({* A single column of cells.*/const CellColumn: React.FC<{- column: CollapsibleTree<CellId>;+ columnId: CellColumnId;index: number;columnsLength: number;appConfig: AppConfig;- notebook: NotebookState;mode: AppMode;userConfig: UserConfig;- connStatus: ConnectionStatus;- actions: CellActions;theme: Theme;- hasOnlyOneCell: boolean;- hasSetupCell: boolean;- onDeleteCell: (payload: { cellId: CellId }) => void;}> = ({- column,+ columnId,index,columnsLength,appConfig,- notebook,mode,userConfig,- connStatus,- actions,theme,- hasOnlyOneCell,- hasSetupCell,- onDeleteCell,}) => {- const connectionState = connStatus.state;+ const cellIds = useCellIds();+ const column = cellIds.get(columnId);+ invariant(column, `Expected column for: ${columnId}`);++ const hasOnlyOneCell = cellIds.hasOnlyOneId();+ const hasSetupCell = cellIds.inOrderIds.includes(SETUP_CELL_ID);return (<Column- columnId={column.id}+ columnId={columnId}index={index}canMoveLeft={index > 0}canMoveRight={index < columnsLength - 1}@@ -206,7 +184,7 @@ const CellColumn: React.FC<{canDelete={columnsLength > 1}footer={<AddCellButtons- columnId={column.id}+ columnId={columnId}className={cn(appConfig.width === "columns" &&"opacity-0 group-hover/column:opacity-100",@@ -223,26 +201,15 @@ const CellColumn: React.FC<{{index === 0 && hasSetupCell && (<Cellkey={SETUP_CELL_ID}+ cellId={SETUP_CELL_ID}theme={theme}showPlaceholder={false}- {...notebook.cellData[SETUP_CELL_ID]}- {...notebook.cellRuntime[SETUP_CELL_ID]}- {...actions}- runElapsedTimeMs={- notebook.cellRuntime[SETUP_CELL_ID].runElapsedTimeMs ??- (notebook.cellData[SETUP_CELL_ID]- .lastExecutionTime as Milliseconds)- }canDelete={true}mode={mode}- connectionState={connectionState}- ref={notebook.cellHandles[SETUP_CELL_ID]}userConfig={userConfig}isCollapsed={false}collapseCount={0}canMoveX={false}- actions={actions}- deleteCell={onDeleteCell}/>)}@@ -252,31 +219,18 @@ const CellColumn: React.FC<{return null;}- const cellData = notebook.cellData[cellId];- const cellRuntime = notebook.cellRuntime[cellId];return (<Cell- key={cellData.id.toString()}+ key={cellId}+ cellId={cellId}theme={theme}showPlaceholder={hasOnlyOneCell}- {...cellData}- {...cellRuntime}- runElapsedTimeMs={- cellRuntime.runElapsedTimeMs ??- (cellData.lastExecutionTime as Milliseconds)- }canDelete={!hasOnlyOneCell}mode={mode}- connectionState={connectionState}- ref={notebook.cellHandles[cellId]}userConfig={userConfig}- config={cellData.config}- name={cellData.name}isCollapsed={column.isCollapsed(cellId)}collapseCount={column.getCount(cellId)}canMoveX={appConfig.width === "columns"}- actions={actions}- deleteCell={onDeleteCell}/>);})}diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 6f1dda6a2e..af0952ce91 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -2528,6 +2528,54 @@ describe("cell reducer", () => {expect(exportedForTesting.isCellCodeHidden(state, newCellId)).toBe(true);});});++ describe("releaseCellAtoms", () => {+ it("atom families cache atoms until explicitly removed", () => {+ const { cellDataAtom, cellRuntimeAtom, cellHandleAtom } =+ exportedForTesting;++ actions.createNewCell({ cellId: firstCellId, before: false });+ const newCellId = state.cellIds.inOrderIds[1];++ const dataAtom1 = cellDataAtom(newCellId);+ const runtimeAtom1 = cellRuntimeAtom(newCellId);+ const handleAtom1 = cellHandleAtom(newCellId);++ // accesses return cached atoms (same reference)+ const dataAtom2 = cellDataAtom(newCellId);+ const runtimeAtom2 = cellRuntimeAtom(newCellId);+ const handleAtom2 = cellHandleAtom(newCellId);++ expect(dataAtom2).toBe(dataAtom1);+ expect(runtimeAtom2).toBe(runtimeAtom1);+ expect(handleAtom2).toBe(handleAtom1);+ });++ it("cleans up atom family cache when cells are deleted", () => {+ const { cellDataAtom, cellRuntimeAtom, cellHandleAtom } =+ exportedForTesting;++ actions.createNewCell({ cellId: firstCellId, before: false });+ const newCellId = state.cellIds.inOrderIds[1];++ // Access to create cache entries+ const dataAtom1 = cellDataAtom(newCellId);+ const runtimeAtom1 = cellRuntimeAtom(newCellId);+ const handleAtom1 = cellHandleAtom(newCellId);++ // Triggers purge+ actions.deleteCell({ cellId: newCellId });++ // Access again (should be new instances after cleanup)+ const dataAtom2 = cellDataAtom(newCellId);+ const runtimeAtom2 = cellRuntimeAtom(newCellId);+ const handleAtom2 = cellHandleAtom(newCellId);++ expect(dataAtom2).not.toBe(dataAtom1);+ expect(runtimeAtom2).not.toBe(runtimeAtom1);+ expect(handleAtom2).not.toBe(handleAtom1);+ });+ });});describe("isCellCodeHidden", () => {diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex b287a53e89..58e776a62a 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -2,7 +2,7 @@import { historyField } from "@codemirror/commands";import { type Atom, atom, useAtom, useAtomValue } from "jotai";-import { selectAtom, splitAtom } from "jotai/utils";+import { atomFamily, selectAtom, splitAtom } from "jotai/utils";import { isEqual, zip } from "lodash-es";import { createRef, type ReducerWithoutAction } from "react";import type { CellHandle } from "@/components/editor/Cell";@@ -591,6 +591,8 @@ const {});serializedEditorState.doc = state.cellData[cellId].code;+ // release the granular atom(s) created for this cell+ releaseCellAtoms(cellId);return {...state,cellIds: state.cellIds.deleteById(cellId),@@ -1537,6 +1539,8 @@ export const cellIdToNamesMap = createDeepEqualAtom(}),);+const scrollKeyAtom = atom((get) => get(notebookAtom).scrollKey);+/// HOOKS/**@@ -1564,6 +1568,11 @@ export const useCellErrors = () => useAtomValue(cellErrorsAtom);*/export const useCellLogs = () => useAtomValue(notebookAtom).cellLogs;+/**+ * React-hook for the notebook scrollKey+ */+export const useScrollKey = () => useAtomValue(scrollKeyAtom);+/// IMPERATIVE GETTERS/**@@ -1608,6 +1617,41 @@ export const columnIdsAtom = atom((get) =>get(notebookAtom).cellIds.getColumnIds(),);+const cellDataAtom = atomFamily((cellId: CellId) =>+ atom((get) => get(notebookAtom).cellData[cellId]),+);+const cellRuntimeAtom = atomFamily((cellId: CellId) =>+ atom((get) => get(notebookAtom).cellRuntime[cellId]),+);+const cellHandleAtom = atomFamily((cellId: CellId) =>+ atom((get) => get(notebookAtom).cellHandles[cellId]),+);+/**+ * Cleans up atomFamily cache entries for the given cell.+ *+ * Jotai's atomFamily retains a cache of created atoms, which can cause memory leaks+ * if not explicitly removed. This function removes the atoms associated with a specific+ * cellId to free up memory.+ *+ * @param cellId - The cell ID whose atoms should be removed.+ * @see https://jotai.org/docs/utilities/family#caveat-memory-leaks+ */+export function releaseCellAtoms(cellId: CellId) {+ cellDataAtom.remove(cellId);+ cellRuntimeAtom.remove(cellId);+ cellHandleAtom.remove(cellId);+}++/** Subscribes to reactive updates of the cell's data. */+export const useCellData = (cellId: CellId) =>+ useAtomValue(cellDataAtom(cellId));+/** Subscribes to reactive updates of the cell's runtime info. */+export const useCellRuntime = (cellId: CellId) =>+ useAtomValue(cellRuntimeAtom(cellId));+/** Subscribes to reactive updates of the cell's handle (e.g. refs or UI bindings). */+export const useCellHandle = (cellId: CellId) =>+ useAtomValue(cellHandleAtom(cellId));+/*** Get the editor views for all cells.*/@@ -1700,4 +1744,8 @@ export const exportedForTesting = {createActions,initialNotebookState,isCellCodeHidden,+ // Export atom families for testing cleanup+ cellDataAtom,+ cellRuntimeAtom,+ cellHandleAtom,};diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsxindex ec135496ca..787fbca711 100644--- a/frontend/src/core/edit-app.tsx+++ b/frontend/src/core/edit-app.tsx@@ -134,7 +134,6 @@ export const EditApp: React.FC<AppProps> = ({const editableCellsArray = (<CellArray- connStatus={connection}mode={viewState.mode}userConfig={userConfig}appConfig={appConfig}diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 08dfd52a6e..a420b3f9ef 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -1,77 +1,112 @@/* Copyright 2024 Marimo. All rights reserved. */import type { Meta, StoryObj } from "@storybook/react-vite";+import { createStore, Provider } from "jotai";+import { createRef } from "react";+import { type NotebookState, notebookAtom } from "@/core/cells/cells";+import {+ type CellRuntimeState,+ createCellRuntimeState,+} from "@/core/cells/types";import { defaultUserConfig } from "@/core/config/config-schema";+import { connectionAtom } from "@/core/network/connection";+import type { CellConfig } from "@/core/network/types";import { WebSocketState } from "@/core/websocket/types";-import { Logger } from "@/utils/Logger";+import { MultiColumn } from "@/utils/id-tree";import type { Milliseconds, Seconds } from "@/utils/time";-import { Cell, type CellProps } from "../components/editor/Cell";+import { Cell as EditorCell } from "../components/editor/Cell";import { TooltipProvider } from "../components/ui/tooltip";import type { CellId } from "../core/cells/ids";-const meta: Meta<typeof Cell> = {- title: "Cell",- component: Cell,- args: {},-};--export default meta;type Story = StoryObj<typeof Cell>;-const props: CellProps = {- theme: "light",- showPlaceholder: false,- id: "1" as CellId,- code: "import marimo as mo",- output: null,- consoleOutputs: [],- status: "idle",- edited: false,- interrupted: false,- errored: false,- stopped: false,- staleInputs: false,- runStartTimestamp: 0 as Seconds,- runElapsedTimeMs: 10 as Milliseconds,- lastRunStartTimestamp: 0 as Seconds,- serializedEditorState: null,- mode: "edit",- name: "cell_1",- connectionState: WebSocketState.OPEN,- canDelete: true,- debuggerActive: false,- isCollapsed: false,- collapseCount: 0,- outline: null,- deleteCell: Logger.log,- actions: {- updateCellCode: Logger.log,- clearCellConsoleOutput: Logger.log,- collapseCell: Logger.log,- expandCell: Logger.log,- createNewCell: Logger.log,- focusCell: Logger.log,- moveCell: Logger.log,- moveToNextCell: Logger.log,- sendToBottom: Logger.log,- sendToTop: Logger.log,- updateCellConfig: Logger.log,- setStdinResponse: Logger.log,- clearSerializedEditorState: Logger.log,- },- canMoveX: false,- config: {- hide_code: false,- disabled: false,- },- userConfig: defaultUserConfig(),+const Cell: React.FC<{+ overrides?: {+ runElapsedTimeMs?: Milliseconds;+ output?: CellRuntimeState["output"];+ edited?: boolean;+ interrupted?: boolean;+ errored?: boolean;+ status?: CellRuntimeState["status"];+ staleInputs?: boolean;+ config?: CellConfig;+ };+}> = ({ overrides = {} }) => {+ const cellId = "1" as CellId;+ const notebook: NotebookState = {+ cellData: {+ [cellId]: {+ id: cellId,+ name: "cell_1",+ code: "import marimo as mo",+ edited: overrides.edited ?? false,+ serializedEditorState: null,+ config: {+ hide_code: overrides.config?.hide_code ?? false,+ disabled: overrides.config?.disabled ?? false,+ column: null,+ },+ lastCodeRun: null,+ lastExecutionTime: null,+ },+ },+ cellIds: MultiColumn.from([[cellId]]),+ cellRuntime: {+ [cellId]: createCellRuntimeState({+ output: overrides.output ?? null,+ runElapsedTimeMs: overrides.runElapsedTimeMs ?? (10 as Milliseconds),+ status: overrides.status ?? "idle",+ consoleOutputs: [],+ interrupted: overrides.interrupted ?? false,+ errored: overrides.errored ?? false,+ stopped: false,+ staleInputs: overrides.staleInputs ?? false,+ runStartTimestamp: 0 as Seconds,+ lastRunStartTimestamp: 0 as Seconds,+ debuggerActive: false,+ outline: null,+ }),+ },+ cellHandles: {+ [cellId]: createRef(),+ },+ cellLogs: [],+ history: [],+ scrollKey: null,+ untouchedNewCells: new Set(),+ };++ const store = createStore();+ store.set(notebookAtom, notebook);+ store.set(connectionAtom, { state: WebSocketState.OPEN });+ return (+ <Provider store={store}>+ <TooltipProvider>+ <EditorCell+ cellId={cellId}+ theme={"light"}+ showPlaceholder={false}+ mode={"edit"}+ canDelete={true}+ isCollapsed={false}+ collapseCount={0}+ canMoveX={false}+ userConfig={defaultUserConfig()}+ />+ </TooltipProvider>+ </Provider>+ );};+export default {+ title: "Cell",+ component: Cell,+ args: {},+} satisfies Meta<typeof Cell>;+export const Primary: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell {...props} />- </TooltipProvider>+ <Cell /></div>),};@@ -79,18 +114,17 @@ export const Primary: Story = {export const WithOutput: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- output={{+ <Cell+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ 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: 1_686_863_688,- }}- />- </TooltipProvider>+ },+ }}+ /></div>),};@@ -98,20 +132,19 @@ export const WithOutput: Story = {export const WithLargeOutput: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- output={{+ <Cell+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ 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>".repeat(10,),mimetype: "text/html",timestamp: 1_686_863_688,- }}- />- </TooltipProvider>+ },+ }}+ /></div>),};@@ -121,14 +154,15 @@ export const UnsavedEditsOutput: Story = {<div className="p-20 max-w-4xl"><TooltipProvider><Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- edited={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: 1_686_863_688,+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ edited: 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: 1_686_863_688,+ },}}/></TooltipProvider>@@ -141,14 +175,15 @@ export const InterruptedOutput: Story = {<div className="p-20 max-w-4xl"><TooltipProvider><Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- 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: 1_686_863_688,+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ 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: 1_686_863_688,+ },}}/></TooltipProvider>@@ -159,19 +194,18 @@ export const InterruptedOutput: Story = {export const WithError: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- errored={true}- output={{+ <Cell+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ errored: 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: 1_686_863_688,- }}- />- </TooltipProvider>+ },+ }}+ /></div>),};@@ -179,22 +213,21 @@ export const WithError: Story = {export const Disabled: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- config={{+ <Cell+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ config: {disabled: true,hide_code: false,- }}- output={{+ },+ 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: 1_686_863_688,- }}- />- </TooltipProvider>+ },+ }}+ /></div>),};@@ -202,19 +235,18 @@ export const Disabled: Story = {export const DisabledTransitively: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- status="disabled-transitively"- output={{+ <Cell+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ status: "disabled-transitively",+ output: {channel: "output",data: "This data is stale because a parent is disabled",mimetype: "text/html",timestamp: 1_686_863_688,- }}- />- </TooltipProvider>+ },+ }}+ /></div>),};@@ -222,20 +254,19 @@ export const DisabledTransitively: Story = {export const StaleStatus: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- status="disabled-transitively"- staleInputs={true}- output={{+ <Cell+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ status: "disabled-transitively",+ staleInputs: true,+ output: {channel: "output",data: "This data is stale because a parent is disabled",mimetype: "text/html",timestamp: 1_686_863_688,- }}- />- </TooltipProvider>+ },+ }}+ /></div>),};@@ -243,20 +274,20 @@ export const StaleStatus: Story = {export const StaleAndEditedStatus: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- status="disabled-transitively"- staleInputs={true}- output={{+ <Cell+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ status: "disabled-transitively",+ staleInputs: true,+ edited: true,+ output: {channel: "output",data: "This data is stale because a parent is disabled, but this cell has been edited since.",mimetype: "text/html",timestamp: 1_686_863_688,- }}- />- </TooltipProvider>+ },+ }}+ /></div>),};@@ -264,24 +295,23 @@ export const StaleAndEditedStatus: Story = {export const DisabledAndStaleStatus: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- config={{+ <Cell+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ config: {disabled: true,hide_code: false,- }}- status="disabled-transitively"- staleInputs={true}- output={{+ },+ status: "disabled-transitively",+ staleInputs: 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: 1_686_863_688,- }}- />- </TooltipProvider>+ },+ }}+ /></div>),};@@ -289,19 +319,18 @@ export const DisabledAndStaleStatus: Story = {export const Running: Story = {render: () => (<div className="p-20 max-w-4xl">- <TooltipProvider>- <Cell- {...props}- runElapsedTimeMs={20 as Milliseconds}- status="running"- output={{+ <Cell+ overrides={{+ runElapsedTimeMs: 20 as Milliseconds,+ 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: 1_686_863_688,- }}- />- </TooltipProvider>+ },+ }}+ /></div>),};