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
Add destructive cell deletion confirmation (#5664)
Trevor Manz51f6cf07a656
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex f68227ed7c..06091b77ba 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -3,6 +3,7 @@import { zodResolver } from "@hookform/resolvers/zod";import { atom, useAtom, useAtomValue, useSetAtom } from "jotai";import {+ AlertTriangleIcon,BrainIcon,CpuIcon,EditIcon,@@ -582,6 +583,48 @@ export const UserConfigForm: React.FC = () => {<FormMessage /><IsOverridden userConfig={config} name="keymap.preset" /></FormItem>+ </div>+ )}+ />+ <FormField+ control={form.control}+ name="keymap.destructive_delete"+ render={({ field }) => (+ <div className="flex flex-col space-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel className="font-normal">+ Destructive delete+ </FormLabel>+ <FormControl>+ <Checkbox+ data-testid="destructive-delete-checkbox"+ checked={field.value}+ disabled={field.disabled}+ onCheckedChange={(checked) => {+ field.onChange(Boolean(checked));+ }}+ />+ </FormControl>+ <FormMessage />+ <IsOverridden+ userConfig={config}+ name="keymap.destructive_delete"+ />+ </FormItem>+ <FormDescription className="flex items-center gap-1">+ Allow deleting non-empty cells+ <Tooltip+ content={+ <div className="max-w-xs">+ <strong>Use with caution:</strong> Deleting cells+ with code can lose work and computed results since+ variables are removed from memory.+ </div>+ }+ >+ <AlertTriangleIcon className="w-3 h-3 text-[var(--amber-11)]" />+ </Tooltip>+ </FormDescription><div><Buttondiff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex aeb1146246..2769ef1103 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -68,6 +68,7 @@ import { CellActionsContextMenu } from "./cell/cell-context-menu";import { CellEditor } from "./cell/code/cell-editor";import { CollapsedCellBanner, CollapseToggle } from "./cell/collapse";import { DeleteButton } from "./cell/DeleteButton";+import { PendingDeleteConfirmation } from "./cell/PendingDeleteConfirmation";import { RunButton } from "./cell/RunButton";import { useRunCell } from "./cell/useRunCells";import { HideCodeButton } from "./code/readonly-python-code";@@ -790,6 +791,7 @@ const EditableCellComponent = ({cellId={cellId}debuggerActive={debuggerActive}/>+ <PendingDeleteConfirmation cellId={cellId} /></div>{isCollapsed && (<CollapsedCellBannerdiff --git a/frontend/src/components/editor/cell/PendingDeleteConfirmation.tsx b/frontend/src/components/editor/cell/PendingDeleteConfirmation.tsxnew file mode 100644index 0000000000..24090d1dae--- /dev/null+++ b/frontend/src/components/editor/cell/PendingDeleteConfirmation.tsx@@ -0,0 +1,127 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { AlertTriangleIcon } from "lucide-react";+import React from "react";+import { FocusScope } from "react-aria";+import { formatElapsedTime } from "@/components/editor/cell/CellStatus";+import { CellLink } from "@/components/editor/links/cell-link";+import { Button } from "@/components/ui/button";+import type { CellId } from "@/core/cells/ids";+import { usePendingDelete } from "@/core/cells/pending-delete-service";+import { cn } from "@/utils/cn";++export const PendingDeleteConfirmation: React.FC<{ cellId: CellId }> = ({+ cellId,+}) => {+ const pendingDelete = usePendingDelete(cellId);++ if (!pendingDelete.isPending) {+ return null;+ }++ // Non-primary handlers in multi-delete just show pending state+ if (pendingDelete.type === "simple") {+ return (+ <div+ className={cn(+ "px-3 py-1.5",+ "bg-[var(--amber-2)] border-t border-[var(--amber-6)]",+ "animate-in slide-in-from-top-2 duration-200",+ )}+ data-testid={`pending-delete-${cellId}`}+ >+ <div className="flex items-center gap-2">+ <AlertTriangleIcon className="w-3 h-3 text-[var(--amber-11)] flex-shrink-0" />+ <span className="text-[var(--amber-11)] text-xs">+ Pending deletion+ </span>+ </div>+ </div>+ );+ }++ const hasExpensiveExecution = pendingDelete.executionDurationMs !== undefined;+ const hasDependencies = pendingDelete.defs.size > 0;+ const formattedTime = formatElapsedTime(+ pendingDelete.executionDurationMs ?? 0,+ );++ let warningMessage = "Pending deletion";+ if (hasExpensiveExecution && hasDependencies) {+ warningMessage = `This cell took ${formattedTime} to run and contains variables referenced by other cells.`;+ } else if (hasExpensiveExecution) {+ warningMessage = `This cell took ${formattedTime} to run.`;+ } else if (hasDependencies) {+ warningMessage = "This cell contains variables referenced by other cells.";+ }++ return (+ <div+ className={cn(+ "px-4 py-3",+ "bg-[var(--amber-2)] border-t border-[var(--amber-6)]",+ "animate-in slide-in-from-top-2 duration-200",+ )}+ data-testid={`pending-delete-${cellId}`}+ >+ <div className="flex items-start gap-3">+ <AlertTriangleIcon className="w-4 h-4 text-[var(--amber-11)] mt-0.5 flex-shrink-0" />+ <div className="flex-1">+ <div className="font-code text-sm text-[0.84375rem]">+ <p className="text-[var(--amber-11)] font-medium">+ {warningMessage}+ </p>++ {hasDependencies &&+ [...pendingDelete.defs.entries()].map(([varName, cells]) => (+ <div key={varName}>+ <p className="text-[var(--amber-11)] mt-2">+ '<span className="font-mono">{varName}</span>' is referenced+ by:+ </p>+ <ul className="list-disc">+ {cells.map((id) => (+ <li+ key={id}+ className="my-0.5 ml-8 text-[var(--amber-11)]/60"+ >+ <CellLink cellId={id} />+ </li>+ ))}+ </ul>+ </div>+ ))}+ </div>+ {/* Only show buttons for single cell - multi-cell uses toast */}+ {pendingDelete.shouldConfirmDelete && (+ <>+ <p className="text-[var(--amber-11)] mt-2 mb-3">+ Are you sure you want to delete?+ </p>+ <FocusScope autoFocus={true}>+ <div className="flex items-center gap-2">+ <Button+ size="xs"+ variant="ghost"+ onClick={() => pendingDelete.cancel()}+ className="text-[var(--amber-11)] hover:bg-[var(--amber-4)] hover:text-[var(--amber-11)]"+ >+ Cancel+ </Button>+ <Button+ size="xs"+ variant="secondary"+ onClick={() => pendingDelete.confirm()}+ className="bg-[var(--amber-11)] hover:bg-[var(--amber-12)] text-white border-[var(--amber-11)]"+ >+ Delete+ </Button>+ </div>+ </FocusScope>+ </>+ )}+ </div>+ </div>+ </div>+ );+};diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 47e48dcbfd..c7316f707a 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -10,6 +10,7 @@ import { DelayMount } from "@/components/utils/delay-mount";import { aiCompletionCellAtom } from "@/core/ai/state";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { useCellActions } from "@/core/cells/cells";+import { usePendingDeleteService } from "@/core/cells/pending-delete-service";import type { CellData, CellRuntimeState } from "@/core/cells/types";import { setupCodeMirror } from "@/core/codemirror/cm";import {@@ -91,6 +92,7 @@ const CellEditorInternal = ({const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom);const deleteCell = useDeleteCellCallback();const { saveOrNameNotebook } = useSaveNotebook();+ const pendingDeleteService = usePendingDeleteService();const loading = status === "running" || status === "queued";const cellActions = useCellActions();@@ -104,6 +106,11 @@ const CellEditorInternal = ({return false;}+ if (pendingDeleteService.idle && userConfig.keymap.destructive_delete) {+ pendingDeleteService.submit([cellId]);+ return true;+ }+deleteCell({ cellId });return true;});diff --git a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts b/frontend/src/components/editor/navigation/__tests__/navigation.test.tsindex 84089d9288..b59a7fc886 100644--- a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts+++ b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts@@ -101,6 +101,8 @@ const mockCellActions = MockNotebook.cellActions({sendToBottom: vi.fn(),updateCellConfig: vi.fn(),markTouched: vi.fn(),+ deleteCell: vi.fn(),+ undoDeleteCell: vi.fn(),});const mockSaveCellConfig = vi.mocked(saveCellConfig);diff --git a/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx b/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsxindex db52dc2d5c..04c64bb5ef 100644--- a/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx+++ b/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx@@ -3,6 +3,7 @@import type { EditorView } from "@codemirror/view";import { useAtomValue } from "jotai";import {+ AlertTriangleIcon,ChevronDownIcon,ChevronsDownIcon,ChevronsUpIcon,@@ -35,7 +36,9 @@ import {useCellActions,} from "@/core/cells/cells";import type { CellId } from "@/core/cells/ids";+import { usePendingDeleteService } from "@/core/cells/pending-delete-service";import { formatEditorViews } from "@/core/codemirror/format";+import { userConfigAtom } from "@/core/config/config";import type { HotkeyAction } from "@/core/hotkeys/hotkeys";import { saveCellConfig } from "@/core/network/requests";import type { CellConfig } from "@/core/network/types";@@ -54,7 +57,8 @@ interface MultiCellActionButton extends Omit<ActionButton, "handle"> {const CellStateDropdown: React.FC<{actions: MultiCellActionButton[][];cellIds: CellId[];-}> = ({ actions, cellIds }) => {+ disabled?: boolean;+}> = ({ actions, cellIds, disabled }) => {return (<DropdownMenu><DropdownMenuTrigger asChild={true}>@@ -63,6 +67,7 @@ const CellStateDropdown: React.FC<{size="sm"className="h-8 px-2 gap-1"title="More actions"+ disabled={disabled}><MoreHorizontalIcon size={13} strokeWidth={1.5} /></Button>@@ -117,13 +122,21 @@ export function useMultiCellActionButtons(cellIds: CellId[]) {const hasOnlyOneCell = useAtomValue(hasOnlyOneCellAtom);const selectionActions = useCellSelectionActions();const runCells = useRunCells();+ const pendingDeleteService = usePendingDeleteService();+ const userConfig = useAtomValue(userConfigAtom);const selectedCount = cellIds.length;const canDelete = !hasOnlyOneCell || selectedCount < cellIds.length;const deleteSelectedCells = useEvent((cellIds: CellId[]) => {+ // First click sets pending, second click deletes+ if (pendingDeleteService.idle && userConfig.keymap.destructive_delete) {+ pendingDeleteService.submit(cellIds);+ return;+ }deleteCell({ cellIds });+ pendingDeleteService.clear();selectionActions.clear();});@@ -329,13 +342,76 @@ export const MultiCellActionToolbar = () => {return null;}- return <MultiCellActionToolbarInternal cellIds={selectedCells} />;+ return (+ <>+ <MultiCellActionToolbarInternal cellIds={selectedCells} />+ <MultiCellPendingDeleteBar cellIds={selectedCells} />+ </>+ );};const Separator = () => <div className="h-4 w-px bg-border mx-1" />;+const MultiCellPendingDeleteBar: React.FC<{ cellIds: CellId[] }> = ({+ cellIds,+}) => {+ const pendingDeleteService = usePendingDeleteService();+ const deleteCell = useDeleteManyCellsCallback();++ if (!pendingDeleteService.shouldConfirmDelete) {+ return null;+ }++ return (+ <div+ className="absolute top-12 justify-center flex w-full left-0 right-0 z-50"+ data-keep-cell-selection={true}+ >+ <div className="mx-20">+ <div className="bg-[var(--amber-2)] border border-[var(--amber-6)] rounded-lg shadow-lg mt-14 px-4 py-3 animate-in slide-in-from-top-2 duration-200">+ <div className="flex items-start gap-3">+ <AlertTriangleIcon className="w-4 h-4 text-[var(--amber-11)] mt-0.5 flex-shrink-0" />+ <div className="flex-1">+ <div className="font-code text-sm text-[0.84375rem]">+ <p className="text-[var(--amber-11)] font-medium">+ Some cells in selection may contain expensive operations.+ </p>+ <p className="text-[var(--amber-11)] mt-1">+ Are you sure you want to delete?+ </p>+ </div>+ <div className="flex items-center gap-2 mt-3">+ <Button+ size="xs"+ variant="ghost"+ onClick={() => pendingDeleteService.clear()}+ className="text-[var(--amber-11)] hover:bg-[var(--amber-4)] hover:text-[var(--amber-11)]"+ >+ Cancel+ </Button>+ <Button+ size="xs"+ variant="secondary"+ onClick={() => {+ deleteCell({ cellIds });+ pendingDeleteService.clear();+ }}+ className="bg-[var(--amber-11)] hover:bg-[var(--amber-12)] text-white border-[var(--amber-11)]"+ >+ Delete+ </Button>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+};+const MultiCellActionToolbarInternal = ({ cellIds }: { cellIds: CellId[] }) => {const selectionActions = useCellSelectionActions();+ const pendingDeleteService = usePendingDeleteService();const { actions, moreActions } = useMultiCellActionButtons(cellIds);const selectedCount = cellIds.length;@@ -356,9 +432,11 @@ const MultiCellActionToolbarInternal = ({ cellIds }: { cellIds: CellId[] }) => {if (evt.target instanceof HTMLHtmlElement) {return;}+ pendingDeleteService.clear();selectionActions.clear();});+ const isPendingDelete = !pendingDeleteService.idle;return (<divclassName="absolute top-12 justify-center flex w-full left-0 right-0 z-50"@@ -385,6 +463,7 @@ const MultiCellActionToolbarInternal = ({ cellIds }: { cellIds: CellId[] }) => {onClick={() => action.handle(cellIds)}className="h-8 px-2 gap-1 flex-shrink-0 flex items-center"title={action.label}+ disabled={isPendingDelete && action.label !== "Delete cells"}>{action.icon}<span className="text-xs">{action.label}</span>@@ -399,7 +478,11 @@ const MultiCellActionToolbarInternal = ({ cellIds }: { cellIds: CellId[] }) => {</div>))}<Separator />- <CellStateDropdown actions={moreActions} cellIds={cellIds} />+ <CellStateDropdown+ actions={moreActions}+ cellIds={cellIds}+ disabled={isPendingDelete}+ /></div></div></div>diff --git a/frontend/src/components/editor/navigation/navigation.ts b/frontend/src/components/editor/navigation/navigation.tsindex ad7773221f..d7aa8bc5de 100644--- a/frontend/src/components/editor/navigation/navigation.ts+++ b/frontend/src/components/editor/navigation/navigation.ts@@ -7,13 +7,19 @@ import { aiCompletionCellAtom } from "@/core/ai/state";import { cellIdsAtom, notebookAtom, useCellActions } from "@/core/cells/cells";import { useSetLastFocusedCellId } from "@/core/cells/focus";import type { CellId } from "@/core/cells/ids";-import { hotkeysAtom, keymapPresetAtom } from "@/core/config/config";+import { usePendingDeleteService } from "@/core/cells/pending-delete-service";+import {+ hotkeysAtom,+ keymapPresetAtom,+ userConfigAtom,+} from "@/core/config/config";import type { HotkeyAction } from "@/core/hotkeys/hotkeys";import { parseShortcut } from "@/core/hotkeys/shortcuts";import { saveCellConfig } from "@/core/network/requests";import { useSaveNotebook } from "@/core/saving/save-component";import { Events } from "@/utils/events";import type { CellActionsDropdownHandle } from "../cell/cell-actions";+import { useDeleteManyCellsCallback } from "../cell/useDeleteCell";import { useRunCells } from "../cell/useRunCells";import { useCellClipboard } from "./clipboard";import { focusCell, focusCellEditor } from "./focus-utils";@@ -75,6 +81,7 @@ function useCellFocusProps(cellId: CellId) {const setLastFocusedCellId = useSetLastFocusedCellId();const actions = useCellActions();const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);+ const pendingDeleteService = usePendingDeleteService();// This occurs at the cell level and descedants.const { focusWithinProps } = useFocusWithin({@@ -86,6 +93,7 @@ function useCellFocusProps(cellId: CellId) {// On blur, hide the code if it was temporarily shown.setTemporarilyShownCode(false);actions.markTouched({ cellId });+ pendingDeleteService.clear();},});@@ -123,8 +131,27 @@ export function useCellNavigationProps(const runCells = useRunCells();const keymapPreset = useAtomValue(keymapPresetAtom);const { copyCells, pasteAtCell } = useCellClipboard();- const selectionActions = useCellSelectionActions();+ const rawSelectionActions = useCellSelectionActions();const isSelected = useIsCellSelected(cellId);+ const pendingDeleteService = usePendingDeleteService();+ const deleteCells = useDeleteManyCellsCallback();+ const userConfig = useAtomValue(userConfigAtom);++ // Wrap selection actions to clear pending cells on any selection change+ const selectionActions = {+ clear: () => {+ pendingDeleteService.clear();+ rawSelectionActions.clear();+ },+ extend: (args: Parameters<typeof rawSelectionActions.extend>[0]) => {+ pendingDeleteService.clear();+ rawSelectionActions.extend(args);+ },+ select: (args: Parameters<typeof rawSelectionActions.select>[0]) => {+ pendingDeleteService.clear();+ rawSelectionActions.select(args);+ },+ };const hotkeys = useAtomValue(hotkeysAtom);@@ -230,27 +257,8 @@ export function useCellNavigationProps(}}- // Keymaps when using vim.- if (- keymapPreset === "vim" &&- handleVimKeybinding(evt.nativeEvent || evt, {- j: keymaps.ArrowDown,- k: keymaps.ArrowUp,- i: keymaps.Enter,- "shift+j": keymaps["Shift+ArrowDown"],- "shift+k": keymaps["Shift+ArrowUp"],- "g g": keymaps["Mod+ArrowUp"],- "shift+g": keymaps["Mod+ArrowDown"],- })- ) {- evt.preventDefault();- return;- }-// Shortcuts- const shortcuts: Partial<- Record<HotkeyAction, HotkeyHandler["handle"] | HotkeyHandler>- > = {+ const shortcuts = {// Cell actions"cell.run": addSingleHandler((cellIds) => {runCells(cellIds);@@ -429,10 +437,61 @@ export function useCellNavigationProps(actions.createNewCell({ cellId, before: false, autoFocus: true });return true;},- };+ "cell.delete": () => {+ // Only handle if destructive_delete is enabled+ if (!userConfig.keymap.destructive_delete) {+ return false;+ }++ const cellIds =+ selectedCells.size >= 2 ? [...selectedCells] : [cellId];++ // Cannot delete running cells+ const notebook = store.get(notebookAtom);+ const hasRunningCell = cellIds.some((id) => {+ const { status } = notebook.cellRuntime[id];+ return status === "running" || status === "queued";+ });++ if (hasRunningCell) {+ return false;+ }++ // First keymap sets pending, second deletes+ if (pendingDeleteService.idle) {+ pendingDeleteService.submit(cellIds);+ return true;+ }++ // user repeated keymap+ deleteCells({ cellIds });+ pendingDeleteService.clear();+ return true;+ },+ } satisfies Partial<+ Record<HotkeyAction, HotkeyHandler["handle"] | HotkeyHandler>+ >;const selectedCells = getSelectedCells(store);+ // Keymaps when using vim.+ if (+ keymapPreset === "vim" &&+ handleVimKeybinding(evt.nativeEvent || evt, {+ j: keymaps.ArrowDown,+ k: keymaps.ArrowUp,+ i: keymaps.Enter,+ "shift+j": keymaps["Shift+ArrowDown"],+ "shift+k": keymaps["Shift+ArrowUp"],+ "g g": keymaps["Mod+ArrowUp"],+ "shift+g": keymaps["Mod+ArrowDown"],+ "d d": () => shortcuts["cell.delete"](),+ })+ ) {+ evt.preventDefault();+ return;+ }+// Handle the shortcutfor (const [shortcut, handler] of Object.entries(shortcuts)) {if (isShortcutPressed(shortcut as HotkeyAction, evt)) {diff --git a/frontend/src/core/cells/__tests__/pending-delete-service.test.tsx b/frontend/src/core/cells/__tests__/pending-delete-service.test.tsxnew file mode 100644index 0000000000..adae9ad85f--- /dev/null+++ b/frontend/src/core/cells/__tests__/pending-delete-service.test.tsx@@ -0,0 +1,202 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { act, renderHook, waitFor } from "@testing-library/react";+import { createStore, Provider } from "jotai";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { MockNotebook } from "@/__mocks__/notebook";+import { notebookAtom } from "@/core/cells/cells";+import { CellId } from "@/core/cells/ids";+import { createCellRuntimeState } from "@/core/cells/types";+import { variablesAtom } from "@/core/variables/state";+import type { VariableName } from "@/core/variables/types";+import type { Milliseconds } from "@/utils/time";+import {+ usePendingDelete,+ usePendingDeleteService,+} from "../pending-delete-service";++const mockDeleteCell = vi.fn();+const mockDeleteManyCells = vi.fn();+vi.mock("@/components/editor/cell/useDeleteCell", () => ({+ useDeleteCellCallback: () => mockDeleteCell,+ useDeleteManyCellsCallback: () => mockDeleteManyCells,+}));++function createTestWrapper() {+ const store = createStore();+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <Provider store={store}>{children}</Provider>+ );+ return { wrapper, store };+}++// Don't clear all mocks - just reset the specific one we care about+beforeEach(() => {+ vi.resetAllMocks();+});++describe("pending-delete-service", () => {+ it("auto-deletes simple cells (no dependencies, short execution time)", async () => {+ const { wrapper, store } = createTestWrapper();++ const cellId = CellId.create();+ const notebook = MockNotebook.notebookState({+ cellData: {+ [cellId]: { code: "print('hello')" },+ },+ });++ notebook.cellRuntime[cellId] = createCellRuntimeState({+ runElapsedTimeMs: 1 as Milliseconds,+ });++ store.set(notebookAtom, notebook);+ store.set(variablesAtom, {});++ const { result } = renderHook(+ () => {+ const service = usePendingDeleteService();+ const deleteState = usePendingDelete(cellId);+ return { service, deleteState };+ },+ { wrapper },+ );++ act(() => {+ result.current.service.submit([cellId]);+ });++ // should flush single cell+ await waitFor(() => {+ expect(mockDeleteCell).toHaveBeenCalledWith({ cellId: cellId });+ });+ });++ it("requires confirmation for expensive cells (long execution time)", () => {+ const { wrapper, store } = createTestWrapper();++ const cellId = CellId.create();+ const notebook = MockNotebook.notebookState({+ cellData: {+ [cellId]: { code: "expensive_computation()" },+ },+ });++ notebook.cellRuntime[cellId] = createCellRuntimeState({+ runElapsedTimeMs: 100_000 as Milliseconds,+ });++ store.set(notebookAtom, notebook);+ store.set(variablesAtom, {});++ const { result: serviceResult } = renderHook(+ () => usePendingDeleteService(),+ { wrapper },+ );++ act(() => {+ serviceResult.current.submit([cellId]);+ });++ const { result } = renderHook(() => usePendingDelete(cellId), {+ wrapper,+ });++ expect(mockDeleteManyCells).not.toHaveBeenCalled();+ expect(result.current.isPending).toBe(true);+ act(() => {+ if (result.current.isPending && "confirm" in result.current) {+ result.current.confirm();+ }+ });++ expect(mockDeleteManyCells).toHaveBeenCalledWith({+ cellIds: [cellId],+ });+ });++ it("requires confirmation for cells with dependencies", () => {+ const { wrapper, store } = createTestWrapper();++ const cell1Id = CellId.create();+ const cell2Id = CellId.create();++ const notebook = MockNotebook.notebookState({+ cellData: {+ [cell1Id]: { code: "x = 1" },+ [cell2Id]: { code: "y = x + 1" },+ },+ });++ // Both have short execution times+ notebook.cellRuntime[cell1Id] = createCellRuntimeState({+ runElapsedTimeMs: 100 as Milliseconds,+ });+ notebook.cellRuntime[cell2Id] = createCellRuntimeState({+ runElapsedTimeMs: 50 as Milliseconds,+ });++ store.set(notebookAtom, notebook);+ store.set(variablesAtom, {+ ["x" as VariableName]: {+ name: "x" as VariableName,+ declaredBy: [cell1Id],+ usedBy: [cell2Id],+ },+ });++ // cell1 with dependencies+ const { result: serviceResult } = renderHook(+ () => usePendingDeleteService(),+ { wrapper },+ );++ act(() => {+ serviceResult.current.submit([cell1Id]);+ });++ // ensure doesn't auto-delete+ renderHook(() => usePendingDelete(cell1Id), { wrapper });+ expect(mockDeleteManyCells).not.toHaveBeenCalled();+ });++ it("prevents individual confirmation when multiple cells are pending", () => {+ const { wrapper, store } = createTestWrapper();++ const cell1Id = CellId.create();+ const cell2Id = CellId.create();+ const notebook = MockNotebook.notebookState({+ cellData: {+ [cell1Id]: { code: "expensive1()" },+ [cell2Id]: { code: "expensive2()" },+ },+ });++ notebook.cellRuntime[cell1Id] = createCellRuntimeState({+ runElapsedTimeMs: 3000 as Milliseconds,+ });+ notebook.cellRuntime[cell2Id] = createCellRuntimeState({+ runElapsedTimeMs: 4000 as Milliseconds,+ });++ store.set(notebookAtom, notebook);+ store.set(variablesAtom, {});++ const { result: serviceResult } = renderHook(+ () => usePendingDeleteService(),+ { wrapper },+ );+ act(() => {+ serviceResult.current.submit([cell1Id, cell2Id]);+ });++ const { result } = renderHook(() => usePendingDelete(cell1Id), {+ wrapper,+ });+ expect(result.current.isPending).toBe(true);+ if (result.current.isPending) {+ expect(result.current.shouldConfirmDelete).toBe(false);+ expect("confirm" in result.current).toBe(false);+ }+ });+});diff --git a/frontend/src/core/cells/pending-delete-service.ts b/frontend/src/core/cells/pending-delete-service.tsnew file mode 100644index 0000000000..5439b904fc--- /dev/null+++ b/frontend/src/core/cells/pending-delete-service.ts@@ -0,0 +1,137 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { atom, useAtom, useAtomValue } from "jotai";+import { useCallback, useEffect } from "react";+import {+ useDeleteCellCallback,+ useDeleteManyCellsCallback,+} from "@/components/editor/cell/useDeleteCell";+import { notebookAtom } from "@/core/cells/cells";+import type { CellId } from "@/core/cells/ids";+import { variablesAtom } from "@/core/variables/state";+import type { VariableName } from "@/core/variables/types";++type PendingDeleteEntry =+ | {+ cellId: CellId;+ type: "simple";+ }+ | {+ cellId: CellId;+ type: "expensive";+ executionDurationMs?: number;+ defs: Map<VariableName, readonly CellId[]>;+ };++const pendingDeleteStateAtom = atom<Map<CellId, PendingDeleteEntry>>(new Map());++export function usePendingDeleteService() {+ const [state, setState] = useAtom(pendingDeleteStateAtom);+ const notebook = useAtomValue(notebookAtom);+ const variables = useAtomValue(variablesAtom);++ const submit = useCallback(+ (cellIds: CellId[]) => {+ const entries = new Map<CellId, PendingDeleteEntry>();++ for (const cellId of cellIds) {+ const runtimeInfo = notebook.cellRuntime[cellId];++ // Build defs map for this cell+ const defs = new Map<VariableName, readonly CellId[]>();+ for (const variable of Object.values(variables)) {+ if (+ variable.declaredBy.includes(cellId) &&+ variable.usedBy.length > 0+ ) {+ defs.set(variable.name, variable.usedBy);+ }+ }++ let executionDurationMs: number | undefined;+ if (+ runtimeInfo?.runElapsedTimeMs &&+ runtimeInfo.runElapsedTimeMs > 2000+ ) {+ executionDurationMs = runtimeInfo.runElapsedTimeMs;+ }++ if (defs.size === 0 && executionDurationMs === undefined) {+ entries.set(cellId, { cellId, type: "simple" });+ } else {+ entries.set(cellId, {+ cellId,+ type: "expensive",+ executionDurationMs,+ defs,+ });+ }+ }++ setState(entries);+ },+ [notebook, variables, setState],+ );++ const clear = useCallback(() => {+ setState(new Map());+ }, [setState]);++ return {+ idle: state.size === 0,+ shouldConfirmDelete: state.size > 1,+ submit,+ clear,+ };+}++export function usePendingDelete(cellId: CellId) {+ const [state, setState] = useAtom(pendingDeleteStateAtom);+ const deleteCell = useDeleteCellCallback();+ const deleteManyCells = useDeleteManyCellsCallback();++ const entry = state.get(cellId);++ // Auto-delete if all are "simple" cells+ useEffect(() => {+ if (state.size === 0) {+ return;+ }+ const entries = [...state.values()];+ if (entries.every((entry) => entry.type === "simple")) {+ if (state.size === 1) {+ deleteCell({ cellId: entries[0].cellId });+ } else {+ deleteManyCells({ cellIds: entries.map((e) => e.cellId) });+ }+ setState(new Map());+ }+ }, [state, deleteCell, deleteManyCells, setState]);++ if (!entry) {+ return { isPending: false as const };+ }++ const canConfirmDelete = state.size === 1;++ if (!canConfirmDelete) {+ return {+ isPending: true as const,+ shouldConfirmDelete: false as const,+ ...entry,+ };+ }++ return {+ isPending: true as const,+ ...entry,+ shouldConfirmDelete: true as const,+ confirm: () => {+ deleteManyCells({+ cellIds: [...state.values()].map((e) => e.cellId),+ });+ setState(new Map());+ },+ cancel: () => setState(new Map()),+ };+}diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex 3358a0652f..34986c4673 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -5,6 +5,7 @@ import { type Extension, Prec } from "@codemirror/state";import { EditorView, type KeyBinding, keymap } from "@codemirror/view";import { createTracebackInfoAtom, SCRATCH_CELL_ID } from "@/core/cells/cells";import { type CellId, HTMLCellId } from "@/core/cells/ids";+import type { KeymapConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { store } from "@/core/state/jotai";import { createObservable } from "@/core/state/observable";@@ -23,7 +24,15 @@ import { errorLineHighlighter } from "./traceback-decorations";/*** Extensions for cell actions*/-function cellKeymaps(cellId: CellId, hotkeys: HotkeyProvider): Extension[] {+function cellKeymaps({+ cellId,+ hotkeys,+ keymapConfig,+}: {+ cellId: CellId;+ hotkeys: HotkeyProvider;+ keymapConfig: KeymapConfig;+}): Extension[] {const keybindings: KeyBinding[] = [];keybindings.push(@@ -98,8 +107,10 @@ function cellKeymaps(cellId: CellId, hotkeys: HotkeyProvider): Extension[] {preventDefault: true,stopPropagation: true,run: (cm) => {- // Cannot delete non-empty cells for safety- if (cm.state.doc.length === 0) {+ // Can only delete non-empty cells when `destructive_delete` is enabled+ const canDelete =+ keymapConfig.destructive_delete || cm.state.doc.length === 0;+ if (canDelete) {const actions = cm.state.facet(cellActionsState);actions.deleteCell();}@@ -338,15 +349,21 @@ export function markdownAutoRunExtension({});}-export function cellBundle(- cellId: CellId,- hotkeys: HotkeyProvider,- cellActions: CodemirrorCellActions,-): Extension[] {+export function cellBundle({+ cellId,+ hotkeys,+ cellActions,+ keymapConfig,+}: {+ cellId: CellId;+ hotkeys: HotkeyProvider;+ cellActions: CodemirrorCellActions;+ keymapConfig: KeymapConfig;+}): Extension[] {return [cellActionsState.of(cellActions),cellIdState.of(cellId),- cellKeymaps(cellId, hotkeys),+ cellKeymaps({ cellId, hotkeys, keymapConfig }),cellCodeEditing(hotkeys),errorLineHighlighter(createObservable(createTracebackInfoAtom(cellId), store),diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.tsindex 1367b6e305..1b2e52c5fd 100644--- a/frontend/src/core/codemirror/cm.ts+++ b/frontend/src/core/codemirror/cm.ts@@ -121,7 +121,7 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {lspConfig,diagnosticsConfig,}),- cellBundle(cellId, hotkeys, cellActions),+ cellBundle({ cellId, hotkeys, cellActions, keymapConfig }),// Comes last so that it can be overriddenbasicBundle(opts),// Underline cmd+clickable placeholderdiff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.tsindex 228af4b8cd..718e45f189 100644--- a/frontend/src/core/config/__tests__/config-schema.test.ts+++ b/frontend/src/core/config/__tests__/config-schema.test.ts@@ -66,6 +66,7 @@ test("default UserConfig - empty", () => {"line_length": 79,},"keymap": {+ "destructive_delete": true,"overrides": {},"preset": "default",},@@ -125,6 +126,7 @@ test("default UserConfig - one level", () => {"line_length": 79,},"keymap": {+ "destructive_delete": true,"overrides": {},"preset": "default",},diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex a0f33e5d3a..4f83030d37 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -87,6 +87,7 @@ export const UserConfigSchema = z.object({preset: z.enum(["default", "vim"]).default("default"),overrides: z.record(z.string()).default({}),+ destructive_delete: z.boolean().default(true),}).passthrough().default({}),diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex b711d8e3cd..d25010d7fc 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -84,11 +84,13 @@ class KeymapConfig(TypedDict):- `preset`: one of `"default"` or `"vim"`- `overrides`: a dict of keymap actions to their keymap override- `vimrc`: path to a vimrc file to load keymaps from+ - `destructive_delete`: if `True`, allows deleting cells with content."""preset: Literal["default", "vim"]overrides: NotRequired[dict[str, str]]vimrc: NotRequired[Optional[str]]+ destructive_delete: NotRequired[bool]OnCellChangeType = Literal["lazy", "autorun"]diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex f646a98106..ecc0c0da17 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -1619,6 +1619,8 @@ components:type: objectkeymap:properties:+ destructive_delete:+ type: booleanoverrides:additionalProperties:type: string@@ -2738,7 +2740,7 @@ components:type: objectinfo:title: marimo API- version: 0.14.10+ version: 0.14.11openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex fa89af2c25..44eb60f9e7 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -3222,6 +3222,7 @@ export interface components {line_length: number;};keymap: {+ destructive_delete?: boolean;overrides?: {[key: string]: string;};